@needle-tools/engine 6.0.0-alpha.4 → 6.0.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +11 -1
  3. package/dist/{gltf-progressive-CcSfG2Ja.js → gltf-progressive-B7lOWdLe.js} +117 -115
  4. package/dist/gltf-progressive-BpT9M5Mt.umd.cjs +10 -0
  5. package/dist/gltf-progressive-D0rzvhNG.min.js +10 -0
  6. package/dist/{materialx-B3qY8vPU.js → materialx-Bd9BE6LR.js} +1 -1
  7. package/dist/{materialx-BwYvA-4x.umd.cjs → materialx-CzRx9AGf.umd.cjs} +2 -2
  8. package/dist/{materialx-CTPhpPxI.min.js → materialx-x1m4IJd1.min.js} +1 -1
  9. package/dist/{needle-engine.bundle-Bmcb5t3w.min.js → needle-engine.bundle-D6mZl1dR.min.js} +29 -29
  10. package/dist/{needle-engine.bundle-BuUj9B4K.umd.cjs → needle-engine.bundle-DOHf03pR.umd.cjs} +14 -14
  11. package/dist/{needle-engine.bundle-0tD9EcNs.js → needle-engine.bundle-Hu7ZAxEI.js} +75 -69
  12. package/dist/needle-engine.d.ts +5 -5
  13. package/dist/needle-engine.js +192 -192
  14. package/dist/needle-engine.min.js +1 -1
  15. package/dist/needle-engine.umd.cjs +1 -1
  16. package/dist/{vendor-BQUQwut5.js → vendor-BatPc34p.js} +50 -41
  17. package/dist/{vendor-BJviq-Oq.umd.cjs → vendor-CDN1hirK.umd.cjs} +1 -1
  18. package/dist/{vendor-CdNldo8c.min.js → vendor-T07c_9f_.min.js} +1 -1
  19. package/lib/engine/api.d.ts +1 -1
  20. package/lib/engine/api.js +1 -1
  21. package/lib/engine/api.js.map +1 -1
  22. package/lib/engine/engine_init.js +2 -2
  23. package/lib/engine/engine_init.js.map +1 -1
  24. package/lib/engine/engine_license.d.ts +7 -7
  25. package/lib/engine/engine_license.js +98 -78
  26. package/lib/engine/engine_license.js.map +1 -1
  27. package/lib/engine/engine_networking_blob.js +3 -3
  28. package/lib/engine/engine_networking_blob.js.map +1 -1
  29. package/lib/engine/engine_utils_qrcode.js +2 -2
  30. package/lib/engine/engine_utils_qrcode.js.map +1 -1
  31. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js +2 -2
  32. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js.map +1 -1
  33. package/lib/engine/webcomponents/needle menu/needle-menu.js +5 -5
  34. package/lib/engine/webcomponents/needle menu/needle-menu.js.map +1 -1
  35. package/lib/engine/webcomponents/needle-engine.js +2 -2
  36. package/lib/engine/webcomponents/needle-engine.js.map +1 -1
  37. package/lib/engine/webcomponents/needle-engine.loading.js +2 -2
  38. package/lib/engine/webcomponents/needle-engine.loading.js.map +1 -1
  39. package/lib/engine/xr/TempXRContext.js +2 -2
  40. package/lib/engine/xr/TempXRContext.js.map +1 -1
  41. package/lib/engine-components/Renderer.d.ts +1 -1
  42. package/lib/engine-components/Renderer.js +2 -11
  43. package/lib/engine-components/Renderer.js.map +1 -1
  44. package/lib/engine-components/export/usdz/USDZExporter.js +4 -4
  45. package/lib/engine-components/export/usdz/USDZExporter.js.map +1 -1
  46. package/package.json +6 -3
  47. package/plugins/common/license.js +4 -4
  48. package/plugins/license/README.md +38 -0
  49. package/plugins/license/cli.js +46 -0
  50. package/plugins/license/index.js +24 -0
  51. package/plugins/vite/license.js +4 -4
  52. package/src/engine/api.ts +1 -1
  53. package/src/engine/engine_init.ts +2 -2
  54. package/src/engine/engine_license.ts +93 -76
  55. package/src/engine/engine_networking_blob.ts +3 -3
  56. package/src/engine/engine_utils_qrcode.ts +2 -2
  57. package/src/engine/webcomponents/needle menu/needle-menu-spatial.ts +2 -2
  58. package/src/engine/webcomponents/needle menu/needle-menu.ts +5 -5
  59. package/src/engine/webcomponents/needle-engine.loading.ts +2 -2
  60. package/src/engine/webcomponents/needle-engine.ts +2 -2
  61. package/src/engine/xr/TempXRContext.ts +2 -2
  62. package/src/engine-components/Renderer.ts +4 -13
  63. package/src/engine-components/export/usdz/USDZExporter.ts +4 -4
  64. package/dist/gltf-progressive-BYG9UH7O.min.js +0 -10
  65. package/dist/gltf-progressive-sK--FWg7.umd.cjs +0 -10
@@ -1,4 +1,4 @@
1
- var AO=Object.defineProperty,IO=(o,e,t)=>e in o?AO(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,LO=(o,e,t)=>IO(o,typeof e!="symbol"?e+"":e,t);import{Vector2 as ee,Vector3 as v,Vector4 as ve,Quaternion as B,Box3 as ri,ShadowMaterial as kv,Euler as je,PlaneGeometry as In,WebGLRenderer as Dr,PerspectiveCamera as me,OrthographicCamera as mu,Scene as Fi,Mesh as V,Texture as Pe,Uniform as an,Color as oe,ShaderMaterial as oo,MeshStandardMaterial as Mt,Box3Helper as DO,GridHelper as Ov,Object3D as R,Material as ke,Matrix3 as sf,Matrix4 as J,Layers as Fs,PropertyBinding as nl,AnimationClip as Yt,KeyframeTrack as jO,FileLoader as Mv,BufferGeometry as Ln,TextureLoader as jr,MeshBasicMaterial as Ie,DoubleSide as Bi,Group as Dn,CylinderGeometry as Rv,SphereGeometry as rf,BoxGeometry as ol,SpriteMaterial as FO,Sprite as BO,Shape as UO,ExtrudeGeometry as zO,Ray as so,CubeUVReflectionMapping as ln,LinearSRGBColorSpace as Xo,ShaderChunk as ai,Sphere as Xc,DataTexture as af,RGBAFormat as gu,EquirectangularReflectionMapping as Qo,SRGBColorSpace as Yo,PMREMGenerator as NO,NeutralToneMapping as sl,AgXToneMapping as fu,ACESFilmicToneMapping as yu,NoToneMapping as bu,AxesHelper as Ui,MathUtils as Ko,Fog as Tv,DirectionalLight as lf,PointLight as cf,PCFShadowMap as $O,BasicNodeLibrary as WO,WebGLRenderTarget as ro,DepthTexture as Ev,NearestFilter as _u,EdgesGeometry as VO,LineSegments as hf,LineBasicMaterial as vu,Line as Qc,BufferAttribute as lt,Raycaster as df,ArrayCamera as GO,Plane as rl,SkinnedMesh as Bs,InterleavedBufferAttribute as Av,Skeleton as HO,Bone as qO,Audio as Iv,AudioListener as Lv,WebGLCubeRenderTarget as XO,CubeCamera as QO,LoopRepeat as YO,LoopOnce as uf,AnimationMixer as pf,InterpolateLinear as KO,InterpolateDiscrete as ZO,InterpolateSmooth as JO,QuaternionKeyframeTrack as Yc,BooleanKeyframeTrack as Dv,VectorKeyframeTrack as Kc,ColorKeyframeTrack as jv,NumberKeyframeTrack as mf,AudioContext as Fv,CompressedTexture as eM,FrontSide as Us,Camera as tM,Frustum as Bv,PositionalAudio as iM,AudioLoader as nM,BackSide as wu,EquirectangularRefractionMapping as gf,CubeTexture as ff,CompressedCubeTexture as Uv,MeshDepthMaterial as oM,CustomBlending as sM,MaxEquation as rM,AlwaysStencilFunc as aM,GreaterEqualStencilFunc as lM,NotEqualStencilFunc as cM,GreaterStencilFunc as hM,LessEqualStencilFunc as dM,EqualStencilFunc as uM,LessStencilFunc as pM,NeverStencilFunc as zv,InvertStencilOp as mM,DecrementWrapStencilOp as gM,IncrementWrapStencilOp as fM,DecrementStencilOp as yM,IncrementStencilOp as bM,ReplaceStencilOp as _M,ZeroStencilOp as vM,KeepStencilOp as wM,AmbientLight as xM,HemisphereLight as SM,Loader as CM,GLSL3 as PM,AlwaysDepth as kM,GreaterEqualDepth as OM,GreaterDepth as MM,LessEqualDepth as RM,LessDepth as TM,NotEqualDepth as EM,EqualDepth as AM,RawShaderMaterial as Nv,BatchedMesh as $v,LinearFilter as xu,UnsignedByteType as IM,MeshPhysicalMaterial as Wv,RingGeometry as LM,Line3 as DM,AdditiveBlending as Vv,LoadingManager as Gv,BoxHelper as jM,SpotLight as FM,DirectionalLightHelper as BM,CameraHelper as UM,LOD as zM,Triangle as NM,NormalBlending as $M,ReinhardToneMapping as yf,LinearToneMapping as bf,EventDispatcher as _f,VideoTexture as WM,CatmullRomCurve3 as VM,MirroredRepeatWrapping as Hv,ShaderLib as Su,UniformsUtils as qv,MeshNormalMaterial as GM,HalfFloatType as vf,Source as HM}from"./three-core.min.js";import{createLoaders as wf,LODsManager as Fr,NEEDLE_progressive as We,getRaycastMesh as Xv,calculateMeshLODLevel as qM,getLODColor as XM,addDracoAndKTX2Loaders as QM,configureLoader as YM,setKTX2TranscoderLocation as KM,setDracoDecoderLocation as ZM}from"./gltf-progressive-BYG9UH7O.min.js";import{GroundedSkybox as al,Font as JM,TextGeometry as eR,FontLoader as tR,GLTFLoader as Zo,EXRLoader as xf,HDRLoader as Qv,Stats as iR,nodeFrame as zi,TransformControlsGizmo as Yv,OrbitControls as nR,PositionalAudioHelper as oR,HorizontalBlurShader as sR,VerticalBlurShader as rR,GLTFExporter as Kv,strToU8 as Zv,zipSync as aR,XRControllerModelFactory as lR,Line2 as cR,LineGeometry as hR,LineMaterial as dR,OBJLoader as Sf,FBXLoader as Jv,TransformControls as uR,InteractiveGroup as pR,HTMLMesh as mR,VertexNormalsHelper as gR,mergeVertices as fR}from"./three-examples.min.js";import{v5 as Cf,ByteBuffer as yR,fetchProfile as bR,MotionController as _R,SIZE_PREFIX_LENGTH as ew,Builder as Pf,attachNeedleIdsToLoadedGltf as vR,createNoise4D as wR,Matrix4 as kf,BatchedParticleRenderer as xR,ParticleSystem as SR,RenderMode as Jo,ConstantColor as CR,Vector4 as PR,ConstantValue as kR,TrailParticle as tw,deriveInstanceId as Of,PROJECT_DOCUMENT_KEY as OR,isProjectDocument as MR,applyDef as RR,applyOver as TR,evaluateProjectDocument as ER,resolveMaterialEntity as AR,createOverApplyState as IR,reportProjectIssues as LR,resolveDocumentRemoteSrc as DR,splitPath as jR,WorkerBase as FR,MeshBVH as BR}from"./vendor-CdNldo8c.min.js";import{__webpack_exports__default as Le,__webpack_exports__Text as iw,__webpack_exports__update as UR,__webpack_exports__Block as nw,SimpleStateBehavior as zR,__webpack_exports__Inline as Mf,__webpack_exports__FontLibrary as ow,ThreeMeshUI as sw}from"./three-mesh-ui-B39TwGSi.min.js";const rw=typeof window<"u"?window.location.search.includes("debugcontext"):!1;var de=(o=>(o.ContextRegistered="ContextRegistered",o.ContextCreationStart="ContextCreationStart",o.ContextCreated="ContextCreated",o.ContextFirstFrameRendered="ContextFirstFrameRendered",o.ContextDestroying="ContextDestroying",o.ContextDestroyed="ContextDestroyed",o.MissingCamera="MissingCamera",o.ContextClearing="ContextClearing",o.ContextCleared="ContextCleared",o))(de||{});class ce{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(rw&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(rw&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].indexOf(t)!==-1?()=>this.unregisterCallback(e,t):(this._callbacks[e].push(t),()=>this.unregisterCallback(e,t))}static unregisterCallback(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i!==-1&&this._callbacks[e].splice(i,1)}static dispatchCallback(e,t,i){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(i)for(const r in i)n[r]=i[r];const s=new Array;return this._callbacks[e].forEach(r=>{const a=r(n);a instanceof Promise&&s.push(a)}),Promise.all(s)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}const Rf=new Map;function Ni(o=globalThis.location?.hostname){if(Rf.has(o))return Rf.get(o);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(o);return Rf.set(o,e),e===!0}function aw(){return window.location.hostname.includes("glitch.me")}const lw=()=>o=>o;function NR(o){return lw()(o)}function $R(){return!!x("debug")}class $i{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let Br=!1;const Tf=new Array;typeof window<"u"&&setTimeout(()=>{if(Br){const o={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const i=t.toString().replace(/=$|=(?=&)/g,"");for(const s of Tf){const r=new URL(e);r.searchParams.append(s,""),o[s]=r.toString().replace(/=$|=(?=&)/g,"")}console.log(`\u{1F335} ?help: Debug Options for Needle Engine.
1
+ var AO=Object.defineProperty,IO=(o,e,t)=>e in o?AO(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,LO=(o,e,t)=>IO(o,typeof e!="symbol"?e+"":e,t);import{Vector2 as ee,Vector3 as v,Vector4 as ve,Quaternion as B,Box3 as ri,ShadowMaterial as kv,Euler as je,PlaneGeometry as In,WebGLRenderer as Dr,PerspectiveCamera as me,OrthographicCamera as mu,Scene as Fi,Mesh as V,Texture as ke,Uniform as an,Color as oe,ShaderMaterial as oo,MeshStandardMaterial as Mt,Box3Helper as DO,GridHelper as Ov,Object3D as R,Material as Oe,Matrix3 as sf,Matrix4 as J,Layers as Fs,PropertyBinding as nl,AnimationClip as Yt,KeyframeTrack as jO,FileLoader as Mv,BufferGeometry as Ln,TextureLoader as jr,MeshBasicMaterial as Ie,DoubleSide as Bi,Group as Dn,CylinderGeometry as Rv,SphereGeometry as rf,BoxGeometry as ol,SpriteMaterial as FO,Sprite as BO,Shape as UO,ExtrudeGeometry as zO,Ray as so,CubeUVReflectionMapping as ln,LinearSRGBColorSpace as Xo,ShaderChunk as ai,Sphere as Xc,DataTexture as af,RGBAFormat as gu,EquirectangularReflectionMapping as Qo,SRGBColorSpace as Yo,PMREMGenerator as NO,NeutralToneMapping as sl,AgXToneMapping as fu,ACESFilmicToneMapping as yu,NoToneMapping as bu,AxesHelper as Ui,MathUtils as Ko,Fog as Tv,DirectionalLight as lf,PointLight as cf,PCFShadowMap as $O,BasicNodeLibrary as WO,WebGLRenderTarget as ro,DepthTexture as Ev,NearestFilter as _u,EdgesGeometry as VO,LineSegments as hf,LineBasicMaterial as vu,Line as Qc,BufferAttribute as lt,Raycaster as df,ArrayCamera as GO,Plane as rl,SkinnedMesh as Bs,InterleavedBufferAttribute as Av,Skeleton as HO,Bone as qO,Audio as Iv,AudioListener as Lv,WebGLCubeRenderTarget as XO,CubeCamera as QO,LoopRepeat as YO,LoopOnce as uf,AnimationMixer as pf,InterpolateLinear as KO,InterpolateDiscrete as ZO,InterpolateSmooth as JO,QuaternionKeyframeTrack as Yc,BooleanKeyframeTrack as Dv,VectorKeyframeTrack as Kc,ColorKeyframeTrack as jv,NumberKeyframeTrack as mf,AudioContext as Fv,CompressedTexture as eM,FrontSide as Us,Camera as tM,Frustum as Bv,PositionalAudio as iM,AudioLoader as nM,BackSide as wu,EquirectangularRefractionMapping as gf,CubeTexture as ff,CompressedCubeTexture as Uv,MeshDepthMaterial as oM,CustomBlending as sM,MaxEquation as rM,AlwaysStencilFunc as aM,GreaterEqualStencilFunc as lM,NotEqualStencilFunc as cM,GreaterStencilFunc as hM,LessEqualStencilFunc as dM,EqualStencilFunc as uM,LessStencilFunc as pM,NeverStencilFunc as zv,InvertStencilOp as mM,DecrementWrapStencilOp as gM,IncrementWrapStencilOp as fM,DecrementStencilOp as yM,IncrementStencilOp as bM,ReplaceStencilOp as _M,ZeroStencilOp as vM,KeepStencilOp as wM,AmbientLight as xM,HemisphereLight as SM,Loader as CM,GLSL3 as PM,AlwaysDepth as kM,GreaterEqualDepth as OM,GreaterDepth as MM,LessEqualDepth as RM,LessDepth as TM,NotEqualDepth as EM,EqualDepth as AM,RawShaderMaterial as Nv,BatchedMesh as $v,LinearFilter as xu,UnsignedByteType as IM,MeshPhysicalMaterial as Wv,RingGeometry as LM,Line3 as DM,AdditiveBlending as Vv,LoadingManager as Gv,BoxHelper as jM,SpotLight as FM,DirectionalLightHelper as BM,CameraHelper as UM,LOD as zM,Triangle as NM,NormalBlending as $M,ReinhardToneMapping as yf,LinearToneMapping as bf,EventDispatcher as _f,VideoTexture as WM,CatmullRomCurve3 as VM,MirroredRepeatWrapping as Hv,ShaderLib as Su,UniformsUtils as qv,MeshNormalMaterial as GM,HalfFloatType as vf,Source as HM}from"./three-core.min.js";import{createLoaders as wf,LODsManager as Fr,NEEDLE_progressive as We,getRaycastMesh as Xv,calculateMeshLODLevel as qM,getLODColor as XM,addDracoAndKTX2Loaders as QM,configureLoader as YM,setKTX2TranscoderLocation as KM,setDracoDecoderLocation as ZM}from"./gltf-progressive-D0rzvhNG.min.js";import{GroundedSkybox as al,Font as JM,TextGeometry as eR,FontLoader as tR,GLTFLoader as Zo,EXRLoader as xf,HDRLoader as Qv,Stats as iR,nodeFrame as zi,TransformControlsGizmo as Yv,OrbitControls as nR,PositionalAudioHelper as oR,HorizontalBlurShader as sR,VerticalBlurShader as rR,GLTFExporter as Kv,strToU8 as Zv,zipSync as aR,XRControllerModelFactory as lR,Line2 as cR,LineGeometry as hR,LineMaterial as dR,OBJLoader as Sf,FBXLoader as Jv,TransformControls as uR,InteractiveGroup as pR,HTMLMesh as mR,VertexNormalsHelper as gR,mergeVertices as fR}from"./three-examples.min.js";import{v5 as Cf,ByteBuffer as yR,fetchProfile as bR,MotionController as _R,SIZE_PREFIX_LENGTH as ew,Builder as Pf,attachNeedleIdsToLoadedGltf as vR,createNoise4D as wR,Matrix4 as kf,BatchedParticleRenderer as xR,ParticleSystem as SR,RenderMode as Jo,ConstantColor as CR,Vector4 as PR,ConstantValue as kR,TrailParticle as tw,deriveInstanceId as Of,PROJECT_DOCUMENT_KEY as OR,isProjectDocument as MR,applyDef as RR,applyOver as TR,evaluateProjectDocument as ER,resolveMaterialEntity as AR,createOverApplyState as IR,reportProjectIssues as LR,resolveDocumentRemoteSrc as DR,splitPath as jR,WorkerBase as FR,MeshBVH as BR}from"./vendor-T07c_9f_.min.js";import{__webpack_exports__default as Le,__webpack_exports__Text as iw,__webpack_exports__update as UR,__webpack_exports__Block as nw,SimpleStateBehavior as zR,__webpack_exports__Inline as Mf,__webpack_exports__FontLibrary as ow,ThreeMeshUI as sw}from"./three-mesh-ui-B39TwGSi.min.js";const rw=typeof window<"u"?window.location.search.includes("debugcontext"):!1;var de=(o=>(o.ContextRegistered="ContextRegistered",o.ContextCreationStart="ContextCreationStart",o.ContextCreated="ContextCreated",o.ContextFirstFrameRendered="ContextFirstFrameRendered",o.ContextDestroying="ContextDestroying",o.ContextDestroyed="ContextDestroyed",o.MissingCamera="MissingCamera",o.ContextClearing="ContextClearing",o.ContextCleared="ContextCleared",o))(de||{});class ce{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(rw&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(rw&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].indexOf(t)!==-1?()=>this.unregisterCallback(e,t):(this._callbacks[e].push(t),()=>this.unregisterCallback(e,t))}static unregisterCallback(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i!==-1&&this._callbacks[e].splice(i,1)}static dispatchCallback(e,t,i){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(i)for(const r in i)n[r]=i[r];const s=new Array;return this._callbacks[e].forEach(r=>{const a=r(n);a instanceof Promise&&s.push(a)}),Promise.all(s)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}const Rf=new Map;function Ni(o=globalThis.location?.hostname){if(Rf.has(o))return Rf.get(o);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(o);return Rf.set(o,e),e===!0}function aw(){return window.location.hostname.includes("glitch.me")}const lw=()=>o=>o;function NR(o){return lw()(o)}function $R(){return!!x("debug")}class $i{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let Br=!1;const Tf=new Array;typeof window<"u"&&setTimeout(()=>{if(Br){const o={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const i=t.toString().replace(/=$|=(?=&)/g,"");for(const s of Tf){const r=new URL(e);r.searchParams.append(s,""),o[s]=r.toString().replace(/=$|=(?=&)/g,"")}console.log(`\u{1F335} ?help: Debug Options for Needle Engine.
2
2
  Append any of these parameters to the URL to enable specific debug options.
3
3
  Example: ${i} will show an onscreen console window.`);const n=Br===!0?"":` (containing "${Br}")`;console.group("Available URL parameters:"+n);for(const s of Object.keys(o).sort())typeof Br=="string"&&!s.toLowerCase().includes(Br.toLowerCase())||(console.groupCollapsed(s),console.log("Reload with this flag enabled:"),console.log(o[s]),console.groupEnd());console.groupEnd()}},100);function Zc(){return new URLSearchParams(globalThis.location?.search)}function x(o){Br&&!Tf.includes(o)&&Tf.push(o);const e=Zc();if(e.has(o)){const t=e.get(o);if(t){const i=Number(t);return isNaN(i)?t:i}else return!0}return!1}Br=x("help");function WR(o,e){const t=Zc();t.has(o)?t.set(o,e):t.append(o,e),document.location.search=t.toString()}function Jc(o,e,t=!0){const i=Zc();i.has(o)?e===null?i.delete(o):i.set(o,e):e!==null&&i.append(o,e),t?cw(o,i):Af(o,i)}function Ef(o,e,t){o.has(e)?o.set(e,t.toString()):o.append(e,t.toString())}function cw(o,e,t){window.history.pushState(t,o,"?"+e.toString()+window.location.hash)}function Af(o,e,t){window.history.replaceState(t,o,"?"+e.toString()+window.location.hash)}function VR(o){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,n=0;n<o;n++)e+=t.charAt(Math.floor(Math.random()*i));return e}function GR(o,e){return Math.floor(Math.random()*(e-o+1))+o}const hw=["smol","tiny","giant","interesting","smart","bright","dull","extreme","beautiful","pretty","dark","epic","salty","silly","funny","lame","lazy","loud","lucky","mad","mean","mighty","mysterious","nasty","odd","old","powerful","quiet","rapid","scary","shiny","shy","silly","smooth","sour","spicy","stupid","sweet","tasty","terrible","ugly","unusual","vast","wet","wild","witty","wrong","zany","zealous","zippy","zombie","zorro"],dw=["cat","dog","mouse","pig","cow","horse","sheep","chicken","duck","goat","panda","tiger","lion","elephant","monkey","bird","fish","snake","frog","turtle","hamster","penguin","kangaroo","whale","dolphin","crocodile","snail","ant","bee","beetle","butterfly","dragon","eagle","fish","giraffe","lizard","panda","penguin","rabbit","snake","spider","tiger","zebra"];function uw(){const o=hw[Math.floor(Math.random()*hw.length)],e=dw[Math.floor(Math.random()*dw.length)];return o+"_"+e}function pw(o){return o=o.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),o.trim()}function eh(o,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===o||e.guid==o)return e;if(i&&e.userData?.components){for(const n of e.userData.components)if(n.guid===o)return n}if(t){if(e.scenes)for(const n in e.scenes){const s=e.scenes[n],r=eh(o,s,t,i);if(r)return r}if(e.children)for(const n in e.children){const s=e.children[n],r=eh(o,s,t,i);if(r)return r}}}function HR(o){return!!(typeof EventTarget<"u"&&o instanceof EventTarget||o instanceof Date||o instanceof RegExp||o instanceof Map||o instanceof Set||o instanceof WeakMap||o instanceof WeakSet||o instanceof Promise||typeof ArrayBuffer<"u"&&o instanceof ArrayBuffer||ArrayBuffer.isView(o))}function th(o,e,t){if(o!=null&&typeof o=="object"){if(t||(t=new WeakSet),t.has(o)||(t.add(o),HR(o)))return o;let i;if(Array.isArray(o))i=[];else{i=Object.create(Object.getPrototypeOf(o));const n=Object.getOwnPropertyDescriptors(o);for(const s in n){const r=n[s];if(r.set||r.writable!==!1)try{i[s]=o[s]}catch{}}}for(const n of Object.keys(o)){const s=o[n];e&&!e(o,n,s)?i[n]=s:s?.clone!==void 0&&typeof s.clone=="function"?i[n]=s.clone():i[n]=th(s,e,t)}return i}return o}function es(o){return new Promise((e,t)=>{setTimeout(e,o)})}function Cu(o,e){if(o<=0)return Promise.resolve();if(e||(e=ce.Current),!e)return Promise.reject("No context");const t=e.time.frameCount+o;return new Promise((i,n)=>{if(!e)return n("No context");const s=()=>{e.time.frameCount>=t&&(e.pre_update_callbacks.splice(e.pre_update_callbacks.indexOf(s),1),i())};e.pre_update_callbacks.push(s)})}const Pu=x("debugresolveurl"),mw="rel:";function qR(o,e){return ao(o,e)}function ao(o,e){if(e===void 0)return Pu&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return Pu&&console.warn("getPath: uri is absolute, returning uri",e),e;if(o===void 0)return Pu&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(mw)&&(e=e.substring(4));const t=o.lastIndexOf("/");if(t>=0){const i=o.substring(0,t+1);for(;i.endsWith("/")&&e.startsWith("/");)e=e.substring(1);const n=i+e;return Pu&&console.log("source:",o,`changed uri
4
4
  from`,e,`
@@ -78,7 +78,7 @@ void main(){
78
78
  // float linearDepth = (depth - 0.99) * 100.0; // Enhance near 1.0 values
79
79
  // gl_FragColor = vec4(linearDepth, linearDepth, linearDepth, 1.0);
80
80
  }
81
- }`})}reset(){this.uniforms.map.value=null,this.uniforms.flipY.value=!0,this.uniforms.writeDepth.value=!1,this.uniforms.depthTexture.value=null,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}}class Er{static _planeGeometry;static _renderer;static _perspectiveCam;static _orthographicCam;static _scene;static _blitMaterial;static _mesh;static get planeGeometry(){return this._planeGeometry??=new In(2,2,1,1)}static get renderer(){return this._renderer??=new Dr({antialias:!1,alpha:!0})}static get perspectiveCam(){return this._perspectiveCam??=new me}static get orthographicCam(){return this._orthographicCam??=new mu}static get scene(){return this._scene??=new Fi}static get blitMaterial(){return this._blitMaterial??=new Qg}static get mesh(){return this._mesh??=new V(Er.planeGeometry,Er.blitMaterial)}static copyTexture(e,t){t||(t=this.blitMaterial),this.blitMaterial.reset();const i=t||this.blitMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;const n=i.vertexShader;i.vertexShader=Qg.vertex;const s=this.mesh;s.material=i,s.frustumCulled=!1,this.scene.children.length=0,this.scene.add(s);const{width:r,height:a}=kT(e);this.renderer.setSize(r,a),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const l=new Pe(this.renderer.domElement);return l.name="Copy",l.needsUpdate=!0,i.vertexShader=n,l}static blit(e,t,i){const{renderer:n=this.renderer,blitMaterial:s=this.blitMaterial,flipY:r=!1,depthTexture:a=null,depthTest:l=!0,depthWrite:c=!0}=i||{};this.blitMaterial.reset(),s.uniforms.map&&(s.uniforms.map.value=e),s.uniforms.flipY&&(s.uniforms.flipY.value=r),a?(s.uniforms.writeDepth=new an(!0),s.uniforms.depthTexture.value=a):(s.uniforms.writeDepth=new an(!1),s.uniforms.depthTexture.value=null),s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const h=this.mesh;h.material=s,h.frustumCulled=!1,this.scene.children.length=0,this.scene.add(h);const d=n.getRenderTarget(),u=n.getContext();l?u.enable(u.DEPTH_TEST):u.disable(u.DEPTH_TEST),n.state.buffers.depth.setMask(c),n.setClearColor(new oe(0,0,0),0),n.setRenderTarget(t),n.clear(),n.render(this.scene,this.perspectiveCam),n.setRenderTarget(d),u.enable(u.DEPTH_TEST),n.state.buffers.depth.setMask(!0)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Uw(e));const i=e.image;if(zT(i)&&ih(i)){const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const s=n.getContext("2d");return s?(s.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}}function Uw(o){return Er.copyTexture(o)}function UT(o,e=!1){return Er.textureToCanvas(o,e)}function zT(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}function zw(o){const e=o.type;return e==="Mesh"||e==="SkinnedMesh"}function Kf(o,e){e?o["needle:rendercustomshadow"]=!0:o["needle:rendercustomshadow"]=!1}function Nw(o){return!!(o&&(o["needle:rendercustomshadow"]===!0||o["needle:rendercustomshadow"]==null))}function Si(o,e=void 0,t=void 0,i=void 0,n){const s=i||new ri;s.makeEmpty();const r=[];function a(c){let h=!0;if(c.visible&&Ow(c)!==!1&&!(c.type==="TransformControlsGizmo"||c.type==="TransformControlsPlane")){if(e){if(Array.isArray(e)){if(e.includes(c))return}else if(typeof e=="function"&&e(c)===!0)return}if(c instanceof DO&&(h=!1),c instanceof Ov&&(h=!1),c instanceof al&&(h=!1),c.isGizmo===!0&&(h=!1),c.material instanceof kv&&(h=!1),h&&!zw(c)&&(!t||c.layers.test(t))){const d=c.getBoundingBox;if(typeof d=="function"){const u=()=>{const m=c.initialized;n?.onIncomplete?.(c,m instanceof Promise?m:void 0)};if(c.isInitialized===!1)u();else try{const m=d.call(c);m&&!m.isEmpty()&&s.union(m.applyMatrix4(c.matrixWorld))}catch{u()}}}if(zw(c)||(h=!1),t&&c.layers.test(t)===!1&&(h=!1),c.isUI!==!0){if(h){const d=c.children;c.children=r;const u=c.position,m=c.scale;if(Number.isNaN(u.x)||Number.isNaN(u.y)||Number.isNaN(u.z)){console.warn(`Object "${c.name}" has NaN values in position or scale.... will ignore it`,u,m);return}c.geometry===null&&(c.geometry=void 0),s.expandByObject(c,!0),c.children=d}for(const d of c.children)a(d)}}}let l=!1;Array.isArray(o)||(o=[o]);for(const c of o)c&&(l=!0,c.updateMatrixWorld(),a(c));return l||console.warn("No objects to fit camera to..."),s}function $w(o,e,t){const i=Si([o],t?.ignore),n=new v;i.getSize(n);const s=new v;i.getCenter(s);const r=new v;e.getSize(r);const a=new v;e.getCenter(a);const l=new v;l.set(r.x/n.x,r.y/n.y,r.z/n.z);const c=Math.min(l.x,l.y,l.z),h=t?.scale!==!1;if(h&&hl(o,Je(o).multiplyScalar(c)),t?.position!==!1){const d=new v;i.getCenter(d),d.y=i.min.y;const u=new v;e.getCenter(u),u.y=e.min.y;const m=u.clone().sub(d);h&&m.multiplyScalar(c),Vi(o,le(o).add(m))}return{boundsBefore:i,scale:l}}function Ww(o,e){const t=Si([o]),i=new v;t.getCenter(i),i.y=t.min.y;const n=e.clone().sub(i),s=le(o);return Vi(o,s.add(n)),{offset:n,bounds:t}}function Zf(o,e,t,i){if(Array.isArray(e)){let r=!0;for(let a=0;a<e.length;a++)Zf(o,e[a],a,e)||(r=!1);return r}if(e.type==="MeshStandardMaterial"||e.type==="MeshBasicMaterial")return!1;if(e["material:fbx"]!=null)return!0;const n=new Mt;n["material:fbx"]=e;const s=e;return s&&(s.map?n.color.set(1,1,1):n.color.copyLinearToSRGB(s.color),n.emissive.copyLinearToSRGB(s.emissive),n.emissiveIntensity=s.emissiveIntensity,n.opacity=s.opacity,n.displacementScale=s.displacementScale,n.transparent=s.transparent,n.bumpMap=s.bumpMap,n.aoMap=s.aoMap,n.map=s.map,n.displacementMap=s.displacementMap,n.emissiveMap=s.emissiveMap,n.normalMap=s.normalMap,n.envMap=s.envMap,n.alphaMap=s.alphaMap,n.metalness=s.reflectivity,n.vertexColors=s.vertexColors,s.shininess&&(n.roughness=1-Math.sqrt(s.shininess)/10),n.needsUpdate=!0),t===void 0?o.material=n:i[t]=n,!0}let Du=!1;function NT(){lT((...o)=>{M()&&ce.Current?.isInXR&&(dl(!0),Vw("error",...o))})}function dl(o){if(o){if(Du)return;Du=!0,WT()}else{if(!Du)return;Du=!1,VT()}}const sh={log:void 0,warn:void 0,error:void 0};class $T{familyName="needle-xr";root=null;context=null;defaultFontSize=.06;constructor(){this.ensureFont()}onEnable(){this.context=ce.Current||ce.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){this.context?.pre_render_callbacks.splice(this.context?.pre_render_callbacks.indexOf(this.onBeforeRender),1),this.root?.removeFromParent()}targetObject=new R;userForwardViewPoint=new v;oneEuroFilter=new $f(90,.8);_lastElementRemoveTime=0;onBeforeRender=()=>{const e=this.context?.mainCamera;if(this.context&&e instanceof me){const t=this.getRoot();Number.isNaN(t.position.x)&&t.position.set(0,0,0),Number.isNaN(t.quaternion.x)&&t.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const i=this.context.xr?.rigScale??1,n=3.5*i,s=e.worldForward;s.y=0,s.normalize().multiplyScalar(n),this.userForwardViewPoint.copy(e.worldPosition).sub(s),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*i&&(this.targetObject.position.copy(this.userForwardViewPoint),nh(this.targetObject,e,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,t.position,this.context.time.time);const r=this.context.time.deltaTime;if(t.quaternion.slerp(this.targetObject.quaternion,r*5),t.scale.setScalar(i),this.targetObject.removeFromParent(),this.context.scene.add(t),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const a=Date.now();for(let l=0;l<this._activeTexts.length;l++){const c=this._activeTexts[l];if(c instanceof Le.Text&&a-c._activatedTime>2e4){c.removeFromParent(),this._textBuffer.push(c),this._activeTexts.splice(l,1);break}}}}};addLog(e,t){const i=this.getRoot(),n=this.getText();let s=16777215,r=0;switch(e){case"log":s=16777215,r=0;break;case"warn":s=16772761,r=4465152;break;case"error":s=16755370,r=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+"..."),t=t.replace(/°/g," deg").replace(/[→⇒]/g,"->").replace(/[✓✔✅]/g,"[ok]").replace(/[✗✘❌]/g,"[x]").replace(/[‘’]/g,"'").replace(/[“”]/g,'"').replace(/[–—]/g,"-").replace(/…/g,"...").replace(/[^\x20-\x7E\n\t]/g,"");const a=new Date().toISOString().split("T")[1].split(".")[0];n.textContent="["+a+"] "+t,n.visible=!0,n._activatedTime=Date.now(),i.add(n),this._activeTexts.push(n),this.context&&this.context.scene.add(i),n.set({backgroundColor:s,color:r}),Le.update()}ensureFont(){let e=Le.FontLibrary.getFontFamily(this.familyName);e||(e=Le.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{Le.update()}))}textOptions={fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025};_textBuffer=[];_activeTexts=[];getText(){const e=this.getRoot();if(this._textBuffer.length>0){const i=this._textBuffer.pop();return i.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(i),100),i}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const t=new Le.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let n=0;n<e.children.length;n++){const s=e.children[n];s instanceof R&&this.disableDepthTestRecursive(s,t+1)}e.renderOrder=10*t,e.layers.set(2);const i=e.material;i&&(i.depthWrite=!1,i.depthTest=!1,i.transparent=!0),t===0&&Le.update()}getRoot(){if(this.root)return this.root;const e=this.defaultFontSize,t={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:e,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new Le.Block(t),this.root}}let $r=null;function WT(){$r||($r=new $T),$r.onEnable();for(const o in sh){sh[o]=console[o];let e=!1;console[o]=function(){if(sh[o]?.apply(console,arguments),!e)try{e=!0,Vw(o,...arguments)}finally{e=!1}}}}function VT(){$r?.onDisable();for(const o in sh)console[o]=sh[o]}const rh=new Map;function Vw(o,...e){try{switch(rh.clear(),o){case"log":$r?.addLog("log",t());break;case"warn":$r?.addLog("warn",t());break;case"error":$r?.addLog("error",t());break}}catch(s){console.error("Error in spatial console",s)}finally{rh.clear()}function t(){let s="";for(let r=0;r<e.length;r++){const a=e[r];s+=i(a),r<e.length-1&&(s+=", ")}return s}function i(s,r=0){if(typeof s=="string")return'"'+s+'"';if(typeof s=="number"){if(s%1!==0){const a=s.toFixed(5),l=a.indexOf(".");let c=a.length-1;for(;c>l&&a[c]==="0";)c--;return a.substring(0,c+1)}return s.toString()}else if(Array.isArray(s)){let a="[";for(let l=0;l<s.length;l++){const c=s[l];a+=i(c,r+1),l<s.length-1&&(a+=", ")}return a+="]",a}else{if(s===null)return"null";if(s===void 0)return"undefined";if(typeof s=="function")return s.name+"()"}if(s instanceof ee)return`(${i(s.x)}, ${i(s.y)})`;if(s instanceof v)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)})`;if(s instanceof ve)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof B)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof ke||s instanceof Pe)return s.name;if(s instanceof sf)return`[${s.elements.join(", ")}]`;if(s instanceof J)return`[${s.elements.join(", ")}]`;if(s instanceof Fs)return s.mask.toString();if(typeof s=="object"){if(rh.has(s))return"*";let a=`{
81
+ }`})}reset(){this.uniforms.map.value=null,this.uniforms.flipY.value=!0,this.uniforms.writeDepth.value=!1,this.uniforms.depthTexture.value=null,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}}class Er{static _planeGeometry;static _renderer;static _perspectiveCam;static _orthographicCam;static _scene;static _blitMaterial;static _mesh;static get planeGeometry(){return this._planeGeometry??=new In(2,2,1,1)}static get renderer(){return this._renderer??=new Dr({antialias:!1,alpha:!0})}static get perspectiveCam(){return this._perspectiveCam??=new me}static get orthographicCam(){return this._orthographicCam??=new mu}static get scene(){return this._scene??=new Fi}static get blitMaterial(){return this._blitMaterial??=new Qg}static get mesh(){return this._mesh??=new V(Er.planeGeometry,Er.blitMaterial)}static copyTexture(e,t){t||(t=this.blitMaterial),this.blitMaterial.reset();const i=t||this.blitMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;const n=i.vertexShader;i.vertexShader=Qg.vertex;const s=this.mesh;s.material=i,s.frustumCulled=!1,this.scene.children.length=0,this.scene.add(s);const{width:r,height:a}=kT(e);this.renderer.setSize(r,a),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const l=new ke(this.renderer.domElement);return l.name="Copy",l.needsUpdate=!0,i.vertexShader=n,l}static blit(e,t,i){const{renderer:n=this.renderer,blitMaterial:s=this.blitMaterial,flipY:r=!1,depthTexture:a=null,depthTest:l=!0,depthWrite:c=!0}=i||{};this.blitMaterial.reset(),s.uniforms.map&&(s.uniforms.map.value=e),s.uniforms.flipY&&(s.uniforms.flipY.value=r),a?(s.uniforms.writeDepth=new an(!0),s.uniforms.depthTexture.value=a):(s.uniforms.writeDepth=new an(!1),s.uniforms.depthTexture.value=null),s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const h=this.mesh;h.material=s,h.frustumCulled=!1,this.scene.children.length=0,this.scene.add(h);const d=n.getRenderTarget(),u=n.getContext();l?u.enable(u.DEPTH_TEST):u.disable(u.DEPTH_TEST),n.state.buffers.depth.setMask(c),n.setClearColor(new oe(0,0,0),0),n.setRenderTarget(t),n.clear(),n.render(this.scene,this.perspectiveCam),n.setRenderTarget(d),u.enable(u.DEPTH_TEST),n.state.buffers.depth.setMask(!0)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Uw(e));const i=e.image;if(zT(i)&&ih(i)){const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const s=n.getContext("2d");return s?(s.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}}function Uw(o){return Er.copyTexture(o)}function UT(o,e=!1){return Er.textureToCanvas(o,e)}function zT(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}function zw(o){const e=o.type;return e==="Mesh"||e==="SkinnedMesh"}function Kf(o,e){e?o["needle:rendercustomshadow"]=!0:o["needle:rendercustomshadow"]=!1}function Nw(o){return!!(o&&(o["needle:rendercustomshadow"]===!0||o["needle:rendercustomshadow"]==null))}function Si(o,e=void 0,t=void 0,i=void 0,n){const s=i||new ri;s.makeEmpty();const r=[];function a(c){let h=!0;if(c.visible&&Ow(c)!==!1&&!(c.type==="TransformControlsGizmo"||c.type==="TransformControlsPlane")){if(e){if(Array.isArray(e)){if(e.includes(c))return}else if(typeof e=="function"&&e(c)===!0)return}if(c instanceof DO&&(h=!1),c instanceof Ov&&(h=!1),c instanceof al&&(h=!1),c.isGizmo===!0&&(h=!1),c.material instanceof kv&&(h=!1),h&&!zw(c)&&(!t||c.layers.test(t))){const d=c.getBoundingBox;if(typeof d=="function"){const u=()=>{const m=c.initialized;n?.onIncomplete?.(c,m instanceof Promise?m:void 0)};if(c.isInitialized===!1)u();else try{const m=d.call(c);m&&!m.isEmpty()&&s.union(m.applyMatrix4(c.matrixWorld))}catch{u()}}}if(zw(c)||(h=!1),t&&c.layers.test(t)===!1&&(h=!1),c.isUI!==!0){if(h){const d=c.children;c.children=r;const u=c.position,m=c.scale;if(Number.isNaN(u.x)||Number.isNaN(u.y)||Number.isNaN(u.z)){console.warn(`Object "${c.name}" has NaN values in position or scale.... will ignore it`,u,m);return}c.geometry===null&&(c.geometry=void 0),s.expandByObject(c,!0),c.children=d}for(const d of c.children)a(d)}}}let l=!1;Array.isArray(o)||(o=[o]);for(const c of o)c&&(l=!0,c.updateMatrixWorld(),a(c));return l||console.warn("No objects to fit camera to..."),s}function $w(o,e,t){const i=Si([o],t?.ignore),n=new v;i.getSize(n);const s=new v;i.getCenter(s);const r=new v;e.getSize(r);const a=new v;e.getCenter(a);const l=new v;l.set(r.x/n.x,r.y/n.y,r.z/n.z);const c=Math.min(l.x,l.y,l.z),h=t?.scale!==!1;if(h&&hl(o,Je(o).multiplyScalar(c)),t?.position!==!1){const d=new v;i.getCenter(d),d.y=i.min.y;const u=new v;e.getCenter(u),u.y=e.min.y;const m=u.clone().sub(d);h&&m.multiplyScalar(c),Vi(o,le(o).add(m))}return{boundsBefore:i,scale:l}}function Ww(o,e){const t=Si([o]),i=new v;t.getCenter(i),i.y=t.min.y;const n=e.clone().sub(i),s=le(o);return Vi(o,s.add(n)),{offset:n,bounds:t}}function Zf(o,e,t,i){if(Array.isArray(e)){let r=!0;for(let a=0;a<e.length;a++)Zf(o,e[a],a,e)||(r=!1);return r}if(e.type==="MeshStandardMaterial"||e.type==="MeshBasicMaterial")return!1;if(e["material:fbx"]!=null)return!0;const n=new Mt;n["material:fbx"]=e;const s=e;return s&&(s.map?n.color.set(1,1,1):n.color.copyLinearToSRGB(s.color),n.emissive.copyLinearToSRGB(s.emissive),n.emissiveIntensity=s.emissiveIntensity,n.opacity=s.opacity,n.displacementScale=s.displacementScale,n.transparent=s.transparent,n.bumpMap=s.bumpMap,n.aoMap=s.aoMap,n.map=s.map,n.displacementMap=s.displacementMap,n.emissiveMap=s.emissiveMap,n.normalMap=s.normalMap,n.envMap=s.envMap,n.alphaMap=s.alphaMap,n.metalness=s.reflectivity,n.vertexColors=s.vertexColors,s.shininess&&(n.roughness=1-Math.sqrt(s.shininess)/10),n.needsUpdate=!0),t===void 0?o.material=n:i[t]=n,!0}let Du=!1;function NT(){lT((...o)=>{M()&&ce.Current?.isInXR&&(dl(!0),Vw("error",...o))})}function dl(o){if(o){if(Du)return;Du=!0,WT()}else{if(!Du)return;Du=!1,VT()}}const sh={log:void 0,warn:void 0,error:void 0};class $T{familyName="needle-xr";root=null;context=null;defaultFontSize=.06;constructor(){this.ensureFont()}onEnable(){this.context=ce.Current||ce.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){this.context?.pre_render_callbacks.splice(this.context?.pre_render_callbacks.indexOf(this.onBeforeRender),1),this.root?.removeFromParent()}targetObject=new R;userForwardViewPoint=new v;oneEuroFilter=new $f(90,.8);_lastElementRemoveTime=0;onBeforeRender=()=>{const e=this.context?.mainCamera;if(this.context&&e instanceof me){const t=this.getRoot();Number.isNaN(t.position.x)&&t.position.set(0,0,0),Number.isNaN(t.quaternion.x)&&t.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const i=this.context.xr?.rigScale??1,n=3.5*i,s=e.worldForward;s.y=0,s.normalize().multiplyScalar(n),this.userForwardViewPoint.copy(e.worldPosition).sub(s),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*i&&(this.targetObject.position.copy(this.userForwardViewPoint),nh(this.targetObject,e,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,t.position,this.context.time.time);const r=this.context.time.deltaTime;if(t.quaternion.slerp(this.targetObject.quaternion,r*5),t.scale.setScalar(i),this.targetObject.removeFromParent(),this.context.scene.add(t),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const a=Date.now();for(let l=0;l<this._activeTexts.length;l++){const c=this._activeTexts[l];if(c instanceof Le.Text&&a-c._activatedTime>2e4){c.removeFromParent(),this._textBuffer.push(c),this._activeTexts.splice(l,1);break}}}}};addLog(e,t){const i=this.getRoot(),n=this.getText();let s=16777215,r=0;switch(e){case"log":s=16777215,r=0;break;case"warn":s=16772761,r=4465152;break;case"error":s=16755370,r=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+"..."),t=t.replace(/°/g," deg").replace(/[→⇒]/g,"->").replace(/[✓✔✅]/g,"[ok]").replace(/[✗✘❌]/g,"[x]").replace(/[‘’]/g,"'").replace(/[“”]/g,'"').replace(/[–—]/g,"-").replace(/…/g,"...").replace(/[^\x20-\x7E\n\t]/g,"");const a=new Date().toISOString().split("T")[1].split(".")[0];n.textContent="["+a+"] "+t,n.visible=!0,n._activatedTime=Date.now(),i.add(n),this._activeTexts.push(n),this.context&&this.context.scene.add(i),n.set({backgroundColor:s,color:r}),Le.update()}ensureFont(){let e=Le.FontLibrary.getFontFamily(this.familyName);e||(e=Le.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{Le.update()}))}textOptions={fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025};_textBuffer=[];_activeTexts=[];getText(){const e=this.getRoot();if(this._textBuffer.length>0){const i=this._textBuffer.pop();return i.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(i),100),i}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const t=new Le.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let n=0;n<e.children.length;n++){const s=e.children[n];s instanceof R&&this.disableDepthTestRecursive(s,t+1)}e.renderOrder=10*t,e.layers.set(2);const i=e.material;i&&(i.depthWrite=!1,i.depthTest=!1,i.transparent=!0),t===0&&Le.update()}getRoot(){if(this.root)return this.root;const e=this.defaultFontSize,t={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:e,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new Le.Block(t),this.root}}let $r=null;function WT(){$r||($r=new $T),$r.onEnable();for(const o in sh){sh[o]=console[o];let e=!1;console[o]=function(){if(sh[o]?.apply(console,arguments),!e)try{e=!0,Vw(o,...arguments)}finally{e=!1}}}}function VT(){$r?.onDisable();for(const o in sh)console[o]=sh[o]}const rh=new Map;function Vw(o,...e){try{switch(rh.clear(),o){case"log":$r?.addLog("log",t());break;case"warn":$r?.addLog("warn",t());break;case"error":$r?.addLog("error",t());break}}catch(s){console.error("Error in spatial console",s)}finally{rh.clear()}function t(){let s="";for(let r=0;r<e.length;r++){const a=e[r];s+=i(a),r<e.length-1&&(s+=", ")}return s}function i(s,r=0){if(typeof s=="string")return'"'+s+'"';if(typeof s=="number"){if(s%1!==0){const a=s.toFixed(5),l=a.indexOf(".");let c=a.length-1;for(;c>l&&a[c]==="0";)c--;return a.substring(0,c+1)}return s.toString()}else if(Array.isArray(s)){let a="[";for(let l=0;l<s.length;l++){const c=s[l];a+=i(c,r+1),l<s.length-1&&(a+=", ")}return a+="]",a}else{if(s===null)return"null";if(s===void 0)return"undefined";if(typeof s=="function")return s.name+"()"}if(s instanceof ee)return`(${i(s.x)}, ${i(s.y)})`;if(s instanceof v)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)})`;if(s instanceof ve)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof B)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof Oe||s instanceof ke)return s.name;if(s instanceof sf)return`[${s.elements.join(", ")}]`;if(s instanceof J)return`[${s.elements.join(", ")}]`;if(s instanceof Fs)return s.mask.toString();if(typeof s=="object"){if(rh.has(s))return"*";let a=`{
82
82
  `;a+=n(r);const l=Object.keys(s);let c="";for(let h=0;h<l.length;h++){const d=l[h],u=s[d];if(rh.has(u)){c+="";continue}rh.set(u,!0),c+=d+":"+i(u,r+1),h<l.length-1&&(c+=", "),c.length>=60&&(c+=`
83
83
  `,c+=n(r),a+=c,c="")}return a+=c,a+=`
84
84
  }`,a}return s}function n(s){let r="";for(let a=0;a<s;a++)r+=" ";return r}}function Fe(o,e){Ur(e?.type??Wi.Log,o,e)}function ge(o,e){Fe(o,{...e,type:Wi.Warn})}function ul(o,e){Fe(o,{...e,type:Wi.Error})}let Ci,Wr=null,lo=null,ah=!1,Gw=null;const Hw="terminal",Jf=x("console");let ju,Fu;function Bu(){if(ju===void 0)try{ju=document.createElement("canvas").getContext("webgl")}catch{ju=null}return ju??null}function Uu(){if(Fu===void 0)try{Fu=document.createElement("canvas").getContext("webgl2")}catch{Fu=null}return Fu??null}function qw(){return Uu()??Bu()}Jf&&ey();const GT=Symbol("consoleParent");function ey(){if(Ci){Ci.showSwitch();return}YT()}function Xw(){Ci&&(Ci.hide(),Ci.hideSwitch())}function HT(){Gw||(Gw=setInterval(qT,500))}let Qw=0;function qT(){const o=yw(),e=o!==Qw;Qw=o,e&&XT()}function XT(){ey(),lo&&(lo.setAttribute("error","true"),lo.innerText="\u{1F92C}")}function QT(){lo&&(lo.removeAttribute("error"),lo.innerText=Hw)}function YT(o=!1){if(Ci!==void 0||ah)return;ah=!0;const e=document.createElement("script");e.onload=()=>{if(!globalThis.VConsole){console.warn("\u{1F335} Debug console failed to load."),ah=!1,Ci=null;return}ah=!1,HT();const t=typeof Jf=="string"&&Jf.includes("network");Ci=new VConsole({defaultPlugins:t?["system","network","element","storage"]:["system","element","storage"],pluginOrder:["default","needle-console"]}),t&&console.warn("\u{1F335} ?console=network: vConsole's fetch proxy is enabled \u2014 WebAssembly streaming (e.g. gaussian splats) will fail on this page");const i=globalThis["needle:codegen_files"];if(i&&i.length>0&&Ci.addPlugin(KT()),Ci.addPlugin(tE()),Ci.addPlugin(iE()),Wr=pE(),Wr&&(Wr[GT]=Wr.parentElement,Wr.style.position="absolute",Wr.style.zIndex=Number.MAX_SAFE_INTEGER.toString()),Ci.setSwitchPosition(20,30),lo=uE(),lo){lo.innerText=Hw,lo.addEventListener("click",QT);const n=document.createElement("style"),s=40;n.innerHTML=`
@@ -140,7 +140,7 @@ void main(){
140
140
  #__vconsole .vc-mask {
141
141
  overflow: hidden;
142
142
  }
143
- `,Wr?.prepend(n),o===!0&&yw()<=0&&Xw(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),ah=!1,Ci=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function KT(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),Ci?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}const ty="padding: 10px; font-family: monospace;",Yw="margin-bottom: 10px;",Vr="margin-bottom: 10px; margin-top: 15px;",ZT="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",Kw="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",JT=Kw,eE=Kw+" word-break: break-all;";function co(o,e=!1){e&&o.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${ZT}'>`;t+="<tbody>";for(const i of o){const n=typeof i.value=="boolean"?i.value?"\u2705":"\u274C":i.value;t+=`<tr><td style='${JT}'>${i.label}</td><td style='${eE}'>${n}</td></tr>`}return t+="</tbody></table>",t}function Zw(){try{if(Uu())return"\u2705"}catch{}return"\u274C"}function tE(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("device-utilities","\u{1F4F1} Device Info");return o.on("renderTab",function(e){let t=`<div style='${ty}'>`;const i=dE();t+=`<h3 style='${Yw}'>Device: ${i}</h3>`,t+=co([{label:"\u{1F4BB} Desktop",value:I.isDesktop()},{label:"\u{1F4F1} Mobile Device",value:I.isMobileDevice()},{label:"\u{1F34E} iOS",value:I.isiOS()},{label:"\u{1F4F1} iPad",value:I.isiPad()},{label:"\u{1F916} Android",value:I.isAndroidDevice()},{label:"\u{1F98A} Mozilla XR",value:I.isMozillaXR()},{label:"\u{1F335} Needle App Clip",value:I.isNeedleAppClip()},{label:"\u{1F34F} macOS",value:I.isMacOS()},{label:"\u{1F453} VisionOS",value:I.isVisionOS()},{label:"\u{1F9ED} Safari",value:I.isSafari()},{label:"\u{1F576}\uFE0F Meta Quest",value:I.isQuest()},{label:"\u{1F517} QuickLook AR Support",value:I.supportsQuickLookAR()}],!0);const n=[],s=I.getiOSVersion();s&&n.push({label:"\u{1F34E} iOS Version",value:s});const r=I.getChromeVersion();r&&n.push({label:"\u{1F310} Chrome Version",value:r});const a=I.getSafariVersion();a&&n.push({label:"\u{1F9ED} Safari Version",value:a}),n.length>0&&(t+=co(n,!1)),t+="</div>",t+=`<div style='${ty} margin-top: 20px;'>`,t+=`<h3 style='${Yw}'>User Agent Info</h3>`;const l=[{label:"User Agent",value:navigator.userAgent},{label:"Platform",value:navigator.platform},{label:"App Version",value:navigator.appVersion},{label:"User Agent Data",value:navigator.userAgentData?`Platform: ${navigator.userAgentData.platform}, Mobile: ${navigator.userAgentData.mobile}`:"Not supported"},{label:"WebXR",value:"xr"in navigator?"\u2705":"\u274C"},{label:"WebGPU",value:"gpu"in navigator?"\u2705":"\u274C"},{label:"WebGL 2",value:Zw()}];t+=co(l,!1),t+="</div>",e(t)}),o}function iE(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("graphics-info","\u{1F3A8} Graphics Info");return o.on("renderTab",async function(e){let t=`<div style='${ty}'>`;const i=nE();i.length>0&&(t+=`<h3 style='${Vr}'>General GPU Info</h3>`,t+=co(i,!1));const n=sE();n.length>0&&(t+=`<h3 style='${Vr}'>WebGL</h3>`,t+=co(n,!1));const s=rE();s.length>0&&(t+=`<h3 style='${Vr}'>WebGL 2 Features</h3>`,t+=co(s,!1));const r=aE();r.length>0&&(t+=`<h3 style='${Vr}'>WebGL Limits</h3>`,t+=co(r,!1));const a=lE();a.length>0&&(t+=`<h3 style='${Vr}'>Texture Formats</h3>`,t+=co(a,!1));const l=await cE();if(l.length>0&&(t+=`<h3 style='${Vr}'>WebGPU</h3>`,t+=co(l,!1)),I.isSafari()){const c=hE();c.length>0&&(t+=`<h3 style='${Vr}'>Safari GPU Info</h3>`,t+=co(c,!1))}t+="</div>",e(t)}),o}function nE(){const o=[],e=window.devicePixelRatio;o.push({label:"Device Pixel Ratio",value:e.toString()}),o.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),o.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const t=I.isMobileDevice()?150:96,i=screen.width/t,n=screen.height/t,s=i*2.54,r=n*2.54;o.push({label:"Estimated Width (cm)",value:s.toFixed(1)}),o.push({label:"Estimated Height (cm)",value:r.toFixed(1)});const a=Jw();if(a){o.push({label:"GPU",value:a.renderer}),o.push({label:"Driver",value:a.vendor}),o.push({label:"ANGLE",value:a.angle||"Not detected"});const l=oE(a.renderer);l&&(l.manufacturer&&o.push({label:"Manufacturer",value:l.manufacturer}),l.cardVersion&&o.push({label:"Card Version",value:l.cardVersion}),l.brand&&o.push({label:"Brand",value:l.brand}),o.push({label:"Integrated",value:l.integrated?"Yes":"No"}),l.layer&&o.push({label:"WebGL Layer",value:l.layer}))}return o}function oE(o){if(!o)return null;const e=(l,c)=>{const h=c.match(l);return h&&h[0]},t=e(/(ANGLE)/g,o)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,o)||o,n=i.split(" ");n.shift();const s=e(/(NVIDIA|AMD|Intel)/g,i)||void 0,r=n.length>0?n.pop():void 0,a=n.length>0?n.join(" "):void 0;return{manufacturer:s,cardVersion:r,brand:a,integrated:s==="Intel",layer:t,card:i}}function sE(){const o=[],e=Jw();return e&&(o.push({label:"\u{1F4CA} WebGL Version",value:e.version}),o.push({label:"\u{1F3AE} WebGL 2 Available",value:Zw()})),o}function rE(){const o=[];try{const e=Uu();if(!e)return o;o.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"\u2705":"\u274C"}),o.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"\u2705":"\u274C"}),o.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"\u2705":"\u274C"}),o.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"\u2705":"\u274C"}),o.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"\u2705":"\u274C"}),o.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"\u2705":"\u274C"})}catch{}return o}function aE(){const o=[];try{const e=qw();if(!e)return o;const t=e instanceof WebGL2RenderingContext;o.push({label:"\u{1F4CF} Max Texture Size",value:e.getParameter(e.MAX_TEXTURE_SIZE).toString()}),o.push({label:"\u{1F3A8} Max Renderbuffer Size",value:e.getParameter(e.MAX_RENDERBUFFER_SIZE).toString()}),o.push({label:"\u{1F517} Max Vertex Attribs",value:e.getParameter(e.MAX_VERTEX_ATTRIBS).toString()}),o.push({label:"\u{1F3AF} Max Texture Units",value:e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS).toString()}),t&&(o.push({label:"\u26A1 Max Samples",value:e.getParameter(e.MAX_SAMPLES).toString()}),o.push({label:"\u{1F504} Max Uniform Buffer Bindings",value:e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),o.push({label:"\u{1F4D0} Max 3D Texture Size",value:e.getParameter(e.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return o}function lE(){const o=[];try{Bu()&&(o.push({label:"WebGL 1 RGBA",value:"\u2705"}),o.push({label:"WebGL 1 RGB",value:"\u2705"}));const e=Uu();e&&(o.push({label:"WebGL 2 RGBA32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 RGB32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 R11F_G11F_B10F",value:"\u2705"}),o.push({label:"WebGL 2 RGB565",value:"\u2705"}),o.push({label:"WebGL 2 RGB5_A1",value:"\u2705"}),o.push({label:"WebGL 2 RGBA4444",value:"\u2705"}))}catch{}return o}async function cE(){const o=[];if(!("gpu"in navigator))return o.push({label:"\u{1F680} WebGPU Support",value:"\u274C Not supported"}),o;o.push({label:"\u{1F680} WebGPU Support",value:"\u2705 Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return o.push({label:"\u{1F3AF} Adapter",value:"No adapter available"}),o;o.push({label:"\u{1F3AF} Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();o.push({label:"\u{1F527} Device",value:t.label||"WebGPU Device"}),o.push({label:"\u{1F4CF} Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),o.push({label:"\u{1F4D0} Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),o.push({label:"\u{1F4CA} Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),o.push({label:"\u{1F4BE} Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),o.push({label:"\u{1F517} Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){o.push({label:"\u274C Error",value:e.message})}return o}function Jw(){try{const o=qw();if(!o)return null;const e=o.getExtension("WEBGL_debug_renderer_info"),t=e?o.getParameter(e.UNMASKED_RENDERER_WEBGL):o.getParameter(o.RENDERER),i=e?o.getParameter(e.UNMASKED_VENDOR_WEBGL):o.getParameter(o.VENDOR),n=o.getParameter(o.VERSION);let s;if(t&&t.includes("ANGLE")){const r=t.match(/ANGLE \(([^)]+)\)/);r&&(s=r[1])}return{renderer:t,vendor:i,version:n,angle:s}}catch{return null}}function hE(){const o=[];try{const e=Bu();if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&o.push({label:"\u{1F34E} Apple GPU",value:i})}}}catch{}try{const e=Bu();e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&o.push({label:"\u{1F5DC}\uFE0F PVRTC Support",value:"\u2705"})}catch{}return o}function dE(){return I.isQuest()?"Meta Quest":I.isVisionOS()?"Vision Pro":I.isiOS()?I.isiPad()?"iPad":"iPhone/iPod":I.isAndroidDevice()?"Android Device":I.isMozillaXR()?"Mozilla XR Browser":I.isNeedleAppClip()?"Needle App Clip":I.isMacOS()?"Mac":I.isDesktop()?"Desktop PC":"Unknown Device"}function uE(){return document.querySelector("#__vconsole .vc-switch")||null}function pE(){return document.querySelector("#__vconsole")||null}const zu=x("debugtypes");class mE{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){zu&&console.warn("TypeStore: Created",this)}add(e,t){zu&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?zu&&i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):(this._types.set(e,t),this._reverseTypes.set(t,e))}addLazy(e,t){this._types.has(e)||this._lazyLoaders.set(e,t)}get(e){return this._types.get(e)||null}async getAsync(e){const t=this._types.get(e);if(t)return t;const i=this._lazyLoaders.get(e);if(i){zu&&console.warn("LAZY LOAD TYPE",e);const n=await i();return this.add(e,n),this._lazyLoaders.delete(e),n}return null}getKey(e){return this._reverseTypes.get(e)||null}get types(){return this._types}}const gE=Symbol("BuiltInType"),k=new mE,iy=function(o){k.get(o.name)||k.add(o.name,o)};class fE{context;mixers=[];constructor(e){this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}var li;(o=>{function e(h,d){const u=h.getRoot();return u&&(u.userData.static||u.matrixAutoUpdate===!1||u.matrixWorldAutoUpdate===!1)?((d===!0||d===void 0&&M())&&console.warn(`AnimationUtils: The root object (${u.name||u.type}) of this AnimationAction has matrixAutoUpdate or matrixWorldAutoUpdate set to false. This may prevent the animation from working correctly. If the object is marked as static, try to change it to dynamic.`,{static:u.userData.static,name:u.userData.name,tag:u.userData.tag,matrixAutoUpdate:u.matrixAutoUpdate,matrixWorldAutoUpdate:u.matrixWorldAutoUpdate}),!1):!0}o.testIfRootCanAnimate=e;function t(h){return h._actions||null}o.tryGetActionsFromMixer=t;function i(h,d){if(d||(d=new Array),h)h.animations&&d.push(...h.animations);else return d;if(h.children)for(const u of h.children)i(u,d);return d}o.tryGetAnimationClipsFromObjectHierarchy=i;const n=Symbol("objectIsAnimatedData");function s(h,d,u){if(!h)return;if(h[n]===void 0){if(!u)return;h[n]=new Set}const m=h[n];u?m.add(d):m.has(d)&&m.delete(d)}o.setObjectAnimated=s;function r(h){if(!h)return!1;const d=h[n];return d!==void 0&&d.size>0}o.getObjectAnimated=r;function a(h){if(!h||!h.animations)return console.debug("No animations found in file"),null;const d="scene"in h?h.scene:h,u=new Array;for(let g=0;g<h.animations.length;g++){const y=h.animations[g];if(!y.tracks||y.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const b in y.tracks){const f=y.tracks[b],_=nl.parseTrackName(f.name);let w=nl.findNode(d,_.nodeName);if(!w){const O=f.__objectName??f.name.substring(0,f.name.indexOf("."));if(w=d.getObjectByProperty("uuid",O)??null,!w)continue}let S=m(w)||m(d);if(!S){const O=k.get("Animation");if(S=d.addComponent(O),!S){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}u.push(S),S.addClip&&S.addClip(y)}}return u;function m(g){if(!g)return null;const y=g.userData?.components;if(y&&y.length>0)for(let b=0;b<y.length;b++){const f=y[b];if(f.isAnimationComponent===!0)return f}return m(g.parent)}}o.autoplayAnimations=a;function l(){return new Yt("empty",0,[])}o.emptyClip=l;function c(h){const d=h?.duration??.3;let u={x:1,y:1,z:1};h?.scale!==void 0&&(typeof h.scale=="number"?u={x:h.scale,y:h.scale,z:h.scale}:u=h.scale);const m=h?.type??"linear",g=h?.scaleFactor??1.2,y=new Array,b=new Array;switch(m){case"linear":y.push(0,d),b.push(u.x,u.y,u.z,u.x*g,u.y*g,u.z*g);break;case"spring":y.push(0,d*.3,d*.5,d*.7,d*.9,d),b.push(u.x,u.y,u.z,u.x*g,u.y*g,u.z*g,u.x*.9,u.y*.9,u.z*.9,u.x*1.05,u.y*1.05,u.z*1.05,u.x*.98,u.y*.98,u.z*.98,u.x,u.y,u.z);break}const f=new jO(".scale",y,b);return new Yt("scale",y[y.length-1],[f])}o.createScaleClip=c})(li||(li={}));const it=function(o){return p(o)},p=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=ex(o);else for(let e=0;e<o.length;e++){const t=o[e];o[e]=ex(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=o}};function ex(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}const tx=x("debugcomponentevents");class Nu{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),tx&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(tx&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const ix=x("debugdefines");$s('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),$s('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),$s('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),$s('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),$s('globalThis["__NEEDLE_ENGINE_VERSION__"] = "6.0.0-alpha.4";'),$s('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),$s('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Oct 02 2026 09:12:34 GMT+0000 (Coordinated Universal Time)";'),$s('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const ci="6.0.0-alpha.4",pl="undefined",lh="Fri Oct 02 2026 09:12:34 GMT+0000 (Coordinated Universal Time)";ix&&console.log(`Engine version: ${ci} (generator: ${pl})
143
+ `,Wr?.prepend(n),o===!0&&yw()<=0&&Xw(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),ah=!1,Ci=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function KT(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),Ci?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}const ty="padding: 10px; font-family: monospace;",Yw="margin-bottom: 10px;",Vr="margin-bottom: 10px; margin-top: 15px;",ZT="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",Kw="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",JT=Kw,eE=Kw+" word-break: break-all;";function co(o,e=!1){e&&o.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${ZT}'>`;t+="<tbody>";for(const i of o){const n=typeof i.value=="boolean"?i.value?"\u2705":"\u274C":i.value;t+=`<tr><td style='${JT}'>${i.label}</td><td style='${eE}'>${n}</td></tr>`}return t+="</tbody></table>",t}function Zw(){try{if(Uu())return"\u2705"}catch{}return"\u274C"}function tE(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("device-utilities","\u{1F4F1} Device Info");return o.on("renderTab",function(e){let t=`<div style='${ty}'>`;const i=dE();t+=`<h3 style='${Yw}'>Device: ${i}</h3>`,t+=co([{label:"\u{1F4BB} Desktop",value:I.isDesktop()},{label:"\u{1F4F1} Mobile Device",value:I.isMobileDevice()},{label:"\u{1F34E} iOS",value:I.isiOS()},{label:"\u{1F4F1} iPad",value:I.isiPad()},{label:"\u{1F916} Android",value:I.isAndroidDevice()},{label:"\u{1F98A} Mozilla XR",value:I.isMozillaXR()},{label:"\u{1F335} Needle App Clip",value:I.isNeedleAppClip()},{label:"\u{1F34F} macOS",value:I.isMacOS()},{label:"\u{1F453} VisionOS",value:I.isVisionOS()},{label:"\u{1F9ED} Safari",value:I.isSafari()},{label:"\u{1F576}\uFE0F Meta Quest",value:I.isQuest()},{label:"\u{1F517} QuickLook AR Support",value:I.supportsQuickLookAR()}],!0);const n=[],s=I.getiOSVersion();s&&n.push({label:"\u{1F34E} iOS Version",value:s});const r=I.getChromeVersion();r&&n.push({label:"\u{1F310} Chrome Version",value:r});const a=I.getSafariVersion();a&&n.push({label:"\u{1F9ED} Safari Version",value:a}),n.length>0&&(t+=co(n,!1)),t+="</div>",t+=`<div style='${ty} margin-top: 20px;'>`,t+=`<h3 style='${Yw}'>User Agent Info</h3>`;const l=[{label:"User Agent",value:navigator.userAgent},{label:"Platform",value:navigator.platform},{label:"App Version",value:navigator.appVersion},{label:"User Agent Data",value:navigator.userAgentData?`Platform: ${navigator.userAgentData.platform}, Mobile: ${navigator.userAgentData.mobile}`:"Not supported"},{label:"WebXR",value:"xr"in navigator?"\u2705":"\u274C"},{label:"WebGPU",value:"gpu"in navigator?"\u2705":"\u274C"},{label:"WebGL 2",value:Zw()}];t+=co(l,!1),t+="</div>",e(t)}),o}function iE(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("graphics-info","\u{1F3A8} Graphics Info");return o.on("renderTab",async function(e){let t=`<div style='${ty}'>`;const i=nE();i.length>0&&(t+=`<h3 style='${Vr}'>General GPU Info</h3>`,t+=co(i,!1));const n=sE();n.length>0&&(t+=`<h3 style='${Vr}'>WebGL</h3>`,t+=co(n,!1));const s=rE();s.length>0&&(t+=`<h3 style='${Vr}'>WebGL 2 Features</h3>`,t+=co(s,!1));const r=aE();r.length>0&&(t+=`<h3 style='${Vr}'>WebGL Limits</h3>`,t+=co(r,!1));const a=lE();a.length>0&&(t+=`<h3 style='${Vr}'>Texture Formats</h3>`,t+=co(a,!1));const l=await cE();if(l.length>0&&(t+=`<h3 style='${Vr}'>WebGPU</h3>`,t+=co(l,!1)),I.isSafari()){const c=hE();c.length>0&&(t+=`<h3 style='${Vr}'>Safari GPU Info</h3>`,t+=co(c,!1))}t+="</div>",e(t)}),o}function nE(){const o=[],e=window.devicePixelRatio;o.push({label:"Device Pixel Ratio",value:e.toString()}),o.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),o.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const t=I.isMobileDevice()?150:96,i=screen.width/t,n=screen.height/t,s=i*2.54,r=n*2.54;o.push({label:"Estimated Width (cm)",value:s.toFixed(1)}),o.push({label:"Estimated Height (cm)",value:r.toFixed(1)});const a=Jw();if(a){o.push({label:"GPU",value:a.renderer}),o.push({label:"Driver",value:a.vendor}),o.push({label:"ANGLE",value:a.angle||"Not detected"});const l=oE(a.renderer);l&&(l.manufacturer&&o.push({label:"Manufacturer",value:l.manufacturer}),l.cardVersion&&o.push({label:"Card Version",value:l.cardVersion}),l.brand&&o.push({label:"Brand",value:l.brand}),o.push({label:"Integrated",value:l.integrated?"Yes":"No"}),l.layer&&o.push({label:"WebGL Layer",value:l.layer}))}return o}function oE(o){if(!o)return null;const e=(l,c)=>{const h=c.match(l);return h&&h[0]},t=e(/(ANGLE)/g,o)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,o)||o,n=i.split(" ");n.shift();const s=e(/(NVIDIA|AMD|Intel)/g,i)||void 0,r=n.length>0?n.pop():void 0,a=n.length>0?n.join(" "):void 0;return{manufacturer:s,cardVersion:r,brand:a,integrated:s==="Intel",layer:t,card:i}}function sE(){const o=[],e=Jw();return e&&(o.push({label:"\u{1F4CA} WebGL Version",value:e.version}),o.push({label:"\u{1F3AE} WebGL 2 Available",value:Zw()})),o}function rE(){const o=[];try{const e=Uu();if(!e)return o;o.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"\u2705":"\u274C"}),o.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"\u2705":"\u274C"}),o.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"\u2705":"\u274C"}),o.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"\u2705":"\u274C"}),o.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"\u2705":"\u274C"}),o.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"\u2705":"\u274C"})}catch{}return o}function aE(){const o=[];try{const e=qw();if(!e)return o;const t=e instanceof WebGL2RenderingContext;o.push({label:"\u{1F4CF} Max Texture Size",value:e.getParameter(e.MAX_TEXTURE_SIZE).toString()}),o.push({label:"\u{1F3A8} Max Renderbuffer Size",value:e.getParameter(e.MAX_RENDERBUFFER_SIZE).toString()}),o.push({label:"\u{1F517} Max Vertex Attribs",value:e.getParameter(e.MAX_VERTEX_ATTRIBS).toString()}),o.push({label:"\u{1F3AF} Max Texture Units",value:e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS).toString()}),t&&(o.push({label:"\u26A1 Max Samples",value:e.getParameter(e.MAX_SAMPLES).toString()}),o.push({label:"\u{1F504} Max Uniform Buffer Bindings",value:e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),o.push({label:"\u{1F4D0} Max 3D Texture Size",value:e.getParameter(e.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return o}function lE(){const o=[];try{Bu()&&(o.push({label:"WebGL 1 RGBA",value:"\u2705"}),o.push({label:"WebGL 1 RGB",value:"\u2705"}));const e=Uu();e&&(o.push({label:"WebGL 2 RGBA32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 RGB32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 R11F_G11F_B10F",value:"\u2705"}),o.push({label:"WebGL 2 RGB565",value:"\u2705"}),o.push({label:"WebGL 2 RGB5_A1",value:"\u2705"}),o.push({label:"WebGL 2 RGBA4444",value:"\u2705"}))}catch{}return o}async function cE(){const o=[];if(!("gpu"in navigator))return o.push({label:"\u{1F680} WebGPU Support",value:"\u274C Not supported"}),o;o.push({label:"\u{1F680} WebGPU Support",value:"\u2705 Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return o.push({label:"\u{1F3AF} Adapter",value:"No adapter available"}),o;o.push({label:"\u{1F3AF} Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();o.push({label:"\u{1F527} Device",value:t.label||"WebGPU Device"}),o.push({label:"\u{1F4CF} Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),o.push({label:"\u{1F4D0} Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),o.push({label:"\u{1F4CA} Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),o.push({label:"\u{1F4BE} Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),o.push({label:"\u{1F517} Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){o.push({label:"\u274C Error",value:e.message})}return o}function Jw(){try{const o=qw();if(!o)return null;const e=o.getExtension("WEBGL_debug_renderer_info"),t=e?o.getParameter(e.UNMASKED_RENDERER_WEBGL):o.getParameter(o.RENDERER),i=e?o.getParameter(e.UNMASKED_VENDOR_WEBGL):o.getParameter(o.VENDOR),n=o.getParameter(o.VERSION);let s;if(t&&t.includes("ANGLE")){const r=t.match(/ANGLE \(([^)]+)\)/);r&&(s=r[1])}return{renderer:t,vendor:i,version:n,angle:s}}catch{return null}}function hE(){const o=[];try{const e=Bu();if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&o.push({label:"\u{1F34E} Apple GPU",value:i})}}}catch{}try{const e=Bu();e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&o.push({label:"\u{1F5DC}\uFE0F PVRTC Support",value:"\u2705"})}catch{}return o}function dE(){return I.isQuest()?"Meta Quest":I.isVisionOS()?"Vision Pro":I.isiOS()?I.isiPad()?"iPad":"iPhone/iPod":I.isAndroidDevice()?"Android Device":I.isMozillaXR()?"Mozilla XR Browser":I.isNeedleAppClip()?"Needle App Clip":I.isMacOS()?"Mac":I.isDesktop()?"Desktop PC":"Unknown Device"}function uE(){return document.querySelector("#__vconsole .vc-switch")||null}function pE(){return document.querySelector("#__vconsole")||null}const zu=x("debugtypes");class mE{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){zu&&console.warn("TypeStore: Created",this)}add(e,t){zu&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?zu&&i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):(this._types.set(e,t),this._reverseTypes.set(t,e))}addLazy(e,t){this._types.has(e)||this._lazyLoaders.set(e,t)}get(e){return this._types.get(e)||null}async getAsync(e){const t=this._types.get(e);if(t)return t;const i=this._lazyLoaders.get(e);if(i){zu&&console.warn("LAZY LOAD TYPE",e);const n=await i();return this.add(e,n),this._lazyLoaders.delete(e),n}return null}getKey(e){return this._reverseTypes.get(e)||null}get types(){return this._types}}const gE=Symbol("BuiltInType"),k=new mE,iy=function(o){k.get(o.name)||k.add(o.name,o)};class fE{context;mixers=[];constructor(e){this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}var li;(o=>{function e(h,d){const u=h.getRoot();return u&&(u.userData.static||u.matrixAutoUpdate===!1||u.matrixWorldAutoUpdate===!1)?((d===!0||d===void 0&&M())&&console.warn(`AnimationUtils: The root object (${u.name||u.type}) of this AnimationAction has matrixAutoUpdate or matrixWorldAutoUpdate set to false. This may prevent the animation from working correctly. If the object is marked as static, try to change it to dynamic.`,{static:u.userData.static,name:u.userData.name,tag:u.userData.tag,matrixAutoUpdate:u.matrixAutoUpdate,matrixWorldAutoUpdate:u.matrixWorldAutoUpdate}),!1):!0}o.testIfRootCanAnimate=e;function t(h){return h._actions||null}o.tryGetActionsFromMixer=t;function i(h,d){if(d||(d=new Array),h)h.animations&&d.push(...h.animations);else return d;if(h.children)for(const u of h.children)i(u,d);return d}o.tryGetAnimationClipsFromObjectHierarchy=i;const n=Symbol("objectIsAnimatedData");function s(h,d,u){if(!h)return;if(h[n]===void 0){if(!u)return;h[n]=new Set}const m=h[n];u?m.add(d):m.has(d)&&m.delete(d)}o.setObjectAnimated=s;function r(h){if(!h)return!1;const d=h[n];return d!==void 0&&d.size>0}o.getObjectAnimated=r;function a(h){if(!h||!h.animations)return console.debug("No animations found in file"),null;const d="scene"in h?h.scene:h,u=new Array;for(let g=0;g<h.animations.length;g++){const y=h.animations[g];if(!y.tracks||y.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const b in y.tracks){const f=y.tracks[b],_=nl.parseTrackName(f.name);let w=nl.findNode(d,_.nodeName);if(!w){const O=f.__objectName??f.name.substring(0,f.name.indexOf("."));if(w=d.getObjectByProperty("uuid",O)??null,!w)continue}let S=m(w)||m(d);if(!S){const O=k.get("Animation");if(S=d.addComponent(O),!S){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}u.push(S),S.addClip&&S.addClip(y)}}return u;function m(g){if(!g)return null;const y=g.userData?.components;if(y&&y.length>0)for(let b=0;b<y.length;b++){const f=y[b];if(f.isAnimationComponent===!0)return f}return m(g.parent)}}o.autoplayAnimations=a;function l(){return new Yt("empty",0,[])}o.emptyClip=l;function c(h){const d=h?.duration??.3;let u={x:1,y:1,z:1};h?.scale!==void 0&&(typeof h.scale=="number"?u={x:h.scale,y:h.scale,z:h.scale}:u=h.scale);const m=h?.type??"linear",g=h?.scaleFactor??1.2,y=new Array,b=new Array;switch(m){case"linear":y.push(0,d),b.push(u.x,u.y,u.z,u.x*g,u.y*g,u.z*g);break;case"spring":y.push(0,d*.3,d*.5,d*.7,d*.9,d),b.push(u.x,u.y,u.z,u.x*g,u.y*g,u.z*g,u.x*.9,u.y*.9,u.z*.9,u.x*1.05,u.y*1.05,u.z*1.05,u.x*.98,u.y*.98,u.z*.98,u.x,u.y,u.z);break}const f=new jO(".scale",y,b);return new Yt("scale",y[y.length-1],[f])}o.createScaleClip=c})(li||(li={}));const it=function(o){return p(o)},p=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=ex(o);else for(let e=0;e<o.length;e++){const t=o[e];o[e]=ex(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=o}};function ex(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}const tx=x("debugcomponentevents");class Nu{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),tx&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(tx&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const ix=x("debugdefines");$s('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),$s('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),$s('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),$s('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),$s('globalThis["__NEEDLE_ENGINE_VERSION__"] = "6.0.0-alpha.6";'),$s('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),$s('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Tue Oct 06 2026 10:27:28 GMT+0000 (Coordinated Universal Time)";'),$s('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const ci="6.0.0-alpha.6",pl="undefined",lh="Tue Oct 06 2026 10:27:28 GMT+0000 (Coordinated Universal Time)";ix&&console.log(`Engine version: ${ci} (generator: ${pl})
144
144
  Project built at ${lh}`);const Ns=NEEDLE_PUBLIC_KEY,ho="needle_isActiveInHierarchy",Gr="builtin_components",ts="needle_editor_guid";function $s(o){try{(0,eval)(o)}catch(e){ix&&console.error(e)}}globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0,globalThis.NEEDLE_USE_POSTPROCESSING=globalThis.NEEDLE_USE_POSTPROCESSING!==void 0?globalThis.NEEDLE_USE_POSTPROCESSING:!0;const ny={experimentalSmartHierarchyUpdate:!1},Gi=Symbol("shadowDomOwner"),yE=x("debugpatch");function $u(o,e,t,i){const n=yE===e;if(!t&&!i)return;const s=e+"___needle";_E(o,e,t,i);const r=Object.getOwnPropertyDescriptor(o,e),a=o[e];n&&console.log("Patch",o.constructor.name,e,r,a),r?(n&&console.log("Apply patch with existing descriptor",o.constructor.name,e,r),typeof r.value=="function"&&(o[e]=ox(r.value,o,e))):(n&&console.log("Create patch with new property",o.constructor.name,e,r),Object.defineProperty(o,e,{set:function(l){if(typeof l=="function")this[s]=ox(l,o,e);else{const c=this[s];sx(o,e,this,c,l),this[s]=l,rx(o,e,this,c,l)}},get:function(){const l=this[s];return typeof l=="function"&&l[s]?l[s]:l}}))}function bE(o,e,t){const i=sy(o,e);if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];s.prefix===t&&(s.prefix=null),s.postfix===t&&(s.postfix=null),!s.prefix&&!s.postfix&&i.splice(n,1)}}const nx=Symbol("Needle:Patches:WrappedFunction");function ox(o,e,t){if(o[nx])return o;const i=function(...n){sx(e,t,this,...n);const s=o.apply(this,n);return rx(e,t,this,s,...n),s};return i[nx]=!0,i}const Wu="Needle:Patches";function oy(){return globalThis[Wu]||(globalThis[Wu]=new WeakMap),globalThis[Wu]}function sy(o,e){const t=oy().get(o);return t?t.get(e):null}function _E(o,e,t,i){let n=oy().get(o);n||(n=new Map,oy().set(o,n));let s=n.get(e);s||(s=[],n.set(e,s)),s.push({prefix:t,postfix:i})}function sx(o,e,t,...i){if(!t)return;const n=sy(o,e);if(n)for(const s of n)s.prefix?.call(t,...i)}function rx(o,e,t,i,...n){if(!t)return;const s=sy(o,e);if(s)for(const r of s)r.postfix?.call(t,i,...n)}function vE(o,e){if(typeof window!==void 0&&window.SPECTOR){console.log(window.SPECTOR);const t=new URLSearchParams(window.location.search);if(t.has("spector")){let i=function(){if(n>o.time.frame)return window.requestAnimationFrame(()=>i());const r=s.captureCanvas(e);r&&r instanceof Promise?r.then(()=>s.displayUI()):s.displayUI()};const n=Number.parseInt(t.get("spector")||"0")||0;console.log("Scheduled Spector capture at frame #"+n);const s=new window.SPECTOR.Spector;s.spyCanvases=!0,i();return}else M()&&console.debug("Spector available: Add '?spector=<frame>' to the URL to enable it and capture a frame.")}}function ax(o){const e=o;return!!(e.parser&&e.parser.json)}var uo=(o=>(o[o.None=0]="None",o[o.DontExport=1]="DontExport",o[o.DontInstantiate=2]="DontInstantiate",o))(uo||{});const Vu=Symbol("component-name");function Gu(o){return o&&typeof o=="object"&&o.isComponent}const wE=Symbol("object"),ry=new $i(()=>new v,20);class lx{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return ry.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return ry.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return ry.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,s,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=s,this._tangentVelocity=r}}class cx{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}}class hx{object;collider;constructor(e,t){this.object=e,this.collider=t}}class Yg{constructor(e){this.context=e,this.root.style.cssText=`
145
145
  position: absolute;
146
146
  width: 1px; height: 1px;
@@ -158,7 +158,7 @@ To unregister you can call the function returned by your event hook (e.g.const u
158
158
 
159
159
  or by using the once option like onStart(()=>{}, { once:true }).
160
160
 
161
- See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function Ws(o,e){const t=gl.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===o){t.splice(n,1);return}}const i=ml.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===o){i.splice(n,1);return}}}function po(o,e){e===de.ContextCreated&&ly.delete(o),gx(o,e)}function gx(o,e){e===Ee.Start&&ml.get(de.ContextCreated)&&gx(o,de.ContextCreated);const t=e===Ee.Start||e===de.ContextCreated,i=gl.get(e);i&&i.length>0&&yx(o,i,t);const n=ml.get(e);if(n&&n.length>0){const s=[...n];n.length=0,yx(o,s,t),s.length>0&&(gl.has(e)||gl.set(e,new Array),gl.get(e).push(...s))}}const fx=[];let qu=0;const Xu={context:null};function yx(o,e,t){const i=fx[qu]??(fx[qu]=[]);qu++;try{CE(o,e,t,i)}finally{i.length=0,qu--}}function CE(o,e,t,i){for(let s=0;s<e.length;s++)i.push(e[s]);let n=ly.get(o);for(let s=0;s<i.length;s++){const r=i[s];let a=!0;if(n&&n.has(r)&&(a=!1),a){const l=Xu.context;try{Xu.context=o,r.method?.call(Xu,o)}catch(c){console.error("Error in lifecycle method",c)}finally{Xu.context=l}}if(r.options?.once){for(let l=0;l<e.length;l++)if(e[l]===r){e.splice(l,1);break}}else t&&(n||(n=new Set,ly.set(o,n)),n.add(r))}}const ly=new WeakMap;function cy(o,e){return ns(o,de.ContextCreated,e),()=>Ws(o,de.ContextCreated)}function PE(o,e){return ns(o,de.ContextClearing,e),()=>Ws(o,de.ContextClearing)}function kE(o,e){return ns(o,de.ContextDestroying,e),()=>Ws(o,de.ContextDestroying)}function Qu(o,e){return ns(o,Ee.Start,e),()=>Ws(o,Ee.Start)}function bx(o,e){return ns(o,Ee.Update,e),()=>Ws(o,Ee.Update)}function OE(o,e){return ns(o,Ee.OnBeforeRender,e),()=>Ws(o,Ee.OnBeforeRender)}function ME(o,e){return ns(o,Ee.OnAfterRender,e),()=>Ws(o,Ee.OnAfterRender)}const Oe=x("__debuglic__"),Yu=new WeakMap,Ku=new WeakMap,hy=new WeakSet;ce.registerCallback(de.ContextDestroying,({context:o})=>{hy.add(o);for(const e of Yu.get(o)??[])clearInterval(e);Yu.delete(o);for(const e of Ku.get(o)??[])clearTimeout(e);Ku.delete(o)});function dy(o,e,t){if(hy.has(o))return;let i=Yu.get(o);i||Yu.set(o,i=new Set);const n=setInterval(e,t);return i.add(n),n}function Zu(o,e,t){if(hy.has(o))return;let i=Ku.get(o);i||Ku.set(o,i=new Set);const n=setTimeout(()=>{i.delete(n),e()},t);return i.add(n),n}const Ju=[];let Hi="",ch="";if(Oe)if(console.log("License Type: "+Hi),ch){console.log("License JWT: "+ch);try{const o=JSON.parse(atob(ch.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));console.log("License JWT payload:",o)}catch{console.log("License JWT payload: (failed to decode)")}}else console.log("License JWT: (none)");function mo(){switch(Hi){case"pro":case"enterprise":return!0}return!1}function hh(){return Hi==="indie"}function uy(){return Hi==="edu"}function cn(){return mo()||hh()||uy()}function RE(o){return mo()||hh()||uy()?(o(!0),()=>{}):(Ju.push(o),()=>{const e=Ju.indexOf(o);e>=0&&Ju.splice(e,1)})}function dh(o){for(const e of Ju)try{e(o)}catch{}}const TE={kty:"EC",crv:"P-256",x:"A34nyKMjhQYVgzeE4tyLUYdx34TAKogDa7v7PRaO9Lg",y:"JZI9IQavGCpGjEG_-pa0J-MHQYWJYINUM-MnvSu0TmE"};function _x(o){const e=o.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),i=atob(t),n=new Uint8Array(i.length);for(let s=0;s<i.length;s++)n[s]=i.charCodeAt(s);return n}async function EE(o){if(!o)return null;try{const e=o.split(".");if(e.length!==3)return null;const[t,i,n]=e,s=await crypto.subtle.importKey("jwk",TE,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),r=new TextEncoder().encode(`${t}.${i}`),a=_x(n);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,a.buffer,r))return Oe&&console.warn("JWT: signature verification failed"),null;const l=new TextDecoder().decode(_x(i)),c=JSON.parse(l);if(typeof c.type!="string"||c.type.length===0)return Oe&&console.warn("JWT: missing or invalid 'type' claim"),null;if(typeof c.exp=="number"){const h=Math.floor(Date.now()/1e3);if(h>c.exp)return Oe&&console.warn("JWT: token has expired (exp="+c.exp+", now="+h+")"),null}if(c.aud){const h=typeof window<"u"?window.location.hostname:void 0;if(h){const d=Array.isArray(c.aud)?c.aud:[c.aud];if(!d.some(u=>h===u||h.endsWith("."+u)))return Oe&&console.warn("JWT: domain '"+h+"' not in allowed audience: "+d.join(", ")),null}}return Oe&&console.log("JWT: verified license type: "+c.type),c.type}catch(e){return Oe&&console.error("JWT: verification error",e),null}}let py;async function AE(){const o=ch;ch="";const e=await EE(o);e?(Hi=e,Oe&&console.log("License type set from verified JWT: "+e),dh(cn())):(Hi="basic",Oe&&o&&console.warn("JWT verification failed \u2014 license reset to basic"))}var ct;(o=>{typeof window<"u"&&(window.addEventListener("error",f=>{c(Q.Current,"unhandled_error",f)}),window.addEventListener("unhandledrejection",f=>{t(f)}));function e(f,_){if(f==="AbortError")return!0;const w=(_||"").toLowerCase();return w.includes("load failed")||w.includes("failed to fetch")||w.includes("networkerror")||w.includes("network connection was lost")||w.includes("the operation was aborted")||w.includes("load cancelled")}function t(f){const _=f?.reason,w=typeof _?.name=="string"?_.name:void 0,S=typeof _?.message=="string"?_.message:typeof _=="string"?_:void 0,O=Q.Current,L=typeof document<"u"?document.visibilityState:void 0,D=typeof navigator<"u"?navigator.onLine:void 0;if(e(w,S)){l(O,"network_rejection",{message:S,name:w,visibility:L,online:D});return}c(O,"unhandled_promise_rejection",{name:w,message:S,stack:_?.stack,url:typeof _?.url=="string"?_.url:void 0,visibility:L,online:D,version:ci,timestamp:Date.now()})}function i(){ay||cy(f=>n(f),{once:!0})}o.init=i;function n(f){if(!s(f)){Oe&&console.debug("Telemetry is disabled via no-telemetry attribute");return}return b({site_id:"dabb8317376f",type:"pageview",pathname:window.location.pathname,hostname:window.location.hostname,page_title:document.title,referrer:document.referrer,user_agent:navigator.userAgent,querystring:window.location.search,language:navigator.language,screenWidth:window.screen.width,screenHeight:window.screen.height,event_name:"page_view"}).then(_=>{if(_ instanceof Response&&_.ok&&Ni()){const w=(f.domElement?.getAttribute("src")||"")+ci+pl+lh+Ns;window.sessionStorage.getItem("session_key")!==w&&(window.sessionStorage.setItem("session_key",w),l(f,"info",{src:f.domElement?.getAttribute("src")||"",version:ci,generator:pl,build_time:lh,public_key:Ns}))}})}function s(f){let _=f?.domElement;if(_||(_=document.querySelector("needle-engine")),!_&&!f)return!1;const w=_?.getAttribute("no-telemetry");return mo()&&(w===""||w==="true"||w==="1")?(Oe&&console.debug("Telemetry is disabled via no-telemetry attribute"),!1):r()?(Oe&&console.debug("Telemetry is disabled via Do Not Track / Global Privacy Control"),!1):typeof window<"u"&&window.crossOriginIsolated?(Oe&&console.debug("Telemetry is disabled on cross-origin-isolated pages"),!1):!0}o.isAllowed=s;function r(){if(typeof navigator>"u")return!1;const f=navigator;if(f.globalPrivacyControl===!0)return!0;const _=f.doNotTrack??f.msDoNotTrack??(typeof window<"u"?window.doNotTrack:null);return _==="1"||_==="yes"}const a="dabb8317376f";async function l(f,_,w){if(!s(f)){Oe&&console.debug("Telemetry is disabled");return}const S={site_id:a,type:"custom_event",pathname:window.location.pathname,event_name:_,properties:w?JSON.stringify(w):void 0};return b(S)}o.sendEvent=l;async function c(f,_,w){if(!s(f)){Oe&&console.debug("Telemetry is disabled");return}w instanceof ErrorEvent?w={message:w.message,stack:w.error?.stack,filename:w.filename,lineno:w.lineno,colno:w.colno,timestamp:w.timeStamp||Date.now()}:w instanceof Error&&(w={message:w.message,stack:w.stack,timestamp:Date.now()});const S={site_id:a,type:"error",event_name:_||"error",properties:JSON.stringify({error_name:_,message:w.message,stack:w.stack,filename:w.filename,lineno:w.lineno,colno:w.colno,timestamp:w.timestamp,name:w.name,visibility:w.visibility,online:w.online,url:w.url,version:w.version})};return b(S)}o.sendError=c;function h(f,_){if(!s(f))return;const w={action:"load",success:_.success,files:_.files,is_reload:_.is_reload,load_ms:Math.round(_.load_ms)};_.error&&(w.error=_.error),_.first_frame_ms!==void 0&&(w.first_frame_ms=Math.round(_.first_frame_ms)),_.since_navigation_ms!==void 0&&(w.since_navigation_ms=Math.round(_.since_navigation_ms)),_.success&&d(f,w),l(f,"engine",w)}o.reportLoad=h;function d(f,_){const w=f?.renderer;if(w)try{if(w.isWebGPURenderer===!0)_.api="webgpu";else{const S=w.getContext();if(S){const O=typeof WebGL2RenderingContext<"u"&&S instanceof WebGL2RenderingContext;_.api=O?"webgl2":"webgl",_.max_texture_size=S.getParameter(S.MAX_TEXTURE_SIZE),O&&(_.max_samples=S.getParameter(S.MAX_SAMPLES));const L=[];S.getExtension("WEBGL_compressed_texture_astc")&&L.push("astc"),S.getExtension("WEBGL_compressed_texture_etc")&&L.push("etc"),S.getExtension("WEBGL_compressed_texture_s3tc")&&L.push("s3tc"),S.getExtension("WEBGL_compressed_texture_pvrtc")&&L.push("pvrtc"),L.length&&(_.compression=L.join(","))}}if(_.dpr=w.getPixelRatio(),_.is_mobile=I.isMobileDevice(),typeof navigator<"u"){navigator.hardwareConcurrency&&(_.cores=navigator.hardwareConcurrency);const S=navigator.deviceMemory;typeof S=="number"&&(_.device_memory=S)}}catch(S){Oe&&console.warn("Telemetry: capability probe failed",S)}}const u=new WeakSet;function m(f){const _=f?.renderer?.domElement;if(!_||u.has(_))return;u.add(_);let w=0;_.addEventListener("webglcontextlost",()=>{w=performance.now(),l(f,"engine",{action:"context_lost",since_navigation_ms:Math.round(performance.now()),during_xr:f?.isInXR===!0})}),_.addEventListener("webglcontextrestored",()=>{l(f,"engine",{action:"context_restored",downtime_ms:w?Math.round(performance.now()-w):void 0})})}o.attachContextLossMonitor=m;const g=new WeakSet;function y(f){if(!f||typeof document>"u"||g.has(f)||!s(f))return;g.add(f);let _=0,w=0,S=0,O=0,L=0;const D=()=>{const E=f.time.deltaTimeUnscaled;if(E<=0)return;_++,w+=E*1e3,E>S&&(S=E);const z=f.renderer?.info?.render;z&&(z.calls>O&&(O=z.calls),z.triangles>L&&(L=z.triangles))};f.post_render_callbacks.push(D);const W=()=>{_=0,w=0,S=0,O=0,L=0},$=()=>{_<=0||(l(f,"engine",{action:"performance",frames:_,duration_ms:Math.round(w),avg_fps:Math.round(1e3*_/w),min_fps:S>0?Math.round(1/S):0,avg_frame_ms:Math.round(w/_*10)/10,max_frame_ms:Math.round(S*1e3*10)/10,peak_draw_calls:O,peak_triangles:L}),W())},H=()=>{document.visibilityState==="hidden"&&$()};document.addEventListener("visibilitychange",H),window.addEventListener("pagehide",$);const G=ce.registerCallback(de.ContextDestroyed,E=>{if(E.context!==f)return;$(),document.removeEventListener("visibilitychange",H),window.removeEventListener("pagehide",$);const z=f.post_render_callbacks.indexOf(D);z>=0&&f.post_render_callbacks.splice(z,1),g.delete(f),G()})}o.attachPerformanceMonitor=y;function b(f){try{return fetch("https://needle.tools/api/v1/rum/t",{method:"POST",body:JSON.stringify(f),headers:{"Content-Type":"application/json"},keepalive:!0,mode:"cors",priority:"low"}).catch(_=>{Oe&&console.error("Failed to send telemetry",_)})}catch(_){Oe&&console.error(_)}return Promise.resolve()}})(ct||(ct={}));function IE(){Hi===""&&(Hi="basic"),py=AE(),ct.init(),ce.registerCallback(de.ContextRegistered,o=>{jE(o.context),DE(o.context),Zu(o.context,()=>BE(o.context),2e3)}),ce.registerCallback(de.ContextCreated,o=>{ct.attachContextLossMonitor(o.context),ct.attachPerformanceMonitor(o.context)})}let ep,my=!1,gy="";async function LE(){if(ep)return ep;if(py&&await py,Hi==="basic")try{const o="https://needle.tools/api/v1/needle-engine/check?location="+encodeURIComponent(window.location.href)+"&version="+ci+"&generator="+encodeURIComponent(pl),e=await fetch(o,{method:"GET"}).catch(t=>{Oe&&console.error("License check failed",t)});e?.status===200?(my=!1,Oe&&console.log("License check succeeded"),Hi="pro",dh(!0)):e?.status===403?(dh(!1),my=!0,gy=await e.text()):(dh(!1),Oe&&console.log("License check failed with status "+e?.status))}catch(o){dh(!1),Oe&&console.error("License check failed",o)}else Oe&&console.log('Runtime license check is skipped because license is already applied as "'+Hi+'"')}ep=LE();async function DE(o){function e(){const n=document.createElement("div");n.className="needle-forbidden",n.style.cssText=`
161
+ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function Ws(o,e){const t=gl.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===o){t.splice(n,1);return}}const i=ml.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===o){i.splice(n,1);return}}}function po(o,e){e===de.ContextCreated&&ly.delete(o),gx(o,e)}function gx(o,e){e===Ee.Start&&ml.get(de.ContextCreated)&&gx(o,de.ContextCreated);const t=e===Ee.Start||e===de.ContextCreated,i=gl.get(e);i&&i.length>0&&yx(o,i,t);const n=ml.get(e);if(n&&n.length>0){const s=[...n];n.length=0,yx(o,s,t),s.length>0&&(gl.has(e)||gl.set(e,new Array),gl.get(e).push(...s))}}const fx=[];let qu=0;const Xu={context:null};function yx(o,e,t){const i=fx[qu]??(fx[qu]=[]);qu++;try{CE(o,e,t,i)}finally{i.length=0,qu--}}function CE(o,e,t,i){for(let s=0;s<e.length;s++)i.push(e[s]);let n=ly.get(o);for(let s=0;s<i.length;s++){const r=i[s];let a=!0;if(n&&n.has(r)&&(a=!1),a){const l=Xu.context;try{Xu.context=o,r.method?.call(Xu,o)}catch(c){console.error("Error in lifecycle method",c)}finally{Xu.context=l}}if(r.options?.once){for(let l=0;l<e.length;l++)if(e[l]===r){e.splice(l,1);break}}else t&&(n||(n=new Set,ly.set(o,n)),n.add(r))}}const ly=new WeakMap;function cy(o,e){return ns(o,de.ContextCreated,e),()=>Ws(o,de.ContextCreated)}function PE(o,e){return ns(o,de.ContextClearing,e),()=>Ws(o,de.ContextClearing)}function kE(o,e){return ns(o,de.ContextDestroying,e),()=>Ws(o,de.ContextDestroying)}function Qu(o,e){return ns(o,Ee.Start,e),()=>Ws(o,Ee.Start)}function bx(o,e){return ns(o,Ee.Update,e),()=>Ws(o,Ee.Update)}function OE(o,e){return ns(o,Ee.OnBeforeRender,e),()=>Ws(o,Ee.OnBeforeRender)}function ME(o,e){return ns(o,Ee.OnAfterRender,e),()=>Ws(o,Ee.OnAfterRender)}const Se=x("__debuglic__"),Yu=new WeakMap,Ku=new WeakMap,hy=new WeakSet;ce.registerCallback(de.ContextDestroying,({context:o})=>{hy.add(o);for(const e of Yu.get(o)??[])clearInterval(e);Yu.delete(o);for(const e of Ku.get(o)??[])clearTimeout(e);Ku.delete(o)});function dy(o,e,t){if(hy.has(o))return;let i=Yu.get(o);i||Yu.set(o,i=new Set);const n=setInterval(e,t);return i.add(n),n}function Zu(o,e,t){if(hy.has(o))return;let i=Ku.get(o);i||Ku.set(o,i=new Set);const n=setTimeout(()=>{i.delete(n),e()},t);return i.add(n),n}const Ju=[];let Hi="",ch="";if(Se)if(console.log("License Type: "+Hi),ch){console.log("License JWT: "+ch);try{const o=JSON.parse(atob(ch.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));console.log("License JWT payload:",o)}catch{console.log("License JWT payload: (failed to decode)")}}else console.log("License JWT: (none)");function mo(){switch(Hi){case"pro":case"enterprise":return!0}return!1}function hh(){return Hi==="indie"}function uy(){return Hi==="edu"}function cn(){return mo()||hh()||uy()}function RE(o){return mo()||hh()||uy()?(o(!0),()=>{}):(Ju.push(o),()=>{const e=Ju.indexOf(o);e>=0&&Ju.splice(e,1)})}function dh(o){for(const e of Ju)try{e(o)}catch{}}const TE={kty:"EC",crv:"P-256",x:"A34nyKMjhQYVgzeE4tyLUYdx34TAKogDa7v7PRaO9Lg",y:"JZI9IQavGCpGjEG_-pa0J-MHQYWJYINUM-MnvSu0TmE"};function _x(o){const e=o.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),i=atob(t),n=new Uint8Array(i.length);for(let s=0;s<i.length;s++)n[s]=i.charCodeAt(s);return n}async function EE(o){if(!o)return null;try{const e=o.split(".");if(e.length!==3)return null;const[t,i,n]=e,s=await crypto.subtle.importKey("jwk",TE,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),r=new TextEncoder().encode(`${t}.${i}`),a=_x(n);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,a.buffer,r))return Se&&console.warn("JWT: signature verification failed"),null;const l=new TextDecoder().decode(_x(i)),c=JSON.parse(l);if(typeof c.type!="string"||c.type.length===0)return Se&&console.warn("JWT: missing or invalid 'type' claim"),null;if(typeof c.exp=="number"){const h=Math.floor(Date.now()/1e3);if(h>c.exp)return Se&&console.warn("JWT: token has expired (exp="+c.exp+", now="+h+")"),null}if(c.aud){const h=typeof window<"u"?window.location.hostname:void 0;if(h){const d=Array.isArray(c.aud)?c.aud:[c.aud];if(!d.some(u=>h===u||h.endsWith("."+u)))return Se&&console.warn("JWT: domain '"+h+"' not in allowed audience: "+d.join(", ")),null}}return Se&&console.log("JWT: verified license type: "+c.type),c.type}catch(e){return Se&&console.error("JWT: verification error",e),null}}let py;async function AE(){let o=ch;if(ch="",!o&&typeof document<"u"){const t=document.querySelector('meta[name="needle-license"]')?.getAttribute("content");if(t)try{const i=new URL(t,document.baseURI),n=await fetch(i,{cache:"no-store"});if(n.ok){const s=await n.json();typeof s?.jwt=="string"&&(o=s.jwt)}}catch(i){Se&&console.warn("Could not load signed license file",i)}}const e=await EE(o);e?(Hi=e,Se&&console.log("License type set from verified JWT: "+e),dh(cn())):(Hi="basic",Se&&o&&console.warn("JWT verification failed \u2014 license reset to basic"))}var ct;(o=>{typeof window<"u"&&(window.addEventListener("error",f=>{c(Q.Current,"unhandled_error",f)}),window.addEventListener("unhandledrejection",f=>{t(f)}));function e(f,_){if(f==="AbortError")return!0;const w=(_||"").toLowerCase();return w.includes("load failed")||w.includes("failed to fetch")||w.includes("networkerror")||w.includes("network connection was lost")||w.includes("the operation was aborted")||w.includes("load cancelled")}function t(f){const _=f?.reason,w=typeof _?.name=="string"?_.name:void 0,S=typeof _?.message=="string"?_.message:typeof _=="string"?_:void 0,O=Q.Current,L=typeof document<"u"?document.visibilityState:void 0,D=typeof navigator<"u"?navigator.onLine:void 0;if(e(w,S)){l(O,"network_rejection",{message:S,name:w,visibility:L,online:D});return}c(O,"unhandled_promise_rejection",{name:w,message:S,stack:_?.stack,url:typeof _?.url=="string"?_.url:void 0,visibility:L,online:D,version:ci,timestamp:Date.now()})}function i(){ay||cy(f=>n(f),{once:!0})}o.init=i;function n(f){if(!s(f)){Se&&console.debug("Telemetry is disabled via no-telemetry attribute");return}return b({site_id:"dabb8317376f",type:"pageview",pathname:window.location.pathname,hostname:window.location.hostname,page_title:document.title,referrer:document.referrer,user_agent:navigator.userAgent,querystring:window.location.search,language:navigator.language,screenWidth:window.screen.width,screenHeight:window.screen.height,event_name:"page_view"}).then(_=>{if(_ instanceof Response&&_.ok&&Ni()){const w=(f.domElement?.getAttribute("src")||"")+ci+pl+lh+Ns;window.sessionStorage.getItem("session_key")!==w&&(window.sessionStorage.setItem("session_key",w),l(f,"info",{src:f.domElement?.getAttribute("src")||"",version:ci,generator:pl,build_time:lh,public_key:Ns}))}})}function s(f){let _=f?.domElement;if(_||(_=document.querySelector("needle-engine")),!_&&!f)return!1;const w=_?.getAttribute("no-telemetry");return mo()&&(w===""||w==="true"||w==="1")?(Se&&console.debug("Telemetry is disabled via no-telemetry attribute"),!1):r()?(Se&&console.debug("Telemetry is disabled via Do Not Track / Global Privacy Control"),!1):typeof window<"u"&&window.crossOriginIsolated?(Se&&console.debug("Telemetry is disabled on cross-origin-isolated pages"),!1):!0}o.isAllowed=s;function r(){if(typeof navigator>"u")return!1;const f=navigator;if(f.globalPrivacyControl===!0)return!0;const _=f.doNotTrack??f.msDoNotTrack??(typeof window<"u"?window.doNotTrack:null);return _==="1"||_==="yes"}const a="dabb8317376f";async function l(f,_,w){if(!s(f)){Se&&console.debug("Telemetry is disabled");return}const S={site_id:a,type:"custom_event",pathname:window.location.pathname,event_name:_,properties:w?JSON.stringify(w):void 0};return b(S)}o.sendEvent=l;async function c(f,_,w){if(!s(f)){Se&&console.debug("Telemetry is disabled");return}w instanceof ErrorEvent?w={message:w.message,stack:w.error?.stack,filename:w.filename,lineno:w.lineno,colno:w.colno,timestamp:w.timeStamp||Date.now()}:w instanceof Error&&(w={message:w.message,stack:w.stack,timestamp:Date.now()});const S={site_id:a,type:"error",event_name:_||"error",properties:JSON.stringify({error_name:_,message:w.message,stack:w.stack,filename:w.filename,lineno:w.lineno,colno:w.colno,timestamp:w.timestamp,name:w.name,visibility:w.visibility,online:w.online,url:w.url,version:w.version})};return b(S)}o.sendError=c;function h(f,_){if(!s(f))return;const w={action:"load",success:_.success,files:_.files,is_reload:_.is_reload,load_ms:Math.round(_.load_ms)};_.error&&(w.error=_.error),_.first_frame_ms!==void 0&&(w.first_frame_ms=Math.round(_.first_frame_ms)),_.since_navigation_ms!==void 0&&(w.since_navigation_ms=Math.round(_.since_navigation_ms)),_.success&&d(f,w),l(f,"engine",w)}o.reportLoad=h;function d(f,_){const w=f?.renderer;if(w)try{if(w.isWebGPURenderer===!0)_.api="webgpu";else{const S=w.getContext();if(S){const O=typeof WebGL2RenderingContext<"u"&&S instanceof WebGL2RenderingContext;_.api=O?"webgl2":"webgl",_.max_texture_size=S.getParameter(S.MAX_TEXTURE_SIZE),O&&(_.max_samples=S.getParameter(S.MAX_SAMPLES));const L=[];S.getExtension("WEBGL_compressed_texture_astc")&&L.push("astc"),S.getExtension("WEBGL_compressed_texture_etc")&&L.push("etc"),S.getExtension("WEBGL_compressed_texture_s3tc")&&L.push("s3tc"),S.getExtension("WEBGL_compressed_texture_pvrtc")&&L.push("pvrtc"),L.length&&(_.compression=L.join(","))}}if(_.dpr=w.getPixelRatio(),_.is_mobile=I.isMobileDevice(),typeof navigator<"u"){navigator.hardwareConcurrency&&(_.cores=navigator.hardwareConcurrency);const S=navigator.deviceMemory;typeof S=="number"&&(_.device_memory=S)}}catch(S){Se&&console.warn("Telemetry: capability probe failed",S)}}const u=new WeakSet;function m(f){const _=f?.renderer?.domElement;if(!_||u.has(_))return;u.add(_);let w=0;_.addEventListener("webglcontextlost",()=>{w=performance.now(),l(f,"engine",{action:"context_lost",since_navigation_ms:Math.round(performance.now()),during_xr:f?.isInXR===!0})}),_.addEventListener("webglcontextrestored",()=>{l(f,"engine",{action:"context_restored",downtime_ms:w?Math.round(performance.now()-w):void 0})})}o.attachContextLossMonitor=m;const g=new WeakSet;function y(f){if(!f||typeof document>"u"||g.has(f)||!s(f))return;g.add(f);let _=0,w=0,S=0,O=0,L=0;const D=()=>{const E=f.time.deltaTimeUnscaled;if(E<=0)return;_++,w+=E*1e3,E>S&&(S=E);const z=f.renderer?.info?.render;z&&(z.calls>O&&(O=z.calls),z.triangles>L&&(L=z.triangles))};f.post_render_callbacks.push(D);const W=()=>{_=0,w=0,S=0,O=0,L=0},$=()=>{_<=0||(l(f,"engine",{action:"performance",frames:_,duration_ms:Math.round(w),avg_fps:Math.round(1e3*_/w),min_fps:S>0?Math.round(1/S):0,avg_frame_ms:Math.round(w/_*10)/10,max_frame_ms:Math.round(S*1e3*10)/10,peak_draw_calls:O,peak_triangles:L}),W())},H=()=>{document.visibilityState==="hidden"&&$()};document.addEventListener("visibilitychange",H),window.addEventListener("pagehide",$);const G=ce.registerCallback(de.ContextDestroyed,E=>{if(E.context!==f)return;$(),document.removeEventListener("visibilitychange",H),window.removeEventListener("pagehide",$);const z=f.post_render_callbacks.indexOf(D);z>=0&&f.post_render_callbacks.splice(z,1),g.delete(f),G()})}o.attachPerformanceMonitor=y;function b(f){try{return fetch("https://needle.tools/api/v1/rum/t",{method:"POST",body:JSON.stringify(f),headers:{"Content-Type":"application/json"},keepalive:!0,mode:"cors",priority:"low"}).catch(_=>{Se&&console.error("Failed to send telemetry",_)})}catch(_){Se&&console.error(_)}return Promise.resolve()}})(ct||(ct={}));function IE(){Hi===""&&(Hi="basic"),py=AE(),ep=LE(),ct.init(),ce.registerCallback(de.ContextRegistered,o=>{jE(o.context),DE(o.context),Zu(o.context,()=>BE(o.context),2e3)}),ce.registerCallback(de.ContextCreated,o=>{ct.attachContextLossMonitor(o.context),ct.attachPerformanceMonitor(o.context)})}let ep,my=!1,gy="";async function LE(){if(ep)return ep;if(py&&await py,Hi==="basic")try{const o="https://needle.tools/api/v1/needle-engine/check?location="+encodeURIComponent(window.location.href)+"&version="+ci+"&generator="+encodeURIComponent(pl),e=await fetch(o,{method:"GET"}).catch(t=>{Se&&console.error("License check failed",t)});e?.status===200?(my=!1,Se&&console.log("License check succeeded"),Hi="pro",dh(!0)):e?.status===403?(dh(!1),my=!0,gy=await e.text()):(dh(!1),Se&&console.log("License check failed with status "+e?.status))}catch(o){dh(!1),Se&&console.error("License check failed",o)}else Se&&console.log('Runtime license check is skipped because license is already applied as "'+Hi+'"')}async function DE(o){function e(){const n=document.createElement("div");n.className="needle-forbidden",n.style.cssText=`
162
162
  position: fixed;
163
163
  top: 0;
164
164
  left: 0;
@@ -186,7 +186,7 @@ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for
186
186
  align-items: center;
187
187
  background-color: rgba(0,0,0,.3);
188
188
  text-shadow: 0 0 2px black;
189
- `;const a=r.style.cssText,l=gy?.length>1?gy:"This web application has been paused.<br/>You might be in violation of the Needle Engine terms of use.<br/>Please contact the Needle support if you think this is a mistake.";return r.innerHTML=l,dy(o,()=>{r.innerHTML!==l&&(r.innerHTML=l),r.parentNode!==n&&n.appendChild(r),n.style.cssText!==s&&(n.style.cssText=s),r.style.cssText!==a&&(r.style.cssText=a)},500),n}let t=e();const i=t.style.cssText;dy(o,()=>{my===!0&&(t.style.cssText!==i&&(t=e()),o.domElement.shadowRoot?t.parentNode!==o.domElement.shadowRoot&&o.domElement.shadowRoot?.appendChild(t):t.parentNode!=document.body&&document.body.appendChild(t))},500)}async function jE(o){try{if(!mo()&&!hh())return fy(o)}catch(e){return Oe&&console.log("License check failed",e),fy(o)}Oe&&fy(o)}async function fy(o){let e=!1;o.domElement.addEventListener("ready",()=>e=!0),await ep?.catch(()=>{}),!(mo()||hh())&&(cn()===!1&&FE(),e?yy(o):o.domElement.addEventListener("ready",()=>{yy(o)}))}function yy(o){const e=`
189
+ `;const a=r.style.cssText,l=gy?.length>1?gy:"This web application has been paused.<br/>You might be in violation of the Needle Engine terms of use.<br/>Please contact the Needle support if you think this is a mistake.";return r.innerHTML=l,dy(o,()=>{r.innerHTML!==l&&(r.innerHTML=l),r.parentNode!==n&&n.appendChild(r),n.style.cssText!==s&&(n.style.cssText=s),r.style.cssText!==a&&(r.style.cssText=a)},500),n}let t=e();const i=t.style.cssText;dy(o,()=>{my===!0&&(t.style.cssText!==i&&(t=e()),o.domElement.shadowRoot?t.parentNode!==o.domElement.shadowRoot&&o.domElement.shadowRoot?.appendChild(t):t.parentNode!=document.body&&document.body.appendChild(t))},500)}async function jE(o){try{if(!mo()&&!hh())return fy(o)}catch(e){return Se&&console.log("License check failed",e),fy(o)}Se&&fy(o)}async function fy(o){let e=!1;o.domElement.addEventListener("ready",()=>e=!0),await ep?.catch(()=>{}),!(mo()||hh())&&(cn()===!1&&FE(),e?yy(o):o.domElement.addEventListener("ready",()=>{yy(o)}))}function yy(o){const e=`
190
190
  position: relative;
191
191
  display: block;
192
192
  background-size: 20px;
@@ -229,7 +229,7 @@ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for
229
229
  padding-left: 25px;
230
230
  border-radius: .5em;
231
231
  border: 2px solid rgba(160,160,160,.3);
232
- `,i=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${ci}`;Q.Current?.xr||navigator.webdriver?console.log(i):console.log("%c "+i,t)}async function BE(o){if(!ct.isAllowed(o)){Oe&&console.debug("Telemetry is disabled");return}try{const e="https://needle.tools/api/v1/needle-engine/ping";if(e){const t=window.location.href.split("?")[0],i={license:Hi,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:ci,generator:pl,build_time:lh,public_key:Ns},n=navigator.sendBeacon?.(e,JSON.stringify(i));Oe&&console.debug("Sent beacon: "+n)}}catch(e){Oe&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}function xx(o){function e(b,f){const _=(b&65535)+(f&65535);return(b>>16)+(f>>16)+(_>>16)<<16|_&65535}function t(b,f){return b<<f|b>>>32-f}function i(b,f,_,w,S,O){return e(t(e(e(f,b),e(w,O)),S),_)}function n(b,f,_,w,S,O,L){return i(f&_|~f&w,b,f,S,O,L)}function s(b,f,_,w,S,O,L){return i(f&w|_&~w,b,f,S,O,L)}function r(b,f,_,w,S,O,L){return i(f^_^w,b,f,S,O,L)}function a(b,f,_,w,S,O,L){return i(_^(f|~w),b,f,S,O,L)}const l=o.length,c=new Uint8Array(Math.ceil((l+9)/64)*64);c.set(o),c[l]=128;const h=new DataView(c.buffer);h.setUint32(c.length-8,l<<3,!0),h.setUint32(c.length-4,l/536870912|0,!0);let d=1732584193,u=4023233417,m=2562383102,g=271733878;for(let b=0;b<c.length>>2;b+=16){const f=L=>h.getInt32((b+L)*4,!0),[_,w,S,O]=[d,u,m,g];d=n(d,u,m,g,f(0),7,-680876936),g=n(g,d,u,m,f(1),12,-389564586),m=n(m,g,d,u,f(2),17,606105819),u=n(u,m,g,d,f(3),22,-1044525330),d=n(d,u,m,g,f(4),7,-176418897),g=n(g,d,u,m,f(5),12,1200080426),m=n(m,g,d,u,f(6),17,-1473231341),u=n(u,m,g,d,f(7),22,-45705983),d=n(d,u,m,g,f(8),7,1770035416),g=n(g,d,u,m,f(9),12,-1958414417),m=n(m,g,d,u,f(10),17,-42063),u=n(u,m,g,d,f(11),22,-1990404162),d=n(d,u,m,g,f(12),7,1804603682),g=n(g,d,u,m,f(13),12,-40341101),m=n(m,g,d,u,f(14),17,-1502002290),u=n(u,m,g,d,f(15),22,1236535329),d=s(d,u,m,g,f(1),5,-165796510),g=s(g,d,u,m,f(6),9,-1069501632),m=s(m,g,d,u,f(11),14,643717713),u=s(u,m,g,d,f(0),20,-373897302),d=s(d,u,m,g,f(5),5,-701558691),g=s(g,d,u,m,f(10),9,38016083),m=s(m,g,d,u,f(15),14,-660478335),u=s(u,m,g,d,f(4),20,-405537848),d=s(d,u,m,g,f(9),5,568446438),g=s(g,d,u,m,f(14),9,-1019803690),m=s(m,g,d,u,f(3),14,-187363961),u=s(u,m,g,d,f(8),20,1163531501),d=s(d,u,m,g,f(13),5,-1444681467),g=s(g,d,u,m,f(2),9,-51403784),m=s(m,g,d,u,f(7),14,1735328473),u=s(u,m,g,d,f(12),20,-1926607734),d=r(d,u,m,g,f(5),4,-378558),g=r(g,d,u,m,f(8),11,-2022574463),m=r(m,g,d,u,f(11),16,1839030562),u=r(u,m,g,d,f(14),23,-35309556),d=r(d,u,m,g,f(1),4,-1530992060),g=r(g,d,u,m,f(4),11,1272893353),m=r(m,g,d,u,f(7),16,-155497632),u=r(u,m,g,d,f(10),23,-1094730640),d=r(d,u,m,g,f(13),4,681279174),g=r(g,d,u,m,f(0),11,-358537222),m=r(m,g,d,u,f(3),16,-722521979),u=r(u,m,g,d,f(6),23,76029189),d=r(d,u,m,g,f(9),4,-640364487),g=r(g,d,u,m,f(12),11,-421815835),m=r(m,g,d,u,f(15),16,530742520),u=r(u,m,g,d,f(2),23,-995338651),d=a(d,u,m,g,f(0),6,-198630844),g=a(g,d,u,m,f(7),10,1126891415),m=a(m,g,d,u,f(14),15,-1416354905),u=a(u,m,g,d,f(5),21,-57434055),d=a(d,u,m,g,f(12),6,1700485571),g=a(g,d,u,m,f(3),10,-1894986606),m=a(m,g,d,u,f(10),15,-1051523),u=a(u,m,g,d,f(1),21,-2054922799),d=a(d,u,m,g,f(8),6,1873313359),g=a(g,d,u,m,f(15),10,-30611744),m=a(m,g,d,u,f(6),15,-1560198380),u=a(u,m,g,d,f(13),21,1309151649),d=a(d,u,m,g,f(4),6,-145523070),g=a(g,d,u,m,f(11),10,-1120210379),m=a(m,g,d,u,f(2),15,718787259),u=a(u,m,g,d,f(9),21,-343485551),d=e(d,_),u=e(u,w),m=e(m,S),g=e(g,O)}const y=new DataView(new ArrayBuffer(16));return y.setUint32(0,d,!0),y.setUint32(4,u,!0),y.setUint32(8,m,!0),y.setUint32(12,g,!0),Array.from(new Uint8Array(y.buffer))}function UE(o){return xx(o).map(e=>e.toString(16).padStart(2,"0")).join("")}function zE(o){return xx(o)}function NE(o){return crypto.subtle.digest("SHA-256",new Uint8Array(o)).then(e=>btoa(String.fromCharCode(...new Uint8Array(e))))}var Hr;(o=>{o.baseUrl="https://networking.needle.tools";function e(l){return UE(new Uint8Array(l))}o.hashMD5=e;function t(l){const c=zE(new Uint8Array(l));return btoa(String.fromCharCode(...c))}o.hashMD5_Base64=t;function i(l){return NE(l)}o.hashSha256=i;function n(l){const c=l.filesize/1024/1024;return cn()?c<50:c<5}o.canUpload=n;async function s(l,c){const h=o.baseUrl;if(h){if(!l.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let d=null;l instanceof File?d=await l.arrayBuffer():d=l.data;const u=d.byteLength,m=u/1024/1024;if(m>50)return c?.silent!==!0&&ge(`File (${m.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${m.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!cn()&&m>5)return c?.silent!==!0&&ge('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${m.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(u<1)return console.warn(`Your file is too small for uploading (${m.toFixed(1)}MB). Min size is 1 byte`),null;const g=t(d),y={filename:l.name,"Content-Md5":g,"Content-Type":l.type||"application/octet-stream",FileSize:u.toString(),"Content-Disposition":`attachment; filename="${l.name}"`,"x-amz-server-side-encryption":"AES256"},b=await fetch(h+"/api/needle/blob",{method:"POST",headers:y,signal:c?.abort}).then(f=>f.json()).catch(f=>(console.error(f),null));if(b==null)return console.warn("Upload failed..."),null;if("error"in b)return console.error(b.error),null;if("upload"in b&&b.upload){let f=function(S){return c?.onProgress?.call(null,{progress01:0,state:"inprogress"}),fetch(S,{method:"PUT",headers:y,body:d,signal:c?.abort}).then(O=>(c?.onProgress?.call(null,{progress01:1,state:"finished"}),O)).catch(O=>O)};console.debug("Uploading file",b.upload);let _=!1,w=null;for(let S=0;S<3;S++)try{if(_)break;if(c?.abort?.aborted)return console.debug("Aborted upload"),null;const O=await f(b.upload);O instanceof Error?(w=O,await es(1e3*S)):O.ok&&(console.debug("File uploaded successfully"),_=!0)}catch(O){console.error(O)}if(!_)return console.error(w?.message||"Failed to upload file"),null}if("download"in b){const f=h+b.download;return console.debug("File found in blob storage",f),{key:b.key,success:!0,download_url:f}}return null}o.upload=s;function r(l){return`${o.baseUrl}/api/needle/blob/${l}`}o.getBlobUrlForKey=r;async function a(l,c){const h=new Mv;h.setResponseType("arraybuffer");const d=await h.loadAsync(l,u=>{c&&c.call(null,u)});return d instanceof ArrayBuffer?new Uint8Array(d):(console.error("Download failed, no arraybuffer returned"),null)}o.download=a})(Hr||(Hr={}));var Bn=(o=>(o[o.OnConnection=0]="OnConnection",o[o.OnRoomJoin=1]="OnRoomJoin",o[o.Queued=2]="Queued",o[o.Immediate=3]="Immediate",o))(Bn||{});const uh={},fl={register(o,e){uh[o]=e},unregister(o){delete uh[o]},list(){return Object.keys(uh)},has(o){return o in uh},async resolve(o){const e=uh[o];return e?e(o):null}};ce.registerCallback(de.ContextCreated,o=>{const e=o.context;Rx(e),Px(e)});const tp=x("debugcomponents"),Sx="eff8ba80-635d-11ec-90d6-0242ac120003";class _t{get seed(){return this._seed}set seed(e){this._seed=e}_originalSeed;_seed;constructor(e){typeof e=="string"&&(e=_t.hash(e)),this._originalSeed=e,this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return Cf(e,Sx);const t=this._seed;return this._seed-=1,Cf(t.toString(),Sx)}initialize(e){typeof e=="string"?this._seed=_t.hash(e):this._seed=e}static createFromString(e){return new _t(this.hash(e))}static hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}var Cx=(o=>(o.NewInstanceCreated="new-instance-created",o.InstanceDestroyed="instance-destroyed",o))(Cx||{});class $E{guid;dontSave;constructor(e){this.guid=e}}function ph(o,e,t=!0,i){if(!o)return;const n=o;if(ki(o,t),!e){console.warn("Can not send destroy: No networking connection provided",o.guid);return}if(!e.isConnected){M()&&console.debug("Can not send destroy: not connected",o.guid);return}let s=o.guid;if(!s&&n.uuid&&(s=n.uuid),!s){console.warn("Can not send destroy: failed to find guid",o);return}by(s,e,i)}function by(o,e,t){const i=new $E(o);t?.saveInRoom===!1&&(i.dontSave=!0),e.send("instance-destroyed",i,Bn.Queued)}const ip=[];function WE(o){return ip.push(o),()=>{const e=ip.indexOf(o);e>=0&&ip.splice(e,1)}}function Px(o){o.connection.beginListen("instance-destroyed",e=>{tp&&console.log("[Remote] Destroyed",o.scene,e);const t=yb(e.guid,o.scene);if(t){for(const i of ip)try{i(e.guid,t)}catch(n){console.error("Error in onSyncDestroy callback",n)}ki(t)}})}class VE{filename;hash;size;constructor(e,t,i){this.filename=e,this.hash=t,this.size=i}}class kx{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;preventCreation=void 0;deleteStateOnDisconnect;constructor(e,t){this.originalGuid=e,this.guid=t}}const np=[];function Ox(o){return np.push(o),()=>{const e=np.indexOf(o);e>=0&&np.splice(e,1)}}function _y(o,e,t,i){const n=o;if(!n.guid)if(n.name)n.guid=n.name;else return console.error("[syncInstantiate] Can not instantiate: a 'guid' is required. For runtime-created objects, either set a name (`obj.name = 'my-prefab'`) or a guid (`obj.guid = 'my-prefab-id'`). The identifier must be the same on all clients.",n),null;if(fl.has(n.guid)||fl.register(n.guid,async()=>n),e.context||(e.context=Q.Current),!e.context)return console.error("[syncInstantiate] Missing network instantiate options / reference to network connection in sync instantiate. Please pass in the Needle Engine context."),null;const s=e?{...e}:null,{instance:r,seed:a}=GE(n,e);if(r){const l=r;if(l.guid){tp&&console.log("[Local] new instance","gameobject:",r?.guid);const c=new kx(n.guid,l.guid);c.seed=a,e.deleteOnDisconnect===!0&&(c.deleteStateOnDisconnect=!0),s&&(s.position&&(Array.isArray(s.position)?c.position={x:s.position[0],y:s.position[1],z:s.position[2]}:c.position={x:s.position.x,y:s.position.y,z:s.position.z}),s.rotation&&(s.rotation instanceof je?s.rotation=new B().setFromEuler(s.rotation):s.rotation instanceof Array&&(s.rotation=new B().fromArray(s.rotation)),c.rotation={x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w}),s.scale&&(Array.isArray(s.scale)?c.scale={x:s.scale[0],y:s.scale[1],z:s.scale[2]}:c.scale={x:s.scale.x,y:s.scale.y,z:s.scale.z})),c.position||(c.position={x:l.position.x,y:l.position.y,z:l.position.z}),c.rotation||(c.rotation={x:l.quaternion.x,y:l.quaternion.y,z:l.quaternion.z,w:l.quaternion.w}),c.scale||(c.scale={x:l.scale.x,y:l.scale.y,z:l.scale.z}),c.visible=n.visible,s?.parent&&(typeof s.parent=="string"?c.parent=s.parent:s.parent?.guid?c.parent=s.parent.guid:s.parent instanceof Fi?c.parent="scene":console.warn("Unsupported parent type in sync instantiate options: "+s.parent?.name)),c.hostData=t,i===!1&&(c.dontSave=!0),!e?.context?.connection&&M()&&console.debug("Object will be instantiated but it will not be synced: not connected",n.guid),e.context.connection.isInRoom&&yl.push(new WeakRef(l)),e?.context?.connection.send("new-instance-created",c)}else console.warn("Missing guid, can not send new instance event",l)}return r}function Mx(){return Math.random()*9999999}const yl=new Array;function Rx(o){const e=o.connection.beginListen("new-instance-created",async i=>{const n=await qE(i.originalGuid,o.scene);if(i.preventCreation===!0)return;if(!n){console.warn("could not find object that was instantiated: "+i.guid);return}const s=new $o;i.position&&(s.position=new v(i.position.x,i.position.y,i.position.z)),i.rotation&&(s.rotation=new B(i.rotation.x,i.rotation.y,i.rotation.z,i.rotation.w)),i.scale&&(s.scale=new v(i.scale.x,i.scale.y,i.scale.z)),s.parent=i.parent,i.seed&&(s.idProvider=new _t(i.seed)),s.visible=i.visible,s.context=o,tp&&o.alias&&console.log("[Remote] instantiate in: "+o.alias);const r=Ks(n,s);if(yl.push(new WeakRef(r)),r){i.parent==="scene"&&o.scene.add(r),tp&&console.log("[Remote] new instance","gameobject:",r?.guid,n);for(const a of np)try{a(r,i,o)}catch(l){console.error("Error in onSyncInstantiate callback",l)}}}),t=o.connection.beginListen("left-room",()=>{yl.length>0&&console.debug(`Left networking room, cleaning up ${yl.length} instantiated objects`);for(const i of yl){const n=i.deref();n&&n.destroy()}yl.length=0});return()=>{e(),t()}}function GE(o,e){const t=Mx(),i=e??new $o;i.idProvider=new _t(t);const n=Ks(o,i);return{seed:t,instance:n}}function Tx(o,e){fl.register(o,e)}function HE(o){fl.unregister(o)}async function qE(o,e){return await fl.resolve(o)||Ex(o,e)}function Ex(o,e){if(e===null||!o)return null;if(e.guid===o)return e;if(e.children)for(const t of e.children){const i=Ex(o,t);if(i)return i}return null}const mh=x("gizmos"),Rt=x("debugextension"),vy=x("debugresolvedependencies"),XE=["/extensions/","extensions/"],QE=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function wy(o,e){vy&&console.log(o,e);const t=[];xy(QE,o,e,t);const i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Ax(o,e){return!o||!e?!1:o["needle:identifier"]!=null&&e["needle:identifier"]!=null?o["needle:identifier"]===e["needle:identifier"]:!1}function YE(o,e){o["needle:identifier"]=e}function xy(o,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(const n of Object.keys(t)){const s=t[n];if(typeof s=="string"){const r=Ix(e,s);if(r!=null)typeof r.then=="function"?i.push(r.then(a=>t[n]=a)):t[n]=r;else{const a=Lx(o,e,s);if(a){i.push(a.then(l=>(t[n]=l,l)));continue}}}else if(Array.isArray(s))for(let r=0;r<s.length;r++){const a=s[r],l=Ix(e,a);if(l!=null){typeof l.then=="function"?i.push(l.then(c=>s[r]=c)):s[r]=l;continue}for(const c of o){const h=Dx(c.prefix,a);if(h>=0){vy&&console.log(c,h,c.dependencyName),i.push(e.getDependency(c.dependencyName,h).then(d=>s[r]=d));break}}typeof a=="object"&&xy(o,e,a,i)}else typeof s=="object"&&xy(o,e,s,i)}else if(typeof t=="string"){const n=Lx(o,e,t);n&&i.push(n)}}function Ix(o,e){if(o&&o.plugins&&typeof e=="string"){for(const t of XE)if(e.startsWith(t)){let i=e.substring(t.length);const n=i.indexOf("/");n>=0&&(i=i.substring(0,n));const s=o.plugins[i];if(Rt&&console.log(i,s),typeof s?.resolve=="function"){const r=e.substring(t.length+i.length+1);return s.resolve(o,r)}break}}return null}function Lx(o,e,t){for(const i of o){const n=Dx(i.prefix,t);if(n>=0)return vy&&console.warn("GET DEPENDENCY",i,n,i.dependencyName),e.getDependency(i.dependencyName,n)}return null}function Dx(o,e){if(typeof e=="string"&&e.startsWith(o)){const t=e.substring(o.length),i=Number.parseInt(t);if(i>=0)return i}return-1}const Sy="NEEDLE_persistent_assets";function KE(o){return o?.___persistentAsset===!0}class ZE{get name(){return Sy}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;const t=this.parser.json.extensions[Sy];if(!t)return;Rt&&console.log(t);const i=new Array;for(const n of t?.assets){const s=wy(this.parser,n);s&&i.push(s)}await Promise.all(i)}resolve(e,t){const i=Number.parseInt(t);if(i>=0){Rt&&console.log(t);const n=e.json.extensions[Sy];if(n){const s=n?.assets[i];if(s&&typeof s=="object"){s.___persistentAsset=!0;const r=s.__type;r&&k.get(r)}return s}}return null}}const go=x("debugserializer");class JE{register(e,t){if(this.typeMap.has(e)){const i=this.typeMap.get(e);if(i===t)return;go&&console.warn("Type: "+e+" is already registered",t,i)}go&&console.log("Register type serializer",t.name,t,e),this.typeMap.set(e,t)}typeMap=new Map;getSerializer(e){if(e)return this.typeMap.get(e)}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){go&&console.log("invalid type");return}const i=e.name,n=this.getSerializer(e);if(n!==void 0)return go&&console.log("FOUND SERIALIZER",n?.name,e.name,e.constructor.name,"for type: "+i,n,e,this.typeMap),n;const s=Object.getPrototypeOf(e);if(s&&s!==e){const r=this.getSerializerForConstructor(s,++t);if(r){const a=s.constructor||s.prototype;go&&console.log("FOUND SERIALIZER(in constructor) "+a.constructor.name,a.name,a,r),this.register(a,r)}if(r)return r}if(t===0&&typeof i=="string"&&i.length>0){for(const[r,a]of this.typeMap)if(r.name===i)return this.register(e,a),a}go&&console.warn("No serializer found for "+i,e,e.name,e.constructor.name)}}const op=new JE;class qi{name;constructor(e,t){if(this.name=t,Array.isArray(e))for(const i of e)op.register(i,this);else op.register(e,this)}}class jx{isDevMode=Ni();cache={};registerDefinedKeys(e,t){if(this.isDevMode&&this.cache[e]===void 0){this.cache[e]=Object.keys(t);const i=t;i.$serializedTypes&&Object.keys(i.$serializedTypes)&&this.cache[e].push(...Object.keys(i.$serializedTypes)),go&&console.log("registerDefinedKeys for "+e,this.cache[e],t)}}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}}class gh{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;type;serializable;implementationInformation;objectToDocumentReference;constructor(e){this.root=e}}function eA(o){return o&&typeof o=="object"&&(typeof o.$serializedTypes=="object"||typeof o.onBeforeDeserialize=="function"||typeof o.onBeforeDeserializeMember=="function"||typeof o.onAfterDeserializeMember=="function"||typeof o.onAfterDeserialize=="function")}function Fx(o,e){const t=o.$serializedTypes;if(t===void 0)return null;const i={};for(const s in t){const r=o[s];if(r!=null&&typeof r=="object"){const a=op.getSerializerForConstructor(r.constructor);if(a){i[s]=a.onSerialize(r,e);continue}}if(typeof r=="number"&&!Number.isFinite(r)){i[s]=String(r);continue}i[s]=r}function n(s){return k.getKey(o.constructor)||s.__name||s.constructor.name}return i.name=n(o),typeof o.guid=="string"&&(i.guid=o.guid),o.enabled===!1&&(i.enabled=!1),i}const sp=[];function Bx(o,e){if(!o)return e;typeof o.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,o.$serializedTypes));const t=Object.getPrototypeOf(o);return Bx(t,e)}function fh(o,e,t){if(!o)return!1;if(t.target=o,o.onBeforeDeserialize!==void 0){const n=o.onBeforeDeserialize(e,t);if(typeof n=="boolean")return n}const i=Bx(o);if(e){if(typeof e.guid=="string"&&(o.guid=e.guid),i)for(const n in i){let s=function(l){const c=l.type;return c?Cy(a,c,t,void 0,o[n]):Cy(a,l,t,void 0,o[n])};const r=i[n],a=e[n];if(go&&console.log(n,a,o,r),!(o[n]!==void 0&&a===void 0)){{const l=zx(a,o[n]);if(l!==a){o[n]=l;continue}}if(t.type=void 0,t.path=n,t.serializable=r,!(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(n,a,t)===!0)){if(r===null)o[n]=a;else{if(Array.isArray(r))for(let l=0;l<r.length;l++){const c=r[l],h=s(c);if(h!==void 0||l===r.length-1){o[n]=h;break}}else o[n]=s(r);sp.length=0}o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(n,a,t)}}}nA(o,e)}return iA(o,e,t.implementationInformation),o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(e,t),!0}const tA=x("noerrors");function iA(o,e,t){if(tA||!e||!Ni()||!o||o.constructor&&o.constructor[gE]===!0)return;const i=o.constructor?.name,n=Object.getOwnPropertyNames(e);for(const s of n){if(s==="sourceId")continue;const r=o[s];if(r==null)continue;const a=e[s];if(t?.getDefinedKey(i,s)===!1){const l=s.charAt(0).toUpperCase()+s.slice(1);t.getDefinedKey(i,l)&&(Ur(Wi.Warn,'<strong>Please rename</strong> "'+l+'" to "'+s+'" in '+i),console.warn('Please use lowercase for field: "'+l+'" in '+i,a,o));continue}if(a!=null){if(typeof a=="object"&&(r===void 0||!r.isObject3D)){if(typeof a.node=="number"||typeof a.guid=="string"){if(a.could_not_resolve)continue;if(!(r!==void 0&&Object.keys(r).length>1)){Ur(Wi.Warn,`<strong>Missing serialization for object reference!</strong>
232
+ `,i=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${ci}`;Q.Current?.xr||navigator.webdriver?console.log(i):console.log("%c "+i,t)}async function BE(o){if(!ct.isAllowed(o)){Se&&console.debug("Telemetry is disabled");return}try{const e="https://needle.tools/api/v1/needle-engine/ping";if(e){const t=window.location.href.split("?")[0],i={license:Hi,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:ci,generator:pl,build_time:lh,public_key:Ns},n=navigator.sendBeacon?.(e,JSON.stringify(i));Se&&console.debug("Sent beacon: "+n)}}catch(e){Se&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}function xx(o){function e(b,f){const _=(b&65535)+(f&65535);return(b>>16)+(f>>16)+(_>>16)<<16|_&65535}function t(b,f){return b<<f|b>>>32-f}function i(b,f,_,w,S,O){return e(t(e(e(f,b),e(w,O)),S),_)}function n(b,f,_,w,S,O,L){return i(f&_|~f&w,b,f,S,O,L)}function s(b,f,_,w,S,O,L){return i(f&w|_&~w,b,f,S,O,L)}function r(b,f,_,w,S,O,L){return i(f^_^w,b,f,S,O,L)}function a(b,f,_,w,S,O,L){return i(_^(f|~w),b,f,S,O,L)}const l=o.length,c=new Uint8Array(Math.ceil((l+9)/64)*64);c.set(o),c[l]=128;const h=new DataView(c.buffer);h.setUint32(c.length-8,l<<3,!0),h.setUint32(c.length-4,l/536870912|0,!0);let d=1732584193,u=4023233417,m=2562383102,g=271733878;for(let b=0;b<c.length>>2;b+=16){const f=L=>h.getInt32((b+L)*4,!0),[_,w,S,O]=[d,u,m,g];d=n(d,u,m,g,f(0),7,-680876936),g=n(g,d,u,m,f(1),12,-389564586),m=n(m,g,d,u,f(2),17,606105819),u=n(u,m,g,d,f(3),22,-1044525330),d=n(d,u,m,g,f(4),7,-176418897),g=n(g,d,u,m,f(5),12,1200080426),m=n(m,g,d,u,f(6),17,-1473231341),u=n(u,m,g,d,f(7),22,-45705983),d=n(d,u,m,g,f(8),7,1770035416),g=n(g,d,u,m,f(9),12,-1958414417),m=n(m,g,d,u,f(10),17,-42063),u=n(u,m,g,d,f(11),22,-1990404162),d=n(d,u,m,g,f(12),7,1804603682),g=n(g,d,u,m,f(13),12,-40341101),m=n(m,g,d,u,f(14),17,-1502002290),u=n(u,m,g,d,f(15),22,1236535329),d=s(d,u,m,g,f(1),5,-165796510),g=s(g,d,u,m,f(6),9,-1069501632),m=s(m,g,d,u,f(11),14,643717713),u=s(u,m,g,d,f(0),20,-373897302),d=s(d,u,m,g,f(5),5,-701558691),g=s(g,d,u,m,f(10),9,38016083),m=s(m,g,d,u,f(15),14,-660478335),u=s(u,m,g,d,f(4),20,-405537848),d=s(d,u,m,g,f(9),5,568446438),g=s(g,d,u,m,f(14),9,-1019803690),m=s(m,g,d,u,f(3),14,-187363961),u=s(u,m,g,d,f(8),20,1163531501),d=s(d,u,m,g,f(13),5,-1444681467),g=s(g,d,u,m,f(2),9,-51403784),m=s(m,g,d,u,f(7),14,1735328473),u=s(u,m,g,d,f(12),20,-1926607734),d=r(d,u,m,g,f(5),4,-378558),g=r(g,d,u,m,f(8),11,-2022574463),m=r(m,g,d,u,f(11),16,1839030562),u=r(u,m,g,d,f(14),23,-35309556),d=r(d,u,m,g,f(1),4,-1530992060),g=r(g,d,u,m,f(4),11,1272893353),m=r(m,g,d,u,f(7),16,-155497632),u=r(u,m,g,d,f(10),23,-1094730640),d=r(d,u,m,g,f(13),4,681279174),g=r(g,d,u,m,f(0),11,-358537222),m=r(m,g,d,u,f(3),16,-722521979),u=r(u,m,g,d,f(6),23,76029189),d=r(d,u,m,g,f(9),4,-640364487),g=r(g,d,u,m,f(12),11,-421815835),m=r(m,g,d,u,f(15),16,530742520),u=r(u,m,g,d,f(2),23,-995338651),d=a(d,u,m,g,f(0),6,-198630844),g=a(g,d,u,m,f(7),10,1126891415),m=a(m,g,d,u,f(14),15,-1416354905),u=a(u,m,g,d,f(5),21,-57434055),d=a(d,u,m,g,f(12),6,1700485571),g=a(g,d,u,m,f(3),10,-1894986606),m=a(m,g,d,u,f(10),15,-1051523),u=a(u,m,g,d,f(1),21,-2054922799),d=a(d,u,m,g,f(8),6,1873313359),g=a(g,d,u,m,f(15),10,-30611744),m=a(m,g,d,u,f(6),15,-1560198380),u=a(u,m,g,d,f(13),21,1309151649),d=a(d,u,m,g,f(4),6,-145523070),g=a(g,d,u,m,f(11),10,-1120210379),m=a(m,g,d,u,f(2),15,718787259),u=a(u,m,g,d,f(9),21,-343485551),d=e(d,_),u=e(u,w),m=e(m,S),g=e(g,O)}const y=new DataView(new ArrayBuffer(16));return y.setUint32(0,d,!0),y.setUint32(4,u,!0),y.setUint32(8,m,!0),y.setUint32(12,g,!0),Array.from(new Uint8Array(y.buffer))}function UE(o){return xx(o).map(e=>e.toString(16).padStart(2,"0")).join("")}function zE(o){return xx(o)}function NE(o){return crypto.subtle.digest("SHA-256",new Uint8Array(o)).then(e=>btoa(String.fromCharCode(...new Uint8Array(e))))}var Hr;(o=>{o.baseUrl="https://networking.needle.tools";function e(l){return UE(new Uint8Array(l))}o.hashMD5=e;function t(l){const c=zE(new Uint8Array(l));return btoa(String.fromCharCode(...c))}o.hashMD5_Base64=t;function i(l){return NE(l)}o.hashSha256=i;function n(l){const c=l.filesize/1024/1024;return cn()?c<50:c<5}o.canUpload=n;async function s(l,c){const h=o.baseUrl;if(h){if(!l.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let d=null;l instanceof File?d=await l.arrayBuffer():d=l.data;const u=d.byteLength,m=u/1024/1024;if(m>50)return c?.silent!==!0&&ge(`File (${m.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${m.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!cn()&&m>5)return c?.silent!==!0&&ge('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${m.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(u<1)return console.warn(`Your file is too small for uploading (${m.toFixed(1)}MB). Min size is 1 byte`),null;const g=t(d),y={filename:l.name,"Content-Md5":g,"Content-Type":l.type||"application/octet-stream",FileSize:u.toString(),"Content-Disposition":`attachment; filename="${l.name}"`,"x-amz-server-side-encryption":"AES256"},b=await fetch(h+"/api/needle/blob",{method:"POST",headers:y,signal:c?.abort}).then(f=>f.json()).catch(f=>(console.error(f),null));if(b==null)return console.warn("Upload failed..."),null;if("error"in b)return console.error(b.error),null;if("upload"in b&&b.upload){let f=function(S){return c?.onProgress?.call(null,{progress01:0,state:"inprogress"}),fetch(S,{method:"PUT",headers:y,body:d,signal:c?.abort}).then(O=>(c?.onProgress?.call(null,{progress01:1,state:"finished"}),O)).catch(O=>O)};console.debug("Uploading file",b.upload);let _=!1,w=null;for(let S=0;S<3;S++)try{if(_)break;if(c?.abort?.aborted)return console.debug("Aborted upload"),null;const O=await f(b.upload);O instanceof Error?(w=O,await es(1e3*S)):O.ok&&(console.debug("File uploaded successfully"),_=!0)}catch(O){console.error(O)}if(!_)return console.error(w?.message||"Failed to upload file"),null}if("download"in b){const f=h+b.download;return console.debug("File found in blob storage",f),{key:b.key,success:!0,download_url:f}}return null}o.upload=s;function r(l){return`${o.baseUrl}/api/needle/blob/${l}`}o.getBlobUrlForKey=r;async function a(l,c){const h=new Mv;h.setResponseType("arraybuffer");const d=await h.loadAsync(l,u=>{c&&c.call(null,u)});return d instanceof ArrayBuffer?new Uint8Array(d):(console.error("Download failed, no arraybuffer returned"),null)}o.download=a})(Hr||(Hr={}));var Bn=(o=>(o[o.OnConnection=0]="OnConnection",o[o.OnRoomJoin=1]="OnRoomJoin",o[o.Queued=2]="Queued",o[o.Immediate=3]="Immediate",o))(Bn||{});const uh={},fl={register(o,e){uh[o]=e},unregister(o){delete uh[o]},list(){return Object.keys(uh)},has(o){return o in uh},async resolve(o){const e=uh[o];return e?e(o):null}};ce.registerCallback(de.ContextCreated,o=>{const e=o.context;Rx(e),Px(e)});const tp=x("debugcomponents"),Sx="eff8ba80-635d-11ec-90d6-0242ac120003";class _t{get seed(){return this._seed}set seed(e){this._seed=e}_originalSeed;_seed;constructor(e){typeof e=="string"&&(e=_t.hash(e)),this._originalSeed=e,this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return Cf(e,Sx);const t=this._seed;return this._seed-=1,Cf(t.toString(),Sx)}initialize(e){typeof e=="string"?this._seed=_t.hash(e):this._seed=e}static createFromString(e){return new _t(this.hash(e))}static hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}var Cx=(o=>(o.NewInstanceCreated="new-instance-created",o.InstanceDestroyed="instance-destroyed",o))(Cx||{});class $E{guid;dontSave;constructor(e){this.guid=e}}function ph(o,e,t=!0,i){if(!o)return;const n=o;if(ki(o,t),!e){console.warn("Can not send destroy: No networking connection provided",o.guid);return}if(!e.isConnected){M()&&console.debug("Can not send destroy: not connected",o.guid);return}let s=o.guid;if(!s&&n.uuid&&(s=n.uuid),!s){console.warn("Can not send destroy: failed to find guid",o);return}by(s,e,i)}function by(o,e,t){const i=new $E(o);t?.saveInRoom===!1&&(i.dontSave=!0),e.send("instance-destroyed",i,Bn.Queued)}const ip=[];function WE(o){return ip.push(o),()=>{const e=ip.indexOf(o);e>=0&&ip.splice(e,1)}}function Px(o){o.connection.beginListen("instance-destroyed",e=>{tp&&console.log("[Remote] Destroyed",o.scene,e);const t=yb(e.guid,o.scene);if(t){for(const i of ip)try{i(e.guid,t)}catch(n){console.error("Error in onSyncDestroy callback",n)}ki(t)}})}class VE{filename;hash;size;constructor(e,t,i){this.filename=e,this.hash=t,this.size=i}}class kx{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;preventCreation=void 0;deleteStateOnDisconnect;constructor(e,t){this.originalGuid=e,this.guid=t}}const np=[];function Ox(o){return np.push(o),()=>{const e=np.indexOf(o);e>=0&&np.splice(e,1)}}function _y(o,e,t,i){const n=o;if(!n.guid)if(n.name)n.guid=n.name;else return console.error("[syncInstantiate] Can not instantiate: a 'guid' is required. For runtime-created objects, either set a name (`obj.name = 'my-prefab'`) or a guid (`obj.guid = 'my-prefab-id'`). The identifier must be the same on all clients.",n),null;if(fl.has(n.guid)||fl.register(n.guid,async()=>n),e.context||(e.context=Q.Current),!e.context)return console.error("[syncInstantiate] Missing network instantiate options / reference to network connection in sync instantiate. Please pass in the Needle Engine context."),null;const s=e?{...e}:null,{instance:r,seed:a}=GE(n,e);if(r){const l=r;if(l.guid){tp&&console.log("[Local] new instance","gameobject:",r?.guid);const c=new kx(n.guid,l.guid);c.seed=a,e.deleteOnDisconnect===!0&&(c.deleteStateOnDisconnect=!0),s&&(s.position&&(Array.isArray(s.position)?c.position={x:s.position[0],y:s.position[1],z:s.position[2]}:c.position={x:s.position.x,y:s.position.y,z:s.position.z}),s.rotation&&(s.rotation instanceof je?s.rotation=new B().setFromEuler(s.rotation):s.rotation instanceof Array&&(s.rotation=new B().fromArray(s.rotation)),c.rotation={x:s.rotation.x,y:s.rotation.y,z:s.rotation.z,w:s.rotation.w}),s.scale&&(Array.isArray(s.scale)?c.scale={x:s.scale[0],y:s.scale[1],z:s.scale[2]}:c.scale={x:s.scale.x,y:s.scale.y,z:s.scale.z})),c.position||(c.position={x:l.position.x,y:l.position.y,z:l.position.z}),c.rotation||(c.rotation={x:l.quaternion.x,y:l.quaternion.y,z:l.quaternion.z,w:l.quaternion.w}),c.scale||(c.scale={x:l.scale.x,y:l.scale.y,z:l.scale.z}),c.visible=n.visible,s?.parent&&(typeof s.parent=="string"?c.parent=s.parent:s.parent?.guid?c.parent=s.parent.guid:s.parent instanceof Fi?c.parent="scene":console.warn("Unsupported parent type in sync instantiate options: "+s.parent?.name)),c.hostData=t,i===!1&&(c.dontSave=!0),!e?.context?.connection&&M()&&console.debug("Object will be instantiated but it will not be synced: not connected",n.guid),e.context.connection.isInRoom&&yl.push(new WeakRef(l)),e?.context?.connection.send("new-instance-created",c)}else console.warn("Missing guid, can not send new instance event",l)}return r}function Mx(){return Math.random()*9999999}const yl=new Array;function Rx(o){const e=o.connection.beginListen("new-instance-created",async i=>{const n=await qE(i.originalGuid,o.scene);if(i.preventCreation===!0)return;if(!n){console.warn("could not find object that was instantiated: "+i.guid);return}const s=new $o;i.position&&(s.position=new v(i.position.x,i.position.y,i.position.z)),i.rotation&&(s.rotation=new B(i.rotation.x,i.rotation.y,i.rotation.z,i.rotation.w)),i.scale&&(s.scale=new v(i.scale.x,i.scale.y,i.scale.z)),s.parent=i.parent,i.seed&&(s.idProvider=new _t(i.seed)),s.visible=i.visible,s.context=o,tp&&o.alias&&console.log("[Remote] instantiate in: "+o.alias);const r=Ks(n,s);if(yl.push(new WeakRef(r)),r){i.parent==="scene"&&o.scene.add(r),tp&&console.log("[Remote] new instance","gameobject:",r?.guid,n);for(const a of np)try{a(r,i,o)}catch(l){console.error("Error in onSyncInstantiate callback",l)}}}),t=o.connection.beginListen("left-room",()=>{yl.length>0&&console.debug(`Left networking room, cleaning up ${yl.length} instantiated objects`);for(const i of yl){const n=i.deref();n&&n.destroy()}yl.length=0});return()=>{e(),t()}}function GE(o,e){const t=Mx(),i=e??new $o;i.idProvider=new _t(t);const n=Ks(o,i);return{seed:t,instance:n}}function Tx(o,e){fl.register(o,e)}function HE(o){fl.unregister(o)}async function qE(o,e){return await fl.resolve(o)||Ex(o,e)}function Ex(o,e){if(e===null||!o)return null;if(e.guid===o)return e;if(e.children)for(const t of e.children){const i=Ex(o,t);if(i)return i}return null}const mh=x("gizmos"),Rt=x("debugextension"),vy=x("debugresolvedependencies"),XE=["/extensions/","extensions/"],QE=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function wy(o,e){vy&&console.log(o,e);const t=[];xy(QE,o,e,t);const i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Ax(o,e){return!o||!e?!1:o["needle:identifier"]!=null&&e["needle:identifier"]!=null?o["needle:identifier"]===e["needle:identifier"]:!1}function YE(o,e){o["needle:identifier"]=e}function xy(o,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(const n of Object.keys(t)){const s=t[n];if(typeof s=="string"){const r=Ix(e,s);if(r!=null)typeof r.then=="function"?i.push(r.then(a=>t[n]=a)):t[n]=r;else{const a=Lx(o,e,s);if(a){i.push(a.then(l=>(t[n]=l,l)));continue}}}else if(Array.isArray(s))for(let r=0;r<s.length;r++){const a=s[r],l=Ix(e,a);if(l!=null){typeof l.then=="function"?i.push(l.then(c=>s[r]=c)):s[r]=l;continue}for(const c of o){const h=Dx(c.prefix,a);if(h>=0){vy&&console.log(c,h,c.dependencyName),i.push(e.getDependency(c.dependencyName,h).then(d=>s[r]=d));break}}typeof a=="object"&&xy(o,e,a,i)}else typeof s=="object"&&xy(o,e,s,i)}else if(typeof t=="string"){const n=Lx(o,e,t);n&&i.push(n)}}function Ix(o,e){if(o&&o.plugins&&typeof e=="string"){for(const t of XE)if(e.startsWith(t)){let i=e.substring(t.length);const n=i.indexOf("/");n>=0&&(i=i.substring(0,n));const s=o.plugins[i];if(Rt&&console.log(i,s),typeof s?.resolve=="function"){const r=e.substring(t.length+i.length+1);return s.resolve(o,r)}break}}return null}function Lx(o,e,t){for(const i of o){const n=Dx(i.prefix,t);if(n>=0)return vy&&console.warn("GET DEPENDENCY",i,n,i.dependencyName),e.getDependency(i.dependencyName,n)}return null}function Dx(o,e){if(typeof e=="string"&&e.startsWith(o)){const t=e.substring(o.length),i=Number.parseInt(t);if(i>=0)return i}return-1}const Sy="NEEDLE_persistent_assets";function KE(o){return o?.___persistentAsset===!0}class ZE{get name(){return Sy}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;const t=this.parser.json.extensions[Sy];if(!t)return;Rt&&console.log(t);const i=new Array;for(const n of t?.assets){const s=wy(this.parser,n);s&&i.push(s)}await Promise.all(i)}resolve(e,t){const i=Number.parseInt(t);if(i>=0){Rt&&console.log(t);const n=e.json.extensions[Sy];if(n){const s=n?.assets[i];if(s&&typeof s=="object"){s.___persistentAsset=!0;const r=s.__type;r&&k.get(r)}return s}}return null}}const go=x("debugserializer");class JE{register(e,t){if(this.typeMap.has(e)){const i=this.typeMap.get(e);if(i===t)return;go&&console.warn("Type: "+e+" is already registered",t,i)}go&&console.log("Register type serializer",t.name,t,e),this.typeMap.set(e,t)}typeMap=new Map;getSerializer(e){if(e)return this.typeMap.get(e)}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){go&&console.log("invalid type");return}const i=e.name,n=this.getSerializer(e);if(n!==void 0)return go&&console.log("FOUND SERIALIZER",n?.name,e.name,e.constructor.name,"for type: "+i,n,e,this.typeMap),n;const s=Object.getPrototypeOf(e);if(s&&s!==e){const r=this.getSerializerForConstructor(s,++t);if(r){const a=s.constructor||s.prototype;go&&console.log("FOUND SERIALIZER(in constructor) "+a.constructor.name,a.name,a,r),this.register(a,r)}if(r)return r}if(t===0&&typeof i=="string"&&i.length>0){for(const[r,a]of this.typeMap)if(r.name===i)return this.register(e,a),a}go&&console.warn("No serializer found for "+i,e,e.name,e.constructor.name)}}const op=new JE;class qi{name;constructor(e,t){if(this.name=t,Array.isArray(e))for(const i of e)op.register(i,this);else op.register(e,this)}}class jx{isDevMode=Ni();cache={};registerDefinedKeys(e,t){if(this.isDevMode&&this.cache[e]===void 0){this.cache[e]=Object.keys(t);const i=t;i.$serializedTypes&&Object.keys(i.$serializedTypes)&&this.cache[e].push(...Object.keys(i.$serializedTypes)),go&&console.log("registerDefinedKeys for "+e,this.cache[e],t)}}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}}class gh{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;type;serializable;implementationInformation;objectToDocumentReference;constructor(e){this.root=e}}function eA(o){return o&&typeof o=="object"&&(typeof o.$serializedTypes=="object"||typeof o.onBeforeDeserialize=="function"||typeof o.onBeforeDeserializeMember=="function"||typeof o.onAfterDeserializeMember=="function"||typeof o.onAfterDeserialize=="function")}function Fx(o,e){const t=o.$serializedTypes;if(t===void 0)return null;const i={};for(const s in t){const r=o[s];if(r!=null&&typeof r=="object"){const a=op.getSerializerForConstructor(r.constructor);if(a){i[s]=a.onSerialize(r,e);continue}}if(typeof r=="number"&&!Number.isFinite(r)){i[s]=String(r);continue}i[s]=r}function n(s){return k.getKey(o.constructor)||s.__name||s.constructor.name}return i.name=n(o),typeof o.guid=="string"&&(i.guid=o.guid),o.enabled===!1&&(i.enabled=!1),i}const sp=[];function Bx(o,e){if(!o)return e;typeof o.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,o.$serializedTypes));const t=Object.getPrototypeOf(o);return Bx(t,e)}function fh(o,e,t){if(!o)return!1;if(t.target=o,o.onBeforeDeserialize!==void 0){const n=o.onBeforeDeserialize(e,t);if(typeof n=="boolean")return n}const i=Bx(o);if(e){if(typeof e.guid=="string"&&(o.guid=e.guid),i)for(const n in i){let s=function(l){const c=l.type;return c?Cy(a,c,t,void 0,o[n]):Cy(a,l,t,void 0,o[n])};const r=i[n],a=e[n];if(go&&console.log(n,a,o,r),!(o[n]!==void 0&&a===void 0)){{const l=zx(a,o[n]);if(l!==a){o[n]=l;continue}}if(t.type=void 0,t.path=n,t.serializable=r,!(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(n,a,t)===!0)){if(r===null)o[n]=a;else{if(Array.isArray(r))for(let l=0;l<r.length;l++){const c=r[l],h=s(c);if(h!==void 0||l===r.length-1){o[n]=h;break}}else o[n]=s(r);sp.length=0}o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(n,a,t)}}}nA(o,e)}return iA(o,e,t.implementationInformation),o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(e,t),!0}const tA=x("noerrors");function iA(o,e,t){if(tA||!e||!Ni()||!o||o.constructor&&o.constructor[gE]===!0)return;const i=o.constructor?.name,n=Object.getOwnPropertyNames(e);for(const s of n){if(s==="sourceId")continue;const r=o[s];if(r==null)continue;const a=e[s];if(t?.getDefinedKey(i,s)===!1){const l=s.charAt(0).toUpperCase()+s.slice(1);t.getDefinedKey(i,l)&&(Ur(Wi.Warn,'<strong>Please rename</strong> "'+l+'" to "'+s+'" in '+i),console.warn('Please use lowercase for field: "'+l+'" in '+i,a,o));continue}if(a!=null){if(typeof a=="object"&&(r===void 0||!r.isObject3D)){if(typeof a.node=="number"||typeof a.guid=="string"){if(a.could_not_resolve)continue;if(!(r!==void 0&&Object.keys(r).length>1)){Ur(Wi.Warn,`<strong>Missing serialization for object reference!</strong>
233
233
 
234
234
  Please change to:
235
235
  @serializable(Object3D)
@@ -244,7 +244,7 @@ Please change to:
244
244
  ${s}? : AssetReference;
245
245
 
246
246
  in script ${i}.ts
247
- <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(i,s,o[s],o);continue}}}}function nA(o,e){for(const t of Object.keys(e)){const i=e[t];if(typeof i=="object"&&i!==null&&i!==void 0){const n=o[t];if(!n){go&&console.log(t,"is undefined on",o);continue}for(const s of Object.keys(i))if(n[s]===void 0&&Ux(i[s])&&!Ux(n)){const r=oA(n,s);if(r&&(r?.writable===void 0||r?.writable===!1)&&r.set===void 0){go&&console.warn('Property is not writable "'+s+'"',n,r,i[s],n[s]);continue}n[s]=i[s]}}}}function oA(o,e){for(;o;){const t=Object.getOwnPropertyDescriptor(o,e);if(t)return t;o=Object.getPrototypeOf(o)}}function Ux(o){switch(typeof o){case"number":case"string":case"boolean":return!0}return!1}function Cy(o,e,t,i,n){let s=typeof e=="function"&&e.prototype===void 0,r=e;if(s)try{if(r=e?.call(e,n),s=!1,r==null)return}catch(h){console.error("Error in callback",h,o)}if(t.type=r,!s&&n&&(n instanceof ke||n instanceof V||n instanceof Ln||n instanceof Yt))return n;if(i||(i={serializer:op.getSerializerForConstructor(r)}),n&&typeof n=="object"&&KE(n)){if(n.__concreteInstance)return n.__concreteInstance;const h=n;if(!h.$serializedTypes&&r.prototype.$serializedTypes&&(h.$serializedTypes=r.prototype.$serializedTypes),h.$serializedTypes&&fh(h,o,t),n&&r!==void 0)try{let d=null;i.serializer&&(d=i.serializer.onDeserialize(o,t)),d||(d=new r,Rt&&console.log("Create concrete instance for persistent asset",n,"instance:",d),bl(d,n)),n.__concreteInstance=d,n=d}catch(d){console.error("Error creating instance or creating values on instance",d,n,r)}return n}if(Array.isArray(o)){const h=[];for(let d=0;d<o.length;d++){const u=o[d],m=Cy(u,e,t,i,u);h.push(m)}return h}const a=i?.serializer;if(a)return a.onDeserialize(o,t);if(n instanceof Pe)return n;let l;if(o&&(o.isMaterial||o.isTexture||o.isObject3D||o instanceof Yt))l=o;else{if(o===void 0)return;if(o===null&&(r===ke||r===Pe||r===V||r===Yt))return null;try{l=new r(...sA(o))}catch(h){console.error("Error creating "+t.path,t.target,h);return}}const c=l;return c.$serializedTypes&&fh(c,o,t),l}function sA(o){if(sp.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(const e of Object.keys(o))sp.push(o[e]);return sp}const Py=Symbol("assigned component properties");function zx(o,e){if(typeof e=="number"){if(o===null)return e;if(o==="Infinity"||o==="-Infinity"||o==="NaN")return Number(o)}return o}function bl(o,e,t,i){if(e==null||o==null)return;o[Py]=!0;const n=o.constructor?.name??"unknown";t?.registerDefinedKeys(n,o);for(const s of Object.keys(e)){const r=rA(o,s);if(typeof r?.value!="function"&&(!r||r.writable===!0||r.set!==void 0)){const a=o[s],l=zx(e[s],a);o[s]=l,i?.onAssigned&&i.onAssigned(o,s,a,l)}}delete o[Py]}function rA(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}const Vs=x("debugaddressables");class Nx{_context;_assetReferences={};constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences)this._assetReferences[t]?.unload();this._assetReferences={}}preUpdate=()=>{};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.url&&(this._assetReferences[e.url]?console.warn("Asset reference already registered",e):this._assetReferences[e.url]=e),e}unregisterAssetReference(e){e.url&&delete this._assetReferences[e.url]}}const ky=Symbol("assetReference");class ie{static getOrCreateFromUrl(e,t){if(!t&&(t=Q.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const i=t.addressables,n=i.findAssetReference(e);if(n)return n;const s=new ie(e,t.hash);return i.registerAssetReference(s),s}static getOrCreate(e,t,i){if(typeof e=="string"){if(!i&&(i=Q.Current,!i))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else i=e.context,e=e.sourceId;const n=ao(e,t);Vs&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);const s=i.addressables,r=s.findAssetReference(n);if(r)return r;const a=new ie(n,i.hash);return s.registerAssetReference(a),a}isAssetReference=!0;get rawAsset(){return this._rawAsset}get asset(){return this._glbRoot??(this._rawAsset?.scene||null)}set asset(e){e?this._rawAsset={animations:e.animations,scene:e,scenes:[e]}:this._rawAsset=null}get uri(){return this._url}get url(){return this._url}get urlName(){return this._urlName}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}_rawAsset=null;_glbRoot;_url;_urlName;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(...e){typeof e[0]=="object"?"url"in e[0]?this._url=e[0].url:(this._url="",e[0].asset&&(this.asset=e[0].asset)):(this._url=e[0],e[2]instanceof R&&(this.asset=e[2]));const t=this._url.lastIndexOf("/");if(t>=0){this._urlName=this._url.substring(t+1);const i=this._urlName.lastIndexOf(".");i>=0&&(this._urlName=this._urlName.substring(0,i))}else this._urlName=this._url;Tx(this._url,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Ys(this.asset)===!0}_loadingPromise=null;isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Vs&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&ki(this.asset.scene,!0,!0),ki(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loadingPromise=null,Q.Current&&Q.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Vs&&console.log("Preload",this.url);const e=await Hr.download(this.url,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(Vs&&console.log("[AssetReference] loadAssetAsync",this.url),!this.mustLoad)return this.asset?.parent&&console.warn(`[AssetReference] "${this.urlName}" is already loaded and parented to "${this.asset.parent.name||"scene"}". loadAssetAsync() returns the same shared instance \u2014 use .instantiate() to create a new copy.`),this.asset;if(e&&this._progressListeners.push(e),this._loadingPromise!==null)return this._loadingPromise.then(n=>this.asset);const t=Q.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("[AssetReference] Failed loading \u2013 Invalid data. Must be of type ArrayBuffer. "+typeof this._rawBinary),null;this._loadingPromise=is().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else Vs&&console.log("Load async",this.url),this._loadingPromise=is().loadSync(t,this.url,this.url,null,n=>{this.raiseProgressEvent(n)});this._loadingPromise.finally(()=>this._loadingPromise=null);const i=await this._loadingPromise;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),i?(i[ky]=this,this._glbRoot&&(this._glbRoot[ky]=this),this.asset&&(this.asset[ky]=this),Dp(t),i.scene!==void 0&&(this._rawAsset=i),this.asset):null}instantiate(e){return this.onInstantiate(e,!1)}instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){const t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(const t of this._progressListeners)t(this,e)}static currentlyInstantiating=new Map;async onInstantiate(e,t=!1,i){const n=Q.Current,s=new $o;if(e instanceof R?s.parent=e:e&&(Object.assign(s,e),s.cloneAssign(e)),s.parent===void 0&&(s.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),Vs&&console.log("Instantiate",this.url,"parent:",e),this.asset){Vs&&console.log("Add to scene",this.asset);let r=ie.currentlyInstantiating.get(this.url);if(r!==void 0&&r>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+r+")"),null;try{if(r===void 0&&(r=0),r+=1,ie.currentlyInstantiating.set(this.url,r),t){s.context=n;const a=this.asset;this.url&&(a.guid=this.url);const l=_y(a,s,void 0,i);if(l)return l}else{const a=Ks(this.asset,s);if(a)return a}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,ie.currentlyInstantiating.set(this.url,r)})}}else Vs&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){const t=e.scene;if(t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name){const i=t.children[0];return i.animations=t.animations,i}else return t}return null}}class aA extends qi{constructor(){super([ie],"AssetReferenceSerializer")}onSerialize(e,t){if(t.objectToDocumentReference){const i=e?.asset??e?._rawAsset;return i&&i.isObject3D===!0?t.objectToDocumentReference(i):e&&typeof e.uri=="string"&&e.uri.length>0?e.uri:null}if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ie.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof R){if(!t.context)return console.error("Missing context"),null;const i=e,n=t.context,s=i.guid??i.uuid,r=n.addressables.findAssetReference(s);if(r)return r;const a=new ie(s,void 0,i);return n.addressables.registerAssetReference(a),a}return null}}const lA=Promise.resolve(null);class Go{static imageReferences=new Map;static getOrCreate(e){let t=Go.imageReferences.get(e);return t||(t=new Go(e),Go.imageReferences.set(e,t)),t}constructor(e){this.url=e}url;_bitmap;_bitmapObject;_bitmapGeneration=0;dispose(){this._bitmapGeneration++,this._bitmapObject&&(this._bitmapObject.close(),this._bitmapObject=void 0),this._bitmap=void 0}static clearCache(){for(const e of Go.imageReferences.values())e.dispose();Go.imageReferences.clear()}createHTMLImage(){const e=new Image;return e.src=this.url,e}loader=null;createTexture(){return this.url?(this.loader||(this.loader=new jr),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(e=>(e&&!e.name?.length&&(e.name=this.url.split("/").pop()??this.url),e))):(console.error("Can not load texture without url"),lA)}getBitmap(){if(this._bitmap)return this._bitmap;const e=this._bitmapGeneration;return this._bitmap=new Promise((t,i)=>{const n=document.createElement("img");n.addEventListener("load",()=>{if(e!==this._bitmapGeneration){t(null);return}createImageBitmap(n).then(s=>{if(e!==this._bitmapGeneration){s.close(),t(null);return}this._bitmapObject=s,t(s)},i)},{once:!0}),n.addEventListener("error",s=>{console.error("Failed to load image:"+this.url,s),t(null)},{once:!0}),n.src=this.url}),this._bitmap}}class $x extends qi{constructor(){super([Go],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=ao(t.gltfId,e);return Go.getOrCreate(i)}}}class Ho{static cache=new Map;static getOrCreate(e){let t=Ho.cache.get(e);return t||(t=new Ho(e),Ho.cache.set(e,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.text())}url;res;constructor(e){this.url=e}dispose(){this.res=void 0}static clearCache(){for(const e of Ho.cache.values())e.dispose();Ho.cache.clear()}}function cA(){Ho.clearCache(),Go.clearCache()}class Wx extends qi{constructor(){super([Ho],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=ao(t.gltfId,e);return Ho.getOrCreate(i)}}}function Vx(){new aA,new $x,new Wx}var Oy=(o=>(o.Visible="application-visible",o.Hidden="application-hidden",o.MuteChanged="application-mutechanged",o))(Oy||{});let yh=!1;const qr=[];function Xr(){if(yh)return;M()&&console.debug("[Needle Engine] User input registered: Media playback is now allowed."),yh=!0;const o=[...qr];qr.length=0,o.forEach(e=>e())}typeof document<"u"&&(document.addEventListener("mousedown",Xr),document.addEventListener("pointerup",Xr),document.addEventListener("click",Xr),document.addEventListener("dragstart",Xr),document.addEventListener("touchend",Xr),document.addEventListener("keydown",Xr)),typeof window<"u"&&"userActivation"in navigator&&navigator.userActivation?.isActive&&(M()&&console.debug("[Needle Engine] User input already active: Media playback is now allowed."),qr.length=0,yh=!0);class no extends EventTarget{static get userInteractionRegistered(){return yh}static registerWaitForAllowAudio=no.registerWaitForInteraction;static registerWaitForInteraction(e){if(e!==null){if(yh){e();return}qr.indexOf(e)===-1&&qr.push(e)}}static unregisterWaitForInteraction(e){const t=qr.indexOf(e);t!==-1&&qr.splice(t,1)}_mute=!1;get muted(){return this._mute}set muted(e){e!==this._mute&&(this._mute=e,this.dispatchEvent(new Event("application-mutechanged")))}context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged,!1)}dispose(){window.removeEventListener("visibilitychange",this.onVisiblityChanged,!1)}onVisiblityChanged=e=>{switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}}class My{_listeners=new Map;emit(e,t){const i=this._listeners.get(e);if(i)for(const n of[...i])n(t)}on(e,t,i){let n=this._listeners.get(e);n||(n=[],this._listeners.set(e,n));const s=()=>{const a=n.indexOf(r);a>=0&&n.splice(a,1)},r=i?.once?(...a)=>{s(),t(...a)}:t;return n.push(r),s}clear(){this._listeners.clear()}}const rp=Symbol("needle:context-reset-behavior");function we(o="empty"){return function(e,t){let i=e[rp];(!i||!Object.prototype.hasOwnProperty.call(e,rp))&&(i=new Map(i),Object.defineProperty(e,rp,{value:i,enumerable:!1,writable:!1,configurable:!0})),i.set(t,o)}}function Gx(o){return o[rp]}function hA(o){const e=Gx(o);if(!e)return;const t=o;for(const[i,n]of e)switch(n){case"keep":case"custom":break;case"null":t[i]=null;break;case"undefined":t[i]=void 0;break;case"empty":{const s=t[i];if(Array.isArray(s))s.length=0;else if(s instanceof Map||s instanceof Set)s.clear();else if(s&&typeof s=="object"){const r=s;for(const a of Object.keys(r)){const l=r[a];Array.isArray(l)?l.length=0:delete r[a]}}else s!=null&&console.warn(`Context.resetRuntimeState: field "${String(i)}" is marked @resettable("empty") but does not hold a collection`,s);break}}}function*Ry(o,e=null){const t=e?e.time:Q.Current.time,i=t.time;for(;t.time-i<o;)yield}function*dA(o){for(let e=0;e<o;e++)yield}function*Hx(o){let e=!0;for(o.then(()=>e=!1),o.catch(()=>e=!1);e;)yield}var _l=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(_l||{});class Gs{static createText(e,t){let i=null;const n=t?.font||pA(t?.familyFamily||null);n instanceof JM?i=this.#t(e,n,t):i==null&&(i=new Ln);const s=t?.color||16777215,r=new V(i,t?.material??new Mt({color:s}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new eR(e,{font:t,size:1,depth:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})}static createOccluder(e){const t=new Ie({colorWrite:!1,depthWrite:!0,side:Bi});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const s=new In(1,1,1,1),r=t?.material??new Mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new V(s,r),i.name="Quad"}break;case"Cube":case 1:{const s=new ol(1,1,1),r=t?.material??new Mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new V(s,r),i.name="Cube"}break;case 10:case"RoundedCube":{const s=uA(1,1,1,.1,2),r=t?.material??new Mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new V(s,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const s=new rf(.5,16,16),r=t?.material??new Mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new V(s,r),i.name="Sphere"}break;case"Cylinder":case 3:{const s=new Rv(.5,.5,1,32),r=t?.material??new Mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new V(s,r),i.name="Cylinder"}break;case"ShaderBall":i=new Dn,i.name="ShaderBall",mA(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const t=new FO({color:16777215});e?.texture&&"map"in t&&(t.map=e.texture);const i=new BO(t);return this.applyDefaultObjectOptions(i,e),i}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function uA(o,e,t,i,n){const s=new UO,r=1e-5,a=i-r;s.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),s.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),s.absarc(o-a*2,e-a*2,r,Math.PI/2,0,!0),s.absarc(o-a*2,r,r,0,-Math.PI/2,!0);const l=new zO(s,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(c,h)=>{const d=[];for(let u=0;u<h.length;u+=3)d.push(new ee(h[u]/o,h[u+1]/e));return d},generateSideWallUV:(c,h,d,u,m,g)=>{const y=[];return y.push(new ee(h[d]/o,h[d+1]/e)),y.push(new ee(h[u]/o,h[u+1]/e)),y.push(new ee(h[m]/o,h[m+1]/e)),y.push(new ee(h[g]/o,h[g+1]/e)),y}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(c,h)=>h)),l.computeVertexNormals(),l}const ap=new Map;function pA(o){let e="";switch(o){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://cdn.needle.tools/static/fonts/facetype/Helvetiker_Regular_ascii.json";break}if(ap.has(e)){const n=ap.get(e);if(n)return n}const t=new tR,i=new Promise((n,s)=>{t.load(e,r=>{ap.set(e,r),n(r)},void 0,s)});return ap.set(e,i),i}let Ty=!1,Ey=null;function mA(o,e){if(Ey===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new Zo,n=wf(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),Ty=!0,Ey=i.loadAsync(t).then(s=>{const r=s.scene;return r.position.y-=.5,r}).catch(s=>(console.warn("Failed to load shaderball mesh: "+s.message),Xx())).finally(()=>{Ty=!1})}if(Ty){const t=Xx();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&qx(i,e),o.add(t)}Ey.then(t=>{o.children.forEach(s=>{s.name==="ShaderBall-Placeholder"&&o.remove(s)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),qx(n,e)),o.add(i)})}function qx(o,e){if(e?.color||e?.material||e?.texture){const t=e?.material??o.material?.clone()??new Mt;e.color&&"color"in t&&t.color instanceof oe&&t.color.set(e.color),e?.texture&&"map"in t&&(t.map=e.texture),o.material=t}}function Xx(){return new Dn().add(Gs.createPrimitive("Sphere",{material:new Ie({transparent:!0,opacity:.1})}))}const nt=x("debuginput");var lp=(o=>(o.Mouse="mouse",o.Touch="touch",o.Controller="controller",o.Hand="hand",o))(lp||{}),Te=(o=>(o.PointerDown="pointerdown",o.PointerUp="pointerup",o.PointerMove="pointermove",o.KeyDown="keydown",o.KeyUp="keyup",o.KeyPressed="keypress",o))(Te||{});class os extends xE{clientZ;deviceIndex;origin;source;mode;get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new so(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}_ray;space;isClick=!1;isDoubleClick=!1;cancelled=!1;get used(){return this._used}_used=!1;use(){this._used=!0}get pointerId(){return this._pointerid}_pointerid;get pointerType(){return this._pointerType}_pointerType;buttonName=void 0;get type(){return this._type}_type;metadata={};intersections=new Array;constructor(e,t,i){super(e,i),this.clientZ=i.clientZ,this._pointerid=i.pointerId,this._pointerType=i.pointerType,this._type=e,this.deviceIndex=i.deviceIndex,this.origin=i.origin,this.source=t,this.mode=i.mode,this._ray=i.ray,this.space=i.device,this.buttonName=i.buttonName,i.cancelled&&(this.cancelled=!0)}_immediatePropagationStopped=!1;get immediatePropagationStopped(){return this._immediatePropagationStopped}_propagationStopped=!1;get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}stopPropagation(){this._propagationStopped=!0,super.stopPropagation(),this.source?.stopPropagation(),nt&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class bh extends SE{source;constructor(e,t,i){super(e,i),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}}class gA{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}}var Hs=(o=>(o[o.Early=-100]="Early",o[o.Default=0]="Default",o[o.Late=100]="Late",o))(Hs||{});class Qx{_eventListeners={};addEventListener(e,t,i){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function")return console.error("Invalid call to addEventListener: callback is required and must be a function!"),()=>{};i?i={...i}:i={};let n=0;i?.queue!=null&&(n=i.queue);const s=this._eventListeners[e],r=s.find(a=>a.priority===n);return r?r.listeners.push({callback:t,options:i}):(s.push({priority:n,listeners:[{callback:t,options:i}]}),s.sort((a,l)=>a.priority-l.priority)),()=>this.removeEventListener(e,t,i)}removeEventListener(e,t,i){if(!this._eventListeners[e]||!t)return;const n=this._eventListeners[e];if(i?.queue!=null){const s=n.find(a=>a.priority===i.queue);if(!s)return;const r=s.listeners.findIndex(a=>a.callback===t);r>=0&&s.listeners.splice(r,1)}else for(const s of n){const r=s.listeners.findIndex(a=>a.callback===t);r>=0&&s.listeners.splice(r,1)}}dispatchEvent(e){let t=!1;if(e instanceof bh){const i=this._eventListeners[e.type];if(i)for(const n of i)for(let s=0;s<n.listeners.length;s++){const r=n.listeners[s];if(r.options?.signal?.aborted){n.listeners.splice(s,1),s--;continue}r.options.once&&(n.listeners.splice(s,1),s--),r.callback(e)}}if(e instanceof os){const i=this._eventListeners[e.type];if(i)for(const n of i){if(t)break;for(let s=0;s<n.listeners.length;s++){const r=n.listeners[s];if(r.options?.signal?.aborted){n.listeners.splice(s,1),s--;continue}if(e.immediatePropagationStopped){t=!0,nt&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,nt&&console.log("propagationStopped",e.type));r.options.once&&(n.listeners.splice(s,1),s--),r.callback(e)}}}}_doubleClickTimeThreshold=.2;_longPressTimeThreshold=1;get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}_setCursorTypes=[];setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){this._setCursorTypes?.length==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const i=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(const s of e)if(i===s){n=!0;break}if(!n)continue}else if(e!==i)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new ee];_pointerPositionsLastFrame=[new ee];_pointerPositionsDelta=[new ee];_pointerPositionsRC=[new ee];_pointerPositionDown=[new v];_pointerDownTime=[];_pointerUpTime=[];_pointerUpTimestamp=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_mouseWheelDeltaY=[0];_pointerEvent=[];_pointerEventsPressed=[];_pointerSpace=[];_pressedStack=new Map;onDownButton(e,t){let i=this._pressedStack.get(e);i||(i=[],this._pressedStack.set(e,i)),i.push(t)}onReleaseButton(e,t){const i=this._pressedStack.get(e);if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const i=this.keysPressed[t];return i.pressed===!1&&i.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyDown(n))return!0;return!1}const i=this.keysPressed[e];return i?i.startFrame===this.context.time.frameCount&&i.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyUp(n))return!0;return!1}const i=this.keysPressed[e];return i?i.frame===this.context.time.frameCount&&i.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyPressed(n))return!0;return!1}const i=this.keysPressed[e];return i&&i.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":nt&&Fe("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":nt&&Fe("Create Pointer move"),this.onMove(e);break;case"pointerup":nt&&Fe("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}constructor(e){this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}_htmlEventSource;_eventsBound=!1;_eventsExplicitlyUnbound=!1;get eventsBound(){return this._eventsBound}get eventsExplicitlyUnbound(){return this._eventsExplicitlyUnbound}bindEvents(){this.unbindDomEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus),this._eventsBound=!0,this._eventsExplicitlyUnbound=!1}unbindEvents(){this._eventsExplicitlyUnbound=!0;for(const e in this._eventListeners)this._eventListeners[e].length=0;this.unbindDomEvents()}unbindDomEvents(){this._eventsBound=!1,window.removeEventListener("contextmenu",this.onContextMenu),this._htmlEventSource?.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove,!0),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),this._htmlEventSource?.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}onLostFocus=()=>{for(const e in this.keysPressed)this.keysPressed[e].pressed=!1};_receivedPointerMoveEventsThisFrame=new Array;onEndOfFrame=()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(const e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0};canReceiveInput(e){return e.target===this.context.renderer?.domElement||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&I.isMozillaXR()?!0:(nt&&console.warn("CanReceiveInput:False for",e.target),!1)}onContextMenu=e=>{this.canReceiveInput(e)};keysPressed={};onKeyDown=e=>{if(nt&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(t&&t.pressed)return;this.keysPressed[e.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key,code:e.code};const i=new bh("keydown",e,e);this.onDispatchEvent(i)};onKeyPressed=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!0,t.frame=this.context.time.frameCount+1;const i=new bh("keypress",e,e);this.onDispatchEvent(i)};onKeyUp=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!1,t.frame=this.context.time.frameCount+1;const i=new bh("keyup",e,e);this.onDispatchEvent(i)};onWheelWindow=e=>{document.pointerLockElement&&this.onMouseWheel(e)};onMouseWheel=e=>{if(this.canReceiveInput(e)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY};onPointerDown=e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;if(e.target instanceof HTMLElement)try{e.target.setPointerCapture(e.pointerId)}catch{}const t=this.getPointerId(e);nt&&Fe(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new os("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:i,pressure:e.pressure});this.onDown(n)};onPointerMove=e=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(e.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(e.pointerId);let t=e.button;e.pointerType==="mouse"&&(t=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(e,t);t===-1&&(t=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,e.clientX,e.clientY),s=new os("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:n,pressure:e.pressure});this.onMove(s)};onPointerCancel=e=>{this.context.isInAR||(nt&&console.log("Pointer cancel",e),this.onPointerUp(e))};onPointerUp=e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);const t=this.getPointerId(e),i=new os("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),pressure:e.pressure});this.onUp(i),this._pointerIds[t]=-1,nt&&console.log("ID="+t,"PointerId="+e.pointerId,"ALL:",[...this._pointerIds])};getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}onTouchStart=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new os("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onDown(r)}};onTouchMove=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new os("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onMove(r)}};onTouchEnd=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=new os("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(s),this._pointerIds[n]=-1}};tempNearPlaneVector=new v;tempFarPlaneVector=new v;tempLookMatrix=new J;getAndUpdateSpatialObjectForScreenPosition(e,t,i){let n=this._pointerSpace[e];n||(n=new R,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const s=this.context.mainCamera;if(s){const r=this.tempNearPlaneVector.set(t,i,-1);this.convertScreenspaceToRaycastSpace(r);const a=this.tempFarPlaneVector.set(r.x,r.y,1);r.unproject(s),a.unproject(s);const l=s.worldUp||U(0,1,0).applyQuaternion(Re(s));this.tempLookMatrix.lookAt(a,r,l),n.position.set(r.x,r.y,r.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),i=e.clientX,n=e.clientY,s=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return nt&&!s&&console.log("Not in rect",t,i,n),s}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)){nt&&console.warn(`Received pointerDown event for pointerId that is already pressed: ${t}/${e.button}`,nt?e:"");return}if(nt&&console.log(e.pointerType,"DOWN",t,e.button),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new v);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,i=this.getPointerPressed(t);i===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!i||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){nt&&console.warn(`Received pointerUp for pointerId that is not pressed: ${t}/${e.button}`,nt?e:"");return}nt&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let a=this._pointerEventsPressed.length-1;a>=0;a--)if(this._pointerEventsPressed[a].pointerId===t){this._pointerEventsPressed.splice(a,1);break}if(!this._pointerPositionDown[t]){nt&&ge("[Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const i=this._pointerUpTime[t],n=this._pointerDownTime[t],s=this.context.time.realtimeSinceStartup,r=s-n;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=s,!e.cancelled&&r<1){let a=e.clientX-this._pointerPositionDown[t].x,l=e.clientY-this._pointerPositionDown[t].y,c=0;if(e.isSpatial&&e.clientZ!=null&&(c=e.clientZ-this._pointerPositionDown[t].z,a*=200,l*=200,c*=200),Math.abs(a)<5&&Math.abs(l)<5&&Math.abs(c)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const h=s-i;nt&&console.log("CLICK",t,a,l,c,h),h<this._doubleClickTimeThreshold&&h>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ee);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ee);const i=this._pointerPositionsLastFrame[t];i.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let s=e.clientX-i.x,r=e.clientY-i.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const h=e.source;s===0&&h.movementX!==0&&(s=h.movementX||0),r===0&&h.movementY!==0&&(r=h.movementY||0)}n.x+=s,n.y+=r,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const a=e.clientX,l=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new ee);const c=this._pointerPositionsRC[t];c.set(a,l),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(e){let t=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===e)return i;t===-1&&this._pointerIds[i]===-1&&(t=i)}return t!==-1?(this._pointerIds[t]=e,t):(nt&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,i){t[e]=i}setPointerStateT(e,t,i){return t[e]=i,i}onDispatchEvent(e){const t=Q.Current;try{Q.Current=this.context,this.dispatchEvent(e)}finally{Q.Current=t}}}const Yx=x("debugexr")||x("debugpmrem");class Kg{get name(){return"NEEDLE_pmrem"}parser;constructor(e){this.parser=e}loadTexture(e){const t=this.name,i=this.parser,n=i.json.textures[e];if(!n.extensions||!n.extensions[t])return null;const s=n.extensions[t],r=i.options.ktx2Loader;return r?(Yx&&console.log("NEEDLE_pmrem.loadTexture",e,s),i.loadTextureImage(e,s.source,r).then(a=>(Kg.postprocess(a),a.name="PMREM_"+a.name,Yx&&console.log("NEEDLE_pmrem: loaded PMREM texture",a),a))):(console.warn("NEEDLE_pmrem: No KTX2Loader available on GLTFLoader \u2014 cannot load PMREM texture"),null)}static postprocess(e){return e.mapping=ln,e}}const Kx="NEEDLE_lightmaps",vl=x("debuglightmapsextension")||x("debuglightmaps");var fo=(o=>(o[o.Lightmap=0]="Lightmap",o[o.Skybox=1]="Skybox",o[o.Reflection=2]="Reflection",o))(fo||{});class fA{get name(){return Kx}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[Kx];if(i){const n=i.textures;return n?.length?(vl&&console.log(i),new Promise(async(s,r)=>{const a=[];for(const c of n)if(c.pointer){vl&&console.log(c);let h=null;if(c.pointer.startsWith("/textures/")||c.pointer.startsWith("textures/"))vl&&console.log("Load texture from gltf",c.pointer),h=wy(this.parser,c.pointer).then(d=>this.resolveTexture(c,d));else if(typeof c.pointer=="string"){vl&&console.log("Load texture from path",c.pointer);const d=ao(this.source,c.pointer),u=d.endsWith(".pmrem.ktx2");let m;d.endsWith(".exr")?m=new xf(this.parser.options.manager):d.endsWith(".hdr")?m=new Qv(this.parser.options.manager):u?m=this.parser.options.ktx2Loader:m=new jr(this.parser.options.manager),h=m.loadAsync(d,void 0).then(g=>(u&&g&&Kg.postprocess(g),this.resolveTexture(c,g)))}else c.pointer;h&&a.push(h)}const l=await Df(a);l?.anyFailed&&(M()||vl)&&console.error("[NEEDLE_lightmaps]Error during extension loading:",l),s()})):null}}return null}resolveTexture(e,t){const i=t;vl&&console.log("Light Texture loaded:",i),i?.isTexture&&(this.registry?(i.colorSpace=Xo,this.registry.registerTexture(this.source,e.type,i,e.index)):console.log(fo[e.type],e.pointer,i))}}const wl=!!x("debuglightmaps");class yA{context;map=new Map;clear(){this.map.clear()}constructor(e){this.context=e}registerTexture(e,t,i,n){wl&&console.log("Registering ",fo[t]+' "'+e+'"',i),this.map.has(e)||this.map.set(e,new Map);const s=this.map.get(e),r=s?.get(t)??[];r.length<n&&(r.length=n+1),lS(i,!1),r[n]=i,s?.set(t,r)}tryGetLightmap(e,t=0){return this.tryGet(e,fo.Lightmap,t)}tryGetSkybox(e){return wl&&console.log("[Get Skybox]",e,this.map),this.tryGet(e,fo.Skybox,0)}tryGetReflection(e){return wl&&console.log("[Get Reflection]",e,this.map),this.tryGet(e,fo.Reflection,0)}tryGet(e,t,i){if(!e)return wl&&console.warn("Missing source id"),null;const n=this.map.get(e);if(!n)return wl&&console.warn(`[Lighting] No ${fo[t]} texture entry for`,e),null;const s=n.get(t);return s===void 0?(wl&&console.warn(`[Lighting] No ${fo[t]} texture for`,e,"index",i),null):!s?.length||s.length<=i?null:s[i]}}ai.lights_fragment_maps=ai.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
247
+ <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(i,s,o[s],o);continue}}}}function nA(o,e){for(const t of Object.keys(e)){const i=e[t];if(typeof i=="object"&&i!==null&&i!==void 0){const n=o[t];if(!n){go&&console.log(t,"is undefined on",o);continue}for(const s of Object.keys(i))if(n[s]===void 0&&Ux(i[s])&&!Ux(n)){const r=oA(n,s);if(r&&(r?.writable===void 0||r?.writable===!1)&&r.set===void 0){go&&console.warn('Property is not writable "'+s+'"',n,r,i[s],n[s]);continue}n[s]=i[s]}}}}function oA(o,e){for(;o;){const t=Object.getOwnPropertyDescriptor(o,e);if(t)return t;o=Object.getPrototypeOf(o)}}function Ux(o){switch(typeof o){case"number":case"string":case"boolean":return!0}return!1}function Cy(o,e,t,i,n){let s=typeof e=="function"&&e.prototype===void 0,r=e;if(s)try{if(r=e?.call(e,n),s=!1,r==null)return}catch(h){console.error("Error in callback",h,o)}if(t.type=r,!s&&n&&(n instanceof Oe||n instanceof V||n instanceof Ln||n instanceof Yt))return n;if(i||(i={serializer:op.getSerializerForConstructor(r)}),n&&typeof n=="object"&&KE(n)){if(n.__concreteInstance)return n.__concreteInstance;const h=n;if(!h.$serializedTypes&&r.prototype.$serializedTypes&&(h.$serializedTypes=r.prototype.$serializedTypes),h.$serializedTypes&&fh(h,o,t),n&&r!==void 0)try{let d=null;i.serializer&&(d=i.serializer.onDeserialize(o,t)),d||(d=new r,Rt&&console.log("Create concrete instance for persistent asset",n,"instance:",d),bl(d,n)),n.__concreteInstance=d,n=d}catch(d){console.error("Error creating instance or creating values on instance",d,n,r)}return n}if(Array.isArray(o)){const h=[];for(let d=0;d<o.length;d++){const u=o[d],m=Cy(u,e,t,i,u);h.push(m)}return h}const a=i?.serializer;if(a)return a.onDeserialize(o,t);if(n instanceof ke)return n;let l;if(o&&(o.isMaterial||o.isTexture||o.isObject3D||o instanceof Yt))l=o;else{if(o===void 0)return;if(o===null&&(r===Oe||r===ke||r===V||r===Yt))return null;try{l=new r(...sA(o))}catch(h){console.error("Error creating "+t.path,t.target,h);return}}const c=l;return c.$serializedTypes&&fh(c,o,t),l}function sA(o){if(sp.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(const e of Object.keys(o))sp.push(o[e]);return sp}const Py=Symbol("assigned component properties");function zx(o,e){if(typeof e=="number"){if(o===null)return e;if(o==="Infinity"||o==="-Infinity"||o==="NaN")return Number(o)}return o}function bl(o,e,t,i){if(e==null||o==null)return;o[Py]=!0;const n=o.constructor?.name??"unknown";t?.registerDefinedKeys(n,o);for(const s of Object.keys(e)){const r=rA(o,s);if(typeof r?.value!="function"&&(!r||r.writable===!0||r.set!==void 0)){const a=o[s],l=zx(e[s],a);o[s]=l,i?.onAssigned&&i.onAssigned(o,s,a,l)}}delete o[Py]}function rA(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}const Vs=x("debugaddressables");class Nx{_context;_assetReferences={};constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences)this._assetReferences[t]?.unload();this._assetReferences={}}preUpdate=()=>{};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.url&&(this._assetReferences[e.url]?console.warn("Asset reference already registered",e):this._assetReferences[e.url]=e),e}unregisterAssetReference(e){e.url&&delete this._assetReferences[e.url]}}const ky=Symbol("assetReference");class ie{static getOrCreateFromUrl(e,t){if(!t&&(t=Q.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const i=t.addressables,n=i.findAssetReference(e);if(n)return n;const s=new ie(e,t.hash);return i.registerAssetReference(s),s}static getOrCreate(e,t,i){if(typeof e=="string"){if(!i&&(i=Q.Current,!i))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else i=e.context,e=e.sourceId;const n=ao(e,t);Vs&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);const s=i.addressables,r=s.findAssetReference(n);if(r)return r;const a=new ie(n,i.hash);return s.registerAssetReference(a),a}isAssetReference=!0;get rawAsset(){return this._rawAsset}get asset(){return this._glbRoot??(this._rawAsset?.scene||null)}set asset(e){e?this._rawAsset={animations:e.animations,scene:e,scenes:[e]}:this._rawAsset=null}get uri(){return this._url}get url(){return this._url}get urlName(){return this._urlName}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}_rawAsset=null;_glbRoot;_url;_urlName;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(...e){typeof e[0]=="object"?"url"in e[0]?this._url=e[0].url:(this._url="",e[0].asset&&(this.asset=e[0].asset)):(this._url=e[0],e[2]instanceof R&&(this.asset=e[2]));const t=this._url.lastIndexOf("/");if(t>=0){this._urlName=this._url.substring(t+1);const i=this._urlName.lastIndexOf(".");i>=0&&(this._urlName=this._urlName.substring(0,i))}else this._urlName=this._url;Tx(this._url,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||Ys(this.asset)===!0}_loadingPromise=null;isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Vs&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&ki(this.asset.scene,!0,!0),ki(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loadingPromise=null,Q.Current&&Q.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Vs&&console.log("Preload",this.url);const e=await Hr.download(this.url,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(Vs&&console.log("[AssetReference] loadAssetAsync",this.url),!this.mustLoad)return this.asset?.parent&&console.warn(`[AssetReference] "${this.urlName}" is already loaded and parented to "${this.asset.parent.name||"scene"}". loadAssetAsync() returns the same shared instance \u2014 use .instantiate() to create a new copy.`),this.asset;if(e&&this._progressListeners.push(e),this._loadingPromise!==null)return this._loadingPromise.then(n=>this.asset);const t=Q.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("[AssetReference] Failed loading \u2013 Invalid data. Must be of type ArrayBuffer. "+typeof this._rawBinary),null;this._loadingPromise=is().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else Vs&&console.log("Load async",this.url),this._loadingPromise=is().loadSync(t,this.url,this.url,null,n=>{this.raiseProgressEvent(n)});this._loadingPromise.finally(()=>this._loadingPromise=null);const i=await this._loadingPromise;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),i?(i[ky]=this,this._glbRoot&&(this._glbRoot[ky]=this),this.asset&&(this.asset[ky]=this),Dp(t),i.scene!==void 0&&(this._rawAsset=i),this.asset):null}instantiate(e){return this.onInstantiate(e,!1)}instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){const t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(const t of this._progressListeners)t(this,e)}static currentlyInstantiating=new Map;async onInstantiate(e,t=!1,i){const n=Q.Current,s=new $o;if(e instanceof R?s.parent=e:e&&(Object.assign(s,e),s.cloneAssign(e)),s.parent===void 0&&(s.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),Vs&&console.log("Instantiate",this.url,"parent:",e),this.asset){Vs&&console.log("Add to scene",this.asset);let r=ie.currentlyInstantiating.get(this.url);if(r!==void 0&&r>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+r+")"),null;try{if(r===void 0&&(r=0),r+=1,ie.currentlyInstantiating.set(this.url,r),t){s.context=n;const a=this.asset;this.url&&(a.guid=this.url);const l=_y(a,s,void 0,i);if(l)return l}else{const a=Ks(this.asset,s);if(a)return a}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,ie.currentlyInstantiating.set(this.url,r)})}}else Vs&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){const t=e.scene;if(t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name){const i=t.children[0];return i.animations=t.animations,i}else return t}return null}}class aA extends qi{constructor(){super([ie],"AssetReferenceSerializer")}onSerialize(e,t){if(t.objectToDocumentReference){const i=e?.asset??e?._rawAsset;return i&&i.isObject3D===!0?t.objectToDocumentReference(i):e&&typeof e.uri=="string"&&e.uri.length>0?e.uri:null}if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ie.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof R){if(!t.context)return console.error("Missing context"),null;const i=e,n=t.context,s=i.guid??i.uuid,r=n.addressables.findAssetReference(s);if(r)return r;const a=new ie(s,void 0,i);return n.addressables.registerAssetReference(a),a}return null}}const lA=Promise.resolve(null);class Go{static imageReferences=new Map;static getOrCreate(e){let t=Go.imageReferences.get(e);return t||(t=new Go(e),Go.imageReferences.set(e,t)),t}constructor(e){this.url=e}url;_bitmap;_bitmapObject;_bitmapGeneration=0;dispose(){this._bitmapGeneration++,this._bitmapObject&&(this._bitmapObject.close(),this._bitmapObject=void 0),this._bitmap=void 0}static clearCache(){for(const e of Go.imageReferences.values())e.dispose();Go.imageReferences.clear()}createHTMLImage(){const e=new Image;return e.src=this.url,e}loader=null;createTexture(){return this.url?(this.loader||(this.loader=new jr),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(e=>(e&&!e.name?.length&&(e.name=this.url.split("/").pop()??this.url),e))):(console.error("Can not load texture without url"),lA)}getBitmap(){if(this._bitmap)return this._bitmap;const e=this._bitmapGeneration;return this._bitmap=new Promise((t,i)=>{const n=document.createElement("img");n.addEventListener("load",()=>{if(e!==this._bitmapGeneration){t(null);return}createImageBitmap(n).then(s=>{if(e!==this._bitmapGeneration){s.close(),t(null);return}this._bitmapObject=s,t(s)},i)},{once:!0}),n.addEventListener("error",s=>{console.error("Failed to load image:"+this.url,s),t(null)},{once:!0}),n.src=this.url}),this._bitmap}}class $x extends qi{constructor(){super([Go],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=ao(t.gltfId,e);return Go.getOrCreate(i)}}}class Ho{static cache=new Map;static getOrCreate(e){let t=Ho.cache.get(e);return t||(t=new Ho(e),Ho.cache.set(e,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.text())}url;res;constructor(e){this.url=e}dispose(){this.res=void 0}static clearCache(){for(const e of Ho.cache.values())e.dispose();Ho.cache.clear()}}function cA(){Ho.clearCache(),Go.clearCache()}class Wx extends qi{constructor(){super([Ho],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=ao(t.gltfId,e);return Ho.getOrCreate(i)}}}function Vx(){new aA,new $x,new Wx}var Oy=(o=>(o.Visible="application-visible",o.Hidden="application-hidden",o.MuteChanged="application-mutechanged",o))(Oy||{});let yh=!1;const qr=[];function Xr(){if(yh)return;M()&&console.debug("[Needle Engine] User input registered: Media playback is now allowed."),yh=!0;const o=[...qr];qr.length=0,o.forEach(e=>e())}typeof document<"u"&&(document.addEventListener("mousedown",Xr),document.addEventListener("pointerup",Xr),document.addEventListener("click",Xr),document.addEventListener("dragstart",Xr),document.addEventListener("touchend",Xr),document.addEventListener("keydown",Xr)),typeof window<"u"&&"userActivation"in navigator&&navigator.userActivation?.isActive&&(M()&&console.debug("[Needle Engine] User input already active: Media playback is now allowed."),qr.length=0,yh=!0);class no extends EventTarget{static get userInteractionRegistered(){return yh}static registerWaitForAllowAudio=no.registerWaitForInteraction;static registerWaitForInteraction(e){if(e!==null){if(yh){e();return}qr.indexOf(e)===-1&&qr.push(e)}}static unregisterWaitForInteraction(e){const t=qr.indexOf(e);t!==-1&&qr.splice(t,1)}_mute=!1;get muted(){return this._mute}set muted(e){e!==this._mute&&(this._mute=e,this.dispatchEvent(new Event("application-mutechanged")))}context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged,!1)}dispose(){window.removeEventListener("visibilitychange",this.onVisiblityChanged,!1)}onVisiblityChanged=e=>{switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}}class My{_listeners=new Map;emit(e,t){const i=this._listeners.get(e);if(i)for(const n of[...i])n(t)}on(e,t,i){let n=this._listeners.get(e);n||(n=[],this._listeners.set(e,n));const s=()=>{const a=n.indexOf(r);a>=0&&n.splice(a,1)},r=i?.once?(...a)=>{s(),t(...a)}:t;return n.push(r),s}clear(){this._listeners.clear()}}const rp=Symbol("needle:context-reset-behavior");function we(o="empty"){return function(e,t){let i=e[rp];(!i||!Object.prototype.hasOwnProperty.call(e,rp))&&(i=new Map(i),Object.defineProperty(e,rp,{value:i,enumerable:!1,writable:!1,configurable:!0})),i.set(t,o)}}function Gx(o){return o[rp]}function hA(o){const e=Gx(o);if(!e)return;const t=o;for(const[i,n]of e)switch(n){case"keep":case"custom":break;case"null":t[i]=null;break;case"undefined":t[i]=void 0;break;case"empty":{const s=t[i];if(Array.isArray(s))s.length=0;else if(s instanceof Map||s instanceof Set)s.clear();else if(s&&typeof s=="object"){const r=s;for(const a of Object.keys(r)){const l=r[a];Array.isArray(l)?l.length=0:delete r[a]}}else s!=null&&console.warn(`Context.resetRuntimeState: field "${String(i)}" is marked @resettable("empty") but does not hold a collection`,s);break}}}function*Ry(o,e=null){const t=e?e.time:Q.Current.time,i=t.time;for(;t.time-i<o;)yield}function*dA(o){for(let e=0;e<o;e++)yield}function*Hx(o){let e=!0;for(o.then(()=>e=!1),o.catch(()=>e=!1);e;)yield}var _l=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(_l||{});class Gs{static createText(e,t){let i=null;const n=t?.font||pA(t?.familyFamily||null);n instanceof JM?i=this.#t(e,n,t):i==null&&(i=new Ln);const s=t?.color||16777215,r=new V(i,t?.material??new Mt({color:s}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new eR(e,{font:t,size:1,depth:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})}static createOccluder(e){const t=new Ie({colorWrite:!1,depthWrite:!0,side:Bi});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const s=new In(1,1,1,1),r=t?.material??new Mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new V(s,r),i.name="Quad"}break;case"Cube":case 1:{const s=new ol(1,1,1),r=t?.material??new Mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new V(s,r),i.name="Cube"}break;case 10:case"RoundedCube":{const s=uA(1,1,1,.1,2),r=t?.material??new Mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new V(s,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const s=new rf(.5,16,16),r=t?.material??new Mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new V(s,r),i.name="Sphere"}break;case"Cylinder":case 3:{const s=new Rv(.5,.5,1,32),r=t?.material??new Mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new V(s,r),i.name="Cylinder"}break;case"ShaderBall":i=new Dn,i.name="ShaderBall",mA(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const t=new FO({color:16777215});e?.texture&&"map"in t&&(t.map=e.texture);const i=new BO(t);return this.applyDefaultObjectOptions(i,e),i}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function uA(o,e,t,i,n){const s=new UO,r=1e-5,a=i-r;s.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),s.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),s.absarc(o-a*2,e-a*2,r,Math.PI/2,0,!0),s.absarc(o-a*2,r,r,0,-Math.PI/2,!0);const l=new zO(s,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(c,h)=>{const d=[];for(let u=0;u<h.length;u+=3)d.push(new ee(h[u]/o,h[u+1]/e));return d},generateSideWallUV:(c,h,d,u,m,g)=>{const y=[];return y.push(new ee(h[d]/o,h[d+1]/e)),y.push(new ee(h[u]/o,h[u+1]/e)),y.push(new ee(h[m]/o,h[m+1]/e)),y.push(new ee(h[g]/o,h[g+1]/e)),y}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(c,h)=>h)),l.computeVertexNormals(),l}const ap=new Map;function pA(o){let e="";switch(o){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://cdn.needle.tools/static/fonts/facetype/Helvetiker_Regular_ascii.json";break}if(ap.has(e)){const n=ap.get(e);if(n)return n}const t=new tR,i=new Promise((n,s)=>{t.load(e,r=>{ap.set(e,r),n(r)},void 0,s)});return ap.set(e,i),i}let Ty=!1,Ey=null;function mA(o,e){if(Ey===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new Zo,n=wf(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),Ty=!0,Ey=i.loadAsync(t).then(s=>{const r=s.scene;return r.position.y-=.5,r}).catch(s=>(console.warn("Failed to load shaderball mesh: "+s.message),Xx())).finally(()=>{Ty=!1})}if(Ty){const t=Xx();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&qx(i,e),o.add(t)}Ey.then(t=>{o.children.forEach(s=>{s.name==="ShaderBall-Placeholder"&&o.remove(s)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),qx(n,e)),o.add(i)})}function qx(o,e){if(e?.color||e?.material||e?.texture){const t=e?.material??o.material?.clone()??new Mt;e.color&&"color"in t&&t.color instanceof oe&&t.color.set(e.color),e?.texture&&"map"in t&&(t.map=e.texture),o.material=t}}function Xx(){return new Dn().add(Gs.createPrimitive("Sphere",{material:new Ie({transparent:!0,opacity:.1})}))}const nt=x("debuginput");var lp=(o=>(o.Mouse="mouse",o.Touch="touch",o.Controller="controller",o.Hand="hand",o))(lp||{}),Te=(o=>(o.PointerDown="pointerdown",o.PointerUp="pointerup",o.PointerMove="pointermove",o.KeyDown="keydown",o.KeyUp="keyup",o.KeyPressed="keypress",o))(Te||{});class os extends xE{clientZ;deviceIndex;origin;source;mode;get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new so(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}_ray;space;isClick=!1;isDoubleClick=!1;cancelled=!1;get used(){return this._used}_used=!1;use(){this._used=!0}get pointerId(){return this._pointerid}_pointerid;get pointerType(){return this._pointerType}_pointerType;buttonName=void 0;get type(){return this._type}_type;metadata={};intersections=new Array;constructor(e,t,i){super(e,i),this.clientZ=i.clientZ,this._pointerid=i.pointerId,this._pointerType=i.pointerType,this._type=e,this.deviceIndex=i.deviceIndex,this.origin=i.origin,this.source=t,this.mode=i.mode,this._ray=i.ray,this.space=i.device,this.buttonName=i.buttonName,i.cancelled&&(this.cancelled=!0)}_immediatePropagationStopped=!1;get immediatePropagationStopped(){return this._immediatePropagationStopped}_propagationStopped=!1;get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}stopPropagation(){this._propagationStopped=!0,super.stopPropagation(),this.source?.stopPropagation(),nt&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class bh extends SE{source;constructor(e,t,i){super(e,i),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}}class gA{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}}var Hs=(o=>(o[o.Early=-100]="Early",o[o.Default=0]="Default",o[o.Late=100]="Late",o))(Hs||{});class Qx{_eventListeners={};addEventListener(e,t,i){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function")return console.error("Invalid call to addEventListener: callback is required and must be a function!"),()=>{};i?i={...i}:i={};let n=0;i?.queue!=null&&(n=i.queue);const s=this._eventListeners[e],r=s.find(a=>a.priority===n);return r?r.listeners.push({callback:t,options:i}):(s.push({priority:n,listeners:[{callback:t,options:i}]}),s.sort((a,l)=>a.priority-l.priority)),()=>this.removeEventListener(e,t,i)}removeEventListener(e,t,i){if(!this._eventListeners[e]||!t)return;const n=this._eventListeners[e];if(i?.queue!=null){const s=n.find(a=>a.priority===i.queue);if(!s)return;const r=s.listeners.findIndex(a=>a.callback===t);r>=0&&s.listeners.splice(r,1)}else for(const s of n){const r=s.listeners.findIndex(a=>a.callback===t);r>=0&&s.listeners.splice(r,1)}}dispatchEvent(e){let t=!1;if(e instanceof bh){const i=this._eventListeners[e.type];if(i)for(const n of i)for(let s=0;s<n.listeners.length;s++){const r=n.listeners[s];if(r.options?.signal?.aborted){n.listeners.splice(s,1),s--;continue}r.options.once&&(n.listeners.splice(s,1),s--),r.callback(e)}}if(e instanceof os){const i=this._eventListeners[e.type];if(i)for(const n of i){if(t)break;for(let s=0;s<n.listeners.length;s++){const r=n.listeners[s];if(r.options?.signal?.aborted){n.listeners.splice(s,1),s--;continue}if(e.immediatePropagationStopped){t=!0,nt&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,nt&&console.log("propagationStopped",e.type));r.options.once&&(n.listeners.splice(s,1),s--),r.callback(e)}}}}_doubleClickTimeThreshold=.2;_longPressTimeThreshold=1;get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}_setCursorTypes=[];setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){this._setCursorTypes?.length==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const i=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(const s of e)if(i===s){n=!0;break}if(!n)continue}else if(e!==i)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new ee];_pointerPositionsLastFrame=[new ee];_pointerPositionsDelta=[new ee];_pointerPositionsRC=[new ee];_pointerPositionDown=[new v];_pointerDownTime=[];_pointerUpTime=[];_pointerUpTimestamp=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_mouseWheelDeltaY=[0];_pointerEvent=[];_pointerEventsPressed=[];_pointerSpace=[];_pressedStack=new Map;onDownButton(e,t){let i=this._pressedStack.get(e);i||(i=[],this._pressedStack.set(e,i)),i.push(t)}onReleaseButton(e,t){const i=this._pressedStack.get(e);if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const i=this.keysPressed[t];return i.pressed===!1&&i.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyDown(n))return!0;return!1}const i=this.keysPressed[e];return i?i.startFrame===this.context.time.frameCount&&i.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyUp(n))return!0;return!1}const i=this.keysPressed[e];return i?i.frame===this.context.time.frameCount&&i.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyPressed(n))return!0;return!1}const i=this.keysPressed[e];return i&&i.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":nt&&Fe("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":nt&&Fe("Create Pointer move"),this.onMove(e);break;case"pointerup":nt&&Fe("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}constructor(e){this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}_htmlEventSource;_eventsBound=!1;_eventsExplicitlyUnbound=!1;get eventsBound(){return this._eventsBound}get eventsExplicitlyUnbound(){return this._eventsExplicitlyUnbound}bindEvents(){this.unbindDomEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus),this._eventsBound=!0,this._eventsExplicitlyUnbound=!1}unbindEvents(){this._eventsExplicitlyUnbound=!0;for(const e in this._eventListeners)this._eventListeners[e].length=0;this.unbindDomEvents()}unbindDomEvents(){this._eventsBound=!1,window.removeEventListener("contextmenu",this.onContextMenu),this._htmlEventSource?.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove,!0),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),this._htmlEventSource?.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}onLostFocus=()=>{for(const e in this.keysPressed)this.keysPressed[e].pressed=!1};_receivedPointerMoveEventsThisFrame=new Array;onEndOfFrame=()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(const e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0};canReceiveInput(e){return e.target===this.context.renderer?.domElement||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&I.isMozillaXR()?!0:(nt&&console.warn("CanReceiveInput:False for",e.target),!1)}onContextMenu=e=>{this.canReceiveInput(e)};keysPressed={};onKeyDown=e=>{if(nt&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(t&&t.pressed)return;this.keysPressed[e.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key,code:e.code};const i=new bh("keydown",e,e);this.onDispatchEvent(i)};onKeyPressed=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!0,t.frame=this.context.time.frameCount+1;const i=new bh("keypress",e,e);this.onDispatchEvent(i)};onKeyUp=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!1,t.frame=this.context.time.frameCount+1;const i=new bh("keyup",e,e);this.onDispatchEvent(i)};onWheelWindow=e=>{document.pointerLockElement&&this.onMouseWheel(e)};onMouseWheel=e=>{if(this.canReceiveInput(e)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY};onPointerDown=e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;if(e.target instanceof HTMLElement)try{e.target.setPointerCapture(e.pointerId)}catch{}const t=this.getPointerId(e);nt&&Fe(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new os("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:i,pressure:e.pressure});this.onDown(n)};onPointerMove=e=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(e.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(e.pointerId);let t=e.button;e.pointerType==="mouse"&&(t=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(e,t);t===-1&&(t=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,e.clientX,e.clientY),s=new os("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:n,pressure:e.pressure});this.onMove(s)};onPointerCancel=e=>{this.context.isInAR||(nt&&console.log("Pointer cancel",e),this.onPointerUp(e))};onPointerUp=e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);const t=this.getPointerId(e),i=new os("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),pressure:e.pressure});this.onUp(i),this._pointerIds[t]=-1,nt&&console.log("ID="+t,"PointerId="+e.pointerId,"ALL:",[...this._pointerIds])};getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}onTouchStart=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new os("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onDown(r)}};onTouchMove=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new os("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onMove(r)}};onTouchEnd=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=new os("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(s),this._pointerIds[n]=-1}};tempNearPlaneVector=new v;tempFarPlaneVector=new v;tempLookMatrix=new J;getAndUpdateSpatialObjectForScreenPosition(e,t,i){let n=this._pointerSpace[e];n||(n=new R,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const s=this.context.mainCamera;if(s){const r=this.tempNearPlaneVector.set(t,i,-1);this.convertScreenspaceToRaycastSpace(r);const a=this.tempFarPlaneVector.set(r.x,r.y,1);r.unproject(s),a.unproject(s);const l=s.worldUp||U(0,1,0).applyQuaternion(Re(s));this.tempLookMatrix.lookAt(a,r,l),n.position.set(r.x,r.y,r.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),i=e.clientX,n=e.clientY,s=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return nt&&!s&&console.log("Not in rect",t,i,n),s}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)){nt&&console.warn(`Received pointerDown event for pointerId that is already pressed: ${t}/${e.button}`,nt?e:"");return}if(nt&&console.log(e.pointerType,"DOWN",t,e.button),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new v);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,i=this.getPointerPressed(t);i===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!i||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){nt&&console.warn(`Received pointerUp for pointerId that is not pressed: ${t}/${e.button}`,nt?e:"");return}nt&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let a=this._pointerEventsPressed.length-1;a>=0;a--)if(this._pointerEventsPressed[a].pointerId===t){this._pointerEventsPressed.splice(a,1);break}if(!this._pointerPositionDown[t]){nt&&ge("[Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const i=this._pointerUpTime[t],n=this._pointerDownTime[t],s=this.context.time.realtimeSinceStartup,r=s-n;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=s,!e.cancelled&&r<1){let a=e.clientX-this._pointerPositionDown[t].x,l=e.clientY-this._pointerPositionDown[t].y,c=0;if(e.isSpatial&&e.clientZ!=null&&(c=e.clientZ-this._pointerPositionDown[t].z,a*=200,l*=200,c*=200),Math.abs(a)<5&&Math.abs(l)<5&&Math.abs(c)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const h=s-i;nt&&console.log("CLICK",t,a,l,c,h),h<this._doubleClickTimeThreshold&&h>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ee);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ee);const i=this._pointerPositionsLastFrame[t];i.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let s=e.clientX-i.x,r=e.clientY-i.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const h=e.source;s===0&&h.movementX!==0&&(s=h.movementX||0),r===0&&h.movementY!==0&&(r=h.movementY||0)}n.x+=s,n.y+=r,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const a=e.clientX,l=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new ee);const c=this._pointerPositionsRC[t];c.set(a,l),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(e){let t=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===e)return i;t===-1&&this._pointerIds[i]===-1&&(t=i)}return t!==-1?(this._pointerIds[t]=e,t):(nt&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,i){t[e]=i}setPointerStateT(e,t,i){return t[e]=i,i}onDispatchEvent(e){const t=Q.Current;try{Q.Current=this.context,this.dispatchEvent(e)}finally{Q.Current=t}}}const Yx=x("debugexr")||x("debugpmrem");class Kg{get name(){return"NEEDLE_pmrem"}parser;constructor(e){this.parser=e}loadTexture(e){const t=this.name,i=this.parser,n=i.json.textures[e];if(!n.extensions||!n.extensions[t])return null;const s=n.extensions[t],r=i.options.ktx2Loader;return r?(Yx&&console.log("NEEDLE_pmrem.loadTexture",e,s),i.loadTextureImage(e,s.source,r).then(a=>(Kg.postprocess(a),a.name="PMREM_"+a.name,Yx&&console.log("NEEDLE_pmrem: loaded PMREM texture",a),a))):(console.warn("NEEDLE_pmrem: No KTX2Loader available on GLTFLoader \u2014 cannot load PMREM texture"),null)}static postprocess(e){return e.mapping=ln,e}}const Kx="NEEDLE_lightmaps",vl=x("debuglightmapsextension")||x("debuglightmaps");var fo=(o=>(o[o.Lightmap=0]="Lightmap",o[o.Skybox=1]="Skybox",o[o.Reflection=2]="Reflection",o))(fo||{});class fA{get name(){return Kx}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[Kx];if(i){const n=i.textures;return n?.length?(vl&&console.log(i),new Promise(async(s,r)=>{const a=[];for(const c of n)if(c.pointer){vl&&console.log(c);let h=null;if(c.pointer.startsWith("/textures/")||c.pointer.startsWith("textures/"))vl&&console.log("Load texture from gltf",c.pointer),h=wy(this.parser,c.pointer).then(d=>this.resolveTexture(c,d));else if(typeof c.pointer=="string"){vl&&console.log("Load texture from path",c.pointer);const d=ao(this.source,c.pointer),u=d.endsWith(".pmrem.ktx2");let m;d.endsWith(".exr")?m=new xf(this.parser.options.manager):d.endsWith(".hdr")?m=new Qv(this.parser.options.manager):u?m=this.parser.options.ktx2Loader:m=new jr(this.parser.options.manager),h=m.loadAsync(d,void 0).then(g=>(u&&g&&Kg.postprocess(g),this.resolveTexture(c,g)))}else c.pointer;h&&a.push(h)}const l=await Df(a);l?.anyFailed&&(M()||vl)&&console.error("[NEEDLE_lightmaps]Error during extension loading:",l),s()})):null}}return null}resolveTexture(e,t){const i=t;vl&&console.log("Light Texture loaded:",i),i?.isTexture&&(this.registry?(i.colorSpace=Xo,this.registry.registerTexture(this.source,e.type,i,e.index)):console.log(fo[e.type],e.pointer,i))}}const wl=!!x("debuglightmaps");class yA{context;map=new Map;clear(){this.map.clear()}constructor(e){this.context=e}registerTexture(e,t,i,n){wl&&console.log("Registering ",fo[t]+' "'+e+'"',i),this.map.has(e)||this.map.set(e,new Map);const s=this.map.get(e),r=s?.get(t)??[];r.length<n&&(r.length=n+1),lS(i,!1),r[n]=i,s?.set(t,r)}tryGetLightmap(e,t=0){return this.tryGet(e,fo.Lightmap,t)}tryGetSkybox(e){return wl&&console.log("[Get Skybox]",e,this.map),this.tryGet(e,fo.Skybox,0)}tryGetReflection(e){return wl&&console.log("[Get Reflection]",e,this.map),this.tryGet(e,fo.Reflection,0)}tryGet(e,t,i){if(!e)return wl&&console.warn("Missing source id"),null;const n=this.map.get(e);if(!n)return wl&&console.warn(`[Lighting] No ${fo[t]} texture entry for`,e),null;const s=n.get(t);return s===void 0?(wl&&console.warn(`[Lighting] No ${fo[t]} texture for`,e,"index",i),null):!s?.length||s.length<=i?null:s[i]}}ai.lights_fragment_maps=ai.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
248
248
  vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
249
249
  // The range of RGBM lightmaps goes from 0 to 34.49 (5^2.2) in linear space, and from 0 to 5 in gamma space.
250
250
  lightMapTexel.rgb *= lightMapTexel.a * 8.; // no idea where that "8" comes from... heuristically derived
@@ -271,7 +271,7 @@ TEX `+i.texture_lod;if(Ay=="density"&&(y+=`
271
271
  `+(g/n.lastScreenCoverage).toFixed(0)+` dens
272
272
  `+(n.lastScreenCoverage*100).toFixed(1)+`% cov
273
273
  `+(n.lastCentrality*100).toFixed(1)+`% centr
274
- `+(cp.min.x.toFixed(2)+"-"+cp.max.x.toFixed(2)+"x"+cp.min.y.toFixed(2)+"-"+cp.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const b=e,f=b.worldForward,_=b.worldPosition,w=U(f).multiplyScalar(c*.7).add(l),S=w.distanceTo(_),O=h[Math.min(h.length-1,Math.max(0,s))]+"88",L=this.context.domHeight>0?screen.height/this.context.domHeight:1,D=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;F.DrawLabel(w,y,S*.012*L*D,void 0,16777215,O)}}}}}const Iy={};function Ly(o,e){Iy[o]=e}function Jx(o){const e=o.getBufferIdentifier(),t=Iy[e];return t(o)}function e1(o){return typeof o.guid=="function"?o.guid():null}class bA{_url;_ws;onOpen=null;onClose=null;onError=null;onMessage=null;get url(){return this._ws?.url??this._url}constructor(e){this._url=e}async start(){const e=await import("./vendor-CdNldo8c.min.js").then(s=>s.index),t=e.default?.WebsocketBuilder??e.WebsocketBuilder,i=e.default?.ExponentialBackoff??e.ExponentialBackoff,n=new t(this._url).withMaxRetries(10).withBackoff(new i(2e3,4)).onOpen(()=>{this._ws=n,this.onOpen?.()}).onClose(()=>{this.onClose?.()}).onError(()=>{this.onError?.(new Error("Websocket connection failed"))}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();n.addEventListener(e.WebsocketEvent.message,(s,r)=>{this.onMessage?.(r.data)})}send(e){this._ws?.send(e)}close(){this._ws?.close(),this._ws=void 0}}function _h(o){const e=[],t={MODULE:void 0,MAYBEMODULE:null,ready(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(i=>{e.push(i)})},async load(){if(t.MODULE)return t.MODULE;const i=await o();t.MODULE=i,t.MAYBEMODULE=i;for(const n of e)n(i);return e.length=0,i}};return t}const A={MaterialX:_h(()=>import("./materialx-CTPhpPxI.min.js")),RAPIER_PHYSICS:_h(()=>import("./rapier-DJ-luMxr.min.js")),POSTPROCESSING:_h(()=>import("./postprocessing-DDQgqL1m.min.js").then(o=>o.index)),POSTPROCESSING_AO:_h(()=>import("./postprocessing-DDQgqL1m.min.js").then(o=>o.N8AO)),PEERJS:_h(()=>import("./vendor-CdNldo8c.min.js").then(o=>o.bundler))};let Dy;const qs=x("debugpeer")!==void 0;function _A(){return Dy}function vA(o){Dy=o}async function t1(o,e){const t=(await A.PEERJS.load()).default;return e||(e={}),e={...Dy,...e},o?new t(o,e):new t(e)}async function i1(){const o=await A.PEERJS.load();return o.default===void 0?o:o.default}class n1{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await i1(),i=new t(e);i.on("error",n=>{qs&&console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new xA(i)})}async trySetupClient(e){const t=await i1();this._client=new t,this._client.on("error",i=>{qs&&console.error("Client error",i)}),this._client.on("open",i=>{qs&&console.debug("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{qs&&console.debug("Connected to host")}),this._clientData.on("data",n=>{qs&&console.debug("<<",n)})})}}class wA{_peer;constructor(e){this._peer=e}}class xA extends wA{get isHost(){return!0}_connections=[];constructor(e){super(e),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("bye")})}onConnection(e){qs&&console.debug("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){qs&&console.debug(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else qs&&console.warn(i)}}}}const o1="https://urls.needle.tools/default-networking-backend/index";let ss="wss://networking-2.needle.tools/socket";const dp=Symbol("originalCallback"),Pi=!!x("debugnet"),xl=!!(Pi||x("debugowner")),up=x("debugnetbin");var s1=(o=>(o.ConnectionInfo="connection-start-info",o))(s1||{}),se=(o=>(o.Join="join-room",o.Leave="leave-room",o.JoinedRoom="joined-room",o.LeftRoom="left-room",o.UserJoinedRoom="user-joined-room",o.UserLeftRoom="user-left-room",o.RoomStateSent="room-state-sent",o))(se||{});class SA{room;viewId;allowEditing;inRoom}class CA{room}class PA{userId}var r1=(o=>(o.RequestHasOwner="request-has-owner",o.ResponseHasOwner="response-has-owner",o.RequestIsOwner="request-is-owner",o.ResponseIsOwner="response-is-owner",o.RequestOwnership="request-ownership",o.GainedOwnership="gained-ownership",o.RemoveOwnership="remove-ownership",o.LostOwnership="lost-ownership",o.GainedOwnershipBroadcast="gained-ownership-broadcast",o.LostOwnershipBroadcast="lost-ownership-broadcast",o))(r1||{});class a1{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;_pendingOwnershipResolve=null;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(xl&&console.log("request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid})))}requestOwnership(){return this._hasOwnership?Promise.resolve(!0):(this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null,xl&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),new Promise(e=>{this._pendingOwnershipResolve=e,setTimeout(()=>{this._pendingOwnershipResolve===e&&(this._pendingOwnershipResolve=null,e(!1))},2e3)}))}async requestOwnershipAsync(){return xl&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this._hasOwnership?(this._hasOwnership=!1,this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this):this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(xl&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!0),this._pendingOwnershipResolve=null)):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(xl&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!1),this._pendingOwnershipResolve=null))}}class uu{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new n1),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Pi}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._transport?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),Pi&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},Bn.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t,i=Bn.Queued){if(i===Bn.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){up&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._transport?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._transport)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,Bn.Immediate);break}const s=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(s)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Pi&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._transport?.send(t)}beginListen(e,t){this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t);const i=()=>this.stopListen(e,t);return i[dp]=t,i}stopListening(e,t){return this.stopListen(e,t)}static _didLogStopListenHint=!1;stopListen(e,t){if(!t||!this._listeners[e])return;const i=t[dp]??t;i!==t&&M()&&!uu._didLogStopListenHint&&(uu._didLogStopListenHint=!0,console.warn("[Needle Engine] Tip: beginListen() returns an unsubscribe function \u2014 you can call it directly instead of using stopListen()."));const n=this._listeners[e].indexOf(i);n>=0&&this._listeners[e].splice(n,1)}beginListenBinary(e,t){this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t);const i=()=>this.stopListenBinary(e,t);return i[dp]=t,i}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=t?.[dp]??t,n=this._listenersBinary[e].indexOf(i);n>=0&&this._listenersBinary[e].splice(n,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e,t){if(this.connected&&e&&e!==ss)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);if(t)return this.connectTransport(t);e&&console.debug("Connecting to user provided url "+e);const i=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return i?ss=i:aw()&&(ss="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._transport&&(this._transport.onOpen=null,this._transport.onClose=null,this._transport.onError=null,this._transport.onMessage=null,this._transport.close(),this._transport=void 0),ss=void 0,this.connected=!1,this._connectionId=null,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1,this._connectingToWebsocketPromise=null}dispose(){this.disconnect(),this._listeners={},this._listenersBinary={},this._waitingForSocket={},this._peer=null}_listeners={};_listenersBinary={};connected=!1;_connectionId=null;_transport;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectTransport(e){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(t=>{let i=!1;const n=s=>{i||(i=!0,t(s))};e.onOpen=()=>{this._connectingToWebsocketPromise=null,this._transport=e,this.connected=!0,M()||Pi?console.log(`Connected to networking backend
274
+ `+(cp.min.x.toFixed(2)+"-"+cp.max.x.toFixed(2)+"x"+cp.min.y.toFixed(2)+"-"+cp.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const b=e,f=b.worldForward,_=b.worldPosition,w=U(f).multiplyScalar(c*.7).add(l),S=w.distanceTo(_),O=h[Math.min(h.length-1,Math.max(0,s))]+"88",L=this.context.domHeight>0?screen.height/this.context.domHeight:1,D=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;F.DrawLabel(w,y,S*.012*L*D,void 0,16777215,O)}}}}}const Iy={};function Ly(o,e){Iy[o]=e}function Jx(o){const e=o.getBufferIdentifier(),t=Iy[e];return t(o)}function e1(o){return typeof o.guid=="function"?o.guid():null}class bA{_url;_ws;onOpen=null;onClose=null;onError=null;onMessage=null;get url(){return this._ws?.url??this._url}constructor(e){this._url=e}async start(){const e=await import("./vendor-T07c_9f_.min.js").then(s=>s.index),t=e.default?.WebsocketBuilder??e.WebsocketBuilder,i=e.default?.ExponentialBackoff??e.ExponentialBackoff,n=new t(this._url).withMaxRetries(10).withBackoff(new i(2e3,4)).onOpen(()=>{this._ws=n,this.onOpen?.()}).onClose(()=>{this.onClose?.()}).onError(()=>{this.onError?.(new Error("Websocket connection failed"))}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();n.addEventListener(e.WebsocketEvent.message,(s,r)=>{this.onMessage?.(r.data)})}send(e){this._ws?.send(e)}close(){this._ws?.close(),this._ws=void 0}}function _h(o){const e=[],t={MODULE:void 0,MAYBEMODULE:null,ready(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(i=>{e.push(i)})},async load(){if(t.MODULE)return t.MODULE;const i=await o();t.MODULE=i,t.MAYBEMODULE=i;for(const n of e)n(i);return e.length=0,i}};return t}const A={MaterialX:_h(()=>import("./materialx-x1m4IJd1.min.js")),RAPIER_PHYSICS:_h(()=>import("./rapier-DJ-luMxr.min.js")),POSTPROCESSING:_h(()=>import("./postprocessing-DDQgqL1m.min.js").then(o=>o.index)),POSTPROCESSING_AO:_h(()=>import("./postprocessing-DDQgqL1m.min.js").then(o=>o.N8AO)),PEERJS:_h(()=>import("./vendor-T07c_9f_.min.js").then(o=>o.bundler))};let Dy;const qs=x("debugpeer")!==void 0;function _A(){return Dy}function vA(o){Dy=o}async function t1(o,e){const t=(await A.PEERJS.load()).default;return e||(e={}),e={...Dy,...e},o?new t(o,e):new t(e)}async function i1(){const o=await A.PEERJS.load();return o.default===void 0?o:o.default}class n1{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await i1(),i=new t(e);i.on("error",n=>{qs&&console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new xA(i)})}async trySetupClient(e){const t=await i1();this._client=new t,this._client.on("error",i=>{qs&&console.error("Client error",i)}),this._client.on("open",i=>{qs&&console.debug("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{qs&&console.debug("Connected to host")}),this._clientData.on("data",n=>{qs&&console.debug("<<",n)})})}}class wA{_peer;constructor(e){this._peer=e}}class xA extends wA{get isHost(){return!0}_connections=[];constructor(e){super(e),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("bye")})}onConnection(e){qs&&console.debug("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){qs&&console.debug(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else qs&&console.warn(i)}}}}const o1="https://urls.needle.tools/default-networking-backend/index";let ss="wss://networking-2.needle.tools/socket";const dp=Symbol("originalCallback"),Pi=!!x("debugnet"),xl=!!(Pi||x("debugowner")),up=x("debugnetbin");var s1=(o=>(o.ConnectionInfo="connection-start-info",o))(s1||{}),se=(o=>(o.Join="join-room",o.Leave="leave-room",o.JoinedRoom="joined-room",o.LeftRoom="left-room",o.UserJoinedRoom="user-joined-room",o.UserLeftRoom="user-left-room",o.RoomStateSent="room-state-sent",o))(se||{});class SA{room;viewId;allowEditing;inRoom}class CA{room}class PA{userId}var r1=(o=>(o.RequestHasOwner="request-has-owner",o.ResponseHasOwner="response-has-owner",o.RequestIsOwner="request-is-owner",o.ResponseIsOwner="response-is-owner",o.RequestOwnership="request-ownership",o.GainedOwnership="gained-ownership",o.RemoveOwnership="remove-ownership",o.LostOwnership="lost-ownership",o.GainedOwnershipBroadcast="gained-ownership-broadcast",o.LostOwnershipBroadcast="lost-ownership-broadcast",o))(r1||{});class a1{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;_pendingOwnershipResolve=null;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(xl&&console.log("request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid})))}requestOwnership(){return this._hasOwnership?Promise.resolve(!0):(this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null,xl&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),new Promise(e=>{this._pendingOwnershipResolve=e,setTimeout(()=>{this._pendingOwnershipResolve===e&&(this._pendingOwnershipResolve=null,e(!1))},2e3)}))}async requestOwnershipAsync(){return xl&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this._hasOwnership?(this._hasOwnership=!1,this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this):this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(xl&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!0),this._pendingOwnershipResolve=null)):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(xl&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!1),this._pendingOwnershipResolve=null))}}class uu{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new n1),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Pi}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._transport?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),Pi&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},Bn.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t,i=Bn.Queued){if(i===Bn.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){up&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._transport?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._transport)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,Bn.Immediate);break}const s=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(s)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Pi&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._transport?.send(t)}beginListen(e,t){this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t);const i=()=>this.stopListen(e,t);return i[dp]=t,i}stopListening(e,t){return this.stopListen(e,t)}static _didLogStopListenHint=!1;stopListen(e,t){if(!t||!this._listeners[e])return;const i=t[dp]??t;i!==t&&M()&&!uu._didLogStopListenHint&&(uu._didLogStopListenHint=!0,console.warn("[Needle Engine] Tip: beginListen() returns an unsubscribe function \u2014 you can call it directly instead of using stopListen()."));const n=this._listeners[e].indexOf(i);n>=0&&this._listeners[e].splice(n,1)}beginListenBinary(e,t){this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t);const i=()=>this.stopListenBinary(e,t);return i[dp]=t,i}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=t?.[dp]??t,n=this._listenersBinary[e].indexOf(i);n>=0&&this._listenersBinary[e].splice(n,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e,t){if(this.connected&&e&&e!==ss)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);if(t)return this.connectTransport(t);e&&console.debug("Connecting to user provided url "+e);const i=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return i?ss=i:aw()&&(ss="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._transport&&(this._transport.onOpen=null,this._transport.onClose=null,this._transport.onError=null,this._transport.onMessage=null,this._transport.close(),this._transport=void 0),ss=void 0,this.connected=!1,this._connectionId=null,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1,this._connectingToWebsocketPromise=null}dispose(){this.disconnect(),this._listeners={},this._listenersBinary={},this._waitingForSocket={},this._peer=null}_listeners={};_listenersBinary={};connected=!1;_connectionId=null;_transport;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectTransport(e){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(t=>{let i=!1;const n=s=>{i||(i=!0,t(s))};e.onOpen=()=>{this._connectingToWebsocketPromise=null,this._transport=e,this.connected=!0,M()||Pi?console.log(`Connected to networking backend
275
275
  `+(e.url??"")):console.debug("Connected to networking backend",e.url??""),n(!0),this.onSendQueued(Bn.OnConnection)},e.onClose=()=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let s="Websocket connection closed...";e.url?.includes("/socket")||(s+=' Do you perhaps mean to connect to "/socket"?'),console.error(s)},e.onError=()=>{console.error("Websocket connection failed..."),n(!1),ct.sendEvent(this.context,"networking",{event:"connection_error"})},e.onMessage=s=>{this.onMessage(s)},e.start()})}async connectWebsocket(){if(this._connectingToWebsocketPromise)return this._connectingToWebsocketPromise;if(ss===void 0&&(console.log("Fetch default backend url: "+o1),ss=await(await fetch(o1)).text()),ss===void 0)return!1;console.debug(`Connecting to networking backend on
276
276
  `+ss);const e=new bA(ss);return this.connectTransport(e)}onMessage(e){const t=e;try{if(typeof t!="string"){t.size&&this.handleIncomingBinaryMessage(t);return}const i=JSON.parse(t);if(Array.isArray(i))for(const n of i)this.handleIncomingStringMessage(n);else this.handleIncomingStringMessage(i);return}catch(i){Pi&&t==="pong"?console.log("<<",t):M()&&console.error("Failed to parse message",i)}}async handleIncomingBinaryMessage(e){up&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new yR(i),s=n.getBufferIdentifier(),r=this._listenersBinary[s],a=Jx(n),l=e1(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;const c=a??n;for(const h of r)h(c)}handleIncomingStringMessage(e){if(Pi&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.debug("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id,ct.sendEvent(this.context,"networking",{event:"connected"}))}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Pi&&console.log(e),e){this._isInRoom=!0;const r=e;this._currentRoomName=r.room,this._currentRoomViewId=r.viewId,this._currentRoomAllowEditing=r.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...r.inRoom),(up||M())&&console.debug("Joined Needle Engine Room: "+r.room);const a=new URL(window.location.href);a.searchParams.has("room")&&a.searchParams.delete("room"),a.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
277
277
  ${a.href}`)}this.onSendQueued(Bn.OnRoomJoin),ct.sendEvent(this.context,"networking",{event:"joined_room",room:this._currentRoomName});break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(up||M())&&console.debug("Left Needle Engine Room: "+n.room)),ct.sendEvent(this.context,"networking",{event:"left_room",room:n.room});break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),Pi&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(Pi&&console.log(r.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":Pi&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),Pi&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(s){console.error('Error invoking callback for "'+e.key+'"',s)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=Bn.OnRoomJoin){if(!this._transport){const s=this._waitingForSocket[i]||[];s.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=s;return}const n=JSON.stringify(this.toMessage(e,t));Pi&&console.log(">>",e),this._transport.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const kA=x("debugplayerview");var rs=(o=>(o.Browser="browser",o.Headset="headset",o.Handheld="handheld",o))(rs||{});class l1{userId;context;viewDevice="browser";get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}removed=!1;_object;constructor(e,t){this.userId=e,this.context=t}}class c1{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new l1(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const i=this.playerViews.get(e);i?.viewDevice===t&&(kA&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}const OA=new Proxy({},{get(o,e){if(e==="then")return;const t=ce.Current;if(!t)return(M()?console.error:console.warn)(`[needle] needle.${e} was accessed before the scene started. Use "needle" inside event handlers or callbacks, not at module top-level. For setup code use: onStart(ctx => { ... })`),Sl("needle not ready \u2014 scene hasn't started yet");const i=t[e];return typeof i=="function"?i.bind(t):i},set(o,e,t){const i=ce.Current;return i?(i[e]=t,!0):((M()?console.error:console.warn)(`[needle] needle.${e} was set before the scene started. Use "needle" inside event handlers or callbacks, not at module top-level. For setup code use: onStart(ctx => { ... })`),!0)}}),h1=new WeakMap;function Sl(o){const e={get(t,i){return i==="then"||typeof i=="symbol"?void 0:((M()?console.error:console.warn)(`[SceneData] ${o}`),Sl(o))},set(t,i){return typeof i=="symbol"||(M()?console.error:console.warn)(`[SceneData] ${o} (tried to set "${i}")`),!0}};return new Proxy({},e)}function d1(o,e){return new Proxy({},{get(t,i){if(i==="$object")return e;if(i==="$components")return new Proxy({},{get(s,r){if(r==="then")return;const a=k.get(r);return a?ls(e,a)||Sl(`Component "${r}" not found on node "${e.name}"`):Sl(`Component type "${r}" not registered (node "${e.name}")`)}});if(i==="then")return;const n=e.children.find(s=>s.name===i)??null;return n?d1(o,n):((M()?console.error:console.warn)(`[SceneData] "${i}" is not a child of "${e.name}". Use .$object to get the Three.js object or .$components.Name to access a component.`),Sl(`"${i}" not found on node "${e.name}"`))}})}function u1(o){let e=h1.get(o);return e||(e=new Proxy({},{get(t,i){return new Proxy({},{get(n,s){if(s==="then")return;const r=o.scene.getObjectByName(s)??null;return r?d1(o,r):Sl(`Node "${s}" not found in scene`)}})}}),h1.set(o,e)),e}const vh=new Uint8Array(4);vh[0]=255,vh[1]=255,vh[2]=255,vh[3]=255;const MA=new af(vh,1,1,gu);function jy(o,e=1){const t="alpha"in o,i=e*e,n=new Uint8Array(4*i),s=Math.floor(o.r*255),r=Math.floor(o.g*255),a=Math.floor(o.b*255);for(let c=0;c<i;c++){const h=c*4;n[h+0]=s,n[h+1]=r,n[h+2]=a,t?n[h+3]=Math.floor(o.alpha*255):n[h+3]=255}const l=new af(n,e,e);return l.needsUpdate=!0,l}function RA(o,e,t,i=1,n=3){const s=i*n,r=[o,e,t],a=r.length,l=new Uint8Array(4*a*s),c=new oe;for(let d=0;d<n;d++){const u=Math.floor(d/n*a),m=j.clamp(u+1,0,a-1),g=r[u],y=r[m],b=d/n*a%1;c.lerpColors(g,y,b);const f=Math.floor(c.r*255),_=Math.floor(c.g*255),w=Math.floor(c.b*255);for(let S=0;S<i;S++){const O=(d*i+S)*4;l[O+0]=f,l[O+1]=_,l[O+2]=w,l[O+3]=255}}const h=new af(l,i,n);return h.needsUpdate=!0,h}function pp(o,e){const t=o.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){const n=t[i],s=t[i+1],r=t[i+2],a=t[i+3],l=new ve(n,s,r,a);e.push(l)}return e}const Fy=[],p1=[];function TA(o,e){if(Fy.length===0)for(let t=0;t<27;t++)Fy.push(0);e||(e=Fy);for(let t=0;t<27;t++)p1[t]=e[t];e=p1,o.unity_SHAr={value:new ve(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new ve(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new ve(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new ve(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new ve(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new ve(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new ve(e[24],e[25],e[26],1)}}class EA{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function AA(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;const t=o.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){const s=o.shaders[i],r=o.shaders[n];if(s.uri&&r.uri||s.code&&r.code){if(!s.code&&s.uri&&await m1(s),!r.code&&r.uri&&await m1(r),!s.code||!r.code)return null;const a=o.techniques[e];return new EA(s.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function m1(o){const e=o.uri;if(e)if(e.endsWith(".glsl")){const t=await new Mv().loadAsync(e);o.code=t.toString()}else o.code=IA(o.uri)}function IA(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const Un=x("debugenvlight");var Cl=(o=>(o[o.Skybox=0]="Skybox",o[o.Trilight=1]="Trilight",o[o.Flat=3]="Flat",o[o.Custom=4]="Custom",o))(Cl||{}),mp=(o=>(o[o.Skybox=0]="Skybox",o[o.Custom=1]="Custom",o))(mp||{});class g1{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}_currentLightSettingsId;_sceneLightSettings;get currentLightSettingsId(){return this._currentLightSettingsId}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new ve;get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){return this._sceneLightSettings?.values()}enable(e){e instanceof ie&&(e=e.url);const t=this._sceneLightSettings?.get(e);return t?(Un&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(Un&&console.warn("No light settings found for",e),!1)}disable(e){if(e instanceof ie&&(e=e.url),e==null)return!1;const t=this._sceneLightSettings?.get(e);return t?(Un&&console.log("Disable scene light settings",e,t),t.enabled=!1,!0):!1}enableCurrent(){return this._currentLightSettingsId?(this.enable(this._currentLightSettingsId),this._currentLightSettingsId??null):null}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}Un&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}Un&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){Un&&console.log("Register reflection",e,t);const i=new f1(this.context,t,1);this._lighting[e]=i}internalGetReflection(e){return this._lighting[e]}__currentReflectionId=null;internalEnableReflection(e){this.__currentReflectionId=e;const t=this._sceneLightSettings?.get(e);switch(Un&&console.log("Enable reflection",e,t?Cl[t.ambientMode]:"Unknown ambient mode",t),t?.ambientMode){case 0:case 4:const i=this.internalGetReflection(e);if(i&&i.Source){Un&&console.log("Setting environment reflection",i);const n=this.context.scene,s=i.Source;return s.mapping!==ln&&(s.mapping=Qo),n.environment=s,n.environmentIntensity=this.environmentIntensity||1,s}else Un&&console.warn("Could not find reflection for source",e);break}if(t?.environmentReflectionSource===1)switch(t?.ambientMode){case 1:if(t.ambientTrilight){const i=t.ambientTrilight,n=RA(i[0],i[1],i[2],64,64);return n.colorSpace=Yo,n.mapping=Qo,this.context.scene.environment=n,n}else console.error("Missing ambient trilight",t.sourceId);case 3:if(t.ambientLight){const i=jy(t.ambientLight,64);return i.colorSpace=Yo,i.mapping=Qo,this.context.scene.environment=i,i}else console.error("Missing ambientlight",t.sourceId)}return null}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){Un&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}Un&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}_lighting={}}class f1{get Source(){return this._source}_source;constructor(e,t,i=1){this._source=t,t.mapping!==ln&&(t.mapping=Qo)}}let By;function LA(o){By=o}function DA(o){return o.isWebGPURenderer===!0&&By?new By(o):new NO(o)}const y1=x("timescale");let Uy=1;typeof y1=="number"&&(Uy=y1);class b1{get time(){return this._time}set time(e){this._time=e}_time=0;get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}_deltaTime=0;get deltaTimeUnscaled(){return this._deltaTimeUnscaled}_deltaTimeUnscaled=0;timeScale=1;get frame(){return this._frame}set frame(e){this._frame=e}_frame=0;get frameCount(){return this.frame}get realtimeSinceStartup(){return this._elapsedUnscaled}get fps(){return 1/this.deltaTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}_clockStartTime=performance.now();_lastUpdateTime=this._clockStartTime;_elapsedUnscaled=0;_smoothedFps=0;_smoothedDeltaTime=0;_fpsSamples=[];_fpsSampleIndex=0;constructor(){typeof Uy=="number"&&(this.timeScale=Uy)}update(){const e=performance.now();this.deltaTime=(e-this._lastUpdateTime)/1e3,this._lastUpdateTime=e,this._elapsedUnscaled+=this.deltaTime,this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let t=0;for(let i=0;i<this._fpsSamples.length;i++)t+=this._fpsSamples[i];this._smoothedDeltaTime=t/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let _1=!1;function v1(o){_1||(_1=!0,jA(),FA())}function jA(){const o=`
@@ -408,7 +408,7 @@ vec3 AgXToneMapping( vec3 color ) {
408
408
  return color;
409
409
  `,e="vec3 AgXToneMapping( vec3 color ) {",t="return color;",i=ai.tonemapping_pars_fragment.indexOf(e),n=ai.tonemapping_pars_fragment.indexOf(t,i);if(i>=0&&n>=0){const s=ai.tonemapping_pars_fragment.substring(i,n+t.length);ai.tonemapping_pars_fragment=ai.tonemapping_pars_fragment.replace(s,o)}else M()&&console.error("Couldn't find AgXToneMapping in ShaderChunk.tonemapping_pars_fragment")}function w1(o){if(typeof o=="string")switch(o=o.toLowerCase(),o){case"none":return bu;case"neutral":return sl;case"aces":return yu;case"agx":return fu;case"khronos_neutral":return sl;default:console.warn("[PostProcessing] Unknown tone mapping mode",o);return}}const Qr=x("debugpost");class x1{_context;_handler=null;_effects=[];_isDirty=!1;get effects(){return this._effects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}_enabled=!0;get enabled(){return this._enabled}set enabled(e){e!==this._enabled&&(this._enabled=e,this.markDirty())}get handler(){return this._handler}get composer(){return this._composer}set composer(e){this._composer=e}_composer=null;multisampling="auto";adaptiveResolution=!1;constructor(e){this._context=e}addEffect(e){this._effects.includes(e)||(this._effects.push(e),this._isDirty=!0)}removeEffect(e){const t=this._effects.indexOf(e);t!==-1&&(this._effects.splice(t,1),this._isDirty=!0)}markDirty(){this._isDirty=!0}_enabledTime=-1;_multisampleAutoChangeTime=0;_multisampleAutoDecreaseTime=0;update(){const e=this._context;if(e.isInXR)return;if(this._isDirty&&e.mainCamera&&this.apply(),this._tonemappingOnlyActive){const i=this._effects.filter(n=>n.active&&n.enabled&&n.isToneMapping===!0);if(i.length>0){const n=i[i.length-1];e.renderer.toneMapping=n.threeToneMapping,e.renderer.toneMappingExposure=n.toneMappingExposure}return}if(!this._handler||!this._composer||this._handler.composer!==this._composer)return;const t=this._composer;if(e.renderer.getContext().isContextLost()&&e.renderer.forceContextRestore(),t.getRenderer()!==e.renderer&&t.setRenderer(e.renderer),t.setMainScene(e.scene),this.multisampling==="auto")if(this._handler.hasSmaaEffect)this._handler.multisampling!==0&&(this._handler.multisampling=0,(Qr||M())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' and there is an SMAA effect.
410
410
 
411
- If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const i=e.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(e.time.realtimeSinceStartup-this._enabledTime>2&&i>.5){const n=this._handler.multisampling;if(this._handler.multisampling>0&&e.time.smoothedFps<=50){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=e.time.realtimeSinceStartup;let s=this._handler.multisampling*.5;s=Math.floor(s),s!=this._handler.multisampling&&(this._handler.multisampling=s),Qr&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${this._handler.multisampling}`)}else if(i>1&&e.time.smoothedFps>=59&&this._handler.multisampling<e.renderer.capabilities.maxSamples&&e.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup;let s=this._handler.multisampling<=0?1:this._handler.multisampling*2;s=Math.floor(s),s!==this._handler.multisampling&&(this._handler.multisampling=s),Qr&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${this._handler.multisampling}`)}}}else{const i=Math.max(0,Math.min(this.multisampling,e.renderer.capabilities.maxSamples));i!==this._handler.multisampling&&(this._handler.multisampling=i)}if(this._handler.adaptivePixelRatio=this.adaptiveResolution,this._handler.updateAdaptivePixelRatio(),e.mainCamera){const i=t.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==e.mainCamera){t.setMainCamera(e.mainCamera);break}}}_lastApplyTime;_rapidApplyCount=0;_tonemappingOnlyActive=!1;_previousToneMapping;_previousToneMappingExposure;apply(){Qr&&console.log(`[PostProcessing] Apply stack (${this._effects.length} effects)`),M()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("[PostProcessing] Detected rapid post processing modifications - this might be a bug")),this._lastApplyTime=Date.now()),this._isDirty=!1;const e=this._enabled?this._effects.filter(t=>t.active&&t.enabled):[];if(e.length<=0){this.restoreTonemapping(),this._handler?.unapply(!1);return}if(e.every(t=>t.isToneMapping===!0)){const t=e[e.length-1];Qr&&console.log("[PostProcessing] Only tonemapping effects in stack \u2014 applying directly to renderer"),this._tonemappingOnlyActive||(this._previousToneMapping=this._context.renderer.toneMapping,this._previousToneMappingExposure=this._context.renderer.toneMappingExposure,this._tonemappingOnlyActive=!0),this._context.renderer.toneMapping=t.threeToneMapping,this._context.renderer.toneMappingExposure=t.toneMappingExposure,this._handler?.unapply(!1);return}this.restoreTonemapping(),this.ensureHandler().then(t=>{if(t)return t.apply(e)}).then(()=>{this._handler&&(this.multisampling==="auto"?this._handler.multisampling=I.isMobileDevice()?2:4:this._handler.multisampling=Math.max(0,Math.min(this.multisampling,this._context.renderer.capabilities.maxSamples)),Qr&&console.debug(`[PostProcessing] Set multisampling to ${this._handler.multisampling} (Is Mobile: ${I.isMobileDevice()})`))}).catch(t=>{console.error("[PostProcessing] Failed to build/apply the postprocessing pipeline",t)}),this._enabledTime=this._context.time.realtimeSinceStartup}restoreTonemapping(){this._tonemappingOnlyActive&&(this._previousToneMapping!==void 0&&(this._context.renderer.toneMapping=this._previousToneMapping),this._previousToneMappingExposure!==void 0&&(this._context.renderer.toneMappingExposure=this._previousToneMappingExposure),this._tonemappingOnlyActive=!1,this._previousToneMapping=void 0,this._previousToneMappingExposure=void 0,Qr&&console.log("[PostProcessing] Restored renderer tonemapping"))}async ensureHandler(){if(!this._handler){const{PostProcessingHandler:e}=await Promise.resolve().then(()=>d4);this._handler||(this._handler=new e(this._context))}return this._handler}dispose(){this.restoreTonemapping(),this._handler?.dispose(),this._handler=null,this._composer=null,this._effects.length=0}}const Yr=[],gp=[];var fp;(o=>{function e(i,n){const s={name:n?.name,priority:n?.priority??0,callback:i};return Yr.push(s),Yr.sort((r,a)=>r.priority===a.priority?0:r.priority>a.priority?-1:1),()=>{const r=Yr.indexOf(s);r>=0&&Yr.splice(r,1)}}o.onCreateCustomModelLoader=e;function t(i){return gp.push(i),()=>{const n=gp.indexOf(i);n>=0&&gp.splice(n,1)}}o.onDetermineModelMimetype=t})(fp||(fp={}));const zy="Gaussian Splat Loader",BA=x("debugsplats")||x("debugsplatsort")||x("debugspatsort"),UA=(()=>{const o=x("splatcull"),e=typeof o=="number"?o:typeof o=="string"?parseFloat(o):NaN;return Number.isFinite(e)&&e>0?Math.min(Math.PI,e*(Math.PI/180)):void 0})(),zA={high:{maxSh:3,minSortIntervalMs:150,fetchers:3,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:512,coneFoveate:.4,behindFoveate:.2,xrFramebufferScale:1,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:Math.PI,xrMaxFps:0},medium:{maxSh:2,minSortIntervalMs:200,fetchers:2,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:384,coneFoveate:.3,behindFoveate:.15,xrFramebufferScale:.9,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:120/180*Math.PI,xrMaxFps:0},low:{maxSh:1,minSortIntervalMs:250,fetchers:1,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(7),maxPixelRadius:320,coneFoveate:.25,behindFoveate:.1,xrFramebufferScale:.8,maxPagedSplats:48*65536,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:110/180*Math.PI,xrMaxFps:30}};function yp(o,e=I.isMobileDevice()){return{...zA[o==="auto"?e?"low":"high":o]}}function Ny(o,e,t){const i=yp(t),n=Zr.get(o);n&&(n.quality=t,t!=="auto"&&(n.level=0,n.fpsBeforeStep=null,n.downBackoffUntil=0,n.goodStreak=0,n.stepFromLevel=null,n.jumpBackoffUntil=0,n.fpsBeforeProbe=null,n.upBackoffUntil=0,n.stableStreak=0),Wy(n));const s=e;if(s){typeof s.maxSh=="number"&&(s.maxSh=i.maxSh);const r=s.paged;r&&(r.setMaxSh(i.maxSh),r.pager&&(r.pager.numFetchers=i.fetchers))}return i}const bp=[{lodRenderScale:1,lodSplatScale:1,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:1,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:1.5,lodSplatScale:.75,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:.8,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:2.25,lodSplatScale:.5,maxPixelRadius:.75,maxStdDevCap:Math.sqrt(7),foveate:.6,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:4/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.75},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.6}],Kr=bp.length-1;function $y(o,e){const t=Math.max(0,Math.min(Kr,Math.round(e))),i=bp[t];return{...o,lodRenderScale:o.lodRenderScale*i.lodRenderScale,lodSplatScale:o.lodSplatScale*i.lodSplatScale,maxPixelRadius:Math.round(o.maxPixelRadius*i.maxPixelRadius),maxStdDev:Math.min(o.maxStdDev,i.maxStdDevCap),coneFoveate:Math.max(.05,o.coneFoveate*i.foveate),behindFoveate:Math.max(.05,o.behindFoveate*i.foveate),minAlpha:Math.max(o.minAlpha,i.minAlphaFloor),resolutionScale:o.resolutionScale*i.resolutionScale}}const Zr=new WeakMap;function NA(o){const e=Zr.get(o);return e?{quality:e.quality,adaptationLevel:e.level,effective:$y(yp(e.quality),e.level)}:null}const $A=1,WA=2,VA=.8,GA=.95,HA=4,S1=3,qA=1.1,wh=30,C1=2,XA=10,P1=.8,QA=8,YA=.9,k1=.5;function O1(o,e,t){const i=Zr.get(o);if(!i||i.quality!=="auto")return;let n=i.level;e.streaming&&(i.lastStreamingTime=Math.max(i.lastStreamingTime,t));const s=t-i.lastStreamingTime>=C1||t-i.lastChangeTime>=XA;i.fpsBeforeStep!==null&&t-i.lastChangeTime>=S1&&s&&(e.smoothedFps<i.fpsBeforeStep*P1?M()&&console.debug(`[SplatQuality] conditions collapsed since the degradation (${i.fpsBeforeStep.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}) \u2014 discarding the measurement, keeping level ${n}`):e.smoothedFps<i.fpsBeforeStep*qA?(n=i.stepFromLevel??Math.max(0,n-1),i.downBackoffUntil=t+wh,i.stepFromLevel!==null&&i.level-i.stepFromLevel>1&&(i.jumpBackoffUntil=t+wh),M()&&console.debug(`[SplatQuality] degradation bought no fps (${i.fpsBeforeStep.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}) \u2014 reverting to level ${n}, backing off ${wh}s`)):M()&&console.debug(`[SplatQuality] degradation bought fps (${i.fpsBeforeStep.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}) \u2014 keeping level ${n}`),i.fpsBeforeStep=null,i.stepFromLevel=null),i.fpsBeforeProbe!==null&&t-i.lastChangeTime>=S1&&s&&(e.smoothedFps<i.fpsBeforeProbe*P1?(n=Math.min(Kr,n+1),M()&&console.debug(`[SplatQuality] conditions collapsed during recovery probe (${i.fpsBeforeProbe.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}) \u2014 restoring level ${n}`)):e.smoothedFps<i.fpsBeforeProbe*YA?(n=Math.min(Kr,n+1),i.upBackoffUntil=t+wh,M()&&console.debug(`[SplatQuality] recovery probe cost fps (${i.fpsBeforeProbe.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}) \u2014 restoring level ${n}, backing off ${wh}s`)):M()&&console.debug(`[SplatQuality] recovery probe kept (fps ${i.fpsBeforeProbe.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}), level ${n}`),i.fpsBeforeProbe=null);const r=e.smoothedFps<e.targetFps*VA,a=e.smoothedFps>=e.targetFps*GA,l=t-i.lastChangeTime>=WA;r?(i.goodStreak=0,l&&t>=i.downBackoffUntil&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<Kr?(!(bp[n+1].resolutionScale<bp[n].resolutionScale)||e.smoothedFps<e.targetFps*k1)&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n++):l&&t<i.downBackoffUntil&&t>=i.jumpBackoffUntil&&e.smoothedFps<e.targetFps*k1&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<Kr&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n=Kr)):a?(i.goodStreak++,i.goodStreak>=HA&&l&&i.fpsBeforeProbe===null&&n>0&&(n--,i.goodStreak=0)):i.goodStreak=0;const c=n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null;i.stableStreak=c?i.stableStreak+1:0,c&&!r&&n>0&&i.stableStreak>=QA&&l&&t>=i.upBackoffUntil&&t-i.lastStreamingTime>=C1&&(i.fpsBeforeProbe=e.smoothedFps,i.stableStreak=0,n--),n!==i.level&&(M()&&console.debug(`[SplatQuality] adaptation level ${i.level} \u2192 ${n} (fps ${e.smoothedFps.toFixed(1)}/${e.targetFps}${n>i.level?", verifying fps gain":i.fpsBeforeProbe!==null?", probing recovery":""})`),i.level=n,i.lastChangeTime=t,Wy(i))}const Pl=new WeakMap;function M1(o,e){if((Pl.get(o)??0)>0)return!0;const t=e.renderer.pager;return!!t&&((t.fetchers?.length??0)>0||(t.fetched?.length??0)>0)}const KA=1500;function ZA(o,e){e.resumeQuietUntil!==0&&performance.now()>=e.resumeQuietUntil&&(e.renderer.pauseWork=!1,e.resumeQuietUntil=0,M()&&console.debug("[SplatQuality] calm resume over \u2014 splat work resumed"));const t=o.time.time,i=M1(o,e);if(i&&(e.lastStreamingTime=Math.max(e.lastStreamingTime,t)),t-e.lastEvalTime<$A||(e.lastEvalTime=t,BA&&JA(o,e),o.time.frameCount<60))return;const n=o.isInXR;let s=(n?o.xrSession?.frameRate:void 0)??60;n&&o.xrFrameRateLimit>0&&(s=Math.min(s,o.xrFrameRateLimit)),O1(o,{smoothedFps:o.time.smoothedFps,targetFps:s,streaming:i},t)}function JA(o,e){const t=e.renderer;if(!t.sortedCenter)return;const i=(a,l)=>{const c=l.getWorldPosition(e2),h=l.getWorldScale(t2),d=(h.x+h.y+h.z)/3,u=t.sortedCenter?c.distanceTo(t.sortedCenter):-1,m=t.lastLod?t.lastLod.pos.distanceTo(c):-1;console.debug(`[SplatSort] ${a} pos=(${c.x.toFixed(4)}, ${c.y.toFixed(4)}, ${c.z.toFixed(4)}) scale=${d.toFixed(4)} sortedCenterDist=${u.toFixed(5)} threshold=${(.001*d).toFixed(5)} lodPosDist=${m.toFixed(4)} activeSplats=${t.activeSplats}`)};if(o.mainCamera){i("mainCamera",o.mainCamera);let a="";for(let l=o.mainCamera.parent;l;l=l.parent)a+=`${l.name||l.type}(s=${l.scale.x.toFixed(2)}) > `;console.debug(`[SplatSort] mainCamera parents: ${a||"none"}`)}if(o.isInXR){const a=o.renderer.xr.getCamera();a&&(i("xrCamera",a),a.cameras?.[0]&&i("xrCamera.eye0",a.cameras[0]))}let n=0;o.scene.traverse(a=>{a.constructor?.name?.includes("SplatMesh")&&n++});const s=(t.pager?.pageLru?.size??0)*(t.pager?.pageSplats??0),r=M1(o,e);console.debug(`[SplatSort] fps=${o.time.smoothedFps.toFixed(1)} splatMeshes=${n} resident=${s}/${t.pager?.maxSplats??0} streaming=${r}(f=${t.pager?.fetchers?.length??0},q=${t.pager?.fetched?.length??0},l=${Pl.get(o)??0}) lod renderScale=${t.lodRenderScale} splatScale=${t.lodSplatScale} pixelScaleLimit=${t.lastLod?.pixelScaleLimit?.toExponential(3)} maxSplats=${t.lastLod?.maxSplats} adaptLevel=${e.level}`)}const e2=new v,t2=new v;function i2(o,e){o.minSortIntervalMs=e.minSortIntervalMs,o.numLodFetchers=e.fetchers,o.lodRenderScale=e.lodRenderScale;const t=I.isiOS()?2/3:1;o.lodSplatScale=e.lodSplatScale*t,o.sortCullHalfAngle=UA??e.sortCullHalfAngle,o.maxStdDev=e.maxStdDev,o.maxPixelRadius=e.maxPixelRadius,o.coneFoveate=e.coneFoveate,o.behindFoveate=e.behindFoveate,o.minAlpha=e.minAlpha,e.maxPagedSplats>0&&!o.pager&&(o.maxPagedSplats=e.maxPagedSplats),o.pager&&(o.pager.numFetchers=e.fetchers),R1=e.xrFramebufferScale}let R1;function T1(){return R1}let E1=1;function n2(){return E1}function Wy(o){const e=$y(yp(o.quality),o.level);if(i2(o.renderer,e),e.resolutionScale!==o.appliedResolutionScale){const t=o.context.resolutionScaleFactor/o.appliedResolutionScale;o.context.resolutionScaleFactor=t*e.resolutionScale,o.appliedResolutionScale=e.resolutionScale,E1=e.resolutionScale,o.context.xr?.setDynamicResolutionScale(e.resolutionScale)}o.context.xr?.refreshRenderResolution(),e.xrMaxFps!==o.appliedXrMaxFps&&(o.context.xrFrameRateLimit===o.appliedXrMaxFps&&(o.context.xrFrameRateLimit=e.xrMaxFps),o.appliedXrMaxFps=e.xrMaxFps),o.context.scene.traverse(t=>t.updateVersion?.())}function o2(o,e){let t;if(o.scene.traverse(i=>{i instanceof e&&(t=i)}),t||(t=new e({renderer:o.renderer}),o.scene.add(t)),Zr.has(o))Zr.get(o).renderer=t;else{const i={context:o,renderer:t,quality:"auto",level:0,lastChangeTime:0,lastEvalTime:0,goodStreak:0,fpsBeforeStep:null,downBackoffUntil:0,lastStreamingTime:-1/0,stepFromLevel:null,jumpBackoffUntil:0,fpsBeforeProbe:null,upBackoffUntil:0,stableStreak:0,appliedResolutionScale:1,appliedXrMaxFps:0,resumeQuietUntil:0};Zr.set(o,i),Wy(i),o.pre_render_callbacks.push(()=>ZA(o,i)),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{const n=Zr.get(o);if(!n)return;const s=n.renderer;document.visibilityState==="hidden"?(s.pauseWork=!0,n.resumeQuietUntil=Number.POSITIVE_INFINITY):n.resumeQuietUntil=performance.now()+KA})}return t}function s2(o){return!/^(blob:|data:)/i.test(o)}function r2(){Yr.some(o=>o.name===zy)||fp.onCreateCustomModelLoader(o=>{switch(o.mimetype){case"model/ply":case"model/spz":case"model/splat":case"model/ksplat":case"model/sog":case"model/rad":{const e=o.mimetype,t=o.context,i={name:zy,loadAsync:async(n,s)=>{const r=await import("./vendor-CdNldo8c.min.js").then(m=>m.spark_module);if(o2(t,r.SparkRenderer),e==="model/rad"&&s2(n))return new r.SplatMesh({url:n,paged:!0});Pl.set(t,(Pl.get(t)??0)+1);const a=()=>Pl.set(t,Math.max(0,(Pl.get(t)??1)-1)),l=new r.SplatLoader,c={"model/ply":r.SplatFileType.PLY,"model/spz":r.SplatFileType.SPZ,"model/splat":r.SplatFileType.SPLAT,"model/ksplat":r.SplatFileType.KSPLAT,"model/sog":r.SplatFileType.PCSOGSZIP,"model/rad":r.SplatFileType.RAD}[e];let h;try{h=await new Promise((m,g)=>{l.loadInternal({url:n,fileType:c,onLoad:m,onError:g,onProgress:y=>{if(s&&y.type==="progress"){const b=y;s(new ProgressEvent("progress",{loaded:b.loaded??0,total:b.total??0,lengthComputable:b.total!=null&&b.total>0}))}}})})}catch(m){throw a(),m}const d=h instanceof r.PackedSplats?{packedSplats:h,lod:!0}:{extSplats:h,lod:!0},u=new r.SplatMesh(d);return u.createLodSplats().catch(m=>console.warn("[Needle Engine] Building the splat LOD tree failed \u2014 rendering without LOD",m)).finally(a),(e==="model/ply"||e==="model/sog")&&u.quaternion.set(1,0,0,0),u},parse:n=>{const s=typeof n=="string"?new TextEncoder().encode(n):n,r=URL.createObjectURL(new Blob([s]));return i.loadAsync(r).finally(()=>URL.revokeObjectURL(r))}};return i}}return null},{name:zy})}const kl=new J().makeRotationY(Math.PI),hn=new B().setFromAxisAngle(new v(0,1,0),Math.PI),a2=x("debugwebxr");class l2{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new R,this.gameObject.name="Implicit XR Rig",a2){const e=sb(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const as=x("debugwebxr"),_p=x("debugcustomgesture"),c2="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",h2="generic-trigger",d2=new B().setFromEuler(new je(Ko.degToRad(0),Ko.degToRad(-90),Ko.degToRad(-90))),u2=new v(.04,-.04,0);class Vy{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__hand;get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??=this.inputSource.handedness}__side=void 0;get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new J;_gripPosition=new v;_gripQuaternion=new B;_linearVelocity=new v;_rayPositionRaw=new v;_rayRotationRaw=new B;_rayMatrix=new J;_rayPosition=new v;_rayQuaternion=new B;get gripPosition(){return U(this._gripPosition)}get gripQuaternion(){return xi(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return U(this._linearVelocity).applyQuaternion(hn)}get rayPosition(){return U(this._rayPosition)}get rayQuaternion(){return xi(this._rayQuaternion)}get gripWorldPosition(){return U(this._gripWorldPosition)}_gripWorldPosition=new v;get gripWorldQuaternion(){return xi(this._gripWorldQuaternion)}_gripWorldQuaternion=new B;get rayWorldPosition(){return U(this._rayWorldPosition)}_rayWorldPosition=new v;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return xi(this._rayWorldQuaternion)}_rayWorldQuaternion=new B;get pinchPosition(){return U(this._pinchPosition)}_pinchPosition=new v;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?Re(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(hn),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(U(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const e=this.handObject?.joints.wrist;if(e){const t=U(0,1,0).applyQuaternion(e.quaternion),i=U(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new Ui(.15);_debugGripAxesHelper=new Ui(.07);_debugRayAxesHelper=new Ui(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new R,this._object.name=`NeedleXRController_${i}`,as&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new R,this._raySpaceObject=new R,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new so,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){F.DrawSphere(this.rayWorldPosition,.003),F.DrawDirection(this.rayWorldPosition,U(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),t=this.inputSource.profiles.join(`
411
+ If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const i=e.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(e.time.realtimeSinceStartup-this._enabledTime>2&&i>.5){const n=this._handler.multisampling;if(this._handler.multisampling>0&&e.time.smoothedFps<=50){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=e.time.realtimeSinceStartup;let s=this._handler.multisampling*.5;s=Math.floor(s),s!=this._handler.multisampling&&(this._handler.multisampling=s),Qr&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${this._handler.multisampling}`)}else if(i>1&&e.time.smoothedFps>=59&&this._handler.multisampling<e.renderer.capabilities.maxSamples&&e.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup;let s=this._handler.multisampling<=0?1:this._handler.multisampling*2;s=Math.floor(s),s!==this._handler.multisampling&&(this._handler.multisampling=s),Qr&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${this._handler.multisampling}`)}}}else{const i=Math.max(0,Math.min(this.multisampling,e.renderer.capabilities.maxSamples));i!==this._handler.multisampling&&(this._handler.multisampling=i)}if(this._handler.adaptivePixelRatio=this.adaptiveResolution,this._handler.updateAdaptivePixelRatio(),e.mainCamera){const i=t.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==e.mainCamera){t.setMainCamera(e.mainCamera);break}}}_lastApplyTime;_rapidApplyCount=0;_tonemappingOnlyActive=!1;_previousToneMapping;_previousToneMappingExposure;apply(){Qr&&console.log(`[PostProcessing] Apply stack (${this._effects.length} effects)`),M()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("[PostProcessing] Detected rapid post processing modifications - this might be a bug")),this._lastApplyTime=Date.now()),this._isDirty=!1;const e=this._enabled?this._effects.filter(t=>t.active&&t.enabled):[];if(e.length<=0){this.restoreTonemapping(),this._handler?.unapply(!1);return}if(e.every(t=>t.isToneMapping===!0)){const t=e[e.length-1];Qr&&console.log("[PostProcessing] Only tonemapping effects in stack \u2014 applying directly to renderer"),this._tonemappingOnlyActive||(this._previousToneMapping=this._context.renderer.toneMapping,this._previousToneMappingExposure=this._context.renderer.toneMappingExposure,this._tonemappingOnlyActive=!0),this._context.renderer.toneMapping=t.threeToneMapping,this._context.renderer.toneMappingExposure=t.toneMappingExposure,this._handler?.unapply(!1);return}this.restoreTonemapping(),this.ensureHandler().then(t=>{if(t)return t.apply(e)}).then(()=>{this._handler&&(this.multisampling==="auto"?this._handler.multisampling=I.isMobileDevice()?2:4:this._handler.multisampling=Math.max(0,Math.min(this.multisampling,this._context.renderer.capabilities.maxSamples)),Qr&&console.debug(`[PostProcessing] Set multisampling to ${this._handler.multisampling} (Is Mobile: ${I.isMobileDevice()})`))}).catch(t=>{console.error("[PostProcessing] Failed to build/apply the postprocessing pipeline",t)}),this._enabledTime=this._context.time.realtimeSinceStartup}restoreTonemapping(){this._tonemappingOnlyActive&&(this._previousToneMapping!==void 0&&(this._context.renderer.toneMapping=this._previousToneMapping),this._previousToneMappingExposure!==void 0&&(this._context.renderer.toneMappingExposure=this._previousToneMappingExposure),this._tonemappingOnlyActive=!1,this._previousToneMapping=void 0,this._previousToneMappingExposure=void 0,Qr&&console.log("[PostProcessing] Restored renderer tonemapping"))}async ensureHandler(){if(!this._handler){const{PostProcessingHandler:e}=await Promise.resolve().then(()=>d4);this._handler||(this._handler=new e(this._context))}return this._handler}dispose(){this.restoreTonemapping(),this._handler?.dispose(),this._handler=null,this._composer=null,this._effects.length=0}}const Yr=[],gp=[];var fp;(o=>{function e(i,n){const s={name:n?.name,priority:n?.priority??0,callback:i};return Yr.push(s),Yr.sort((r,a)=>r.priority===a.priority?0:r.priority>a.priority?-1:1),()=>{const r=Yr.indexOf(s);r>=0&&Yr.splice(r,1)}}o.onCreateCustomModelLoader=e;function t(i){return gp.push(i),()=>{const n=gp.indexOf(i);n>=0&&gp.splice(n,1)}}o.onDetermineModelMimetype=t})(fp||(fp={}));const zy="Gaussian Splat Loader",BA=x("debugsplats")||x("debugsplatsort")||x("debugspatsort"),UA=(()=>{const o=x("splatcull"),e=typeof o=="number"?o:typeof o=="string"?parseFloat(o):NaN;return Number.isFinite(e)&&e>0?Math.min(Math.PI,e*(Math.PI/180)):void 0})(),zA={high:{maxSh:3,minSortIntervalMs:150,fetchers:3,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:512,coneFoveate:.4,behindFoveate:.2,xrFramebufferScale:1,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:Math.PI,xrMaxFps:0},medium:{maxSh:2,minSortIntervalMs:200,fetchers:2,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:384,coneFoveate:.3,behindFoveate:.15,xrFramebufferScale:.9,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:120/180*Math.PI,xrMaxFps:0},low:{maxSh:1,minSortIntervalMs:250,fetchers:1,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(7),maxPixelRadius:320,coneFoveate:.25,behindFoveate:.1,xrFramebufferScale:.8,maxPagedSplats:48*65536,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:110/180*Math.PI,xrMaxFps:30}};function yp(o,e=I.isMobileDevice()){return{...zA[o==="auto"?e?"low":"high":o]}}function Ny(o,e,t){const i=yp(t),n=Zr.get(o);n&&(n.quality=t,t!=="auto"&&(n.level=0,n.fpsBeforeStep=null,n.downBackoffUntil=0,n.goodStreak=0,n.stepFromLevel=null,n.jumpBackoffUntil=0,n.fpsBeforeProbe=null,n.upBackoffUntil=0,n.stableStreak=0),Wy(n));const s=e;if(s){typeof s.maxSh=="number"&&(s.maxSh=i.maxSh);const r=s.paged;r&&(r.setMaxSh(i.maxSh),r.pager&&(r.pager.numFetchers=i.fetchers))}return i}const bp=[{lodRenderScale:1,lodSplatScale:1,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:1,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:1.5,lodSplatScale:.75,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:.8,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:2.25,lodSplatScale:.5,maxPixelRadius:.75,maxStdDevCap:Math.sqrt(7),foveate:.6,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:4/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.75},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.6}],Kr=bp.length-1;function $y(o,e){const t=Math.max(0,Math.min(Kr,Math.round(e))),i=bp[t];return{...o,lodRenderScale:o.lodRenderScale*i.lodRenderScale,lodSplatScale:o.lodSplatScale*i.lodSplatScale,maxPixelRadius:Math.round(o.maxPixelRadius*i.maxPixelRadius),maxStdDev:Math.min(o.maxStdDev,i.maxStdDevCap),coneFoveate:Math.max(.05,o.coneFoveate*i.foveate),behindFoveate:Math.max(.05,o.behindFoveate*i.foveate),minAlpha:Math.max(o.minAlpha,i.minAlphaFloor),resolutionScale:o.resolutionScale*i.resolutionScale}}const Zr=new WeakMap;function NA(o){const e=Zr.get(o);return e?{quality:e.quality,adaptationLevel:e.level,effective:$y(yp(e.quality),e.level)}:null}const $A=1,WA=2,VA=.8,GA=.95,HA=4,S1=3,qA=1.1,wh=30,C1=2,XA=10,P1=.8,QA=8,YA=.9,k1=.5;function O1(o,e,t){const i=Zr.get(o);if(!i||i.quality!=="auto")return;let n=i.level;e.streaming&&(i.lastStreamingTime=Math.max(i.lastStreamingTime,t));const s=t-i.lastStreamingTime>=C1||t-i.lastChangeTime>=XA;i.fpsBeforeStep!==null&&t-i.lastChangeTime>=S1&&s&&(e.smoothedFps<i.fpsBeforeStep*P1?M()&&console.debug(`[SplatQuality] conditions collapsed since the degradation (${i.fpsBeforeStep.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}) \u2014 discarding the measurement, keeping level ${n}`):e.smoothedFps<i.fpsBeforeStep*qA?(n=i.stepFromLevel??Math.max(0,n-1),i.downBackoffUntil=t+wh,i.stepFromLevel!==null&&i.level-i.stepFromLevel>1&&(i.jumpBackoffUntil=t+wh),M()&&console.debug(`[SplatQuality] degradation bought no fps (${i.fpsBeforeStep.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}) \u2014 reverting to level ${n}, backing off ${wh}s`)):M()&&console.debug(`[SplatQuality] degradation bought fps (${i.fpsBeforeStep.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}) \u2014 keeping level ${n}`),i.fpsBeforeStep=null,i.stepFromLevel=null),i.fpsBeforeProbe!==null&&t-i.lastChangeTime>=S1&&s&&(e.smoothedFps<i.fpsBeforeProbe*P1?(n=Math.min(Kr,n+1),M()&&console.debug(`[SplatQuality] conditions collapsed during recovery probe (${i.fpsBeforeProbe.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}) \u2014 restoring level ${n}`)):e.smoothedFps<i.fpsBeforeProbe*YA?(n=Math.min(Kr,n+1),i.upBackoffUntil=t+wh,M()&&console.debug(`[SplatQuality] recovery probe cost fps (${i.fpsBeforeProbe.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}) \u2014 restoring level ${n}, backing off ${wh}s`)):M()&&console.debug(`[SplatQuality] recovery probe kept (fps ${i.fpsBeforeProbe.toFixed(1)} \u2192 ${e.smoothedFps.toFixed(1)}), level ${n}`),i.fpsBeforeProbe=null);const r=e.smoothedFps<e.targetFps*VA,a=e.smoothedFps>=e.targetFps*GA,l=t-i.lastChangeTime>=WA;r?(i.goodStreak=0,l&&t>=i.downBackoffUntil&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<Kr?(!(bp[n+1].resolutionScale<bp[n].resolutionScale)||e.smoothedFps<e.targetFps*k1)&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n++):l&&t<i.downBackoffUntil&&t>=i.jumpBackoffUntil&&e.smoothedFps<e.targetFps*k1&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<Kr&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n=Kr)):a?(i.goodStreak++,i.goodStreak>=HA&&l&&i.fpsBeforeProbe===null&&n>0&&(n--,i.goodStreak=0)):i.goodStreak=0;const c=n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null;i.stableStreak=c?i.stableStreak+1:0,c&&!r&&n>0&&i.stableStreak>=QA&&l&&t>=i.upBackoffUntil&&t-i.lastStreamingTime>=C1&&(i.fpsBeforeProbe=e.smoothedFps,i.stableStreak=0,n--),n!==i.level&&(M()&&console.debug(`[SplatQuality] adaptation level ${i.level} \u2192 ${n} (fps ${e.smoothedFps.toFixed(1)}/${e.targetFps}${n>i.level?", verifying fps gain":i.fpsBeforeProbe!==null?", probing recovery":""})`),i.level=n,i.lastChangeTime=t,Wy(i))}const Pl=new WeakMap;function M1(o,e){if((Pl.get(o)??0)>0)return!0;const t=e.renderer.pager;return!!t&&((t.fetchers?.length??0)>0||(t.fetched?.length??0)>0)}const KA=1500;function ZA(o,e){e.resumeQuietUntil!==0&&performance.now()>=e.resumeQuietUntil&&(e.renderer.pauseWork=!1,e.resumeQuietUntil=0,M()&&console.debug("[SplatQuality] calm resume over \u2014 splat work resumed"));const t=o.time.time,i=M1(o,e);if(i&&(e.lastStreamingTime=Math.max(e.lastStreamingTime,t)),t-e.lastEvalTime<$A||(e.lastEvalTime=t,BA&&JA(o,e),o.time.frameCount<60))return;const n=o.isInXR;let s=(n?o.xrSession?.frameRate:void 0)??60;n&&o.xrFrameRateLimit>0&&(s=Math.min(s,o.xrFrameRateLimit)),O1(o,{smoothedFps:o.time.smoothedFps,targetFps:s,streaming:i},t)}function JA(o,e){const t=e.renderer;if(!t.sortedCenter)return;const i=(a,l)=>{const c=l.getWorldPosition(e2),h=l.getWorldScale(t2),d=(h.x+h.y+h.z)/3,u=t.sortedCenter?c.distanceTo(t.sortedCenter):-1,m=t.lastLod?t.lastLod.pos.distanceTo(c):-1;console.debug(`[SplatSort] ${a} pos=(${c.x.toFixed(4)}, ${c.y.toFixed(4)}, ${c.z.toFixed(4)}) scale=${d.toFixed(4)} sortedCenterDist=${u.toFixed(5)} threshold=${(.001*d).toFixed(5)} lodPosDist=${m.toFixed(4)} activeSplats=${t.activeSplats}`)};if(o.mainCamera){i("mainCamera",o.mainCamera);let a="";for(let l=o.mainCamera.parent;l;l=l.parent)a+=`${l.name||l.type}(s=${l.scale.x.toFixed(2)}) > `;console.debug(`[SplatSort] mainCamera parents: ${a||"none"}`)}if(o.isInXR){const a=o.renderer.xr.getCamera();a&&(i("xrCamera",a),a.cameras?.[0]&&i("xrCamera.eye0",a.cameras[0]))}let n=0;o.scene.traverse(a=>{a.constructor?.name?.includes("SplatMesh")&&n++});const s=(t.pager?.pageLru?.size??0)*(t.pager?.pageSplats??0),r=M1(o,e);console.debug(`[SplatSort] fps=${o.time.smoothedFps.toFixed(1)} splatMeshes=${n} resident=${s}/${t.pager?.maxSplats??0} streaming=${r}(f=${t.pager?.fetchers?.length??0},q=${t.pager?.fetched?.length??0},l=${Pl.get(o)??0}) lod renderScale=${t.lodRenderScale} splatScale=${t.lodSplatScale} pixelScaleLimit=${t.lastLod?.pixelScaleLimit?.toExponential(3)} maxSplats=${t.lastLod?.maxSplats} adaptLevel=${e.level}`)}const e2=new v,t2=new v;function i2(o,e){o.minSortIntervalMs=e.minSortIntervalMs,o.numLodFetchers=e.fetchers,o.lodRenderScale=e.lodRenderScale;const t=I.isiOS()?2/3:1;o.lodSplatScale=e.lodSplatScale*t,o.sortCullHalfAngle=UA??e.sortCullHalfAngle,o.maxStdDev=e.maxStdDev,o.maxPixelRadius=e.maxPixelRadius,o.coneFoveate=e.coneFoveate,o.behindFoveate=e.behindFoveate,o.minAlpha=e.minAlpha,e.maxPagedSplats>0&&!o.pager&&(o.maxPagedSplats=e.maxPagedSplats),o.pager&&(o.pager.numFetchers=e.fetchers),R1=e.xrFramebufferScale}let R1;function T1(){return R1}let E1=1;function n2(){return E1}function Wy(o){const e=$y(yp(o.quality),o.level);if(i2(o.renderer,e),e.resolutionScale!==o.appliedResolutionScale){const t=o.context.resolutionScaleFactor/o.appliedResolutionScale;o.context.resolutionScaleFactor=t*e.resolutionScale,o.appliedResolutionScale=e.resolutionScale,E1=e.resolutionScale,o.context.xr?.setDynamicResolutionScale(e.resolutionScale)}o.context.xr?.refreshRenderResolution(),e.xrMaxFps!==o.appliedXrMaxFps&&(o.context.xrFrameRateLimit===o.appliedXrMaxFps&&(o.context.xrFrameRateLimit=e.xrMaxFps),o.appliedXrMaxFps=e.xrMaxFps),o.context.scene.traverse(t=>t.updateVersion?.())}function o2(o,e){let t;if(o.scene.traverse(i=>{i instanceof e&&(t=i)}),t||(t=new e({renderer:o.renderer}),o.scene.add(t)),Zr.has(o))Zr.get(o).renderer=t;else{const i={context:o,renderer:t,quality:"auto",level:0,lastChangeTime:0,lastEvalTime:0,goodStreak:0,fpsBeforeStep:null,downBackoffUntil:0,lastStreamingTime:-1/0,stepFromLevel:null,jumpBackoffUntil:0,fpsBeforeProbe:null,upBackoffUntil:0,stableStreak:0,appliedResolutionScale:1,appliedXrMaxFps:0,resumeQuietUntil:0};Zr.set(o,i),Wy(i),o.pre_render_callbacks.push(()=>ZA(o,i)),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{const n=Zr.get(o);if(!n)return;const s=n.renderer;document.visibilityState==="hidden"?(s.pauseWork=!0,n.resumeQuietUntil=Number.POSITIVE_INFINITY):n.resumeQuietUntil=performance.now()+KA})}return t}function s2(o){return!/^(blob:|data:)/i.test(o)}function r2(){Yr.some(o=>o.name===zy)||fp.onCreateCustomModelLoader(o=>{switch(o.mimetype){case"model/ply":case"model/spz":case"model/splat":case"model/ksplat":case"model/sog":case"model/rad":{const e=o.mimetype,t=o.context,i={name:zy,loadAsync:async(n,s)=>{const r=await import("./vendor-T07c_9f_.min.js").then(m=>m.spark_module);if(o2(t,r.SparkRenderer),e==="model/rad"&&s2(n))return new r.SplatMesh({url:n,paged:!0});Pl.set(t,(Pl.get(t)??0)+1);const a=()=>Pl.set(t,Math.max(0,(Pl.get(t)??1)-1)),l=new r.SplatLoader,c={"model/ply":r.SplatFileType.PLY,"model/spz":r.SplatFileType.SPZ,"model/splat":r.SplatFileType.SPLAT,"model/ksplat":r.SplatFileType.KSPLAT,"model/sog":r.SplatFileType.PCSOGSZIP,"model/rad":r.SplatFileType.RAD}[e];let h;try{h=await new Promise((m,g)=>{l.loadInternal({url:n,fileType:c,onLoad:m,onError:g,onProgress:y=>{if(s&&y.type==="progress"){const b=y;s(new ProgressEvent("progress",{loaded:b.loaded??0,total:b.total??0,lengthComputable:b.total!=null&&b.total>0}))}}})})}catch(m){throw a(),m}const d=h instanceof r.PackedSplats?{packedSplats:h,lod:!0}:{extSplats:h,lod:!0},u=new r.SplatMesh(d);return u.createLodSplats().catch(m=>console.warn("[Needle Engine] Building the splat LOD tree failed \u2014 rendering without LOD",m)).finally(a),(e==="model/ply"||e==="model/sog")&&u.quaternion.set(1,0,0,0),u},parse:n=>{const s=typeof n=="string"?new TextEncoder().encode(n):n,r=URL.createObjectURL(new Blob([s]));return i.loadAsync(r).finally(()=>URL.revokeObjectURL(r))}};return i}}return null},{name:zy})}const kl=new J().makeRotationY(Math.PI),hn=new B().setFromAxisAngle(new v(0,1,0),Math.PI),a2=x("debugwebxr");class l2{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new R,this.gameObject.name="Implicit XR Rig",a2){const e=sb(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const as=x("debugwebxr"),_p=x("debugcustomgesture"),c2="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",h2="generic-trigger",d2=new B().setFromEuler(new je(Ko.degToRad(0),Ko.degToRad(-90),Ko.degToRad(-90))),u2=new v(.04,-.04,0);class Vy{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__hand;get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??=this.inputSource.handedness}__side=void 0;get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new J;_gripPosition=new v;_gripQuaternion=new B;_linearVelocity=new v;_rayPositionRaw=new v;_rayRotationRaw=new B;_rayMatrix=new J;_rayPosition=new v;_rayQuaternion=new B;get gripPosition(){return U(this._gripPosition)}get gripQuaternion(){return xi(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return U(this._linearVelocity).applyQuaternion(hn)}get rayPosition(){return U(this._rayPosition)}get rayQuaternion(){return xi(this._rayQuaternion)}get gripWorldPosition(){return U(this._gripWorldPosition)}_gripWorldPosition=new v;get gripWorldQuaternion(){return xi(this._gripWorldQuaternion)}_gripWorldQuaternion=new B;get rayWorldPosition(){return U(this._rayWorldPosition)}_rayWorldPosition=new v;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return xi(this._rayWorldQuaternion)}_rayWorldQuaternion=new B;get pinchPosition(){return U(this._pinchPosition)}_pinchPosition=new v;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?Re(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(hn),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(U(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const e=this.handObject?.joints.wrist;if(e){const t=U(0,1,0).applyQuaternion(e.quaternion),i=U(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new Ui(.15);_debugGripAxesHelper=new Ui(.07);_debugRayAxesHelper=new Ui(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new R,this._object.name=`NeedleXRController_${i}`,as&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new R,this._raySpaceObject=new R,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new so,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){F.DrawSphere(this.rayWorldPosition,.003),F.DrawDirection(this.rayWorldPosition,U(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),t=this.inputSource.profiles.join(`
412
412
  `);let i=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
413
413
  C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(i+=`
414
414
  Pinch: ${this.getGesture("pinch")?.value.toFixed(3)}`),i+=`
@@ -419,7 +419,7 @@ Pinch: ${this.getGesture("pinch")?.value.toFixed(3)}`),i+=`
419
419
  Layout: `;for(const n of Object.keys(this._layout.components||{})){const s=this.getStick(n),r=this._layout.components[n]?.gamepadIndices,a=r?Object.entries(r).map(l=>l[0][0].toUpperCase()+l[0].slice(1)+"="+l[1]).join(","):"";i+=`
420
420
  ${n}: ${this._layout.components[n]?.type} [${a}] (${s.x.toPrecision(2)},${s.y.toPrecision(2)})`}}F.DrawLabel(e,i,.006)}onUpdateFrame(e){if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace||!this.inputSource.gamepad?.connected){this._isTracking=!1;return}const t=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=t!=null;let i=null,n=null,s=null,r=null;if(t){const h=t.transform;this._rayMatrix.fromArray(h.matrix).premultiply(kl),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,U(1,1,1)),s=U(h.position),r=xi(h.orientation),this._rayPositionRaw.copy(s),this._rayRotationRaw.copy(r)}if(this.inputSource.gripSpace){const h=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(h){const d=h.transform;if(i=U(d.position),n=xi(d.orientation),this._gripMatrix.fromArray(d.matrix).premultiply(kl),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,U(1,1,1)),"linearVelocity"in h&&h.linearVelocity){const u=h.linearVelocity;this._linearVelocity.set(u.x,u.y,u.z)}}}this.xr.context.mainCamera?.parent&&(this._object.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&this._gripSpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&this._raySpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const a=this.hand;if(a){let h=!1;const d=a.get("wrist"),u=d&&this.getHandJointPose(d,e);if(u){h=!0;const y=u.transform.position,b=u.transform.orientation;this._object.position.set(y.x,y.y,y.z),this._object.quaternion.set(b.x,b.y,b.z,b.w).multiply(hn)}h||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(hn));const m=a.get("middle-finger-metacarpal"),g=m&&this.getHandJointPose(m,e);g&&(this._gripMatrix.fromArray(g.transform.matrix).premultiply(kl),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,U(1,1,1)),i=U().copy(g.transform.position),n=xi().copy(g.transform.orientation),n.multiply(d2),i.add(U(u2).applyQuaternion(n)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&i&&n?(this._object.position.copy(i),this._object.quaternion.copy(n).multiply(hn)):s&&r&&(this._object.position.copy(s),this._object.quaternion.copy(r).multiply(hn));as&&(s&&r&&(this._raySpaceObject?.position.copy(s),this._raySpaceObject?.quaternion.copy(r).multiply(hn)),i&&n&&(this._gripSpaceObject?.position.copy(i),this._gripSpaceObject?.quaternion.copy(n).multiply(hn)));const l=this.xr.context.mainCamera?.parent,c=l?Re(l):void 0;i&&n&&(this._gripWorldPosition.copy(i),l&&this._gripWorldPosition.applyMatrix4(l.matrixWorld),this._gripWorldQuaternion.copy(n),this._gripWorldQuaternion.multiply(hn),c&&this._gripWorldQuaternion.premultiply(c)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,as&&console.warn("Controller disconnected",this.index),this.cancelPinch(),this._selectIsActive&&(this._selectIsActive=!1,this._selectCompleted=!1,this.emitPointerEvent(Te.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,null,void 0,!0)),this._squeezeIsActive&&(this._squeezeIsActive=!1,this._squeezeCompleted=!1,this.emitPointerEvent(Te.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,null,void 0,!0));for(const e of this._object.children)this.xr.context.scene.attach(e);this._object?.removeFromParent(),this._debugAxesHelper?.removeFromParent(),this._debugGripAxesHelper?.removeFromParent(),this._debugRayAxesHelper?.removeFromParent(),this._gripSpaceObject?.removeFromParent(),this._raySpaceObject?.removeFromParent(),this.unsubscribeEvents(),this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}getButton(e){if(!this._layout)return;switch(e){case"primary-button":if(this.isLeft)e="x-button";else if(this.isRight)e="a-button";else return;break;case"primary":return this.hand?this.getGesture("pinch"):this.toNeedleGamepadButton(0,e);case"xr-standard-trigger":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(0,e);break;case"xr-standard-squeeze":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(1,e);break;case"xr-standard-thumbstick":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(3,e);break}if(this._buttonMap.has(e))return this.toNeedleGamepadButton(this._buttonMap.get(e),e);const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"button":case"squeeze":if(this.inputSource.gamepad){const i=t.gamepadIndices.button;return this._buttonMap.set(e,i),this.toNeedleGamepadButton(i,e)}break;default:console.warn("Unsupported component type",t.type);break}this._buttonMap.set(e,void 0)}getGesture(e){const t=this.states[e];if(!t)return null;this.states[e]=t;const i=this._needleGamepadButtons[e]||new I1(void 0,e);return i.pressed=t.pressed,i.value=t.value,i.isDown=t.isDown,i.isUp=t.isUp,this._needleGamepadButtons[e]=i,i}getPointerId(e){if((e==="primary"||e==="pinch")&&(e=0),typeof e!="number"){const t=this._buttonMap.get(e);if(t===void 0)return;e=t}return this.index*10+e}_needleGamepadButtons={};toNeedleGamepadButton(e,t){if(!this.inputSource.gamepad?.buttons)return;const i=this.inputSource.gamepad?.buttons[e],n=this.states[e],s=this._needleGamepadButtons[e]||new I1(e,t);return i&&(s.pressed=i.pressed,s.value=i.value,s.touched=i.touched),n&&(s.isDown=n.isDown,s.isUp=n.isUp),this._needleGamepadButtons[e]=s,s}getStick(e){if(!this._layout)return{x:0,y:0,z:0};if(this.isHand)return{x:0,y:0,z:0};e==="primary"&&this._layout.components["xr-standard-thumbstick"]&&(e="xr-standard-thumbstick");const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"thumbstick":case"touchpad":if(this.inputSource.gamepad){const i=t.gamepadIndices.xAxis,n=t.gamepadIndices.yAxis;let s=this.inputSource.gamepad.axes[i]||0,r=this.inputSource.gamepad.axes[n]||0;s*=-1,r*=-1;const a=t.gamepadIndices.button,l=this.inputSource.gamepad?.buttons[a]?.value||0;return{x:s,y:r,z:l}}}return{x:0,y:0,z:0}}_buttonMap=new Map;_motioncontroller;_layout;getMotionController;initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),this._isMetaQuestTouchController=this.profiles.includes("meta-quest-touch-plus")||this.profiles.includes("oculus-touch-v3"),this._isMxInk=this.profiles.includes("logitech-mx-ink"),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=bR(this.inputSource,c2,h2);this.getMotionController=e.then(t=>{if(!this.connected)return null;this._motioncontroller=new _R(this.inputSource,t.profile,t.assetPath||"");const i=t.profile.layouts[this.inputSource.handedness];if(this._layout=i,this._layout){if(!this._layout.gamepad?.length){this._layout.gamepad=[];for(const n in this._layout.components){const s=this._layout.components[n];this._layout.gamepad[s.gamepadIndices.button]=n}}this.profiles.length>=1&&this.profiles[0]==="htc-vive-focus-plus"&&this.inputSource.gamepad&&this.inputSource.gamepad.axes.length===4&&!this._layout.components["xr-standard-thumbstick"]&&(this._layout.components["xr-standard-thumbstick"]={type:"thumbstick",gamepadIndices:{xAxis:2,yAxis:3}})}return this._motioncontroller}).catch(t=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,t),null))}}emitPointerDownEvent=!0;emitPointerUpEvent=!0;emitPointerMoveEvent=!0;pointerMoveDistanceThreshold=.03;pointerMoveAngleThreshold=.05;subscribeEvents(){this.xr.session.addEventListener("selectstart",this.onSelectStart),this.xr.session.addEventListener("select",this.onSelect),this.xr.session.addEventListener("selectend",this.onSelectEnd),this.xr.session.addEventListener("squeezestart",this.onSqueezeStart),this.xr.session.addEventListener("squeeze",this.onSqueeze),this.xr.session.addEventListener("squeezeend",this.onSqueezeEnd)}unsubscribeEvents(){this.xr.session.removeEventListener("selectstart",this.onSelectStart),this.xr.session.removeEventListener("select",this.onSelect),this.xr.session.removeEventListener("selectend",this.onSelectEnd),this.xr.session.removeEventListener("squeezestart",this.onSqueezeStart),this.xr.session.removeEventListener("squeeze",this.onSqueeze),this.xr.session.removeEventListener("squeezeend",this.onSqueezeEnd)}_selectButtonIndex=void 0;_squeezeButtonIndex=void 0;_selectIsActive=!1;_squeezeIsActive=!1;_selectCompleted=!1;_squeezeCompleted=!1;onSelectStart=e=>{if(!this.emitPointerDownEvent||this.inputSource!==e.inputSource)return;this.onUpdateFrame(e.frame),this._hasSelectEvent=!0;const t=this._layout?.selectComponentId,i=this._layout?.components[t]?.gamepadIndices?.button;i!==void 0&&(this._selectButtonIndex=i),this._selectIsActive=!0,!_p&&(as&&F.DrawDirection(this.rayWorldPosition,U(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this._selectCompleted=!1,this.emitPointerEvent(Te.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSelect=e=>{this.inputSource===e.inputSource&&(this._selectCompleted=!0)};onSelectEnd=e=>{if(!this.emitPointerUpEvent||_p||this.inputSource!==e.inputSource)return;this._selectIsActive=!1;const t=!this._selectCompleted;this._selectCompleted=!1,this.emitPointerEvent(Te.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,e,void 0,t)};onSqueezeStart=e=>{this.emitPointerDownEvent&&this.inputSource===e.inputSource&&(this._squeezeButtonIndex=this._layout?.components["xr-standard-squeeze"]?.gamepadIndices?.button,this._squeezeButtonIndex!==void 0&&(as&&F.DrawDirection(this.rayWorldPosition,U(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this._squeezeIsActive=!0,this._squeezeCompleted=!1,this.emitPointerEvent(Te.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)))};onSqueeze=e=>{this.inputSource===e.inputSource&&(this._squeezeCompleted=!0)};onSqueezeEnd=e=>{if(this.emitPointerUpEvent&&this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0){this._squeezeIsActive=!1;const t=!this._squeezeCompleted;this._squeezeCompleted=!1,this.emitPointerEvent(Te.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e,void 0,t)}};states={};cancelPinch(){const e=this.states.pinch;e?.pressed&&(e.isDown=!1,e.isUp=!0,e.pressed=!1,this.states.pinch=e,this.emitPointerEvent(Te.PointerUp,0,"pinch",!1,null,0,!0))}updateInputEvents(){if(this.gamepad?.buttons){for(let e=0;e<this.gamepad.buttons.length;e++){const t=this.gamepad.buttons[e],i=this.states[e]||new A1;let n=null;this._isMxInk&&(e===4||e===5)?(t.value>0&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):t.value===0&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):i.pressed&&(n="pointermove",i.isDown=!1,i.isUp=!1),i.pressed=t.value>0,i.value=t.value):(t.pressed&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):!t.pressed&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):(i.isDown=!1,i.isUp=!1),i.pressed=t.pressed,i.value=t.value),this.states[e]=i;const s=e!==this._selectButtonIndex&&e!==this._squeezeButtonIndex;if(n!=null&&s){let r=this._layout?.gamepad[e];this._isMxInk&&e===4&&(r="stylus-touch"),this._isMxInk&&e===5&&(r="stylus-tip"),(as||_p)&&console.log("Emitting pointer event",n,e,r,t.value,this.gamepad,this._layout),this.emitPointerEvent(n,e,r??"none",!1,null,t.value)}}if(this._isMetaQuestTouchController){const e=this.gamepad.buttons.length-1,t=this.states[e];if(t&&t.isDown){const i=this.context.menu;i.spatialMenuIsVisible?i.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const e=this.handObject;if(!e){this.cancelPinch();return}const t=e.joints["index-finger-tip"],i=e.joints["thumb-tip"];if(t&&i&&(!t.visible||!i.visible)){this.cancelPinch();return}if(t&&i){const n=t.position.distanceTo(i.position);this._pinchPosition.lerpVectors(t.position,i.position,.5);const s=this.xr.context.mainCamera?.parent;if(s&&this._pinchPosition.applyMatrix4(s.matrixWorld),n!==0){const r=this.states.pinch||new A1,a=(.02+.01)*1.5;r.value=1-(n-.02)/a;const l=n<.02-.01,c=n>.02+.01;l&&!r.pressed?(_p&&console.log("pinch start",n),r.isDown=!0,r.isUp=!1,r.pressed=!0):c&&r.pressed?(r.isDown=!1,r.isUp=!0,r.pressed=!1):(r.isDown=!1,r.isUp=!1),this.states.pinch=r}}}}_didMoveLastFrame=!1;_lastPointerMovePosition=new v;_lastPointerMoveQuaternion=new B;onUpdateMove(){if(!this.emitPointerMoveEvent)return;let e=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(e=!0),e||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(e=!0),e){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),as&&F.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let t=this.xr.context.input.getFirstPressedButtonForPointer(this.index);t===void 0&&(t=0);const i=this.gamepad?.buttons[t]?.value;this.emitPointerEvent("pointermove",t,"none",!1,null,i)}else this._didMoveLastFrame=!1}pointerInit;emitPointerEvent(e,t,i,n,s=null,r,a=!1){if(!this.emitEvents){as&&e!==Te.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,e,t);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.getPointerId(t),this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=t,this.pointerInit.buttonName=i,this.pointerInit.isPrimary=n,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=r,this.pointerInit.clientX=this._rayPosition.x/this.xr.rigScale,this.pointerInit.clientY=this._rayPosition.y/this.xr.rigScale,this.pointerInit.clientZ=this._rayPosition.z/this.xr.rigScale,this.pointerInit.cancelled=a;const l=Q.Current;Q.Current=this.xr.context,as&&e!=="pointermove"&&console.warn("Pointer event",e,t,i,{...this.pointerInit}),this.xr.context.input.createInputEvent(new os(e,s,this.pointerInit)),Q.Current=l}}}class A1{isDown=!1;isUp=!1;pressed=!1;value=0}class I1{index;name;touched=!1;pressed=!1;value=0;isDown=!1;isUp=!1;constructor(e,t){this.index=e,this.name=t}}const xh=x("debugwebxr");class Gy{controllerStates=[];userId;context;userStateEvtName;constructor(e,t){this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}onReceivedControllerState=e=>{xh&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);for(let t=0;t<this.controllerStates.length;t++)if(this.controllerStates[t].handedness===e.handedness){this.controllerStates[t]=e;return}this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];e.controllers.some(n=>n.side===i.handedness)||(xh&&console.log(`XRSync: ${i.type} ${i.handedness} removed`),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateHandednessState(t.side,e)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateHandednessState(e,t){let i=!1,n,s=!1;for(const a of t.controllers){if(a.side!==e)continue;s=!0;const l=a.hand?"hand":"controller";a.isTracking?(i=!0,n=l):n===void 0&&(n=l)}if(!s)return;const r=this.controllerStates.find(a=>a.handedness===e);if(r)(r.isTracking!==i||r.type!==n)&&(r.isTracking=i,r.type=n,this.context.connection.send(this.userStateEvtName,r));else{const a={guid:this.userId+"-"+e,isTracking:i,handedness:e,type:n};this.controllerStates.push(a),this.context.connection.send(this.userStateEvtName,a),xh&&console.log(`XRSync: ${a.type} ${a.handedness} added`)}}}class L1{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);if(i)return i.controllerStates.some(n=>n.handedness===t&&n.isTracking)}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?(i.controllerStates.find(n=>n.handedness===t&&n.isTracking)??i.controllerStates.find(n=>n.handedness===t))?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(se.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(se.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(se.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(se.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(xh&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Gy(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Gy(e,this.context))}};onLeftRoom=()=>{this.context.connection.connectionId&&(this._states.has(this.context.connection.connectionId)||(this._states.get(this.context.connection.connectionId)?.dispose(),this._states.delete(this.context.connection.connectionId)))};onOtherUserJoinedRoom=e=>{const t=e.userId;this._states.has(t)||(xh&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new Gy(t,this.context)))};onOtherUserLeftRoom=e=>{const t=e.userId;this._states.has(t)||(this._states.get(t)?.dispose(),this._states.delete(t))};_states=new Map;onUpdate(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.update(e)}onExitXR(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.onExitXR(e)}}class D1{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new Ie({color:0,transparent:!0,depthTest:!1,fog:!1,side:Bi}),this._fadeToColorQuad=new V(new In(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const s=this._requestedFadeValue;n.opacity=j.lerp(n.opacity,s,t/.03),Math.abs(n.opacity-s)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}const p2='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',m2=btoa(p2),g2="data:image/svg+xml;base64,"+m2,Ol=g2,f2=`<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" version="1.1" viewBox="0 0 1014 282" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m665.95 132.73v44.88l-10.56-8.4c-0.8-0.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18 0.4-6.06 1.2s-3.54 1.8-4.98 3-2.56 2.5-3.36 3.9-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c0.32 0.24 0.56 0.44 0.72 0.6s0.36 0.32 0.6 0.48c0.96-1.2 2.14-2.28 3.54-3.24s2.92-1.76 4.56-2.4 3.34-1.14 5.1-1.5 3.44-0.54 5.04-0.54c1.44 0 2.92 0.04 4.44 0.12s2.84 0.28 3.96 0.6c4.56 1.12 7.8 3.12 9.72 6s2.88 6.56 2.88 11.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m732.38 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m795.93 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m858.57 97.21c0.64 0.48 0.96 1.16 0.96 2.04v74.88c-0.08 1.04-0.12 2.12-0.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18s-2.06-1.66-2.46-1.98c-1.76 2.48-4.26 4.44-7.5 5.88s-7.02 2.16-11.34 2.16c-3.84 0-7.4-0.7-10.68-2.1s-6.14-3.44-8.58-6.12-4.34-5.94-5.7-9.78-2.04-8.16-2.04-12.96c0-4.32 0.78-8.34 2.34-12.06s3.6-6.92 6.12-9.6 5.38-4.78 8.58-6.3 6.48-2.28 9.84-2.28c2.56 0 4.82 0.22 6.78 0.66s3.68 1.06 5.16 1.86 2.78 1.74 3.9 2.82 2.16 2.22 3.12 3.42v-35.04l10.68 8.64zm-27.96 67.92c3.6 0 6.52-0.68 8.76-2.04s3.98-3.06 5.22-5.1 2.1-4.22 2.58-6.54 0.72-4.44 0.72-6.36v-1.2c0-1.12-0.22-2.7-0.66-4.74s-1.28-4.06-2.52-6.06-3-3.7-5.28-5.1-5.22-2.02-8.82-1.86c-3.44 0-6.26 0.74-8.46 2.22s-3.96 3.26-5.28 5.34-2.24 4.2-2.76 6.36-0.78 3.92-0.78 5.28c0 1.84 0.24 3.92 0.72 6.24s1.36 4.48 2.64 6.48 3.04 3.68 5.28 5.04 5.12 2.04 8.64 2.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m882.81 97.09c0.64 0.48 0.96 1.12 0.96 1.92l-0.12 41.04v37.08l-10.56-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-77.88l10.8 8.64z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m950.36 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.8559 0 0 .7642 45.348 36.475)"> <g transform="translate(2.7114)"> <path d="m3.935 173.02c-0.331 0-0.497-0.402-0.497-1.207v-51.002c0-0.738 0.138-1.107 0.414-1.107h1.781c0.277 0 0.415 0.335 0.415 1.006v5.935c0 0.336 0.027 0.553 0.083 0.654 0.055 0.101 0.151-0.017 0.289-0.352 0.912-1.744 1.754-3.236 2.527-4.477 0.773-1.24 1.554-2.179 2.341-2.816s1.65-0.956 2.588-0.956c1.685 0 3.011 0.922 3.977 2.766 0.967 1.845 1.602 3.84 1.905 5.986 0.056 0.268 0.139 0.369 0.249 0.302s0.221-0.235 0.331-0.503c0.939-1.811 1.802-3.353 2.589-4.628 0.787-1.274 1.581-2.246 2.382-2.917s1.671-1.006 2.61-1.006c2.016 0 3.569 1.392 4.66 4.175 1.09 2.783 1.636 6.421 1.636 10.915v37.925c0 0.871-0.18 1.307-0.539 1.307h-1.739c-0.138 0-0.249-0.1-0.332-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.338-6.321-1.015-8.3-0.676-1.978-1.76-2.967-3.251-2.967-0.884 0-1.726 0.386-2.527 1.157s-1.519 1.727-2.154 2.867-1.201 2.213-1.699 3.219c-0.248 0.469-0.421 0.905-0.517 1.308-0.097 0.402-0.145 0.972-0.145 1.71v37.221c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.166 0-0.29-0.1-0.373-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.332-6.321-0.994-8.3-0.663-1.978-1.754-2.967-3.273-2.967-1.242 0-2.375 0.704-3.396 2.112-1.022 1.409-2.223 3.555-3.604 6.439v39.031c0 0.805-0.18 1.207-0.539 1.207h-1.698z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m53.642 166.28c-1.077 2.549-2.237 4.477-3.479 5.785-1.243 1.307-2.61 1.961-4.101 1.961-2.154 0-3.853-1.324-5.095-3.973-1.243-2.649-1.864-6.187-1.864-10.613 0-3.488 0.4-6.489 1.201-9.004s1.988-4.51 3.562-5.985c1.574-1.476 3.521-2.414 5.841-2.817l3.686-0.704c0.221-0.067 0.394-0.218 0.518-0.453 0.124-0.234 0.187-0.587 0.187-1.056v-2.917c0-3.89-0.504-6.975-1.512-9.255s-2.354-3.42-4.039-3.42c-1.298 0-2.472 0.72-3.521 2.162s-2.002 3.572-2.858 6.388c-0.083 0.268-0.159 0.453-0.228 0.554-0.069 0.1-0.172 0.083-0.311-0.051l-1.698-1.71c-0.083-0.134-0.138-0.285-0.166-0.453-0.027-0.167 0.014-0.452 0.125-0.855 0.856-3.353 2.009-6.052 3.459-8.098 1.449-2.045 3.224-3.068 5.322-3.068 1.74 0 3.211 0.687 4.412 2.062s2.112 3.37 2.734 5.986c0.621 2.615 0.932 5.7 0.932 9.255v35.712c0 0.536-0.035 0.888-0.104 1.056s-0.2 0.251-0.393 0.251h-1.533c-0.166 0-0.29-0.117-0.373-0.352-0.083-0.234-0.124-0.553-0.124-0.955l-0.083-5.231c-0.055-0.939-0.221-1.006-0.497-0.202zm0.456-19.314c0-1.14-0.194-1.643-0.58-1.509l-3.107 0.603c-1.436 0.202-2.686 0.638-3.749 1.308-1.063 0.671-1.953 1.543-2.671 2.616s-1.257 2.33-1.616 3.772-0.538 3.102-0.538 4.98c0 3.152 0.455 5.616 1.367 7.393 0.911 1.778 2.14 2.666 3.686 2.666 0.939 0 1.85-0.419 2.734-1.257s1.671-1.895 2.361-3.169c0.663-1.408 1.181-2.85 1.553-4.326 0.373-1.475 0.56-2.883 0.56-4.225v-8.852z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m79.034 173.02c-0.166 0-0.297-0.117-0.394-0.352-0.096-0.234-0.145-0.553-0.145-0.955v-4.628c0-0.536-0.041-0.838-0.124-0.905s-0.207 0.1-0.373 0.503c-0.276 0.67-0.69 1.593-1.242 2.766-0.553 1.174-1.271 2.23-2.154 3.169-0.884 0.939-1.961 1.408-3.231 1.408-1.74 0-3.314-0.989-4.722-2.967-1.409-1.979-2.534-4.963-3.376-8.953-0.843-3.991-1.264-8.937-1.264-14.838 0-5.701 0.415-10.68 1.243-14.939s1.988-7.595 3.479-10.009c1.492-2.415 3.204-3.622 5.137-3.622 1.436 0 2.616 0.57 3.541 1.71 0.926 1.14 1.719 2.381 2.382 3.722 0.249 0.47 0.414 0.637 0.497 0.503s0.125-0.536 0.125-1.207v-23.841c0-0.805 0.151-1.208 0.455-1.208h1.864c0.276 0 0.414 0.369 0.414 1.107v72.128c0 0.537-0.041 0.905-0.124 1.107-0.083 0.201-0.235 0.301-0.455 0.301h-1.533zm-0.621-42.049c-0.939-2.213-1.885-3.94-2.838-5.181s-2.009-1.861-3.169-1.861c-1.463 0-2.768 0.889-3.914 2.666s-2.044 4.376-2.693 7.796-0.973 7.578-0.973 12.474c0 5.097 0.338 9.272 1.015 12.524 0.676 3.253 1.567 5.651 2.672 7.193 1.104 1.543 2.305 2.314 3.603 2.314 1.188 0 2.258-0.704 3.211-2.113 0.952-1.408 1.705-3.118 2.257-5.13s0.829-3.957 0.829-5.835v-24.847z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m89.514 149.38c0 3.42 0.345 6.606 1.035 9.557 0.691 2.951 1.609 5.315 2.755 7.092s2.437 2.666 3.873 2.666c1.519 0 2.837-0.738 3.956-2.213 1.118-1.476 2.064-3.655 2.837-6.539 0.083-0.336 0.166-0.52 0.249-0.554 0.083-0.033 0.179 0.017 0.29 0.151l1.408 1.912c0.221 0.268 0.235 0.67 0.041 1.207-0.69 2.548-1.47 4.661-2.34 6.337-0.87 1.677-1.857 2.935-2.962 3.773-1.104 0.838-2.319 1.257-3.645 1.257-2.043 0-3.838-1.14-5.385-3.42-1.546-2.28-2.761-5.482-3.645-9.607-0.884-4.124-1.325-8.836-1.325-14.134 0-5.901 0.455-10.931 1.367-15.089 0.911-4.158 2.14-7.377 3.686-9.658 1.547-2.28 3.3-3.42 5.261-3.42 1.988 0 3.714 1.073 5.178 3.219 1.463 2.146 2.595 5.231 3.396 9.255s1.201 8.886 1.201 14.587c0 0.469-0.02 0.939-0.062 1.408-0.041 0.469-0.214 0.704-0.517 0.704h-16.362c-0.083 0-0.152 0.151-0.207 0.453-0.056 0.302-0.083 0.654-0.083 1.056zm13.752-6.237c0.304 0 0.497-0.1 0.58-0.302 0.083-0.201 0.124-0.57 0.124-1.106 0-3.219-0.283-6.187-0.849-8.903s-1.367-4.896-2.402-6.539c-1.036-1.643-2.272-2.464-3.708-2.464-1.629 0-2.996 0.955-4.101 2.867-1.104 1.911-1.94 4.342-2.506 7.293s-0.849 6.002-0.849 9.154h13.711z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m148.54 119.7c0.165 0 0.283 0.117 0.352 0.352s0.076 0.52 0.02 0.855l-6.254 50.902c-0.028 0.47-0.104 0.788-0.228 0.956s-0.297 0.251-0.518 0.251h-1.615c-0.442 0-0.718-0.402-0.829-1.207l-5.26-40.138c-0.111-0.604-0.201-0.905-0.27-0.905s-0.131 0.301-0.186 0.905l-5.012 40.138c-0.028 0.47-0.097 0.788-0.207 0.956-0.111 0.168-0.277 0.251-0.497 0.251h-1.74c-0.442 0-0.718-0.402-0.829-1.207l-6.503-50.801c-0.055-0.403-0.048-0.721 0.021-0.956s0.2-0.352 0.393-0.352h1.823c0.166 0 0.297 0.067 0.393 0.201 0.097 0.134 0.159 0.403 0.187 0.805l5.302 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.219-41.949c0.055-0.268 0.124-0.47 0.207-0.604s0.193-0.201 0.331-0.201h1.533c0.138 0 0.262 0.067 0.373 0.201 0.11 0.134 0.179 0.403 0.207 0.805l5.468 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.053-41.849c0.055-0.335 0.138-0.57 0.249-0.704 0.11-0.134 0.234-0.201 0.373-0.201h1.284z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m156.49 171.51c0 0.604-0.042 1.006-0.125 1.208-0.082 0.201-0.262 0.301-0.538 0.301h-1.533c-0.221 0-0.366-0.083-0.435-0.251s-0.103-0.486-0.103-0.956v-50.902c0-0.805 0.152-1.207 0.456-1.207h1.822c0.304 0 0.456 0.402 0.456 1.207v50.6zm0.165-63.979c0 1.207-0.207 1.811-0.621 1.811h-1.905c-0.221 0-0.366-0.135-0.435-0.403s-0.104-0.67-0.104-1.207v-7.847c0-1.006 0.18-1.509 0.539-1.509h1.988c0.359 0 0.538 0.47 0.538 1.409v7.746z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m168.3 124.83c-0.221 0-0.331 0.269-0.331 0.805v33.801c0 3.42 0.221 5.667 0.663 6.74 0.441 1.073 1.09 1.609 1.946 1.609h3.024c0.138 0 0.242 0.084 0.311 0.252 0.069 0.167 0.103 0.419 0.103 0.754v2.716c0 0.537-0.138 0.906-0.414 1.107-0.248 0.067-0.614 0.134-1.098 0.201-0.483 0.067-0.959 0.118-1.429 0.151-0.469 0.034-0.828 0.05-1.077 0.05-1.712 0-2.934-0.955-3.665-2.867-0.732-1.911-1.098-5.013-1.098-9.305v-35.108c0-0.604-0.124-0.906-0.373-0.906h-3.521c-0.248 0-0.373-0.268-0.373-0.804v-3.521c0-0.537 0.111-0.805 0.332-0.805h3.686c0.166 0 0.263-0.268 0.29-0.805l0.415-16.095c0-0.805 0.124-1.207 0.372-1.207h1.492c0.303 0 0.455 0.436 0.455 1.307v15.995c0 0.537 0.097 0.805 0.29 0.805h5.468c0.221 0 0.331 0.268 0.331 0.805v3.521c0 0.536-0.124 0.804-0.373 0.804h-5.426z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m179.4 173.02c-0.331 0-0.497-0.402-0.497-1.207v-72.329c0-0.738 0.138-1.107 0.414-1.107h1.782c0.276 0 0.414 0.336 0.414 1.006v27.162c0 0.335 0.034 0.536 0.103 0.603s0.159-0.033 0.27-0.302c0.994-1.81 1.898-3.319 2.713-4.526 0.814-1.208 1.629-2.113 2.444-2.717 0.814-0.603 1.691-0.905 2.63-0.905 2.182 0 3.839 1.375 4.971 4.125 1.132 2.749 1.698 6.404 1.698 10.965v37.925c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.165 0-0.29-0.1-0.373-0.301-0.082-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.366-6.321-1.097-8.3-0.732-1.978-1.899-2.967-3.501-2.967-0.883 0-1.705 0.318-2.464 0.956-0.76 0.637-1.526 1.576-2.299 2.816-0.773 1.241-1.643 2.834-2.61 4.779v39.031c0 0.805-0.179 1.207-0.538 1.207h-1.699z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> </g> <g transform="matrix(.80638 0 0 .80638 452.53 65.421)" fill-rule="nonzero"> <path d="m79.32 36.98v150.76l15.68-13.2 6.59-156.31-22.27 18.75z" fill="url(#f)"/> <path d="m79.32 36.98-22.27-18.75 6.59 156.31 15.68 13.2v-150.76z" fill="url(#e)"/> <path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z" fill="url(#d)"/> <path d="m25.19 104.83-25.19-14.59 16.97 53.86 16.85 9.77-8.63-49.04z" fill="url(#c)"/> <path d="M43.86,82.5L18.69,67.98L0,90.24L25.18,104.83L43.86,82.5Z" fill="#9c3"/> <path d="m134.82 78.69-9.97 56.5 15.58-9.04 19.57-62.05-25.18 14.59z" fill="url(#b)"/> <path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z" fill="url(#a)"/> <path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33 25.19-14.59z" fill="#ffe113"/> <path d="M101.59,18.23L79.32,0L57.05,18.23L79.32,36.98L101.59,18.23Z" fill="#f3e600"/> </g> <defs> <linearGradient id="f" x2="1" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)" gradientUnits="userSpaceOnUse"><stop stop-color="#62d399" offset="0"/><stop stop-color="#acd842" offset=".51"/><stop stop-color="#d7db0a" offset=".9"/><stop stop-color="#d7db0a" offset="1"/></linearGradient> <linearGradient id="e" x2="1" gradientTransform="matrix(-1.6,-162.13,162.13,-1.6,69.68,178.9)" gradientUnits="userSpaceOnUse"><stop stop-color="#0ba398" offset="0"/><stop stop-color="#4ca352" offset=".5"/><stop stop-color="#76a30a" offset="1"/></linearGradient> <linearGradient id="d" x2="1" gradientTransform="matrix(-1.9,-67.98,67.98,-1.9,36.6,152.17)" gradientUnits="userSpaceOnUse"><stop stop-color="#36a382" offset="0"/><stop stop-color="#36a382" offset=".19"/><stop stop-color="#49a459" offset=".54"/><stop stop-color="#76a30b" offset="1"/></linearGradient> <linearGradient id="c" x2="1" gradientTransform="matrix(2.18,-62.38,62.38,2.18,15.82,153.24)" gradientUnits="userSpaceOnUse"><stop stop-color="#267880" offset="0"/><stop stop-color="#457a5c" offset=".51"/><stop stop-color="#717516" offset="1"/></linearGradient> <linearGradient id="b" x2="1" gradientTransform="matrix(13.85,-71.96,71.96,13.85,135.08,135.43)" gradientUnits="userSpaceOnUse"><stop stop-color="#b0d939" offset="0"/><stop stop-color="#eadb04" offset="1"/></linearGradient> <linearGradient id="a" x2="1" gradientTransform="matrix(26.159 -64.737 64.737 26.159 107.42 128.14)" gradientUnits="userSpaceOnUse"><stop stop-color="#74af52" offset="0"/><stop stop-color="#74af52" offset=".17"/><stop stop-color="#99be32" offset=".48"/><stop stop-color="#c0c40a" offset="1"/></linearGradient> </defs> </svg>`;btoa(f2);const y2='<svg viewBox="0 0 509 154" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M665.95 132.73v44.88l-10.56-8.4c-.8-.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18.4-6.06 1.2-1.88.8-3.54 1.8-4.98 3-1.44 1.2-2.56 2.5-3.36 3.9-.8 1.4-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-.72-.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c.32.24.56.44.72.6.16.16.36.32.6.48.96-1.2 2.14-2.28 3.54-3.24 1.4-.96 2.92-1.76 4.56-2.4 1.64-.64 3.34-1.14 5.1-1.5 1.76-.36 3.44-.54 5.04-.54 1.44 0 2.92.04 4.44.12 1.52.08 2.84.28 3.96.6 4.56 1.12 7.8 3.12 9.72 6 1.92 2.88 2.88 6.56 2.88 11.04ZM732.38 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM795.93 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM858.57 97.21c.64.48.96 1.16.96 2.04v74.88c-.08 1.04-.12 2.12-.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18-1.24-1-2.06-1.66-2.46-1.98-1.76 2.48-4.26 4.44-7.5 5.88-3.24 1.44-7.02 2.16-11.34 2.16-3.84 0-7.4-.7-10.68-2.1-3.28-1.4-6.14-3.44-8.58-6.12-2.44-2.68-4.34-5.94-5.7-9.78-1.36-3.84-2.04-8.16-2.04-12.96 0-4.32.78-8.34 2.34-12.06 1.56-3.72 3.6-6.92 6.12-9.6 2.52-2.68 5.38-4.78 8.58-6.3 3.2-1.52 6.48-2.28 9.84-2.28 2.56 0 4.82.22 6.78.66 1.96.44 3.68 1.06 5.16 1.86s2.78 1.74 3.9 2.82a35.92 35.92 0 0 1 3.12 3.42V88.57l10.68 8.64Zm-27.96 67.92c3.6 0 6.52-.68 8.76-2.04 2.24-1.36 3.98-3.06 5.22-5.1a20.5 20.5 0 0 0 2.58-6.54c.48-2.32.72-4.44.72-6.36v-1.2c0-1.12-.22-2.7-.66-4.74-.44-2.04-1.28-4.06-2.52-6.06s-3-3.7-5.28-5.1c-2.28-1.4-5.22-2.02-8.82-1.86-3.44 0-6.26.74-8.46 2.22-2.2 1.48-3.96 3.26-5.28 5.34-1.32 2.08-2.24 4.2-2.76 6.36-.52 2.16-.78 3.92-.78 5.28 0 1.84.24 3.92.72 6.24.48 2.32 1.36 4.48 2.64 6.48s3.04 3.68 5.28 5.04c2.24 1.36 5.12 2.04 8.64 2.04ZM882.81 97.09c.64.48.96 1.12.96 1.92l-.12 41.04v37.08l-10.56-8.4c-.72-.64-1.08-1.44-1.08-2.4V88.45l10.8 8.64ZM950.36 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14Z" style="fill-rule:nonzero" transform="translate(-452.406 -63.709) scale(1.00797)"/><path d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75Z" style="fill:url(#a);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98Z" style="fill:url(#b);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33Z" style="fill:url(#c);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04Z" style="fill:url(#d);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5Z" style="fill:#9c3;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59Z" style="fill:url(#e);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5Z" style="fill:url(#f);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1Z" style="fill:#ffe113;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75Z" style="fill:#f3e600;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><defs><linearGradient id="a" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)"><stop offset="0" style="stop-color:#62d399;stop-opacity:1"/><stop offset=".51" style="stop-color:#acd842;stop-opacity:1"/><stop offset=".9" style="stop-color:#d7db0a;stop-opacity:1"/><stop offset="1" style="stop-color:#d7db0a;stop-opacity:1"/></linearGradient><linearGradient id="b" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-90.565 123.412 54.953) scale(162.14)"><stop offset="0" style="stop-color:#0ba398;stop-opacity:1"/><stop offset=".5" style="stop-color:#4ca352;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30a;stop-opacity:1"/></linearGradient><linearGradient id="c" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="scale(-68) rotate(88.4 .881 -1.396)"><stop offset="0" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".19" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".54" style="stop-color:#49a459;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30b;stop-opacity:1"/></linearGradient><linearGradient id="d" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-88 87.255 68.431) scale(62.42)"><stop offset="0" style="stop-color:#267880;stop-opacity:1"/><stop offset=".51" style="stop-color:#457a5c;stop-opacity:1"/><stop offset="1" style="stop-color:#717516;stop-opacity:1"/></linearGradient><linearGradient id="e" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-79.1 149.53 -14.065) scale(73.28)"><stop offset="0" style="stop-color:#b0d939;stop-opacity:1"/><stop offset="1" style="stop-color:#eadb04;stop-opacity:1"/></linearGradient><linearGradient id="f" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-67.997 148.705 -15.558) scale(69.8226)"><stop offset="0" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".17" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".48" style="stop-color:#99be32;stop-opacity:1"/><stop offset="1" style="stop-color:#c0c40a;stop-opacity:1"/></linearGradient></defs></svg>',b2=btoa(y2),_2="data:image/svg+xml;charset=utf-8;base64,"+b2,j1=_2;class Uc{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t).catch(n=>{console.error("Failed to start temporary XR session:",n)});return i?(i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new Uc(e,t,i),this._active):(i.end(),null)):(this._requestInFlight=!1,null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await es(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}get isVR(){return this._mode==="immersive-vr"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new Dr({alpha:!0,antialias:!0}),this._renderer.outputColorSpace="srgb",this._renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),this._renderer.setSize(window.innerWidth,window.innerHeight,!0),I.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const n=Math.min(2,window.devicePixelRatio),s=Math.floor(window.innerWidth*n),r=Math.floor(window.innerHeight*n);this._renderer.domElement.width=s,this._renderer.domElement.height=r}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new me,this._scene=new Fi,this._scene.fog=new Tv(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;_frames=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera),this._lastTime=e,this._frames++};_roomFlyObjects=[];_logoObject=null;get _logoDistance(){return this.isAR?.3:5}get _logoScale(){return this.isAR?.04:1}update(e,t){const i=e*4e-4;for(let r=0;r<this._roomFlyObjects.length;r++){const a=this._roomFlyObjects[r];a.position.y+=Math.sin(i+r*.5)*.005,a.rotateY(.002)}const n=this._logoObject,s=this._renderer.xr.getCamera();if(n){const r=new v;s.getWorldDirection(r);const a=s.position.clone().addScaledVector(r,this._logoDistance),l=this.isAR?.005:1e-5;n.position.lerp(a,this._frames<=2?1:t*l),n.lookAt(this._camera.position)}}async onBeforeHandoff(){await es(1e3),this._scene.clear()}setupScene(){this._scene.background=new oe(0);let e=Ol;if(cn()){const h=document.querySelector("needle-engine");if(h){const d=h.getAttribute("logo-src");d?.length&&(e=d,M()&&console.debug("[XR] Using custom loading logo from license:",e))}}const t=this._logoObject=new V(new In(1,1,1,1),new Ie({transparent:!0,side:2}));t.scale.multiplyScalar(this._logoScale*window.devicePixelRatio),t.renderOrder=1e3,t.material.opacity=0,this._scene.add(t);const i=document.createElement("canvas"),n=i.getContext("2d"),s=new Image,r=h=>{if(!n)return;t.material.opacity=1;const d=1024;i.width=d,i.height=d,n.imageSmoothingQuality="high";const u=d*.19,m=s.width/s.height;{const w=i.height-u*1.5,S=w*m,O=(i.width-S)/2;n.drawImage(s,O,0,S,w)}const g=d*.12,y="Loading...";n.shadowBlur=0,n.fillStyle=this.isAR?"white":"rgba(255,255,255,0.4)",n.font=`${g}px Arial`,n.shadowBlur=d*.02,n.shadowColor="rgba(0,0,0,0.5)",n.shadowOffsetX=0,n.shadowOffsetY=0;const b=n.measureText(y);n.fillText(y,i.width/2-b.width/2,i.height-u/4),n.font=`${g}px Arial`,n.fillText(y,i.width/2-b.width/2,i.height-u/4);const f=new jr().load(i.toDataURL());f.generateMipmaps=!0,f.colorSpace="srgb",f.anisotropy=4;const _=i.width/i.height;t.scale.x=this._logoScale*_*window.devicePixelRatio,t.scale.y=this._logoScale*window.devicePixelRatio,t.material.map=f,t.material.needsUpdate=!0};s.onload=()=>r(),s.onerror=h=>{console.error("Failed to load temporary XR logo:",e,h),s.src=Ol},s.crossOrigin="anonymous",s.src=e;const a=new lf(16777215,1);a.position.set(0,20,0),a.castShadow=!1,this._scene.add(a);const l=new lf(16777215,1);l.position.set(0,-1,0),l.castShadow=!1,this._scene.add(l);const c=new cf(16777215,1,100,1);if(c.position.set(0,2,0),c.castShadow=!1,c.distance=200,this._scene.add(c),this.isAR===!1)for(let h=0;h<100;h++){const d=new Mt({color:2236962,metalness:1,roughness:.8}),u=_l.Sphere,m=Gs.createPrimitive(u,{material:d});m.position.x=j.random(-50,50),m.position.y=j.random(-2,50),m.position.z=j.random(-50,50),m.rotation.x=j.random(0,Math.PI*2),m.rotation.y=j.random(0,Math.PI*2),m.rotation.z=j.random(0,Math.PI*2),m.scale.multiplyScalar(.5+Math.random()*10);const g=m.position.distanceTo(this._camera.position)-m.scale.x;g<10&&(m.position.z+=5,m.position.multiplyScalar(1+1/g)),this._roomFlyObjects.push(m),this._scene.add(m)}}}var Sh;(o=>{const e=[];function t(){e?.length||M()&&console.warn("No USDZ exporters found \u2013 cannot export USDZ for QuickLook.");for(const s of e)s.exportAndOpen();return!0}o.exportAndOpen=t;function i(s){e.push(s)}o.registerExporter=i;function n(s){if(!e)return;const r=e.indexOf(s);r>=0&&e.splice(r,1)}o.unregisterExporter=n})(Sh||(Sh={}));function F1(){try{const o=globalThis.document,e=o?.permissionsPolicy??o?.featurePolicy;if(e&&typeof e.allowsFeature=="function")return e.allowsFeature("xr-spatial-tracking")}catch{}return!0}const et=x("debugwebxr"),B1=x("stats");let Hy=0;function v2(o){let e=null;const t=o;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=o,e}w2();async function w2(){let o="immersive-vr";try{if(!F1())return;if(I.isNeedleAppClip())o="immersive-ar";else if(await navigator.xr?.isSessionSupported("immersive-vr")||(o="immersive-ar"),o==="immersive-ar"&&!await navigator.xr?.isSessionSupported("immersive-ar"))return}catch(e){console.debug("[NeedleXRSession:granted] Error while checking XR support:",e);return}if(x("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],ce.addContextCreatedCallback(async t=>{if(!e)return;dl(!0);const i=await e;if(i){const n=q.getDefaultSessionInit(o);q.setSession(o,i,n,t.context)}else console.error("[NeedleXRSession:granted] ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,i=t?JSON.parse(t):null;let n=null;if(U1()&&(await Uc.start(e||o,i||q.getDefaultSessionInit(o)).catch(s=>console.warn("[NeedleXRSession:granted] TemporaryXRContext start failed:",s)),await C2(),n=await Uc.handoff()),n)q.setSession(n.mode,n.session,n.init,Q.Current);else if(e&&t){console.log("[NeedleXRSession:granted] Restore last session");const s=JSON.parse(t);q.start(e,s).catch(r=>console.warn(r))}else q.start(o).catch(s=>console.warn("[NeedleXRSession:granted] failed:",s))},{once:!0})}}function x2(o,e){sessionStorage.setItem("needle_xr_session_mode",o),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function S2(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const qy=new Set;ce.registerCallback(de.ContextCreationStart,async o=>{qy.add(o.context)}),ce.registerCallback(de.ContextCreated,async o=>{qy.delete(o.context);const e=o.context?.domElement.getAttribute("autostart")||null;P2(e)});function U1(){return qy.size>0}function C2(){return new Promise(o=>{const e=Date.now(),t=setInterval(()=>{(!U1()||Date.now()-e>6e4)&&(clearInterval(t),o())},100)})}typeof window<"u"&&I.isDesktop()&&M()&&window.addEventListener("keydown",o=>{(o.key==="x"||o.key==="Escape")&&q.active&&q.stop()}),typeof document<"u"&&document.addEventListener("needlego-log",o=>{const e=o.detail;e?.m&&M()&&(e.l==="error"?ul(e.m):e.l==="warn"&&ge(e.m))});function P2(o){o&&o?.toLowerCase()==="ar"&&no.registerWaitForInteraction(()=>{q.start("ar")})}const vp=Symbol("initial-fov"),Xy=Symbol("initial-near");class q{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new L1(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static appClipBaseUrl="https://appclip.needle.tools/x/";static _appClipUrl=null;static get appClipUrl(){return this._appClipUrl}static set appClipUrl(e){if(!e){this._appClipUrl=null;return}const t=e.trim();this._appClipUrl=/^https?:\/\//i.test(t)?t:this.appClipBaseUrl+t.replace(/^\/+/,"")}static getAppClipLaunchUrl(){if(this._appClipUrl)return new URL(this._appClipUrl);const e=new URL("https://appclip.apple.com/id?p=tools.needle.launch-app.Clip");return e.searchParams.set("url",location.href),e}static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){this.ensureDeviceChangeInvalidation();const t=this._sessionSupportedCache[e];if(t!==void 0)return Promise.resolve(t);const i=this._sessionSupportedInFlight[e];if(i!==void 0)return i;const n=this.xrSystem;if(!n)return Promise.resolve(!1);let s;return F1()?s=n.isSessionSupported(e).catch(r=>(et&&console.error(r),!1)):(et&&console.warn("[WebXR] xr-spatial-tracking is not allowed in this document \u2014 reporting XR as unsupported. The embedding page/iframe must grant the policy."),s=Promise.resolve(!1)),this._sessionSupportedInFlight[e]=s,s.then(r=>{this._sessionSupportedCache[e]=r,delete this._sessionSupportedInFlight[e]}),s}static _sessionSupportedCache={};static _sessionSupportedInFlight={};static _deviceChangeHooked=!1;static ensureDeviceChangeInvalidation(){if(this._deviceChangeHooked)return;const e=this.xrSystem;if(e){this._deviceChangeHooked=!0;try{e.addEventListener?.("devicechange",()=>{this._sessionSupportedCache={},this._sessionSupportedInFlight={}})}catch{}}}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>q.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return I.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return I.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(t||(t={}),I.isiOS()){const l=this._sessionSupportedCache["immersive-ar"]??await this.isARSupported();if(I.isVisionOS()&&!l&&(e==="ar"||e==="immersive-ar")&&(e="quicklook"),e==="quicklook")return ct.sendEvent(Q.Current,"xr",{action:"quicklook_export",source:"NeedleXRSession.start"}),Sh.exportAndOpen(),null;if(!l&&(e==="immersive-ar"||e==="ar")){this.invokeSessionRequestStart("immersive-ar",t,i??Q.Current);const c=window.top||window,h=q.getAppClipLaunchUrl(),d=h.toString();ct.sendEvent(Q.Current,"xr",{action:"app_clip_launch",source:"NeedleXRSession.start",url:d,init:t?JSON.stringify(t):null});try{console.debug("iOS device detected - opening Needle App Clip for AR experience",{mode:e,init:t,url:h}),c.location.href=d}catch(u){console.warn(`Error navigating to AppClip ${d}
421
421
  `,u),window!==window.top?window.open(d,"_blank"):window.location.href=d}return setTimeout(()=>{this.invokeSessionRequestEnd("immersive-ar",t||{},null)},3e3),null}}if(e==="quicklook")return console.error("QuickLook mode is only supported on iOS devices."),null;if(e=="ar"&&(e="immersive-ar"),M()&&x("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Uc.start(e,t||q.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(et||M())&&ge("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=Q.Current),i||(i=ce.All[0]),!i)throw new Error("No Needle Engine Context found");switch(e){case"immersive-ar":{if(await q.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const l=this.getDefaultSessionInit(e),c=v2(i.domElement);c&&!I.isQuest()&&(l.domOverlay={root:c}),t={...l,...t}}break;case"immersive-vr":{if(await q.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await Uc.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;et?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const l of n)if(l.onBeforeXR&&l.activeAndEnabled&&!l.destroyed)try{await l.onBeforeXR(e,t)}catch(c){console.error("[NeedleXRSession] onBeforeXR hook failed:",c)}this.invokeSessionRequestStart(e,t,i??Q.Current);const s=Array.from(new Set(t.requiredFeatures)),r=Array.from(new Set(t.optionalFeatures)).filter(l=>!s.includes(l));t.requiredFeatures=s,t.optionalFeatures=r,et&&Fe("Requesting "+e+" session ("+Date.now()+")"),ct.sendEvent(Q.Current,"xr",{action:"session_request",mode:e,source:"NeedleXRSession.start",init:JSON.stringify(t)}),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const a=await this._currentSessionRequest?.catch(l=>{if(console.error(l,"Code: "+l?.code,"requiredFeatures:",t.requiredFeatures,"optionalFeatures:",t.optionalFeatures),l?.code===9){let c=typeof l?.message=="string"&&l.message.length>0?l.message:"Make sure you allow the required permissions.";t.requiredFeatures?.length||(c=e==="immersive-ar"?"AR seems to be blocked or unavailable on this device. Check the browser's site settings (Augmented Reality and Camera permissions) and that 'Google Play Services for AR' is installed and up to date.":"VR seems to be blocked or unavailable on this device. Check the browser's site settings (Virtual Reality permission).",window.self!==window.top&&(c+=' Embedded pages need allow="xr-spatial-tracking; camera" on the iframe.'),console.warn(`[Needle] The ${e} session request was rejected although all requested features are optional \u2014 the device or browser is blocking the session mode itself, not the session configuration.`)),ge(`Couldn't start XR session: ${c}`,{duration:3e4})}console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&ge("XR requires a secure connection (HTTPS)",{duration:3e4})});return this._currentSessionRequest=void 0,this._currentSessionRequestMode=null,this.invokeSessionRequestEnd(e,t,a),a?this.setSession(e,a,t,i):(console.warn("XR Session request was rejected"),null)}static invokeSessionRequestStart(e,t,i){for(const n of this._sessionRequestStartListeners)n({mode:e,init:t,context:i})}static invokeSessionRequestEnd(e,t,i){for(const n of this._sessionRequestEndListeners)n({mode:e,init:t,newSession:i||null})}static framebufferScaleFactor;static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new q(e,t,n,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),et?console.log(`%cStarted ${e} session`,"font-weight:bold;",s):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(et&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):et&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{et&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return q._sync}get running(){return!this._ended&&this.session!=null}session;mode;get appliedFramebufferScaleFactor(){return this._appliedFramebufferScaleFactor}_appliedFramebufferScaleFactor=1;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||M()&&I.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e){const i=t.trackingState;if(i==="tracked"||i==="emulated")return!0}}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&Ys(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return U(0,0,0);const t=U(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(xi(this.rig.gameObject.quaternion)),t}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(Ys(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}et&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const s of n.results)return this.convertHitTestResult(s);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=U(i.transform.position),s=xi(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(kl),r?.parent){n.applyMatrix4(r.parent.matrixWorld),s.multiply(hn);const a=Re(r.parent);a.premultiply(hn),s.premultiply(a)}return{hit:e,position:n,quaternion:s}}return null}convertSpace(e){const t=U(e.position);t.applyMatrix4(kl);const i=xi(e.orientation);return i.premultiply(hn),{position:t,quaternion:i}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_scripts_in_xr=new Set;_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,i,n){x2(e,n.init),this.session=t,this.mode=e,this.context=i,(et||x("console"))&&dl(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(l=>typeof l.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,ns(this.onBefore,Ee.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),this.context.addBeforeRenderListener(this.context.scene,this.syncCameraCullingMask),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(l=>t.requestHitTestSource?.call(t,{space:l})?.then(c=>this._viewerHitTestSource=c).catch(c=>console.error(c))).catch(l=>console.error(l)),this.context.mainCamera&&(this._originalCameraWorldPosition=le(this.context.mainCamera,new v),this._originalCameraWorldRotation=Re(this.context.mainCamera,new B),this._originalCameraWorldScale=Je(this.context.mainCamera,new v),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof me&&(this.context.mainCamera[vp]=this.context.mainCamera.fov)),this._defaultRig=new l2,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let l=0;l<t.inputSources.length;l++){const c=t.inputSources[l];if(!c.handedness){console.warn("Input source in xr session has no handedness - ignoring",l);continue}this.onInputSourceAdded(c)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",l=>{for(const c of l.removed)this.disconnectInputSource(c);for(const c of l.added)this.onInputSourceAdded(c)}),this.context.xr=this;const s=q.framebufferScaleFactor??T1()??1;this.context.renderer.xr.setFramebufferScaleFactor(s),this._appliedFramebufferScaleFactor=s,this._dynamicResolutionScale=n2();const r=this.context.xrFrameRateLimit;if(r>0&&this.session.supportedFrameRates?.length){const l=Array.from(this.session.supportedFrameRates).filter(c=>c<=r+1);if(l.length){const c=Math.max(...l);this.session.updateTargetFrameRate(c).then(()=>console.debug(`[XR] session frame rate capped at ${c} (requested limit ${r})`),()=>{})}}const a=()=>this.context.renderer.xr.setSession(this.session);a().then(this.onRendererSessionSet).catch(l=>{const c=typeof XRWebGLBinding<"u"?XRWebGLBinding.prototype:null;if(l instanceof TypeError&&c&&"createProjectionLayer"in c){console.warn("renderer.xr.setSession failed constructing XRWebGLBinding (non-native XRSession from a WebXR emulator/polyfill) - retrying with the XRProjectionLayer path disabled. See https://github.com/meta-quest/immersive-web-emulator/issues/80");const h=c.createProjectionLayer;delete c.createProjectionLayer,a().then(this.onRendererSessionSet).catch(d=>console.error("renderer.xr.setSession retry failed:",d)).finally(()=>{c.createProjectionLayer=h});return}console.error("renderer.xr.setSession failed:",l)}),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):et&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it"),I.isNeedleAppClip()&&window.requestAnimationFrame(()=>this.applyAppClipCanvasResolution())}get dynamicResolutionScale(){return this._dynamicResolutionScale}_dynamicResolutionScale=1;refreshRenderResolution(){this.running&&I.isNeedleAppClip()&&this.applyAppClipCanvasResolution()}setDynamicResolutionScale(e){e=Math.min(1,Math.max(.25,e)),e!==this._dynamicResolutionScale&&(this._dynamicResolutionScale=e,M()&&console.debug(`[XR] dynamic resolution scale \u2192 ${e}`),I.isNeedleAppClip()&&this.applyAppClipCanvasResolution())}applyAppClipCanvasResolution(){const e=this.context.renderer.domElement,t=Math.min(2,window.devicePixelRatio||1),i=q.framebufferScaleFactor??T1()??1;this._appliedFramebufferScaleFactor=i;const n=t*i*this._dynamicResolutionScale,s=Math.floor(window.innerWidth*n),r=Math.floor(window.innerHeight*n);(Math.abs(e.width-s)>2||Math.abs(e.height-r)>2)&&(e.width=s,e.height=r,console.debug("Applied canvas resolution for Needle AppClip XR session",t,this.appliedFramebufferScaleFactor,this._dynamicResolutionScale,e.width,e.height))}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new Vy(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(s,r)=>{if(s.inputSource===e){et&&console.log("Disconnecting controller",s.index);const a=r.indexOf(s);a>=0&&r.splice(a,1),this.invokeControllerEvent(s,this._controllerRemoved,"removed");const l={xr:this,controller:s,change:"removed"};for(const c of this._xr_scripts)c.onXRControllerRemoved&&c.onXRControllerRemoved(l);s.onDisconnected()}},i=[...this.controllers];for(let s=i.length-1;s>=0;s--){const r=i[s];t(r,this.controllers)}const n=[...this._newControllers];for(let s=n.length-1;s>=0;s--){const r=n[s];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;if(this._ended=!0,console.debug("XR Session ended"),I.isNeedleAppClip()&&M()){let s=0,r=0,a=window.requestAnimationFrame(function c(){s++,a=window.requestAnimationFrame(c)});const l=window.setInterval(()=>{r++,console.debug(`[XR] post-session heartbeat ${r}/10: window rAF ticks last second=${s}, engine frame=${this.context.time.frameCount}, visibility=${document.visibilityState}, focus=${document.hasFocus()}`),s=0,r>=10&&(window.clearInterval(l),window.cancelAnimationFrame(a))},1e3)}ct.sendEvent(Q.Current,"xr",{action:"session_end",mode:this.mode,source:"NeedleXRSession.onEnd"}),S2(),this.onAfterRender(),this.revertCustomForward(),this.detachXRCameras(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,Ws(this.onBefore,Ee.LateUpdate),this.context.removeBeforeRenderListener(this.context.scene,this.syncCameraCullingMask);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),W1({session:this});for(const s of q._xrEndListeners)s({xr:this});const n=[...this.controllers];for(let s=0;s<n.length;s++)this.disconnectInputSource(n[s].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const s of this._xr_scripts)this._scripts_in_xr.delete(s),s?.onLeaveXR?.({xr:this});this._scripts_in_xr.clear(),this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&Vi(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Fn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&hl(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof me&&(this.context.mainCamera[vp]&&(this.context.mainCamera.fov=this.context.mainCamera[vp],this.context.mainCamera[vp]=0),this.context.mainCamera[Xy]&&(this.context.mainCamera.near=this.context.mainCamera[Xy],this.context.mainCamera[Xy]=0))),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),dl(!1)};_didStart=!1;onBefore=e=>{const t=e.xrFrame;if(!t)return;if(this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==!1&&(et&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig){const n=this._mainCamera?.gameObject??this.context.mainCamera;n&&(n.parent===this._cameraRenderParent?this._cameraRenderParent.parent:n.parent)!==this.rig.gameObject&&this.rig.gameObject.add(n)}this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let s=0;s<n.length;s++){const r=this.context.new_scripts_xr[s];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(s,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(s,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const s=Si(this.context.scene.children);if(s){const r=s.getSize(U());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(s.min.x+r.x*.5,s.min.y,s.max.z+r.z*.5+1.5);const l=s.getCenter(U());l.y=a.position.y,a.lookAt(l)}}}$1({session:this}),Xr();for(const s of q._xrStartListeners)s(i);const n=[...this._xr_scripts];et&&console.log("NeedleXRSession start, handle scripts:",n);for(const s of n){if(s.destroyed){this._script_to_remove.push(s);continue}if(!s.activeAndEnabled){this.markInactive(s);continue}this.invokeCallback_EnterXR(s);for(const r of this.controllers)this.invokeCallback_ControllerAdded(s,r)}}this.syncXRCameraParents();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const s of n){if(!s.connected){console.warn("New controller is not connected",s);continue}this.controllers.push(s);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,s)}}this.controllers.sort((s,r)=>s.index-r.index)}et&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(dl(!0),console.error("XRControllers are not added but inputSources are present"));for(let n=this._xr_scripts.length-1;n>=0;n--){const s=this._xr_scripts[n];if(s.destroyed===!0){this._script_to_remove.push(s);continue}if(s.activeAndEnabled===!1){this.markInactive(s);continue}}for(const n of this._xr_update_scripts)n.destroyed||n.activeAndEnabled===!1||n.onUpdateXR&&n.onUpdateXR(i);if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const s of n)!s.destroyed&&this.running&&s.onLeaveXR?.(i),this.removeScript(s)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(et)for(const e of this.controllers)e.onRenderDebug();if((et||B1)&&this.rig&&(Hy++,Hy>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,et||B1)for(const s of this.controllers)n+=`
422
- ${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking} hts:${s.hasHitTestSource?"yes":"no"}`;Hy=0,F.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof me&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),I.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(et&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled&&(this._inactive_scripts.splice(e,1),this.addScript(t))){this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){et&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const s=this._inactive_scripts.indexOf(e);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(e){this._scripts_in_xr.add(e),e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){this._scripts_in_xr.delete(e)&&e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncXRCameraParents(){const e=this.context.xrCamera;if(!e)return;const t=this.context.mainCamera?.parent;if(t)for(const i of e.cameras)i.parent!==t&&(i.hideFlags|=uo.DontExport|uo.DontInstantiate,t.add(i))}detachXRCameras(){const e=this.context.renderer?.xr?.getCamera();if(e)for(const t of e.cameras)t.removeFromParent()}syncCameraCullingMask=()=>{const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}};invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const s=t[n];if(s)try{s({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new R().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=Je(this.rig.gameObject);e*=i.x}this._camera instanceof me&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,et&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof me&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new B;_transformPosition=new v;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){if(this._dynamicResolutionScale!==1&&!I.isNeedleAppClip())for(const i of this._viewerPose.views)i.requestViewportScale?.(this._dynamicResolutionScale);const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new D1),this._transition}fadeTransition(){return this._transition||(this._transition=new D1),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof me&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const Ml=[];function wp(o){return Ml.indexOf(o)===-1&&Ml.push(o),()=>Qy(o)}function Qy(o){const e=Ml.indexOf(o);e!==-1&&Ml.splice(e,1)}const Rl=[];function Yy(o){return Rl.indexOf(o)===-1&&Rl.push(o),()=>z1(o)}function z1(o){const e=Rl.indexOf(o);e!==-1&&Rl.splice(e,1)}function k2(o){return xp.indexOf(o)===-1&&(xp.push(o),q.onSessionRequestStart(o)),()=>N1(o)}function N1(o){const e=xp.indexOf(o);e!==-1&&(xp.splice(e,1),q.offSessionRequestStart(o))}const xp=[];function $1(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:o}));for(let e=0;e<Ml.length;e++)Ml[e](o)}function W1(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:o}));for(let e=0;e<Rl.length;e++)Rl[e](o)}var Xs;(o=>{function e(n){return n==="0"||n?.toLowerCase()==="false"}o.isFalsey=e;function t(n,s,r){const a=n.getAttribute(s);return e(a)?null:(r?.onAttribute?.call(null,a),a)}o.getAttributeValueIfNotFalsey=t;function i(n,s,r){const a=n.getAttribute(s);return a===null?null:e(a)?(r?.onAttribute?.call(null,a,!0),!1):(r?.onAttribute?.call(null,a,!1),a)}o.getAttributeAndCheckFalsey=i})(Xs||(Xs={}));async function V1(o){if(!globalThis.QRCode){const l="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js";let c=document.head.querySelector(`script[src="${l}"]`);c||(c=document.createElement("script"),c.src=l,document.head.appendChild(c)),await new Promise((h,d)=>{c.addEventListener("load",()=>{h(!0)})})}const e=globalThis.QRCode,t=o.domElement??document.createElement("div"),i=new e(t,{width:o.width??256,height:o.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:o.showLogo?e.CorrectionLevel.H:e.CorrectLevel.M,...o}),n=i?._oQRCode.moduleCount||0,s=i?._oDrawing?._elCanvas;let r=.25;n<40?r=Math.floor(n/4)/n:r=Math.floor(n/6)/n;const a=Math.floor(n/20)/n;try{const l=await O2(s,{showLogo:o.showLogo,logoSize:r,logoPadding:a}).catch(c=>{});l&&(t.innerHTML="",t.append(l))}catch{}if(o.showUrl!==!1&&o.text){const l=t.querySelector(".qr-code-link-label");let c=o.text.replace(/^(https?:\/\/)?(www\.)?/,"").replace(/\/+$/,"").replace(/\?+$/,"");if(c="Scan to visit "+c,l)l.textContent=c;else{const h=document.createElement("div");h.classList.add("qr-code-link-label"),o.text=c,h.textContent=o.text,h.addEventListener("click",d=>{d.stopImmediatePropagation()}),h.style.textAlign="center",h.style.fontSize="0.8em",h.style.marginTop="0.1em",h.style.color="#000000",h.style.fontFamily="'Roboto Flex', sans-serif",h.style.opacity="0.5",h.style.wordBreak="break-all",h.style.wordWrap="break-word",h.style.marginBottom="0.3em",t.style.width="calc(210px + 20px)",t.appendChild(h)}}return t}async function O2(o,e){if(!o)return;const t=8,i=20,n=e.logoPadding||1/32,s="transparent",r=0,a=new Image,l=document.querySelector("needle-engine");l||console.debug("[QR Code] No web component found");const c=cn();let h=null;if(h=Xs.getAttributeAndCheckFalsey(l,"qrcode-logo-src"),c&&e.showLogo!==!0&&h===!1||(h||=Xs.getAttributeAndCheckFalsey(l,"logo-src"),c&&e.showLogo!==!0&&h===!1)||(h||=Xs.getAttributeAndCheckFalsey(l,"loading-logo-src"),c&&e.showLogo!==!0&&h===!1)||(h&&!c&&(console.warn("[QR Code] Custom logo is only available with a commercial license. Using default Needle logo. Please get a commercial license at https://needle.tools/pricing."),h=null),h||=Ol,!h))return;let d=!1;e.showLogo!==!1&&(a.src=h,d=await new Promise((w,S)=>{a.onload=()=>w(!0),a.onerror=O=>{const L=h!==Ol?"'"+h+"'":null;console.error("[QR Code] Error loading logo image for QR code",L,M()?O:""),w(!1)}}));const u=document.createElement("canvas");u.width=o.width+t,u.height=o.height+t;const m=u.getContext("2d");if(!m)return;m.fillStyle="#ffffff",m.fillRect(0,0,u.width,u.height),m.drawImage(o,t/2,t/2),m.imageSmoothingEnabled=!0,m.imageSmoothingQuality="high",m.mozImageSmoothingEnabled=!0,m.webkitImageSmoothingEnabled=!0,m.globalCompositeOperation="lighten";const g=m.createLinearGradient(0,0,0,u.height);g.addColorStop(0,"rgb(45, 45, 45)"),g.addColorStop(1,"rgb(45, 45, 45)"),m.fillStyle=g,m.fillRect(0,0,u.width,u.height),m.globalCompositeOperation="source-over";let y=Math.min(o.width,o.height)*(e.logoSize||.25),b=y;if(d){const w=a.width/a.height;w>1?b=y/w:y=b*w;const S=n*o.width,O=Math.max(y,b),L=Math.round(O+S),D=Math.round(O+S),W=(u.width-O)/2,$=(u.height-O)/2;m.shadowColor=s,m.shadowBlur=i;const H=r,G=Math.round(W-S/2),E=Math.round($-S/2);m.beginPath(),m.moveTo(G+H,E),m.lineTo(G+L-H,E),m.quadraticCurveTo(G+L,E,G+L,E+H),m.lineTo(G+L,E+D-H),m.quadraticCurveTo(G+L,E+D,G+L-H,E+D),m.lineTo(G+H,E+D),m.quadraticCurveTo(G,E+D,G,E+D-H),m.lineTo(G,E+H),m.quadraticCurveTo(G,E,G+H,E),m.fillStyle="#ffffff",m.closePath(),m.fill(),m.clip(),m.shadowColor="transparent";const z=(u.width-y)/2,Y=(u.height-b)/2;m.drawImage(a,z,Y,y,b)}const f=u.toDataURL("image/png"),_=document.createElement("img");return _.src=f,_.style.width="100%",_.style.height="auto",_}const Ky="Material Symbols Outlined";function Tt(o){const e=document.createElement("span");return e.style.maxWidth="48px",e.style.maxHeight="48px",e.style.overflow="hidden",e.classList.add("material-symbols-outlined","notranslate"),e.setAttribute("translate","no"),e.innerText=o,e.style.visibility="hidden",e.style.userSelect="none",e.setAttribute("role","img"),e.setAttribute("aria-label",o+" icon"),e.setAttribute("aria-hidden","true"),M2(new WeakRef(e),o),e}function M2(o,e){eb(Ky).then(t=>{const i=o.deref();i&&(t?(i.style.visibility="",i.innerText=e):e==="more_vert"?(i.style.visibility="",i.innerText="More"):i.style.display="none")})}function G1(o){return o.classList?.contains("material-symbols-outlined")||!1}const Sp=new Map;async function Zy(o){if(await eb(Ky),Sp.has(o))return Sp.get(o);const e=document.createElement("canvas"),t=48;e.width=t,e.height=t;const i=e.getContext("2d");if(i){i.font=`${t}px '${Ky}'`,i.fillStyle="black",i.fillText(o,0,t);const n=e.toDataURL(),s=new Pe;s.name=o+" icon";const r=new Image;return s.image=r,r.src=n,s.needsUpdate=!0,Sp.set(o,s),s}return Sp.set(o,null),null}const Jy=new Map;async function eb(o,e=5,t=0){document.fonts.check(`1em '${o}'`)||await document.fonts.ready;const i=Jy.get(o)||document.fonts.load(`1em '${o}'`).then(n=>n?.length>0).finally(()=>{Jy.delete(o)});return Jy.set(o,i),await i?!0:t<e?new Promise(n=>{setTimeout(()=>{n(eb(o,e,t+1))},1e3)}):!1}function Cp(o,e){o.setAttribute("priority",String(e))}function R2(o){const e=o.getAttribute("priority");if(e){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}}class On{static _instance;static get instance(){return this.getOrCreate()}static getOrCreate(){return this._instance||(this._instance=new On),this._instance}static create(){return new On}_fullscreenButton;get fullscreenButton(){return this._fullscreenButton}createFullscreenButton(e){if(this._fullscreenButton)return this._fullscreenButton;if(!document.fullscreenEnabled)return M()&&console.warn("NeedleMenu: Fullscreen button could not be created, device doesn't support the Fullscreen API"),null;const t=document.createElement("button");this._fullscreenButton=t,t.classList.add("fullscreen-button"),t.title="Click to enter fullscreen mode",Cp(t,3);const i=Tt("fullscreen"),n=Tt("fullscreen_exit");return t.appendChild(i),t.onclick=()=>{document.fullscreenElement?document.exitFullscreen():"webkitRequestFullscreen"in e.domElement&&typeof e.domElement.webkitRequestFullscreen=="function"?e.domElement.webkitRequestFullscreen():"requestFullscreen"in e.domElement&&e.domElement.requestFullscreen()},document.addEventListener("fullscreenchange",()=>{document.fullscreenElement?(i.remove(),t.appendChild(n),t.title="Click to enter fullscreen mode"):(n.remove(),t.appendChild(i),t.title="Click to exit fullscreen mode")}),globalThis.addEventListener("needle-xrsession-start",()=>{t.style.display="none"}),globalThis.addEventListener("needle-xrsession-end",()=>{t.style.display=""}),t}_muteButton;get muteButton(){return this._muteButton}createMuteButton(e){if(this._muteButton)return this._muteButton;const t=document.createElement("button");this._muteButton=t,t.classList.add("mute-button"),t.title="Click to mute/unmute";const i=Tt("volume_off"),n=Tt("volume_up");return Cp(t,1),e.application.muted?t.appendChild(i):t.appendChild(n),t.onclick=()=>{e.application.muted?(i.remove(),t.appendChild(n),e.application.muted=!1):(n.remove(),t.appendChild(i),e.application.muted=!0)},t}_qrButton;get qrButton(){return this._qrButton}_customQRButtonUrl;set qrButtonUrl(e){try{new URL(e),this._customQRButtonUrl=e}catch{console.warn(`[Needle] QR code button URL is not a valid URL '${e}'`)}}get qrButtonUrl(){return this._customQRButtonUrl||window.location.href}createQRCode(e){if(this._qrButton)return this._qrButton;const t=this,i=document.createElement("button");this._qrButton=i,i.innerText="QR Code",i.prepend(Tt("qr_code")),i.title="Scan this QR code with your phone to open this page",this.hideElementDuringXRSession(i),Cp(this._qrButton,20);const n=document.createElement("div");n.style.cssText=`
422
+ ${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking} hts:${s.hasHitTestSource?"yes":"no"}`;Hy=0,F.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof me&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),I.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(et&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled&&(this._inactive_scripts.splice(e,1),this.addScript(t))){this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){et&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const s=this._inactive_scripts.indexOf(e);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(e){this._scripts_in_xr.add(e),e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){this._scripts_in_xr.delete(e)&&e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncXRCameraParents(){const e=this.context.xrCamera;if(!e)return;const t=this.context.mainCamera?.parent;if(t)for(const i of e.cameras)i.parent!==t&&(i.hideFlags|=uo.DontExport|uo.DontInstantiate,t.add(i))}detachXRCameras(){const e=this.context.renderer?.xr?.getCamera();if(e)for(const t of e.cameras)t.removeFromParent()}syncCameraCullingMask=()=>{const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}};invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const s=t[n];if(s)try{s({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new R().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=Je(this.rig.gameObject);e*=i.x}this._camera instanceof me&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,et&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof me&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new B;_transformPosition=new v;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){if(this._dynamicResolutionScale!==1&&!I.isNeedleAppClip())for(const i of this._viewerPose.views)i.requestViewportScale?.(this._dynamicResolutionScale);const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new D1),this._transition}fadeTransition(){return this._transition||(this._transition=new D1),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof me&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const Ml=[];function wp(o){return Ml.indexOf(o)===-1&&Ml.push(o),()=>Qy(o)}function Qy(o){const e=Ml.indexOf(o);e!==-1&&Ml.splice(e,1)}const Rl=[];function Yy(o){return Rl.indexOf(o)===-1&&Rl.push(o),()=>z1(o)}function z1(o){const e=Rl.indexOf(o);e!==-1&&Rl.splice(e,1)}function k2(o){return xp.indexOf(o)===-1&&(xp.push(o),q.onSessionRequestStart(o)),()=>N1(o)}function N1(o){const e=xp.indexOf(o);e!==-1&&(xp.splice(e,1),q.offSessionRequestStart(o))}const xp=[];function $1(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:o}));for(let e=0;e<Ml.length;e++)Ml[e](o)}function W1(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:o}));for(let e=0;e<Rl.length;e++)Rl[e](o)}var Xs;(o=>{function e(n){return n==="0"||n?.toLowerCase()==="false"}o.isFalsey=e;function t(n,s,r){const a=n.getAttribute(s);return e(a)?null:(r?.onAttribute?.call(null,a),a)}o.getAttributeValueIfNotFalsey=t;function i(n,s,r){const a=n.getAttribute(s);return a===null?null:e(a)?(r?.onAttribute?.call(null,a,!0),!1):(r?.onAttribute?.call(null,a,!1),a)}o.getAttributeAndCheckFalsey=i})(Xs||(Xs={}));async function V1(o){if(!globalThis.QRCode){const l="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js";let c=document.head.querySelector(`script[src="${l}"]`);c||(c=document.createElement("script"),c.src=l,document.head.appendChild(c)),await new Promise((h,d)=>{c.addEventListener("load",()=>{h(!0)})})}const e=globalThis.QRCode,t=o.domElement??document.createElement("div"),i=new e(t,{width:o.width??256,height:o.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:o.showLogo?e.CorrectionLevel.H:e.CorrectLevel.M,...o}),n=i?._oQRCode.moduleCount||0,s=i?._oDrawing?._elCanvas;let r=.25;n<40?r=Math.floor(n/4)/n:r=Math.floor(n/6)/n;const a=Math.floor(n/20)/n;try{const l=await O2(s,{showLogo:o.showLogo,logoSize:r,logoPadding:a}).catch(c=>{});l&&(t.innerHTML="",t.append(l))}catch{}if(o.showUrl!==!1&&o.text){const l=t.querySelector(".qr-code-link-label");let c=o.text.replace(/^(https?:\/\/)?(www\.)?/,"").replace(/\/+$/,"").replace(/\?+$/,"");if(c="Scan to visit "+c,l)l.textContent=c;else{const h=document.createElement("div");h.classList.add("qr-code-link-label"),o.text=c,h.textContent=o.text,h.addEventListener("click",d=>{d.stopImmediatePropagation()}),h.style.textAlign="center",h.style.fontSize="0.8em",h.style.marginTop="0.1em",h.style.color="#000000",h.style.fontFamily="'Roboto Flex', sans-serif",h.style.opacity="0.5",h.style.wordBreak="break-all",h.style.wordWrap="break-word",h.style.marginBottom="0.3em",t.style.width="calc(210px + 20px)",t.appendChild(h)}}return t}async function O2(o,e){if(!o)return;const t=8,i=20,n=e.logoPadding||1/32,s="transparent",r=0,a=new Image,l=document.querySelector("needle-engine");l||console.debug("[QR Code] No web component found");const c=cn();let h=null;if(h=Xs.getAttributeAndCheckFalsey(l,"qrcode-logo-src"),c&&e.showLogo!==!0&&h===!1||(h||=Xs.getAttributeAndCheckFalsey(l,"logo-src"),c&&e.showLogo!==!0&&h===!1)||(h||=Xs.getAttributeAndCheckFalsey(l,"loading-logo-src"),c&&e.showLogo!==!0&&h===!1)||(h&&!c&&(console.warn("[QR Code] Custom logo is only available with a commercial license. Using default Needle logo. Please get a commercial license at https://needle.tools/pricing."),h=null),h||=Ol,!h))return;let d=!1;e.showLogo!==!1&&(a.src=h,d=await new Promise((w,S)=>{a.onload=()=>w(!0),a.onerror=O=>{const L=h!==Ol?"'"+h+"'":null;console.error("[QR Code] Error loading logo image for QR code",L,M()?O:""),w(!1)}}));const u=document.createElement("canvas");u.width=o.width+t,u.height=o.height+t;const m=u.getContext("2d");if(!m)return;m.fillStyle="#ffffff",m.fillRect(0,0,u.width,u.height),m.drawImage(o,t/2,t/2),m.imageSmoothingEnabled=!0,m.imageSmoothingQuality="high",m.mozImageSmoothingEnabled=!0,m.webkitImageSmoothingEnabled=!0,m.globalCompositeOperation="lighten";const g=m.createLinearGradient(0,0,0,u.height);g.addColorStop(0,"rgb(45, 45, 45)"),g.addColorStop(1,"rgb(45, 45, 45)"),m.fillStyle=g,m.fillRect(0,0,u.width,u.height),m.globalCompositeOperation="source-over";let y=Math.min(o.width,o.height)*(e.logoSize||.25),b=y;if(d){const w=a.width/a.height;w>1?b=y/w:y=b*w;const S=n*o.width,O=Math.max(y,b),L=Math.round(O+S),D=Math.round(O+S),W=(u.width-O)/2,$=(u.height-O)/2;m.shadowColor=s,m.shadowBlur=i;const H=r,G=Math.round(W-S/2),E=Math.round($-S/2);m.beginPath(),m.moveTo(G+H,E),m.lineTo(G+L-H,E),m.quadraticCurveTo(G+L,E,G+L,E+H),m.lineTo(G+L,E+D-H),m.quadraticCurveTo(G+L,E+D,G+L-H,E+D),m.lineTo(G+H,E+D),m.quadraticCurveTo(G,E+D,G,E+D-H),m.lineTo(G,E+H),m.quadraticCurveTo(G,E,G+H,E),m.fillStyle="#ffffff",m.closePath(),m.fill(),m.clip(),m.shadowColor="transparent";const z=(u.width-y)/2,Y=(u.height-b)/2;m.drawImage(a,z,Y,y,b)}const f=u.toDataURL("image/png"),_=document.createElement("img");return _.src=f,_.style.width="100%",_.style.height="auto",_}const Ky="Material Symbols Outlined";function Tt(o){const e=document.createElement("span");return e.style.maxWidth="48px",e.style.maxHeight="48px",e.style.overflow="hidden",e.classList.add("material-symbols-outlined","notranslate"),e.setAttribute("translate","no"),e.innerText=o,e.style.visibility="hidden",e.style.userSelect="none",e.setAttribute("role","img"),e.setAttribute("aria-label",o+" icon"),e.setAttribute("aria-hidden","true"),M2(new WeakRef(e),o),e}function M2(o,e){eb(Ky).then(t=>{const i=o.deref();i&&(t?(i.style.visibility="",i.innerText=e):e==="more_vert"?(i.style.visibility="",i.innerText="More"):i.style.display="none")})}function G1(o){return o.classList?.contains("material-symbols-outlined")||!1}const Sp=new Map;async function Zy(o){if(await eb(Ky),Sp.has(o))return Sp.get(o);const e=document.createElement("canvas"),t=48;e.width=t,e.height=t;const i=e.getContext("2d");if(i){i.font=`${t}px '${Ky}'`,i.fillStyle="black",i.fillText(o,0,t);const n=e.toDataURL(),s=new ke;s.name=o+" icon";const r=new Image;return s.image=r,r.src=n,s.needsUpdate=!0,Sp.set(o,s),s}return Sp.set(o,null),null}const Jy=new Map;async function eb(o,e=5,t=0){document.fonts.check(`1em '${o}'`)||await document.fonts.ready;const i=Jy.get(o)||document.fonts.load(`1em '${o}'`).then(n=>n?.length>0).finally(()=>{Jy.delete(o)});return Jy.set(o,i),await i?!0:t<e?new Promise(n=>{setTimeout(()=>{n(eb(o,e,t+1))},1e3)}):!1}function Cp(o,e){o.setAttribute("priority",String(e))}function R2(o){const e=o.getAttribute("priority");if(e){const t=Number.parseFloat(e);if(!Number.isNaN(t))return t}}class On{static _instance;static get instance(){return this.getOrCreate()}static getOrCreate(){return this._instance||(this._instance=new On),this._instance}static create(){return new On}_fullscreenButton;get fullscreenButton(){return this._fullscreenButton}createFullscreenButton(e){if(this._fullscreenButton)return this._fullscreenButton;if(!document.fullscreenEnabled)return M()&&console.warn("NeedleMenu: Fullscreen button could not be created, device doesn't support the Fullscreen API"),null;const t=document.createElement("button");this._fullscreenButton=t,t.classList.add("fullscreen-button"),t.title="Click to enter fullscreen mode",Cp(t,3);const i=Tt("fullscreen"),n=Tt("fullscreen_exit");return t.appendChild(i),t.onclick=()=>{document.fullscreenElement?document.exitFullscreen():"webkitRequestFullscreen"in e.domElement&&typeof e.domElement.webkitRequestFullscreen=="function"?e.domElement.webkitRequestFullscreen():"requestFullscreen"in e.domElement&&e.domElement.requestFullscreen()},document.addEventListener("fullscreenchange",()=>{document.fullscreenElement?(i.remove(),t.appendChild(n),t.title="Click to enter fullscreen mode"):(n.remove(),t.appendChild(i),t.title="Click to exit fullscreen mode")}),globalThis.addEventListener("needle-xrsession-start",()=>{t.style.display="none"}),globalThis.addEventListener("needle-xrsession-end",()=>{t.style.display=""}),t}_muteButton;get muteButton(){return this._muteButton}createMuteButton(e){if(this._muteButton)return this._muteButton;const t=document.createElement("button");this._muteButton=t,t.classList.add("mute-button"),t.title="Click to mute/unmute";const i=Tt("volume_off"),n=Tt("volume_up");return Cp(t,1),e.application.muted?t.appendChild(i):t.appendChild(n),t.onclick=()=>{e.application.muted?(i.remove(),t.appendChild(n),e.application.muted=!1):(n.remove(),t.appendChild(i),e.application.muted=!0)},t}_qrButton;get qrButton(){return this._qrButton}_customQRButtonUrl;set qrButtonUrl(e){try{new URL(e),this._customQRButtonUrl=e}catch{console.warn(`[Needle] QR code button URL is not a valid URL '${e}'`)}}get qrButtonUrl(){return this._customQRButtonUrl||window.location.href}createQRCode(e){if(this._qrButton)return this._qrButton;const t=this,i=document.createElement("button");this._qrButton=i,i.innerText="QR Code",i.prepend(Tt("qr_code")),i.title="Scan this QR code with your phone to open this page",this.hideElementDuringXRSession(i),Cp(this._qrButton,20);const n=document.createElement("div");n.style.cssText=`
423
423
  position: fixed;
424
424
  display: inline-block;
425
425
  padding: 0.5rem;
@@ -864,7 +864,7 @@ ${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connecte
864
864
  </div>
865
865
  `;const t=this.attachShadow({mode:"open"});q1(),this._unsubscribeFont=Ch(tb,{loadedCallback:()=>{this.handleSizeChange()}}),Ch(tb,{element:t});const i=e.content.cloneNode(!0);t?.appendChild(i),this.root=t.querySelector("#root"),this.wrapper=this.root?.querySelector(".wrapper"),this.options=this.root?.querySelector(".options.main-container"),this.optionsCompactMode=this.root?.querySelector(".options.compact-only"),this.logoContainer=this.root?.querySelector(".logo"),this.compactMenuButton=this.root?.querySelector(".compact-menu-button"),this.compactMenuButton.append(Tt("more_vert")),this.foldout=this.root?.querySelector(".foldout"),this.root?.appendChild(this.wrapper),this.wrapper.classList.add("wrapper");const n=Zg.create();n.setType("compact"),n.style.minHeight="1rem",this.logoContainer.append(n),this.logoContainer.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});try{this._licenseFrame=window.requestAnimationFrame(()=>{this._licenseFrame=void 0,this._unsubscribeLicense=RE(c=>{if(c==!0&&cn()&&!Q1){let h=this._userRequestedLogoVisible;h===void 0&&(h=!1),this.___onSetLogoVisible(h)}else this.___onSetLogoVisible(!0)})})}catch(c){console.error("[Needle Menu] License check failed.",c)}this.compactMenuButton.addEventListener("click",c=>{c.preventDefault(),this.root.classList.toggle("open")});let s=this._context;setTimeout(()=>s=this._context);let r=0;const a=(c,h)=>{El&&console.log("Set menu visible",h),s?.isInAR&&s.arOverlayElement?c!=s.arOverlayElement&&s.arOverlayElement.appendChild(this):this.parentNode!=this._domElement?.shadowRoot&&this._domElement?.shadowRoot?.appendChild(this),this.style.display=h?"flex":"none",this.style.visibility="visible",this.style.opacity="1"};let l=!1;new MutationObserver(c=>{if(!l)try{l=!0,this.onChangeDetected(c);const h=this?.parentNode;if((this.style.display!="flex"||this.style.visibility!="visible"||this.style.opacity!="1"||h!=this._domElement?.shadowRoot)&&!cn()){const d=r++;Ni()&&this._userRequestedMenuVisible===!1?(d===0&&a(h,this._userRequestedMenuVisible),d===1&&console.warn("Needle Menu Warning: You need a commercial license to hide the Needle Engine menu \u2192 The menu will be visible in your deployed website without one. See https://needle.tools/pricing for details.")):d===0?a(h,!0):setTimeout(()=>a(h,!0),5)}}finally{l=!1}}).observe(this.root,{childList:!0,subtree:!0,attributes:!0}),El&&this.___insertDebugOptions()}ensureInitialized(){this._didInitialize||(this._didInitialize=!0,this.initializeDom())}_sizeChangeInterval;connectedCallback(){this.ensureInitialized(),window.addEventListener("resize",this.handleSizeChange),this.addEventListener("beforexrselect",this.#t),this.handleMenuVisible(),this._sizeChangeInterval=setInterval(()=>this.handleSizeChange(void 0,!1),5e3),setTimeout(()=>{this._domElement?.addEventListener("resize",this.handleSizeChange),this._domElement?.addEventListener("click",this.#i)},1)}disconnectedCallback(){window.removeEventListener("resize",this.handleSizeChange),this.removeEventListener("beforexrselect",this.#t),clearInterval(this._sizeChangeInterval),this._domElement?.removeEventListener("resize",this.handleSizeChange),this._context?.domElement.removeEventListener("click",this.#i)}#t=e=>{e.preventDefault()};#i=e=>{if(!e.defaultPrevented&&e.target==this._domElement&&e instanceof PointerEvent&&e.button===0&&this.root.classList.contains("open")){const t=this.foldout.getBoundingClientRect(),i=e;i.clientX>t.left&&i.clientX<t.right&&i.clientY>t.top&&i.clientY<t.bottom||this.root.classList.toggle("open",!1)}};_userRequestedLogoVisible=void 0;showNeedleLogo(e){this._userRequestedLogoVisible=e,!(!e&&(!cn()||Q1)&&(console.warn("[Needle Engine] You need a commercial license to hide the Needle Engine logo in production."),!Ni()))&&this.___onSetLogoVisible(e)}get logoIsVisible(){return!this.root.classList.contains("logo-hidden")}___onSetLogoVisible(e){this.logoContainer.style.display="",this.logoContainer.style.opacity="1",this.logoContainer.style.visibility="visible",e?(this.root.classList.remove("logo-hidden"),this.root.classList.add("logo-visible")):(this.root.classList.remove("logo-visible"),this.root.classList.add("logo-hidden"))}setPosition(e){if(e!=="top"&&e!=="bottom")return console.error("NeedleMenu.setPosition: invalid position",e);this.root.classList.remove("top","bottom"),this.root.classList.add(e)}_userRequestedMenuVisible=void 0;setVisible(e){this._userRequestedMenuVisible=e,this.style.display=e?"flex":"none"}closeFoldout(){this.root.classList.remove("open")}root;wrapper;options;optionsCompactMode;logoContainer;compactMenuButton;foldout;trackedElements=new WeakSet;trackElement(e){this.trackedElements.has(e)||(this.trackedElements.add(e),e.addEventListener("click",t=>{ct.sendEvent(this._context,"needle-menu",{action:"button_clicked",element:t.target instanceof Node?t.target.nodeName:e.nodeName,label:e.textContent,title:e instanceof HTMLElement?e.title:void 0,pointerid:t instanceof PointerEvent?t.pointerId:void 0})}))}append(...e){for(const t of e)if(typeof t=="string"){const i=document.createTextNode(t);this.trackElement(i),this.options.appendChild(i)}else this.trackElement(t),this.options.appendChild(t)}appendChild(e){if(!(e instanceof Node)){const t=document.createElement("button");if(t.textContent=e.label,t.onclick=e.onClick,t.setAttribute("priority",e.priority?.toString()??"0"),e.title&&(t.title=e.title),e.icon){const i=Tt(e.icon);e.iconSide==="right"?t.appendChild(i):t.prepend(i)}e.class&&t.classList.add(e.class),e=t}return this.trackElement(e),this.options.appendChild(e)}prepend(...e){for(const t of e)if(typeof t=="string"){const i=document.createTextNode(t);this.trackElement(i),this.options.prepend(i)}else this.trackElement(t),this.options.prepend(t)}_isHandlingChange=!1;_pauseMutationObserverOptionsContainer=!1;onChangeDetected(e){if(!this._isHandlingChange){this._isHandlingChange=!0;try{this.handleMenuVisible();for(const t of e)t.target==this.options&&(this._pauseMutationObserverOptionsContainer||this.onOptionsChildrenChanged(t))}finally{this._isHandlingChange=!1}}}onOptionsChildrenChanged(e){if(this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions),this.handleSizeChange(void 0,!0),e.type==="childList"&&e.addedNodes.length>0){const t=Array.from(this.options.children);t.sort((n,s)=>{const r=parseInt(n.getAttribute("priority")||"0"),a=parseInt(s.getAttribute("priority")||"0");return r-a});let i=!1;for(let n=0;n<t.length;n++){const s=this.options.children[n],r=t[n];if(s!==r){i=!0;break}}if(i)for(const n of t)this.options.appendChild(n)}}_didSort=new Map;handleMenuVisible(){El&&console.log("Update VisibleState: Any Content?",this.hasAnyContent),this.hasAnyContent?this.root.style.display="":this.root.style.display="none",this.root.classList.toggle("has-options",this.hasAnyVisibleOptions),this.root.classList.toggle("has-no-options",!this.hasAnyVisibleOptions)}get hasAnyContent(){return!!(this.logoContainer.style.display!="none"||this.hasAnyVisibleOptions)}get hasAnyVisibleOptions(){for(let e=0;e<this.options.children.length;e++){const t=this.options.children[e];if(t.tagName==="SLOT"){const i=t.assignedNodes();for(const n of i)if(n instanceof HTMLElement&&n.style.display!="none")return!0}else if(t.style.display!="none")return!0}return!1}_lastAvailableWidthChange=0;_timeoutHandleSize=0;_timeoutHandleCompactItems=0;handleSizeChange=(e,t)=>{if(!this._domElement)return;const i=this._domElement.clientWidth;if(i<100){clearTimeout(this._timeoutHandleSize),this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style");return}const n=i-20;if(!t&&Math.abs(n-this._lastAvailableWidthChange)<1)return;this._lastAvailableWidthChange=n,clearTimeout(this._timeoutHandleSize),this._timeoutHandleSize=setTimeout(()=>{const l=a();l<0?(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style")):l>0&&(this.root.classList.remove("compact"),this.foldout.classList.remove("floating-panel-style"),a()<0&&(this.root.classList.add("compact"),this.foldout.classList.add("floating-panel-style"))),this._pauseMutationObserverOptionsContainer=!0,this.updateCompactFoldoutItem(),window.requestAnimationFrame(()=>this._pauseMutationObserverOptionsContainer=!1)},150);const s=()=>{let l=0;return l+=this.options.getBoundingClientRect().width,l+=this.optionsCompactMode.getBoundingClientRect().width,l+=10*this.options.childElementCount,l+=this.logoContainer.style.display!="none"?this.logoContainer.getBoundingClientRect().width:0,l};let r=-1;const a=()=>{const l=n-s();return El&&l!==r&&(r=l,Fe(`Menu space left: ${l.toFixed(0)}px`)),l}};updateCompactFoldoutItem(){if(this.root.classList.contains("compact")){let e=null,t=-1e7;const i=n=>{if(n instanceof HTMLElement){const s=Ph.getElementPriority(n);if(s!==void 0&&s>=t){const r=window.getComputedStyle(n);if(r.display==="none"||r.visibility==="hidden"||r.opacity==="0")return;e=n,t=s}}};for(let n=0;n<this.options.children.length;n++)i(this.options.children.item(n));for(let n=0;n<this.optionsCompactMode.children.length;n++)i(this.optionsCompactMode.children.item(n));if(e&&!this.optionsCompactMode.contains(e)){this.optionsCompactMode.childNodes.forEach(s=>{this.options.appendChild(s)});const n=e;this.optionsCompactMode.appendChild(n)}else e||this.optionsCompactMode.childNodes.forEach(n=>{this.options.appendChild(n)})}else this.optionsCompactMode.childNodes.forEach(e=>{this.options.appendChild(e)})}___insertDebugOptions(){window.addEventListener("keydown",i=>{i.key==="p"&&this.setPosition(this.root.classList.contains("top")?"bottom":"top")});const e=document.createElement("button");e.textContent="Hide Buttons",e.onclick=()=>{const i=new Array(this.options.children.length);for(let n=0;n<this.options.children.length;n++)i[n]=this.options.children[n];for(const n of i)this.options.removeChild(n);setTimeout(()=>{for(const n of i)this.options.appendChild(n)},1e3)},this.appendChild(e);const t=document.createElement("button");t.textContent="Toggle Logo",t.addEventListener("click",()=>{this.logoContainer.style.display=this.logoContainer.style.display==="none"?"":"none"}),this.appendChild(t)}}var I2=Object.defineProperty,xe=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&I2(e,t,n),n};const ot=x("debugcontext"),L2=x("stats"),D2=x("debugactive"),j2=x("debugframerate"),F2=x("debugcoroutine"),B2={};class U2{name;alias;hash;runInBackground;domElement;renderer;camera;scene}var Ee=(o=>(o[o.Start=-1]="Start",o[o.EarlyUpdate=0]="EarlyUpdate",o[o.Update=1]="Update",o[o.LateUpdate=2]="LateUpdate",o[o.OnBeforeRender=3]="OnBeforeRender",o[o.OnAfterRender=4]="OnAfterRender",o[o.PrePhysicsStep=9]="PrePhysicsStep",o[o.PostPhysicsStep=10]="PostPhysicsStep",o[o.Undefined=-1]="Undefined",o))(Ee||{});function kp(o,e){if(!o)return;if(!o.isComponent){(M()||ot)&&console.error(`Registered script is not a Needle Engine component.
866
866
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
867
- `,o);return}e||(e=Q.Current,ot&&console.warn("> Registering component without context"));const t=e?.new_scripts;t.includes(o)||t.push(o)}const ye=class Ce{static _defaultTargetFramerate={value:90,toString(){return this.value}};static get DefaultTargetFrameRate(){return Ce._defaultTargetFramerate.value}static set DefaultTargetFrameRate(e){Ce._defaultTargetFramerate.value=e}static _defaultWebglRendererParameters={alpha:!1,powerPreference:I.isiOS()||I.isMacOS()?"default":"high-performance",stencil:!0};static get DefaultWebGLRendererParameters(){return Ce._defaultWebglRendererParameters}static ExperimentalWebGPU=!1;get version(){return ci}static get Current(){return ce.Current}static set Current(e){ce.Current=e}static get All(){return ce.All}name;alias;isManagedExternally=!1;isPaused=!1;get lifecycle(){return this._lifecycle}set lifecycle(e){if(e===this._lifecycle)return;const t=this._lifecycle;this._lifecycle=e,t==="held"&&e==="running"&&this.reconcileLifecycleAfterHold(),this.events.emit("lifecycle-changed",{context:this,lifecycle:e,previous:t})}_lifecycle="running";reconcileLifecycleAfterHold(){this.scene&&(Ih(this.scene,!0),$n(this.scene,e=>{e.__didAwake===!0&&e.__didEnable!==!0&&!e.destroyed&&e.activeAndEnabled&&e.__internalEnable()},!0))}runInBackground=!1;targetFrameRate;physicsSteps=1;hash;domElement;appendHTMLElement(e){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(e):this.domElement.appendChild(e)}xrFrameRateLimit=0;get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;_boundingClientRectFrame=-1;_boundingClientRect=null;_domX;_domY;calculateBoundingClientRect(){if(this.xr){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){return this.renderer?.xr?.isPresenting||!1}xr=null;get xrSessionMode(){return this.xr?.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){return this.renderer?.xr?.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){return this.renderer.xr.isPresenting?this.renderer?.xr?.getCamera():void 0}_xrFrame=null;get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=-1;scene;renderer;get composer(){return this.postprocessing.composer}set composer(e){this.postprocessing.composer=e}scripts=[];scripts_pausedChanged=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];scripts_immersive_vr=[];scripts_immersive_ar=[];coroutines={};post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];pre_update_oneshot_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];new_scripts_xr=[];mainCameraComponent=void 0;get sceneData(){return u1(this)}get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.threeCamera||e.buildCamera(),e.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new me(35,this.domWidth/this.domHeight,.1,1e3),this.scene?.add(this._fallbackCamera)),this._fallbackCamera}set mainCamera(e){this._mainCamera=e}_mainCamera=null;_fallbackCamera=null;get application(){return this._application}_application;get animations(){return this._animations}_animations;get time(){return this._time}_time;get input(){return this._input}_input;get physics(){return this._physics}_physics;get postprocessing(){return this._postprocessing}_postprocessing;get connection(){return this._connection}_connection;get events(){return this._events}_events=new My;assets;lights=new Array;get mainLight(){let e=null;for(const t of this.lights)t.type==="directional"&&(!e||t.intensity>e.intensity)&&(e=t);return e}get rendererData(){return this.sceneLighting}sceneLighting;addressables;lightmaps;players;lodsManager;menu;accessibility;get isCreated(){return this._isCreated}get rootSourceId(){return this.rootSceneSourceIdentifiers[0]||void 0}_needsUpdateSize=!1;_isCreated=!1;_isCreating=!1;_isVisible=!1;_stats=L2?new iR:null;constructor(e){this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer&&(this.renderer=e.renderer,this.isManagedExternally=!0),e?.runInBackground!==void 0&&(this.runInBackground=e.runInBackground),e?.scene?this.scene=e.scene:this.scene=new Fi,this._fallbackCamera&&!this._fallbackCamera.parent&&this.scene.add(this._fallbackCamera),e?.camera&&(this._mainCamera=e.camera),this._application=new no(this),this._time=new b1,this._input=new Qx(this),this._physics=new zc(this),this._postprocessing=new x1(this),this._connection=new uu(this),this.assets=new oS,this.sceneLighting=new g1(this),this.addressables=new Nx(this),this.lightmaps=new yA(this),this.players=new c1(this),this.menu=new Ph(this),this.lodsManager=new Zx(this),this._animations=new fE(this),this.accessibility=new Yg(this);const t=()=>this._needsUpdateSize=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(n=>this._needsUpdateSize=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>this._intersectionObserver?.disconnect()),ce.register(this)}async createNewRenderer(e){if(this.renderer?.dispose(),e={...Ce.DefaultWebGLRendererParameters,...e},e.antialias??=(globalThis.devicePixelRatio??1)<=1.5,!e.canvas){const t=this.domElement?.shadowRoot?.querySelector("canvas");t?(e.canvas=t,ot&&console.log("Using canvas from shadow root",t)):ot&&console.warn("No canvas found in shadow root, creating new canvas. This may cause input events to not work correctly. To fix this, make sure to use the canvas provided by the Needle Engine Web Component (e.g. by using context.createNewRenderer() without parameters or passing the canvas from the shadow root explicitly).")}if(ot&&console.log("Using Renderer Parameters:",e,this.domElement),Ce.ExperimentalWebGPU){const{WebGPURenderer:t,PMREMGenerator:i}=await import("./three-core.min.js").then(s=>s.Three_WebGPU),n=new t({forceWebGL:!0,canvas:e.canvas,antialias:e.antialias,alpha:e.alpha});await n.init(),this.renderer=n,LA(i),console.warn(`[Needle] EXPERIMENTAL WebGPURenderer active (${this.renderer.backend?.isWebGPUBackend?"WebGPU":"WebGL2"} backend). Post-processing & WebXR are not supported in this mode.`)}else this.renderer=new Dr(e);return this.renderer.domElement.setAttribute("aria-label","3D rendering"),this.renderer.domElement.setAttribute("role","img"),Ce.ExperimentalWebGPU||(this.renderer.debug.checkShaderErrors=M()||x("checkshadererrors")===!0),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=bu,this.renderer.setClearColor(new oe("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=$O,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=Yo,Ce.ExperimentalWebGPU||(this.renderer.library=new WO),this.lodsManager.setRenderer(this.renderer),this.input.bindEvents(),vE(this,this.renderer.domElement),this.renderer}_intersectionObserver=null;internalOnUpdateVisible(){this._intersectionObserver?.disconnect(),this._intersectionObserver?.observe(this.domElement)}_disposeCallbacks=[];requestSizeUpdate(){this._needsUpdateSize=!0}maxRenderResolution;get devicePixelRatio(){return this._devicePixelRatio}set devicePixelRatio(e){e!==this._devicePixelRatio&&(this._devicePixelRatio=e,this._needsUpdateSize=!0)}_devicePixelRatio="auto";updateSize(e=!1){if(e||!this.isManagedExternally&&this.renderer.xr?.isPresenting===!1){this._needsUpdateSize=!1;const t=this.resolutionScaleFactor;let i=this.domWidth*t,n=this.domHeight*t;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),i=Math.min(this.maxRenderResolution.x,i),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),n=Math.min(this.maxRenderResolution.y,n));const s=this.mainCamera;this.updateAspect(s),this.renderer.setSize(i,n,!0),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%";const r=typeof this.devicePixelRatio=="number"?this.devicePixelRatio:this.devicePixelRatio==="auto"?Math.min(2,window.devicePixelRatio):void 0;r!==void 0&&this.renderer.setPixelRatio(r),this.composer&&(this.composer.setSize?.call(this.composer,i,n),r!==void 0&&"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&this.composer.setPixelRatio?.call(this.composer,window.devicePixelRatio))}}updateAspect(e,t,i){if(!e)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const n=t/i;if(e.isPerspectiveCamera){const s=e,r=s.aspect;s.aspect=n,r!==s.aspect&&e.updateProjectionMatrix()}else if(e.isOrthographicCamera){const s=e,r=s.top-s.bottom,a=r*n/2,l=r/2;(s.left!=-a||s.top!=l)&&(s.left=-a,s.right=a,s.top=l,s.bottom=-l,e.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}_originalCreationArgs;async onCreate(e){return this.create(e)}async create(e){try{this._isCreating=!0,e!==this._originalCreationArgs&&(this._originalCreationArgs=th(e)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(e);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onUnhandledRejection=e=>{this.onError(e.reason)};onError(e){this.domElement.dispatchEvent(new CustomEvent("error",{detail:e}))}clear(){ce.dispatchCallback(de.ContextClearing,this),po(this,de.ContextClearing),ki(this.scene,!0,!0),this.scene=new Fi,this._fallbackCamera=null,this._mainCamera=null,this.addressables?.dispose(),this.lightmaps?.clear(),this.accessibility?.clear(),this.resetSubsystems(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),ce.dispatchCallback(de.ContextCleared,this)}resetRuntimeState(){if(this.isInXR)throw new Error("Context.resetRuntimeState() is not supported during an active XR session. End the session first.");const e=t=>!t.destroyed&&t.__internalDidAwake===!0;if(M()&&this.scripts.some(e)){const t=this.scripts.filter(e);console.warn(`Context.resetRuntimeState() dropped ${t.length} live component(s) without teardown \u2014 their onDisable/onDestroy will never run and resources they hold (event listeners, timers, physics state) leak. Call destroy() on scene content before resetting.`,t.slice(0,10))}hA(this),bI(this),this.resetSubsystems()}resetSubsystems(){this.physics?.engine?.dispose(),this._onBeforeRenderListeners.clear(),this._onAfterRenderListeners.clear(),this._events.clear(),this._events=new My,this.lights.length=0}dispose(){this.internalOnDestroy(),this.accessibility.dispose()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){Ce.Current=this,ce.dispatchCallback(de.ContextDestroying,this),po(this,de.ContextDestroying),(zi.camera===this._mainCamera||zi.camera===this._fallbackCamera||zi.camera===this.mainCameraComponent?.threeCamera)&&(zi.camera=null),this.renderer&&zi.renderer===this.renderer&&(zi.camera=null,zi.renderer=null,zi.object=null,zi.material=null,zi.scene=null,zi.geometry=null),this.clear(),this.lodsManager.disable(),this.renderer?.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(ot&&console.log("Disposing renderer"),this.renderer.dispose())),vI(this.scene),wI(this),this.scene=null,this.renderer=null,this.application.dispose(),this.input.dispose(),this.connection.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const e of this._disposeCallbacks)try{e()}catch(t){console.error("Error in on dispose callback:",t,e)}this.domElement?.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,ce.dispatchCallback(de.ContextDestroyed,this),po(this,de.ContextDestroyed),ce.unregister(this),ce.Registered.length===0&&(cA(),We.dispose()),Ce.Current===this&&(Ce.Current=null)}registerCoroutineUpdate(e,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+e.name+`
867
+ `,o);return}e||(e=Q.Current,ot&&console.warn("> Registering component without context"));const t=e?.new_scripts;t.includes(o)||t.push(o)}const ye=class Pe{static _defaultTargetFramerate={value:90,toString(){return this.value}};static get DefaultTargetFrameRate(){return Pe._defaultTargetFramerate.value}static set DefaultTargetFrameRate(e){Pe._defaultTargetFramerate.value=e}static _defaultWebglRendererParameters={alpha:!1,powerPreference:I.isiOS()||I.isMacOS()?"default":"high-performance",stencil:!0};static get DefaultWebGLRendererParameters(){return Pe._defaultWebglRendererParameters}static ExperimentalWebGPU=!1;get version(){return ci}static get Current(){return ce.Current}static set Current(e){ce.Current=e}static get All(){return ce.All}name;alias;isManagedExternally=!1;isPaused=!1;get lifecycle(){return this._lifecycle}set lifecycle(e){if(e===this._lifecycle)return;const t=this._lifecycle;this._lifecycle=e,t==="held"&&e==="running"&&this.reconcileLifecycleAfterHold(),this.events.emit("lifecycle-changed",{context:this,lifecycle:e,previous:t})}_lifecycle="running";reconcileLifecycleAfterHold(){this.scene&&(Ih(this.scene,!0),$n(this.scene,e=>{e.__didAwake===!0&&e.__didEnable!==!0&&!e.destroyed&&e.activeAndEnabled&&e.__internalEnable()},!0))}runInBackground=!1;targetFrameRate;physicsSteps=1;hash;domElement;appendHTMLElement(e){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(e):this.domElement.appendChild(e)}xrFrameRateLimit=0;get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;_boundingClientRectFrame=-1;_boundingClientRect=null;_domX;_domY;calculateBoundingClientRect(){if(this.xr){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){return this.renderer?.xr?.isPresenting||!1}xr=null;get xrSessionMode(){return this.xr?.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){return this.renderer?.xr?.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){return this.renderer.xr.isPresenting?this.renderer?.xr?.getCamera():void 0}_xrFrame=null;get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=-1;scene;renderer;get composer(){return this.postprocessing.composer}set composer(e){this.postprocessing.composer=e}scripts=[];scripts_pausedChanged=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];scripts_immersive_vr=[];scripts_immersive_ar=[];coroutines={};post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];pre_update_oneshot_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];new_scripts_xr=[];mainCameraComponent=void 0;get sceneData(){return u1(this)}get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.threeCamera||e.buildCamera(),e.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new me(35,this.domWidth/this.domHeight,.1,1e3),this.scene?.add(this._fallbackCamera)),this._fallbackCamera}set mainCamera(e){this._mainCamera=e}_mainCamera=null;_fallbackCamera=null;get application(){return this._application}_application;get animations(){return this._animations}_animations;get time(){return this._time}_time;get input(){return this._input}_input;get physics(){return this._physics}_physics;get postprocessing(){return this._postprocessing}_postprocessing;get connection(){return this._connection}_connection;get events(){return this._events}_events=new My;assets;lights=new Array;get mainLight(){let e=null;for(const t of this.lights)t.type==="directional"&&(!e||t.intensity>e.intensity)&&(e=t);return e}get rendererData(){return this.sceneLighting}sceneLighting;addressables;lightmaps;players;lodsManager;menu;accessibility;get isCreated(){return this._isCreated}get rootSourceId(){return this.rootSceneSourceIdentifiers[0]||void 0}_needsUpdateSize=!1;_isCreated=!1;_isCreating=!1;_isVisible=!1;_stats=L2?new iR:null;constructor(e){this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer&&(this.renderer=e.renderer,this.isManagedExternally=!0),e?.runInBackground!==void 0&&(this.runInBackground=e.runInBackground),e?.scene?this.scene=e.scene:this.scene=new Fi,this._fallbackCamera&&!this._fallbackCamera.parent&&this.scene.add(this._fallbackCamera),e?.camera&&(this._mainCamera=e.camera),this._application=new no(this),this._time=new b1,this._input=new Qx(this),this._physics=new zc(this),this._postprocessing=new x1(this),this._connection=new uu(this),this.assets=new oS,this.sceneLighting=new g1(this),this.addressables=new Nx(this),this.lightmaps=new yA(this),this.players=new c1(this),this.menu=new Ph(this),this.lodsManager=new Zx(this),this._animations=new fE(this),this.accessibility=new Yg(this);const t=()=>this._needsUpdateSize=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(n=>this._needsUpdateSize=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>this._intersectionObserver?.disconnect()),ce.register(this)}async createNewRenderer(e){if(this.renderer?.dispose(),e={...Pe.DefaultWebGLRendererParameters,...e},e.antialias??=(globalThis.devicePixelRatio??1)<=1.5,!e.canvas){const t=this.domElement?.shadowRoot?.querySelector("canvas");t?(e.canvas=t,ot&&console.log("Using canvas from shadow root",t)):ot&&console.warn("No canvas found in shadow root, creating new canvas. This may cause input events to not work correctly. To fix this, make sure to use the canvas provided by the Needle Engine Web Component (e.g. by using context.createNewRenderer() without parameters or passing the canvas from the shadow root explicitly).")}if(ot&&console.log("Using Renderer Parameters:",e,this.domElement),Pe.ExperimentalWebGPU){const{WebGPURenderer:t,PMREMGenerator:i}=await import("./three-core.min.js").then(s=>s.Three_WebGPU),n=new t({forceWebGL:!0,canvas:e.canvas,antialias:e.antialias,alpha:e.alpha});await n.init(),this.renderer=n,LA(i),console.warn(`[Needle] EXPERIMENTAL WebGPURenderer active (${this.renderer.backend?.isWebGPUBackend?"WebGPU":"WebGL2"} backend). Post-processing & WebXR are not supported in this mode.`)}else this.renderer=new Dr(e);return this.renderer.domElement.setAttribute("aria-label","3D rendering"),this.renderer.domElement.setAttribute("role","img"),Pe.ExperimentalWebGPU||(this.renderer.debug.checkShaderErrors=M()||x("checkshadererrors")===!0),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=bu,this.renderer.setClearColor(new oe("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=$O,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=Yo,Pe.ExperimentalWebGPU||(this.renderer.library=new WO),this.lodsManager.setRenderer(this.renderer),this.input.bindEvents(),vE(this,this.renderer.domElement),this.renderer}_intersectionObserver=null;internalOnUpdateVisible(){this._intersectionObserver?.disconnect(),this._intersectionObserver?.observe(this.domElement)}_disposeCallbacks=[];requestSizeUpdate(){this._needsUpdateSize=!0}maxRenderResolution;get devicePixelRatio(){return this._devicePixelRatio}set devicePixelRatio(e){e!==this._devicePixelRatio&&(this._devicePixelRatio=e,this._needsUpdateSize=!0)}_devicePixelRatio="auto";updateSize(e=!1){if(e||!this.isManagedExternally&&this.renderer.xr?.isPresenting===!1){this._needsUpdateSize=!1;const t=this.resolutionScaleFactor;let i=this.domWidth*t,n=this.domHeight*t;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),i=Math.min(this.maxRenderResolution.x,i),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),n=Math.min(this.maxRenderResolution.y,n));const s=this.mainCamera;this.updateAspect(s),this.renderer.setSize(i,n,!0),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%";const r=typeof this.devicePixelRatio=="number"?this.devicePixelRatio:this.devicePixelRatio==="auto"?Math.min(2,window.devicePixelRatio):void 0;r!==void 0&&this.renderer.setPixelRatio(r),this.composer&&(this.composer.setSize?.call(this.composer,i,n),r!==void 0&&"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&this.composer.setPixelRatio?.call(this.composer,window.devicePixelRatio))}}updateAspect(e,t,i){if(!e)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const n=t/i;if(e.isPerspectiveCamera){const s=e,r=s.aspect;s.aspect=n,r!==s.aspect&&e.updateProjectionMatrix()}else if(e.isOrthographicCamera){const s=e,r=s.top-s.bottom,a=r*n/2,l=r/2;(s.left!=-a||s.top!=l)&&(s.left=-a,s.right=a,s.top=l,s.bottom=-l,e.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}_originalCreationArgs;async onCreate(e){return this.create(e)}async create(e){try{this._isCreating=!0,e!==this._originalCreationArgs&&(this._originalCreationArgs=th(e)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(e);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onUnhandledRejection=e=>{this.onError(e.reason)};onError(e){this.domElement.dispatchEvent(new CustomEvent("error",{detail:e}))}clear(){ce.dispatchCallback(de.ContextClearing,this),po(this,de.ContextClearing),ki(this.scene,!0,!0),this.scene=new Fi,this._fallbackCamera=null,this._mainCamera=null,this.addressables?.dispose(),this.lightmaps?.clear(),this.accessibility?.clear(),this.resetSubsystems(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),ce.dispatchCallback(de.ContextCleared,this)}resetRuntimeState(){if(this.isInXR)throw new Error("Context.resetRuntimeState() is not supported during an active XR session. End the session first.");const e=t=>!t.destroyed&&t.__internalDidAwake===!0;if(M()&&this.scripts.some(e)){const t=this.scripts.filter(e);console.warn(`Context.resetRuntimeState() dropped ${t.length} live component(s) without teardown \u2014 their onDisable/onDestroy will never run and resources they hold (event listeners, timers, physics state) leak. Call destroy() on scene content before resetting.`,t.slice(0,10))}hA(this),bI(this),this.resetSubsystems()}resetSubsystems(){this.physics?.engine?.dispose(),this._onBeforeRenderListeners.clear(),this._onAfterRenderListeners.clear(),this._events.clear(),this._events=new My,this.lights.length=0}dispose(){this.internalOnDestroy(),this.accessibility.dispose()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){Pe.Current=this,ce.dispatchCallback(de.ContextDestroying,this),po(this,de.ContextDestroying),(zi.camera===this._mainCamera||zi.camera===this._fallbackCamera||zi.camera===this.mainCameraComponent?.threeCamera)&&(zi.camera=null),this.renderer&&zi.renderer===this.renderer&&(zi.camera=null,zi.renderer=null,zi.object=null,zi.material=null,zi.scene=null,zi.geometry=null),this.clear(),this.lodsManager.disable(),this.renderer?.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(ot&&console.log("Disposing renderer"),this.renderer.dispose())),vI(this.scene),wI(this),this.scene=null,this.renderer=null,this.application.dispose(),this.input.dispose(),this.connection.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const e of this._disposeCallbacks)try{e()}catch(t){console.error("Error in on dispose callback:",t,e)}this.domElement?.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,ce.dispatchCallback(de.ContextDestroyed,this),po(this,de.ContextDestroyed),ce.unregister(this),ce.Registered.length===0&&(cA(),We.dispose()),Pe.Current===this&&(Pe.Current=null)}registerCoroutineUpdate(e,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+e.name+`
868
868
  Coroutine functions must be generators: "*myCoroutine() {...}"
869
869
  Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn("Camera component is missing camera",e);return}const t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;const i=e.threeCamera;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners=new Map;_onAfterRenderListeners=new Map;addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){const i=[];this._onBeforeRenderListeners.set(e.uuid,i),e.onBeforeRender=this._createRenderCallbackWrapper(i)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const i=this._onBeforeRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(e,t){if(!this._onAfterRenderListeners.has(e.uuid)){const i=[];this._onAfterRenderListeners.set(e.uuid,i),e.onAfterRender=this._createRenderCallbackWrapper(i)}this._onAfterRenderListeners.get(e.uuid)?.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const i=this._onAfterRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(e){return(t,i,n,s,r,a)=>{for(let l=0;l<e.length;l++){const c=e[l];c(t,i,n,s,r,a)}}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;if(!this._needsVisibleUpdate&&this._lastStyleComputedResult!==void 0)return this._lastStyleComputedResult;this._needsVisibleUpdate=!1;const e=getComputedStyle(this.domElement);return this._lastStyleComputedResult=e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0",this._lastStyleComputedResult}_needsVisibleUpdate=!0;_lastStyleComputedResult=void 0;_createId=0;async internalOnCreate(e){const t=++this._createId;ot&&console.log("Creating context",this.name,e);const i=globalThis["needle:dependencies:ready"];i instanceof Promise&&(ot&&console.log("Waiting for dependencies to be ready"),await i.catch(h=>{if(ot||M()){if(ul("Needle Engine dependencies failed to load. Please check the console for more details"),h instanceof ReferenceError){let d="YourComponentName";const u=h.message.indexOf("'");if(u>0){const m=h.message.indexOf("'",u+1);if(m>0){const g=h.message.substring(u+1,m);g.length>3&&(d=g)}}console.error(`Needle Engine dependencies failed to load:
870
870
 
@@ -874,13 +874,13 @@ Possible solutions:
874
874
  \u2192 Replace @serializable(${d}) in your script with @serializable(Behaviour)
875
875
  \u2192 If you only need type information try importing the type only, e.g: import { type ${d} }
876
876
 
877
- ---`,h);return}console.error("Needle Engine dependencies failed to load",h)}}).then(()=>{ot&&console.log("Needle Engine dependencies are ready")})),this.clear();const n=this.renderer,s=!n||n.isDisposed===!0;this.isManagedExternally===!1&&s?await this.createNewRenderer():this.lodsManager.setRenderer(this.renderer),this.renderer?.setAnimationLoop(null),Ce.Current=this,await ce.dispatchCallback(de.ContextCreationStart,this);let r=!0,a;try{Ce.Current=this,e?a=await this.internalLoadInitialContent(t,e):a=[]}catch(h){console.error(h),r=!1}if(!r)return this.onError("Failed to load initial content"),!1;if(t!==this._createId||e?.abortSignal?.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return ot&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),Ce.Current=this,Ce.Current=this;for(let h=0;h<this.new_scripts.length;h++){const d=this.new_scripts[h];if(d.gameObject!==void 0&&d.gameObject!==null){d.gameObject.userData===void 0&&(d.gameObject.userData={}),d.gameObject.userData.components===void 0&&(d.gameObject.userData.components=[]);const u=d.gameObject.userData.components;u.includes(d)||u.push(d)}}if(this.post_setup_callbacks)for(let h=0;h<this.post_setup_callbacks.length;h++)Ce.Current=this,await this.post_setup_callbacks[h](this);if(!this._mainCamera){Ce.Current=this;let h=null;$n(this.scene,d=>{const u=d;if(u?.isCamera){if(Lh(u.gameObject),!u.activeAndEnabled)return;if(u.tag==="MainCamera")return h=u,!0;h=u}}),h?this.setCurrentCamera(h):!ce.dispatchCallback(de.MissingCamera,this,{files:a})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),Ce.Current=this,Dp(this),this.physics.engine&&(this.physics.engine?.step(0),this.physics.engine?.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._needsUpdateSize=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",this.domElement.shadowRoot?.appendChild(this._stats.dom)),ot&&Lu(this.scene,!0),this.targetFrameRate===void 0?(ot&&console.warn("No target framerate set, using default",Ce.DefaultTargetFrameRate),this.targetFrameRate=Ce._defaultTargetFramerate):ot&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const l=ce.dispatchCallback(de.ContextCreated,this,{files:a});if(l){const h=this.domElement;"internalSetLoadingMessage"in h&&typeof h.internalSetLoadingMessage=="function"&&h?.internalSetLoadingMessage("finish loading"),await l}if(e?.abortSignal?.aborted)return!1;const c=this.rootSourceId;return c&&this.sceneLighting.enable(c),po(this,de.ContextCreated),ot&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!e?.abortSignal?.aborted&&this.restartRenderLoop(),!0}rootSceneSourceIdentifiers=[];async internalLoadInitialContent(e,t){this.rootSceneSourceIdentifiers.length=0;const i=new Array;if(t.files.length===0)return i;const n=[...t.files];this.rootSceneSourceIdentifiers.push(...n);const s={name:"",progress:null,index:0,count:n.length},r=is(),a=0;for(let l=0;l<n.length;l++){if(t.abortSignal?.aborted){ot&&console.log("Aborting loading because of abort signal");break}if(e!==this._createId){ot&&console.log("Aborting loading because create id changed",e,this._createId);break}const c=n[l];t?.onLoadingStart?.call(this,l,c),ot&&console.log("Context Load "+c);const h=await r.loadSync(this,c,c,a,d=>{t.abortSignal?.aborted||(s.name=c,s.progress=d,s.index=l,s.count=n.length,t.onLoadingProgress?.call(this,s))});t?.onLoadingFinished?.call(this,l,c,h??null),h?i.push({src:c,file:h}):console.warn("Could not load file: "+c)}if(e!==this._createId||t.abortSignal?.aborted){ot&&console.log("Aborting loading because create id changed or abort signal was set",e,this._createId);for(const l of i)if(l&&l.file)for(const c of l.file.scenes)ki(c,!0,!0)}else{let l=!1;for(const c of i)c&&c.file&&(c.file.scene?(l=!0,this.scene.add(c.file.scene)):console.warn("No scene found in loaded file"));if(!l){for(const c of i)if(c&&c.file&&"parser"in c.file){if(!Array.isArray(c.file.parser.json.materials))continue;const h=new Dn;h.name="Material Preview";let d=0;for(let u=0;u<c.file.parser.json.materials.length;u++){const m=await c.file.parser.getDependency("material",u),g=new R;g.position.x=u*1.1,g.position.y=d,h.add(g),Gs.createPrimitive("ShaderBall",{parent:g,material:m})}d+=1,c.file.scene=h,c.file.scenes=[h],this.scene.add(h)}}}return i}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((e,t)=>{this.isManagedExternally||this.update(e,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}_renderlooperrors=0;update(e,t){if(t===void 0&&(t=null),M()||ot||mI())try{this.internalStep(e,t),this._renderlooperrors=0}catch(i){this._renderlooperrors+=1,(M()||ot)&&(i instanceof Error||i instanceof TypeError)&&Fe("Caught unhandled exception during render-loop - see console for details.",{type:Wi.Error}),console.error("Frame #"+this.time.frame+`
878
- `,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),ct.sendError(Ce.Current,"renderloop",i instanceof Error?i:new Error(String(i)))),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}setCameraFocusRect(e,t){const i=this._focusRect;if(this._focusRect=e,t&&Object.assign(this.focusRectSettings,t),t?.damping===void 0&&i){let n=i;i instanceof HTMLElement&&(n=i.getBoundingClientRect()),n&&"top"in n&&n.bottom>=-100&&n.right>=-100&&n.top<=window.innerHeight+100&&n.left<=window.innerWidth+100&&(this.focusRectSettings.damping=.2)}}get focusRect(){return this._focusRect}get focusRectSize(){const e=this._focusRect;if(e&&(e instanceof DOMRect||"width"in e&&"height"in e&&"x"in e&&"y"in e))return{x:e.x,y:e.y,width:e.width,height:e.height};if(e instanceof HTMLElement){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}return null}focusRectSettings={damping:0,zoom:1,offsetX:0,offsetY:0};_focusRect=null;_lastTimestamp=0;_accumulatedTime=0;_dispatchReadyAfterFrame=!1;internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){if(this.frameBegin(e,t)===!1)return!1;const i=this._lifecycle==="held";return i?xS(this):(this.processLifecycle(),this.updateScripts(),this.stepPhysicsDefault()),this.preRender(t,i),!0}frameBegin(e,t){!this.input.eventsBound&&!this.input.eventsExplicitlyUnbound&&this.input.bindEvents(),this.renderer.info.autoReset=!!t,this.renderer.info.autoReset===!1&&this.renderer.info.reset(),this._needsVisibleUpdate=!0;const i=t!==null&&this._xrFrame===null;if(this._xrFrame=t,i&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let n=this.targetFrameRate;if(typeof n=="object"&&(n=n.value),this._accumulatedTime<1/(n+1))return!1;this._accumulatedTime=0}return this._stats?.begin(),Ce.Current=this,this.onHandlePaused()?!1:(Ce.Current=this,this.time.update(),j2&&console.log("FPS",this.time.smoothedFps.toFixed(0)),!0)}processLifecycle(){_I(this.scene),AS(),Dp(this),Ih(this.scene),SS(this),po(this,-1)}updateScripts(){for(;this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const e=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(e)}if(this.pre_update_oneshot_callbacks){for(const e in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[e]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const e in this.pre_update_callbacks)this.pre_update_callbacks[e]();this._currentFrameEvent=0;for(let e=0;e<this.scripts_earlyUpdate.length;e++){const t=this.scripts_earlyUpdate[e];t.activeAndEnabled&&t.earlyUpdate!==void 0&&(Ce.Current=this,t.earlyUpdate())}this.executeCoroutines(0),po(this,0),this._currentFrameEvent=1;for(let e=0;e<this.scripts_update.length;e++){const t=this.scripts_update[e];t.activeAndEnabled&&t.update!==void 0&&(Ce.Current=this,t.update())}this.executeCoroutines(1),po(this,1),this._currentFrameEvent=2;for(let e=0;e<this.scripts_lateUpdate.length;e++){const t=this.scripts_lateUpdate[e];t.activeAndEnabled&&t.lateUpdate!==void 0&&(Ce.Current=this,t.lateUpdate())}this.executeCoroutines(2),po(this,2)}stepPhysicsDefault(){this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps)}preRender(e,t){if(this.isVisibleToUser||this.runInBackground){if(this._currentFrameEvent=3,!t){for(let i=0;i<this.scripts_onBeforeRender.length;i++){const n=this.scripts_onBeforeRender[i];n.activeAndEnabled&&n.onBeforeRender!==void 0&&(Ce.Current=this,n.onBeforeRender(e))}this.executeCoroutines(3),po(this,3)}if(this._needsUpdateSize&&this.updateSize(),this.pre_render_callbacks)for(const i in this.pre_render_callbacks)this.pre_render_callbacks[i](e);if(this._focusRect&&this.mainCamera instanceof me){const i=this.focusRectSettings,n=i.damping>0?this.time.deltaTime/i.damping:1;PT(this._focusRect,this.focusRectSettings,n,this.mainCamera,this.renderer)}}}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,i=this.time.deltaTime/t;for(let n=0;n<t;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(yI(this),this._currentFrameEvent=-1,zi.camera=this.mainCamera,zi.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){if(this._lifecycle!=="held"){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(Ce.Current=this,t.onAfterRender())}this.executeCoroutines(4),po(this,4)}if(this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}if(this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats){this._stats.end();const e=this.time.fps<20?50:150;if(this.time.frameCount%e===0||this.time.frameCount===1){const t=window.performance&&window.performance.memory?`${(window.performance.memory.usedJSHeapSize/1024/1024).toFixed(2)} MB`:"n/a",i=this.renderer.getContext();console.log(this.renderer.info.render.calls+" DrawCalls",`
877
+ ---`,h);return}console.error("Needle Engine dependencies failed to load",h)}}).then(()=>{ot&&console.log("Needle Engine dependencies are ready")})),this.clear();const n=this.renderer,s=!n||n.isDisposed===!0;this.isManagedExternally===!1&&s?await this.createNewRenderer():this.lodsManager.setRenderer(this.renderer),this.renderer?.setAnimationLoop(null),Pe.Current=this,await ce.dispatchCallback(de.ContextCreationStart,this);let r=!0,a;try{Pe.Current=this,e?a=await this.internalLoadInitialContent(t,e):a=[]}catch(h){console.error(h),r=!1}if(!r)return this.onError("Failed to load initial content"),!1;if(t!==this._createId||e?.abortSignal?.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return ot&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),Pe.Current=this,Pe.Current=this;for(let h=0;h<this.new_scripts.length;h++){const d=this.new_scripts[h];if(d.gameObject!==void 0&&d.gameObject!==null){d.gameObject.userData===void 0&&(d.gameObject.userData={}),d.gameObject.userData.components===void 0&&(d.gameObject.userData.components=[]);const u=d.gameObject.userData.components;u.includes(d)||u.push(d)}}if(this.post_setup_callbacks)for(let h=0;h<this.post_setup_callbacks.length;h++)Pe.Current=this,await this.post_setup_callbacks[h](this);if(!this._mainCamera){Pe.Current=this;let h=null;$n(this.scene,d=>{const u=d;if(u?.isCamera){if(Lh(u.gameObject),!u.activeAndEnabled)return;if(u.tag==="MainCamera")return h=u,!0;h=u}}),h?this.setCurrentCamera(h):!ce.dispatchCallback(de.MissingCamera,this,{files:a})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),Pe.Current=this,Dp(this),this.physics.engine&&(this.physics.engine?.step(0),this.physics.engine?.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._needsUpdateSize=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",this.domElement.shadowRoot?.appendChild(this._stats.dom)),ot&&Lu(this.scene,!0),this.targetFrameRate===void 0?(ot&&console.warn("No target framerate set, using default",Pe.DefaultTargetFrameRate),this.targetFrameRate=Pe._defaultTargetFramerate):ot&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const l=ce.dispatchCallback(de.ContextCreated,this,{files:a});if(l){const h=this.domElement;"internalSetLoadingMessage"in h&&typeof h.internalSetLoadingMessage=="function"&&h?.internalSetLoadingMessage("finish loading"),await l}if(e?.abortSignal?.aborted)return!1;const c=this.rootSourceId;return c&&this.sceneLighting.enable(c),po(this,de.ContextCreated),ot&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!e?.abortSignal?.aborted&&this.restartRenderLoop(),!0}rootSceneSourceIdentifiers=[];async internalLoadInitialContent(e,t){this.rootSceneSourceIdentifiers.length=0;const i=new Array;if(t.files.length===0)return i;const n=[...t.files];this.rootSceneSourceIdentifiers.push(...n);const s={name:"",progress:null,index:0,count:n.length},r=is(),a=0;for(let l=0;l<n.length;l++){if(t.abortSignal?.aborted){ot&&console.log("Aborting loading because of abort signal");break}if(e!==this._createId){ot&&console.log("Aborting loading because create id changed",e,this._createId);break}const c=n[l];t?.onLoadingStart?.call(this,l,c),ot&&console.log("Context Load "+c);const h=await r.loadSync(this,c,c,a,d=>{t.abortSignal?.aborted||(s.name=c,s.progress=d,s.index=l,s.count=n.length,t.onLoadingProgress?.call(this,s))});t?.onLoadingFinished?.call(this,l,c,h??null),h?i.push({src:c,file:h}):console.warn("Could not load file: "+c)}if(e!==this._createId||t.abortSignal?.aborted){ot&&console.log("Aborting loading because create id changed or abort signal was set",e,this._createId);for(const l of i)if(l&&l.file)for(const c of l.file.scenes)ki(c,!0,!0)}else{let l=!1;for(const c of i)c&&c.file&&(c.file.scene?(l=!0,this.scene.add(c.file.scene)):console.warn("No scene found in loaded file"));if(!l){for(const c of i)if(c&&c.file&&"parser"in c.file){if(!Array.isArray(c.file.parser.json.materials))continue;const h=new Dn;h.name="Material Preview";let d=0;for(let u=0;u<c.file.parser.json.materials.length;u++){const m=await c.file.parser.getDependency("material",u),g=new R;g.position.x=u*1.1,g.position.y=d,h.add(g),Gs.createPrimitive("ShaderBall",{parent:g,material:m})}d+=1,c.file.scene=h,c.file.scenes=[h],this.scene.add(h)}}}return i}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((e,t)=>{this.isManagedExternally||this.update(e,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}_renderlooperrors=0;update(e,t){if(t===void 0&&(t=null),M()||ot||mI())try{this.internalStep(e,t),this._renderlooperrors=0}catch(i){this._renderlooperrors+=1,(M()||ot)&&(i instanceof Error||i instanceof TypeError)&&Fe("Caught unhandled exception during render-loop - see console for details.",{type:Wi.Error}),console.error("Frame #"+this.time.frame+`
878
+ `,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),ct.sendError(Pe.Current,"renderloop",i instanceof Error?i:new Error(String(i)))),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}setCameraFocusRect(e,t){const i=this._focusRect;if(this._focusRect=e,t&&Object.assign(this.focusRectSettings,t),t?.damping===void 0&&i){let n=i;i instanceof HTMLElement&&(n=i.getBoundingClientRect()),n&&"top"in n&&n.bottom>=-100&&n.right>=-100&&n.top<=window.innerHeight+100&&n.left<=window.innerWidth+100&&(this.focusRectSettings.damping=.2)}}get focusRect(){return this._focusRect}get focusRectSize(){const e=this._focusRect;if(e&&(e instanceof DOMRect||"width"in e&&"height"in e&&"x"in e&&"y"in e))return{x:e.x,y:e.y,width:e.width,height:e.height};if(e instanceof HTMLElement){const t=e.getBoundingClientRect();return{x:t.x,y:t.y,width:t.width,height:t.height}}return null}focusRectSettings={damping:0,zoom:1,offsetX:0,offsetY:0};_focusRect=null;_lastTimestamp=0;_accumulatedTime=0;_dispatchReadyAfterFrame=!1;internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){if(this.frameBegin(e,t)===!1)return!1;const i=this._lifecycle==="held";return i?xS(this):(this.processLifecycle(),this.updateScripts(),this.stepPhysicsDefault()),this.preRender(t,i),!0}frameBegin(e,t){!this.input.eventsBound&&!this.input.eventsExplicitlyUnbound&&this.input.bindEvents(),this.renderer.info.autoReset=!!t,this.renderer.info.autoReset===!1&&this.renderer.info.reset(),this._needsVisibleUpdate=!0;const i=t!==null&&this._xrFrame===null;if(this._xrFrame=t,i&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let n=this.targetFrameRate;if(typeof n=="object"&&(n=n.value),this._accumulatedTime<1/(n+1))return!1;this._accumulatedTime=0}return this._stats?.begin(),Pe.Current=this,this.onHandlePaused()?!1:(Pe.Current=this,this.time.update(),j2&&console.log("FPS",this.time.smoothedFps.toFixed(0)),!0)}processLifecycle(){_I(this.scene),AS(),Dp(this),Ih(this.scene),SS(this),po(this,-1)}updateScripts(){for(;this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const e=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(e)}if(this.pre_update_oneshot_callbacks){for(const e in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[e]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const e in this.pre_update_callbacks)this.pre_update_callbacks[e]();this._currentFrameEvent=0;for(let e=0;e<this.scripts_earlyUpdate.length;e++){const t=this.scripts_earlyUpdate[e];t.activeAndEnabled&&t.earlyUpdate!==void 0&&(Pe.Current=this,t.earlyUpdate())}this.executeCoroutines(0),po(this,0),this._currentFrameEvent=1;for(let e=0;e<this.scripts_update.length;e++){const t=this.scripts_update[e];t.activeAndEnabled&&t.update!==void 0&&(Pe.Current=this,t.update())}this.executeCoroutines(1),po(this,1),this._currentFrameEvent=2;for(let e=0;e<this.scripts_lateUpdate.length;e++){const t=this.scripts_lateUpdate[e];t.activeAndEnabled&&t.lateUpdate!==void 0&&(Pe.Current=this,t.lateUpdate())}this.executeCoroutines(2),po(this,2)}stepPhysicsDefault(){this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps)}preRender(e,t){if(this.isVisibleToUser||this.runInBackground){if(this._currentFrameEvent=3,!t){for(let i=0;i<this.scripts_onBeforeRender.length;i++){const n=this.scripts_onBeforeRender[i];n.activeAndEnabled&&n.onBeforeRender!==void 0&&(Pe.Current=this,n.onBeforeRender(e))}this.executeCoroutines(3),po(this,3)}if(this._needsUpdateSize&&this.updateSize(),this.pre_render_callbacks)for(const i in this.pre_render_callbacks)this.pre_render_callbacks[i](e);if(this._focusRect&&this.mainCamera instanceof me){const i=this.focusRectSettings,n=i.damping>0?this.time.deltaTime/i.damping:1;PT(this._focusRect,this.focusRectSettings,n,this.mainCamera,this.renderer)}}}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,i=this.time.deltaTime/t;for(let n=0;n<t;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(yI(this),this._currentFrameEvent=-1,zi.camera=this.mainCamera,zi.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){if(this._lifecycle!=="held"){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(Pe.Current=this,t.onAfterRender())}this.executeCoroutines(4),po(this,4)}if(this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}if(this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats){this._stats.end();const e=this.time.fps<20?50:150;if(this.time.frameCount%e===0||this.time.frameCount===1){const t=window.performance&&window.performance.memory?`${(window.performance.memory.usedJSHeapSize/1024/1024).toFixed(2)} MB`:"n/a",i=this.renderer.getContext();console.log(this.renderer.info.render.calls+" DrawCalls",`
879
879
  Render:`,{shaders:this.renderer.info.programs?.length,...this.renderer.info.render},`
880
880
  Memory:`,{usedMemory:t,...this.renderer.info.memory},`
881
881
  Renderer:`,{dpr:this.renderer.getPixelRatio(),windowDpr:window.devicePixelRatio,antialias:i.getContextAttributes()?.antialias,samples:i.getParameter(i.SAMPLES),resolution:`${this.renderer.domElement.width}x${this.renderer.domElement.height}`},`
882
- Target Framerate: `+this.targetFrameRate)}}this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),ce.dispatchCallback(de.ContextFirstFrameRendered,this))}_tempClearColor=new oe;_tempClearColor2=new oe;renderNow(e){if(!e&&(e=this.mainCamera,!e))return!1;if(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==bu&&v1(),this.postprocessing.update(),this.composer&&!this.isInXR){e&&"setMainCamera"in this.composer&&this.composer.passes[0]?.mainCamera!=e&&this.composer.setMainCamera(e);const t=this.renderer.getClearColor(this._tempClearColor),i=this.renderer.getClearAlpha();this._tempClearColor2.copy(t),this.renderer.setClearColor(t.convertSRGBToLinear(),this.renderer.getClearAlpha()),this.composer.render(this.time.deltaTime),this.renderer.setClearColor(this._tempClearColor2,i)}else e&&(this.isInXR&&I.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,e));return this._isRendering=!1,!0}_contextRestoreTries=0;handleRendererContextLost(){this.time.frame%10&&this.renderer.getContext().isContextLost()&&this._contextRestoreTries++<100&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}_wasPaused=!1;onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){D2&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(Ce.Current=this,i.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new ro(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new Ev(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Pe,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=_u,this._renderTarget.texture.magFilter=_u,this._renderTarget.texture.format=gu)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){const i=this.coroutines[e];for(let n=0;n<i.length;n++)try{const s=i[n];if(!s.comp||s.comp.destroyed||!s.main||s.comp.enabled===!1){F2&&console.log("Removing coroutine",s.comp,s.comp.enabled),i.splice(n,1),--n;continue}const r=s.chained;if(r&&r.length>0){const c=r[r.length-1].next();if(c.done&&r.pop(),t(c)&&(s.chained||(s.chained=[]),s.chained.push(c.value)),!c.done)continue}const a=s.main.next();if(a.done===!0){i.splice(n,1),--n;continue}const l=a.value;if(t(l)){if(l.next().done)continue;s.chained||(s.chained=[]),s.chained.push(l)}else if(l instanceof Promise){const c=l;s.chained||(s.chained=[]);const h=Hx(c);s.chained?.push(h);continue}}catch(s){console.error(s)}}function t(i){return!!(i&&i.next&&i.return)}}};xe([we()],ye.prototype,"scripts"),xe([we()],ye.prototype,"scripts_pausedChanged"),xe([we()],ye.prototype,"scripts_earlyUpdate"),xe([we()],ye.prototype,"scripts_update"),xe([we()],ye.prototype,"scripts_lateUpdate"),xe([we()],ye.prototype,"scripts_onBeforeRender"),xe([we()],ye.prototype,"scripts_onAfterRender"),xe([we()],ye.prototype,"scripts_WithCorroutines"),xe([we()],ye.prototype,"scripts_immersive_vr"),xe([we()],ye.prototype,"scripts_immersive_ar"),xe([we()],ye.prototype,"coroutines"),xe([we("keep")],ye.prototype,"post_setup_callbacks"),xe([we("keep")],ye.prototype,"pre_update_callbacks"),xe([we("keep")],ye.prototype,"pre_render_callbacks"),xe([we("keep")],ye.prototype,"post_render_callbacks"),xe([we()],ye.prototype,"pre_update_oneshot_callbacks"),xe([we()],ye.prototype,"new_scripts"),xe([we()],ye.prototype,"new_script_start"),xe([we()],ye.prototype,"new_scripts_pre_setup_callbacks"),xe([we()],ye.prototype,"new_scripts_post_setup_callbacks"),xe([we()],ye.prototype,"new_scripts_xr"),xe([we("undefined")],ye.prototype,"mainCameraComponent"),xe([we("null")],ye.prototype,"_mainCamera"),xe([we("null")],ye.prototype,"_fallbackCamera"),xe([we("custom")],ye.prototype,"_events"),xe([we("custom")],ye.prototype,"lights"),xe([we("keep")],ye.prototype,"_disposeCallbacks"),xe([we()],ye.prototype,"_cameraStack"),xe([we("custom")],ye.prototype,"_onBeforeRenderListeners"),xe([we("custom")],ye.prototype,"_onAfterRenderListeners"),xe([we("keep")],ye.prototype,"rootSceneSourceIdentifiers");let Q=ye;const nb=x("debugwebxr");class Y1{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(nb&&console.log("FOUND AVATAR HEAD",e.name),i.head=new ie("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(nb&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new ie("",t,e)),!i.rightHand&&n.includes("right")&&(nb&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new ie("",t,e)));for(let s=0;s<e.children.length;s++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[s];this.tryFindAvatarObjects(r,t,i)}}}class he extends oe{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.setRGB(Number.isFinite(e)?e:0,Number.isFinite(t)?t:0,Number.isFinite(i)?i:0),this.alpha=typeof n=="number"&&Number.isFinite(n)?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=j.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,s=t;return n.alpha!=null&&s.alpha!=null&&(this.alpha=j.lerp(n.alpha,s.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new he(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,s=t>>8&255,r=t>>0&255;return new he(i/255,n/255,s/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,s=t>>0&255;return new he(i/255,n/255,s/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new he(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new he(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new he(e[0],e[1],e[2],e[3]);if(e.length===3)return new he(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new he(e)}}const Kt=new v,K1=new v,Z1=new B,z2=x("debuggizmos"),zn=8947848,ob=32;class F{constructor(){}static enabled=!0;static isGizmo(e){return e[rb]!==void 0}static setVisible(e){for(const t of Di.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,s,r,a,l=!0){if(!F.enabled)return null;s||(s=zn);const c=q.active?.rigScale??1,h=Di.getTextLabel(n,t,i*c,s,r);return h[J1]=l===!1,a instanceof R&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=zn,n=0,s=!0){if(!F.enabled)return;const r=Di.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Kt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Kt.x,e.y+Kt.y,e.z+Kt.z),a.needsUpdate=!0,r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,Nn(r.material,i)}static DrawDirection(e,t,i=zn,n=0,s=!0,r=1){if(!F.enabled)return;const a=Di.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Kt.set(0,0,-r),Z1.set(t.x,t.y,t.z,t.w),Kt.applyQuaternion(Z1)):(Kt.set(t.x,t.y,t.z),Kt.multiplyScalar(r)),l.setXYZ(1,e.x+Kt.x,e.y+Kt.y,e.z+Kt.z),l.needsUpdate=!0,a.material.depthTest=s,a.material.depthWrite=!1,Nn(a.material,i)}static DrawLine(e,t,i=zn,n=0,s=!0){if(!F.enabled)return;const r=Di.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,Nn(r.material,i)}static DrawCircle(e,t,i,n=zn,s=0,r=!0){if(!F.enabled)return;const a=Di.getCircle(s);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Kt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,Nn(a.material,n)}static DrawWireSphere(e,t,i=zn,n=0,s=!0){if(!F.enabled)return;const r=Di.getSphere(t,n,!0);zr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,Nn(r.material,i)}static DrawSphere(e,t,i=zn,n=0,s=!0){if(!F.enabled)return;const r=Di.getSphere(t,n,!1);zr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,Nn(r.material,i)}static DrawWireBox(e,t,i=zn,n=0,s=!0,r=void 0){if(!F.enabled)return;const a=Di.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=s,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,Nn(a.material,i)}static DrawWireBox3(e,t=zn,i=0,n=!0){if(!F.enabled)return;const s=Di.getBox(i);s.position.copy(e.getCenter(Kt)),s.scale.copy(e.getSize(Kt)),s.material.depthTest=n,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1,Nn(s.material,t)}static _up=new v(0,1,0);static DrawArrow(e,t,i=zn,n=0,s=!0,r=!1){if(!F.enabled)return;const a=Di.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Kt.set(t.x,t.y,t.z).sub(K1.set(e.x,e.y,e.z)).normalize());const l=Kt.set(t.x,t.y,t.z).sub(K1.set(e.x,e.y,e.z)).length()*.1;a.scale.set(l,l,l),a.material.depthTest=s,a.material.wireframe=r,Nn(a.material,i),this.DrawLine(e,t,i,n,s)}static DrawWireMesh(e){const t=Di.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,Nn(t.material,e.color??zn)}}const N2=new ol(1,1,1);function sb(o=null){const e=new oe(o??14540253),t=new VO(N2);return new hf(t,new vu({color:e}))}function Nn(o,e){if(Array.isArray(o)){for(const i of o)Nn(i,e);return}const t=e instanceof he?e.a:1;o.color.set(e),o.opacity=t,o.transparent=t<1}const rb=Symbol("GizmoCache"),J1=Symbol("GizmoLabelOnTop");class Di{static familyName="needle-gizmos";static ensureFont(){let e=Le.FontLibrary.getFontFamily(this.familyName);e||(e=Le.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{Le.update()}))}static getTextLabel(e,t,i,n,s){this.ensureFont();let r=this.textLabelCache.pop(),a=1;s&&typeof s=="string"&&s?.length>=8&&s.startsWith("#")?(a=parseInt(s.substring(7),16)/255,s=s.substring(0,7),z2&&console.log(s,a)):typeof s=="object"&&s.a!==void 0&&(a=s.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:s??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new iw(l);const c=this,h=r;h.setText=function(d){this.set({textContent:d}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(Q.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new ol(1,1,1);t=new V(i)}return this.registerTimedObject(Q.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Qc;let i=t.geometry.getAttribute("position");i||(i=new lt(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(Q.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new Qc;let i=t.geometry.getAttribute("position");if(!i){i=new lt(new Float32Array(ob*3),3),t.geometry.setAttribute("position",i);const n=U(0,1,0),s=U(0,0,1),r=U(s);r.cross(n).normalize();const a=U(r),l=Math.PI*2/(ob-1);for(let c=0;c<ob+1;c++){const h=l*c;n.copy(a).multiplyScalar(Math.cos(h)*1),r.copy(s).multiplyScalar(Math.sin(h)*1);const d=n.add(r);i.setXYZ(c,d.x,d.y,d.z)}}}return t.frustumCulled=!1,this.registerTimedObject(Q.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new V(new rf(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(Q.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new V(new Rv(0,.5,1,8))),this.registerTimedObject(Q.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new V,t.material=new Ie),this.registerTimedObject(Q.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const s=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(s){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==s){const a=e.pre_render_callbacks.indexOf(s);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(s)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[rb]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(Q.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Le.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof Le.MeshUIBaseElement){if(Ys(n))continue;const s=e.isInVR,r=!1,a=!s;nh(n,e.mainCamera,r,a),n[J1]===!0&&Di.applyLabelOnTop(n)}}}static applyLabelOnTop(e){e.traverse(t=>{const i=t.material;if(i){t.renderOrder=999999;for(const n of Array.isArray(i)?i:[i])n.depthTest=!1,n.depthWrite=!1}})}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let s=t.length-1;s>=0;s--){const r=t[s];n>=i[s]-1e-6&&(t.splice(s,1),i.splice(s,1),r.removeFromParent(),Ys(r)!=!0&&r[rb].push(r))}}}const hi=x("debugphysics"),$2=x("debugworker"),eS=new Fs;class Jr{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new ee),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){eS.set(e),this.layerMask=eS}setMask(e){this.layerMask||(this.layerMask=new Fs);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class ab{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}let lb=null;function tS(o){lb=o}class zc{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;_engine;get engine(){return this._engine}set engine(e){this._engine=e}getOrCreatePhysicsEngine(){return this._engine===void 0&&lb&&(this._engine=lb(this.context)),this._engine??null}constructor(e){this.context=e}raycaster=new df;defaultRaycastOptions=new Jr;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new Fs;sphere=new Xc;sphereOverlap(e,t,i=!0,n=!1,s=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,s);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){hi&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return hi&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof GO&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let s=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Fs?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),hi&&console.time("raycast"),s.length=0,zc._raycasting++,this.intersect(this.raycaster,n,s,e),s.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),zc._raycasting--,hi&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",s?.length?[...s]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),s}intersect(e,t,i,n){for(const s of t){if(!s||s.visible===!1||F.isGizmo(s)||n.lineThreshold!==void 0&&n.lineThreshold<0&&s instanceof Qc)continue;let r=!0;const a=s,l=a.geometry,c=!l&&s.raycast!==R.prototype.raycast;if(s.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(s);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(!l&&!c||l&&!iS(l))&&(r=!1);if(r){const h=i.length;if(c)e.intersectObject(a,!1,i);else{const d=s.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof al&&(u=!1),d==="lod"){const m=Xv(s);m&&(a.geometry=m)}!u&&V2(a,e,i)||(n.useAcceleratedRaycast!==!1?Mp.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l}if(hi&&i.length!=h){const d=i[i.length-1];F.DrawWireSphere(d.point,.1,7798784,1,!1),F.DrawWireMesh({mesh:s,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,s.children,i,n)}return i}tempBoundingBox=new ri;intersectSphere(e,t,i,n,s,r,a,l){let c=e&&e.isMesh&&e.layers.test(n)&&!F.isGizmo(e);c&&=e.visible,c&&=!(e instanceof Qc),c&&=!(e instanceof al);const h=e,d=h.geometry;if(c&&l){const u=l(e);if(u===!1)return;u==="continue in children"&&(c=!1)}if(d&&iS(d)||(c=!1),c){if(a){const u=this.sphere;u.center.copy(t),u.radius=i;const m=s.length;if(Mp.runMeshBVHRaycast(this.sphere,h,s,this.context,{}),m!=s.length&&!r)return}else if(d.boundingBox||d.computeBoundingBox(),d.boundingBox){h.matrixWorldNeedsUpdate&&h.updateWorldMatrix(!1,!1);const u=this.tempBoundingBox.copy(d.boundingBox).applyMatrix4(h.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(u)){const g=le(e),y=g.distanceTo(m.center),b=new ab(e,y,g);if(s.push(b),!r)return}}}if(e.children)for(const u of e.children){const m=s.length;if(this.intersectSphere(u,t,i,n,s,r,a,l),m!=s.length&&!r)return}}}function iS(o){return!(o.index&&o.index.array.length<3)}const ea=new Xc,Op=new rl,W2=new sf;function V2(o,e,t){const i=o._computeIntersections;if(!i)return!1;let n=o["_computeIntersections:Needle"];return n||(n=o["_computeIntersections:Needle"]=function(s,r,a){const l=this,c=l.geometry.boundingSphere;if(c){if(l instanceof al){Op.setFromNormalAndCoplanarPoint(U(0,1,0),U(0,-l.position.y,0)),Op.applyMatrix4(l.matrixWorld,W2);const d=s.ray.intersectPlane(Op,U());if(d){ea.copy(c),ea.applyMatrix4(l.matrixWorld);const u=U(d).sub(s.ray.origin).length(),m=ea.radius*.5;u<m&&r.push({distance:u,point:d,object:l,normal:Op.normal.clone()})}return}ea.copy(c),ea.applyMatrix4(l.matrixWorld);const h=s.ray.intersectSphere(ea,U());if(h){const d=U(h).sub(s.ray.origin),u=d.length();if(u>ea.radius){const m=d.clone().normalize();r.push({distance:u,point:h,object:l,normal:m})}}}}),o._computeIntersections=n,e.intersectObject(o,!1,t),o._computeIntersections=i,!0}function cb(o,e){const t=o.children;o.children=[];try{return e()}finally{o.children=t}}var Mp;(o=>{let e=0;function t(_,w,S,O,L){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w?.isSkinnedMesh){const W=w,$=W.bvhNeedsUpdate;if(!W.staticGenerator)l(),r&&(cb(w,()=>{W.staticGenerator=new r(w),W.staticGenerator.applyWorldTransforms=!1,W.staticGeometry=W.staticGenerator.generate()}),D.boundsTree=a?.call(W.staticGeometry),W.staticGeometryLastUpdate=performance.now()+Math.random()*200,W.bvhNeedsUpdate=!0);else if(D.boundsTree&&(W.autoUpdateMeshBvhInterval!==void 0&&W.autoUpdateMeshBvhInterval>=0||$===!0)){const H=performance.now(),G=H-W.staticGeometryLastUpdate,E=W.autoUpdateMeshBvhInterval??100;($||G>E)&&(hi&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${G.toFixed(2)}ms`),W.bvhNeedsUpdate=!1,W.staticGeometryLastUpdate=H,cb(w,()=>W.staticGenerator?.generate(W.staticGeometry)),D.boundsTree.refit())}}else if(!D.boundsTree){h||f();let W=!0;if((O.xr||D[g]===!1||D.getAttribute("position")?.isInterleavedBufferAttribute||D.index&&D.index?.isInterleavedBufferAttribute||e>10)&&(W=!1),W&&u){if(D[m]===void 0){let $=null;if(b.length>0){const H=b.shift();H&&!H.running&&($=H)}if(!$&&y.length<3)try{$2&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",import.meta.url),$=new u,y.push($)}catch(H){H instanceof DOMException&&H.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(H),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(H)),e++}if($!=null&&!$.running){const H=w.name;hi&&console.log("<<<< worker start",H,$),D[m]="queued",performance.mark("bvh.create.start");const G=D.clone();try{$.generate(G).then(E=>{D[m]="done",D.boundsTree=E}).catch(E=>{D[m]="failed - "+E?.message,D[g]=!1,hi&&console.error("Failed to generate mesh bvh on worker",E)}).finally(()=>{hi&&console.log(">>>>> worker done",H,{hasBoundsTre:D.boundsTree!=null}),b.push($),G.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(E){console.error("Failed to generate mesh bvh on worker",E)}}else hi&&console.warn("No worker available")}}else(!d||!W)&&(l(),s&&(performance.mark("bvh.create.start"),D.boundsTree=new s(D),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(_ instanceof df){const W=_,$=w.raycast;if(D.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),hi&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(hi&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[m],hasAcceleratedRaycast:n!=null}),L.allowSlowRaycastFallback===!1&&(D.getAttribute("position")?.array?.length??0)>2e3)return hi&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const H=W.firstHitOnly;return W.firstHitOnly=!1,W.intersectObject(w,!1,S),W.firstHitOnly=H,w.raycast=$,!0}else if(_ instanceof Xc){const W=D.boundsTree;if(W){const $=_;if(c.copy(w.matrixWorld).invert(),$.applyMatrix4(c),W.intersectsSphere($)){const H=le(w),G=H.distanceTo($.center),E=new ab(w,G,H);S.push(E)}}return!0}return!1}o.runMeshBVHRaycast=t;let i=!1,n=null,s=null,r=null,a=null;function l(){i||(i=!0,import("./vendor-CdNldo8c.min.js").then(_=>_.index$1).then(_=>{n=_.acceleratedRaycast,s=_.MeshBVH,r=_.StaticGeometryGenerator,a=_.computeBoundsTree}).catch(_=>{(hi||M())&&console.error("Failed to load BVH library...",_.message)}))}const c=new J;let h=!1,d=!1,u=null;const m=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],b=[];function f(){h=!0,d=!0,Promise.resolve().then(()=>m4).then(_=>{u=_.GenerateMeshBVHWorker}).catch(_=>{hi||M()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",_)}).finally(()=>{d=!1})}})(Mp||(Mp={}));const nS=Symbol("gltf-loader-internal-usage-tracker"),G2=x("debugusers");class Nc{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Nc._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){Nc._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const s=t.call(this,i,n);return s.then(r=>(r&&(e._loadedObjects.add(r),r[nS]=e._loadingId),r)),s},null}afterRoot(e){Nc._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[nS],t instanceof R&&(t.parent||t instanceof V&&setTimeout(()=>{G2&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class oS{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
883
- `+i.src),e.preventDefault())}})}}const Rp=x("trackresources");function sS(){return Rp==="dispose"}let ta=!0;Rp===0&&(ta=!1);function H2(o){ta=o}function rS(){return ta}const aS=Symbol("disposable");function lS(o,e){o&&(o[aS]=e,ia&&console.warn("Set disposable",e,o))}const cS=Symbol("disposed");function q2(o){return o[cS]===!0}function Be(o){if(o){if(o[aS]===!1){ia&&console.warn("Object is marked as not disposable",o);return}if(typeof o=="object"&&(o[cS]=!0),o instanceof Fi)Be(o.environment),Be(o.background),Be(o.customDepthMaterial),Be(o.customDistanceMaterial);else if(o instanceof Bs)Be(o.geometry),Be(o.material),Be(o.skeleton),Be(o.bindMatrix),Be(o.bindMatrixInverse),Be(o.customDepthMaterial),Be(o.customDistanceMaterial),o.visible=!1;else if(o instanceof V)Be(o.geometry),Be(o.material),Be(o.customDepthMaterial),Be(o.customDistanceMaterial),o.visible=!1;else if(o instanceof R)o.visible=!1;else if(o instanceof Ln){Al(o);for(const e of Object.keys(o.attributes)){const t=o.attributes[e];Be(t)}}else if(o instanceof lt||o instanceof Av)ia&&console.warn("BufferAttribute dispose not supported",o.count);else if(o instanceof Array)for(const e of o)e instanceof ke&&Be(e);else if(o instanceof ke){Al(o);for(const t of Object.keys(o)){const i=o[t];i instanceof Pe&&Be(i)}const e=o.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof Pe?Be(i):i instanceof an&&Be(i.value)}}else o instanceof Pe?(Al(o),Al(o.source),o.source?.data instanceof ImageBitmap&&Al(o.source.data)):o instanceof HO?(Al(o.boneTexture),o.boneTexture=null):o instanceof qO||!(o instanceof R)&&ia&&console.warn("Unknown object type",o)}}function Al(o){o&&((ia||sS()||Rp)&&console.warn("\u{1F9E8} FREE",o),o instanceof ImageBitmap||"dispose"in o&&typeof o.dispose=="function"&&o.dispose())}function X2(o){}const Q2=new Set;function hb(o,e,t=null,i){if(i||(i=Q2,i.clear()),!o)return i;const n=o[kh];if(n)for(const s of n)i.has(s)||t?.call(null,s)!==!1&&(i.add(s),e&&hb(s,!0,t,i));return i}function Y2(o){return o[Oh]}const ia=x("debugresourceusers")||x("debugmemory"),kh=Symbol("needle-resource-users"),Oh=Symbol("needle-resource-users-count");function di(o,e){$u(o,e,function(t,i){ta&&!zc.raycasting&&(Tp(kh,this,t,!1),Tp(kh,this,i,!0))})}ta&&(di(V.prototype,"material"),di(V.prototype,"geometry"),di(ke.prototype,"map"),di(ke.prototype,"bumpMap"),di(ke.prototype,"alphaMap"),di(ke.prototype,"normalMap"),di(ke.prototype,"displacementMap"),di(ke.prototype,"roughnessMap"),di(ke.prototype,"metalnessMap"),di(ke.prototype,"emissiveMap"),di(ke.prototype,"specularMap"),di(ke.prototype,"envMap"),di(ke.prototype,"lightMap"),di(ke.prototype,"aoMap"),di(ke.prototype,"gradientMap"));function K2(o){if(ta===!1)return;const e=o[kh];if(e)for(const t of e)Tp(kh,t,o,!1)}ta&&$u(ke.prototype,"dispose",function(){K2(this)});let db=0;function Tp(o,e,t,i){if(db>0)return;if(Array.isArray(t)){for(const s of t)Tp(o,e,s,i);return}if(!t)return;let n=t[o];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let s=t[Oh]||0;s+=1,t[Oh]=s,ia&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,s,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let s=t[Oh]||0;s>0&&(s-=1,t[Oh]=s),ia&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,s,"users:",n),s<=0&&(Nc.isLoading(t)||(Rp&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),sS()&&Be(t)))}t[o]=n}try{$u(Dr.prototype,"render",function(){db++},function(){db--})}catch(o){console.warn("Could not wrap WebGLRenderer.render",o)}const Mh=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),hS=Symbol("isUsingInstancing"),dS=Symbol("instancingRenderer"),Rh=Symbol("instancingAutoUpdateBounds");class Mn{static isUsingInstancing(e){return e[hS]===!0}static getRenderer(e){return e[dS]||null}setAutoUpdateBounds(e,t){const i=Mn.getRenderer(e);i&&(i[Rh]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[Mh]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Mn.markDirty(i,!0)}}const Qs=x("debuginstantiate"),Il=new Map,Th=Symbol("original-component-name");function ub(o,e,t){if(e===null||!o)return;const i=o.guid,n=o.guid;n?.length&&(Il.has(n)||(Qs&&console.log('Creating InstanceIdProvider with key "'+n+'" for object '+o.name),Il.set(n,new _t(n))));const s=n&&Il.get(n)||e;if(o.guid=s.generateUUID(),i&&i!=="invalid"&&(t[i]=o.guid),o&&o.userData&&o.userData.components)for(const r of o.userData.components){if(r===null)continue;const a=r.guid;a?Il.has(a)||(Qs&&console.log('Creating InstanceIdProvider with key "'+a+'" for component '+r[Th]),Il.set(a,new _t(a))):Qs&&console.warn("Can not create IdProvider: component "+r[Th]+" has no guid",r.guid);const l=Il.get(a)||e,c=r.guid;r.guid=l.generateUUID(),c&&c!=="invalid"&&(t[c]=r.guid)}if(o.children)for(const r of o.children)ub(r,e,t)}function Z2(o){for(const e in o){const t=o[e].clone;if(!(!t?.isObject3D||!t?.userData?.components))for(let i=0;i<t.userData.components.length;i++){const n=t.userData.components[i],s=Object.entries(n);for(const[r,a]of s){if(a==null||r==="guid"||r===ts||typeof a!="object"&&typeof a!="string")continue;const l=na(r,a,o);l!==void 0&&(n[r]=l)}}}}let Xi=null;function uS(o,e){if(!Qs){pb(o,e);return}Xi={objects:0,components:0,props:0,remapped:0};const t=typeof performance<"u"?performance.now():Date.now();pb(o,e);const i=(typeof performance<"u"?performance.now():Date.now())-t,n=Xi;Xi=null,console.log(`[resolveStringGuids] root="${o.name}" objects=${n.objects} components=${n.components} propsVisited=${n.props} remapped=${n.remapped} mapSize=${Object.keys(e).length} in ${i.toFixed(2)}ms`)}function pb(o,e){if(Xi&&Xi.objects++,o.userData?.components)for(const t of o.userData.components)t!==null&&(Xi&&Xi.components++,mb(t,e));if(o.children)for(const t of o.children)pb(t,e)}function mb(o,e,t){if(t||(t=new WeakSet),!t.has(o)){t.add(o);for(const i of Object.keys(o)){Xi&&Xi.props++;const n=o[i];if(n!=null)if(typeof n=="string"){const s=e[n];s&&(o[i]=s,Xi&&Xi.remapped++)}else if(Array.isArray(n))for(let s=0;s<n.length;s++){const r=n[s];if(typeof r=="string"){const a=e[r];a&&(n[s]=a,Xi&&Xi.remapped++)}else(Array.isArray(r)||gb(r))&&mb(r,e,t)}else gb(n)&&mb(n,e,t)}}}function na(o,e,t){if(e!==void 0){if(e===null)return null;if(typeof e=="string"){const i=t[e];return i?i.clone:void 0}if(typeof e=="object"){if(Gu(e))return J2(e,t);if(e.isObject3D===!0){if(o==="gameObject")return;const i=e.uuid,n=t[i]?.clone;return n?(Qs&&console.log(o,"old",e,"new",n),n):void 0}if(sI(e))return e.clone();if(Array.isArray(e))return eI(o,e,t);if(e instanceof Map)return tI(e,t);if(e instanceof Set)return iI(e,t);if(!(e instanceof WeakMap||e instanceof WeakSet)){if(eA(e)&&e.$serializedTypes)return nI(e,t);if(gb(e))return oI(o,e,t)}}}}function J2(o,e){const t=o.gameObject;if(!t)return;const i=t.uuid,n=e[i]?.clone;if(!n){Qs&&console.log("Component reference did not change (external)",o);return}const s=t.userData.components.indexOf(o);if(s>=0&&n.isObject3D)return Qs&&console.log("Resolved component",i,"at index",s),n.userData.components[s];console.warn("Could not find component at expected index",o)}function eI(o,e,t){const i=[];for(let n=0;n<e.length;n++){const s=e[n];if(s==null){i.push(s);continue}if(typeof s!="object"&&typeof s!="string"){i.push(s);continue}const r=na(o,s,t);i.push(r!==void 0?r:s)}return i}function tI(o,e){const t=new Map;let i=!1;for(const[n,s]of o){let r=n,a=s;if(typeof n=="object"&&n!==null){const l=na("",n,e);l!==void 0&&(r=l,i=!0)}if(typeof s=="object"&&s!==null){const l=na("",s,e);l!==void 0&&(a=l,i=!0)}t.set(r,a)}return t}function iI(o,e){const t=new Set;for(const i of o)if(typeof i=="object"&&i!==null){const n=na("",i,e);t.add(n!==void 0?n:i)}else t.add(i);return t}function nI(o,e){const t=Object.assign(Object.create(Object.getPrototypeOf(o)),o);let i=!1;for(const n in t.$serializedTypes){const s=t[n];if(s!=null&&typeof s=="object"){Qs&&console.log("Recursively resolve references for",n,s);const r=na(n,s,e);r!==void 0&&(t[n]=r,i=!0)}}return i?t:void 0}function oI(o,e,t){let i=!1;const n={...e};for(const s of Object.keys(n)){const r=n[s];if(r==null||typeof r!="object"&&typeof r!="string")continue;const a=na(s,r,t);a!==void 0&&(n[s]=a,i=!0)}return i?n:void 0}function gb(o){if(typeof o!="object"||o===null)return!1;const e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function sI(o){return o.isVector2===!0||o.isVector3===!0||o.isVector4===!0||o.isQuaternion===!0||o.isEuler===!0||o.isColor===!0||o.isMatrix2===!0||o.isMatrix3===!0||o.isMatrix4===!0}const pS=new Map;function mS(o,e){if(!o)return;if(!e){console.warn("No prototype found",o,o.prototype,o.constructor);return}const t=pS.get(e);t&&t.apply(o)}function fb(o){const e=rI(o.prototype);pS.set(o,e)}function rI(o){return new aI(o)}class aI{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}}function Eh(o){o&&o.isObject3D===!0&&mS(o,R)}let gS=!1;function lI(){if(gS)return;if(gS=!0,ny.experimentalSmartHierarchyUpdate){const i=R.prototype.add;R.prototype.add=function(...r){return jl(),i.apply(this,r)};const n=R.prototype.attach;R.prototype.attach=function(...r){return jl(),n.apply(this,r)};const s=R.prototype.remove;R.prototype.remove=function(...r){return jl(),s.apply(this,r)}}R.prototype.SetActive=function(i){this.visible=i},R.prototype.setActive=function(i){this.visible=i},R.prototype.destroy=function(){ki(this)},R.prototype.addComponent=function(i,n){return bo(this,i,n)},R.prototype.addNewComponent=function(i,n){return bo(this,i,n)},R.prototype.removeComponent=function(i){return Np(this,i)},R.prototype.getOrAddComponent=function(i,n){return Dh(this,i,n)},R.prototype.getComponent=function(i){return ls(this,i)},R.prototype.getComponents=function(i,n){return Bl(this,i,n)},R.prototype.getComponentInChildren=function(i,n=!1){return jh(this,i,n)},R.prototype.getComponentsInChildren=function(i,n){return Ul(this,i,n)},R.prototype.getComponentInParent=function(i,n=!1){return Fh(this,i,n)},R.prototype.getComponentsInParent=function(i,n){return $p(this,i,n)},Object.getOwnPropertyDescriptor(R.prototype,"activeSelf")||Object.defineProperty(R.prototype,"activeSelf",{get:function(){return Ll(this)},set:function(i){oa(this,i)}}),Object.getOwnPropertyDescriptor(R.prototype,"raycastAllowed")||Object.defineProperty(R.prototype,"raycastAllowed",{get:function(){return this.userData&&this.userData.raycastAllowed!==!1},set:function(i){const n=this;n.userData||(n.userData={}),n.userData.raycastAllowed=i}}),Object.getOwnPropertyDescriptor(R.prototype,"worldPosition")||Object.defineProperty(R.prototype,"worldPosition",{get:function(){return this instanceof Yv?le(this.object):le(this)},set:function(i){Vi(this,i)}}),Object.getOwnPropertyDescriptor(R.prototype,"worldQuaternion")||Object.defineProperty(R.prototype,"worldQuaternion",{get:function(){return this instanceof Yv?Re(this.object):Re(this)},set:function(i){Fn(this,i)}}),Object.getOwnPropertyDescriptor(R.prototype,"worldRotation")||Object.defineProperty(R.prototype,"worldRotation",{get:function(){return Iu(this)},set:function(i){Fw(this,i)}}),Object.getOwnPropertyDescriptor(R.prototype,"worldScale")||Object.defineProperty(R.prototype,"worldScale",{get:function(){return Je(this)},set:function(i){hl(this,i)}});const o=new J,e=new v(0,0,0),t=new v(0,1,0);Object.getOwnPropertyDescriptor(R.prototype,"worldForward")||Object.defineProperty(R.prototype,"worldForward",{get:function(){return U().set(0,0,1).applyQuaternion(Re(this))},set:function(i){const n=xi().setFromRotationMatrix(o.lookAt(e.set(0,0,0),i,t.set(0,1,0)));this.worldQuaternion=n}}),Object.getOwnPropertyDescriptor(R.prototype,"worldRight")||Object.defineProperty(R.prototype,"worldRight",{get:function(){return U().set(1,0,0).applyQuaternion(Re(this))}}),Object.getOwnPropertyDescriptor(R.prototype,"worldUp")||Object.defineProperty(R.prototype,"worldUp",{get:function(){return U().set(0,1,0).applyQuaternion(Re(this))}}),Object.getOwnPropertyDescriptor(R.prototype,"contains")||Object.defineProperty(R.prototype,"contains",{value:function(i){if(!i)return!1;if(this===i)return!0;for(const n of this.children)if(n.contains(i))return!0;return!1}}),fb(R)}const Ep=x("debuggetcomponent"),cI=x("debuginstantiate");class $o{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new $o;return e.idProvider=this.idProvider,e.parent=this.parent,e.keepWorldPosition=this.keepWorldPosition,e.position=Array.isArray(this.position)?[...this.position]:this.position?.clone(),e.rotation=Array.isArray(this.rotation)?[...this.rotation]:this.rotation?.clone(),e.scale=Array.isArray(this.scale)?[...this.scale]:this.scale?.clone(),e.visible=this.visible,e.context=this.context,e.components=this.components,e}cloneAssign(e){this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=Array.isArray(e.position)?[...e.position]:e.position?.clone(),this.rotation=Array.isArray(e.rotation)?[...e.rotation]:e.rotation?.clone(),this.scale=Array.isArray(e.scale)?[...e.scale]:e.scale?.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function Ll(o){return o.visible}function oa(o,e){return typeof e=="number"&&(e=e>.5),o.visible=e,o.visible}function fS(o){return o[ho]||Ap(o)}function yS(o,e){o[hS]=e}function Ap(o){return Mn.isUsingInstancing(o)}function yb(o,e){return eh(o,e,!0,!0)}const bS=Symbol("isDestroyed");function Ys(o){return o[bS]}function _S(o,e){o[bS]=e}const bb=Symbol("isDontDestroy");function Dl(o,e=!0){o[bb]=e}const Ip=[],Lp=[];function ki(o,e=!0,t=!1){Ip.length=0,Lp.length=0,_b(o,e,!0);for(const i of Ip)i.gameObject=null,i.context=null;for(const i of Lp)_S(i,!0),t&&Be(i);Lp.length=0,Ip.length=0}function _b(o,e=!0,t=!0){if(o==null)return;const i=o;if(i.isComponent){if(i[bb])return;Ip.push(i);const r=i.gameObject;i.__internalDisable?.(),i.__internalDestroy?.(),i.gameObject=r;return}if(o[bb])return;const n=o;Ep&&console.log(n),Lp.push(n);const s=n.userData?.components;if(s!=null&&Array.isArray(s)){let r=s.length;for(let a=0;a<s.length;a++){const l=s[a];_b(l,e,!1),s.length<r&&(r=s.length,a--)}}if(e&&n.children)for(const r of n.children)_b(r,e,!1);t&&n.removeFromParent()}function $n(o,e,t=!0){return vS(o,e,t)}function*vb(o,e,t=!1,i=999,n=0){if(o?.userData.components&&!(n>i)){for(const s of o.userData.components)e&&s?.isComponent===!0&&s instanceof e?yield s:yield s;if(t===!0)for(const s of o.children)yield*vb(s,e,!0,i,n+1)}}function vS(o,e,t,i=0){if(o){if(o.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if(o.userData?.components)for(let n=0;n<o.userData.components.length;n++){const s=o.userData.components[n];if(s?.isComponent===!0){const r=e(s);if(r!==void 0)return r}}if(t&&o.children){const n=i+1;for(let s=0;s<o.children.length;s++){const r=o.children[s];if(!r)continue;const a=vS(r,e,t,n);if(a!==void 0)return a}}}}function Ks(o,e){if("isAssetReference"in o)return o.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new $o,t.position=e):t=e);let i=Q.Current;t?.context&&(i=t.context),Ep&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new _t(Date.now()));const n=[],s={},r={},a=wS(i,o,t,n,s,r);a&&(Z2(s),uI(r,s),dI(s)),Ep&&(Lu(o,!0),Lu(a,!0));const l={};for(const c in s){const h=s[c],d=h.original,u=h.clone;d instanceof R&&u instanceof R&&(l[d.guid||d.uuid]=u.guid||u.uuid)}if(t?.components!==!1){const c=new Set;for(const h in n){const d=n[h],u=d.guid;if(t&&t.idProvider){const m=d[ts],g=typeof m=="string"&&m.length>0?m:u;if(d.guid=g&&t.idProvider.remapUUID?t.idProvider.remapUUID(g):t.idProvider.generateUUID(),c.has(d.guid))if(console.warn(`[instantiate] duplicate component guid in source content ("${g}") \u2014 deriving a disambiguated guid. Fix the source: two components must not share a guid.`),t.idProvider.remapUUID&&g){let y=1;do d.guid=t.idProvider.remapUUID(`${g}:dup:${y++}`);while(c.has(d.guid))}else d.guid=t.idProvider.generateUUID();c.add(d.guid),l[u]=d.guid,g!==u&&(l[g]=d.guid),Ep&&console.log(d.name,d.guid)}kp(d,i),d.__internalNewInstanceCreated&&d.__internalNewInstanceCreated()}for(const h in n){const d=n[h];d.enabled!==!1&&(d.enabled=!0)}Dp(i)}return a}function wS(o,e,t,i,n,s){if(!e||e[Gi]||e instanceof Iv||e instanceof Lv||e.hideFlags&uo.DontInstantiate)return null;const r=e.userData;e.userData={};const a=e.children;e.children=[];const l=e.clone(!1);Eh(l),e.userData=r,e.children=a;const c={original:e,clone:l};if(n[e.uuid]=c,e.guid&&e.guid!==e.uuid&&(n[e.guid]=c),cI&&console.log("ADD",e,l),e.type==="SkinnedMesh"&&(s[e.uuid]={original:e,clone:l}),t?.visible!==void 0&&(l.visible=t.visible),t?.idProvider){const d=e.userData?.["needle-id"];l.uuid=d&&t.idProvider.remapUUID?t.idProvider.remapUUID(d):t.idProvider.generateUUID();const u=l;u&&(u.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const h=e.parent;if(h&&h.add(l),t?.position)if(Array.isArray(t.position)){const d=new v;d.fromArray(t.position),l.worldPosition=d}else l.worldPosition=t.position;else l.position.copy(e.position);if(t?.rotation){if(t.rotation instanceof B)l.worldQuaternion=t.rotation;else if(t.rotation instanceof je)l.worldQuaternion=xi().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const d=new je;d.fromArray(t.rotation),l.worldQuaternion=xi().setFromEuler(d)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const d=new v;d.fromArray(t.scale),t.scale=d}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=eh(t.parent,o.scene,!0):d=t.parent,d){const u=t.keepWorldPosition===!0?d.attach:d.add;u?u.call(d,l):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,u]of Object.entries(e.userData))d!=="components"&&(l.userData[d]=u);if(e.userData?.components){const d=e.userData.components,u=[];l.userData.components=u;for(let m=0;m<d.length;m++){const g=d[m],y=new g.constructor;hI(g,y),g[ts]!==void 0&&(y[ts]=g[ts]),u.push(y),y.gameObject=l,i.push(y),n[g.guid]={original:g,clone:y},Nu.dispatchComponentLifecycleEvent("component-added",y)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const d in e.children){const u=e.children[d],m=wS(o,u,t,i,n,s);m&&(n[m.uuid]={original:u,clone:m},l.add(m))}return l}function hI(o,e,t){bl(e,o,void 0,{})}function dI(o){for(const e in o){const t=o[e],i=t.original;if(i.isDirectionalLight!==!0&&i.isSpotLight!==!0)continue;const n=i.target;if(!n||n.parent!==i)continue;const s=Object.values(o).find(a=>a.original===n);if(!s)continue;const r=s.clone;t.clone.target=r,r.hideFlags|=uo.DontExport}}function uI(o,e){for(const t in o){const i=o[t],n=i.original,s=n.skeleton,r=i.clone;if(!s){console.warn("Skinned mesh has no skeleton?",i);continue}const a=s.bones,l=r.skeleton.clone();r.skeleton=l,r.bindMatrix.clone().copy(n.bindMatrix),r.bindMatrixInverse.copy(n.bindMatrixInverse);const c=[];l.bones=c;for(let h=0;h<a.length;h++){const d=a[h],u=e[d.uuid].clone;c.push(u)}}for(const t in o){const i=o[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function Ah(o,e){try{e||o()}catch(t){return console.error(t),!1}return!0}const wb=x("debugnewscripts"),pI=x("debughierarchy"),Ne=[];function mI(){return Ne.length>0}function Dp(o){if(wb&&console.log("Register new components",o.new_scripts.length,[...o.new_scripts],o.alias?"element: "+o.alias:o.hash,o),xS(o),!(o.new_scripts.length<=0)){Ne.length=0,o.new_scripts.length>0&&Ne.push(...o.new_scripts),o.new_scripts.length=0;for(let e=0;e<Ne.length;e++)try{const t=Ne[e];if(t.isComponent!==!0){(M()||wb)&&console.error(`Registered script is not a Needle Engine component.
882
+ Target Framerate: `+this.targetFrameRate)}}this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),ce.dispatchCallback(de.ContextFirstFrameRendered,this))}_tempClearColor=new oe;_tempClearColor2=new oe;renderNow(e){if(!e&&(e=this.mainCamera,!e))return!1;if(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==bu&&v1(),this.postprocessing.update(),this.composer&&!this.isInXR){e&&"setMainCamera"in this.composer&&this.composer.passes[0]?.mainCamera!=e&&this.composer.setMainCamera(e);const t=this.renderer.getClearColor(this._tempClearColor),i=this.renderer.getClearAlpha();this._tempClearColor2.copy(t),this.renderer.setClearColor(t.convertSRGBToLinear(),this.renderer.getClearAlpha()),this.composer.render(this.time.deltaTime),this.renderer.setClearColor(this._tempClearColor2,i)}else e&&(this.isInXR&&I.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,e));return this._isRendering=!1,!0}_contextRestoreTries=0;handleRendererContextLost(){this.time.frame%10&&this.renderer.getContext().isContextLost()&&this._contextRestoreTries++<100&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}_wasPaused=!1;onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){D2&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(Pe.Current=this,i.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new ro(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new Ev(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new ke,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=_u,this._renderTarget.texture.magFilter=_u,this._renderTarget.texture.format=gu)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){const i=this.coroutines[e];for(let n=0;n<i.length;n++)try{const s=i[n];if(!s.comp||s.comp.destroyed||!s.main||s.comp.enabled===!1){F2&&console.log("Removing coroutine",s.comp,s.comp.enabled),i.splice(n,1),--n;continue}const r=s.chained;if(r&&r.length>0){const c=r[r.length-1].next();if(c.done&&r.pop(),t(c)&&(s.chained||(s.chained=[]),s.chained.push(c.value)),!c.done)continue}const a=s.main.next();if(a.done===!0){i.splice(n,1),--n;continue}const l=a.value;if(t(l)){if(l.next().done)continue;s.chained||(s.chained=[]),s.chained.push(l)}else if(l instanceof Promise){const c=l;s.chained||(s.chained=[]);const h=Hx(c);s.chained?.push(h);continue}}catch(s){console.error(s)}}function t(i){return!!(i&&i.next&&i.return)}}};xe([we()],ye.prototype,"scripts"),xe([we()],ye.prototype,"scripts_pausedChanged"),xe([we()],ye.prototype,"scripts_earlyUpdate"),xe([we()],ye.prototype,"scripts_update"),xe([we()],ye.prototype,"scripts_lateUpdate"),xe([we()],ye.prototype,"scripts_onBeforeRender"),xe([we()],ye.prototype,"scripts_onAfterRender"),xe([we()],ye.prototype,"scripts_WithCorroutines"),xe([we()],ye.prototype,"scripts_immersive_vr"),xe([we()],ye.prototype,"scripts_immersive_ar"),xe([we()],ye.prototype,"coroutines"),xe([we("keep")],ye.prototype,"post_setup_callbacks"),xe([we("keep")],ye.prototype,"pre_update_callbacks"),xe([we("keep")],ye.prototype,"pre_render_callbacks"),xe([we("keep")],ye.prototype,"post_render_callbacks"),xe([we()],ye.prototype,"pre_update_oneshot_callbacks"),xe([we()],ye.prototype,"new_scripts"),xe([we()],ye.prototype,"new_script_start"),xe([we()],ye.prototype,"new_scripts_pre_setup_callbacks"),xe([we()],ye.prototype,"new_scripts_post_setup_callbacks"),xe([we()],ye.prototype,"new_scripts_xr"),xe([we("undefined")],ye.prototype,"mainCameraComponent"),xe([we("null")],ye.prototype,"_mainCamera"),xe([we("null")],ye.prototype,"_fallbackCamera"),xe([we("custom")],ye.prototype,"_events"),xe([we("custom")],ye.prototype,"lights"),xe([we("keep")],ye.prototype,"_disposeCallbacks"),xe([we()],ye.prototype,"_cameraStack"),xe([we("custom")],ye.prototype,"_onBeforeRenderListeners"),xe([we("custom")],ye.prototype,"_onAfterRenderListeners"),xe([we("keep")],ye.prototype,"rootSceneSourceIdentifiers");let Q=ye;const nb=x("debugwebxr");class Y1{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(nb&&console.log("FOUND AVATAR HEAD",e.name),i.head=new ie("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(nb&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new ie("",t,e)),!i.rightHand&&n.includes("right")&&(nb&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new ie("",t,e)));for(let s=0;s<e.children.length;s++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[s];this.tryFindAvatarObjects(r,t,i)}}}class he extends oe{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.setRGB(Number.isFinite(e)?e:0,Number.isFinite(t)?t:0,Number.isFinite(i)?i:0),this.alpha=typeof n=="number"&&Number.isFinite(n)?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=j.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,s=t;return n.alpha!=null&&s.alpha!=null&&(this.alpha=j.lerp(n.alpha,s.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new he(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,s=t>>8&255,r=t>>0&255;return new he(i/255,n/255,s/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,s=t>>0&255;return new he(i/255,n/255,s/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new he(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new he(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new he(e[0],e[1],e[2],e[3]);if(e.length===3)return new he(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new he(e)}}const Kt=new v,K1=new v,Z1=new B,z2=x("debuggizmos"),zn=8947848,ob=32;class F{constructor(){}static enabled=!0;static isGizmo(e){return e[rb]!==void 0}static setVisible(e){for(const t of Di.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,s,r,a,l=!0){if(!F.enabled)return null;s||(s=zn);const c=q.active?.rigScale??1,h=Di.getTextLabel(n,t,i*c,s,r);return h[J1]=l===!1,a instanceof R&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=zn,n=0,s=!0){if(!F.enabled)return;const r=Di.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Kt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Kt.x,e.y+Kt.y,e.z+Kt.z),a.needsUpdate=!0,r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,Nn(r.material,i)}static DrawDirection(e,t,i=zn,n=0,s=!0,r=1){if(!F.enabled)return;const a=Di.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Kt.set(0,0,-r),Z1.set(t.x,t.y,t.z,t.w),Kt.applyQuaternion(Z1)):(Kt.set(t.x,t.y,t.z),Kt.multiplyScalar(r)),l.setXYZ(1,e.x+Kt.x,e.y+Kt.y,e.z+Kt.z),l.needsUpdate=!0,a.material.depthTest=s,a.material.depthWrite=!1,Nn(a.material,i)}static DrawLine(e,t,i=zn,n=0,s=!0){if(!F.enabled)return;const r=Di.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,Nn(r.material,i)}static DrawCircle(e,t,i,n=zn,s=0,r=!0){if(!F.enabled)return;const a=Di.getCircle(s);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Kt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,Nn(a.material,n)}static DrawWireSphere(e,t,i=zn,n=0,s=!0){if(!F.enabled)return;const r=Di.getSphere(t,n,!0);zr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,Nn(r.material,i)}static DrawSphere(e,t,i=zn,n=0,s=!0){if(!F.enabled)return;const r=Di.getSphere(t,n,!1);zr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,Nn(r.material,i)}static DrawWireBox(e,t,i=zn,n=0,s=!0,r=void 0){if(!F.enabled)return;const a=Di.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=s,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,Nn(a.material,i)}static DrawWireBox3(e,t=zn,i=0,n=!0){if(!F.enabled)return;const s=Di.getBox(i);s.position.copy(e.getCenter(Kt)),s.scale.copy(e.getSize(Kt)),s.material.depthTest=n,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1,Nn(s.material,t)}static _up=new v(0,1,0);static DrawArrow(e,t,i=zn,n=0,s=!0,r=!1){if(!F.enabled)return;const a=Di.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Kt.set(t.x,t.y,t.z).sub(K1.set(e.x,e.y,e.z)).normalize());const l=Kt.set(t.x,t.y,t.z).sub(K1.set(e.x,e.y,e.z)).length()*.1;a.scale.set(l,l,l),a.material.depthTest=s,a.material.wireframe=r,Nn(a.material,i),this.DrawLine(e,t,i,n,s)}static DrawWireMesh(e){const t=Di.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,Nn(t.material,e.color??zn)}}const N2=new ol(1,1,1);function sb(o=null){const e=new oe(o??14540253),t=new VO(N2);return new hf(t,new vu({color:e}))}function Nn(o,e){if(Array.isArray(o)){for(const i of o)Nn(i,e);return}const t=e instanceof he?e.a:1;o.color.set(e),o.opacity=t,o.transparent=t<1}const rb=Symbol("GizmoCache"),J1=Symbol("GizmoLabelOnTop");class Di{static familyName="needle-gizmos";static ensureFont(){let e=Le.FontLibrary.getFontFamily(this.familyName);e||(e=Le.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{Le.update()}))}static getTextLabel(e,t,i,n,s){this.ensureFont();let r=this.textLabelCache.pop(),a=1;s&&typeof s=="string"&&s?.length>=8&&s.startsWith("#")?(a=parseInt(s.substring(7),16)/255,s=s.substring(0,7),z2&&console.log(s,a)):typeof s=="object"&&s.a!==void 0&&(a=s.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:s??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new iw(l);const c=this,h=r;h.setText=function(d){this.set({textContent:d}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(Q.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new ol(1,1,1);t=new V(i)}return this.registerTimedObject(Q.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Qc;let i=t.geometry.getAttribute("position");i||(i=new lt(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(Q.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new Qc;let i=t.geometry.getAttribute("position");if(!i){i=new lt(new Float32Array(ob*3),3),t.geometry.setAttribute("position",i);const n=U(0,1,0),s=U(0,0,1),r=U(s);r.cross(n).normalize();const a=U(r),l=Math.PI*2/(ob-1);for(let c=0;c<ob+1;c++){const h=l*c;n.copy(a).multiplyScalar(Math.cos(h)*1),r.copy(s).multiplyScalar(Math.sin(h)*1);const d=n.add(r);i.setXYZ(c,d.x,d.y,d.z)}}}return t.frustumCulled=!1,this.registerTimedObject(Q.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new V(new rf(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(Q.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new V(new Rv(0,.5,1,8))),this.registerTimedObject(Q.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new V,t.material=new Ie),this.registerTimedObject(Q.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const s=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(s){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==s){const a=e.pre_render_callbacks.indexOf(s);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(s)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[rb]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(Q.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Le.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof Le.MeshUIBaseElement){if(Ys(n))continue;const s=e.isInVR,r=!1,a=!s;nh(n,e.mainCamera,r,a),n[J1]===!0&&Di.applyLabelOnTop(n)}}}static applyLabelOnTop(e){e.traverse(t=>{const i=t.material;if(i){t.renderOrder=999999;for(const n of Array.isArray(i)?i:[i])n.depthTest=!1,n.depthWrite=!1}})}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let s=t.length-1;s>=0;s--){const r=t[s];n>=i[s]-1e-6&&(t.splice(s,1),i.splice(s,1),r.removeFromParent(),Ys(r)!=!0&&r[rb].push(r))}}}const hi=x("debugphysics"),$2=x("debugworker"),eS=new Fs;class Jr{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new ee),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){eS.set(e),this.layerMask=eS}setMask(e){this.layerMask||(this.layerMask=new Fs);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class ab{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}let lb=null;function tS(o){lb=o}class zc{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;_engine;get engine(){return this._engine}set engine(e){this._engine=e}getOrCreatePhysicsEngine(){return this._engine===void 0&&lb&&(this._engine=lb(this.context)),this._engine??null}constructor(e){this.context=e}raycaster=new df;defaultRaycastOptions=new Jr;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new Fs;sphere=new Xc;sphereOverlap(e,t,i=!0,n=!1,s=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,s);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){hi&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return hi&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof GO&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let s=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Fs?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),hi&&console.time("raycast"),s.length=0,zc._raycasting++,this.intersect(this.raycaster,n,s,e),s.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),zc._raycasting--,hi&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",s?.length?[...s]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),s}intersect(e,t,i,n){for(const s of t){if(!s||s.visible===!1||F.isGizmo(s)||n.lineThreshold!==void 0&&n.lineThreshold<0&&s instanceof Qc)continue;let r=!0;const a=s,l=a.geometry,c=!l&&s.raycast!==R.prototype.raycast;if(s.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(s);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(!l&&!c||l&&!iS(l))&&(r=!1);if(r){const h=i.length;if(c)e.intersectObject(a,!1,i);else{const d=s.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof al&&(u=!1),d==="lod"){const m=Xv(s);m&&(a.geometry=m)}!u&&V2(a,e,i)||(n.useAcceleratedRaycast!==!1?Mp.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l}if(hi&&i.length!=h){const d=i[i.length-1];F.DrawWireSphere(d.point,.1,7798784,1,!1),F.DrawWireMesh({mesh:s,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,s.children,i,n)}return i}tempBoundingBox=new ri;intersectSphere(e,t,i,n,s,r,a,l){let c=e&&e.isMesh&&e.layers.test(n)&&!F.isGizmo(e);c&&=e.visible,c&&=!(e instanceof Qc),c&&=!(e instanceof al);const h=e,d=h.geometry;if(c&&l){const u=l(e);if(u===!1)return;u==="continue in children"&&(c=!1)}if(d&&iS(d)||(c=!1),c){if(a){const u=this.sphere;u.center.copy(t),u.radius=i;const m=s.length;if(Mp.runMeshBVHRaycast(this.sphere,h,s,this.context,{}),m!=s.length&&!r)return}else if(d.boundingBox||d.computeBoundingBox(),d.boundingBox){h.matrixWorldNeedsUpdate&&h.updateWorldMatrix(!1,!1);const u=this.tempBoundingBox.copy(d.boundingBox).applyMatrix4(h.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(u)){const g=le(e),y=g.distanceTo(m.center),b=new ab(e,y,g);if(s.push(b),!r)return}}}if(e.children)for(const u of e.children){const m=s.length;if(this.intersectSphere(u,t,i,n,s,r,a,l),m!=s.length&&!r)return}}}function iS(o){return!(o.index&&o.index.array.length<3)}const ea=new Xc,Op=new rl,W2=new sf;function V2(o,e,t){const i=o._computeIntersections;if(!i)return!1;let n=o["_computeIntersections:Needle"];return n||(n=o["_computeIntersections:Needle"]=function(s,r,a){const l=this,c=l.geometry.boundingSphere;if(c){if(l instanceof al){Op.setFromNormalAndCoplanarPoint(U(0,1,0),U(0,-l.position.y,0)),Op.applyMatrix4(l.matrixWorld,W2);const d=s.ray.intersectPlane(Op,U());if(d){ea.copy(c),ea.applyMatrix4(l.matrixWorld);const u=U(d).sub(s.ray.origin).length(),m=ea.radius*.5;u<m&&r.push({distance:u,point:d,object:l,normal:Op.normal.clone()})}return}ea.copy(c),ea.applyMatrix4(l.matrixWorld);const h=s.ray.intersectSphere(ea,U());if(h){const d=U(h).sub(s.ray.origin),u=d.length();if(u>ea.radius){const m=d.clone().normalize();r.push({distance:u,point:h,object:l,normal:m})}}}}),o._computeIntersections=n,e.intersectObject(o,!1,t),o._computeIntersections=i,!0}function cb(o,e){const t=o.children;o.children=[];try{return e()}finally{o.children=t}}var Mp;(o=>{let e=0;function t(_,w,S,O,L){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w?.isSkinnedMesh){const W=w,$=W.bvhNeedsUpdate;if(!W.staticGenerator)l(),r&&(cb(w,()=>{W.staticGenerator=new r(w),W.staticGenerator.applyWorldTransforms=!1,W.staticGeometry=W.staticGenerator.generate()}),D.boundsTree=a?.call(W.staticGeometry),W.staticGeometryLastUpdate=performance.now()+Math.random()*200,W.bvhNeedsUpdate=!0);else if(D.boundsTree&&(W.autoUpdateMeshBvhInterval!==void 0&&W.autoUpdateMeshBvhInterval>=0||$===!0)){const H=performance.now(),G=H-W.staticGeometryLastUpdate,E=W.autoUpdateMeshBvhInterval??100;($||G>E)&&(hi&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${G.toFixed(2)}ms`),W.bvhNeedsUpdate=!1,W.staticGeometryLastUpdate=H,cb(w,()=>W.staticGenerator?.generate(W.staticGeometry)),D.boundsTree.refit())}}else if(!D.boundsTree){h||f();let W=!0;if((O.xr||D[g]===!1||D.getAttribute("position")?.isInterleavedBufferAttribute||D.index&&D.index?.isInterleavedBufferAttribute||e>10)&&(W=!1),W&&u){if(D[m]===void 0){let $=null;if(b.length>0){const H=b.shift();H&&!H.running&&($=H)}if(!$&&y.length<3)try{$2&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",import.meta.url),$=new u,y.push($)}catch(H){H instanceof DOMException&&H.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(H),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(H)),e++}if($!=null&&!$.running){const H=w.name;hi&&console.log("<<<< worker start",H,$),D[m]="queued",performance.mark("bvh.create.start");const G=D.clone();try{$.generate(G).then(E=>{D[m]="done",D.boundsTree=E}).catch(E=>{D[m]="failed - "+E?.message,D[g]=!1,hi&&console.error("Failed to generate mesh bvh on worker",E)}).finally(()=>{hi&&console.log(">>>>> worker done",H,{hasBoundsTre:D.boundsTree!=null}),b.push($),G.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(E){console.error("Failed to generate mesh bvh on worker",E)}}else hi&&console.warn("No worker available")}}else(!d||!W)&&(l(),s&&(performance.mark("bvh.create.start"),D.boundsTree=new s(D),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(_ instanceof df){const W=_,$=w.raycast;if(D.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),hi&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(hi&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[m],hasAcceleratedRaycast:n!=null}),L.allowSlowRaycastFallback===!1&&(D.getAttribute("position")?.array?.length??0)>2e3)return hi&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const H=W.firstHitOnly;return W.firstHitOnly=!1,W.intersectObject(w,!1,S),W.firstHitOnly=H,w.raycast=$,!0}else if(_ instanceof Xc){const W=D.boundsTree;if(W){const $=_;if(c.copy(w.matrixWorld).invert(),$.applyMatrix4(c),W.intersectsSphere($)){const H=le(w),G=H.distanceTo($.center),E=new ab(w,G,H);S.push(E)}}return!0}return!1}o.runMeshBVHRaycast=t;let i=!1,n=null,s=null,r=null,a=null;function l(){i||(i=!0,import("./vendor-T07c_9f_.min.js").then(_=>_.index$1).then(_=>{n=_.acceleratedRaycast,s=_.MeshBVH,r=_.StaticGeometryGenerator,a=_.computeBoundsTree}).catch(_=>{(hi||M())&&console.error("Failed to load BVH library...",_.message)}))}const c=new J;let h=!1,d=!1,u=null;const m=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],b=[];function f(){h=!0,d=!0,Promise.resolve().then(()=>m4).then(_=>{u=_.GenerateMeshBVHWorker}).catch(_=>{hi||M()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",_)}).finally(()=>{d=!1})}})(Mp||(Mp={}));const nS=Symbol("gltf-loader-internal-usage-tracker"),G2=x("debugusers");class Nc{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Nc._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){Nc._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const s=t.call(this,i,n);return s.then(r=>(r&&(e._loadedObjects.add(r),r[nS]=e._loadingId),r)),s},null}afterRoot(e){Nc._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[nS],t instanceof R&&(t.parent||t instanceof V&&setTimeout(()=>{G2&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class oS{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
883
+ `+i.src),e.preventDefault())}})}}const Rp=x("trackresources");function sS(){return Rp==="dispose"}let ta=!0;Rp===0&&(ta=!1);function H2(o){ta=o}function rS(){return ta}const aS=Symbol("disposable");function lS(o,e){o&&(o[aS]=e,ia&&console.warn("Set disposable",e,o))}const cS=Symbol("disposed");function q2(o){return o[cS]===!0}function Be(o){if(o){if(o[aS]===!1){ia&&console.warn("Object is marked as not disposable",o);return}if(typeof o=="object"&&(o[cS]=!0),o instanceof Fi)Be(o.environment),Be(o.background),Be(o.customDepthMaterial),Be(o.customDistanceMaterial);else if(o instanceof Bs)Be(o.geometry),Be(o.material),Be(o.skeleton),Be(o.bindMatrix),Be(o.bindMatrixInverse),Be(o.customDepthMaterial),Be(o.customDistanceMaterial),o.visible=!1;else if(o instanceof V)Be(o.geometry),Be(o.material),Be(o.customDepthMaterial),Be(o.customDistanceMaterial),o.visible=!1;else if(o instanceof R)o.visible=!1;else if(o instanceof Ln){Al(o);for(const e of Object.keys(o.attributes)){const t=o.attributes[e];Be(t)}}else if(o instanceof lt||o instanceof Av)ia&&console.warn("BufferAttribute dispose not supported",o.count);else if(o instanceof Array)for(const e of o)e instanceof Oe&&Be(e);else if(o instanceof Oe){Al(o);for(const t of Object.keys(o)){const i=o[t];i instanceof ke&&Be(i)}const e=o.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof ke?Be(i):i instanceof an&&Be(i.value)}}else o instanceof ke?(Al(o),Al(o.source),o.source?.data instanceof ImageBitmap&&Al(o.source.data)):o instanceof HO?(Al(o.boneTexture),o.boneTexture=null):o instanceof qO||!(o instanceof R)&&ia&&console.warn("Unknown object type",o)}}function Al(o){o&&((ia||sS()||Rp)&&console.warn("\u{1F9E8} FREE",o),o instanceof ImageBitmap||"dispose"in o&&typeof o.dispose=="function"&&o.dispose())}function X2(o){}const Q2=new Set;function hb(o,e,t=null,i){if(i||(i=Q2,i.clear()),!o)return i;const n=o[kh];if(n)for(const s of n)i.has(s)||t?.call(null,s)!==!1&&(i.add(s),e&&hb(s,!0,t,i));return i}function Y2(o){return o[Oh]}const ia=x("debugresourceusers")||x("debugmemory"),kh=Symbol("needle-resource-users"),Oh=Symbol("needle-resource-users-count");function di(o,e){$u(o,e,function(t,i){ta&&!zc.raycasting&&(Tp(kh,this,t,!1),Tp(kh,this,i,!0))})}ta&&(di(V.prototype,"material"),di(V.prototype,"geometry"),di(Oe.prototype,"map"),di(Oe.prototype,"bumpMap"),di(Oe.prototype,"alphaMap"),di(Oe.prototype,"normalMap"),di(Oe.prototype,"displacementMap"),di(Oe.prototype,"roughnessMap"),di(Oe.prototype,"metalnessMap"),di(Oe.prototype,"emissiveMap"),di(Oe.prototype,"specularMap"),di(Oe.prototype,"envMap"),di(Oe.prototype,"lightMap"),di(Oe.prototype,"aoMap"),di(Oe.prototype,"gradientMap"));function K2(o){if(ta===!1)return;const e=o[kh];if(e)for(const t of e)Tp(kh,t,o,!1)}ta&&$u(Oe.prototype,"dispose",function(){K2(this)});let db=0;function Tp(o,e,t,i){if(db>0)return;if(Array.isArray(t)){for(const s of t)Tp(o,e,s,i);return}if(!t)return;let n=t[o];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let s=t[Oh]||0;s+=1,t[Oh]=s,ia&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,s,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let s=t[Oh]||0;s>0&&(s-=1,t[Oh]=s),ia&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,s,"users:",n),s<=0&&(Nc.isLoading(t)||(Rp&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),sS()&&Be(t)))}t[o]=n}try{$u(Dr.prototype,"render",function(){db++},function(){db--})}catch(o){console.warn("Could not wrap WebGLRenderer.render",o)}const Mh=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),hS=Symbol("isUsingInstancing"),dS=Symbol("instancingRenderer"),Rh=Symbol("instancingAutoUpdateBounds");class Mn{static isUsingInstancing(e){return e[hS]===!0}static getRenderer(e){return e[dS]||null}setAutoUpdateBounds(e,t){const i=Mn.getRenderer(e);i&&(i[Rh]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[Mh]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Mn.markDirty(i,!0)}}const Qs=x("debuginstantiate"),Il=new Map,Th=Symbol("original-component-name");function ub(o,e,t){if(e===null||!o)return;const i=o.guid,n=o.guid;n?.length&&(Il.has(n)||(Qs&&console.log('Creating InstanceIdProvider with key "'+n+'" for object '+o.name),Il.set(n,new _t(n))));const s=n&&Il.get(n)||e;if(o.guid=s.generateUUID(),i&&i!=="invalid"&&(t[i]=o.guid),o&&o.userData&&o.userData.components)for(const r of o.userData.components){if(r===null)continue;const a=r.guid;a?Il.has(a)||(Qs&&console.log('Creating InstanceIdProvider with key "'+a+'" for component '+r[Th]),Il.set(a,new _t(a))):Qs&&console.warn("Can not create IdProvider: component "+r[Th]+" has no guid",r.guid);const l=Il.get(a)||e,c=r.guid;r.guid=l.generateUUID(),c&&c!=="invalid"&&(t[c]=r.guid)}if(o.children)for(const r of o.children)ub(r,e,t)}function Z2(o){for(const e in o){const t=o[e].clone;if(!(!t?.isObject3D||!t?.userData?.components))for(let i=0;i<t.userData.components.length;i++){const n=t.userData.components[i],s=Object.entries(n);for(const[r,a]of s){if(a==null||r==="guid"||r===ts||typeof a!="object"&&typeof a!="string")continue;const l=na(r,a,o);l!==void 0&&(n[r]=l)}}}}let Xi=null;function uS(o,e){if(!Qs){pb(o,e);return}Xi={objects:0,components:0,props:0,remapped:0};const t=typeof performance<"u"?performance.now():Date.now();pb(o,e);const i=(typeof performance<"u"?performance.now():Date.now())-t,n=Xi;Xi=null,console.log(`[resolveStringGuids] root="${o.name}" objects=${n.objects} components=${n.components} propsVisited=${n.props} remapped=${n.remapped} mapSize=${Object.keys(e).length} in ${i.toFixed(2)}ms`)}function pb(o,e){if(Xi&&Xi.objects++,o.userData?.components)for(const t of o.userData.components)t!==null&&(Xi&&Xi.components++,mb(t,e));if(o.children)for(const t of o.children)pb(t,e)}function mb(o,e,t){if(t||(t=new WeakSet),!t.has(o)){t.add(o);for(const i of Object.keys(o)){Xi&&Xi.props++;const n=o[i];if(n!=null)if(typeof n=="string"){const s=e[n];s&&(o[i]=s,Xi&&Xi.remapped++)}else if(Array.isArray(n))for(let s=0;s<n.length;s++){const r=n[s];if(typeof r=="string"){const a=e[r];a&&(n[s]=a,Xi&&Xi.remapped++)}else(Array.isArray(r)||gb(r))&&mb(r,e,t)}else gb(n)&&mb(n,e,t)}}}function na(o,e,t){if(e!==void 0){if(e===null)return null;if(typeof e=="string"){const i=t[e];return i?i.clone:void 0}if(typeof e=="object"){if(Gu(e))return J2(e,t);if(e.isObject3D===!0){if(o==="gameObject")return;const i=e.uuid,n=t[i]?.clone;return n?(Qs&&console.log(o,"old",e,"new",n),n):void 0}if(sI(e))return e.clone();if(Array.isArray(e))return eI(o,e,t);if(e instanceof Map)return tI(e,t);if(e instanceof Set)return iI(e,t);if(!(e instanceof WeakMap||e instanceof WeakSet)){if(eA(e)&&e.$serializedTypes)return nI(e,t);if(gb(e))return oI(o,e,t)}}}}function J2(o,e){const t=o.gameObject;if(!t)return;const i=t.uuid,n=e[i]?.clone;if(!n){Qs&&console.log("Component reference did not change (external)",o);return}const s=t.userData.components.indexOf(o);if(s>=0&&n.isObject3D)return Qs&&console.log("Resolved component",i,"at index",s),n.userData.components[s];console.warn("Could not find component at expected index",o)}function eI(o,e,t){const i=[];for(let n=0;n<e.length;n++){const s=e[n];if(s==null){i.push(s);continue}if(typeof s!="object"&&typeof s!="string"){i.push(s);continue}const r=na(o,s,t);i.push(r!==void 0?r:s)}return i}function tI(o,e){const t=new Map;let i=!1;for(const[n,s]of o){let r=n,a=s;if(typeof n=="object"&&n!==null){const l=na("",n,e);l!==void 0&&(r=l,i=!0)}if(typeof s=="object"&&s!==null){const l=na("",s,e);l!==void 0&&(a=l,i=!0)}t.set(r,a)}return t}function iI(o,e){const t=new Set;for(const i of o)if(typeof i=="object"&&i!==null){const n=na("",i,e);t.add(n!==void 0?n:i)}else t.add(i);return t}function nI(o,e){const t=Object.assign(Object.create(Object.getPrototypeOf(o)),o);let i=!1;for(const n in t.$serializedTypes){const s=t[n];if(s!=null&&typeof s=="object"){Qs&&console.log("Recursively resolve references for",n,s);const r=na(n,s,e);r!==void 0&&(t[n]=r,i=!0)}}return i?t:void 0}function oI(o,e,t){let i=!1;const n={...e};for(const s of Object.keys(n)){const r=n[s];if(r==null||typeof r!="object"&&typeof r!="string")continue;const a=na(s,r,t);a!==void 0&&(n[s]=a,i=!0)}return i?n:void 0}function gb(o){if(typeof o!="object"||o===null)return!1;const e=Object.getPrototypeOf(o);return e===Object.prototype||e===null}function sI(o){return o.isVector2===!0||o.isVector3===!0||o.isVector4===!0||o.isQuaternion===!0||o.isEuler===!0||o.isColor===!0||o.isMatrix2===!0||o.isMatrix3===!0||o.isMatrix4===!0}const pS=new Map;function mS(o,e){if(!o)return;if(!e){console.warn("No prototype found",o,o.prototype,o.constructor);return}const t=pS.get(e);t&&t.apply(o)}function fb(o){const e=rI(o.prototype);pS.set(o,e)}function rI(o){return new aI(o)}class aI{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}}function Eh(o){o&&o.isObject3D===!0&&mS(o,R)}let gS=!1;function lI(){if(gS)return;if(gS=!0,ny.experimentalSmartHierarchyUpdate){const i=R.prototype.add;R.prototype.add=function(...r){return jl(),i.apply(this,r)};const n=R.prototype.attach;R.prototype.attach=function(...r){return jl(),n.apply(this,r)};const s=R.prototype.remove;R.prototype.remove=function(...r){return jl(),s.apply(this,r)}}R.prototype.SetActive=function(i){this.visible=i},R.prototype.setActive=function(i){this.visible=i},R.prototype.destroy=function(){ki(this)},R.prototype.addComponent=function(i,n){return bo(this,i,n)},R.prototype.addNewComponent=function(i,n){return bo(this,i,n)},R.prototype.removeComponent=function(i){return Np(this,i)},R.prototype.getOrAddComponent=function(i,n){return Dh(this,i,n)},R.prototype.getComponent=function(i){return ls(this,i)},R.prototype.getComponents=function(i,n){return Bl(this,i,n)},R.prototype.getComponentInChildren=function(i,n=!1){return jh(this,i,n)},R.prototype.getComponentsInChildren=function(i,n){return Ul(this,i,n)},R.prototype.getComponentInParent=function(i,n=!1){return Fh(this,i,n)},R.prototype.getComponentsInParent=function(i,n){return $p(this,i,n)},Object.getOwnPropertyDescriptor(R.prototype,"activeSelf")||Object.defineProperty(R.prototype,"activeSelf",{get:function(){return Ll(this)},set:function(i){oa(this,i)}}),Object.getOwnPropertyDescriptor(R.prototype,"raycastAllowed")||Object.defineProperty(R.prototype,"raycastAllowed",{get:function(){return this.userData&&this.userData.raycastAllowed!==!1},set:function(i){const n=this;n.userData||(n.userData={}),n.userData.raycastAllowed=i}}),Object.getOwnPropertyDescriptor(R.prototype,"worldPosition")||Object.defineProperty(R.prototype,"worldPosition",{get:function(){return this instanceof Yv?le(this.object):le(this)},set:function(i){Vi(this,i)}}),Object.getOwnPropertyDescriptor(R.prototype,"worldQuaternion")||Object.defineProperty(R.prototype,"worldQuaternion",{get:function(){return this instanceof Yv?Re(this.object):Re(this)},set:function(i){Fn(this,i)}}),Object.getOwnPropertyDescriptor(R.prototype,"worldRotation")||Object.defineProperty(R.prototype,"worldRotation",{get:function(){return Iu(this)},set:function(i){Fw(this,i)}}),Object.getOwnPropertyDescriptor(R.prototype,"worldScale")||Object.defineProperty(R.prototype,"worldScale",{get:function(){return Je(this)},set:function(i){hl(this,i)}});const o=new J,e=new v(0,0,0),t=new v(0,1,0);Object.getOwnPropertyDescriptor(R.prototype,"worldForward")||Object.defineProperty(R.prototype,"worldForward",{get:function(){return U().set(0,0,1).applyQuaternion(Re(this))},set:function(i){const n=xi().setFromRotationMatrix(o.lookAt(e.set(0,0,0),i,t.set(0,1,0)));this.worldQuaternion=n}}),Object.getOwnPropertyDescriptor(R.prototype,"worldRight")||Object.defineProperty(R.prototype,"worldRight",{get:function(){return U().set(1,0,0).applyQuaternion(Re(this))}}),Object.getOwnPropertyDescriptor(R.prototype,"worldUp")||Object.defineProperty(R.prototype,"worldUp",{get:function(){return U().set(0,1,0).applyQuaternion(Re(this))}}),Object.getOwnPropertyDescriptor(R.prototype,"contains")||Object.defineProperty(R.prototype,"contains",{value:function(i){if(!i)return!1;if(this===i)return!0;for(const n of this.children)if(n.contains(i))return!0;return!1}}),fb(R)}const Ep=x("debuggetcomponent"),cI=x("debuginstantiate");class $o{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new $o;return e.idProvider=this.idProvider,e.parent=this.parent,e.keepWorldPosition=this.keepWorldPosition,e.position=Array.isArray(this.position)?[...this.position]:this.position?.clone(),e.rotation=Array.isArray(this.rotation)?[...this.rotation]:this.rotation?.clone(),e.scale=Array.isArray(this.scale)?[...this.scale]:this.scale?.clone(),e.visible=this.visible,e.context=this.context,e.components=this.components,e}cloneAssign(e){this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=Array.isArray(e.position)?[...e.position]:e.position?.clone(),this.rotation=Array.isArray(e.rotation)?[...e.rotation]:e.rotation?.clone(),this.scale=Array.isArray(e.scale)?[...e.scale]:e.scale?.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function Ll(o){return o.visible}function oa(o,e){return typeof e=="number"&&(e=e>.5),o.visible=e,o.visible}function fS(o){return o[ho]||Ap(o)}function yS(o,e){o[hS]=e}function Ap(o){return Mn.isUsingInstancing(o)}function yb(o,e){return eh(o,e,!0,!0)}const bS=Symbol("isDestroyed");function Ys(o){return o[bS]}function _S(o,e){o[bS]=e}const bb=Symbol("isDontDestroy");function Dl(o,e=!0){o[bb]=e}const Ip=[],Lp=[];function ki(o,e=!0,t=!1){Ip.length=0,Lp.length=0,_b(o,e,!0);for(const i of Ip)i.gameObject=null,i.context=null;for(const i of Lp)_S(i,!0),t&&Be(i);Lp.length=0,Ip.length=0}function _b(o,e=!0,t=!0){if(o==null)return;const i=o;if(i.isComponent){if(i[bb])return;Ip.push(i);const r=i.gameObject;i.__internalDisable?.(),i.__internalDestroy?.(),i.gameObject=r;return}if(o[bb])return;const n=o;Ep&&console.log(n),Lp.push(n);const s=n.userData?.components;if(s!=null&&Array.isArray(s)){let r=s.length;for(let a=0;a<s.length;a++){const l=s[a];_b(l,e,!1),s.length<r&&(r=s.length,a--)}}if(e&&n.children)for(const r of n.children)_b(r,e,!1);t&&n.removeFromParent()}function $n(o,e,t=!0){return vS(o,e,t)}function*vb(o,e,t=!1,i=999,n=0){if(o?.userData.components&&!(n>i)){for(const s of o.userData.components)e&&s?.isComponent===!0&&s instanceof e?yield s:yield s;if(t===!0)for(const s of o.children)yield*vb(s,e,!0,i,n+1)}}function vS(o,e,t,i=0){if(o){if(o.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if(o.userData?.components)for(let n=0;n<o.userData.components.length;n++){const s=o.userData.components[n];if(s?.isComponent===!0){const r=e(s);if(r!==void 0)return r}}if(t&&o.children){const n=i+1;for(let s=0;s<o.children.length;s++){const r=o.children[s];if(!r)continue;const a=vS(r,e,t,n);if(a!==void 0)return a}}}}function Ks(o,e){if("isAssetReference"in o)return o.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new $o,t.position=e):t=e);let i=Q.Current;t?.context&&(i=t.context),Ep&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new _t(Date.now()));const n=[],s={},r={},a=wS(i,o,t,n,s,r);a&&(Z2(s),uI(r,s),dI(s)),Ep&&(Lu(o,!0),Lu(a,!0));const l={};for(const c in s){const h=s[c],d=h.original,u=h.clone;d instanceof R&&u instanceof R&&(l[d.guid||d.uuid]=u.guid||u.uuid)}if(t?.components!==!1){const c=new Set;for(const h in n){const d=n[h],u=d.guid;if(t&&t.idProvider){const m=d[ts],g=typeof m=="string"&&m.length>0?m:u;if(d.guid=g&&t.idProvider.remapUUID?t.idProvider.remapUUID(g):t.idProvider.generateUUID(),c.has(d.guid))if(console.warn(`[instantiate] duplicate component guid in source content ("${g}") \u2014 deriving a disambiguated guid. Fix the source: two components must not share a guid.`),t.idProvider.remapUUID&&g){let y=1;do d.guid=t.idProvider.remapUUID(`${g}:dup:${y++}`);while(c.has(d.guid))}else d.guid=t.idProvider.generateUUID();c.add(d.guid),l[u]=d.guid,g!==u&&(l[g]=d.guid),Ep&&console.log(d.name,d.guid)}kp(d,i),d.__internalNewInstanceCreated&&d.__internalNewInstanceCreated()}for(const h in n){const d=n[h];d.enabled!==!1&&(d.enabled=!0)}Dp(i)}return a}function wS(o,e,t,i,n,s){if(!e||e[Gi]||e instanceof Iv||e instanceof Lv||e.hideFlags&uo.DontInstantiate)return null;const r=e.userData;e.userData={};const a=e.children;e.children=[];const l=e.clone(!1);Eh(l),e.userData=r,e.children=a;const c={original:e,clone:l};if(n[e.uuid]=c,e.guid&&e.guid!==e.uuid&&(n[e.guid]=c),cI&&console.log("ADD",e,l),e.type==="SkinnedMesh"&&(s[e.uuid]={original:e,clone:l}),t?.visible!==void 0&&(l.visible=t.visible),t?.idProvider){const d=e.userData?.["needle-id"];l.uuid=d&&t.idProvider.remapUUID?t.idProvider.remapUUID(d):t.idProvider.generateUUID();const u=l;u&&(u.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const h=e.parent;if(h&&h.add(l),t?.position)if(Array.isArray(t.position)){const d=new v;d.fromArray(t.position),l.worldPosition=d}else l.worldPosition=t.position;else l.position.copy(e.position);if(t?.rotation){if(t.rotation instanceof B)l.worldQuaternion=t.rotation;else if(t.rotation instanceof je)l.worldQuaternion=xi().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const d=new je;d.fromArray(t.rotation),l.worldQuaternion=xi().setFromEuler(d)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const d=new v;d.fromArray(t.scale),t.scale=d}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=eh(t.parent,o.scene,!0):d=t.parent,d){const u=t.keepWorldPosition===!0?d.attach:d.add;u?u.call(d,l):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,u]of Object.entries(e.userData))d!=="components"&&(l.userData[d]=u);if(e.userData?.components){const d=e.userData.components,u=[];l.userData.components=u;for(let m=0;m<d.length;m++){const g=d[m],y=new g.constructor;hI(g,y),g[ts]!==void 0&&(y[ts]=g[ts]),u.push(y),y.gameObject=l,i.push(y),n[g.guid]={original:g,clone:y},Nu.dispatchComponentLifecycleEvent("component-added",y)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const d in e.children){const u=e.children[d],m=wS(o,u,t,i,n,s);m&&(n[m.uuid]={original:u,clone:m},l.add(m))}return l}function hI(o,e,t){bl(e,o,void 0,{})}function dI(o){for(const e in o){const t=o[e],i=t.original;if(i.isDirectionalLight!==!0&&i.isSpotLight!==!0)continue;const n=i.target;if(!n||n.parent!==i)continue;const s=Object.values(o).find(a=>a.original===n);if(!s)continue;const r=s.clone;t.clone.target=r,r.hideFlags|=uo.DontExport}}function uI(o,e){for(const t in o){const i=o[t],n=i.original,s=n.skeleton,r=i.clone;if(!s){console.warn("Skinned mesh has no skeleton?",i);continue}const a=s.bones,l=r.skeleton.clone();r.skeleton=l,r.bindMatrix.clone().copy(n.bindMatrix),r.bindMatrixInverse.copy(n.bindMatrixInverse);const c=[];l.bones=c;for(let h=0;h<a.length;h++){const d=a[h],u=e[d.uuid].clone;c.push(u)}}for(const t in o){const i=o[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function Ah(o,e){try{e||o()}catch(t){return console.error(t),!1}return!0}const wb=x("debugnewscripts"),pI=x("debughierarchy"),Ne=[];function mI(){return Ne.length>0}function Dp(o){if(wb&&console.log("Register new components",o.new_scripts.length,[...o.new_scripts],o.alias?"element: "+o.alias:o.hash,o),xS(o),!(o.new_scripts.length<=0)){Ne.length=0,o.new_scripts.length>0&&Ne.push(...o.new_scripts),o.new_scripts.length=0;for(let e=0;e<Ne.length;e++)try{const t=Ne[e];if(t.isComponent!==!0){(M()||wb)&&console.error(`Registered script is not a Needle Engine component.
884
884
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
885
885
  `,t),Ne.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
886
886
  Did you add and remove a component in the same frame?`),Ne.splice(e,1),e--;continue}t.context=o,Lh(t.gameObject),jp(t,o)}catch(t){console.error(t),yo(Ne[e],o),Ne.splice(e,1),e--}for(let e=0;e<Ne.length;e++)try{const t=Ne[e];if(t.destroyed){yo(Ne[e],o),Ne.splice(e,1),e--;continue}if(t.registering)try{t.registering()}catch(i){console.error(i)}t.__internalAwake!==void 0&&(t.gameObject||console.error("Calling awake for a component without a GameObject",t,t.gameObject),Lh(t.gameObject),t.activeAndEnabled&&Ah(t.__internalAwake.bind(t)))}catch(t){console.error(t),yo(Ne[e],o),Ne.splice(e,1),e--}for(let e=0;e<Ne.length;e++)try{const t=Ne[e];if(t.destroyed||t.enabled===!1||(Lh(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Ah(t.__internalEnable.bind(t)))}catch(t){console.error(t),yo(Ne[e],o),Ne.splice(e,1),e--}for(let e=0;e<Ne.length;e++)try{const t=Ne[e];if(t.destroyed||!t.gameObject)continue;o.new_script_start.push(t)}catch(t){console.error(t),yo(Ne[e],o),Ne.splice(e,1),e--}Ne.length=0;for(const e of o.new_scripts_post_setup_callbacks)e&&e();o.new_scripts_post_setup_callbacks.length=0}}function xS(o){for(;o.new_scripts_pre_setup_callbacks.length>0;){const e=o.new_scripts_pre_setup_callbacks.splice(0);for(const t of e)t&&t()}}function gI(o){o&&(o.__internalDisable(!0),yo(o,o.context))}function SS(o,e){for(let t=0;t<o.new_script_start.length;t++)try{const i=o.new_script_start[t];if(e!==void 0&&i.gameObject!==e||i.destroyed||i.activeAndEnabled===!1)continue;Ah(i.__internalAwake.bind(i)),i.enabled&&(Ah(i.__internalEnable.bind(i)),Ah(i.__internalStart.bind(i)),o.new_script_start.splice(t,1),t--)}catch(i){console.error(i),yo(o.new_script_start[t],o),o.new_script_start.splice(t,1),t--}}function jp(o,e){e.scripts.indexOf(o)===-1&&(e.scripts.push(o),o.earlyUpdate&&e.scripts_earlyUpdate.push(o),o.update&&e.scripts_update.push(o),o.lateUpdate&&e.scripts_lateUpdate.push(o),o.onBeforeRender&&e.scripts_onBeforeRender.push(o),o.onAfterRender&&e.scripts_onAfterRender.push(o),o.onPausedChanged&&e.scripts_pausedChanged.push(o),xb(o,null)&&e.new_scripts_xr.push(o),xb(o,"immersive-vr")&&e.scripts_immersive_vr.push(o),xb(o,"immersive-ar")&&e.scripts_immersive_ar.push(o))}function yo(o,e){dn(o,e.new_scripts),dn(o,e.new_script_start),dn(o,e.scripts),dn(o,e.scripts_earlyUpdate),dn(o,e.scripts_update),dn(o,e.scripts_lateUpdate),dn(o,e.scripts_onBeforeRender),dn(o,e.scripts_onAfterRender),dn(o,e.scripts_pausedChanged),dn(o,e.new_scripts_xr),dn(o,e.scripts_immersive_vr),dn(o,e.scripts_immersive_ar),e.stopAllCoroutinesFrom(o)}function dn(o,e){const t=e.indexOf(o);t>=0&&e.splice(t,1)}function xb(o,e){if(o){const t=o;if(t.onBeforeXR||t.onEnterXR||t.onUpdateXR||t.onLeaveXR||t.onXRControllerAdded||t.onXRControllerRemoved)return!(e!=null&&t.supportsXR?.(e)===!1)}return!1}let Sb=!0;function jl(){Sb=!0}function Ih(o,e=!1){if(ny.experimentalSmartHierarchyUpdate){if(!e&&!Sb)return;Sb=!1}if(o||(o=ce.Current.scene),!o){console.trace("Invalid call - no current context.");return}const t=Ll(o);Fp(o,t,!0)||(wb||M()?console.error(`Error updating hierarchy
@@ -904,7 +904,7 @@ ${t.path}! : AssetReference;
904
904
  Could not find method ${s.method} on object ${a.name}. Please rename ${s.method} to ${h}?
905
905
  `,a[h],`
906
906
  in script: `,a),ge("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
907
- Could not find method ${s.method} on object ${a.name}`,a,typeof a[s.method])};if(typeof a[s.method]!="function"){let h=!1,d=a;for(;d;){const u=Object.getOwnPropertyDescriptor(d,s.method);if(u&&(u.writable===!0||u.set)){h=!0;break}d=Object.getPrototypeOf(d)}!h&&(M()||Rt)&&c()}}if(a){let c=s.argument;if(c!==void 0?c=r(c):s.arguments!==void 0&&(c=s.arguments.map(r)),a[s.method]===void 0)console.warn(`EventList method not found: "${s.method}" on ${a?.name}`);else{c!==void 0&&!Array.isArray(c)&&(c=[c]);const h=new Wn(a,s.method,c,s.enabled);i.push(h)}}else M()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,s)}const n=new re(i);return Rt&&console.log(n),n}}}const Ab=new WeakMap;class JS extends qi{constructor(){super([qo,ro])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof Pe&&t.type===qo){let i=e;const n=Ab.get(i)?.deref();n&&(i=n),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof eM&&(i.isCompressedTexture=!1,i.format=gu);const s=i.image,r=new qo(s.width,s.height,{colorSpace:Xo});return r.texture=i,r}}}class eC extends qi{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return ao(t.gltfId,e)}}class dL extends qi{constructor(){super([Eb])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0){const i=ao(t.gltfId,e);if(i)return new Eb(i)}}}let tC,Ib,$h,iC;function nC(){const o=Pe.prototype.clone;Pe.prototype.clone=function(){const e=o.call(this);return Ab.has(e)||Ab.set(e,new WeakRef(this)),e},tC=new rL,new aL,Ib=new lL,$h=new cL,iC=new hL,new JS,new eC,new dL}var uL=Object.defineProperty,pL=Object.getOwnPropertyDescriptor,Wh=(o,e,t,i)=>{for(var n=i>1?void 0:i?pL(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&uL(e,t,n),n};const Hp=x("debuggroundprojection"),Vh=new je,mL=new J,oC=`
907
+ Could not find method ${s.method} on object ${a.name}`,a,typeof a[s.method])};if(typeof a[s.method]!="function"){let h=!1,d=a;for(;d;){const u=Object.getOwnPropertyDescriptor(d,s.method);if(u&&(u.writable===!0||u.set)){h=!0;break}d=Object.getPrototypeOf(d)}!h&&(M()||Rt)&&c()}}if(a){let c=s.argument;if(c!==void 0?c=r(c):s.arguments!==void 0&&(c=s.arguments.map(r)),a[s.method]===void 0)console.warn(`EventList method not found: "${s.method}" on ${a?.name}`);else{c!==void 0&&!Array.isArray(c)&&(c=[c]);const h=new Wn(a,s.method,c,s.enabled);i.push(h)}}else M()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,s)}const n=new re(i);return Rt&&console.log(n),n}}}const Ab=new WeakMap;class JS extends qi{constructor(){super([qo,ro])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof ke&&t.type===qo){let i=e;const n=Ab.get(i)?.deref();n&&(i=n),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof eM&&(i.isCompressedTexture=!1,i.format=gu);const s=i.image,r=new qo(s.width,s.height,{colorSpace:Xo});return r.texture=i,r}}}class eC extends qi{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return ao(t.gltfId,e)}}class dL extends qi{constructor(){super([Eb])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0){const i=ao(t.gltfId,e);if(i)return new Eb(i)}}}let tC,Ib,$h,iC;function nC(){const o=ke.prototype.clone;ke.prototype.clone=function(){const e=o.call(this);return Ab.has(e)||Ab.set(e,new WeakRef(this)),e},tC=new rL,new aL,Ib=new lL,$h=new cL,iC=new hL,new JS,new eC,new dL}var uL=Object.defineProperty,pL=Object.getOwnPropertyDescriptor,Wh=(o,e,t,i)=>{for(var n=i>1?void 0:i?pL(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&uL(e,t,n),n};const Hp=x("debuggroundprojection"),Vh=new je,mL=new J,oC=`
908
908
  #ifdef NEEDLE_USE_CUBE_UV_MAP
909
909
  varying vec3 vNeedleGroundProjectionWorldDirection;
910
910
  #endif
@@ -996,7 +996,7 @@ uniform mat3 needleGroundProjectionBackgroundRotation;
996
996
  #endif`),r.fragmentShader=r.fragmentShader.replace("#include <map_pars_fragment>",`#include <map_pars_fragment>
997
997
  ${gL}
998
998
  #include <cube_uv_reflection_fragment>`).replace("#include <map_fragment>",fL).replace("#include <opaque_fragment>",`${yL}
999
- #include <opaque_fragment>`)};const i=o.defines??={},n=JSON.stringify(i),s=e.mapping===ln?bL(e):null;if(s){const r=a=>Number.isInteger(a)?`${a}.0`:`${a}`;i.NEEDLE_USE_CUBE_UV_MAP=1,i.ENVMAP_TYPE_CUBE_UV=1,i.CUBEUV_TEXEL_WIDTH=r(s.texelWidth),i.CUBEUV_TEXEL_HEIGHT=r(s.texelHeight),i.CUBEUV_MAX_MIP=r(s.maxMip)}else delete i.NEEDLE_USE_CUBE_UV_MAP,delete i.ENVMAP_TYPE_CUBE_UV,delete i.CUBEUV_TEXEL_WIDTH,delete i.CUBEUV_TEXEL_HEIGHT,delete i.CUBEUV_MAX_MIP;n!==JSON.stringify(i)&&(o.needsUpdate=!0)}class wo extends T{applyOnAwake=!0;autoFit=!0;set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}_radius=50;set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}_height=3;set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}_arblending=0;_lastBackground;_lastRadius;_lastHeight;_projection;_watcher;_savedBackgroundBlur=null;_forceBackgroundBlur=e=>{if(this._savedBackgroundBlur!==null||!(this.scene.background instanceof Pe))return;const t=this.scene.backgroundBlurriness??0;this._savedBackgroundBlur=t,this.scene.backgroundBlurriness=1};_restoreBackgroundBlur=()=>{this._savedBackgroundBlur!==null&&(this.scene.backgroundBlurriness=this._savedBackgroundBlur,this._savedBackgroundBlur=null)};awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new Is(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{Hp&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0})),this.context.pre_render_callbacks.indexOf(this._forceBackgroundBlur)<0&&this.context.pre_render_callbacks.push(this._forceBackgroundBlur),this.context.post_render_callbacks.indexOf(this._restoreBackgroundBlur)<0&&this.context.post_render_callbacks.push(this._restoreBackgroundBlur)}onDisable(){this._teardown()}onDestroy(){this._teardown()}_teardown(){this._watcher?.revoke(),this._projection?.removeFromParent();const e=this.context.pre_render_callbacks.indexOf(this._forceBackgroundBlur);e>=0&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this._restoreBackgroundBlur);t>=0&&this.context.post_render_callbacks.splice(t,1),this._restoreBackgroundBlur()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Cu(1),this.updateProjection())}onBeforeRender(){if(this._projection&&this.scene.backgroundRotation&&(Vh.copy(this.scene.backgroundRotation),Vh.x*=-1,Vh.y*=-1,Vh.z*=-1,Lb(this._projection.material).needleGroundProjectionBackgroundRotation.value.setFromMatrix4(mL.makeRotationFromEuler(Vh))),this._projection){const e=this.context.xr?.isPassThrough===!0||this.context.xr?.isAR===!0,t=this.context.scene.background instanceof Pe?this.context.scene.background:e&&this.arBlending>0?this._lastBackground:void 0;if(t){const i=this.context.scene.backgroundBlurriness??0,n=this._lastBlurriness!==i;this.updateProjectionMaterial(t,n||this._needsTextureUpdate)}}}updateAndCreate(){this.updateProjection(),this._watcher?.apply()}_needsTextureUpdate=!1;_autoFitPending=!1;_awaitedBounds=new WeakSet;updateProjection(){const e=this.context.xr?.isPassThrough===!0||this.context.xr?.isAR===!0;let t;const i=this.context.scene.background;if(i instanceof Pe)t=i;else if(e&&this.arBlending>0&&this._lastBackground)t=this._lastBackground;else{this._projection?.removeFromParent();return}if(e&&this.arBlending===0){this._projection?.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let n=!0;const s=0,r=t!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||r){Hp&&console.log("Create/Update Ground Projection",t.name),this._projection?.removeFromParent();try{this._projection=new al(t,this._height,this._radius,64),sC(this._projection.material,t)}catch(a){console.error("Error creating three GroundProjection",a);return}this._projection.position.y=this._height-s,this._projection.name="GroundProjection",Kf(this._projection,!1)}else n=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&(n||this._autoFitPending)){this._autoFitPending=!1,this._projection.updateWorldMatrix(!0,!0);const a=Si(this.context.scene.children,[this._projection],void 0,void 0,{onIncomplete:(c,h)=>{h&&!this._awaitedBounds.has(c)&&(this._awaitedBounds.add(c),h.finally(()=>{this._autoFitPending=!0}))}}),l=a.min.y;if(l<1/0){const c=U();c.x=a.min.x+(a.max.x-a.min.x)*.5;const h=Je(this.gameObject).x;c.y=l+this._height*h-s,c.z=a.min.z+(a.max.z-a.min.z)*.5,Vi(this._projection,c)}Hp&&F.DrawWireBox3(a,65280,5)}this.updateProjectionMaterial(t,!0),this._lastBackground=t,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}_blurrynessShader=null;_lastBlurriness=-1;updateProjectionMaterial(e,t=!1){if(!this._projection)return;const i=this.context.scene.backgroundBlurriness??0,n=e.mapping===ln;let s=e;if(!n&&i>.001){const c=!!this._projection.material.map&&this._projection.material.map!==e;t||!c?s=this.updateBlurriness(e,i):this._projection.material.map&&(s=this._projection.material.map)}this._projection.material.map!==s&&(this._projection.material.map=s);const r=this._projection.material.map??e;r.mapping=e.mapping,sC(this._projection.material,r);const a=Lb(this._projection.material);a.needleGroundProjectionBlurriness.value=n?i:0,a.needleGroundProjectionBackgroundIntensity.value=this.context.scene.backgroundIntensity??1;const l=this._projection.material.transparent;this._projection.material.transparent=(this.context.xr?.isAR===!0&&this.arBlending>1e-6)??!1,a.needleGroundProjectionBlending.value=this._projection.material.transparent?this.arBlending:0,a.needleGroundProjectionAlphaFactor.value=this.context.isInPassThrough?.95:1,l!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1,this._lastBlurriness=i,this._needsTextureUpdate=!1}updateBlurriness(e,t){Hp&&console.log("Update Blurriness",t),this._blurrynessShader??=new oo({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t}},vertexShader:_L,fragmentShader:vL}),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=t,e.needsUpdate=!0;const i=Er.copyTexture(e,this._blurrynessShader);return i.mapping=e.mapping,i}}Wh([p()],wo.prototype,"applyOnAwake",2),Wh([p()],wo.prototype,"autoFit",2),Wh([p()],wo.prototype,"radius",1),Wh([p()],wo.prototype,"height",1),Wh([p()],wo.prototype,"arBlending",1);const _L=`
999
+ #include <opaque_fragment>`)};const i=o.defines??={},n=JSON.stringify(i),s=e.mapping===ln?bL(e):null;if(s){const r=a=>Number.isInteger(a)?`${a}.0`:`${a}`;i.NEEDLE_USE_CUBE_UV_MAP=1,i.ENVMAP_TYPE_CUBE_UV=1,i.CUBEUV_TEXEL_WIDTH=r(s.texelWidth),i.CUBEUV_TEXEL_HEIGHT=r(s.texelHeight),i.CUBEUV_MAX_MIP=r(s.maxMip)}else delete i.NEEDLE_USE_CUBE_UV_MAP,delete i.ENVMAP_TYPE_CUBE_UV,delete i.CUBEUV_TEXEL_WIDTH,delete i.CUBEUV_TEXEL_HEIGHT,delete i.CUBEUV_MAX_MIP;n!==JSON.stringify(i)&&(o.needsUpdate=!0)}class wo extends T{applyOnAwake=!0;autoFit=!0;set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}_radius=50;set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}_height=3;set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}_arblending=0;_lastBackground;_lastRadius;_lastHeight;_projection;_watcher;_savedBackgroundBlur=null;_forceBackgroundBlur=e=>{if(this._savedBackgroundBlur!==null||!(this.scene.background instanceof ke))return;const t=this.scene.backgroundBlurriness??0;this._savedBackgroundBlur=t,this.scene.backgroundBlurriness=1};_restoreBackgroundBlur=()=>{this._savedBackgroundBlur!==null&&(this.scene.backgroundBlurriness=this._savedBackgroundBlur,this._savedBackgroundBlur=null)};awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new Is(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{Hp&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0})),this.context.pre_render_callbacks.indexOf(this._forceBackgroundBlur)<0&&this.context.pre_render_callbacks.push(this._forceBackgroundBlur),this.context.post_render_callbacks.indexOf(this._restoreBackgroundBlur)<0&&this.context.post_render_callbacks.push(this._restoreBackgroundBlur)}onDisable(){this._teardown()}onDestroy(){this._teardown()}_teardown(){this._watcher?.revoke(),this._projection?.removeFromParent();const e=this.context.pre_render_callbacks.indexOf(this._forceBackgroundBlur);e>=0&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this._restoreBackgroundBlur);t>=0&&this.context.post_render_callbacks.splice(t,1),this._restoreBackgroundBlur()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Cu(1),this.updateProjection())}onBeforeRender(){if(this._projection&&this.scene.backgroundRotation&&(Vh.copy(this.scene.backgroundRotation),Vh.x*=-1,Vh.y*=-1,Vh.z*=-1,Lb(this._projection.material).needleGroundProjectionBackgroundRotation.value.setFromMatrix4(mL.makeRotationFromEuler(Vh))),this._projection){const e=this.context.xr?.isPassThrough===!0||this.context.xr?.isAR===!0,t=this.context.scene.background instanceof ke?this.context.scene.background:e&&this.arBlending>0?this._lastBackground:void 0;if(t){const i=this.context.scene.backgroundBlurriness??0,n=this._lastBlurriness!==i;this.updateProjectionMaterial(t,n||this._needsTextureUpdate)}}}updateAndCreate(){this.updateProjection(),this._watcher?.apply()}_needsTextureUpdate=!1;_autoFitPending=!1;_awaitedBounds=new WeakSet;updateProjection(){const e=this.context.xr?.isPassThrough===!0||this.context.xr?.isAR===!0;let t;const i=this.context.scene.background;if(i instanceof ke)t=i;else if(e&&this.arBlending>0&&this._lastBackground)t=this._lastBackground;else{this._projection?.removeFromParent();return}if(e&&this.arBlending===0){this._projection?.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let n=!0;const s=0,r=t!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||r){Hp&&console.log("Create/Update Ground Projection",t.name),this._projection?.removeFromParent();try{this._projection=new al(t,this._height,this._radius,64),sC(this._projection.material,t)}catch(a){console.error("Error creating three GroundProjection",a);return}this._projection.position.y=this._height-s,this._projection.name="GroundProjection",Kf(this._projection,!1)}else n=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&(n||this._autoFitPending)){this._autoFitPending=!1,this._projection.updateWorldMatrix(!0,!0);const a=Si(this.context.scene.children,[this._projection],void 0,void 0,{onIncomplete:(c,h)=>{h&&!this._awaitedBounds.has(c)&&(this._awaitedBounds.add(c),h.finally(()=>{this._autoFitPending=!0}))}}),l=a.min.y;if(l<1/0){const c=U();c.x=a.min.x+(a.max.x-a.min.x)*.5;const h=Je(this.gameObject).x;c.y=l+this._height*h-s,c.z=a.min.z+(a.max.z-a.min.z)*.5,Vi(this._projection,c)}Hp&&F.DrawWireBox3(a,65280,5)}this.updateProjectionMaterial(t,!0),this._lastBackground=t,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}_blurrynessShader=null;_lastBlurriness=-1;updateProjectionMaterial(e,t=!1){if(!this._projection)return;const i=this.context.scene.backgroundBlurriness??0,n=e.mapping===ln;let s=e;if(!n&&i>.001){const c=!!this._projection.material.map&&this._projection.material.map!==e;t||!c?s=this.updateBlurriness(e,i):this._projection.material.map&&(s=this._projection.material.map)}this._projection.material.map!==s&&(this._projection.material.map=s);const r=this._projection.material.map??e;r.mapping=e.mapping,sC(this._projection.material,r);const a=Lb(this._projection.material);a.needleGroundProjectionBlurriness.value=n?i:0,a.needleGroundProjectionBackgroundIntensity.value=this.context.scene.backgroundIntensity??1;const l=this._projection.material.transparent;this._projection.material.transparent=(this.context.xr?.isAR===!0&&this.arBlending>1e-6)??!1,a.needleGroundProjectionBlending.value=this._projection.material.transparent?this.arBlending:0,a.needleGroundProjectionAlphaFactor.value=this.context.isInPassThrough?.95:1,l!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1,this._lastBlurriness=i,this._needsTextureUpdate=!1}updateBlurriness(e,t){Hp&&console.log("Update Blurriness",t),this._blurrynessShader??=new oo({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t}},vertexShader:_L,fragmentShader:vL}),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=t,e.needsUpdate=!0;const i=Er.copyTexture(e,this._blurrynessShader);return i.mapping=e.mapping,i}}Wh([p()],wo.prototype,"applyOnAwake",2),Wh([p()],wo.prototype,"autoFit",2),Wh([p()],wo.prototype,"radius",1),Wh([p()],wo.prototype,"height",1),Wh([p()],wo.prototype,"arBlending",1);const _L=`
1000
1000
  varying vec2 vUv;
1001
1001
 
1002
1002
  void main() {
@@ -1083,8 +1083,8 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
1083
1083
 
1084
1084
  Content-Type: "${t.headers.get("content-type")}"
1085
1085
  "Text: "${s}"
1086
- Binary:`,i)}else $e&&console.debug("Could not determine file type from binary data");return"unknown"}const u0=x("debugstencil");function FD(o,e){return(o&1<<e.layer)!=0}const BD=Symbol("stencils");class Ar{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(u0&&console.log(t,Ar.stencils),!t)return;const i=Ar.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];if(FD(s.layer,e)){u0&&console.log(s),setTimeout(()=>{Ni()&&Ap(e.gameObject)&&(ge("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let r=0;r<e.sharedMaterials.length;r++){let a=e.sharedMaterials[r];a&&(a=a.clone(),a[BD]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=s.value,a.stencilFunc=s.compareFunc,a.stencilZPass=s.passOp,a.stencilFail=s.failOp,a.stencilZFail=s.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=s.event*1e3+s.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[zD];if(i){u0&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const s of n){const r={...s};r.compareFunc=UD(r.compareFunc),r.passOp=p0(r.passOp),r.failOp=p0(r.failOp),r.zFailOp=p0(r.zFailOp),Ar.stencils[this.source]||(Ar.stencils[this.source]=[]),Ar.stencils[this.source].push(r)}}}return null}}function p0(o){switch(o){case 0:return wM;case 1:return vM;case 2:return _M;case 3:return bM;case 4:return yM;case 6:return fM;case 7:return gM;case 5:return mM}return 0}function UD(o){switch(o){case 1:return zv;case 2:return pM;case 3:return uM;case 4:return dM;case 5:return hM;case 6:return cM;case 7:return lM;case 8:return aM}return zv}const zD="NEEDLE_render_objects";class ND{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 i=this.meshToOwners.get(e);i||(i=new Set,this.meshToOwners.set(e,i)),i.add(t)}removeHook(e,t){const i=this.meshToOwners.get(e);i&&(i.delete(t),i.size===0&&this.meshToOwners.delete(e))}getOriginalCallbacks(e){return this.meshToOriginalCallbacks.get(e)}setOriginalCallbacks(e,t){this.meshToOriginalCallbacks.set(e,t)}}const rr=new ND;class Ls{_overrides=[];_defines={};_object=null;get object(){return this._object}constructor(e=null){this._object=e}static get(e){let t=rr.getBlock(e);return t||(t=new Ls(e),rr.setBlock(e,t),GD(e,t)),t}static hasOverrides(e){const t=rr.getBlock(e);return t?t.hasOverrides():!1}dispose(){this._object&&rr.deleteBlock(this._object),this._overrides=[],this._object=null}setOverride(e,t,i){const n=this._overrides.find(s=>s.name===e);n?(n.value=t,n.textureTransform=i):this._overrides.push({name:e,value:t,textureTransform:i})}getOverride(e){return this._overrides.find(t=>t.name===e)}removeOverride(e){const t=this._overrides.findIndex(i=>i.name===e);t>=0&&this._overrides.splice(t,1)}removeOveride(e){this.removeOverride(e)}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(){const e=[],t=Object.keys(this._defines).sort();for(const i of t){const n=this._defines[i];n!==void 0&&e.push(`d:${i}=${n}`)}for(const i of this._overrides){if(i.value===null)continue;let n="";if(i.value instanceof Pe){if(n=i.value.uuid||"texture",i.textureTransform){const s=i.textureTransform;s.offset&&(n+=`;to:${s.offset.x},${s.offset.y}`),s.repeat&&(n+=`;tr:${s.repeat.x},${s.repeat.y}`)}}else if(Array.isArray(i.value))n=i.value.join(",");else if(i.value&&typeof i.value=="object"&&"r"in i.value){const s=i.value;n=`${s.r},${s.g},${s.b},${s.a!==void 0?s.a:""}`}else if(i.value&&typeof i.value=="object"&&"x"in i.value){const s=i.value;n=`${s.x},${s.y}${s.z!==void 0?`,${s.z}`:""}${s.w!==void 0?`,${s.w}`:""}`}else n=String(i.value);e.push(`${i.name}=${n}`)}return e.join(";")}}const vm=Symbol("originalValues"),wm=Symbol("savedTextureTransforms");function m0(o){let e=rr.getBlock(o);if(e)return{block:e,owner:o};if(o.parent&&o.parent.type==="Group"&&(e=rr.getBlock(o.parent),e))return{block:e,owner:o.parent}}const Yl=Symbol("beforeRenderingFlag"),g0=new WeakMap,f0=new WeakMap,$D=function(o,e,t,i){const n=m0(this)?.block;if(n&&n.hasOverrides()){const s=n.getOverride("transmission")?.value,r=n.getOverride("transparent")?.value;s!==void 0&&typeof s=="number"&&"transmission"in t&&s!==t.transmission&&(f0.set(this,t.transmission),t.transmission=s),r!==void 0&&typeof r=="boolean"&&r!==t.transparent&&(g0.set(this,t.transparent),t.transparent=r)}},WD=function(o,e,t,i){const n=g0.get(o);n!==void 0&&(g0.delete(o),t.transparent=n);const s=f0.get(o);s!==void 0&&(f0.delete(o),t.transmission=s)};let GC=!1;const VD=x("debugreflectionprobe"),HC=function(o,e,t,i,n,s){const r=this.material;if(!r)return;if(Array.isArray(r)){if(!r.includes(n))return}else if(r!==n)return;this[Yl]===void 0&&(this[Yl]=new WeakSet),this[Yl].add(n);const a=m0(this);if(!a)return;const{block:l,owner:c}=a,h=l.overrides,d=n,u=l.getDefines(),m=Object.keys(u);if(m.length>0){d.defines||(d.defines={});for(const b of m){const f=u[b];f!==void 0&&(d.defines[b]=f)}}if(h.length===0&&m.length===0)return;let g=m.length>0;d[vm]||(d[vm]=[]);const y=d[vm];for(const b of h){if(b.value===null)continue;if(d.isMeshBasicMaterial===!0&&(b.name==="envMap"||b.name==="envMapRotation"||b.name==="envMapIntensity")){b.name==="envMap"&&!GC&&(M()||VD)&&(GC=!0,console.warn(`MaterialPropertyBlock: Ignoring envMap override on MeshBasicMaterial (object: "${this.name}", material: "${n.name}"). Use a lit material such as MeshStandardMaterial if reflection probes are intended.`));continue}const f=d[b.name],_=y.find(w=>w.name===b.name);if(_?_.value=f:y.push({name:b.name,value:f}),!g&&!!f!=!!b.value&&(g=!0),d[b.name]=b.value,b.textureTransform&&b.value instanceof Pe){const w=b.value;d[wm]||(d[wm]=[]),d[wm].push({name:b.name,offsetX:w.offset.x,offsetY:w.offset.y,repeatX:w.repeat.x,repeatY:w.repeat.y});const S=b.textureTransform;S.offset&&w.offset.copy(S.offset),S.repeat&&w.repeat.copy(S.repeat)}}g&&(d.needsUpdate=!0),d._forceRefresh=!0},qC=function(o,e,t,i,n,s){if(this[Yl]===void 0||!this[Yl].has(n))return;this[Yl].delete(n);const r=m0(this);if(!r)return;const{block:a,owner:l}=r,c=a.overrides,h=n,d=h[vm],u=a.getDefines(),m=Object.keys(u);let g=!1;if(m.length>0&&h.defines){for(const b of m)delete h.defines[b];g=!0}if(c.length===0){g&&(h.needsUpdate=!0,h._forceRefresh=!0);return}if(!d)return;const y=h[wm];if(y&&y.length>0){for(const b of y){const f=c.find(_=>_.name===b.name);f?.value instanceof Pe&&(f.value.offset.set(b.offsetX,b.offsetY),f.value.repeat.set(b.repeatX,b.repeatY))}y.length=0}for(const b of c){const f=d.find(_=>_.name===b.name);f&&(!g&&!!b.value!=!!f.value&&(g=!0),h[b.name]=f.value)}g&&(h.needsUpdate=!0),h._forceRefresh=!0};function GD(o,e){o.type==="Group"?o.children.forEach(t=>{(t.type==="Mesh"||t.type==="SkinnedMesh")&&XC(t,o,e)}):(o.type==="Mesh"||o.type==="SkinnedMesh")&&XC(o,o,e)}function XC(o,e,t){if(!rr.isHooked(o,e)){if(rr.addHook(o,e),o["needle:materialPropertyBlock"]=t,!o.onBeforeRender)o.onBeforeRender=HC;else{const i=o.onBeforeRender;o.onBeforeRender=function(n,s,r,a,l,c){i.call(this,n,s,r,a,l,c),HC.call(this,n,s,r,a,l,c)}}if(!o.onAfterRender)o.onAfterRender=qC;else{const i=o.onAfterRender;o.onAfterRender=function(n,s,r,a,l,c){qC.call(this,n,s,r,a,l,c),i.call(this,n,s,r,a,l,c)}}o.onBeforeRenderListPush=$D,o.onAfterRenderListPush=WD}}var HD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,xm=(o,e,t,i)=>{for(var n=i>1?void 0:i?qD(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&HD(e,t,n),n};const Kl=x("debugreflectionprobe"),QC=x("noreflectionprobe");let wa=null;const XD=Symbol("reflectionProbeKey"),ld=class io extends T{static _probes=new Map;static testBox=new ri;static isUsingReflectionProbe(e){return!!e[XD]}static onEnabled=new re;static onDisabled=new re;static get(e,t,i,n){if(!e||e.isObject3D!==!0||QC)return null;const s=io._probes.get(t);if(s){for(const r of s)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return Kl&&console.log("Found reflection probe",e.name,r.name),r}}return Kl&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;_textureUrlInFlight;set texture(e){if(this._texture!==e){if(typeof e=="string"){Kl&&console.debug(`[ReflectionProbe] Loading reflection probe texture from URL: ${e}`),this._textureUrlInFlight=e;const t=ao(this.sourceId,e);id(t,this.context.renderer).then(i=>{this._textureUrlInFlight===e&&i&&(this._textureUrlInFlight=void 0,Kl&&console.debug(`[ReflectionProbe] Successfully loaded reflection probe texture: ${e}`),this.texture=i)});return}this.__didAwake&&(this._textureUrlInFlight=void 0),this._texture=e,Kl&&console.debug("[ReflectionProbe] Set reflection probe texture "+(e?.name||"(removed)")),e&&(e instanceof ff||e.mapping===ln||e.mapping!==Qo&&(e.mapping=Qo),e.colorSpace=Xo,e.needsUpdate=!0)}}get texture(){return this._texture}intensity=1;center=new v;size=new v(1,1,1);__lightmapIntensityScale=!0;isInBox(e){return wa??=new ri,wa.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),Si([e],void 0,void 0,io.testBox),io.testBox.isEmpty()?wa.containsPoint(e.worldPosition):wa?.intersectsBox(io.testBox)}constructor(){super(),io._probes.has(this.context)||io._probes.set(this.context,[]),io._probes.get(this.context)?.push(this)}awake(){this._texture&&(this._texture.mapping!==ln&&(this._texture.mapping=Qo),this._texture.colorSpace=Xo,this._texture.needsUpdate=!0)}update(){Kl&&(wa??=new ri,wa.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),F.DrawWireBox3(wa,5592320))}onEnable(){io.onEnabled?.invoke(this)}onDisable(){io.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(){const e=io._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}apply(e){if(QC||!this.enabled||!this.texture)return;const t=Ls.get(e);t.setOverride("envMap",this.texture),t.setOverride("envMapRotation",this.gameObject.rotation);let i=this.intensity;this.__lightmapIntensityScale&&t.getOverride("lightMap")&&(i/=Math.PI),t.setOverride("envMapIntensity",i)}unapply(e){const t=Ls.get(e);t&&t.getOverride("envMap")?.value===this.texture&&(t.removeOverride("envMap"),t.removeOverride("envMapRotation"),t.removeOverride("envMapIntensity"))}};xm([p([Pe,String])],ld.prototype,"texture",1),xm([p()],ld.prototype,"intensity",2),xm([p(v)],ld.prototype,"center",2),xm([p(v)],ld.prototype,"size",2);let ps=ld;const y0=x("debugexr");class QD{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,y0&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,n=i.json.textures[e];if(y0&&console.log("EXT_texture_exr.loadTexture",e,n),!n.extensions||!n.extensions[t])return null;const s=n.extensions[t],r=new xf(i.options.manager);return y0&&console.log("EXT_texture_exr.loadTexture",s),i.loadTextureImage(e,s.source,r)}}typeof window<"u"&&window.addEventListener("unhandledrejection",o=>{});const Po=Rt,Sm="$___Export_Components",YD="NEEDLE_components";class KD{[Gr]}class ZD{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class b0{get name(){return YD}exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{if("serializeUserData"in t){const i=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,s)=>{try{this.serializeUserData(n,s)&&(t.extensionsUsed[this.name]=!0),i(n,s)}finally{this.afterSerializeUserData(n,s)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){const i=e.userData?.components;return!i||i.length<=0?!1:(delete e.userData.components,e[Sm]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Po&&console.log("DONE",JSON.stringify(t)),e[Sm]===void 0)return;const i=e[Sm];delete e[Sm],i!==null&&(e.userData.components=i)}writeNode(e,t){Po&&console.log(e.name,e.uuid);const i=new ZD(e,-1,t);this.exportContext[e.uuid]=i}afterParse(e){Po&&console.log("AFTER",e);const t=this.writer?.nodeMap;if(t)for(const[n,s]of t)this.objectToNodeMap[n.uuid]=s;for(const n in this.exportContext){const s=this.exportContext[n],r=s.node,a=s.nodeDef,l=t?.get(r)??s.nodeIndex;l===void 0||l<0||this.writeComponentsIntoDef(r,a,l)}const i=this.writer?.json?.scenes;if(i){const n=Array.isArray(e)?e:[e];let s=0;for(const r of n)if(r?.isScene===!0){if(s>=i.length)break;this.writeComponentsIntoDef(r,i[s]),s++}}}writeComponentsIntoDef(e,t,i){const n=e.userData?.components;if(!n||n.length<=0)return;this.context.object=e,this.context.nodeId=i,this.context.objectToNode=this.objectToNodeMap;const s=[];for(const r of n){this.context.target=r;const a=is().writeBuiltinComponentData(r,this.context);a!==null&&s.push(a)}if(s.length>0){const r=new KD;r[Gr]=s,t.extensions=t.extensions||{},t.extensions[this.name]=r,Po&&console.log("DID WRITE",e,i!==void 0?`nodeIndex ${i}`:"(scene)",s)}}parser;nodeToObjectMap={};gltf=null;beforeRoot(){return Po&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;const t=e.parser,i=t?.extensions;if(!i)return;const n=i[this.name];Po&&console.log("After root",e,this.parser,i);const s=[];if(n===!0){const r=t.json.nodes;if(r){for(let l=0;l<r.length;l++){const c=await t.getDependency("node",l);this.nodeToObjectMap[l]=c}for(let l=0;l<r.length;l++){const c=r[l],h=l,d=c.extensions;if(!d)continue;const u=d[this.name];if(!u)continue;Po&&console.log("NODE",c);const m=this.nodeToObjectMap[h];if(!m){console.error("Could not find object for node index: "+h,c,t);continue}Eh(m),s.push(this.createComponents(e,c,m,u))}}const a=t.json.scenes;if(a)for(let l=0;l<a.length;l++){const c=a[l],h=c?.extensions?.[this.name];if(!h)continue;const d=await t.getDependency("scene",l);if(!d){console.error("Could not find scene for index: "+l,c,t);continue}Eh(d),s.push(this.createComponents(e,c,d,h))}}await Promise.all(s);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;YE(r,l)}}}async createComponents(e,t,i,n){if(!n)return;const s=n[Gr];if(s){const r=new Array;Po&&console.log(i.name,s);for(const a in s){const l=s[a];if(Po&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),(l?.name==="MeshRenderer"||l?.name==="SkinnedMeshRenderer")&&!l.sharedMaterials){let c=!1;if("mesh"in t){const h=t.mesh;if(typeof h=="number"&&e.parser){const d=e.parser.json.meshes?.[h];d?.primitives&&(l.sharedMaterials=d.primitives.map(u=>"/materials/"+(u.material??0)),c=!0)}}!c&&(Po||M())&&console.warn(`[NEEDLE_components] Component '${l.name}' on object '${i.name}' is not added to a mesh or failed to retrieve materials from glTF.`)}l&&this.parser&&r.push(wy(this.parser,l).catch(c=>console.error(`Error while resolving references (see console for details)
1087
- `,c,i,l))),i.userData=i.userData||{},i.userData[Gr]=i.userData[Gr]||[],i.userData[Gr].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const YC="NEEDLE_gameobject_data",JD={Default:0,"Ignore Raycast":2},Cm=new Map,_0=8,Pm=31;function ej(o){if(typeof o=="number"&&isFinite(o))return o;if(typeof o=="string"&&o.length>0){const e=JD[o];if(e!==void 0)return e;let t=Cm.get(o);return t===void 0&&(t=Math.min(_0+Cm.size,Pm),_0+Cm.size>Pm&&console.warn(`[NEEDLE_gameobject_data] more than ${Pm-_0+1} named layers \u2014 "${o}" shares index ${Pm}`),Cm.set(o,t)),t}return 0}class tj{get name(){return YC}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const s=n.extensions[YC];if(s){const r=this.findAndApplyExtensionData(i,s);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(ej(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}}const KC="NEEDLE_lighting_settings",Zl=x("debugenvlight");class ij{get name(){return KC}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[KC];if(i){Zl&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const s=e.scene.children[0];n=P.addComponent(s,km,{},{callAwake:!1})}else{const s=new R;s.name="LightSettings "+this.sourceId,e.scene.add(s),n=P.addComponent(s,km,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new oe().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(s=>new oe().fromArray(s))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}ce.registerCallback(de.ContextCreated,o=>{const e=o.context,t=P.findObjectOfType(km,e);t?.sourceId&&(t.enabled=!0)});class km extends T{ambientMode=Cl.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=mp.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===mp.Skybox?fo.Skybox:fo.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),Zl&&window.addEventListener("keydown",t=>{this.destroyed||t.key==="l"&&(this.enabled=!this.enabled)});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*j.lerp(0,1.33,t)}onEnable(){if(Zl&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Cl.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new xM(this.ambientLight,this.ambientIntensity*e),Zl&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Cl.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new SM(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),Zl&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,i)}}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(){Zl&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}var Om;(o=>{async function e(t,i){if(!t)throw new Error("URL or XML string is required to load a MaterialX material");const n=await A.MaterialX.load(),s=t.trimStart().startsWith("<"),r=s?t:await fetch(t).then(c=>c.text()).catch(console.error);if(!r)return console.warn("Failed to load MaterialX file from url",t),null;let a;if(i?.url||!s){const c=(i?.url||t).split("/");c.pop(),a=c.join("/")}const l=new jr;return n.Experimental_API.createMaterialXMaterial(r,i?.materialNameOrIndex??0,{getTexture:async c=>(!c.startsWith("http")&&!c.startsWith("data:")&&!c.startsWith("blob:")&&!c.startsWith("file:")&&a&&(c=a+"/"+c),l.loadAsync(c).catch(h=>{console.warn(`Failed to load texture for MaterialX material ${c}`,h)}))},{cacheKey:t})}o.loadFromUrl=e})(Om||(Om={}));class nj extends CM{loadAsync(e,t){return new Promise((i,n)=>{this.load(e,i,t,n)})}load(e,t,i,n){i?.({type:"progress",loaded:0,total:0}),Om.loadFromUrl(e,{}).then(s=>{s?t(this.onLoaded(s)):n?.(new Error("Failed to load MaterialX material from url: "+e))})}onLoaded(e){return Gs.createPrimitive("ShaderBall",{material:e})}}class oj{constructor(e,t,i,n){this.context=e,this.url=i,this.parser=n}context;url;parser;get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const e=await A.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(t){console.error(t)}}}loadMaterial(e){return this.mtlxLoader?this.mtlxLoader.loadMaterial(e):null}}var ZC=(o=>(o[o.INT=5124]="INT",o[o.FLOAT=5126]="FLOAT",o[o.FLOAT_VEC2=35664]="FLOAT_VEC2",o[o.FLOAT_VEC3=35665]="FLOAT_VEC3",o[o.FLOAT_VEC4=35666]="FLOAT_VEC4",o[o.INT_VEC2=35667]="INT_VEC2",o[o.INT_VEC3=35668]="INT_VEC3",o[o.INT_VEC4=35669]="INT_VEC4",o[o.BOOL=35670]="BOOL",o[o.BOOL_VEC2=35671]="BOOL_VEC2",o[o.BOOL_VEC3=35672]="BOOL_VEC3",o[o.BOOL_VEC4=35673]="BOOL_VEC4",o[o.FLOAT_MAT2=35674]="FLOAT_MAT2",o[o.FLOAT_MAT3=35675]="FLOAT_MAT3",o[o.FLOAT_MAT4=35676]="FLOAT_MAT4",o[o.SAMPLER_2D=35678]="SAMPLER_2D",o[o.SAMPLER_3D=35680]="SAMPLER_3D",o[o.SAMPLER_CUBE=35681]="SAMPLER_CUBE",o[o.UNKNOWN=0]="UNKNOWN",o))(ZC||{});const ko=x("debugcustomshader"),Jl="NEEDLE_techniques_webgl";class sj{objectToWorldMatrix=new J;worldToObjectMatrix=new J;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),pp(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),pp(this.worldToObjectMatrix,this.worldToObject)}}class ze extends Nv{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return JC(e),e}constructor(e,...t){super(...t),this.identifier=e,ko&&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)&&Q.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=Q.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&Q.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new J;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new J;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new v;static _mainLightColor=new ve;static _mainLightPosition=new v;static _lightData=new ve;_rendererData=new sj;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&Q.Current.setRequireColor(!0),this.depthTextureUniform&&Q.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,s,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,s)}onUpdateUniforms(e,t){const i=Q.Current;if(e&&(ze.viewProjection&&this.uniforms[this._viewProjectionName]&&(ze.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),pp(ze.viewProjection,ze._viewProjectionValues)),ze.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ze.viewMatrix.copy(e.matrixWorldInverse),pp(ze.viewMatrix,ze._viewMatrixValues)),this.uniforms[ze._worldSpaceCameraPosName]&&ze._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=i.sceneLighting.timeVec4.x/20,a.y=i.sceneLighting.timeVec4.x,a.z=i.sceneLighting.timeVec4.x*2,a.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(i.sceneLighting.timeVec4.x/8),a.y=Math.sin(i.sceneLighting.timeVec4.x/4),a.z=Math.sin(i.sceneLighting.timeVec4.x/2),a.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(i.sceneLighting.timeVec4.x/8),a.y=Math.cos(i.sceneLighting.timeVec4.x/4),a.z=Math.cos(i.sceneLighting.timeVec4.x/2),a.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=i.time.deltaTime,a.y=1/i.time.deltaTime,a.z=i.time.smoothedDeltaTime,a.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const a=le(n.gameObject,ze._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ze._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ze._mainLightColor};const l=n.intensity;ze._lightData.z=l,this.uniforms.unity_LightData={value:ze._lightData}}if(e&&(ze.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ze._viewProjectionValues),ze.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ze._viewMatrixValues),this.uniforms[ze._worldSpaceCameraPosName]&&(this.uniforms[ze._worldSpaceCameraPosName]={value:ze._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const s=this.depthTextureUniform;s&&(s.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class rj{get name(){return Jl}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return ko&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Jl])return ko&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;ko&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Jl].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Jl];if(!n)return ko?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;ko&&console.log(n);const s=n.techniques[i];return s?new Promise(async(r,a)=>{const l=await AA(n,s.program),c=l?.fragmentShader,h=l?.vertexShader;if(!c||!h)return a();ko&&console.log("loadMaterial",t,l);const d={},u=s.uniforms;(h.includes("_Time")||c.includes("_Time"))&&(d._Time={value:new ve(0,0,0,0)}),(h.includes("_SinTime")||c.includes("_SinTime"))&&(d._SinTime={value:new ve(0,0,0,0)}),(h.includes("_CosTime")||c.includes("_CosTime"))&&(d._CosTime={value:new ve(0,0,0,0)}),(h.includes("unity_DeltaTime")||c.includes("unity_DeltaTime"))&&(d.unity_DeltaTime={value:new ve(0,0,0,0)});for(const y in u){const b=y;switch(b){case"_TimeParameters":const f=new ve;d[b]={value:f};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":d[b]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":d[b]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":d[b]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":d[b]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":d[b]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Jl]){const y=t.extensions[Jl];if(y.technique===i){ko&&console.log(t.name,"Material Properties",y);for(const b in y.values){const f=y.values[b];if(typeof f=="string"){if(f.startsWith("/textures/")){const _=f.substring(10),w=Number.parseInt(_);if(w>=0){const S=await this.parser.getDependency("texture",w);S instanceof Pe&&(S.colorSpace=Xo,S.needsUpdate=!0),d[b]={value:S};continue}}if(b==="alphaMode"){f==="BLEND"&&(m=!0);continue}}if(Array.isArray(f)&&f.length===4){d[b]={value:new ve(f[0],f[1],f[2],f[3])};continue}d[b]={value:f}}}}const g=new ze(this.identifier,{name:t.name??"",uniforms:d,vertexShader:h,fragmentShader:c,lights:!1});switch(g.glslVersion=PM,g.vertexShader=g.vertexShader.replace("#version 300 es",""),g.fragmentShader=g.fragmentShader.replace("#version 300 es",""),d._Cull?.value){case 0:g.side=Bi;break;case 1:g.side=wu;break;case 2:g.side=Us;break;default:g.side=Us;break}switch(d._ZTest?.value){case 3:g.depthTest=!0,g.depthFunc=AM;break;case 6:g.depthTest=!0,g.depthFunc=EM;break;case 2:g.depthTest=!0,g.depthFunc=TM;break;case 4:g.depthTest=!0,g.depthFunc=RM;break;case 5:g.depthTest=!0,g.depthFunc=MM;break;case 7:g.depthTest=!0,g.depthFunc=OM;break;case 8:g.depthTest=!1,g.depthFunc=kM;break}g.transparent=m,m&&(g.depthWrite=!1),TA(d),g.onUpdateUniforms();for(const y in u){const b=y,f=u[y].type;d[b]?.value===void 0&&(f===ZC.SAMPLER_2D?(d[b]={value:MA},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,u[y]))}ko&&console.log(g.uuid,d),JC(g),r(g)}):null}}function JC(o){if(o.uniforms){ko&&console.log("Uniforms:",o.uniforms);for(const t in o.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break;case"_map":e("map",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(o,t)||Object.defineProperty(o,t,{get:()=>o.uniforms[i].value,set:n=>{o.uniforms[i].value=n,o.needsUpdate=!0}})}}const aj=x("debugextensions");let Mm;const lj=import("./vendor-CdNldo8c.min.js").then(o=>o.index$2).then(async o=>(Mm=o.GLTFAnimationPointerExtension,Mm)).catch(o=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",o)}),xa=new Array;function cj(o){xa.includes(o)||xa.push(o)}function hj(o){const e=xa.indexOf(o);e>=0&&xa.splice(e,1)}function v0(o){if(o instanceof Zo){const e=new b0;return o.register(t=>(e.parser=t,e)),e}return null}class dj{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 Rm(o,e,t,i){const n=t.indexOf("?");n>=0&&(t=t.substring(0,n)),i||(i=t),(i.startsWith("blob:")||i.startsWith("data:"))&&console.debug("[GLTFLoader] Suspicious sourceId detected"),o.register(s=>new tj(s)),o.register(s=>new ZE(s)),o.register(s=>new fA(s,e.lightmaps,i)),o.register(s=>new ij(s,i,e)),o.register(s=>new rj(s,i)),o.register(s=>new Ar(s,i)),o.register(s=>new We(s)),o.register(s=>new QD(s)),o.register(s=>new Kg(s)),o.register(s=>new oj(e,o,t,s)),rS()&&o.register(s=>new Nc(s)),await lj.catch(s=>{}),o.register(s=>{if(Mm){const r=new Mm(s);return r.setAnimationPointerResolver.bind(r)(new dj),r}else return(aj||M())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const s of xa)s.onImport&&s.onImport(o,t,e)}function w0(o,e){for(const t of xa)t.onExport&&t.onExport(o,e)}function eP(o,e,t){for(const i of xa)i.onLoaded&&i.onLoaded(o,e,t)}const Dt=x("debuginstancing"),uj=Dt==="lods",x0=x("debugprogressive")==="colors"||uj;function S0(o,e,t,i){return o.lodsManager.manager?.trackLoadingPromise(e,t,i),i}function tP(o){return o.determinant()<0}class Ka{static instance=new Ka;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,s,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,s);if(a){n===null&&(n=[]),n.push(a);const l=a.object.material;Array.isArray(l)?l.forEach(c=>S0(i,"texture",c,We.assignTextureLOD(c,0))):S0(i,"texture",l,We.assignTextureLOD(l,0))}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const c of t.children)n=this.setup(e,c,i,n,s,l)}return r===0&&s.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return Dt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const s=e,r=s.geometry,a=s.material;if(Array.isArray(a))return null;s.updateWorldMatrix(!0,!1);const l=tP(s.matrixWorld);for(const u of this.objs)if(!!u.canAdd(r,a,l))return u.addInstance(s,r);let c=Ka.getStartInstanceCount(e);(!c||c<0)&&(c=4);let h=e.name;h?.length||(h=uw());const d=new Mr(h,r,a,c,t,l);return this.objs.push(d),d.addInstance(s,r)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(s,r)=>{const a=t(s,r);return(e[Mh]||i.equals(a)===!1)&&(i.copy(a),e[Mh]=!0),a};e.matrixWorld.multiplyMatrices=n}}class Ja{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.geometry.index?this.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;_geometry;get geometry(){return this._geometry}renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;currentMeshLOD;pendingMeshLOD;constructor(e,t,i=e.geometry){this.__instanceIndex=-1,this.object=e,this._geometry=i,this.renderer=t,this.currentMeshLOD=i.userData?.LODS?.level,e[dS]=t,this.meshInformation=Sa(e.geometry),Ja.all.push(this)}updateMeshInformation(){const e=Sa(this.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.assertMirroringUnchanged(),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}_didWarnAboutMirroringChange=!1;assertMirroringUnchanged(){this._didWarnAboutMirroringChange||tP(this.object.matrixWorld)!==this.renderer.mirrored&&(this._didWarnAboutMirroringChange=!0,console.warn(`[Instancing] "${this.name}" changed its mirroring at runtime (world matrix determinant flipped sign). Instanced objects can not change mirroring - this object will render its backfaces. Disable instancing for it via Renderer.setInstanced(obj, false).`))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;if(this._geometry!==e){const n=this.__instanceIndex>=0;return n&&this.renderer.remove(this,!1),this._geometry=e,this.updateMeshInformation(),n?this.renderer.add(this):!0}this._geometry=e;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((M()||Dt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),P.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),P.markAsInstancedRendered(this.object,!1),e)){const t=Ja.all.indexOf(this);t>=0&&Ja.all.splice(t,1)}}}class Mr{get batchedMesh(){return this._batchedMesh}get mirrored(){return this._mirrored}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(),Dt&&this._batchedMesh.boundingSphere){const i=Mr.debugBoundsSphere.copy(this._batchedMesh.boundingSphere).applyMatrix4(this._batchedMesh.matrixWorld);F.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_mirrored;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static instanceMatrix=new J;static lodProjectionScreenMatrix=new J;static debugBoundsSphere=new Xc;static debugLODColor=new oe;static lodSelectionResult={level:-1,primitiveIndex:0,screenCoverage:0,screenspaceVolume:new v,centrality:1};canAdd(e,t,i){return this._maxVertexCount>1e7||this._mirrored!==i||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,i,n,s,r=!1){this.name=e,this.geometry=t,this.material=i,this._context=s,this._mirrored=r,this._maxInstanceCount=Math.max(2,n),Dt&&(this._debugMaterial=iP(x0));const a=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=a.vertexCount,this._maxIndexCount=a.indexCount,this._batchedMesh=new $v(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this.applyBatchTransform(this._batchedMesh),this._batchedMesh[Rh]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof Nv&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),s.pre_render_callbacks.push(this.onBeforeRender),s.post_render_callbacks.push(this.onAfterRender),Dt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){Dt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e,t){const i=new Ja(e,this,t);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(i)}catch(n){if(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()})
1086
+ Binary:`,i)}else $e&&console.debug("Could not determine file type from binary data");return"unknown"}const u0=x("debugstencil");function FD(o,e){return(o&1<<e.layer)!=0}const BD=Symbol("stencils");class Ar{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(u0&&console.log(t,Ar.stencils),!t)return;const i=Ar.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];if(FD(s.layer,e)){u0&&console.log(s),setTimeout(()=>{Ni()&&Ap(e.gameObject)&&(ge("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let r=0;r<e.sharedMaterials.length;r++){let a=e.sharedMaterials[r];a&&(a=a.clone(),a[BD]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=s.value,a.stencilFunc=s.compareFunc,a.stencilZPass=s.passOp,a.stencilFail=s.failOp,a.stencilZFail=s.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=s.event*1e3+s.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[zD];if(i){u0&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const s of n){const r={...s};r.compareFunc=UD(r.compareFunc),r.passOp=p0(r.passOp),r.failOp=p0(r.failOp),r.zFailOp=p0(r.zFailOp),Ar.stencils[this.source]||(Ar.stencils[this.source]=[]),Ar.stencils[this.source].push(r)}}}return null}}function p0(o){switch(o){case 0:return wM;case 1:return vM;case 2:return _M;case 3:return bM;case 4:return yM;case 6:return fM;case 7:return gM;case 5:return mM}return 0}function UD(o){switch(o){case 1:return zv;case 2:return pM;case 3:return uM;case 4:return dM;case 5:return hM;case 6:return cM;case 7:return lM;case 8:return aM}return zv}const zD="NEEDLE_render_objects";class ND{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 i=this.meshToOwners.get(e);i||(i=new Set,this.meshToOwners.set(e,i)),i.add(t)}removeHook(e,t){const i=this.meshToOwners.get(e);i&&(i.delete(t),i.size===0&&this.meshToOwners.delete(e))}getOriginalCallbacks(e){return this.meshToOriginalCallbacks.get(e)}setOriginalCallbacks(e,t){this.meshToOriginalCallbacks.set(e,t)}}const rr=new ND;class Ls{_overrides=[];_defines={};_object=null;get object(){return this._object}constructor(e=null){this._object=e}static get(e){let t=rr.getBlock(e);return t||(t=new Ls(e),rr.setBlock(e,t),GD(e,t)),t}static hasOverrides(e){const t=rr.getBlock(e);return t?t.hasOverrides():!1}dispose(){this._object&&rr.deleteBlock(this._object),this._overrides=[],this._object=null}setOverride(e,t,i){const n=this._overrides.find(s=>s.name===e);n?(n.value=t,n.textureTransform=i):this._overrides.push({name:e,value:t,textureTransform:i})}getOverride(e){return this._overrides.find(t=>t.name===e)}removeOverride(e){const t=this._overrides.findIndex(i=>i.name===e);t>=0&&this._overrides.splice(t,1)}removeOveride(e){this.removeOverride(e)}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(){const e=[],t=Object.keys(this._defines).sort();for(const i of t){const n=this._defines[i];n!==void 0&&e.push(`d:${i}=${n}`)}for(const i of this._overrides){if(i.value===null)continue;let n="";if(i.value instanceof ke){if(n=i.value.uuid||"texture",i.textureTransform){const s=i.textureTransform;s.offset&&(n+=`;to:${s.offset.x},${s.offset.y}`),s.repeat&&(n+=`;tr:${s.repeat.x},${s.repeat.y}`)}}else if(Array.isArray(i.value))n=i.value.join(",");else if(i.value&&typeof i.value=="object"&&"r"in i.value){const s=i.value;n=`${s.r},${s.g},${s.b},${s.a!==void 0?s.a:""}`}else if(i.value&&typeof i.value=="object"&&"x"in i.value){const s=i.value;n=`${s.x},${s.y}${s.z!==void 0?`,${s.z}`:""}${s.w!==void 0?`,${s.w}`:""}`}else n=String(i.value);e.push(`${i.name}=${n}`)}return e.join(";")}}const vm=Symbol("originalValues"),wm=Symbol("savedTextureTransforms");function m0(o){let e=rr.getBlock(o);if(e)return{block:e,owner:o};if(o.parent&&o.parent.type==="Group"&&(e=rr.getBlock(o.parent),e))return{block:e,owner:o.parent}}const Yl=Symbol("beforeRenderingFlag"),g0=new WeakMap,f0=new WeakMap,$D=function(o,e,t,i){const n=m0(this)?.block;if(n&&n.hasOverrides()){const s=n.getOverride("transmission")?.value,r=n.getOverride("transparent")?.value;s!==void 0&&typeof s=="number"&&"transmission"in t&&s!==t.transmission&&(f0.set(this,t.transmission),t.transmission=s),r!==void 0&&typeof r=="boolean"&&r!==t.transparent&&(g0.set(this,t.transparent),t.transparent=r)}},WD=function(o,e,t,i){const n=g0.get(o);n!==void 0&&(g0.delete(o),t.transparent=n);const s=f0.get(o);s!==void 0&&(f0.delete(o),t.transmission=s)};let GC=!1;const VD=x("debugreflectionprobe"),HC=function(o,e,t,i,n,s){const r=this.material;if(!r)return;if(Array.isArray(r)){if(!r.includes(n))return}else if(r!==n)return;this[Yl]===void 0&&(this[Yl]=new WeakSet),this[Yl].add(n);const a=m0(this);if(!a)return;const{block:l,owner:c}=a,h=l.overrides,d=n,u=l.getDefines(),m=Object.keys(u);if(m.length>0){d.defines||(d.defines={});for(const b of m){const f=u[b];f!==void 0&&(d.defines[b]=f)}}if(h.length===0&&m.length===0)return;let g=m.length>0;d[vm]||(d[vm]=[]);const y=d[vm];for(const b of h){if(b.value===null)continue;if(d.isMeshBasicMaterial===!0&&(b.name==="envMap"||b.name==="envMapRotation"||b.name==="envMapIntensity")){b.name==="envMap"&&!GC&&(M()||VD)&&(GC=!0,console.warn(`MaterialPropertyBlock: Ignoring envMap override on MeshBasicMaterial (object: "${this.name}", material: "${n.name}"). Use a lit material such as MeshStandardMaterial if reflection probes are intended.`));continue}const f=d[b.name],_=y.find(w=>w.name===b.name);if(_?_.value=f:y.push({name:b.name,value:f}),!g&&!!f!=!!b.value&&(g=!0),d[b.name]=b.value,b.textureTransform&&b.value instanceof ke){const w=b.value;d[wm]||(d[wm]=[]),d[wm].push({name:b.name,offsetX:w.offset.x,offsetY:w.offset.y,repeatX:w.repeat.x,repeatY:w.repeat.y});const S=b.textureTransform;S.offset&&w.offset.copy(S.offset),S.repeat&&w.repeat.copy(S.repeat)}}g&&(d.needsUpdate=!0),d._forceRefresh=!0},qC=function(o,e,t,i,n,s){if(this[Yl]===void 0||!this[Yl].has(n))return;this[Yl].delete(n);const r=m0(this);if(!r)return;const{block:a,owner:l}=r,c=a.overrides,h=n,d=h[vm],u=a.getDefines(),m=Object.keys(u);let g=!1;if(m.length>0&&h.defines){for(const b of m)delete h.defines[b];g=!0}if(c.length===0){g&&(h.needsUpdate=!0,h._forceRefresh=!0);return}if(!d)return;const y=h[wm];if(y&&y.length>0){for(const b of y){const f=c.find(_=>_.name===b.name);f?.value instanceof ke&&(f.value.offset.set(b.offsetX,b.offsetY),f.value.repeat.set(b.repeatX,b.repeatY))}y.length=0}for(const b of c){const f=d.find(_=>_.name===b.name);f&&(!g&&!!b.value!=!!f.value&&(g=!0),h[b.name]=f.value)}g&&(h.needsUpdate=!0),h._forceRefresh=!0};function GD(o,e){o.type==="Group"?o.children.forEach(t=>{(t.type==="Mesh"||t.type==="SkinnedMesh")&&XC(t,o,e)}):(o.type==="Mesh"||o.type==="SkinnedMesh")&&XC(o,o,e)}function XC(o,e,t){if(!rr.isHooked(o,e)){if(rr.addHook(o,e),o["needle:materialPropertyBlock"]=t,!o.onBeforeRender)o.onBeforeRender=HC;else{const i=o.onBeforeRender;o.onBeforeRender=function(n,s,r,a,l,c){i.call(this,n,s,r,a,l,c),HC.call(this,n,s,r,a,l,c)}}if(!o.onAfterRender)o.onAfterRender=qC;else{const i=o.onAfterRender;o.onAfterRender=function(n,s,r,a,l,c){qC.call(this,n,s,r,a,l,c),i.call(this,n,s,r,a,l,c)}}o.onBeforeRenderListPush=$D,o.onAfterRenderListPush=WD}}var HD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,xm=(o,e,t,i)=>{for(var n=i>1?void 0:i?qD(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&HD(e,t,n),n};const Kl=x("debugreflectionprobe"),QC=x("noreflectionprobe");let wa=null;const XD=Symbol("reflectionProbeKey"),ld=class io extends T{static _probes=new Map;static testBox=new ri;static isUsingReflectionProbe(e){return!!e[XD]}static onEnabled=new re;static onDisabled=new re;static get(e,t,i,n){if(!e||e.isObject3D!==!0||QC)return null;const s=io._probes.get(t);if(s){for(const r of s)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return Kl&&console.log("Found reflection probe",e.name,r.name),r}}return Kl&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;_textureUrlInFlight;set texture(e){if(this._texture!==e){if(typeof e=="string"){Kl&&console.debug(`[ReflectionProbe] Loading reflection probe texture from URL: ${e}`),this._textureUrlInFlight=e;const t=ao(this.sourceId,e);id(t,this.context.renderer).then(i=>{this._textureUrlInFlight===e&&i&&(this._textureUrlInFlight=void 0,Kl&&console.debug(`[ReflectionProbe] Successfully loaded reflection probe texture: ${e}`),this.texture=i)});return}this.__didAwake&&(this._textureUrlInFlight=void 0),this._texture=e,Kl&&console.debug("[ReflectionProbe] Set reflection probe texture "+(e?.name||"(removed)")),e&&(e instanceof ff||e.mapping===ln||e.mapping!==Qo&&(e.mapping=Qo),e.colorSpace=Xo,e.needsUpdate=!0)}}get texture(){return this._texture}intensity=1;center=new v;size=new v(1,1,1);__lightmapIntensityScale=!0;isInBox(e){return wa??=new ri,wa.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),Si([e],void 0,void 0,io.testBox),io.testBox.isEmpty()?wa.containsPoint(e.worldPosition):wa?.intersectsBox(io.testBox)}constructor(){super(),io._probes.has(this.context)||io._probes.set(this.context,[]),io._probes.get(this.context)?.push(this)}awake(){this._texture&&(this._texture.mapping!==ln&&(this._texture.mapping=Qo),this._texture.colorSpace=Xo,this._texture.needsUpdate=!0)}update(){Kl&&(wa??=new ri,wa.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),F.DrawWireBox3(wa,5592320))}onEnable(){io.onEnabled?.invoke(this)}onDisable(){io.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(){const e=io._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}apply(e){if(QC||!this.enabled||!this.texture)return;const t=Ls.get(e);t.setOverride("envMap",this.texture),t.setOverride("envMapRotation",this.gameObject.rotation);let i=this.intensity;this.__lightmapIntensityScale&&t.getOverride("lightMap")&&(i/=Math.PI),t.setOverride("envMapIntensity",i)}unapply(e){const t=Ls.get(e);t&&t.getOverride("envMap")?.value===this.texture&&(t.removeOverride("envMap"),t.removeOverride("envMapRotation"),t.removeOverride("envMapIntensity"))}};xm([p([ke,String])],ld.prototype,"texture",1),xm([p()],ld.prototype,"intensity",2),xm([p(v)],ld.prototype,"center",2),xm([p(v)],ld.prototype,"size",2);let ps=ld;const y0=x("debugexr");class QD{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,y0&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,n=i.json.textures[e];if(y0&&console.log("EXT_texture_exr.loadTexture",e,n),!n.extensions||!n.extensions[t])return null;const s=n.extensions[t],r=new xf(i.options.manager);return y0&&console.log("EXT_texture_exr.loadTexture",s),i.loadTextureImage(e,s.source,r)}}typeof window<"u"&&window.addEventListener("unhandledrejection",o=>{});const Po=Rt,Sm="$___Export_Components",YD="NEEDLE_components";class KD{[Gr]}class ZD{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class b0{get name(){return YD}exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{if("serializeUserData"in t){const i=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,s)=>{try{this.serializeUserData(n,s)&&(t.extensionsUsed[this.name]=!0),i(n,s)}finally{this.afterSerializeUserData(n,s)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){const i=e.userData?.components;return!i||i.length<=0?!1:(delete e.userData.components,e[Sm]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Po&&console.log("DONE",JSON.stringify(t)),e[Sm]===void 0)return;const i=e[Sm];delete e[Sm],i!==null&&(e.userData.components=i)}writeNode(e,t){Po&&console.log(e.name,e.uuid);const i=new ZD(e,-1,t);this.exportContext[e.uuid]=i}afterParse(e){Po&&console.log("AFTER",e);const t=this.writer?.nodeMap;if(t)for(const[n,s]of t)this.objectToNodeMap[n.uuid]=s;for(const n in this.exportContext){const s=this.exportContext[n],r=s.node,a=s.nodeDef,l=t?.get(r)??s.nodeIndex;l===void 0||l<0||this.writeComponentsIntoDef(r,a,l)}const i=this.writer?.json?.scenes;if(i){const n=Array.isArray(e)?e:[e];let s=0;for(const r of n)if(r?.isScene===!0){if(s>=i.length)break;this.writeComponentsIntoDef(r,i[s]),s++}}}writeComponentsIntoDef(e,t,i){const n=e.userData?.components;if(!n||n.length<=0)return;this.context.object=e,this.context.nodeId=i,this.context.objectToNode=this.objectToNodeMap;const s=[];for(const r of n){this.context.target=r;const a=is().writeBuiltinComponentData(r,this.context);a!==null&&s.push(a)}if(s.length>0){const r=new KD;r[Gr]=s,t.extensions=t.extensions||{},t.extensions[this.name]=r,Po&&console.log("DID WRITE",e,i!==void 0?`nodeIndex ${i}`:"(scene)",s)}}parser;nodeToObjectMap={};gltf=null;beforeRoot(){return Po&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;const t=e.parser,i=t?.extensions;if(!i)return;const n=i[this.name];Po&&console.log("After root",e,this.parser,i);const s=[];if(n===!0){const r=t.json.nodes;if(r){for(let l=0;l<r.length;l++){const c=await t.getDependency("node",l);this.nodeToObjectMap[l]=c}for(let l=0;l<r.length;l++){const c=r[l],h=l,d=c.extensions;if(!d)continue;const u=d[this.name];if(!u)continue;Po&&console.log("NODE",c);const m=this.nodeToObjectMap[h];if(!m){console.error("Could not find object for node index: "+h,c,t);continue}Eh(m),s.push(this.createComponents(e,c,m,u))}}const a=t.json.scenes;if(a)for(let l=0;l<a.length;l++){const c=a[l],h=c?.extensions?.[this.name];if(!h)continue;const d=await t.getDependency("scene",l);if(!d){console.error("Could not find scene for index: "+l,c,t);continue}Eh(d),s.push(this.createComponents(e,c,d,h))}}await Promise.all(s);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;YE(r,l)}}}async createComponents(e,t,i,n){if(!n)return;const s=n[Gr];if(s){const r=new Array;Po&&console.log(i.name,s);for(const a in s){const l=s[a];if(Po&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),(l?.name==="MeshRenderer"||l?.name==="SkinnedMeshRenderer")&&!l.sharedMaterials){let c=!1;if("mesh"in t){const h=t.mesh;if(typeof h=="number"&&e.parser){const d=e.parser.json.meshes?.[h];d?.primitives&&(l.sharedMaterials=d.primitives.map(u=>"/materials/"+(u.material??0)),c=!0)}}!c&&(Po||M())&&console.warn(`[NEEDLE_components] Component '${l.name}' on object '${i.name}' is not added to a mesh or failed to retrieve materials from glTF.`)}l&&this.parser&&r.push(wy(this.parser,l).catch(c=>console.error(`Error while resolving references (see console for details)
1087
+ `,c,i,l))),i.userData=i.userData||{},i.userData[Gr]=i.userData[Gr]||[],i.userData[Gr].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const YC="NEEDLE_gameobject_data",JD={Default:0,"Ignore Raycast":2},Cm=new Map,_0=8,Pm=31;function ej(o){if(typeof o=="number"&&isFinite(o))return o;if(typeof o=="string"&&o.length>0){const e=JD[o];if(e!==void 0)return e;let t=Cm.get(o);return t===void 0&&(t=Math.min(_0+Cm.size,Pm),_0+Cm.size>Pm&&console.warn(`[NEEDLE_gameobject_data] more than ${Pm-_0+1} named layers \u2014 "${o}" shares index ${Pm}`),Cm.set(o,t)),t}return 0}class tj{get name(){return YC}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const s=n.extensions[YC];if(s){const r=this.findAndApplyExtensionData(i,s);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(ej(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}}const KC="NEEDLE_lighting_settings",Zl=x("debugenvlight");class ij{get name(){return KC}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[KC];if(i){Zl&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const s=e.scene.children[0];n=P.addComponent(s,km,{},{callAwake:!1})}else{const s=new R;s.name="LightSettings "+this.sourceId,e.scene.add(s),n=P.addComponent(s,km,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new oe().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(s=>new oe().fromArray(s))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}ce.registerCallback(de.ContextCreated,o=>{const e=o.context,t=P.findObjectOfType(km,e);t?.sourceId&&(t.enabled=!0)});class km extends T{ambientMode=Cl.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=mp.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===mp.Skybox?fo.Skybox:fo.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),Zl&&window.addEventListener("keydown",t=>{this.destroyed||t.key==="l"&&(this.enabled=!this.enabled)});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*j.lerp(0,1.33,t)}onEnable(){if(Zl&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Cl.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new xM(this.ambientLight,this.ambientIntensity*e),Zl&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Cl.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new SM(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),Zl&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,i)}}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(){Zl&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}var Om;(o=>{async function e(t,i){if(!t)throw new Error("URL or XML string is required to load a MaterialX material");const n=await A.MaterialX.load(),s=t.trimStart().startsWith("<"),r=s?t:await fetch(t).then(c=>c.text()).catch(console.error);if(!r)return console.warn("Failed to load MaterialX file from url",t),null;let a;if(i?.url||!s){const c=(i?.url||t).split("/");c.pop(),a=c.join("/")}const l=new jr;return n.Experimental_API.createMaterialXMaterial(r,i?.materialNameOrIndex??0,{getTexture:async c=>(!c.startsWith("http")&&!c.startsWith("data:")&&!c.startsWith("blob:")&&!c.startsWith("file:")&&a&&(c=a+"/"+c),l.loadAsync(c).catch(h=>{console.warn(`Failed to load texture for MaterialX material ${c}`,h)}))},{cacheKey:t})}o.loadFromUrl=e})(Om||(Om={}));class nj extends CM{loadAsync(e,t){return new Promise((i,n)=>{this.load(e,i,t,n)})}load(e,t,i,n){i?.({type:"progress",loaded:0,total:0}),Om.loadFromUrl(e,{}).then(s=>{s?t(this.onLoaded(s)):n?.(new Error("Failed to load MaterialX material from url: "+e))})}onLoaded(e){return Gs.createPrimitive("ShaderBall",{material:e})}}class oj{constructor(e,t,i,n){this.context=e,this.url=i,this.parser=n}context;url;parser;get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const e=await A.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(t){console.error(t)}}}loadMaterial(e){return this.mtlxLoader?this.mtlxLoader.loadMaterial(e):null}}var ZC=(o=>(o[o.INT=5124]="INT",o[o.FLOAT=5126]="FLOAT",o[o.FLOAT_VEC2=35664]="FLOAT_VEC2",o[o.FLOAT_VEC3=35665]="FLOAT_VEC3",o[o.FLOAT_VEC4=35666]="FLOAT_VEC4",o[o.INT_VEC2=35667]="INT_VEC2",o[o.INT_VEC3=35668]="INT_VEC3",o[o.INT_VEC4=35669]="INT_VEC4",o[o.BOOL=35670]="BOOL",o[o.BOOL_VEC2=35671]="BOOL_VEC2",o[o.BOOL_VEC3=35672]="BOOL_VEC3",o[o.BOOL_VEC4=35673]="BOOL_VEC4",o[o.FLOAT_MAT2=35674]="FLOAT_MAT2",o[o.FLOAT_MAT3=35675]="FLOAT_MAT3",o[o.FLOAT_MAT4=35676]="FLOAT_MAT4",o[o.SAMPLER_2D=35678]="SAMPLER_2D",o[o.SAMPLER_3D=35680]="SAMPLER_3D",o[o.SAMPLER_CUBE=35681]="SAMPLER_CUBE",o[o.UNKNOWN=0]="UNKNOWN",o))(ZC||{});const ko=x("debugcustomshader"),Jl="NEEDLE_techniques_webgl";class sj{objectToWorldMatrix=new J;worldToObjectMatrix=new J;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),pp(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),pp(this.worldToObjectMatrix,this.worldToObject)}}class ze extends Nv{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return JC(e),e}constructor(e,...t){super(...t),this.identifier=e,ko&&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)&&Q.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=Q.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&Q.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new J;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new J;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new v;static _mainLightColor=new ve;static _mainLightPosition=new v;static _lightData=new ve;_rendererData=new sj;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&Q.Current.setRequireColor(!0),this.depthTextureUniform&&Q.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,s,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,s)}onUpdateUniforms(e,t){const i=Q.Current;if(e&&(ze.viewProjection&&this.uniforms[this._viewProjectionName]&&(ze.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),pp(ze.viewProjection,ze._viewProjectionValues)),ze.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ze.viewMatrix.copy(e.matrixWorldInverse),pp(ze.viewMatrix,ze._viewMatrixValues)),this.uniforms[ze._worldSpaceCameraPosName]&&ze._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=i.sceneLighting.timeVec4.x/20,a.y=i.sceneLighting.timeVec4.x,a.z=i.sceneLighting.timeVec4.x*2,a.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(i.sceneLighting.timeVec4.x/8),a.y=Math.sin(i.sceneLighting.timeVec4.x/4),a.z=Math.sin(i.sceneLighting.timeVec4.x/2),a.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(i.sceneLighting.timeVec4.x/8),a.y=Math.cos(i.sceneLighting.timeVec4.x/4),a.z=Math.cos(i.sceneLighting.timeVec4.x/2),a.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=i.time.deltaTime,a.y=1/i.time.deltaTime,a.z=i.time.smoothedDeltaTime,a.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const a=le(n.gameObject,ze._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ze._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ze._mainLightColor};const l=n.intensity;ze._lightData.z=l,this.uniforms.unity_LightData={value:ze._lightData}}if(e&&(ze.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ze._viewProjectionValues),ze.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ze._viewMatrixValues),this.uniforms[ze._worldSpaceCameraPosName]&&(this.uniforms[ze._worldSpaceCameraPosName]={value:ze._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const s=this.depthTextureUniform;s&&(s.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class rj{get name(){return Jl}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return ko&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Jl])return ko&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;ko&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Jl].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Jl];if(!n)return ko?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;ko&&console.log(n);const s=n.techniques[i];return s?new Promise(async(r,a)=>{const l=await AA(n,s.program),c=l?.fragmentShader,h=l?.vertexShader;if(!c||!h)return a();ko&&console.log("loadMaterial",t,l);const d={},u=s.uniforms;(h.includes("_Time")||c.includes("_Time"))&&(d._Time={value:new ve(0,0,0,0)}),(h.includes("_SinTime")||c.includes("_SinTime"))&&(d._SinTime={value:new ve(0,0,0,0)}),(h.includes("_CosTime")||c.includes("_CosTime"))&&(d._CosTime={value:new ve(0,0,0,0)}),(h.includes("unity_DeltaTime")||c.includes("unity_DeltaTime"))&&(d.unity_DeltaTime={value:new ve(0,0,0,0)});for(const y in u){const b=y;switch(b){case"_TimeParameters":const f=new ve;d[b]={value:f};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":d[b]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":d[b]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":d[b]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":d[b]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":d[b]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Jl]){const y=t.extensions[Jl];if(y.technique===i){ko&&console.log(t.name,"Material Properties",y);for(const b in y.values){const f=y.values[b];if(typeof f=="string"){if(f.startsWith("/textures/")){const _=f.substring(10),w=Number.parseInt(_);if(w>=0){const S=await this.parser.getDependency("texture",w);S instanceof ke&&(S.colorSpace=Xo,S.needsUpdate=!0),d[b]={value:S};continue}}if(b==="alphaMode"){f==="BLEND"&&(m=!0);continue}}if(Array.isArray(f)&&f.length===4){d[b]={value:new ve(f[0],f[1],f[2],f[3])};continue}d[b]={value:f}}}}const g=new ze(this.identifier,{name:t.name??"",uniforms:d,vertexShader:h,fragmentShader:c,lights:!1});switch(g.glslVersion=PM,g.vertexShader=g.vertexShader.replace("#version 300 es",""),g.fragmentShader=g.fragmentShader.replace("#version 300 es",""),d._Cull?.value){case 0:g.side=Bi;break;case 1:g.side=wu;break;case 2:g.side=Us;break;default:g.side=Us;break}switch(d._ZTest?.value){case 3:g.depthTest=!0,g.depthFunc=AM;break;case 6:g.depthTest=!0,g.depthFunc=EM;break;case 2:g.depthTest=!0,g.depthFunc=TM;break;case 4:g.depthTest=!0,g.depthFunc=RM;break;case 5:g.depthTest=!0,g.depthFunc=MM;break;case 7:g.depthTest=!0,g.depthFunc=OM;break;case 8:g.depthTest=!1,g.depthFunc=kM;break}g.transparent=m,m&&(g.depthWrite=!1),TA(d),g.onUpdateUniforms();for(const y in u){const b=y,f=u[y].type;d[b]?.value===void 0&&(f===ZC.SAMPLER_2D?(d[b]={value:MA},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,u[y]))}ko&&console.log(g.uuid,d),JC(g),r(g)}):null}}function JC(o){if(o.uniforms){ko&&console.log("Uniforms:",o.uniforms);for(const t in o.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break;case"_map":e("map",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(o,t)||Object.defineProperty(o,t,{get:()=>o.uniforms[i].value,set:n=>{o.uniforms[i].value=n,o.needsUpdate=!0}})}}const aj=x("debugextensions");let Mm;const lj=import("./vendor-T07c_9f_.min.js").then(o=>o.index$2).then(async o=>(Mm=o.GLTFAnimationPointerExtension,Mm)).catch(o=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",o)}),xa=new Array;function cj(o){xa.includes(o)||xa.push(o)}function hj(o){const e=xa.indexOf(o);e>=0&&xa.splice(e,1)}function v0(o){if(o instanceof Zo){const e=new b0;return o.register(t=>(e.parser=t,e)),e}return null}class dj{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 Rm(o,e,t,i){const n=t.indexOf("?");n>=0&&(t=t.substring(0,n)),i||(i=t),(i.startsWith("blob:")||i.startsWith("data:"))&&console.debug("[GLTFLoader] Suspicious sourceId detected"),o.register(s=>new tj(s)),o.register(s=>new ZE(s)),o.register(s=>new fA(s,e.lightmaps,i)),o.register(s=>new ij(s,i,e)),o.register(s=>new rj(s,i)),o.register(s=>new Ar(s,i)),o.register(s=>new We(s)),o.register(s=>new QD(s)),o.register(s=>new Kg(s)),o.register(s=>new oj(e,o,t,s)),rS()&&o.register(s=>new Nc(s)),await lj.catch(s=>{}),o.register(s=>{if(Mm){const r=new Mm(s);return r.setAnimationPointerResolver.bind(r)(new dj),r}else return(aj||M())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const s of xa)s.onImport&&s.onImport(o,t,e)}function w0(o,e){for(const t of xa)t.onExport&&t.onExport(o,e)}function eP(o,e,t){for(const i of xa)i.onLoaded&&i.onLoaded(o,e,t)}const Dt=x("debuginstancing"),uj=Dt==="lods",x0=x("debugprogressive")==="colors"||uj;function S0(o,e,t,i){return o.lodsManager.manager?.trackLoadingPromise(e,t,i),i}function tP(o){return o.determinant()<0}class Ka{static instance=new Ka;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,s,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,s);if(a){n===null&&(n=[]),n.push(a);const l=a.object.material;Array.isArray(l)?l.forEach(c=>S0(i,"texture",c,We.assignTextureLOD(c,0))):S0(i,"texture",l,We.assignTextureLOD(l,0))}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const c of t.children)n=this.setup(e,c,i,n,s,l)}return r===0&&s.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return Dt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const s=e,r=s.geometry,a=s.material;if(Array.isArray(a))return null;s.updateWorldMatrix(!0,!1);const l=tP(s.matrixWorld);for(const u of this.objs)if(!!u.canAdd(r,a,l))return u.addInstance(s,r);let c=Ka.getStartInstanceCount(e);(!c||c<0)&&(c=4);let h=e.name;h?.length||(h=uw());const d=new Mr(h,r,a,c,t,l);return this.objs.push(d),d.addInstance(s,r)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(s,r)=>{const a=t(s,r);return(e[Mh]||i.equals(a)===!1)&&(i.copy(a),e[Mh]=!0),a};e.matrixWorld.multiplyMatrices=n}}class Ja{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.geometry.index?this.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;_geometry;get geometry(){return this._geometry}renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;currentMeshLOD;pendingMeshLOD;constructor(e,t,i=e.geometry){this.__instanceIndex=-1,this.object=e,this._geometry=i,this.renderer=t,this.currentMeshLOD=i.userData?.LODS?.level,e[dS]=t,this.meshInformation=Sa(e.geometry),Ja.all.push(this)}updateMeshInformation(){const e=Sa(this.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.assertMirroringUnchanged(),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}_didWarnAboutMirroringChange=!1;assertMirroringUnchanged(){this._didWarnAboutMirroringChange||tP(this.object.matrixWorld)!==this.renderer.mirrored&&(this._didWarnAboutMirroringChange=!0,console.warn(`[Instancing] "${this.name}" changed its mirroring at runtime (world matrix determinant flipped sign). Instanced objects can not change mirroring - this object will render its backfaces. Disable instancing for it via Renderer.setInstanced(obj, false).`))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;if(this._geometry!==e){const n=this.__instanceIndex>=0;return n&&this.renderer.remove(this,!1),this._geometry=e,this.updateMeshInformation(),n?this.renderer.add(this):!0}this._geometry=e;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((M()||Dt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),P.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),P.markAsInstancedRendered(this.object,!1),e)){const t=Ja.all.indexOf(this);t>=0&&Ja.all.splice(t,1)}}}class Mr{get batchedMesh(){return this._batchedMesh}get mirrored(){return this._mirrored}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(),Dt&&this._batchedMesh.boundingSphere){const i=Mr.debugBoundsSphere.copy(this._batchedMesh.boundingSphere).applyMatrix4(this._batchedMesh.matrixWorld);F.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_mirrored;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static instanceMatrix=new J;static lodProjectionScreenMatrix=new J;static debugBoundsSphere=new Xc;static debugLODColor=new oe;static lodSelectionResult={level:-1,primitiveIndex:0,screenCoverage:0,screenspaceVolume:new v,centrality:1};canAdd(e,t,i){return this._maxVertexCount>1e7||this._mirrored!==i||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,i,n,s,r=!1){this.name=e,this.geometry=t,this.material=i,this._context=s,this._mirrored=r,this._maxInstanceCount=Math.max(2,n),Dt&&(this._debugMaterial=iP(x0));const a=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=a.vertexCount,this._maxIndexCount=a.indexCount,this._batchedMesh=new $v(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this.applyBatchTransform(this._batchedMesh),this._batchedMesh[Rh]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof Nv&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),s.pre_render_callbacks.push(this.onBeforeRender),s.post_render_callbacks.push(this.onAfterRender),Dt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){Dt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e,t){const i=new Ja(e,this,t);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(i)}catch(n){if(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()})
1088
1088
  `,n),M()){ul("Failed instancing mesh. See the browser console for details.");debugger}return null}return i}add(e){const t=e.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-=1),this._currentInstanceCount<=0&&(this._batchedMesh.visible=!1),this.markNeedsUpdate()))}updateInstance(e,t){this.setInstanceMatrix(t,e),this.markNeedsUpdate()}applyBatchTransform(e){this._mirrored&&e.scale.z!==-1&&(e.scale.z=-1,e.updateMatrixWorld())}setInstanceMatrix(e,t){if(!this._mirrored){this._batchedMesh.setMatrixAt(e,t);return}const i=Mr.instanceMatrix.copy(t),n=i.elements;n[2]=-n[2],n[6]=-n[6],n[10]=-n[10],n[14]=-n[14],this._batchedMesh.setMatrixAt(e,i)}updateGeometry(e,t){return this.validateGeometry(e)?(this.mustGrow()&&this.grow(e),Dt&&console.debug("[Instancing] UPDATE GEOMETRY at "+t,this._batchedMesh._geometryCount,e.name,Sa(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.updateProgressiveMeshLODs(),this._batchedMesh.layers.enableAll(),this._needUpdateBounds&&this._batchedMesh[Rh]===!0&&(Dt==="verbose"&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())};updateProgressiveMeshLODs(){const e=this._context.mainCamera;if(!e)return;Mr.lodProjectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const t=this._context.lodsManager?.targetTriangleDensity??2e5,i=this._handles.length;for(let n=0;n<i;n++){const s=this._handles[n];if(!s||s.__instanceIndex<0)continue;const r=this.calculateProgressiveMeshLOD(s,t);r<0||s.currentMeshLOD===r||s.pendingMeshLOD===r||this.assignProgressiveMeshLOD(s,r)}}assignProgressiveMeshLOD(e,t){const i=e.geometry;e.pendingMeshLOD=t;const n=We.assignMeshLOD(e.object,t,{apply:s=>this.shouldApplyProgressiveMeshLOD(e,t)&&(i===s||e.setGeometry(s))?(e.object.geometry=s,e.currentMeshLOD=t,this.updateDebugLODColor(e),!0):!1});S0(this._context,"mesh",e.object,n).catch(s=>{(Dt||M())&&console.warn(`Failed loading instanced mesh LOD ${t} for ${e.name}`,s)}).finally(()=>{e.pendingMeshLOD===t&&(e.pendingMeshLOD=void 0)})}shouldApplyProgressiveMeshLOD(e,t){if(e.__instanceIndex<0)return!1;if(e.pendingMeshLOD===t)return!0;const i=e.currentMeshLOD??e.geometry.userData?.LODS?.level??1/0;if(t>=i)return!1;const n=e.pendingMeshLOD;return typeof n=="number"&&t>=n}calculateProgressiveMeshLOD(e,t){e.object.matrixWorldNeedsUpdate&&e.object.updateWorldMatrix(!0,!1);const i=this._context.mainCamera;return i?qM({geometry:e.geometry,matrixWorld:e.object.matrixWorld,camera:i,projectionScreenMatrix:Mr.lodProjectionScreenMatrix,desiredDensity:t,canvasHeight:this._context.renderer.domElement.clientHeight||this._context.renderer.domElement.height,currentLevel:e.currentMeshLOD??-1,target:Mr.lodSelectionResult}).level:-1}onAfterRender=()=>{this._batchedMesh.layers.disableAll()};validateGeometry(e){const t=this.geometry;for(const i in e.attributes)if(i!=="batchId"&&!t.hasAttribute(i))return M()&&console.warn(`BatchedMesh: Added geometry has extra "${i}" attribute. All geometries must have consistent attributes.`),!1;for(const i in t.attributes)if(i!=="batchId"&&!e.hasAttribute(i))return M()&&console.warn(`BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`),!1;return!0}markNeedsUpdate(){Dt==="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;const t=Sa(e),i=t.vertexCount,n=t.indexCount;return this._currentVertexCount+i>this._maxVertexCount||this._currentIndexCount+n>this._maxIndexCount}_growId=0;grow(e){const t=++this._growId,i=this.count>=this._maxInstanceCount?Math.ceil(this._maxInstanceCount*2):this._maxInstanceCount,n=this.tryEstimateVertexCountSize(i,[e]),s=1.25,r=Math.max(this._maxVertexCount,Math.ceil(n.vertexCount*s)),a=Math.max(this._maxIndexCount,Math.ceil(n.indexCount*s));if(Dt){const h=Sa(e);console.warn(`[Instancing] Growing Buffer
1089
1089
  Mesh: "${this.name}${e.name?.length?"/"+e.name:""}" (${h.vertexCount.toLocaleString()} vertices, ${h.indexCount.toLocaleString()} indices)
1090
1090
  Max count ${this._maxInstanceCount.toLocaleString()} \u2192 ${i.toLocaleString()}
@@ -1137,7 +1137,7 @@ Texture:`,i),this.setLightmapDebugMaterial()):Tm&&console.log("Use debuglightmap
1137
1137
  gl_FragColor = lightMapTexel;
1138
1138
  gl_FragColor.a = 1.;
1139
1139
  }
1140
- `,defines:{USE_LIGHTMAP:""}})}}var pj=Object.defineProperty,ms=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&pj(e,t,n),n};const ec=x("debugrenderer"),oP=x("debugskinnedmesh"),sP=x("noinstancing"),mj=x("wireframe");var rP=(o=>(o[o.Off=0]="Off",o[o.BlendProbes=1]="BlendProbes",o[o.BlendProbesAndSkybox=2]="BlendProbesAndSkybox",o[o.Simple=3]="Simple",o))(rP||{});class aP{path=null;asset=null;default}class gj{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&ec&&console.warn("SharedMaterials have changed: "+this._renderer.name),this._changed=e}is(e){return this._renderer===e}constructor(e,t){this._renderer=e;const i=this.setMaterial.bind(this),n=this.getMaterial.bind(this),s=e.gameObject;if(this._targets=[],s)switch(s.type){case"Group":this._targets=[...s.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(s);break}let r=!1,a,l=0;for(let c=0;c<this._targets.length;c++){const h=this._targets[c];if(!h)continue;const d=h.material;if(d){d.shadowSide=d.side;for(let u=0;u<t.length;u++){const m=t[u];if(!m){r=!0;continue}if(d.name===m.name){a===void 0&&(a=new Map),a.set(u,c),l=Math.max(l,u);break}}}}if(r){this._indexMapMaxIndex=l,this._indexMap=a;const c=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(c),Ni()&&ge("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(c,h){if(typeof h=="string"){const d=parseInt(h);if(!isNaN(d))return n(d)}return c[h]},set(c,h,d){return typeof h=="string"&&i(d,Number.parseInt(h)),Reflect.set(c,h,d)?(d instanceof ke&&(c.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const 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;const i=this._targets[t];!i||i.material===void 0||(i.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const i=t[e];return i?i.material:null}}const Oo=class su extends T{static setInstanced(e,t){const i=Dh(e,su);return i.enableInstancing=t,i.setInstancingEnabled(t),i}static isInstanced(e){const t=ls(e,su);return t?t.isInstancingActive:Mn.isUsingInstancing(e)}static setVisible(e,t){So(e,t)}receiveShadows=!1;shadowCastingMode=0;lightmapIndex=-1;lightmapScaleOffset=new ve(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(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.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.isOwnSubmesh(e)&&this._sharedMeshes.push(e);else this.isMeshOrSkinnedMesh(this.gameObject)&&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 i=0;i<this._sharedMaterials.length;i++){const n=i<e.length?e[i]:null;n&&n instanceof ke?this.sharedMaterials[i]=n:t||(t=!0,console.warn("Can not assign null as material: "+this.name,n))}}}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._originalMaterials=[]),this._sharedMaterials=new gj(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return sP}_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(const 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,ec&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&ec&&this.probeAnchor.add(new Ui(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const i=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(i)||P.getComponent(i,su))){if(this.renderOrder.length<=e){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+e,"ChildElement:",i);continue}i.renderOrder=this.renderOrder[e],e+=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(),mj)for(let e=0;e<this.sharedMaterials.length;e++){const t=this.sharedMaterials[e];t&&(t.wireframe=!0)}}applyLightmapping(){if(this.lightmapIndex>=0&&!this._lightmaps){const e=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(e){this._lightmaps||(this._lightmaps=[]);const t=new C0(this);t.init(this.lightmapIndex,this.lightmapScaleOffset,e),this._lightmaps.push(t)}else ec&&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(const e of this._handles)this._handlesTempArray.push(e);return this._handlesTempArray}_handlesTempArray=[];setInstancingEnabled(e){if(this._isInstancingEnabled===e){if(!e||this._handles&&this._handles.length>0)return!0}else this._isInstancingEnabled=e;if(e){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this._handles===void 0||this._handles===null){if(this._handles=Ka.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return P.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return P.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this._handles)for(const t of this._handles)t.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this._handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!sP&&(this.setInstancingEnabled(!0),Mn.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(e=>e)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe(),ps.onEnabled.addEventListener(this.onReflectionProbeEnabled),ps.onDisabled.addEventListener(this.onReflectionProbeDisabled)}onDisable(){this.setVisibility(!1),ps.onEnabled.removeEventListener(this.onReflectionProbeEnabled),ps.onDisabled.removeEventListener(this.onReflectionProbeDisabled),this._handles&&this._handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this._handles=null,this.isMultiMaterialObject(this.gameObject))for(const 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()),ec==this.name&&this.gameObject instanceof V){this.gameObject.geometry.computeBoundingSphere();const e=U(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);F.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(const 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[Mh]===!0){this.gameObject[Mh]=!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&&P.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];So(t.object,!1)}if(this.reflectionProbeUsage!==0&&this._reflectionProbe?this._reflectionProbe.apply(this.gameObject):this.reflectionProbeUsage===0&&this._reflectionProbe&&this._reflectionProbe.unapply(this.gameObject),this._sharedMaterials)for(const e of this._sharedMaterials)e&&"envMap"in e&&"envMapIntensity"in e&&!ps.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment,e.envMapRotation=this.context.scene.environmentRotation);else ec&&console.warn("[Renderer] sharedMaterials not initialized yet: "+this.name)}}onBeforeRenderThree=(e,t,i,n,s,r)=>{if(s.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=this.context.scene.environmentIntensity;s.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(s),a.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];So(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(){Ar.applyStencil(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){this._reflectionProbe=null,this.reflectionProbeUsage!==0&&(this.startCoroutine(this._updateReflectionProbe(),Ee.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=ps.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))So(this.gameObject,e);else for(const t of this.gameObject.children)this.isOwnSubmesh(t)&&So(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}isOwnSubmesh(e){return this.isMeshOrSkinnedMesh(e)&&!ls(e,su)}};ms([p()],Oo.prototype,"receiveShadows"),ms([p()],Oo.prototype,"shadowCastingMode"),ms([p()],Oo.prototype,"lightmapIndex"),ms([p(ve)],Oo.prototype,"lightmapScaleOffset"),ms([p()],Oo.prototype,"enableInstancing"),ms([p()],Oo.prototype,"renderOrder"),ms([p()],Oo.prototype,"allowOcclusionWhenDynamic"),ms([p(R)],Oo.prototype,"probeAnchor"),ms([p()],Oo.prototype,"reflectionProbeUsage");let gi=Oo;class cd extends gi{}class P0 extends cd{_needUpdateBoundingSphere=!1;awake(){super.awake(),oP&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof Bs){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,i=Xv(e);i&&(e.geometry=i),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(oP){for(const e of this.sharedMeshes)if(e instanceof Bs&&e.boundingSphere){const t=U(e.boundingSphere.center).applyMatrix4(e.matrixWorld);F.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var Em=(o=>(o[o.Off=0]="Off",o[o.On=1]="On",o[o.TwoSided=2]="TwoSided",o[o.ShadowsOnly=3]="ShadowsOnly",o))(Em||{}),fj=Object.defineProperty,tc=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&fj(e,t,n),n};const fi=x("debugdroplistener");class yj extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const bj="blob";class gs extends T{dropArea;fitIntoVolume=!1;fitVolumeSize=new v(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new re;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new ee,point:t?.point,size:t?.size},!1)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}awake(){for(const e of this.gameObject.children)this.dropArea&&e.contains(this.dropArea)||this._addedObjects.push(e)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent),M()&&this.dropArea&&(this.dropArea.getComponentInChildren(gi)||console.warn("[DropListener] The assigned DropArea does not seem to have a renderer/mesh. Drag and Drop events will not be detected."))}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}onNetworkEvent=e=>{if(!this.useNetworking){fi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new ee,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new ee,point:e.point,size:e.size},!0)}};handlePaste=e=>{this.context.connection.allowEditing===!1||e.defaultPrevented||navigator.clipboard.readText().then(t=>{if(t&&(t.startsWith("http")||t.startsWith("https")||t.startsWith("blob"))){const i={screenposition:new ee(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(i)&&this.addFromUrl(t,i,!1)}}).catch(console.warn)};onDrag=e=>{fi&&console.debug("DropListener Drag",e,this.context.connection.allowEditing),this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(fi&&console.debug("DropListener Drop",e,this.context.connection.allowEditing),this.context.connection.allowEditing===!1||!e?.dataTransfer||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new ee(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const s in i){const r=i[s];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){fi&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],c=r[6],h=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${c}/${h}`}else e.startsWith("https://polyhaven.com/a")&&(e=_j(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const s=await Am.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(s&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(s,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(fi&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Jc(bj,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){fi&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){fi&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await Am.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const s=this.onObjectLoaded(n,t,!1);s&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),Hr.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(s)&&this.sendDropEvent(r.download_url,s,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&t.destroy();this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:s}=e;if(fi&&console.log(`Dropped ${this.gameObject.name}`,n),!n?.scene)return console.warn("No object specified to add to scene",n),null;this.removePreviouslyAddedObjects();const r=n.scene;r.position.copy(this.gameObject.worldPosition);const a=Je(this.gameObject);let l=new v(0,0,0);a.x=Math.abs(a.x),a.y=Math.abs(a.y),a.z=Math.abs(a.z);let c=r.scale.clone();const h=new ri().setFromCenterAndSize(new v(0,this.fitVolumeSize.y*a.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize.clone().multiply(a));if(fi&&F.DrawWireBox3(h,255,5),this.fitIntoVolume&&($w(r,h,{position:!this.placeAtHitPosition}),c=r.scale.clone().divide(a),l=r.worldPosition.clone().sub(this.gameObject.worldPosition).divide(a),fi&&F.DrawSphere(l,.1,16711680,5)),this.gameObject.attach(r),r.position.copy(l),r.quaternion.identity(),r.scale.copy(c),fi&&F.DrawArrow(this.gameObject.worldPosition,r.getWorldPosition(new v),65280,5),this._addedObjects.push(r),this._addedModels.push(n),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const u=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,u&&u.length>0)for(const m of u){const g=m.point.clone();fi&&console.log("Place object at hit",m),Ww(r,g);break}}li.autoplayAnimations(n);const d=new yj({sender:this,gltf:n,model:n,object:r,contentMD5:s,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(d),this.onDropped?.invoke(d.detail),r&&this.context.events.emit("scene-content-changed",{source:this,object:r}),!i&&t.url?.startsWith("http")&&this.context.connection.isConnected&&r&&this.sendDropEvent(t.url,r,s),r}async sendDropEvent(e,t,i){if(!this.useNetworking){fi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const n=Si([t]),s={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new v),contentMD5:i};this.context.connection.send("droplistener",s)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone()),i=this.context.physics.raycast({screenPoint:t,recursive:!0,testObject:s=>!this._addedObjects.some(r=>r.contains(s))});if(!i.length)return M()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1;const n=i[0];return!!(this.dropArea&&this.dropArea.contains(n.object))}}tc([p(R)],gs.prototype,"dropArea"),tc([p()],gs.prototype,"fitIntoVolume"),tc([p(v)],gs.prototype,"fitVolumeSize"),tc([p()],gs.prototype,"placeAtHitPosition"),tc([p()],gs.prototype,"useNetworking"),tc([p(re)],gs.prototype,"onDropped");function _j(o){if(!o.startsWith("https://polyhaven.com/"))return o;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",t=new URL(o).pathname.split("/").pop(),i=`${e}${t}/${t}_4k.gltf`;return console.log("Resolved polyhaven asset url",o,"\u2192",i),i}var Am;(o=>{async function e(i,n,s){const r=s.guid,a=new _t(r),l=new Blob([i],{type:i.type||d0(i.name)||void 0}),c=URL.createObjectURL(l),h=await is().loadSync(n,c,i.name,a).catch(d=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,d),null));return URL.revokeObjectURL(c),h?new Promise((d,u)=>{const m=new FileReader;m.readAsArrayBuffer(i),m.onloadend=async g=>{const y=m.result,b=Hr.hashMD5(y);return d({model:h,contentMD5:b})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}o.loadFile=e;async function t(i,n){const s=new _t(n.guid),r=i.toString();fi&&F.DrawWireSphere(n.point,.1,16711680,3);const a=Ql.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size});try{const l=await is().loadSync(n.context,r,r,s,h=>{a.onProgress(h.loaded/h.total)}).catch(h=>(console.warn(h),null));if(!l)return console.warn("Unsupported file type: "+i.toString()),null;let c="";try{const h=await fetch(r).then(d=>d.arrayBuffer());c=Hr.hashMD5(h)}catch(h){console.warn("Failed to compute content hash for "+r,h)}return{model:l,contentMD5:c}}finally{fi?setTimeout(()=>Ql.removePreview(n.guid),3e3):Ql.removePreview(n.guid)}}o.loadFileFromURL=t})(Am||(Am={}));var vj=Object.defineProperty,k0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vj(e,t,n),n};const Im=class SO extends T{parent=null;object=null;limitCount=60;_currentCount=0;_startPosition=null;_startQuaternion=null;start(){if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.ensureParentGuid(),this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const t=new _t(this.guid);this.object=P.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),P.getComponent(this.object,SO)?.destroy();let i=this.object.getComponentInChildren(va);i||(i=this.object.addComponent(va,{dragMode:l0.SnapToSurfaces}),i.guid=t.generateUUID());let n=P.getComponent(i.gameObject,Gn);n||(n=i.gameObject.addComponent(Gn),n.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(va);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new v(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new B(0,0,0,1)}this.gameObject.getComponentInParent(pn)||this.gameObject.addComponent(pn)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}_forwardPointerEvents=new Map;onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const i=P.getComponent(t,va);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):M()&&console.warn(`Duplicated object (${t.name}) does not have DragControls`)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}ensureParentGuid(){this.parent&&(this.parent.guid||this.parent.userData?.guid||(this.parent.guid=new _t(this.guid+"/parent").generateUUID()))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield Ry(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(P.isDestroyed(this.object))return this.object=null,null;this.object.matrixAutoUpdate===!1&&(this.object.updateMatrix(),M()&&(console.warn(`Object "${this.object.name}" has matrixAutoUpdate disabled. This can cause duplicated objects to have incorrect position/rotation/scale. Consider enabling matrixAutoUpdate or calling updateMatrix() before duplication.`),ge("Duplicatable: Object has matrixAutoUpdate disabled"))),this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new $o;this.parent||(this.parent=this.gameObject.parent),this.ensureParentGuid(),this.parent&&(e.parent=this.parent.guid??this.parent.userData?.guid,e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const t=P.instantiateSynced(this.object,e);return console.assert(t!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),t}};k0([p(R)],Im.prototype,"parent"),k0([p(R)],Im.prototype,"object"),k0([p()],Im.prototype,"limitCount");let O0=Im;var fs=(o=>(o[o.PointerEnter=0]="PointerEnter",o[o.PointerExit=1]="PointerExit",o[o.PointerDown=2]="PointerDown",o[o.PointerUp=3]="PointerUp",o[o.PointerClick=4]="PointerClick",o))(fs||{}),wj=Object.defineProperty,M0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&wj(e,t,n),n};class R0{eventID;callback=new re}M0([p()],R0.prototype,"eventID"),M0([p(re)],R0.prototype,"callback");class Lm extends T{triggers=[];invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback?.invoke()}hasTrigger(e){return this.triggers?.some(t=>t.eventID===e)??!1}shouldChangeCursor(){return this.hasTrigger(fs.PointerClick)||this.hasTrigger(fs.PointerDown)||this.hasTrigger(fs.PointerUp)}onPointerClick(e){this.invoke(fs.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(fs.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(fs.PointerExit)}onPointerDown(e){this.invoke(fs.PointerDown)}onPointerUp(e){this.invoke(fs.PointerUp)}}M0([p(R0)],Lm.prototype,"triggers");class lP{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,s={};t.extensions=t.extensions||{},t.extensions[this.name]=s;let r=new J;const a=new Array,l=new Array,c=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let g=new v,y=new B,b=new v;r.decompose(g,y,b),a.push(g.x,g.y,g.z),l.push(y.x,y.y,y.z,y.w),c.push(b.x,b.y,b.z)}const h=new Float32Array(a),d=new Float32Array(l),u=new Float32Array(c);s.attributes={TRANSLATION:i.processAccessor(new lt(h,3)),ROTATION:i.processAccessor(new lt(d,4)),SCALE:i.processAccessor(new lt(u,3))},n[this.name]=!0}}class cP{writer;constructor(e){this.writer=e}writeNode(e){}}class xj extends cP{beforeWriteNode(e,t){F.isGizmo(e)&&(t.keep=!1)}}class hP extends cP{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=jy(new he(1,1,1,0)))}}function dP(o){const e=uo.DontExport;return!(o.hideFlags&e)}function uP(o){return pP(o)}function pP(o,e=[]){let t=0;for(let i=0;i<o.children.length;t++){const n=o.children[i];if(!dP(n)){o.children.splice(i,1),n.parent=null;const s=t;e.push(()=>Sj(n,o,s));continue}pP(n,e),i++}return e}function Sj(o,e,t){o.parent=e,e.children.splice(Math.min(t,e.children.length),0,o)}var Cj=Object.defineProperty,mP=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Cj(e,t,n),n};const Dm=x("debuggltfexport");class T0 extends Xt{sceneRoot}const E0=class Fc extends T{binary=!0;objects=[];ext;async exportNow(e,t){Dm&&console.log("Exporting objects as glTF",this.objects),e||(e="scene"),(!this.objects||this.objects.length<=0)&&(this.objects=[this.context.scene]);const i={binary:this.binary,pivot:Fc.calculateCenter(this.objects),...t},n=await this.export(this.objects,i).catch(s=>(console.error(s),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Fc.saveArrayBuffer(n,e):Fc.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const i=new Kv;i.register(h=>new lP(h)),i.register(h=>new hP(h)),w0(i,this.context),Fc.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||Fc.collectAnimations(e),...t},s=new Array,r=new R;t?.pivot&&r.position.sub(t.pivot),Dm&&console.log("EXPORT",e),e.forEach(h=>{h&&dP(h)&&(r.children.push(h),h.matrixAutoUpdate=!1,h.matrix.copy(h.matrixWorld),P.getComponentsInChildren(h,gi).forEach(d=>{P.isActiveInHierarchy(d.gameObject)&&d.setInstancingEnabled(!1)}),s.push(...uP(h)))});const a=new gh(r);return t?.needleComponents&&(this.ext=new b0),this.ext&&(this.ext.registerExport(i),this.ext.context=a),new Promise((h,d)=>{Dm&&console.log("Starting glTF export.");try{i?.parse(r,u=>{l(),h(u)},u=>{l(),d(u)},n)}catch(u){console.error(u),l(),d(u)}finally{Dm&&console.log("Finished glTF export.")}});function l(){s.forEach(h=>h()),s.length=0,c()}function c(){e.forEach(h=>{h&&(h.matrixAutoUpdate=!0,P.getComponentsInChildren(h,gi).forEach(d=>{P.isActiveInHierarchy(d.gameObject)&&d.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(const i of e)i&&i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const i=t||new v;return i.set(0,0,0),e.forEach(n=>{i.add(le(n))}),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};mP([p()],E0.prototype,"binary"),mP([p(R)],E0.prototype,"objects");let A0=E0;function Pj(){typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{canvas;constructor(o,e){return this.canvas=document.createElement("canvas"),this.canvas.width=o,this.canvas.height=e,this.canvas.convertToBlob=(t,i)=>new Promise(n=>{this.canvas.toBlob(n,t,i)}),this.canvas}})}const kj=x("debugprogress");function gP(o){o=o||new Date;const e=o.getMonth()+1,t=o.getDate(),i=o.getHours(),n=o.getMinutes(),s=o.getSeconds(),r=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(i<10?"0":"")+i,c=(n<10?"0":"")+n,h=(s<10?"0":"")+s;return o.getFullYear()+r+a+"-"+l+c+h}class ue{static start(e,t){typeof t=="string"&&(t={parentScope:t});const i=new Oj(e,t);hd.set(e,i)}static report(e,t){const i=hd.get(e);if(!i){console.warn("Reporting progress for non-existing scope",e);return}typeof t=="string"&&(t={message:t,autoStep:!0}),i.report(t)}static end(e){const t=hd.get(e);t&&(t.end(),hd.delete(e))}}const hd=new Map;class Oj{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?hd.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??!!kj,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);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,s=0;for(const a of this.childScopes)n+=a.selfProgress,s+=1;s>0&&(n/=s);const r=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*r}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let i=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(i+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e?.message&&(i=e.message+" \u2013 "+i),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(i="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"\u2013"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+i),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,i),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(const 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}}const Ge="</StageRoot/Materials";function Mj(o,e,t){const i=new Map,n=y=>{const b=y.type___needle,f=i.get(b)||new Map;if(i.set(b,f),!f.has(y)){const _=`${b}${f.size?`_${f.size}`:""}`;f.set(y,_)}return f.get(y)},s=o.colorNode?jm(o.colorNode):[],r=o.colorNode?`color3f inputs:diffuseColor.connect = ${Ge}/${e}/${n(s.values().next().value)}.outputs:out>`:"",a=o.roughnessNode?jm(o.roughnessNode):[],l=o.roughnessNode?`float inputs:roughness.connect = ${Ge}/${e}/${n(a.values().next().value)}.outputs:out>`:"",c=o.normalNode?jm(o.normalNode):[],h=o.normalNode?`float3 inputs:normal.connect = ${Ge}/${e}/${n(c.values().next().value)}.outputs:out>`:"",d=o.metalnessNode?jm(o.metalnessNode):[],u=o.metalnessNode?`float inputs:metallic.connect = ${Ge}/${e}/${n(d.values().next().value)}.outputs:out>`:"",m=new Set([...s,...a,...c,...d]),g=Ej(m,e,t,n);return console.debug(g),`
1140
+ `,defines:{USE_LIGHTMAP:""}})}}var pj=Object.defineProperty,ms=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&pj(e,t,n),n};const ec=x("debugrenderer"),oP=x("debugskinnedmesh"),sP=x("noinstancing"),mj=x("wireframe");var rP=(o=>(o[o.Off=0]="Off",o[o.BlendProbes=1]="BlendProbes",o[o.BlendProbesAndSkybox=2]="BlendProbesAndSkybox",o[o.Simple=3]="Simple",o))(rP||{});class aP{path=null;asset=null;default}class gj{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&ec&&console.warn("SharedMaterials have changed: "+this._renderer.name),this._changed=e}is(e){return this._renderer===e}constructor(e,t){this._renderer=e;const i=this.setMaterial.bind(this),n=this.getMaterial.bind(this),s=e.gameObject;if(this._targets=[],s)switch(s.type){case"Group":this._targets=[...s.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(s);break}let r=!1,a,l=0;for(let c=0;c<this._targets.length;c++){const h=this._targets[c];if(!h)continue;const d=h.material;if(d){d.shadowSide=d.side;for(let u=0;u<t.length;u++){const m=t[u];if(!m){r=!0;continue}if(d.name===m.name){a===void 0&&(a=new Map),a.set(u,c),l=Math.max(l,u);break}}}}if(r){this._indexMapMaxIndex=l,this._indexMap=a;const c=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(c),Ni()&&ge("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(c,h){if(typeof h=="string"){const d=parseInt(h);if(!isNaN(d))return n(d)}return c[h]},set(c,h,d){return typeof h=="string"&&i(d,Number.parseInt(h)),Reflect.set(c,h,d)?(d instanceof Oe&&(c.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const 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;const i=this._targets[t];!i||i.material===void 0||(i.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const i=t[e];return i?i.material:null}}const Oo=class su extends T{static setInstanced(e,t){const i=Dh(e,su);return i.enableInstancing=t,i.setInstancingEnabled(t),i}static isInstanced(e){const t=ls(e,su);return t?t.isInstancingActive:Mn.isUsingInstancing(e)}static setVisible(e,t){So(e,t)}receiveShadows=!1;shadowCastingMode=0;lightmapIndex=-1;lightmapScaleOffset=new ve(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){return this.sharedMeshes[0]}_sharedMeshes=[];get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.isOwnSubmesh(e)&&this._sharedMeshes.push(e);else this.isMeshOrSkinnedMesh(this.gameObject)&&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 i=0;i<this._sharedMaterials.length;i++){const n=i<e.length?e[i]:null;n&&n instanceof Oe?this.sharedMaterials[i]=n:t||(t=!0,console.warn("Can not assign null as material: "+this.name,n))}}}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._originalMaterials=[]),this._sharedMaterials=new gj(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return sP}_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(const 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,ec&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&ec&&this.probeAnchor.add(new Ui(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const i=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(i)||P.getComponent(i,su))){if(this.renderOrder.length<=e){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+e,"ChildElement:",i);continue}i.renderOrder=this.renderOrder[e],e+=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(),mj)for(let e=0;e<this.sharedMaterials.length;e++){const t=this.sharedMaterials[e];t&&(t.wireframe=!0)}}applyLightmapping(){if(this.lightmapIndex>=0&&!this._lightmaps){const e=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(e){this._lightmaps||(this._lightmaps=[]);const t=new C0(this);t.init(this.lightmapIndex,this.lightmapScaleOffset,e),this._lightmaps.push(t)}else ec&&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(const e of this._handles)this._handlesTempArray.push(e);return this._handlesTempArray}_handlesTempArray=[];setInstancingEnabled(e){if(this._isInstancingEnabled===e){if(!e||this._handles&&this._handles.length>0)return!0}else this._isInstancingEnabled=e;if(e){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this._handles===void 0||this._handles===null){if(this._handles=Ka.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return P.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return P.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this._handles)for(const t of this._handles)t.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this._handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!sP&&(this.setInstancingEnabled(!0),Mn.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(e=>e)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe(),ps.onEnabled.addEventListener(this.onReflectionProbeEnabled),ps.onDisabled.addEventListener(this.onReflectionProbeDisabled)}onDisable(){this.setVisibility(!1),ps.onEnabled.removeEventListener(this.onReflectionProbeEnabled),ps.onDisabled.removeEventListener(this.onReflectionProbeDisabled),this._handles&&this._handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this._handles=null,this.isMultiMaterialObject(this.gameObject))for(const 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()),ec==this.name&&this.gameObject instanceof V){this.gameObject.geometry.computeBoundingSphere();const e=U(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);F.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(const 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[Mh]===!0){this.gameObject[Mh]=!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&&P.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];So(t.object,!1)}if(this.reflectionProbeUsage!==0&&this._reflectionProbe?this._reflectionProbe.apply(this.gameObject):this.reflectionProbeUsage===0&&this._reflectionProbe&&this._reflectionProbe.unapply(this.gameObject),this._sharedMaterials)for(const e of this._sharedMaterials)e&&"envMap"in e&&"envMapIntensity"in e&&!ps.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment,e.envMapRotation=this.context.scene.environmentRotation);else ec&&console.warn("[Renderer] sharedMaterials not initialized yet: "+this.name)}}onBeforeRenderThree=(e,t,i,n,s,r)=>{if(s.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=this.context.scene.environmentIntensity;s.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(s),a.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];So(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(){Ar.applyStencil(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){this._reflectionProbe=null,this.reflectionProbeUsage!==0&&(this.startCoroutine(this._updateReflectionProbe(),Ee.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=ps.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))So(this.gameObject,e);else for(const t of this.gameObject.children)this.isOwnSubmesh(t)&&So(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}isOwnSubmesh(e){return this.isMeshOrSkinnedMesh(e)&&!ls(e,su)}};ms([p()],Oo.prototype,"receiveShadows"),ms([p()],Oo.prototype,"shadowCastingMode"),ms([p()],Oo.prototype,"lightmapIndex"),ms([p(ve)],Oo.prototype,"lightmapScaleOffset"),ms([p()],Oo.prototype,"enableInstancing"),ms([p()],Oo.prototype,"renderOrder"),ms([p()],Oo.prototype,"allowOcclusionWhenDynamic"),ms([p(R)],Oo.prototype,"probeAnchor"),ms([p()],Oo.prototype,"reflectionProbeUsage");let gi=Oo;class cd extends gi{}class P0 extends cd{_needUpdateBoundingSphere=!1;awake(){super.awake(),oP&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof Bs){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,i=Xv(e);i&&(e.geometry=i),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(oP){for(const e of this.sharedMeshes)if(e instanceof Bs&&e.boundingSphere){const t=U(e.boundingSphere.center).applyMatrix4(e.matrixWorld);F.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var Em=(o=>(o[o.Off=0]="Off",o[o.On=1]="On",o[o.TwoSided=2]="TwoSided",o[o.ShadowsOnly=3]="ShadowsOnly",o))(Em||{}),fj=Object.defineProperty,tc=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&fj(e,t,n),n};const fi=x("debugdroplistener");class yj extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const bj="blob";class gs extends T{dropArea;fitIntoVolume=!1;fitVolumeSize=new v(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new re;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new ee,point:t?.point,size:t?.size},!1)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}awake(){for(const e of this.gameObject.children)this.dropArea&&e.contains(this.dropArea)||this._addedObjects.push(e)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent),M()&&this.dropArea&&(this.dropArea.getComponentInChildren(gi)||console.warn("[DropListener] The assigned DropArea does not seem to have a renderer/mesh. Drag and Drop events will not be detected."))}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}onNetworkEvent=e=>{if(!this.useNetworking){fi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new ee,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new ee,point:e.point,size:e.size},!0)}};handlePaste=e=>{this.context.connection.allowEditing===!1||e.defaultPrevented||navigator.clipboard.readText().then(t=>{if(t&&(t.startsWith("http")||t.startsWith("https")||t.startsWith("blob"))){const i={screenposition:new ee(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(i)&&this.addFromUrl(t,i,!1)}}).catch(console.warn)};onDrag=e=>{fi&&console.debug("DropListener Drag",e,this.context.connection.allowEditing),this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(fi&&console.debug("DropListener Drop",e,this.context.connection.allowEditing),this.context.connection.allowEditing===!1||!e?.dataTransfer||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new ee(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const s in i){const r=i[s];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){fi&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],c=r[6],h=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${c}/${h}`}else e.startsWith("https://polyhaven.com/a")&&(e=_j(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const s=await Am.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(s&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(s,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(fi&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Jc(bj,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){fi&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){fi&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await Am.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const s=this.onObjectLoaded(n,t,!1);s&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),Hr.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(s)&&this.sendDropEvent(r.download_url,s,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&t.destroy();this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:s}=e;if(fi&&console.log(`Dropped ${this.gameObject.name}`,n),!n?.scene)return console.warn("No object specified to add to scene",n),null;this.removePreviouslyAddedObjects();const r=n.scene;r.position.copy(this.gameObject.worldPosition);const a=Je(this.gameObject);let l=new v(0,0,0);a.x=Math.abs(a.x),a.y=Math.abs(a.y),a.z=Math.abs(a.z);let c=r.scale.clone();const h=new ri().setFromCenterAndSize(new v(0,this.fitVolumeSize.y*a.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize.clone().multiply(a));if(fi&&F.DrawWireBox3(h,255,5),this.fitIntoVolume&&($w(r,h,{position:!this.placeAtHitPosition}),c=r.scale.clone().divide(a),l=r.worldPosition.clone().sub(this.gameObject.worldPosition).divide(a),fi&&F.DrawSphere(l,.1,16711680,5)),this.gameObject.attach(r),r.position.copy(l),r.quaternion.identity(),r.scale.copy(c),fi&&F.DrawArrow(this.gameObject.worldPosition,r.getWorldPosition(new v),65280,5),this._addedObjects.push(r),this._addedModels.push(n),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const u=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,u&&u.length>0)for(const m of u){const g=m.point.clone();fi&&console.log("Place object at hit",m),Ww(r,g);break}}li.autoplayAnimations(n);const d=new yj({sender:this,gltf:n,model:n,object:r,contentMD5:s,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(d),this.onDropped?.invoke(d.detail),r&&this.context.events.emit("scene-content-changed",{source:this,object:r}),!i&&t.url?.startsWith("http")&&this.context.connection.isConnected&&r&&this.sendDropEvent(t.url,r,s),r}async sendDropEvent(e,t,i){if(!this.useNetworking){fi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const n=Si([t]),s={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new v),contentMD5:i};this.context.connection.send("droplistener",s)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone()),i=this.context.physics.raycast({screenPoint:t,recursive:!0,testObject:s=>!this._addedObjects.some(r=>r.contains(s))});if(!i.length)return M()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1;const n=i[0];return!!(this.dropArea&&this.dropArea.contains(n.object))}}tc([p(R)],gs.prototype,"dropArea"),tc([p()],gs.prototype,"fitIntoVolume"),tc([p(v)],gs.prototype,"fitVolumeSize"),tc([p()],gs.prototype,"placeAtHitPosition"),tc([p()],gs.prototype,"useNetworking"),tc([p(re)],gs.prototype,"onDropped");function _j(o){if(!o.startsWith("https://polyhaven.com/"))return o;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",t=new URL(o).pathname.split("/").pop(),i=`${e}${t}/${t}_4k.gltf`;return console.log("Resolved polyhaven asset url",o,"\u2192",i),i}var Am;(o=>{async function e(i,n,s){const r=s.guid,a=new _t(r),l=new Blob([i],{type:i.type||d0(i.name)||void 0}),c=URL.createObjectURL(l),h=await is().loadSync(n,c,i.name,a).catch(d=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,d),null));return URL.revokeObjectURL(c),h?new Promise((d,u)=>{const m=new FileReader;m.readAsArrayBuffer(i),m.onloadend=async g=>{const y=m.result,b=Hr.hashMD5(y);return d({model:h,contentMD5:b})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}o.loadFile=e;async function t(i,n){const s=new _t(n.guid),r=i.toString();fi&&F.DrawWireSphere(n.point,.1,16711680,3);const a=Ql.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size});try{const l=await is().loadSync(n.context,r,r,s,h=>{a.onProgress(h.loaded/h.total)}).catch(h=>(console.warn(h),null));if(!l)return console.warn("Unsupported file type: "+i.toString()),null;let c="";try{const h=await fetch(r).then(d=>d.arrayBuffer());c=Hr.hashMD5(h)}catch(h){console.warn("Failed to compute content hash for "+r,h)}return{model:l,contentMD5:c}}finally{fi?setTimeout(()=>Ql.removePreview(n.guid),3e3):Ql.removePreview(n.guid)}}o.loadFileFromURL=t})(Am||(Am={}));var vj=Object.defineProperty,k0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vj(e,t,n),n};const Im=class SO extends T{parent=null;object=null;limitCount=60;_currentCount=0;_startPosition=null;_startQuaternion=null;start(){if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.ensureParentGuid(),this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const t=new _t(this.guid);this.object=P.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),P.getComponent(this.object,SO)?.destroy();let i=this.object.getComponentInChildren(va);i||(i=this.object.addComponent(va,{dragMode:l0.SnapToSurfaces}),i.guid=t.generateUUID());let n=P.getComponent(i.gameObject,Gn);n||(n=i.gameObject.addComponent(Gn),n.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(va);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new v(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new B(0,0,0,1)}this.gameObject.getComponentInParent(pn)||this.gameObject.addComponent(pn)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}_forwardPointerEvents=new Map;onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const i=P.getComponent(t,va);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):M()&&console.warn(`Duplicated object (${t.name}) does not have DragControls`)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}ensureParentGuid(){this.parent&&(this.parent.guid||this.parent.userData?.guid||(this.parent.guid=new _t(this.guid+"/parent").generateUUID()))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield Ry(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(P.isDestroyed(this.object))return this.object=null,null;this.object.matrixAutoUpdate===!1&&(this.object.updateMatrix(),M()&&(console.warn(`Object "${this.object.name}" has matrixAutoUpdate disabled. This can cause duplicated objects to have incorrect position/rotation/scale. Consider enabling matrixAutoUpdate or calling updateMatrix() before duplication.`),ge("Duplicatable: Object has matrixAutoUpdate disabled"))),this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new $o;this.parent||(this.parent=this.gameObject.parent),this.ensureParentGuid(),this.parent&&(e.parent=this.parent.guid??this.parent.userData?.guid,e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const t=P.instantiateSynced(this.object,e);return console.assert(t!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),t}};k0([p(R)],Im.prototype,"parent"),k0([p(R)],Im.prototype,"object"),k0([p()],Im.prototype,"limitCount");let O0=Im;var fs=(o=>(o[o.PointerEnter=0]="PointerEnter",o[o.PointerExit=1]="PointerExit",o[o.PointerDown=2]="PointerDown",o[o.PointerUp=3]="PointerUp",o[o.PointerClick=4]="PointerClick",o))(fs||{}),wj=Object.defineProperty,M0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&wj(e,t,n),n};class R0{eventID;callback=new re}M0([p()],R0.prototype,"eventID"),M0([p(re)],R0.prototype,"callback");class Lm extends T{triggers=[];invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback?.invoke()}hasTrigger(e){return this.triggers?.some(t=>t.eventID===e)??!1}shouldChangeCursor(){return this.hasTrigger(fs.PointerClick)||this.hasTrigger(fs.PointerDown)||this.hasTrigger(fs.PointerUp)}onPointerClick(e){this.invoke(fs.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(fs.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(fs.PointerExit)}onPointerDown(e){this.invoke(fs.PointerDown)}onPointerUp(e){this.invoke(fs.PointerUp)}}M0([p(R0)],Lm.prototype,"triggers");class lP{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,s={};t.extensions=t.extensions||{},t.extensions[this.name]=s;let r=new J;const a=new Array,l=new Array,c=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let g=new v,y=new B,b=new v;r.decompose(g,y,b),a.push(g.x,g.y,g.z),l.push(y.x,y.y,y.z,y.w),c.push(b.x,b.y,b.z)}const h=new Float32Array(a),d=new Float32Array(l),u=new Float32Array(c);s.attributes={TRANSLATION:i.processAccessor(new lt(h,3)),ROTATION:i.processAccessor(new lt(d,4)),SCALE:i.processAccessor(new lt(u,3))},n[this.name]=!0}}class cP{writer;constructor(e){this.writer=e}writeNode(e){}}class xj extends cP{beforeWriteNode(e,t){F.isGizmo(e)&&(t.keep=!1)}}class hP extends cP{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=jy(new he(1,1,1,0)))}}function dP(o){const e=uo.DontExport;return!(o.hideFlags&e)}function uP(o){return pP(o)}function pP(o,e=[]){let t=0;for(let i=0;i<o.children.length;t++){const n=o.children[i];if(!dP(n)){o.children.splice(i,1),n.parent=null;const s=t;e.push(()=>Sj(n,o,s));continue}pP(n,e),i++}return e}function Sj(o,e,t){o.parent=e,e.children.splice(Math.min(t,e.children.length),0,o)}var Cj=Object.defineProperty,mP=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Cj(e,t,n),n};const Dm=x("debuggltfexport");class T0 extends Xt{sceneRoot}const E0=class Fc extends T{binary=!0;objects=[];ext;async exportNow(e,t){Dm&&console.log("Exporting objects as glTF",this.objects),e||(e="scene"),(!this.objects||this.objects.length<=0)&&(this.objects=[this.context.scene]);const i={binary:this.binary,pivot:Fc.calculateCenter(this.objects),...t},n=await this.export(this.objects,i).catch(s=>(console.error(s),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Fc.saveArrayBuffer(n,e):Fc.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const i=new Kv;i.register(h=>new lP(h)),i.register(h=>new hP(h)),w0(i,this.context),Fc.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||Fc.collectAnimations(e),...t},s=new Array,r=new R;t?.pivot&&r.position.sub(t.pivot),Dm&&console.log("EXPORT",e),e.forEach(h=>{h&&dP(h)&&(r.children.push(h),h.matrixAutoUpdate=!1,h.matrix.copy(h.matrixWorld),P.getComponentsInChildren(h,gi).forEach(d=>{P.isActiveInHierarchy(d.gameObject)&&d.setInstancingEnabled(!1)}),s.push(...uP(h)))});const a=new gh(r);return t?.needleComponents&&(this.ext=new b0),this.ext&&(this.ext.registerExport(i),this.ext.context=a),new Promise((h,d)=>{Dm&&console.log("Starting glTF export.");try{i?.parse(r,u=>{l(),h(u)},u=>{l(),d(u)},n)}catch(u){console.error(u),l(),d(u)}finally{Dm&&console.log("Finished glTF export.")}});function l(){s.forEach(h=>h()),s.length=0,c()}function c(){e.forEach(h=>{h&&(h.matrixAutoUpdate=!0,P.getComponentsInChildren(h,gi).forEach(d=>{P.isActiveInHierarchy(d.gameObject)&&d.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(const i of e)i&&i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const i=t||new v;return i.set(0,0,0),e.forEach(n=>{i.add(le(n))}),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};mP([p()],E0.prototype,"binary"),mP([p(R)],E0.prototype,"objects");let A0=E0;function Pj(){typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{canvas;constructor(o,e){return this.canvas=document.createElement("canvas"),this.canvas.width=o,this.canvas.height=e,this.canvas.convertToBlob=(t,i)=>new Promise(n=>{this.canvas.toBlob(n,t,i)}),this.canvas}})}const kj=x("debugprogress");function gP(o){o=o||new Date;const e=o.getMonth()+1,t=o.getDate(),i=o.getHours(),n=o.getMinutes(),s=o.getSeconds(),r=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(i<10?"0":"")+i,c=(n<10?"0":"")+n,h=(s<10?"0":"")+s;return o.getFullYear()+r+a+"-"+l+c+h}class ue{static start(e,t){typeof t=="string"&&(t={parentScope:t});const i=new Oj(e,t);hd.set(e,i)}static report(e,t){const i=hd.get(e);if(!i){console.warn("Reporting progress for non-existing scope",e);return}typeof t=="string"&&(t={message:t,autoStep:!0}),i.report(t)}static end(e){const t=hd.get(e);t&&(t.end(),hd.delete(e))}}const hd=new Map;class Oj{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?hd.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??!!kj,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);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,s=0;for(const a of this.childScopes)n+=a.selfProgress,s+=1;s>0&&(n/=s);const r=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*r}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let i=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(i+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e?.message&&(i=e.message+" \u2013 "+i),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(i="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"\u2013"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+i),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,i),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(const 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}}const Ge="</StageRoot/Materials";function Mj(o,e,t){const i=new Map,n=y=>{const b=y.type___needle,f=i.get(b)||new Map;if(i.set(b,f),!f.has(y)){const _=`${b}${f.size?`_${f.size}`:""}`;f.set(y,_)}return f.get(y)},s=o.colorNode?jm(o.colorNode):[],r=o.colorNode?`color3f inputs:diffuseColor.connect = ${Ge}/${e}/${n(s.values().next().value)}.outputs:out>`:"",a=o.roughnessNode?jm(o.roughnessNode):[],l=o.roughnessNode?`float inputs:roughness.connect = ${Ge}/${e}/${n(a.values().next().value)}.outputs:out>`:"",c=o.normalNode?jm(o.normalNode):[],h=o.normalNode?`float3 inputs:normal.connect = ${Ge}/${e}/${n(c.values().next().value)}.outputs:out>`:"",d=o.metalnessNode?jm(o.metalnessNode):[],u=o.metalnessNode?`float inputs:metallic.connect = ${Ge}/${e}/${n(d.values().next().value)}.outputs:out>`:"",m=new Set([...s,...a,...c,...d]),g=Ej(m,e,t,n);return console.debug(g),`
1141
1141
 
1142
1142
  def Material "${e}" ${o.name?`(
1143
1143
  displayName = "${o.name}"
@@ -1189,7 +1189,7 @@ ${c}
1189
1189
  )
1190
1190
  `}}const ic=`
1191
1191
  `,yi="</StageRoot/Materials";class _P{str;indent;constructor(){this.str="",this.indent=0}clear(){this.str="",this.indent=0}beginBlock(e=void 0,t="{",i=!0){e!==void 0?(e=this.applyIndent(e),this.str+=e,i?(this.str+=ic,this.str+=this.applyIndent(t)):this.str+=" "+t):this.str+=this.applyIndent(t),this.str+=ic,this.indent+=1}closeBlock(e="}"){this.indent-=1,this.str+=this.applyIndent(e)+ic}beginArray(e){e=this.applyIndent(e+" = ["),this.str+=e,this.str+=ic,this.indent+=1}closeArray(){this.indent-=1,this.str+=this.applyIndent("]")+ic}appendLine(e=""){e=this.applyIndent(e),this.str+=e,this.str+=ic}toString(){return this.str}applyIndent(e){let t="";for(let i=0;i<this.indent;i++)t+=" ";return t+e}}class jj{root;exporter;extensions=[];quickLookCompatible;exportInvisible;materials;textures;files;document;output;animations;constructor(e,t,i){this.root=e||void 0,this.exporter=t,this.quickLookCompatible=i.quickLookCompatible,this.exportInvisible=i.exportInvisible,i.extensions&&(this.extensions=i.extensions),this.materials=new Map,this.textures={},this.files={},this.document=new I0,this.output="",this.animations=[]}makeNameSafe(e){return Zi(e)}}const vP=()=>({ar:{anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}},quickLookCompatible:!1,extensions:[],maxTextureSize:4096,exportInvisible:!1});let wP=class{debug;pruneUnusedNodes;sceneAnchoringOptions=vP();extensions=[];keepObject;beforeWritingDocument;constructor(){this.debug=!1,this.pruneUnusedNodes=!0}async parse(o,e=vP()){e=Object.assign({},e),this.sceneAnchoringOptions=e;const t=new jj(o,this,e);this.extensions=t.extensions;const i=t.files,n="model.usda";i[n]=null,t.materials;const s=t.textures;ue.report("export-usdz","Invoking onBeforeBuildDocument"),await Fm(t,"onBeforeBuildDocument"),ue.report("export-usdz","Done onBeforeBuildDocument"),ue.report("export-usdz","Reparent bones to common ancestor");const r=[],a=new Set;o?.traverse(g=>{if(!(!e.exportInvisible&&!g.visible)&&g instanceof Bs){const y=g.skeleton.bones,b=yP(y);if(b){const f={object:g,originalParent:g.parent,newParent:b};r.push(f),a.add(f.object.uuid),f.newParent&&a.add(f.newParent.uuid),f.originalParent&&a.add(f.originalParent.uuid)}}});for(const g of r){const{object:y,originalParent:b,newParent:f}=g;f.add(y)}ue.report("export-usdz","Traversing hierarchy"),o&&xP(o,t.document,t,this.keepObject),ue.report("export-usdz","Invoking onAfterBuildDocument"),await Fm(t,"onAfterBuildDocument");const l=t.extensions.find(g=>g.extensionName==="Behaviour")?.getAllTargetUuids()??new Set;if(this.pruneUnusedNodes){const g={allBehaviorTargets:l,debug:!1,boneReparentings:a,quickLookCompatible:t.quickLookCompatible};this.debug&&SP(t.document,"Hierarchy BEFORE pruning",g),CP(t.document,g),this.debug&&SP(t.document,"Hierarchy AFTER pruning")}else this.debug&&console.log("Pruning of empty nodes is disabled. This may result in a larger USDZ file.");ue.report("export-usdz",{message:"Parsing document",autoStep:10}),await Fj(t,e),ue.report("export-usdz","Invoking onAfterSerialize"),await Fm(t,"onAfterSerialize");for(const g of r){const{object:y,originalParent:b,newParent:f}=g;b&&b.add(y)}t.exporter?.beforeWritingDocument?.();const c=t.document.buildHeader(t)+`
1192
- `+t.output;this.debug&&console.debug(c),i[n]=Zv(c),t.output="",ue.report("export-usdz",{message:"Exporting textures",autoStep:10}),ue.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const h=new Dr({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),d=Object.keys(s).length;ue.report("export-usdz-textures",{totalSteps:d*3,currentStep:0});const u=async g=>{const y=s[g],b=y.texture,f=U0.includes(b.format);let _={imageData:b.image};ue.report("export-usdz-textures",{message:"read back texture",autoStep:!0});const w=y.scale!==void 0&&y.scale.x!==1&&y.scale.y!==1&&y.scale.z!==1&&y.scale.w!==1;(b.isCompressedTexture||b.isRenderTargetTexture||w)&&(_=await kP(b,e.maxTextureSize,h,y.scale)),ue.report("export-usdz-textures",{message:"convert texture to canvas",autoStep:!0});const S=await Uj(_.imageBitmap||_.imageData,e.maxTextureSize).catch(O=>{console.error("Error converting texture to canvas",b,O)});if(S){ue.report("export-usdz-textures",{message:"convert canvas to blob",autoStep:!0});const O=await S.convertToBlob({type:f?"image/png":"image/jpeg",quality:.95});i[`textures/${g}.${f?"png":"jpg"}`]=new Uint8Array(await O.arrayBuffer())}else console.warn("Can`t export texture: ",b)};for(const g in s)await u(g);h.dispose(),ue.end("export-usdz-textures");let m=0;for(const g in i){const y=i[g],b=34+g.length;m+=b;const f=m&63;if(f!==4){const _=64-f,w=new Uint8Array(_);i[g]=[y,{extra:{12345:w}}]}m=y.length}return ue.report("export-usdz","zip archive"),aR(i,{level:0})}};function xP(o,e,t,i){if(!t.exportInvisible&&!o.visible)return;let n,s,r;const a={position:o.position,quaternion:o.quaternion,scale:o.scale};if(o.position.x===0&&o.position.y===0&&o.position.z===0&&(a.position=null),o.quaternion.x===0&&o.quaternion.y===0&&o.quaternion.z===0&&o.quaternion.w===1&&(a.quaternion=null),o.scale.x===1&&o.scale.y===1&&o.scale.z===1&&(a.scale=null),(o instanceof V||o instanceof Bs)&&(s=o.geometry,r=o.material),i&&!i(o)&&(s=void 0,r=void 0),(o instanceof V||o instanceof Bs)&&r&&typeof r=="object"&&(r instanceof Mt||r instanceof Ie||r.isMeshPhysicalNodeMaterial||r instanceof ke&&r.type==="MeshLineMaterial")){const l=zm(o),c=o instanceof Bs?o:null;n=new vt(o.uuid,l,a,s,r,void 0,c,o.animations)}else if(o instanceof me||o instanceof mu){const l=zm(o);n=new vt(o.uuid,l,a,void 0,void 0,o)}else{const l=zm(o);n=new vt(o.uuid,l,a,void 0,void 0,void 0,void 0,o.animations)}if(n){if(n.displayName=o.userData?.name||o.name,n.visibility=o.visible?void 0:"invisible",e&&e.add(n),e=n,t.extensions)for(const l of t.extensions)l.onExportObject&&l.onExportObject.call(l,o,n,t)}else{const l=zm(o),c=new vt(o.uuid,l,{position:o.position,quaternion:o.quaternion,scale:o.scale});e&&e.add(c),e=c}for(const l of o.children)xP(l,e,t,i)}function SP(o,e,...t){const i={};let n=0;function s(r,a){n++;let l=r.displayName||r.name;l+=" ("+r.uuid+")",(r.geometry||r.material||r.camera||r.skinnedMesh)&&(l+=" ("+(r.geometry?"geo, ":"")+(r.material?"mat, ":"")+(r.camera?"cam, ":"")+(r.skinnedMesh?"skin, ":"")+")"),a[l]={};const c={object:r};r.material&&(c.mat=!0),r.geometry&&(c.geo=!0),r.camera&&(c.cam=!0),r.skinnedMesh&&(c.skin=!0),a[l]._self=c;for(const h of r.children)h&&s(h,a[l])}s(o,i),console.log(e+" ("+n+" nodes)",i,...t)}function CP(o,e){let t=!0;const i=new Array,n=new Array;if(o.children.length===0)t=!0;else{const c=[...o.children];for(const h of c)if(h){const d=CP(h,e);e.debug&&(d?i.push(h):n.push(h)),t=t&&d}}const s=e.allBehaviorTargets.has(o.uuid),r=o.geometry||o.material||o.camera&&!e.quickLookCompatible||o.skinnedMesh||!1,a=e.boneReparentings.has(o.uuid),l=t&&!s&&!r&&!a;return l?(e.debug&&console.log("Pruned object:",(o.displayName||o.name)+" ("+o.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:s,allChildsWerePruned:t,isBoneReparenting:a,object:o,prunedChilds:i,keptChilds:n}),o.parent?.remove(o)):e.debug&&console.log("Kept object:",(o.displayName||o.name)+" ("+o.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:s,allChildsWerePruned:t,isBoneReparenting:a,object:o,prunedChilds:i,keptChilds:n}),l}async function Fj(o,e){ue.start("export-usdz-resources","export-usdz");const t=[];for(const c of o.document.children)PP(c,o,t);const i=t.length;for(let c=0;c<i;c++)ue.report("export-usdz-resources",{totalSteps:i,currentStep:c}),await new Promise((h,d)=>{t[c](),h()});ue.end("export-usdz-resources");const n=new _P,s=o.exporter.sceneAnchoringOptions.ar;n.beginBlock(`def Xform "${o.document.name}"`),n.beginBlock(`def Scope "Scenes" (
1192
+ `+t.output;this.debug&&console.debug(c),i[n]=Zv(c),t.output="",ue.report("export-usdz",{message:"Exporting textures",autoStep:10}),ue.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const h=new Dr({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),d=Object.keys(s).length;ue.report("export-usdz-textures",{totalSteps:d*3,currentStep:0});const u=async g=>{const y=s[g],b=y.texture,f=U0.includes(b.format);let _={imageData:b.image};ue.report("export-usdz-textures",{message:"read back texture",autoStep:!0});const w=y.scale!==void 0&&y.scale.x!==1&&y.scale.y!==1&&y.scale.z!==1&&y.scale.w!==1;(b.isCompressedTexture||b.isRenderTargetTexture||w)&&(_=await kP(b,e.maxTextureSize,h,y.scale)),ue.report("export-usdz-textures",{message:"convert texture to canvas",autoStep:!0});const S=await Uj(_.imageBitmap||_.imageData,e.maxTextureSize).catch(O=>{console.error("Error converting texture to canvas",b,O)});if(S){ue.report("export-usdz-textures",{message:"convert canvas to blob",autoStep:!0});const O=await S.convertToBlob({type:f?"image/png":"image/jpeg",quality:.95});i[`textures/${g}.${f?"png":"jpg"}`]=new Uint8Array(await O.arrayBuffer())}else console.warn("Can`t export texture: ",b)};for(const g in s)await u(g);h.dispose(),ue.end("export-usdz-textures");let m=0;for(const g in i){const y=i[g],b=34+g.length;m+=b;const f=m&63;if(f!==4){const _=64-f,w=new Uint8Array(_);i[g]=[y,{extra:{12345:w}}]}m=y.length}return ue.report("export-usdz","zip archive"),aR(i,{level:0})}};function xP(o,e,t,i){if(!t.exportInvisible&&!o.visible)return;let n,s,r;const a={position:o.position,quaternion:o.quaternion,scale:o.scale};if(o.position.x===0&&o.position.y===0&&o.position.z===0&&(a.position=null),o.quaternion.x===0&&o.quaternion.y===0&&o.quaternion.z===0&&o.quaternion.w===1&&(a.quaternion=null),o.scale.x===1&&o.scale.y===1&&o.scale.z===1&&(a.scale=null),(o instanceof V||o instanceof Bs)&&(s=o.geometry,r=o.material),i&&!i(o)&&(s=void 0,r=void 0),(o instanceof V||o instanceof Bs)&&r&&typeof r=="object"&&(r instanceof Mt||r instanceof Ie||r.isMeshPhysicalNodeMaterial||r instanceof Oe&&r.type==="MeshLineMaterial")){const l=zm(o),c=o instanceof Bs?o:null;n=new vt(o.uuid,l,a,s,r,void 0,c,o.animations)}else if(o instanceof me||o instanceof mu){const l=zm(o);n=new vt(o.uuid,l,a,void 0,void 0,o)}else{const l=zm(o);n=new vt(o.uuid,l,a,void 0,void 0,void 0,void 0,o.animations)}if(n){if(n.displayName=o.userData?.name||o.name,n.visibility=o.visible?void 0:"invisible",e&&e.add(n),e=n,t.extensions)for(const l of t.extensions)l.onExportObject&&l.onExportObject.call(l,o,n,t)}else{const l=zm(o),c=new vt(o.uuid,l,{position:o.position,quaternion:o.quaternion,scale:o.scale});e&&e.add(c),e=c}for(const l of o.children)xP(l,e,t,i)}function SP(o,e,...t){const i={};let n=0;function s(r,a){n++;let l=r.displayName||r.name;l+=" ("+r.uuid+")",(r.geometry||r.material||r.camera||r.skinnedMesh)&&(l+=" ("+(r.geometry?"geo, ":"")+(r.material?"mat, ":"")+(r.camera?"cam, ":"")+(r.skinnedMesh?"skin, ":"")+")"),a[l]={};const c={object:r};r.material&&(c.mat=!0),r.geometry&&(c.geo=!0),r.camera&&(c.cam=!0),r.skinnedMesh&&(c.skin=!0),a[l]._self=c;for(const h of r.children)h&&s(h,a[l])}s(o,i),console.log(e+" ("+n+" nodes)",i,...t)}function CP(o,e){let t=!0;const i=new Array,n=new Array;if(o.children.length===0)t=!0;else{const c=[...o.children];for(const h of c)if(h){const d=CP(h,e);e.debug&&(d?i.push(h):n.push(h)),t=t&&d}}const s=e.allBehaviorTargets.has(o.uuid),r=o.geometry||o.material||o.camera&&!e.quickLookCompatible||o.skinnedMesh||!1,a=e.boneReparentings.has(o.uuid),l=t&&!s&&!r&&!a;return l?(e.debug&&console.log("Pruned object:",(o.displayName||o.name)+" ("+o.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:s,allChildsWerePruned:t,isBoneReparenting:a,object:o,prunedChilds:i,keptChilds:n}),o.parent?.remove(o)):e.debug&&console.log("Kept object:",(o.displayName||o.name)+" ("+o.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:s,allChildsWerePruned:t,isBoneReparenting:a,object:o,prunedChilds:i,keptChilds:n}),l}async function Fj(o,e){ue.start("export-usdz-resources","export-usdz");const t=[];for(const c of o.document.children)PP(c,o,t);const i=t.length;for(let c=0;c<i;c++)ue.report("export-usdz-resources",{totalSteps:i,currentStep:c}),await new Promise((h,d)=>{t[c](),h()});ue.end("export-usdz-resources");const n=new _P,s=o.exporter.sceneAnchoringOptions.ar;n.beginBlock(`def Xform "${o.document.name}"`),n.beginBlock(`def Scope "Scenes" (
1193
1193
  kind = "sceneLibrary"
1194
1194
  )`),n.beginBlock('def Xform "Scene"',"(",!1),n.appendLine('apiSchemas = ["Preliminary_AnchoringAPI"]'),n.appendLine("customData = {"),n.appendLine(" bool preliminary_collidesWithEnvironment = 0"),n.appendLine(' string sceneName = "Scene"'),n.appendLine("}"),n.appendLine('sceneName = "Scene"'),n.closeBlock(")"),n.beginBlock(),n.appendLine(`token preliminary:anchoring:type = "${s.anchoring.type}"`),s.anchoring.type==="plane"&&n.appendLine(`token preliminary:planeAnchoring:alignment = "${s.planeAnchoring.alignment}"`),s.anchoring.type==="image"&&n.appendLine(`rel preliminary:imageAnchoring:referenceImage = </${o.document.name}/Scenes/Scene/AnchoringReferenceImage>`),n.appendLine();const r=c=>{if(!c)return 0;let h=1;for(const d of c.children)h+=r(d);return h},a=r(o.document);ue.start("export-usdz-xforms","export-usdz"),ue.report("export-usdz-xforms",{totalSteps:a,currentStep:1});for(const c of o.document.children)RP(c,n,o);ue.end("export-usdz-xforms"),ue.report("export-usdz","invoke onAfterHierarchy"),await Fm(o,"onAfterHierarchy",n),n.closeBlock(),n.closeBlock(),ue.report("export-usdz","Building materials");const l=Gj(o.materials,o.textures,e.quickLookCompatible);n.appendLine(l),n.closeBlock(),ue.report("export-usdz","write to string"),o.output+=n.toString()}function PP(o,e,t){if(!o)return;const i=o.geometry,n=o.material;if(i)if(n&&("isMeshStandardMaterial"in n&&n.isMeshStandardMaterial||"isMeshBasicMaterial"in n&&n.isMeshBasicMaterial||n.type==="MeshLineMaterial")){const s="geometries/"+D0(i,o.name)+".usda";if(!(s in e.files)){const r=()=>{const a=$j(i,o.skinnedMesh?.skeleton?.bones,e.quickLookCompatible);e.files[s]=Nj(a)};t.push(r)}}else console.warn("NeedleUSDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)",n?.name);n&&e.materials.get(n.uuid)===void 0&&(e.materials[n.uuid]=n);for(const s of o.children)PP(s,e,t)}async function Fm(o,e,t=null){if(o.extensions){for(const i of o.extensions)if(i&&typeof i[e]=="function"){const n=i[e].call(i,o,t);n instanceof Promise&&await n}}}let Bm=null,bi=null,L0,nc,Um;async function kP(o,e=1/0,t=null,i=void 0){L0||(L0=new In(2,2,1,1)),nc||(nc=new oo({uniforms:{blitTexture:new an(o),flipY:new an(!1),scale:new an(new ve(1,1,1,1))},vertexShader:`
1195
1195
  varying vec2 vUv;
@@ -1372,7 +1372,7 @@ ${r.join(`
1372
1372
  `)}`:""}
1373
1373
  }`}function IP(o){return`(${o.r}, ${o.g}, ${o.b})`}function LP(o){return`(${o.x}, ${o.y})`}const U0=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];x("debugusdz");class qt{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+Zi(e)+"_"+qt.global_id++,this.trigger=t,this.action=i}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let s=0;s<this.trigger.length;s++){const r=this.trigger[s];n+="<"+r.id+">",s+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const s of this.trigger)s.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const sc=new Set;function z0(o,e){let t="";if(Array.isArray(o)){sc.clear();let i="[ ";for(let n=0;n<o.length;n++){let s=o[n];if(!s){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}if(typeof s=="string"){if(sc.has(s))continue;i+=s,sc.add(s)}else if(typeof s=="object"){if(s.isObject3D&&(s=e.findById(s.uuid),!s)){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}const r=s.getPath?.call(s);if(sc.has(r))continue;i+=r,sc.add(r)}n+1<o.length&&(i+=", ")}i+=" ]",t=i,sc.clear()}else if(typeof o=="object"){const i=o;if(i.isObject3D&&(o=e.findById(i.uuid)),!o)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",i),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${i.uuid}.`);t=o.getPath?.call(o)}return t}class Rr{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+Rr.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=z0(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 DP(o,e={direct:!0,indirect:!0}){const t=vt.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},o.add(t)}class ei{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new Rr(void 0,"SceneStart");return e.tokenId="SceneTransition",e.type="enter",this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){const i=new Rr(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof vt&&DP(n,t);else e instanceof vt&&DP(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new Rr(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Ca{static global_id=0;static getId(){return this.global_id++}id;actions;loops=0;performCount=1;type="serial";multiplePerformOperation=void 0;constructor(e,t){this.id=e,this.actions=t}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const n=i===this.actions[this.actions.length-1];t.appendLine("<"+i.id+">"+(n?"":", "))}t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops}`),t.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),t.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.appendLine();for(const i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}class ji{static global_id=0;id;tokenId;affectedObjects;easeType;motionType=void 0;duration;moveDistance;style;type;front;up;start;animationSpeed;reversed;pingPong;xFormTarget;audio;gain;auralMode;multiplePerformOperation;velocity;comment;animationName;clone(){const e=new ji,t=e.id;return Object.assign(e,this),e.id=t,e}constructor(e,t){e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+ji.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=z0(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=z0(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&t.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),t.closeBlock()}}class En{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new En(0,1,0)}static get right(){return new En(1,0,0)}static get forward(){return new En(0,0,1)}static get back(){return new En(0,0,-1)}static get zero(){return new En(0,0,0)}}class be{static sequence(...e){return new Ca("Group_"+Ca.getId(),e).makeSequence()}static parallel(...e){return new Ca("Group_"+Ca.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new ji(e);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=t,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(e,t,i=!1,n=!1){const s=new ji(e);s.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,c=t.clipName;if(s.comment=`Animation: ${c}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,s.animationName=c,s.start=r,s.duration=a,s.animationSpeed=l,s.reversed=i,s.pingPong=n,s.multiplePerformOperation="allow",i&&(s.start-=a),n){s.pingPong=!1;const h=s.clone();return h.reversed=!i,h.start=s.start,h.reversed&&(h.start-=a),be.sequence(s,h)}return s}static waitAction(e){const t=new ji;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const s=new ji(e);return s.tokenId="LookAtCamera",s.duration=t===void 0?9999999999999:t,s.front=i??En.forward,s.up=n??En.up,s}static emphasize(e,t,i="bounce",n=1,s="basic"){const r=new ji(e);return r.tokenId="Emphasize",r.duration=t,r.style=s??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,s="inout"){const r=new ji(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?s:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),r.xFormTarget=t,r}static playAudioAction(e,t,i="play",n=1,s="spatial"){const r=new ji(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=s,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new ji(e);return i.tokenId="Impulse",i.velocity=t,i}}class qj{get id(){return this.object.uuid}object;model;constructor(e){this.object=e}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class N0 extends qj{constructor(e,t,i,n){super(e),this.matrix=t,this.material=i,this.geometry=n}matrix;material;geometry;onApply(e){const t=this.model;if(!t)return;t.parent?.isDynamic||vt.createEmptyParent(t);const i=t.clone();this.matrix&&i.setMatrix(this.matrix),this.material&&(i.material=this.material),this.geometry&&(i.geometry=this.geometry),t.parent?.add(i)}_enableAction;_disableAction;enable(){return this._enableAction?this._enableAction:(this._enableAction=be.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=be.fadeAction(this.object,0,!1),this._disableAction)}}class jP{actions;sortedActions;constructor(e){this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}const Mo=x("debugusdzanimation"),$0=x("debugusdzanimationserialization");class Lr{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??Ze.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){return this.clip?.name??"rest"}ext;root;_nearestAnimatedRoot=void 0;clip;speed;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}static isDescendantOf(e,t){let i=t;if(!i||!e)return!1;for(;i;){if(!i)return!1;if(i===e)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){let e;try{for(const t of this.clip?.tracks??[]){const i=nl.parseTrackName(t.name);let n=nl.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||Lr.isDescendantOf(e,n))continue;if(!Lr.isDescendantOf(n,e)){for(;!Lr.isDescendantOf(n,e)&&n.parent;)n=n.parent;Lr.isDescendantOf(n,e)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,e,n)}e=n}}}catch(t){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",t),e=void 0}return e}}class Ze{clip;pos;rot;scale;root;target;duration=0;useRootMotion=!1;static frameRate=60;static animationDurationPadding=6/60;static restPoseClipDuration=6/60;constructor(e,t,i){if(this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=Ze.restPoseClipDuration,i&&i.tracks){const s=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));s!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,s,this.duration),this.duration=s)}const n=P.getComponent(e,Et);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it \u2013 this is likely a bug");return}e.name.endsWith("position")?this.pos=e:e.name.endsWith("quaternion")?this.rot=e:e.name.endsWith("scale")?this.scale=e:(e.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Only .position, .rotation, .scale are supported."),M()&&ge("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){return this.clip?Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){if(!this.clip)return[0,this.duration];const n=this.pos?.times,s=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&s)for(const l of s)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,c)=>l-c),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const s=new v,r=new B,a=new v(1,1,1),l=this.target,c=t?this.pos?.createInterpolant():void 0,h=i?this.rot?.createInterpolant():void 0,d=n?this.scale?.createInterpolant():void 0;c||s.set(l.position.x,l.position.y,l.position.z),h||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),d||a.set(l.scale.x,l.scale.y,l.scale.z);const u=(g,y)=>{const b=g;b&&b.valueSize!==y&&(b.valueSize=y)};u(c,3),u(h,4),u(d,3);const m=0;for(let g=0-m;g<e.length+m;g++){let y=0,b=0;if(g<0?(y=e[0],b=y-Ze.animationDurationPadding/2+1/60):g>=e.length?(y=e[e.length-1],b=y+Ze.animationDurationPadding/2-1/60):(y=e[g],b=y),c){const f=c.evaluate(y);s.set(f[0],f[1],f[2])}if(h){const f=h.evaluate(y);r.set(f[0],f[1],f[2],f[3])}if(d){const f=d.evaluate(y);a.set(f[0],f[1],f[2])}if(this.useRootMotion&&l===this.root){const f=new J;f.compose(s,r,a),f.multiply(l.matrix),f.decompose(s,r,a)}yield{time:b,translation:s,rotation:r,scale:a,index:g}}}}class Vm{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:(Ze.restPoseClipDuration+Ze.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>e&&(e=n)}return e*60}getClipCount(e){return this.rootToRegisteredClip.get(e)?.length??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error("USDZExporter: Missing start time for clip \u2013 please report a bug.",e),0):0}registerAnimation(e,t){if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);Mo&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,s=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const c of t.tracks){const h=nl.parseTrackName(c.name),d=nl.findNode(e,h.nodeName);if(!d){console.warn("no object found for track",c.name,"using "+e.name+" instead");continue}this.dict.has(d)||this.dict.set(d,[]);const u=this.dict.get(d);if(!u){console.warn("no transform data found for target ",d,"at slot "+s+", this is likely a bug");continue}a.delete(d),this.injectRestPoses&&!u[0]&&(console.log("Injecting rest pose",d,t,"at slot",s),u[0]=new Ze(null,d,null));let m=u[s];m||(m=new Ze(e,d,t),u[s]=m),m.addTrack(c),r?.includes(d)||r?.push(d)}Mo&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",s,"for root",e,"targets",r);for(const c of a){const h=this.dict.get(c);if(!h)continue;if(this.injectRestPoses&&!h[0]){console.warn("Adding rest pose for ",c,t,"at slot",s,"This is likely a bug, should have been added earlier.");const u=new Ze(null,c,null);h[0]=u}let d=h[s];d||(Mo&&console.log("Adding padding clip for ",c,t,"at slot",s),d=new Ze(e,c,t),h[s]=d)}const l=new Lr(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),Mo&&console.log({root:e,clip:t,info:l}),t){const c=this.rootToRegisteredClip.get(e);if(c?c.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=Ze.restPoseClipDuration);let h=this.lastClipEndTime+Ze.animationDurationPadding,d=h+t.duration;const u=Math.round(h*60)/60,m=Math.round(d*60)/60;Math.abs(u-h)<.01&&(h=u),Math.abs(m-d)<.01&&(d=m),h=Math.ceil(h),d=h+t.duration,this.clipToStartTime.set(t,h),this.lastClipEndTime=d}}return l}onAfterHierarchy(e){Mo&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){Mo&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const t of this.rootTargetMap.keys()){const i=this.rootTargetMap.get(t);if(!i)continue;let n;const s=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export \u2013 please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets \u2013 please report a bug!",a);for(let l=0;l<a.length;l++){let c=a[l];if(!c){const d=l-(this.injectRestPoses?1:0);a[l]=new Ze(null,r,this.rootToRegisteredClip.get(t)[d]),c=a[l]}const h=c.getDuration();if(s[l]===void 0)s[l]=h;else if(s[l]!==h){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),s[l]=h;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;$0&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){P.foreachComponent(e,s=>{const r=s;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new Xj(e,this);this.serializers.push(n),n.registerCallback(t)}}class Xj{model=void 0;object;animationData;ext;callback;constructor(e,t){this.object=e,this.animationData=t.animationData,this.ext=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),$0&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,s=this.animationData;if(n&&n.skinnedMesh){let r=function(E){const z=[];for(const[Y,K]of E){let ne=`${Y} : [`;const ae=[];for(const te of K)ae.push(`(${pe(te.x)}, ${pe(te.y)}, ${pe(te.z)})`);ne=ne.concat(ae.join(", ")),ne=ne.concat("],"),z.push(ne)}return z},a=function(E){const z=[];for(const[Y,K]of E){let ne=`${Y} : [`;const ae=[];for(const te of K)ae.push(`(${pe(te.w)}, ${pe(te.x)}, ${pe(te.y)}, ${pe(te.z)})`);ne=ne.concat(ae.join(", ")),ne=ne.concat("],"),z.push(ne)}return z},l=function(E){let z,Y=!0;const K=new Map;for(const[ae,te]of E){z===void 0&&(z=te.length),z!==te.length&&(Y=!1);let _e=0;for(const Qt of te)_e++,Qt||(K.has(ae)||K.set(ae,[]),K.get(ae).push(_e))}Mo&&console.log("Bone count: ",E.size,"TransformData entries per bone: ",z,"Undefined bone entries: ",K),console.assert(Y,"All bones should have the same number of TransformData entries",E),console.assert(K.size===0,"All TransformData entries should be set",K);const ne=[];for(const[ae,te]of E)for(let _e=0;_e<te.length;_e++){const Qt=te[_e],tl=i.getStartTimeByClip(Qt.clip);ne.length<=_e&&ne.push({pos:[],rot:[],scale:[],timeOffset:tl});const js=ne[_e];js.pos.push(...Qt.getSortedTimesArray(!0,!1,!1)),js.rot.push(...Qt.getSortedTimesArray(!1,!0,!1)),js.scale.push(...Qt.getSortedTimesArray(!1,!1,!0))}for(const ae of ne)ae.pos.sort((te,_e)=>te-_e),ae.rot.sort((te,_e)=>te-_e),ae.scale.sort((te,_e)=>te-_e),ae.pos=[...new Set(ae.pos)],ae.rot=[...new Set(ae.rot)],ae.scale=[...new Set(ae.scale)];return ne},c=function(E,z,Y){const K=new Map,ne=new Map,ae=new Map,te=z.length;for(const _e of Y){const Qt=E.get(_e);let tl;Qt?console.assert(Qt.length===te,"We should have the same number of TransformData entries for each bone",Qt,z):tl=new Ze(null,_e,null);for(let js=0;js<te;js++){const of=Qt?Qt[js]:tl,il=z[js];for(const{time:Hc,translation:qc}of of.getValues(il.pos,!0,!1,!1)){const An=(Hc+il.timeOffset)*60;K.has(An)||K.set(An,new Array),K.get(An).push(qc.clone())}for(const{time:Hc,rotation:qc}of of.getValues(il.rot,!1,!0,!1)){const An=(Hc+il.timeOffset)*60;ne.has(An)||ne.set(An,new Array),ne.get(An).push(qc.clone())}for(const{time:Hc,scale:qc}of of.getValues(il.scale,!1,!1,!0)){const An=(Hc+il.timeOffset)*60;ae.has(An)||ae.set(An,new Array),ae.get(An).push(qc.clone())}}}return{position:K.size==0?void 0:K,quaternion:ne.size==0?void 0:ne,scale:ae.size==0?void 0:ae}},h=function(E){const z=[];for(const Y of E)z.push(`(${pe(Y.x)}, ${pe(Y.y)}, ${pe(Y.z)})`);return z.join(", ")},d=function(E){const z=[];for(const Y of E)z.push(`(${pe(Y.w)}, ${pe(Y.x)}, ${pe(Y.y)}, ${pe(Y.z)})`);return z.join(", ")},u=function(E){const z=new Map;if(Mo){const Y=new Array;for(const[K,ne]of s)Y.push(K.uuid+": "+ne.length+" "+ne.map(ae=>ae.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
1374
1374
  `+Y.join(`
1375
- `))}for(const Y of E){const K=s.get(Y);K&&z.set(Y,K)}return z},m=function(E){const z=u(E),Y=l(z);return c(z,Y,E)};const g=n.skinnedMesh.skeleton,y=new Array,b=[],f=[];for(const E of g.bones){b.push(E),f.push(E.uuid);const z=g.boneInverses[g.bones.indexOf(E)];y.push({bone:E,inverse:z})}let _=1e4;for(;f.length<g.bones.length&&_-- >0;)for(const E of b){const z=E.children;for(const Y of z)if(f.indexOf(Y.uuid)===-1&&g.bones.indexOf(Y)!==-1){b.push(Y),f.push(Y.uuid);const K=g.boneInverses[g.bones.indexOf(Y)];y.push({bone:Y,inverse:K})}}_<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,g.bones,f);for(const E of bP(g.bones))y.push({bone:E,inverse:E.matrixWorld.clone().invert()});const w=y[0].bone.parent;w||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),y.sort((E,z)=>oc(E.bone,w)>oc(z.bone,w)?1:-1);const S=t.quickLookCompatible,O=[],L=[],D=[],W=[];for(const{bone:E}of y){if(S){const z=E.scale;z.x==0&&(z.x=1e-5),z.y==0&&(z.y=1e-5),z.z==0&&(z.z=1e-5),O.push(new J().compose(E.position,E.quaternion,E.scale))}else O.push(E.matrix.clone());L.push(E.position),D.push(E.quaternion),W.push(E.scale)}const $=y.map(E=>'"'+oc(E.bone,w)+'"').join(", "),H=y.map(E=>TP(E.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${H}]`),e.appendLine(`uniform token[] joints = [${$}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${O.map(E=>TP(E)).join(", ")}]`);const G=m(y.map(E=>E.bone));if(Mo){let E=1e7,z=0;for(const Y of G.position?.keys()??[])E=Math.min(E,Y),z=Math.max(z,Y);console.log("Time samples",E,z,G)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${$}]`),e.appendLine(`quatf[] rotations = [${d(D)}]`),G&&G.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const E=a(G.quaternion);for(const z of E)e.appendLine(z);e.closeBlock()}if(e.appendLine(`half3[] scales = [${h(W)}]`),G&&G.scale){e.beginBlock("half3[] scales.timeSamples = {","");const E=r(G.scale);for(const z of E)e.appendLine(z);e.closeBlock()}if(e.appendLine(`float3[] translations = [${h(L)}]`),G&&G.position){e.beginBlock("float3[] translations.timeSamples = {","");const E=r(G.position);for(const z of E)e.appendLine(z);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let h=0;h<i.length;h++)i[h]===void 0&&(i[h]=new Ze(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const s=this.object,r=this.model,a=this.animationData.get(s);if(!a||s.isSkinnedMesh)return;$0&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function c(h,d){if(h.some(u=>u&&{position:u.pos,rotation:u.rot,scale:u.scale}[d])){switch(d){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let u=0;u<h.length;u++){const m=h[u];if(!m)continue;const g=n.getStartTimeByClip(m.clip),y=m.getSortedTimesArray(d==="position",d==="rotation",d==="scale");if(!y||y.length===0){console.error("got an animated object but no time values?",s,m);continue}const b=!m.clip,f=d==="position"&&(m.pos||b),_=d==="rotation"&&(m.rot||b),w=d==="scale"&&(m.scale||b);if(f||_||w){const S=m.clip?.name??"rest",O=m.getDuration();Mo&&console.log("Write .timeSamples:",S,g,O,h),e.appendLine("# "+S+": start="+l.format(g*Ze.frameRate)+", length="+l.format(O*Ze.frameRate)+", frames="+m.getFrames())}if(f)for(const{time:S,translation:O}of m.getValues(y,!0,!1,!1)){const L=`${l.format((g+S)*Ze.frameRate)}: (${pe(O.x)}, ${pe(O.y)}, ${pe(O.z)}),`;e.appendLine(L)}if(_)for(const{time:S,rotation:O}of m.getValues(y,!1,!0,!1)){const L=`${l.format((g+S)*Ze.frameRate)}: (${pe(O.w)}, ${pe(O.x)}, ${pe(O.y)}, ${pe(O.z)}),`;e.appendLine(L)}if(w)for(const{time:S,scale:O}of m.getValues(y,!1,!1,!0)){const L=`${l.format((g+S)*Ze.frameRate)}: (${pe(O.x)}, ${pe(O.y)}, ${pe(O.z)}),`;e.appendLine(L)}}e.closeBlock()}}c(a,"position"),c(a,"rotation"),c(a,"scale")}}const Qj=x("debugusdz");class Ya{static getName(e){const t=e.split(".").pop();let i=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),Zi(i)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=P.getComponents(e,Yi);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const r=s.clip.split("/").pop()||"Audio",a=Ya.getName(s.clip),l=Zi(a);if(!this.files.some(c=>c.path===s.clip)){this.files.push({path:s.clip,name:a});const c=a.toLowerCase();i.quickLookCompatible&&!c.endsWith(".mp3")&&!c.endsWith(".wav")&&!c.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(c,h)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${r}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){Qj&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const n=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}}}var Yj=Object.defineProperty,He=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Yj(e,t,n),n};const FP=x("debugusdzbehaviours");class Pa extends T{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new v;targetRot=new B;targetScale=new v;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){const t=this.object?.getComponentsInChildren(rt);if(t)for(const i of t)i.resetVelocities(),i.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;const e=le(this.object).clone(),t=le(this.target).clone(),i=Re(this.object).clone(),n=Re(this.target).clone(),s=Je(this.object).clone(),r=Je(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),c=s.distanceTo(r);if(a<.01&&l<.01&&c<.01){Vi(this.object,t),Fn(this.object,n),hl(this.object,r),this.coroutine=null;return}let h=0,d=0;for(;h<1;)h+=this.context.time.deltaTime/this.duration,h>1&&(h=1),d=h<.5?4*h*h*h:1-Math.pow(-2*h+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(i,n,d),this.targetScale.lerpVectors(s,r,d),Vi(this.object,this.targetPos),Fn(this.object,this.targetRot),hl(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),s=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(s),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new qt("Move to "+this.target?.name,ei.tapTrigger(this.gameObject),be.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}He([p(R)],Pa.prototype,"object"),He([p(R)],Pa.prototype,"target"),He([p()],Pa.prototype,"duration"),He([p()],Pa.prototype,"relativeMotion");const Gm=class _i extends T{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,M()&&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 t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof V)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):Ax(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],_i._materialTriggersPerId={},_i.variantSwitchIndex=0,this.materialToSwitch&&await We.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await We.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(_i._materialTriggersPerId[this.materialToSwitch.uuid]||(_i._materialTriggersPerId[this.materialToSwitch.uuid]=[]),_i._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=_i._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const s of i){const r=s.createVariants();r&&r.length>0&&(n[s.selfModel.uuid]=r)}for(const s of i){const r=[];for(const a in n)a!==s.selfModel.uuid&&r.push(...n[a]);s.createAndAttachBehaviors(e,n[s.selfModel.uuid],r)}}delete _i._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],s=Math.max(0,this.fadeDuration);n.push(be.fadeAction([...this.targetModels,...i],s,!1)),n.push(be.fadeAction(t,s,!0)),e.addBehavior(new qt("Select_"+this.selfModel.name,ei.tapTrigger(this.selfModel),be.parallel(...n))),_i._parallelStartHiddenActions.push(...t),_i._startHiddenBehaviour||(_i._startHiddenBehaviour=new qt("StartHidden_"+this.selfModel.name,ei.sceneStartTrigger(),be.fadeAction(_i._parallelStartHiddenActions,s,!1)),e.addBehavior(_i._startHiddenBehaviour))}static getMaterialName(e){return Zi(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+_i.variantSwitchIndex+++"_"+_i.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&vt.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};He([p(ke)],Gm.prototype,"materialToSwitch"),He([p(ke)],Gm.prototype,"variantMaterial"),He([p()],Gm.prototype,"fadeDuration");let W0=Gm;const dd=class Ke extends T{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,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[Ke.wasVisible]===void 0&&(this.gameObject[Ke.wasVisible]=this.gameObject.activeSelf),this.target[Ke.wasVisible]===void 0&&(this.target[Ke.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[Ke.wasVisible],this.targetStateBeforeCreatingDocument=this.target[Ke.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&I0.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[Ke.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggle"+Ke.clonedToggleIndex++,i.add(l),this.gameObject[Ke.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[Ke.toggleClone];if(!this.gameObject[Ke.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggleReverse"+Ke.clonedToggleIndex++,i.add(l),this.gameObject[Ke.reverseToggleClone]=l}this.toggleModel=this.gameObject[Ke.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(be.fadeAction(n,0,!1)),a.push(be.fadeAction(this.toggleModel,0,!0)),a.push(be.fadeAction(this.targetModel,0,s)),e.addBehavior(new qt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),ei.tapTrigger(n),be.parallel(...a)));const l=[];l.push(be.fadeAction(this.toggleModel,0,!1)),l.push(be.fadeAction(n,0,!0)),l.push(be.fadeAction(this.targetModel,0,!s)),e.addBehavior(new qt("Toggle_"+n.name+"_ToggleTo"+(s?"Off":"On"),ei.tapTrigger(this.toggleModel),be.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(be.fadeAction(n,0,!1)),a.push(be.fadeAction(this.targetModel,0,s)),e.addBehavior(new qt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),ei.tapTrigger(n),a.length>1?be.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),Rn.add(r,e)}}afterSerialize(e,t){this.gameObject[Ke.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[Ke.wasVisible],delete this.gameObject[Ke.wasVisible]),this.target&&this.target[Ke.wasVisible]!==void 0&&(this.target.visible=this.target[Ke.wasVisible],delete this.target[Ke.wasVisible]),delete this.gameObject[Ke.toggleClone],delete this.gameObject[Ke.reverseToggleClone]}};He([p(R)],dd.prototype,"target"),He([p()],dd.prototype,"toggleOnClick"),He([p()],dd.prototype,"targetState"),He([p()],dd.prototype,"hideSelf");let V0=dd;class Rn extends T{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)Rn._fadeObjects.includes(n)||(console.log("adding hide on start",n),Rn._fadeObjects.push(n));Rn._fadeBehaviour===void 0&&(Rn._fadeBehaviour=new qt("HideOnStart",ei.sceneStartTrigger(),be.fadeAction(Rn._fadeObjects,0,!1)),t.addBehavior(Rn._fadeBehaviour))}start(){P.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Rn.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=P.isActiveSelf(this.gameObject)}}class rc extends T{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,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new qt("emphasize "+this.name,ei.tapTrigger(this.gameObject),be.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}He([p()],rc.prototype,"target"),He([p()],rc.prototype,"duration"),He([p()],rc.prototype,"motionType");class lr extends T{target;clip="";toggleOnClick=!1;trigger="tap";ensureAudioSource(){if(!this.target){const e={spatialBlend:1,volume:1,loop:!1,clip:this.clip,preload:!0},t=this.gameObject.addComponent(Yi,e);t&&(this.target=t)}}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Play audio: "+(this.clip||this.target?.clip||"unknown clip"),hidden:!1}),this.ensureAudioSource()}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,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const s=this.target?this.target.gameObject:this.gameObject;Ya.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(u=>{u instanceof V&&u.visible&&(l=!0)}),l=!0;const c=e.addAudioClip(n);let h=be.playAudioAction(s,c,"play",r,a);this.target&&this.target.loop&&(h=be.sequence(h).makeLooping());const d=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(h.multiplePerformOperation="stop");const u=new qt("playAudio"+d,ei.tapTrigger(t),h);e.addBehavior(u)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const u=new qt("playAudioOnStart"+d,ei.sceneStartTrigger(),h);e.addBehavior(u)}}}}He([p(Yi)],lr.prototype,"target"),He([p(URL)],lr.prototype,"clip"),He([p()],lr.prototype,"toggleOnClick");const G0=class No extends T{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=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(No.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';M()&&ge(e),console.warn(e,...No.rootsWithExclusivePlayback)}No.animationActions=[],No.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof Vm);if(!n)return;const s=n.getClipCount(this.target)>1;s&&(M()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),No.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=No.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),c=new qt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?ei.tapTrigger(this.selfModel):ei.sceneStartTrigger(),l);s&&c.makeExclusive(!0),e.addBehavior(c)}})}static getActionForSequences(e,t,i,n,s){const r=(l,c)=>{let h=No.animationActions.find(d=>d.affectedObjects==l&&d.start==c.start&&d.duration==c.duration&&d.animationSpeed==c.speed);return h||(h=be.startAnimationAction(l,c),No.animationActions.push(h)),h},a=be.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:be.sequence();for(const c of n)l.addAction(r(t,c));l.makeLooping(),a!==l&&a.addAction(l)}return s&&s>0&&a.actions.unshift(be.waitAction(s)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(Et),s=t.getComponent(Zt);if(!n&&!s)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(s){const g=e.registerAnimation(t,s.clip);g&&(s.loop?a.push(g):r.push(g));let y=0;if(s.minMaxOffsetNormalized){const b=s.minMaxOffsetNormalized.x,f=s.minMaxOffsetNormalized.y;y=(s.clip?.duration||1)*(b+Math.random()*(f-b))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:y}}const l=n?.runtimeAnimatorController;let c=l?.findState(i),h=[],d=[];if(l&&c){const g=new Array;g.push(c);let y=!1;for(;g.length<100;){if(!c||c===null||!c.transitions||c.transitions.length===0){c.motion?.isLooping&&(y=!0);break}const b=c.transitions.find(_=>_.conditions.length===0),f=b?l.getState(b.destinationState,0):null;if(f&&g.includes(f)){c=f,y=!0;break}else if(b){if(c=f,!c)break;g.push(c)}else{y=c.motion?.isLooping??!1;break}}if(y&&c){const b=g.indexOf(c);h=g.slice(0,b),d=g.slice(b),FP&&console.log("found loop from "+i,"states until loop",h,"states looping",d)}else h=g,d=[],FP&&console.log("found no loop from "+i,"states",h);if(!d.length){const b=h[h.length-1],f=b.motion?.clip;if(f){let _;if(e.holdClipMap.has(f))_=e.holdClipMap.get(f);else{const w=b.name+"_hold";_=f.clone(),_.duration=1,_.name=w;const S=f.duration;_.tracks=f.tracks.map(O=>{const L=O.clone();L.times=new Float32Array([0,S]);const D=O.values.length,W=O.getValueSize(),$=O.values.slice(D-W,D);return L.values=new Float32Array(2*W),L.values.set($,0),L.values.set($,W),L}),_.name=w,e.holdClipMap.set(f,_)}if(_){const w={name:_.name,motion:{clip:_,isLooping:!1,name:_.name},speed:1,transitions:[],behaviours:[],hash:b.hash+1};d.push(w)}}}}if(h.length===1&&(!h[0].motion?.clip||h[0].motion?.clip.tracks?.length===0)){r=new Array;const g=e.registerAnimation(t,null);g&&r.push(g);return}if(h=h.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),d=d.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),h.length===0&&d.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const u=(g,y)=>{if(!t)return;const b=e.registerAnimation(t,g.motion.clip??null);b?(b.speed=g.speed,y.push(b)):console.warn("Couldn't register animation for state "+g.name+" on "+n?.name)};if(h.length>0){r=new Array;for(const g of h)u(g,r)}if(d.length>0){a=new Array;for(const g of d)u(g,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const g=n.minMaxOffsetNormalized.x,y=n.minMaxOffsetNormalized.y;m=((h.length?h[0]:d.length?d[0]:null)?.motion.clip?.duration||1)*(g+Math.random()*(y-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=No.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};He([p(Et)],G0.prototype,"animator"),He([p()],G0.prototype,"stateName");let ud=G0;class ac extends T{getType(){}target;getDuration(){}}He([p(R)],ac.prototype,"target");class pd extends T{target}He([p(ac)],pd.prototype,"target");class md extends ac{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}He([p()],md.prototype,"type"),He([p()],md.prototype,"duration");class H0 extends pd{}let Hm;function Kj(o){Hm=o}function Zj(){if(!Hm)return null;const o=Hm.find();return o?{handler:o,created:!1}:{handler:Hm.create(),created:!0}}const Jj=100,e3=200,t3=300;class Tr{static _instance;static create(){return new Tr}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return On.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=I.supportsQuickLookAR();let i="View in AR";I.isVisionOS()?i="View in AR":(t||I.isiOS())&&(i="Open in Quicklook"),e.innerText=i,e.prepend(Tt("view_in_ar")),Ph.setElementPriority(e,e3);let n=!1,s=null;return e.addEventListener("click",()=>{const r=Zj();r&&(s=r.handler,n=r.created),n&&s&&(s.objectToExport=Q.Current.scene),s?(e.classList.add("this-mode-is-requested"),s.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(a=>{e.classList.remove("this-mode-is-requested"),console.error(a)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.title="Click to start an AR session";const n=()=>{i.innerText="Enter AR",i.prepend(Tt("view_in_ar"))};n();let s;return i.addEventListener("click",()=>{q.start(t,e),I.isiOS()&&!I.isVisionOS()&&setTimeout(()=>{i.innerHTML="Tap again",i.prepend(Tt("view_in_ar")),clearTimeout(s),s=setTimeout(n,4e3)},500)}),Ph.setElementPriority(i,t3),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(Tt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>q.start(t,e)),Ph.setElementPriority(i,Jj),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(Tt("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&Fe("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{q.isSessionSupported("immersive-vr").then(i=>{t.style.display=i?"none":""})}),t}createQRCode(){return On.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!(t==="immersive-ar"&&I.isiOS()&&!I.isVisionOS())){if(!("xr"in navigator)){e.style.display="none";return}q.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",M()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device. Make sure your server runs using HTTPS and you have a device connected that supports '+t)})}}hideElementDuringXRSession(e){wp(t=>{e["previous-display"]=e.style.display,e.style.setProperty("display","none","important")}),Yy(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(q.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),q.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var i3=Object.defineProperty,n3=Object.getOwnPropertyDescriptor,jt=(o,e,t,i)=>{for(var n=i>1?void 0:i?n3(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&i3(e,t,n),n};const gd=x("debugspriterenderer"),o3=x("wireframe");class Za{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&Za.cache[e.guid])return gd&&console.log("Take cached geometry for sprite",e.guid),Za.cache[e.guid];const t=new Ln;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let s=0;s<e.triangles.length;s+=1){const r=e.triangles[s];i[s*3]=-e.vertices[r].x,i[s*3+1]=e.vertices[r].y,i[s*3+2]=0;const a=e.uv[r];n[s*2]=a.x,n[s*2+1]=1-a.y}return t.setAttribute("position",new lt(i,3)),t.setAttribute("uv",new lt(n,2)),e.guid&&(this.cache[e.guid]=t),gd&&console.log("Built sprite geometry",e,t),t}}class s3{x;y}function BP(o){o&&(o.colorSpace!=Yo&&(o.colorSpace=Yo,o.needsUpdate=!0),o.minFilter==_u&&o.magFilter==_u&&(o.anisotropy=1,o.needsUpdate=!0))}let ys=class{constructor(o){o&&(this.texture=o,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new V(Za.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&BP(this.texture),this._material=new Ie({map:this.texture,color:16777215,side:Bi,transparent:!0})),this._material}_material;getGeometry(){return Za.getOrCreateGeometry(this)}};jt([p()],ys.prototype,"guid",2),jt([p(Pe)],ys.prototype,"texture",2),jt([it()],ys.prototype,"triangles",2),jt([it()],ys.prototype,"uv",2),jt([it()],ys.prototype,"vertices",2);const q0=Symbol("spriteOwner");class lc{sprites;constructor(){this.sprites=[]}}jt([p(ys)],lc.prototype,"sprites",2);const X0=class Sv{static create(){const e=new Sv;return e.spriteSheet=new lc,e}constructor(){}clone(){const e=new Sv;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new lc,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(BP(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;We.assignTextureLOD(n,0).then(r=>{r instanceof Pe&&(i.texture=r,e?.map===s&&(e.map=r,e.needsUpdate=!0))})}}};jt([p(lc)],X0.prototype,"spriteSheet",2),jt([p()],X0.prototype,"index",2);let cc=X0;class Ri extends T{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=cc.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.round(e);gd&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof ys?(this._spriteSheet||(this._spriteSheet=cc.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=cc.create(),gd&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return gd&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=Za.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new Ie({color:16777215,side:Bi});if(o3&&(n.wireframe=!0),this.color&&(n.color||(n.color=new oe),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let s=i.texture;s[q0]!==void 0&&s[q0]!==this&&this.spriteFrames>1&&(s=i.texture=s.clone()),s[q0]=this,n.map=s}this.sharedMaterial=n,this._currentSprite=new V(Za.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),We.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}jt([p()],Ri.prototype,"drawMode",2),jt([p(s3)],Ri.prototype,"size",2),jt([p(he)],Ri.prototype,"color",2),jt([p(ke)],Ri.prototype,"sharedMaterial",2),jt([p()],Ri.prototype,"transparent",2),jt([p()],Ri.prototype,"cutoutThreshold",2),jt([p()],Ri.prototype,"castShadows",2),jt([p()],Ri.prototype,"renderOrder",2),jt([p()],Ri.prototype,"toneMapped",2),jt([p(cc)],Ri.prototype,"sprite",1);const fd=x("debugwebxr"),Q0=x("debugartouch"),r3=new J().makeRotationY(Math.PI),UP=new v(1,1,1),qm=new J,yd=new J;function a3(o,e,t=1e-6){for(let i=0;i<16;i++)if(Math.abs(o.elements[i]-e.elements[i])>t)return!1;return!0}class Tn extends T{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){e=Math.max(1e-6,e),e!==this._arScale&&(this._arScale=e,this.onSetScale())}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!0;_isPlacing=!0;_startOffset=new J;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new Fi;_reticle=[];_hitRefPoses=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;_pendingAnchorPose=null;_anchorLastLocalPose=new J;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){fd&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,this._pendingAnchorPose=null,this._hitRefPoses.length=0,Tn._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new R;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Si(this._placementScene.children),n=i.getCenter(new v),s=i.getSize(new v),r=new J;r.makeTranslation(n.x,n.y-s.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),P.addComponent(t,this);for(const i of this._reticle)ki(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Hs.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Hs.Early}),this.onRevertSceneChanges(),this._anchor=null,this._pendingAnchorPose=null,Tn._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const s=n.getHitTest();s&&(i=!0,this.updateReticleAndHits(e.xr,n.index,s,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else if(this.useXRAnchor&&this.updateXRAnchor(e.xr),this.arTouchTransform?(this.userInput||(this.userInput=new tf(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale)}this.userInput.reset()}}updateReticleAndHits(e,t,i,n){if(this.useXRAnchor){const r=e.referenceSpace,a=r?i.hit.getPose(r):void 0;if(a){let l=this._hitRefPoses[t];l||(l=this._hitRefPoses[t]={x:0,y:0,z:0,qx:0,qy:0,qz:0,qw:1});const{position:c,orientation:h}=a.transform;l.x=c.x,l.y=c.y,l.z=c.z,l.qx=h.x,l.qy=h.y,l.qz=h.z,l.qw=h.w}}let s=this._reticle[t];if(!s){if(this.customReticle)if(this.customReticle.asset)s=Ks(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else s=new V(new LM(.07,.09,32).rotateX(-Math.PI/2),new Ie({side:Bi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),s.name="AR Placement Reticle";if(fd){const r=new Ui(1);r.position.y+=.01,s.add(r)}this._reticle[t]=s,s.matrixAutoUpdate=!1,s.visible=!1}if(s.lastPos=s.lastPos||i.position.clone(),s.lastQuat=s.lastQuat||i.quaternion.clone(),s.position.copy(s.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),s.lastPos.copy(s.position),s.quaternion.copy(s.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),s.lastQuat.copy(s.quaternion),s.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(s),s.updateMatrix(),s.visible=!0,s.parent!==this.context.scene&&this.context.scene.add(s),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(s.quaternion),this.upVec.dot(U(0,1,0))>.9){let r=s["autoplace:timer"]||0;r>=1?(s.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,s["autoplace:timer"]=r)}else s["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(q.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=0;if(e&&e.origin instanceof Vy){const n=this._reticle[e.origin.index];n&&(t=n,i=e.origin.index)}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),Tn._hasPlaced=!0,this.useXRAnchor){const n=this._hitRefPoses[i];n?this._pendingAnchorPose={...n}:(console.warn("[WebARSessionRoot] can not create a XR anchor: no hit pose was captured for the placement"),M()&&ge("Can not create XR anchor: no hit pose available"))}if(this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!Tn._hasPlaced)return;const e=q.active?.rig?.gameObject;if(e){const t=q.active?.rigScale||1,i=1/this._arScale*t,n=new J().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)e.comp.destroyed||Ys(e.originalObject)||P.addComponent(e.originalObject,e.comp);this._reparentedComponents.length=0}updateXRAnchor(e){const t=e.referenceSpace;if(!t)return;const i=e.frame;if(this._pendingAnchorPose){const a=this._pendingAnchorPose;if(this._pendingAnchorPose=null,typeof i.createAnchor!="function"||e.session.enabledFeatures?.includes("anchors")===!1){(fd||M())&&(console.warn("[WebARSessionRoot] useXRAnchor is enabled but WebXR anchors are not supported by this session"),ge("WebXR anchors are not supported by this session"));return}const l=new XRRigidTransform({x:a.x,y:a.y,z:a.z},{x:a.qx,y:a.qy,z:a.qz,w:a.qw}),c=e.convertSpace(l);this._anchorLastLocalPose.compose(c.position,c.quaternion,UP),i.createAnchor(l,t).then(h=>{e.running&&!this._isPlacing?(this._anchor=h,fd&&console.log("[WebARSessionRoot] created XR anchor",h)):h.delete()}).catch(h=>{console.warn("[WebARSessionRoot] failed to create XR anchor",h),M()&&ge("Failed to create XR anchor")});return}if(!this._anchor)return;const n=e.rig?.gameObject;if(!n)return;const s=i.getPose(this._anchor.anchorSpace,t);if(!s)return;const r=e.convertSpace(s.transform);if(qm.compose(r.position,r.quaternion,UP),!a3(qm,this._anchorLastLocalPose)&&(yd.copy(qm).invert().premultiply(this._anchorLastLocalPose),this._anchorLastLocalPose.copy(qm),n.updateMatrix(),n.matrix.multiply(yd),n.matrix.decompose(n.position,n.quaternion,n.scale),fd)){const a=yd.elements[12],l=yd.elements[13],c=yd.elements[14];console.log(`[WebARSessionRoot] applied XR anchor correction: ${(Math.hypot(a,l,c)*1e3).toFixed(2)}mm`)}}upVec=new v(0,1,0);lookPoint=new v;worldUpVec=new v(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,s=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=s.y,e.lookAt(n))}onApplyPose(e){const t=q.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(r3),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class tf{static up=new v(0,1,0);static zero=new v(0,0,0);static one=new v(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new J,this.plane=new rl,this.plane.setFromNormalAndCoplanarPoint(tf.up,tf.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)}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDown),this.context.input.addEventListener("pointermove",this.onPointerMove),this.context.input.addEventListener("pointerup",this.onPointerUp))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDown),this.context.input.removeEventListener("pointermove",this.onPointerMove),this.context.input.removeEventListener("pointerup",this.onPointerUp),this._tracked.clear(),this._hasTwoFingerRef=!1)}_tracked=new Map;_hasTwoFingerRef=!1;_lastTwoFingerAngle=0;_lastTwoFingerDist=0;_resyncGesture=!1;isPointerUsed(e){return this.context.input.getIsPointerIdInUse(e)}onPointerDown=e=>{if(e.mode==="screen"&&e.button===0){if(e.used||this.isPointerUsed(e.pointerId)){M()&&console.debug(`[WebARSessionRoot] AR touch #${e.pointerId} ignored for touch transform: pointer is used (grabbed by a component)`);return}this._tracked.set(e.pointerId,new ee(e.clientX,e.clientY)),Q0?console.debug(`[ARTouch] down #${e.pointerId} (${e.clientX.toFixed(0)}, ${e.clientY.toFixed(0)}) type=${e.pointerType} tracked=${this._tracked.size}`):M()&&console.debug(`[WebARSessionRoot] AR touch #${e.pointerId} down (tracked fingers: ${this._tracked.size})`),this._hasTwoFingerRef=!1,this._resyncGesture=!0}};onPointerMove=e=>{if(e.mode!=="screen")return;const t=this._tracked.get(e.pointerId);if(!t)return;if(this.isPointerUsed(e.pointerId)){M()&&console.debug(`[WebARSessionRoot] AR touch #${e.pointerId} dropped from touch transform: pointer became used mid-gesture`),this._tracked.delete(e.pointerId),this._hasTwoFingerRef=!1,this._resyncGesture=!0;return}const i=e.clientX,n=e.clientY;if(this._resyncGesture){t.set(i,n),this._resyncGesture=!1,this._hasTwoFingerRef=!1;return}if(this._tracked.size===1)this.oneFingerDrag&&this.pixelToGround(i,n,this._curW)&&this.pixelToGround(t.x,t.y,this._prevW)&&this.addMovement(this._curW.x-this._prevW.x,this._curW.z-this._prevW.z),t.set(i,n);else if(this._tracked.size===2){t.set(i,n);const s=this._tracked.values(),r=s.next().value,a=s.next().value,l=Math.atan2(a.y-r.y,a.x-r.x),c=r.distanceTo(a);if(Q0&&console.debug(`[ARTouch] move #${e.pointerId} (${i.toFixed(0)}, ${n.toFixed(0)}) a=(${r.x.toFixed(0)}, ${r.y.toFixed(0)}) b=(${a.x.toFixed(0)}, ${a.y.toFixed(0)}) dist=${c.toFixed(1)} last=${this._lastTwoFingerDist.toFixed(1)} ref=${this._hasTwoFingerRef}`),this._hasTwoFingerRef){if(this.twoFingerRotate){const h=l-this._lastTwoFingerAngle;Math.abs(h)>.001&&this.addRotation(h)}if(this.twoFingerScale&&this._lastTwoFingerDist>1&&c>1){let h,d;if(this.pixelToGround((r.x+a.x)/2,(r.y+a.y)/2,this._pivotW))h=this._pivotW.x,d=this._pivotW.z;else{const u=this.context.mainCamera;h=u?.worldPosition.x??0,d=u?.worldPosition.z??0}this.applyScaleRatio(c/this._lastTwoFingerDist,h,d)}}this._lastTwoFingerAngle=l,this._lastTwoFingerDist=c,this._hasTwoFingerRef=!0}};onPointerUp=e=>{e.mode==="screen"&&(Q0&&console.debug(`[ARTouch] up #${e.pointerId} (${e.clientX.toFixed(0)}, ${e.clientY.toFixed(0)}) tracked=${this._tracked.size-(this._tracked.has(e.pointerId)?1:0)}`),this._tracked.delete(e.pointerId),this._hasTwoFingerRef=!1,this._resyncGesture=!0,this._tracked.size<2&&this._gestureScale!==1&&(M()&&console.debug(`[WebARSessionRoot] pinch scale gesture ended: total \xD7${this._gestureScale.toFixed(3)}, rig scale now ${(q.active?.rigScale??1).toFixed(3)}`),this._gestureScale=1))};_raycaster=new df;_screenPos=new v;_camPos=new v;_curW=new v;_prevW=new v;_pivotW=new v;_gestureScale=1;pixelToGround(e,t,i){const n=this.context.mainCamera;if(!n)return!1;this._screenPos.set(e/window.innerWidth*2-1,-(t/window.innerHeight)*2+1,1),this._screenPos.unproject(n),this._camPos.copy(n.worldPosition);const s=this._screenPos.sub(this._camPos).normalize();return Math.abs(s.y)<.08?!1:(this._raycaster.set(this._camPos,s),this._raycaster.ray.intersectPlane(this.plane,i)!==null)}addMovement(e,t){e/=this._scale,t/=this._scale,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new J;applyScaleRatio(e,t,i){if(!isFinite(e)||e<=0||e===1)return;this._scale*=1/e,this._gestureScale*=e;const n=this._tempMatrix.makeScale(e,e,e);n.elements[12]=t*(1-e),n.elements[14]=i*(1-e),this.offset.premultiply(n),this._hasChanged=!0}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}var l3=Object.defineProperty,Xm=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&l3(e,t,n),n};const ti=x("debugplayersync"),Qm=class CO extends T{static async setupFrom(e,t){let i;if(typeof e=="string"){if(i=ie.getOrCreateFromUrl(e),!i.asset){const r=await i.loadAssetAsync();r&&P.getOrAddComponent(r,Ti)}}else{const r=t?.guid??e.guid??e.name??e.uuid;e.guid||(e.guid=r),i=new ie({asset:e}),P.getOrAddComponent(e,Ti)}const n=new CO;n._internalInit(t),n.asset=i;const s=new R;return s.guid=t?.guid??(typeof e=="string"?e:e.guid||e.name||e.uuid),P.addComponent(s,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;_unsubSyncInstantiate;constructor(){super(),this.onPlayerSpawned=new re}awake(){this.watchTabVisible()}onEnable(){this.context.connection.beginListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.destroyInstance),this._unsubSyncInstantiate=Ox((e,t)=>{const i=this.asset?.asset?.guid;!i||t.originalGuid!==i||P.getComponentsInChildren(e,Ti)?.length&&(ti&&console.log("PlayerSync: remote player spawned",e.name),this.onPlayerSpawned?.invoke(e))}),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.destroyInstance),this._unsubSyncInstantiate?.()}onJoinedRoom=()=>{ti&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(ti&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.url)return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=P.getComponentsInChildren(e,Ti);if(ti&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),P.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{ti&&console.log("PlayerSync.destroyInstance",e),ph(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Ti.all.length-1;t>=0;t--){const i=Ti.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};Xm([p()],Qm.prototype,"autoSync"),Xm([p(ie)],Qm.prototype,"asset"),Xm([p(re)],Qm.prototype,"onPlayerSpawned");let Y0=Qm;var zP=(o=>(o.OwnerChanged="ownerChanged",o))(zP||{});const K0=class Gt extends T{static _all=[];static get all(){return Gt._all}static _local=[];static get local(){return Gt._local}static getFor(e){if(e instanceof R)return P.getComponentInParent(e,Gt);if(e instanceof T)return P.getComponentInParent(e.gameObject,Gt)}static isLocalPlayer(e){return Gt.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new re;onFirstOwnerChangeEvent=new re;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){ti&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${e} (me: ${this.context.connection.connectionId})`);const i=Gt._local.indexOf(this);i>=0&&Gt._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){Gt._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const s=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(s),Gt.dispatchEvent("ownerChanged",s)}awake(){Gt.all.push(this),ti&&console.log("Registered new PlayerState",this.guid,Gt.all.length-1,Gt.all),this.context.connection.beginListen(se.UserLeftRoom,this.onUserLeftRoom)}async start(){ti&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await es(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ti&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(ti&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ti&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ti&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ti&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ti&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),ph(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ti&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(se.UserLeftRoom,this.onUserLeftRoom),Gt.all.splice(Gt.all.indexOf(this),1),this.isLocalPlayer){const e=Gt._local.indexOf(this);e>=0&&Gt._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){ti&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};Xm([qb(K0.prototype.onOwnerChange)],K0.prototype,"owner");let Ti=K0;var c3=Object.defineProperty,hc=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&c3(e,t,n),n};class Ro extends T{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!==void 0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(I.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}hc([p()],Ro.prototype,"position"),hc([p()],Ro.prototype,"showNeedleLogo"),hc([p()],Ro.prototype,"showSpatialMenu"),hc([p()],Ro.prototype,"createFullscreenButton"),hc([p()],Ro.prototype,"createMuteButton"),hc([p()],Ro.prototype,"createQRCodeButton");const h3=x("debugavatar");class wt extends T{static getAvatar(e){return e>=0&&e<wt.instances.length?wt.instances[e]:null}static instances=[];static onAvatarMarkerCreated(e){return wt._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return wt._onAvatarMarkerDestroyed.push(e),e}static _onNewAvatarMarkerAdded=[];static _onAvatarMarkerDestroyed=[];connectionId;avatar;awake(){wt.instances.push(this),h3&&console.log(this);for(const e of wt._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){wt.instances.splice(wt.instances.indexOf(this),1);for(const e of wt._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}}var d3=Object.defineProperty,u3=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&d3(e,t,n),n};const dc=x("debugxrflags"),NP=x("disablexrflags");NP&&console.warn("XRFlags are disabled");var To=(o=>(o[o.Never=0]="Never",o[o.Browser=1]="Browser",o[o.AR=2]="AR",o[o.VR=4]="VR",o[o.FirstPerson=8]="FirstPerson",o[o.ThirdPerson=16]="ThirdPerson",o[o.All=4294967295]="All",o))(To||{});class vi{static Global=new vi;Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){dc&&console.warn("Set XR flag state to",e),this.Mask=e,Qn.Apply()}Enable(e){this.Mask|=e,Qn.Apply()}Disable(e){this.Mask&=~e,Qn.Apply()}Toggle(e){this.Mask^=e,Qn.Apply()}EnableAll(){this.Mask=-1,Qn.Apply()}DisableAll(){this.Mask=0,Qn.Apply()}}const $P=class As extends T{static registry=[];static Apply(){for(const e of this.registry)e.UpdateVisible(vi.Global)}static firstApply;static buffer=new vi;visibleIn;awake(){As.registry.push(this)}onEnable(){As.firstApply?this.UpdateVisible(vi.Global):(As.firstApply=!0,As.Apply())}onDestroy(){const e=As.registry.indexOf(this);e>=0&&As.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(NP)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),dc&&console.log(i),As.buffer.Mask=i,e=As.buffer),e instanceof vi?(dc&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(dc&&console.log(this.name,"use global mask"),vi.Global.Has(this.visibleIn)),t!==void 0)if(t)dc&&console.log(this.name,"is visible",this.gameObject.uuid),P.setActive(this.gameObject,!0);else{if(dc&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};u3([p()],$P.prototype,"visibleIn");let Qn=$P;var p3=Object.defineProperty,Z0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&p3(e,t,n),n};const bd=x("debugwebxr"),WP=new B().setFromAxisAngle(new v(0,1,0),Math.PI);class cr extends T{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_remoteLeftHandMeshes;_remoteRightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;bd&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Ti.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(wt);i.avatar=this.gameObject,i.connectionId=t.owner,this.context.players.setPlayerView(t.owner,this.head?.asset,rs.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){const t=this.gameObject.getComponent(wt);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=Ti.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const c=P.getComponentsInChildren(this.head.asset,Qn);for(const h of c)h.enabled=!1,h.gameObject.visible=!1}}const n=e.xr.leftController,s=this.leftHand?.asset;s&&(n&&(s.position.copy(n.gripPosition),s.quaternion.copy(n.gripQuaternion),s.quaternion.multiply(WP)),s.visible=!0,this.updateHandVisibility(n,s,this._leftHandMeshes));const r=e.xr.rightController,a=this.rightHand?.asset;a&&(r&&(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(WP)),a.visible=!0,this.updateHandVisibility(r,a,this._rightHandMeshes))}onBeforeRender(){this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e?.isTracking===!0,s=!!e?.model&&e.model.visible&&e.model!==t,r=n&&!s;i.forEach(a=>{So(a,r)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=Ti.getFor(this);if(e&&e.isLocalPlayer==!1){const t=q.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=t.isTracking(e.owner,"left")??!1;this._remoteLeftHandMeshes=this.setRemoteHandRendered(this.leftHand?.asset,this._remoteLeftHandMeshes,i);const n=t.isTracking(e.owner,"right")??!1;this._remoteRightHandMeshes=this.setRemoteHandRendered(this.rightHand?.asset,this._remoteRightHandMeshes,n)}if(this.head?.asset){const i=P.getComponentsInChildren(this.head.asset,Qn);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}setRemoteHandRendered(e,t,i){if(!e)return t;e.visible=!0,(!t||t.length===0)&&(t=[],e.traverse(n=>{n.isMesh&&t.push(n)}));for(const n of t)So(n,i);return t}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Y1.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 R&&(this.head=new ie("",this.sourceId,this.head));else{const e=new R;e.name="Head";const t=Gs.createPrimitive(_l.Cube);e.add(t),this.gameObject.add(e),this.head=new ie("",this.sourceId,e),bd&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof R&&(this.rightHand=new ie("",this.sourceId,this.rightHand));else{const e=new R;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ie("",this.sourceId,e),bd&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof R&&(this.leftHand=new ie("",this.sourceId,this.leftHand));else{const e=new R;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ie("",this.sourceId,e),bd&&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)}),Ti.isLocalPlayer(this.gameObject)&&(this._syncTransforms=P.getComponentsInChildren(this.gameObject,Gn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),s=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),s&&a.push(s),r&&a.push(r);const l=await Df(a);bd&&console.log("Avatar loaded results:",l)}}Z0([p(ie)],cr.prototype,"head"),Z0([p(ie)],cr.prototype,"leftHand"),Z0([p(ie)],cr.prototype,"rightHand");const m3=x("debugdecoders");let J0=null;function VP(){if(!J0){const o=wf(null);J0={dracoLoader:o.dracoLoader,ktx2Loader:o.ktx2Loader,meshoptDecoder:o.meshoptDecoder}}return J0}function GP(o){o!==void 0&&typeof o=="string"&&ZM(o)}function HP(o){if(o!==void 0&&typeof o=="string"&&o!=="js"){const e=VP();m3&&console.log("Setting draco decoder type to",o),e.dracoLoader.setDecoderConfig({type:o})}}function qP(o){o!==void 0&&typeof o=="string"&&KM(o)}function XP(o,e){const t=VP();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),QM(o),o.dracoLoader||o.setDRACOLoader(t.dracoLoader),o.ktx2Loader||o.setKTX2Loader(t.ktx2Loader),o.meshoptDecoder||o.setMeshoptDecoder(t.meshoptDecoder),YM(o,{progressive:!0}),o}const g3="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/",QP=["wrist","thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip","index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip","middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip","ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip","pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"];class f3{controller;handModel;bones=[];constructor(e,t,i,n,s=null,r=null){this.controller=t,this.handModel=e;const a=i||g3;s===null&&(s=new Zo,s.setPath(a));const l=`${n}.glb`;s.load(l,c=>{const h=c.scene.children[0];if(!h){console.error(`XRHandMeshModel: "${a}${l}" contains no hand object.`);return}this.handModel.add(h),h.layers.mask=this.handModel.layers.mask;const d=h.getObjectByProperty("type","SkinnedMesh");d?(d.frustumCulled=!1,d.castShadow=!0,d.receiveShadow=!0):console.warn(`XRHandMeshModel: no SkinnedMesh in the ${n} hand model \u2014 it will not deform.`);const u=[];for(const m of QP){const g=h.getObjectByName(m);g?g.jointName=m:u.push(m),this.bones.push(g)}u.length&&console.warn(`XRHandMeshModel: the ${n} hand model is missing ${u.length} of ${QP.length} joints (${u.join(", ")}).`),r?.(h)},void 0,c=>{console.error(`XRHandMeshModel: failed to load the ${n} hand model from "${a}${l}" \u2014 the hand will not be visible.`,c)})}updateMesh(){const e=this.controller.joints;for(let t=0;t<this.bones.length;t++){const i=this.bones[t];if(!i?.jointName)continue;const n=e[i.jointName];n?.visible&&(i.position.copy(n.position),i.quaternion.copy(n.quaternion))}}}var y3=Object.defineProperty,Ym=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&y3(e,t,n),n};const hr=x("debugwebxr"),dr=new Array;class bs extends T{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static _factory;static get factory(){return this._factory??=new lR}supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:t}=e;if(this.createControllerModel||this.createHandModel){if(t.hand){if(this.createHandModel){const i=await this.loadHandModel(this,t);if(!i||!t.connected||!t.isHand){i?.handObject&&Dl(i.handObject,!1),i?.handObject?.destroy();return}this._models.push({controller:t,model:i.handObject,handmesh:i.handmesh}),this._models.sort((n,s)=>n.controller.index-s.controller.index),this.scene.add(i.handObject),t.model=i.handObject}}else if(this.createControllerModel){const i=await t.getModelUrl();if(i){const n=await this.loadModel(t,i);if(!n||!t.connected||t.isHand)return;this._models.push({controller:t,model:n}),this._models.sort((s,r)=>s.controller.index-r.controller.index),this.scene.add(n),n.traverse(s=>{s.layers.set(2),s.matrixAutoUpdate=!1,s.updateMatrix()}),t.model=n}else t.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+t.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(Dl(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(Dl(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(q.active&&(hr&&(dr[0]=Date.now()),this.updateRendering(q.active),hr)){const e=Date.now()-dr[0];dr.push(e),dr.length>=30&&(dr[0]=0,dr.reduce((t,i)=>t+i,0)/dr.length,dr.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){hr&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const s=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(s&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const c=n.getHandJointPose(a);if(c){const h=c.transform.position,d=c.transform.orientation;l.position.copy(h),l.quaternion.copy(d),l.matrixAutoUpdate=!1}l.visible=c!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(kl))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const i=await ie.getOrCreate("",t).instantiate();return Dl(i),q.active?.isPassThrough&&i.traverseVisible(n=>{this.makeOccluder(n)}),i}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(hr?F.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const s=new Zo;XP(s,i);let r="";const a=t.side==="left"?this.customLeftHand:this.customRightHand;a?(r=a.url.split(".").slice(0,-1).join("."),s.setPath("")):(r=t.inputSource.handedness==="left"?"left":"right",s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const l=a?.url??`${s.path}${r}.glb`;await Rm(s,i,l,l);const c=v0(s),h=new R;Dl(h);const d=new f3(h,n,s.path,r,s,u=>{const m=c?.gltf;m?.scene.children?.length===0&&(m.scene.children[0]=u),c?.gltf&&is().createBuiltinComponents(e.context,l,c.gltf,null,c),u.traverse(g=>{g.layers.set(2),q.active?.isPassThrough&&!a&&this.makeOccluder(g),g instanceof V&&We.assignMeshLOD(g,0)}),t.connected||(hr&&F.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),u.removeFromParent())});if(hr&&h.add(new Ui(.5)),t.inputSource.hand){hr&&console.log(t.inputSource.hand);for(const u of t.inputSource.hand.values())if(n.joints[u.jointName]===void 0){const m=new Dn;m.matrixAutoUpdate=!1,m.visible=!0,n.joints[u.jointName]=m,n.add(m)}}else hr&&F.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:h,handmesh:d}}makeOccluder(e){if(e instanceof V){let t=e.material;t instanceof ke&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}Ym([p()],bs.prototype,"createControllerModel"),Ym([p()],bs.prototype,"createHandModel"),Ym([p(ie)],bs.prototype,"customLeftHand"),Ym([p(ie)],bs.prototype,"customRightHand");class Km extends T{}var b3=Object.defineProperty,ur=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&b3(e,t,n),n};const e_=x("debugwebxr");class Ji extends T{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=U(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const s=Je(t);n.multiplyScalar(s.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),M()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const i=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(i)<.3&&(this._didApplyRotation=!1);else if(Math.abs(i)>.5){this._didApplyRotation=!0;const n=i>0?1:-1,s=le(this.context.mainCamera).clone();t.rotateY(n*j.toRadians(this.rotationStep));const r=le(this.context.mainCamera).clone().sub(s);r.y=0,t.position.sub(r)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const s=e.getGesture("pinch");s&&(i=s.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof al){const r=n.normal?.dot(U(0,1,0));if(r!==void 0&&r<.4)return}let s=n?.point;if(!s&&!this.useTeleportTarget){this._plane||(this._plane=new rl(new v(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new v(0,1,0),r);const a=e.ray;s=r.clone(),this._plane.intersectLine(new DM(a.origin,U(a.direction).multiplyScalar(1e4).add(a.origin)),s),s.distanceTo(r)>t.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!P.getComponentInParent(n.object,Km))return;const r=s.clone();if(e_&&F.DrawSphere(s,.025,16711680,5),this.context.mainCamera?.position){const a=this.context.xr?.getUserOffsetInRig();a&&(a.y=0,r.sub(a),e_&&F.DrawWireSphere(a.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const s=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(s),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,c=this._lastHitDistances[t],h=this._hitDistances[t]!=null,d=c??a;n.scale.set(a,a,d),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let u=n.material.opacity;l?u=1:this.showHits&&d<e.rigScale*.5?u=0:i.getButton("primary")?.pressed?u=.5:u=h?.2:.1,n.material.opacity=j.lerp(n.material.opacity,u,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],s=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,s=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(s=!1),!s){const h=this._hitDiscs[t];h&&h.visible&&h.hit&&this.updateHitPointerPosition(i,h,h.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let c=l.find(h=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(h.object));if(c||(c=l[0]),n&&(n.controller=i,n.hit=c),this._hitDistances[t]=c?.distance||null,c){this._lastHitDistances[t]=c.distance;const h=e.rigScale??1;e_&&(F.DrawWireSphere(c.point,.025*h,16711680),F.DrawLabel(U(0,.2,0).add(c.point),c.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=c,n.visible=c.distance>h*.05;let d=.01*(h+c.distance);const u=i.getButton("primary")?.pressed;u&&(d*=1.1),n.scale.set(d,d,d),n.layers.set(2);let m=n.material.opacity;if(u?m=1:m=c.distance<.15*h?.2:.6,n.material.opacity=j.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(c.normal){this.updateHitPointerPosition(i,n,c.distance);const g=c.normal.applyQuaternion(Re(c.object));n.quaternion.setFromUnitVectors(_3,g)}else this.updateHitPointerPosition(i,n,c.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Xp(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=U(e.rayWorldPosition);n.add(U(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new V(new rf(.3,6,6),new Ie({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:Bi}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new cR;e.layers.disableAll(),e.layers.enable(2);const t=new hR;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const s=new dR({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:Vv,dashed:!1});return e.material=s,e}}ur([p()],Ji.prototype,"movementSpeed"),ur([p()],Ji.prototype,"rotationStep"),ur([p()],Ji.prototype,"useTeleport"),ur([p()],Ji.prototype,"usePinchToTeleport"),ur([p()],Ji.prototype,"useTeleportTarget"),ur([p()],Ji.prototype,"useTeleportFade"),ur([p()],Ji.prototype,"showRays"),ur([p()],Ji.prototype,"showHits");const _3=new v(0,1,0);var v3=Object.defineProperty,Ft=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&v3(e,t,n),n};const _d=x("debugwebxr"),w3=x("debugusdz"),St=class Bc extends T{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!0;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){q.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&ge('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).');const e=()=>{P.findObjectOfType(Ao)||(_d&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=P.addComponent(this.gameObject,Ao),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)};this.useQuicklookExport?e():I.isVisionOS()&&q.isARSupported().then(t=>{t||e()}),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(_d&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ie("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Y0),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await q.isVRSupported()&&this.createVRButton?q.offerSession("immersive-vr","default",this.context):this.createARButton&&await q.isARSupported()&&this.createARButton?q.offerSession("immersive-ar","default",this.context):!1}get session(){return q.active??null}get sessionMode(){return q.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return q.start("immersive-vr",e,this.context)}async enterAR(e){return q.start("immersive-ar",e,this.context)}exitXR(){q.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!Bc.activeWebXRComponent||Bc.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${Bc.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}Bc.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;_d&&console.log("WebXR onEnterXR"),this._previousXRState=vi.Global.Mask;const t=e.xr.isVR;if(vi.Global.Set(t?To.VR:To.AR),e.xr.isAR){let i=P.findObjectOfType(Tn,this.context,!1);if(!i)if(this.usePlacementReticle){const n=new R;for(const s of this.context.scene.children)n.add(s);this.context.scene.add(n),i=P.addComponent(n,Tn),this._createdComponentsInSession.push(i)}else(_d||M())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=P.findObjectOfType(Qa)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Qa))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){vi.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),Cu(1).then(()=>Bc.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Ji);return!t&&e&&(t=this.gameObject.addComponent(Ji),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(bs);return!t&&e&&(t=this.gameObject.addComponent(bs),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=>{_d&&console.log("WebXR.onAvatarSpawned",e);let t=P.getComponentInChildren(e,cr);t??=P.addComponent(e,cr)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Tr.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((I.isiOS()&&I.isSafari()||w3)&&this.useQuicklookExport){const e=P.findObjectOfType(Ao);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e)}}if(this.createSendToQuestButton&&!I.isQuest()&&q.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t)}}),this.createQRCode){const e=zl(Ro);if(e&&e.createQRCodeButton===!1)M()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!I.isMobileDevice()){const t=On.getOrCreate().createQRCode();this.addButton(t)}}}_buttons=[];addButton(e){this._buttons.push(e),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};Ft([p()],St.prototype,"createVRButton"),Ft([p()],St.prototype,"createARButton"),Ft([p()],St.prototype,"createSendToQuestButton"),Ft([p()],St.prototype,"createQRCode"),Ft([p()],St.prototype,"useDefaultControls"),Ft([p()],St.prototype,"showControllerModels"),Ft([p()],St.prototype,"showHandModels"),Ft([p()],St.prototype,"usePlacementReticle"),Ft([p(ie)],St.prototype,"customARPlacementReticle"),Ft([p()],St.prototype,"usePlacementAdjustment"),Ft([p()],St.prototype,"arScale"),Ft([p()],St.prototype,"useXRAnchor"),Ft([p()],St.prototype,"autoPlace"),Ft([p()],St.prototype,"autoCenter"),Ft([p()],St.prototype,"useQuicklookExport"),Ft([p()],St.prototype,"useDepthSensing"),Ft([p()],St.prototype,"useSpatialGrab"),Ft([p(ie)],St.prototype,"defaultAvatar");let Zm=St;const Jm=x("debugusdzbehaviours");class t_{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+Ya.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{P.foreachComponent(i,n=>{const s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const r=s.beforeCreateDocument?.call(s,this,e);r instanceof Promise&&t.push(r)}},!1)}),Jm&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const d of this.behaviourComponents)typeof d.afterCreateDocument=="function"&&d.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,s=new Set,r=Jm;let a=`graph LR
1375
+ `))}for(const Y of E){const K=s.get(Y);K&&z.set(Y,K)}return z},m=function(E){const z=u(E),Y=l(z);return c(z,Y,E)};const g=n.skinnedMesh.skeleton,y=new Array,b=[],f=[];for(const E of g.bones){b.push(E),f.push(E.uuid);const z=g.boneInverses[g.bones.indexOf(E)];y.push({bone:E,inverse:z})}let _=1e4;for(;f.length<g.bones.length&&_-- >0;)for(const E of b){const z=E.children;for(const Y of z)if(f.indexOf(Y.uuid)===-1&&g.bones.indexOf(Y)!==-1){b.push(Y),f.push(Y.uuid);const K=g.boneInverses[g.bones.indexOf(Y)];y.push({bone:Y,inverse:K})}}_<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,g.bones,f);for(const E of bP(g.bones))y.push({bone:E,inverse:E.matrixWorld.clone().invert()});const w=y[0].bone.parent;w||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),y.sort((E,z)=>oc(E.bone,w)>oc(z.bone,w)?1:-1);const S=t.quickLookCompatible,O=[],L=[],D=[],W=[];for(const{bone:E}of y){if(S){const z=E.scale;z.x==0&&(z.x=1e-5),z.y==0&&(z.y=1e-5),z.z==0&&(z.z=1e-5),O.push(new J().compose(E.position,E.quaternion,E.scale))}else O.push(E.matrix.clone());L.push(E.position),D.push(E.quaternion),W.push(E.scale)}const $=y.map(E=>'"'+oc(E.bone,w)+'"').join(", "),H=y.map(E=>TP(E.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${H}]`),e.appendLine(`uniform token[] joints = [${$}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${O.map(E=>TP(E)).join(", ")}]`);const G=m(y.map(E=>E.bone));if(Mo){let E=1e7,z=0;for(const Y of G.position?.keys()??[])E=Math.min(E,Y),z=Math.max(z,Y);console.log("Time samples",E,z,G)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${$}]`),e.appendLine(`quatf[] rotations = [${d(D)}]`),G&&G.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const E=a(G.quaternion);for(const z of E)e.appendLine(z);e.closeBlock()}if(e.appendLine(`half3[] scales = [${h(W)}]`),G&&G.scale){e.beginBlock("half3[] scales.timeSamples = {","");const E=r(G.scale);for(const z of E)e.appendLine(z);e.closeBlock()}if(e.appendLine(`float3[] translations = [${h(L)}]`),G&&G.position){e.beginBlock("float3[] translations.timeSamples = {","");const E=r(G.position);for(const z of E)e.appendLine(z);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let h=0;h<i.length;h++)i[h]===void 0&&(i[h]=new Ze(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const s=this.object,r=this.model,a=this.animationData.get(s);if(!a||s.isSkinnedMesh)return;$0&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function c(h,d){if(h.some(u=>u&&{position:u.pos,rotation:u.rot,scale:u.scale}[d])){switch(d){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let u=0;u<h.length;u++){const m=h[u];if(!m)continue;const g=n.getStartTimeByClip(m.clip),y=m.getSortedTimesArray(d==="position",d==="rotation",d==="scale");if(!y||y.length===0){console.error("got an animated object but no time values?",s,m);continue}const b=!m.clip,f=d==="position"&&(m.pos||b),_=d==="rotation"&&(m.rot||b),w=d==="scale"&&(m.scale||b);if(f||_||w){const S=m.clip?.name??"rest",O=m.getDuration();Mo&&console.log("Write .timeSamples:",S,g,O,h),e.appendLine("# "+S+": start="+l.format(g*Ze.frameRate)+", length="+l.format(O*Ze.frameRate)+", frames="+m.getFrames())}if(f)for(const{time:S,translation:O}of m.getValues(y,!0,!1,!1)){const L=`${l.format((g+S)*Ze.frameRate)}: (${pe(O.x)}, ${pe(O.y)}, ${pe(O.z)}),`;e.appendLine(L)}if(_)for(const{time:S,rotation:O}of m.getValues(y,!1,!0,!1)){const L=`${l.format((g+S)*Ze.frameRate)}: (${pe(O.w)}, ${pe(O.x)}, ${pe(O.y)}, ${pe(O.z)}),`;e.appendLine(L)}if(w)for(const{time:S,scale:O}of m.getValues(y,!1,!1,!0)){const L=`${l.format((g+S)*Ze.frameRate)}: (${pe(O.x)}, ${pe(O.y)}, ${pe(O.z)}),`;e.appendLine(L)}}e.closeBlock()}}c(a,"position"),c(a,"rotation"),c(a,"scale")}}const Qj=x("debugusdz");class Ya{static getName(e){const t=e.split(".").pop();let i=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),Zi(i)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=P.getComponents(e,Yi);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const r=s.clip.split("/").pop()||"Audio",a=Ya.getName(s.clip),l=Zi(a);if(!this.files.some(c=>c.path===s.clip)){this.files.push({path:s.clip,name:a});const c=a.toLowerCase();i.quickLookCompatible&&!c.endsWith(".mp3")&&!c.endsWith(".wav")&&!c.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(c,h)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${r}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){Qj&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const n=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}}}var Yj=Object.defineProperty,He=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Yj(e,t,n),n};const FP=x("debugusdzbehaviours");class Pa extends T{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new v;targetRot=new B;targetScale=new v;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){const t=this.object?.getComponentsInChildren(rt);if(t)for(const i of t)i.resetVelocities(),i.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;const e=le(this.object).clone(),t=le(this.target).clone(),i=Re(this.object).clone(),n=Re(this.target).clone(),s=Je(this.object).clone(),r=Je(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),c=s.distanceTo(r);if(a<.01&&l<.01&&c<.01){Vi(this.object,t),Fn(this.object,n),hl(this.object,r),this.coroutine=null;return}let h=0,d=0;for(;h<1;)h+=this.context.time.deltaTime/this.duration,h>1&&(h=1),d=h<.5?4*h*h*h:1-Math.pow(-2*h+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(i,n,d),this.targetScale.lerpVectors(s,r,d),Vi(this.object,this.targetPos),Fn(this.object,this.targetRot),hl(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),s=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(s),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new qt("Move to "+this.target?.name,ei.tapTrigger(this.gameObject),be.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}He([p(R)],Pa.prototype,"object"),He([p(R)],Pa.prototype,"target"),He([p()],Pa.prototype,"duration"),He([p()],Pa.prototype,"relativeMotion");const Gm=class _i extends T{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,M()&&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 t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof V)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):Ax(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],_i._materialTriggersPerId={},_i.variantSwitchIndex=0,this.materialToSwitch&&await We.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await We.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(_i._materialTriggersPerId[this.materialToSwitch.uuid]||(_i._materialTriggersPerId[this.materialToSwitch.uuid]=[]),_i._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=_i._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const s of i){const r=s.createVariants();r&&r.length>0&&(n[s.selfModel.uuid]=r)}for(const s of i){const r=[];for(const a in n)a!==s.selfModel.uuid&&r.push(...n[a]);s.createAndAttachBehaviors(e,n[s.selfModel.uuid],r)}}delete _i._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],s=Math.max(0,this.fadeDuration);n.push(be.fadeAction([...this.targetModels,...i],s,!1)),n.push(be.fadeAction(t,s,!0)),e.addBehavior(new qt("Select_"+this.selfModel.name,ei.tapTrigger(this.selfModel),be.parallel(...n))),_i._parallelStartHiddenActions.push(...t),_i._startHiddenBehaviour||(_i._startHiddenBehaviour=new qt("StartHidden_"+this.selfModel.name,ei.sceneStartTrigger(),be.fadeAction(_i._parallelStartHiddenActions,s,!1)),e.addBehavior(_i._startHiddenBehaviour))}static getMaterialName(e){return Zi(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+_i.variantSwitchIndex+++"_"+_i.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&vt.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};He([p(Oe)],Gm.prototype,"materialToSwitch"),He([p(Oe)],Gm.prototype,"variantMaterial"),He([p()],Gm.prototype,"fadeDuration");let W0=Gm;const dd=class Ke extends T{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,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[Ke.wasVisible]===void 0&&(this.gameObject[Ke.wasVisible]=this.gameObject.activeSelf),this.target[Ke.wasVisible]===void 0&&(this.target[Ke.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[Ke.wasVisible],this.targetStateBeforeCreatingDocument=this.target[Ke.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&I0.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[Ke.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggle"+Ke.clonedToggleIndex++,i.add(l),this.gameObject[Ke.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[Ke.toggleClone];if(!this.gameObject[Ke.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggleReverse"+Ke.clonedToggleIndex++,i.add(l),this.gameObject[Ke.reverseToggleClone]=l}this.toggleModel=this.gameObject[Ke.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(be.fadeAction(n,0,!1)),a.push(be.fadeAction(this.toggleModel,0,!0)),a.push(be.fadeAction(this.targetModel,0,s)),e.addBehavior(new qt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),ei.tapTrigger(n),be.parallel(...a)));const l=[];l.push(be.fadeAction(this.toggleModel,0,!1)),l.push(be.fadeAction(n,0,!0)),l.push(be.fadeAction(this.targetModel,0,!s)),e.addBehavior(new qt("Toggle_"+n.name+"_ToggleTo"+(s?"Off":"On"),ei.tapTrigger(this.toggleModel),be.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(be.fadeAction(n,0,!1)),a.push(be.fadeAction(this.targetModel,0,s)),e.addBehavior(new qt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),ei.tapTrigger(n),a.length>1?be.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),Rn.add(r,e)}}afterSerialize(e,t){this.gameObject[Ke.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[Ke.wasVisible],delete this.gameObject[Ke.wasVisible]),this.target&&this.target[Ke.wasVisible]!==void 0&&(this.target.visible=this.target[Ke.wasVisible],delete this.target[Ke.wasVisible]),delete this.gameObject[Ke.toggleClone],delete this.gameObject[Ke.reverseToggleClone]}};He([p(R)],dd.prototype,"target"),He([p()],dd.prototype,"toggleOnClick"),He([p()],dd.prototype,"targetState"),He([p()],dd.prototype,"hideSelf");let V0=dd;class Rn extends T{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)Rn._fadeObjects.includes(n)||(console.log("adding hide on start",n),Rn._fadeObjects.push(n));Rn._fadeBehaviour===void 0&&(Rn._fadeBehaviour=new qt("HideOnStart",ei.sceneStartTrigger(),be.fadeAction(Rn._fadeObjects,0,!1)),t.addBehavior(Rn._fadeBehaviour))}start(){P.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Rn.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=P.isActiveSelf(this.gameObject)}}class rc extends T{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,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new qt("emphasize "+this.name,ei.tapTrigger(this.gameObject),be.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}He([p()],rc.prototype,"target"),He([p()],rc.prototype,"duration"),He([p()],rc.prototype,"motionType");class lr extends T{target;clip="";toggleOnClick=!1;trigger="tap";ensureAudioSource(){if(!this.target){const e={spatialBlend:1,volume:1,loop:!1,clip:this.clip,preload:!0},t=this.gameObject.addComponent(Yi,e);t&&(this.target=t)}}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Play audio: "+(this.clip||this.target?.clip||"unknown clip"),hidden:!1}),this.ensureAudioSource()}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,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const s=this.target?this.target.gameObject:this.gameObject;Ya.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(u=>{u instanceof V&&u.visible&&(l=!0)}),l=!0;const c=e.addAudioClip(n);let h=be.playAudioAction(s,c,"play",r,a);this.target&&this.target.loop&&(h=be.sequence(h).makeLooping());const d=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(h.multiplePerformOperation="stop");const u=new qt("playAudio"+d,ei.tapTrigger(t),h);e.addBehavior(u)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const u=new qt("playAudioOnStart"+d,ei.sceneStartTrigger(),h);e.addBehavior(u)}}}}He([p(Yi)],lr.prototype,"target"),He([p(URL)],lr.prototype,"clip"),He([p()],lr.prototype,"toggleOnClick");const G0=class No extends T{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=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(No.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';M()&&ge(e),console.warn(e,...No.rootsWithExclusivePlayback)}No.animationActions=[],No.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof Vm);if(!n)return;const s=n.getClipCount(this.target)>1;s&&(M()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),No.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=No.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),c=new qt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?ei.tapTrigger(this.selfModel):ei.sceneStartTrigger(),l);s&&c.makeExclusive(!0),e.addBehavior(c)}})}static getActionForSequences(e,t,i,n,s){const r=(l,c)=>{let h=No.animationActions.find(d=>d.affectedObjects==l&&d.start==c.start&&d.duration==c.duration&&d.animationSpeed==c.speed);return h||(h=be.startAnimationAction(l,c),No.animationActions.push(h)),h},a=be.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:be.sequence();for(const c of n)l.addAction(r(t,c));l.makeLooping(),a!==l&&a.addAction(l)}return s&&s>0&&a.actions.unshift(be.waitAction(s)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(Et),s=t.getComponent(Zt);if(!n&&!s)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(s){const g=e.registerAnimation(t,s.clip);g&&(s.loop?a.push(g):r.push(g));let y=0;if(s.minMaxOffsetNormalized){const b=s.minMaxOffsetNormalized.x,f=s.minMaxOffsetNormalized.y;y=(s.clip?.duration||1)*(b+Math.random()*(f-b))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:y}}const l=n?.runtimeAnimatorController;let c=l?.findState(i),h=[],d=[];if(l&&c){const g=new Array;g.push(c);let y=!1;for(;g.length<100;){if(!c||c===null||!c.transitions||c.transitions.length===0){c.motion?.isLooping&&(y=!0);break}const b=c.transitions.find(_=>_.conditions.length===0),f=b?l.getState(b.destinationState,0):null;if(f&&g.includes(f)){c=f,y=!0;break}else if(b){if(c=f,!c)break;g.push(c)}else{y=c.motion?.isLooping??!1;break}}if(y&&c){const b=g.indexOf(c);h=g.slice(0,b),d=g.slice(b),FP&&console.log("found loop from "+i,"states until loop",h,"states looping",d)}else h=g,d=[],FP&&console.log("found no loop from "+i,"states",h);if(!d.length){const b=h[h.length-1],f=b.motion?.clip;if(f){let _;if(e.holdClipMap.has(f))_=e.holdClipMap.get(f);else{const w=b.name+"_hold";_=f.clone(),_.duration=1,_.name=w;const S=f.duration;_.tracks=f.tracks.map(O=>{const L=O.clone();L.times=new Float32Array([0,S]);const D=O.values.length,W=O.getValueSize(),$=O.values.slice(D-W,D);return L.values=new Float32Array(2*W),L.values.set($,0),L.values.set($,W),L}),_.name=w,e.holdClipMap.set(f,_)}if(_){const w={name:_.name,motion:{clip:_,isLooping:!1,name:_.name},speed:1,transitions:[],behaviours:[],hash:b.hash+1};d.push(w)}}}}if(h.length===1&&(!h[0].motion?.clip||h[0].motion?.clip.tracks?.length===0)){r=new Array;const g=e.registerAnimation(t,null);g&&r.push(g);return}if(h=h.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),d=d.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),h.length===0&&d.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const u=(g,y)=>{if(!t)return;const b=e.registerAnimation(t,g.motion.clip??null);b?(b.speed=g.speed,y.push(b)):console.warn("Couldn't register animation for state "+g.name+" on "+n?.name)};if(h.length>0){r=new Array;for(const g of h)u(g,r)}if(d.length>0){a=new Array;for(const g of d)u(g,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const g=n.minMaxOffsetNormalized.x,y=n.minMaxOffsetNormalized.y;m=((h.length?h[0]:d.length?d[0]:null)?.motion.clip?.duration||1)*(g+Math.random()*(y-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=No.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};He([p(Et)],G0.prototype,"animator"),He([p()],G0.prototype,"stateName");let ud=G0;class ac extends T{getType(){}target;getDuration(){}}He([p(R)],ac.prototype,"target");class pd extends T{target}He([p(ac)],pd.prototype,"target");class md extends ac{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}He([p()],md.prototype,"type"),He([p()],md.prototype,"duration");class H0 extends pd{}let Hm;function Kj(o){Hm=o}function Zj(){if(!Hm)return null;const o=Hm.find();return o?{handler:o,created:!1}:{handler:Hm.create(),created:!0}}const Jj=100,e3=200,t3=300;class Tr{static _instance;static create(){return new Tr}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return On.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=I.supportsQuickLookAR();let i="View in AR";I.isVisionOS()?i="View in AR":(t||I.isiOS())&&(i="Open in Quicklook"),e.innerText=i,e.prepend(Tt("view_in_ar")),Ph.setElementPriority(e,e3);let n=!1,s=null;return e.addEventListener("click",()=>{const r=Zj();r&&(s=r.handler,n=r.created),n&&s&&(s.objectToExport=Q.Current.scene),s?(e.classList.add("this-mode-is-requested"),s.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(a=>{e.classList.remove("this-mode-is-requested"),console.error(a)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.title="Click to start an AR session";const n=()=>{i.innerText="Enter AR",i.prepend(Tt("view_in_ar"))};n();let s;return i.addEventListener("click",()=>{q.start(t,e),I.isiOS()&&!I.isVisionOS()&&setTimeout(()=>{i.innerHTML="Tap again",i.prepend(Tt("view_in_ar")),clearTimeout(s),s=setTimeout(n,4e3)},500)}),Ph.setElementPriority(i,t3),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(Tt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>q.start(t,e)),Ph.setElementPriority(i,Jj),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(Tt("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&Fe("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{q.isSessionSupported("immersive-vr").then(i=>{t.style.display=i?"none":""})}),t}createQRCode(){return On.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!(t==="immersive-ar"&&I.isiOS()&&!I.isVisionOS())){if(!("xr"in navigator)){e.style.display="none";return}q.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",M()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device. Make sure your server runs using HTTPS and you have a device connected that supports '+t)})}}hideElementDuringXRSession(e){wp(t=>{e["previous-display"]=e.style.display,e.style.setProperty("display","none","important")}),Yy(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(q.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),q.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var i3=Object.defineProperty,n3=Object.getOwnPropertyDescriptor,jt=(o,e,t,i)=>{for(var n=i>1?void 0:i?n3(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&i3(e,t,n),n};const gd=x("debugspriterenderer"),o3=x("wireframe");class Za{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&Za.cache[e.guid])return gd&&console.log("Take cached geometry for sprite",e.guid),Za.cache[e.guid];const t=new Ln;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let s=0;s<e.triangles.length;s+=1){const r=e.triangles[s];i[s*3]=-e.vertices[r].x,i[s*3+1]=e.vertices[r].y,i[s*3+2]=0;const a=e.uv[r];n[s*2]=a.x,n[s*2+1]=1-a.y}return t.setAttribute("position",new lt(i,3)),t.setAttribute("uv",new lt(n,2)),e.guid&&(this.cache[e.guid]=t),gd&&console.log("Built sprite geometry",e,t),t}}class s3{x;y}function BP(o){o&&(o.colorSpace!=Yo&&(o.colorSpace=Yo,o.needsUpdate=!0),o.minFilter==_u&&o.magFilter==_u&&(o.anisotropy=1,o.needsUpdate=!0))}let ys=class{constructor(o){o&&(this.texture=o,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new V(Za.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&BP(this.texture),this._material=new Ie({map:this.texture,color:16777215,side:Bi,transparent:!0})),this._material}_material;getGeometry(){return Za.getOrCreateGeometry(this)}};jt([p()],ys.prototype,"guid",2),jt([p(ke)],ys.prototype,"texture",2),jt([it()],ys.prototype,"triangles",2),jt([it()],ys.prototype,"uv",2),jt([it()],ys.prototype,"vertices",2);const q0=Symbol("spriteOwner");class lc{sprites;constructor(){this.sprites=[]}}jt([p(ys)],lc.prototype,"sprites",2);const X0=class Sv{static create(){const e=new Sv;return e.spriteSheet=new lc,e}constructor(){}clone(){const e=new Sv;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new lc,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(BP(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;We.assignTextureLOD(n,0).then(r=>{r instanceof ke&&(i.texture=r,e?.map===s&&(e.map=r,e.needsUpdate=!0))})}}};jt([p(lc)],X0.prototype,"spriteSheet",2),jt([p()],X0.prototype,"index",2);let cc=X0;class Ri extends T{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=cc.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.round(e);gd&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof ys?(this._spriteSheet||(this._spriteSheet=cc.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=cc.create(),gd&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return gd&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=Za.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new Ie({color:16777215,side:Bi});if(o3&&(n.wireframe=!0),this.color&&(n.color||(n.color=new oe),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let s=i.texture;s[q0]!==void 0&&s[q0]!==this&&this.spriteFrames>1&&(s=i.texture=s.clone()),s[q0]=this,n.map=s}this.sharedMaterial=n,this._currentSprite=new V(Za.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),We.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}jt([p()],Ri.prototype,"drawMode",2),jt([p(s3)],Ri.prototype,"size",2),jt([p(he)],Ri.prototype,"color",2),jt([p(Oe)],Ri.prototype,"sharedMaterial",2),jt([p()],Ri.prototype,"transparent",2),jt([p()],Ri.prototype,"cutoutThreshold",2),jt([p()],Ri.prototype,"castShadows",2),jt([p()],Ri.prototype,"renderOrder",2),jt([p()],Ri.prototype,"toneMapped",2),jt([p(cc)],Ri.prototype,"sprite",1);const fd=x("debugwebxr"),Q0=x("debugartouch"),r3=new J().makeRotationY(Math.PI),UP=new v(1,1,1),qm=new J,yd=new J;function a3(o,e,t=1e-6){for(let i=0;i<16;i++)if(Math.abs(o.elements[i]-e.elements[i])>t)return!1;return!0}class Tn extends T{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){e=Math.max(1e-6,e),e!==this._arScale&&(this._arScale=e,this.onSetScale())}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!0;_isPlacing=!0;_startOffset=new J;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new Fi;_reticle=[];_hitRefPoses=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;_pendingAnchorPose=null;_anchorLastLocalPose=new J;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){fd&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,this._pendingAnchorPose=null,this._hitRefPoses.length=0,Tn._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new R;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Si(this._placementScene.children),n=i.getCenter(new v),s=i.getSize(new v),r=new J;r.makeTranslation(n.x,n.y-s.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),P.addComponent(t,this);for(const i of this._reticle)ki(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Hs.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Hs.Early}),this.onRevertSceneChanges(),this._anchor=null,this._pendingAnchorPose=null,Tn._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const s=n.getHitTest();s&&(i=!0,this.updateReticleAndHits(e.xr,n.index,s,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else if(this.useXRAnchor&&this.updateXRAnchor(e.xr),this.arTouchTransform?(this.userInput||(this.userInput=new tf(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale)}this.userInput.reset()}}updateReticleAndHits(e,t,i,n){if(this.useXRAnchor){const r=e.referenceSpace,a=r?i.hit.getPose(r):void 0;if(a){let l=this._hitRefPoses[t];l||(l=this._hitRefPoses[t]={x:0,y:0,z:0,qx:0,qy:0,qz:0,qw:1});const{position:c,orientation:h}=a.transform;l.x=c.x,l.y=c.y,l.z=c.z,l.qx=h.x,l.qy=h.y,l.qz=h.z,l.qw=h.w}}let s=this._reticle[t];if(!s){if(this.customReticle)if(this.customReticle.asset)s=Ks(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else s=new V(new LM(.07,.09,32).rotateX(-Math.PI/2),new Ie({side:Bi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),s.name="AR Placement Reticle";if(fd){const r=new Ui(1);r.position.y+=.01,s.add(r)}this._reticle[t]=s,s.matrixAutoUpdate=!1,s.visible=!1}if(s.lastPos=s.lastPos||i.position.clone(),s.lastQuat=s.lastQuat||i.quaternion.clone(),s.position.copy(s.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),s.lastPos.copy(s.position),s.quaternion.copy(s.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),s.lastQuat.copy(s.quaternion),s.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(s),s.updateMatrix(),s.visible=!0,s.parent!==this.context.scene&&this.context.scene.add(s),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(s.quaternion),this.upVec.dot(U(0,1,0))>.9){let r=s["autoplace:timer"]||0;r>=1?(s.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,s["autoplace:timer"]=r)}else s["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(q.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=0;if(e&&e.origin instanceof Vy){const n=this._reticle[e.origin.index];n&&(t=n,i=e.origin.index)}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),Tn._hasPlaced=!0,this.useXRAnchor){const n=this._hitRefPoses[i];n?this._pendingAnchorPose={...n}:(console.warn("[WebARSessionRoot] can not create a XR anchor: no hit pose was captured for the placement"),M()&&ge("Can not create XR anchor: no hit pose available"))}if(this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!Tn._hasPlaced)return;const e=q.active?.rig?.gameObject;if(e){const t=q.active?.rigScale||1,i=1/this._arScale*t,n=new J().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)e.comp.destroyed||Ys(e.originalObject)||P.addComponent(e.originalObject,e.comp);this._reparentedComponents.length=0}updateXRAnchor(e){const t=e.referenceSpace;if(!t)return;const i=e.frame;if(this._pendingAnchorPose){const a=this._pendingAnchorPose;if(this._pendingAnchorPose=null,typeof i.createAnchor!="function"||e.session.enabledFeatures?.includes("anchors")===!1){(fd||M())&&(console.warn("[WebARSessionRoot] useXRAnchor is enabled but WebXR anchors are not supported by this session"),ge("WebXR anchors are not supported by this session"));return}const l=new XRRigidTransform({x:a.x,y:a.y,z:a.z},{x:a.qx,y:a.qy,z:a.qz,w:a.qw}),c=e.convertSpace(l);this._anchorLastLocalPose.compose(c.position,c.quaternion,UP),i.createAnchor(l,t).then(h=>{e.running&&!this._isPlacing?(this._anchor=h,fd&&console.log("[WebARSessionRoot] created XR anchor",h)):h.delete()}).catch(h=>{console.warn("[WebARSessionRoot] failed to create XR anchor",h),M()&&ge("Failed to create XR anchor")});return}if(!this._anchor)return;const n=e.rig?.gameObject;if(!n)return;const s=i.getPose(this._anchor.anchorSpace,t);if(!s)return;const r=e.convertSpace(s.transform);if(qm.compose(r.position,r.quaternion,UP),!a3(qm,this._anchorLastLocalPose)&&(yd.copy(qm).invert().premultiply(this._anchorLastLocalPose),this._anchorLastLocalPose.copy(qm),n.updateMatrix(),n.matrix.multiply(yd),n.matrix.decompose(n.position,n.quaternion,n.scale),fd)){const a=yd.elements[12],l=yd.elements[13],c=yd.elements[14];console.log(`[WebARSessionRoot] applied XR anchor correction: ${(Math.hypot(a,l,c)*1e3).toFixed(2)}mm`)}}upVec=new v(0,1,0);lookPoint=new v;worldUpVec=new v(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,s=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=s.y,e.lookAt(n))}onApplyPose(e){const t=q.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(r3),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class tf{static up=new v(0,1,0);static zero=new v(0,0,0);static one=new v(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new J,this.plane=new rl,this.plane.setFromNormalAndCoplanarPoint(tf.up,tf.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)}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDown),this.context.input.addEventListener("pointermove",this.onPointerMove),this.context.input.addEventListener("pointerup",this.onPointerUp))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDown),this.context.input.removeEventListener("pointermove",this.onPointerMove),this.context.input.removeEventListener("pointerup",this.onPointerUp),this._tracked.clear(),this._hasTwoFingerRef=!1)}_tracked=new Map;_hasTwoFingerRef=!1;_lastTwoFingerAngle=0;_lastTwoFingerDist=0;_resyncGesture=!1;isPointerUsed(e){return this.context.input.getIsPointerIdInUse(e)}onPointerDown=e=>{if(e.mode==="screen"&&e.button===0){if(e.used||this.isPointerUsed(e.pointerId)){M()&&console.debug(`[WebARSessionRoot] AR touch #${e.pointerId} ignored for touch transform: pointer is used (grabbed by a component)`);return}this._tracked.set(e.pointerId,new ee(e.clientX,e.clientY)),Q0?console.debug(`[ARTouch] down #${e.pointerId} (${e.clientX.toFixed(0)}, ${e.clientY.toFixed(0)}) type=${e.pointerType} tracked=${this._tracked.size}`):M()&&console.debug(`[WebARSessionRoot] AR touch #${e.pointerId} down (tracked fingers: ${this._tracked.size})`),this._hasTwoFingerRef=!1,this._resyncGesture=!0}};onPointerMove=e=>{if(e.mode!=="screen")return;const t=this._tracked.get(e.pointerId);if(!t)return;if(this.isPointerUsed(e.pointerId)){M()&&console.debug(`[WebARSessionRoot] AR touch #${e.pointerId} dropped from touch transform: pointer became used mid-gesture`),this._tracked.delete(e.pointerId),this._hasTwoFingerRef=!1,this._resyncGesture=!0;return}const i=e.clientX,n=e.clientY;if(this._resyncGesture){t.set(i,n),this._resyncGesture=!1,this._hasTwoFingerRef=!1;return}if(this._tracked.size===1)this.oneFingerDrag&&this.pixelToGround(i,n,this._curW)&&this.pixelToGround(t.x,t.y,this._prevW)&&this.addMovement(this._curW.x-this._prevW.x,this._curW.z-this._prevW.z),t.set(i,n);else if(this._tracked.size===2){t.set(i,n);const s=this._tracked.values(),r=s.next().value,a=s.next().value,l=Math.atan2(a.y-r.y,a.x-r.x),c=r.distanceTo(a);if(Q0&&console.debug(`[ARTouch] move #${e.pointerId} (${i.toFixed(0)}, ${n.toFixed(0)}) a=(${r.x.toFixed(0)}, ${r.y.toFixed(0)}) b=(${a.x.toFixed(0)}, ${a.y.toFixed(0)}) dist=${c.toFixed(1)} last=${this._lastTwoFingerDist.toFixed(1)} ref=${this._hasTwoFingerRef}`),this._hasTwoFingerRef){if(this.twoFingerRotate){const h=l-this._lastTwoFingerAngle;Math.abs(h)>.001&&this.addRotation(h)}if(this.twoFingerScale&&this._lastTwoFingerDist>1&&c>1){let h,d;if(this.pixelToGround((r.x+a.x)/2,(r.y+a.y)/2,this._pivotW))h=this._pivotW.x,d=this._pivotW.z;else{const u=this.context.mainCamera;h=u?.worldPosition.x??0,d=u?.worldPosition.z??0}this.applyScaleRatio(c/this._lastTwoFingerDist,h,d)}}this._lastTwoFingerAngle=l,this._lastTwoFingerDist=c,this._hasTwoFingerRef=!0}};onPointerUp=e=>{e.mode==="screen"&&(Q0&&console.debug(`[ARTouch] up #${e.pointerId} (${e.clientX.toFixed(0)}, ${e.clientY.toFixed(0)}) tracked=${this._tracked.size-(this._tracked.has(e.pointerId)?1:0)}`),this._tracked.delete(e.pointerId),this._hasTwoFingerRef=!1,this._resyncGesture=!0,this._tracked.size<2&&this._gestureScale!==1&&(M()&&console.debug(`[WebARSessionRoot] pinch scale gesture ended: total \xD7${this._gestureScale.toFixed(3)}, rig scale now ${(q.active?.rigScale??1).toFixed(3)}`),this._gestureScale=1))};_raycaster=new df;_screenPos=new v;_camPos=new v;_curW=new v;_prevW=new v;_pivotW=new v;_gestureScale=1;pixelToGround(e,t,i){const n=this.context.mainCamera;if(!n)return!1;this._screenPos.set(e/window.innerWidth*2-1,-(t/window.innerHeight)*2+1,1),this._screenPos.unproject(n),this._camPos.copy(n.worldPosition);const s=this._screenPos.sub(this._camPos).normalize();return Math.abs(s.y)<.08?!1:(this._raycaster.set(this._camPos,s),this._raycaster.ray.intersectPlane(this.plane,i)!==null)}addMovement(e,t){e/=this._scale,t/=this._scale,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new J;applyScaleRatio(e,t,i){if(!isFinite(e)||e<=0||e===1)return;this._scale*=1/e,this._gestureScale*=e;const n=this._tempMatrix.makeScale(e,e,e);n.elements[12]=t*(1-e),n.elements[14]=i*(1-e),this.offset.premultiply(n),this._hasChanged=!0}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}var l3=Object.defineProperty,Xm=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&l3(e,t,n),n};const ti=x("debugplayersync"),Qm=class CO extends T{static async setupFrom(e,t){let i;if(typeof e=="string"){if(i=ie.getOrCreateFromUrl(e),!i.asset){const r=await i.loadAssetAsync();r&&P.getOrAddComponent(r,Ti)}}else{const r=t?.guid??e.guid??e.name??e.uuid;e.guid||(e.guid=r),i=new ie({asset:e}),P.getOrAddComponent(e,Ti)}const n=new CO;n._internalInit(t),n.asset=i;const s=new R;return s.guid=t?.guid??(typeof e=="string"?e:e.guid||e.name||e.uuid),P.addComponent(s,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;_unsubSyncInstantiate;constructor(){super(),this.onPlayerSpawned=new re}awake(){this.watchTabVisible()}onEnable(){this.context.connection.beginListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.destroyInstance),this._unsubSyncInstantiate=Ox((e,t)=>{const i=this.asset?.asset?.guid;!i||t.originalGuid!==i||P.getComponentsInChildren(e,Ti)?.length&&(ti&&console.log("PlayerSync: remote player spawned",e.name),this.onPlayerSpawned?.invoke(e))}),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(se.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.destroyInstance),this._unsubSyncInstantiate?.()}onJoinedRoom=()=>{ti&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(ti&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.url)return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=P.getComponentsInChildren(e,Ti);if(ti&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),P.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{ti&&console.log("PlayerSync.destroyInstance",e),ph(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Ti.all.length-1;t>=0;t--){const i=Ti.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};Xm([p()],Qm.prototype,"autoSync"),Xm([p(ie)],Qm.prototype,"asset"),Xm([p(re)],Qm.prototype,"onPlayerSpawned");let Y0=Qm;var zP=(o=>(o.OwnerChanged="ownerChanged",o))(zP||{});const K0=class Gt extends T{static _all=[];static get all(){return Gt._all}static _local=[];static get local(){return Gt._local}static getFor(e){if(e instanceof R)return P.getComponentInParent(e,Gt);if(e instanceof T)return P.getComponentInParent(e.gameObject,Gt)}static isLocalPlayer(e){return Gt.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new re;onFirstOwnerChangeEvent=new re;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){ti&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${e} (me: ${this.context.connection.connectionId})`);const i=Gt._local.indexOf(this);i>=0&&Gt._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){Gt._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const s=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(s),Gt.dispatchEvent("ownerChanged",s)}awake(){Gt.all.push(this),ti&&console.log("Registered new PlayerState",this.guid,Gt.all.length-1,Gt.all),this.context.connection.beginListen(se.UserLeftRoom,this.onUserLeftRoom)}async start(){ti&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await es(300),this.context.connection.userIsInRoom(this.owner)==!1&&(ti&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(ti&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?ti&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(ti&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):ti&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){ti&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),ph(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(ti&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(se.UserLeftRoom,this.onUserLeftRoom),Gt.all.splice(Gt.all.indexOf(this),1),this.isLocalPlayer){const e=Gt._local.indexOf(this);e>=0&&Gt._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){ti&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};Xm([qb(K0.prototype.onOwnerChange)],K0.prototype,"owner");let Ti=K0;var c3=Object.defineProperty,hc=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&c3(e,t,n),n};class Ro extends T{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!==void 0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(I.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}hc([p()],Ro.prototype,"position"),hc([p()],Ro.prototype,"showNeedleLogo"),hc([p()],Ro.prototype,"showSpatialMenu"),hc([p()],Ro.prototype,"createFullscreenButton"),hc([p()],Ro.prototype,"createMuteButton"),hc([p()],Ro.prototype,"createQRCodeButton");const h3=x("debugavatar");class wt extends T{static getAvatar(e){return e>=0&&e<wt.instances.length?wt.instances[e]:null}static instances=[];static onAvatarMarkerCreated(e){return wt._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return wt._onAvatarMarkerDestroyed.push(e),e}static _onNewAvatarMarkerAdded=[];static _onAvatarMarkerDestroyed=[];connectionId;avatar;awake(){wt.instances.push(this),h3&&console.log(this);for(const e of wt._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){wt.instances.splice(wt.instances.indexOf(this),1);for(const e of wt._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}}var d3=Object.defineProperty,u3=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&d3(e,t,n),n};const dc=x("debugxrflags"),NP=x("disablexrflags");NP&&console.warn("XRFlags are disabled");var To=(o=>(o[o.Never=0]="Never",o[o.Browser=1]="Browser",o[o.AR=2]="AR",o[o.VR=4]="VR",o[o.FirstPerson=8]="FirstPerson",o[o.ThirdPerson=16]="ThirdPerson",o[o.All=4294967295]="All",o))(To||{});class vi{static Global=new vi;Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){dc&&console.warn("Set XR flag state to",e),this.Mask=e,Qn.Apply()}Enable(e){this.Mask|=e,Qn.Apply()}Disable(e){this.Mask&=~e,Qn.Apply()}Toggle(e){this.Mask^=e,Qn.Apply()}EnableAll(){this.Mask=-1,Qn.Apply()}DisableAll(){this.Mask=0,Qn.Apply()}}const $P=class As extends T{static registry=[];static Apply(){for(const e of this.registry)e.UpdateVisible(vi.Global)}static firstApply;static buffer=new vi;visibleIn;awake(){As.registry.push(this)}onEnable(){As.firstApply?this.UpdateVisible(vi.Global):(As.firstApply=!0,As.Apply())}onDestroy(){const e=As.registry.indexOf(this);e>=0&&As.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(NP)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),dc&&console.log(i),As.buffer.Mask=i,e=As.buffer),e instanceof vi?(dc&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(dc&&console.log(this.name,"use global mask"),vi.Global.Has(this.visibleIn)),t!==void 0)if(t)dc&&console.log(this.name,"is visible",this.gameObject.uuid),P.setActive(this.gameObject,!0);else{if(dc&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};u3([p()],$P.prototype,"visibleIn");let Qn=$P;var p3=Object.defineProperty,Z0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&p3(e,t,n),n};const bd=x("debugwebxr"),WP=new B().setFromAxisAngle(new v(0,1,0),Math.PI);class cr extends T{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_remoteLeftHandMeshes;_remoteRightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;bd&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Ti.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(wt);i.avatar=this.gameObject,i.connectionId=t.owner,this.context.players.setPlayerView(t.owner,this.head?.asset,rs.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){const t=this.gameObject.getComponent(wt);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=Ti.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const c=P.getComponentsInChildren(this.head.asset,Qn);for(const h of c)h.enabled=!1,h.gameObject.visible=!1}}const n=e.xr.leftController,s=this.leftHand?.asset;s&&(n&&(s.position.copy(n.gripPosition),s.quaternion.copy(n.gripQuaternion),s.quaternion.multiply(WP)),s.visible=!0,this.updateHandVisibility(n,s,this._leftHandMeshes));const r=e.xr.rightController,a=this.rightHand?.asset;a&&(r&&(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(WP)),a.visible=!0,this.updateHandVisibility(r,a,this._rightHandMeshes))}onBeforeRender(){this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e?.isTracking===!0,s=!!e?.model&&e.model.visible&&e.model!==t,r=n&&!s;i.forEach(a=>{So(a,r)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=Ti.getFor(this);if(e&&e.isLocalPlayer==!1){const t=q.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=t.isTracking(e.owner,"left")??!1;this._remoteLeftHandMeshes=this.setRemoteHandRendered(this.leftHand?.asset,this._remoteLeftHandMeshes,i);const n=t.isTracking(e.owner,"right")??!1;this._remoteRightHandMeshes=this.setRemoteHandRendered(this.rightHand?.asset,this._remoteRightHandMeshes,n)}if(this.head?.asset){const i=P.getComponentsInChildren(this.head.asset,Qn);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}setRemoteHandRendered(e,t,i){if(!e)return t;e.visible=!0,(!t||t.length===0)&&(t=[],e.traverse(n=>{n.isMesh&&t.push(n)}));for(const n of t)So(n,i);return t}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};Y1.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 R&&(this.head=new ie("",this.sourceId,this.head));else{const e=new R;e.name="Head";const t=Gs.createPrimitive(_l.Cube);e.add(t),this.gameObject.add(e),this.head=new ie("",this.sourceId,e),bd&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof R&&(this.rightHand=new ie("",this.sourceId,this.rightHand));else{const e=new R;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ie("",this.sourceId,e),bd&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof R&&(this.leftHand=new ie("",this.sourceId,this.leftHand));else{const e=new R;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ie("",this.sourceId,e),bd&&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)}),Ti.isLocalPlayer(this.gameObject)&&(this._syncTransforms=P.getComponentsInChildren(this.gameObject,Gn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),s=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),s&&a.push(s),r&&a.push(r);const l=await Df(a);bd&&console.log("Avatar loaded results:",l)}}Z0([p(ie)],cr.prototype,"head"),Z0([p(ie)],cr.prototype,"leftHand"),Z0([p(ie)],cr.prototype,"rightHand");const m3=x("debugdecoders");let J0=null;function VP(){if(!J0){const o=wf(null);J0={dracoLoader:o.dracoLoader,ktx2Loader:o.ktx2Loader,meshoptDecoder:o.meshoptDecoder}}return J0}function GP(o){o!==void 0&&typeof o=="string"&&ZM(o)}function HP(o){if(o!==void 0&&typeof o=="string"&&o!=="js"){const e=VP();m3&&console.log("Setting draco decoder type to",o),e.dracoLoader.setDecoderConfig({type:o})}}function qP(o){o!==void 0&&typeof o=="string"&&KM(o)}function XP(o,e){const t=VP();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),QM(o),o.dracoLoader||o.setDRACOLoader(t.dracoLoader),o.ktx2Loader||o.setKTX2Loader(t.ktx2Loader),o.meshoptDecoder||o.setMeshoptDecoder(t.meshoptDecoder),YM(o,{progressive:!0}),o}const g3="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/",QP=["wrist","thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip","index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip","middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip","ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip","pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"];class f3{controller;handModel;bones=[];constructor(e,t,i,n,s=null,r=null){this.controller=t,this.handModel=e;const a=i||g3;s===null&&(s=new Zo,s.setPath(a));const l=`${n}.glb`;s.load(l,c=>{const h=c.scene.children[0];if(!h){console.error(`XRHandMeshModel: "${a}${l}" contains no hand object.`);return}this.handModel.add(h),h.layers.mask=this.handModel.layers.mask;const d=h.getObjectByProperty("type","SkinnedMesh");d?(d.frustumCulled=!1,d.castShadow=!0,d.receiveShadow=!0):console.warn(`XRHandMeshModel: no SkinnedMesh in the ${n} hand model \u2014 it will not deform.`);const u=[];for(const m of QP){const g=h.getObjectByName(m);g?g.jointName=m:u.push(m),this.bones.push(g)}u.length&&console.warn(`XRHandMeshModel: the ${n} hand model is missing ${u.length} of ${QP.length} joints (${u.join(", ")}).`),r?.(h)},void 0,c=>{console.error(`XRHandMeshModel: failed to load the ${n} hand model from "${a}${l}" \u2014 the hand will not be visible.`,c)})}updateMesh(){const e=this.controller.joints;for(let t=0;t<this.bones.length;t++){const i=this.bones[t];if(!i?.jointName)continue;const n=e[i.jointName];n?.visible&&(i.position.copy(n.position),i.quaternion.copy(n.quaternion))}}}var y3=Object.defineProperty,Ym=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&y3(e,t,n),n};const hr=x("debugwebxr"),dr=new Array;class bs extends T{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static _factory;static get factory(){return this._factory??=new lR}supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:t}=e;if(this.createControllerModel||this.createHandModel){if(t.hand){if(this.createHandModel){const i=await this.loadHandModel(this,t);if(!i||!t.connected||!t.isHand){i?.handObject&&Dl(i.handObject,!1),i?.handObject?.destroy();return}this._models.push({controller:t,model:i.handObject,handmesh:i.handmesh}),this._models.sort((n,s)=>n.controller.index-s.controller.index),this.scene.add(i.handObject),t.model=i.handObject}}else if(this.createControllerModel){const i=await t.getModelUrl();if(i){const n=await this.loadModel(t,i);if(!n||!t.connected||t.isHand)return;this._models.push({controller:t,model:n}),this._models.sort((s,r)=>s.controller.index-r.controller.index),this.scene.add(n),n.traverse(s=>{s.layers.set(2),s.matrixAutoUpdate=!1,s.updateMatrix()}),t.model=n}else t.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+t.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(Dl(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(Dl(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(q.active&&(hr&&(dr[0]=Date.now()),this.updateRendering(q.active),hr)){const e=Date.now()-dr[0];dr.push(e),dr.length>=30&&(dr[0]=0,dr.reduce((t,i)=>t+i,0)/dr.length,dr.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){hr&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const s=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(s&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const c=n.getHandJointPose(a);if(c){const h=c.transform.position,d=c.transform.orientation;l.position.copy(h),l.quaternion.copy(d),l.matrixAutoUpdate=!1}l.visible=c!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(kl))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const i=await ie.getOrCreate("",t).instantiate();return Dl(i),q.active?.isPassThrough&&i.traverseVisible(n=>{this.makeOccluder(n)}),i}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(hr?F.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const s=new Zo;XP(s,i);let r="";const a=t.side==="left"?this.customLeftHand:this.customRightHand;a?(r=a.url.split(".").slice(0,-1).join("."),s.setPath("")):(r=t.inputSource.handedness==="left"?"left":"right",s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const l=a?.url??`${s.path}${r}.glb`;await Rm(s,i,l,l);const c=v0(s),h=new R;Dl(h);const d=new f3(h,n,s.path,r,s,u=>{const m=c?.gltf;m?.scene.children?.length===0&&(m.scene.children[0]=u),c?.gltf&&is().createBuiltinComponents(e.context,l,c.gltf,null,c),u.traverse(g=>{g.layers.set(2),q.active?.isPassThrough&&!a&&this.makeOccluder(g),g instanceof V&&We.assignMeshLOD(g,0)}),t.connected||(hr&&F.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),u.removeFromParent())});if(hr&&h.add(new Ui(.5)),t.inputSource.hand){hr&&console.log(t.inputSource.hand);for(const u of t.inputSource.hand.values())if(n.joints[u.jointName]===void 0){const m=new Dn;m.matrixAutoUpdate=!1,m.visible=!0,n.joints[u.jointName]=m,n.add(m)}}else hr&&F.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:h,handmesh:d}}makeOccluder(e){if(e instanceof V){let t=e.material;t instanceof Oe&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}Ym([p()],bs.prototype,"createControllerModel"),Ym([p()],bs.prototype,"createHandModel"),Ym([p(ie)],bs.prototype,"customLeftHand"),Ym([p(ie)],bs.prototype,"customRightHand");class Km extends T{}var b3=Object.defineProperty,ur=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&b3(e,t,n),n};const e_=x("debugwebxr");class Ji extends T{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=U(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const s=Je(t);n.multiplyScalar(s.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),M()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const i=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(i)<.3&&(this._didApplyRotation=!1);else if(Math.abs(i)>.5){this._didApplyRotation=!0;const n=i>0?1:-1,s=le(this.context.mainCamera).clone();t.rotateY(n*j.toRadians(this.rotationStep));const r=le(this.context.mainCamera).clone().sub(s);r.y=0,t.position.sub(r)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const s=e.getGesture("pinch");s&&(i=s.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof al){const r=n.normal?.dot(U(0,1,0));if(r!==void 0&&r<.4)return}let s=n?.point;if(!s&&!this.useTeleportTarget){this._plane||(this._plane=new rl(new v(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new v(0,1,0),r);const a=e.ray;s=r.clone(),this._plane.intersectLine(new DM(a.origin,U(a.direction).multiplyScalar(1e4).add(a.origin)),s),s.distanceTo(r)>t.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!P.getComponentInParent(n.object,Km))return;const r=s.clone();if(e_&&F.DrawSphere(s,.025,16711680,5),this.context.mainCamera?.position){const a=this.context.xr?.getUserOffsetInRig();a&&(a.y=0,r.sub(a),e_&&F.DrawWireSphere(a.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const s=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(s),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,c=this._lastHitDistances[t],h=this._hitDistances[t]!=null,d=c??a;n.scale.set(a,a,d),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let u=n.material.opacity;l?u=1:this.showHits&&d<e.rigScale*.5?u=0:i.getButton("primary")?.pressed?u=.5:u=h?.2:.1,n.material.opacity=j.lerp(n.material.opacity,u,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],s=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,s=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(s=!1),!s){const h=this._hitDiscs[t];h&&h.visible&&h.hit&&this.updateHitPointerPosition(i,h,h.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let c=l.find(h=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(h.object));if(c||(c=l[0]),n&&(n.controller=i,n.hit=c),this._hitDistances[t]=c?.distance||null,c){this._lastHitDistances[t]=c.distance;const h=e.rigScale??1;e_&&(F.DrawWireSphere(c.point,.025*h,16711680),F.DrawLabel(U(0,.2,0).add(c.point),c.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=c,n.visible=c.distance>h*.05;let d=.01*(h+c.distance);const u=i.getButton("primary")?.pressed;u&&(d*=1.1),n.scale.set(d,d,d),n.layers.set(2);let m=n.material.opacity;if(u?m=1:m=c.distance<.15*h?.2:.6,n.material.opacity=j.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(c.normal){this.updateHitPointerPosition(i,n,c.distance);const g=c.normal.applyQuaternion(Re(c.object));n.quaternion.setFromUnitVectors(_3,g)}else this.updateHitPointerPosition(i,n,c.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Xp(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=U(e.rayWorldPosition);n.add(U(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new V(new rf(.3,6,6),new Ie({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:Bi}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new cR;e.layers.disableAll(),e.layers.enable(2);const t=new hR;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const s=new dR({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:Vv,dashed:!1});return e.material=s,e}}ur([p()],Ji.prototype,"movementSpeed"),ur([p()],Ji.prototype,"rotationStep"),ur([p()],Ji.prototype,"useTeleport"),ur([p()],Ji.prototype,"usePinchToTeleport"),ur([p()],Ji.prototype,"useTeleportTarget"),ur([p()],Ji.prototype,"useTeleportFade"),ur([p()],Ji.prototype,"showRays"),ur([p()],Ji.prototype,"showHits");const _3=new v(0,1,0);var v3=Object.defineProperty,Ft=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&v3(e,t,n),n};const _d=x("debugwebxr"),w3=x("debugusdz"),St=class Bc extends T{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!0;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){q.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&ge('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).');const e=()=>{P.findObjectOfType(Ao)||(_d&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=P.addComponent(this.gameObject,Ao),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)};this.useQuicklookExport?e():I.isVisionOS()&&q.isARSupported().then(t=>{t||e()}),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(_d&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ie("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Y0),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await q.isVRSupported()&&this.createVRButton?q.offerSession("immersive-vr","default",this.context):this.createARButton&&await q.isARSupported()&&this.createARButton?q.offerSession("immersive-ar","default",this.context):!1}get session(){return q.active??null}get sessionMode(){return q.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return q.start("immersive-vr",e,this.context)}async enterAR(e){return q.start("immersive-ar",e,this.context)}exitXR(){q.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!Bc.activeWebXRComponent||Bc.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${Bc.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}Bc.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;_d&&console.log("WebXR onEnterXR"),this._previousXRState=vi.Global.Mask;const t=e.xr.isVR;if(vi.Global.Set(t?To.VR:To.AR),e.xr.isAR){let i=P.findObjectOfType(Tn,this.context,!1);if(!i)if(this.usePlacementReticle){const n=new R;for(const s of this.context.scene.children)n.add(s);this.context.scene.add(n),i=P.addComponent(n,Tn),this._createdComponentsInSession.push(i)}else(_d||M())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=P.findObjectOfType(Qa)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Qa))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){vi.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),Cu(1).then(()=>Bc.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Ji);return!t&&e&&(t=this.gameObject.addComponent(Ji),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(bs);return!t&&e&&(t=this.gameObject.addComponent(bs),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=>{_d&&console.log("WebXR.onAvatarSpawned",e);let t=P.getComponentInChildren(e,cr);t??=P.addComponent(e,cr)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Tr.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((I.isiOS()&&I.isSafari()||w3)&&this.useQuicklookExport){const e=P.findObjectOfType(Ao);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e)}}if(this.createSendToQuestButton&&!I.isQuest()&&q.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t)}}),this.createQRCode){const e=zl(Ro);if(e&&e.createQRCodeButton===!1)M()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!I.isMobileDevice()){const t=On.getOrCreate().createQRCode();this.addButton(t)}}}_buttons=[];addButton(e){this._buttons.push(e),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};Ft([p()],St.prototype,"createVRButton"),Ft([p()],St.prototype,"createARButton"),Ft([p()],St.prototype,"createSendToQuestButton"),Ft([p()],St.prototype,"createQRCode"),Ft([p()],St.prototype,"useDefaultControls"),Ft([p()],St.prototype,"showControllerModels"),Ft([p()],St.prototype,"showHandModels"),Ft([p()],St.prototype,"usePlacementReticle"),Ft([p(ie)],St.prototype,"customARPlacementReticle"),Ft([p()],St.prototype,"usePlacementAdjustment"),Ft([p()],St.prototype,"arScale"),Ft([p()],St.prototype,"useXRAnchor"),Ft([p()],St.prototype,"autoPlace"),Ft([p()],St.prototype,"autoCenter"),Ft([p()],St.prototype,"useQuicklookExport"),Ft([p()],St.prototype,"useDepthSensing"),Ft([p()],St.prototype,"useSpatialGrab"),Ft([p(ie)],St.prototype,"defaultAvatar");let Zm=St;const Jm=x("debugusdzbehaviours");class t_{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+Ya.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{P.foreachComponent(i,n=>{const s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const r=s.beforeCreateDocument?.call(s,this,e);r instanceof Promise&&t.push(r)}},!1)}),Jm&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const d of this.behaviourComponents)typeof d.afterCreateDocument=="function"&&d.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,s=new Set,r=Jm;let a=`graph LR
1376
1376
  `,l="";function c(d){if(d instanceof Ca){r&&(a+=`subgraph Group_${d.id}
1377
1377
  `);for(const u of d.actions)r&&(a+=`${d.id}[${d.id}] -- ${d.type},loops:${d.loops} --> ${u.id}[${u.id}]
1378
1378
  `),c(u);r&&(a+=`end
@@ -1394,7 +1394,7 @@ dateFormat X
1394
1394
  axisFormat %s
1395
1395
  `;const u=Array.from(s),m=new Set;for(const f of u)if(f.affectedObjects&&typeof f.affectedObjects!="string"){if(Array.isArray(f.affectedObjects))for(const _ of f.affectedObjects)m.add(_);else m.add(f.affectedObjects);r&&(d+=`section ${f.animationName} (${f.id})
1396
1396
  `,d+=`${f.id} : ${f.start}, ${f.duration}s
1397
- `)}r&&s.size&&console.log(d);const g=new Set;for(const f of m){f.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",f);let _=f.getPath();_.startsWith("<")&&(_=_.substring(1)),_.endsWith(">")&&(_=_.substring(0,_.length-1)),g.add({path:_,obj:f})}const y=Array.from(g).sort((f,_)=>f.path.length-_.path.length),b=new Array;for(let f=0;f<y.length;f++)for(let _=f+1;_<y.length;_++)if(y[_].path.startsWith(y[f].path)){const w=y[_],S=y[f];b.push({child:w.obj.displayName+" ("+w.path+")",parent:S.obj.displayName+" ("+S.path+")"})}b.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:b,playAnimationActions:s})}for(const d of new Set([...t,...i]))if(Array.isArray(d))for(const u of d)n.add(u.uuid);else n.add(d.uuid);Jm&&console.log("All Behavior trigger sources and action targets",t,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(e,t){if(this.behaviours?.length){t.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Jm&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:i}of this.audioClipsCopy){if(e.files[i])return;const n=await(await(await fetch(t)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class i_{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=P.getComponents(e,rt).filter(l=>l.enabled),s=P.getComponents(e,Ki).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=s.length>0?s[0]:null;a&&!r&&(r=new rt,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,c)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),s.length>0){const h=s[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const d=h.sharedMaterial;d&&d.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${h.sharedMaterial?.dynamicFriction}`),d&&d.bounciness!==void 0&&l.appendLine(`double restitution = ${h.sharedMaterial?.bounciness}`),d&&d.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${h.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,c)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const h=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${h}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof Hl){const d=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${d.radius}`)}else if(a instanceof hm){const d=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${d.size.x}, ${d.size.y}, ${d.size.z})`)}else if(a instanceof hs){const d=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${d.radius}`),l.appendLine(`float height = ${d.height}`)}else if(a instanceof sr&&a.sharedMesh?.geometry){const d=a.sharedMesh.geometry;d.boundingBox||d.computeBoundingBox();const u=a.sharedMesh.geometry.boundingBox;u&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${u.max.x-u.min.x}, ${u.max.y-u.min.y}, ${u.max.z-u.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),s.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const x3=x("debugshadowcomponents");nw.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class kn extends T{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){wi.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=P.getComponentInParent(this.gameObject,vd)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=P.getComponentInParent(i,kn),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Gi]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),mh&&e.add(new Ui(.5)),this.onAfterAddedToScene(),n&&UR(),x3&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Gi]===void 0||e[Gi]===this)&&(e[Gi]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[Gi]===t){i(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class vd extends kn{awake(){super.awake()}}var S3=Object.defineProperty,C3=Object.getOwnPropertyDescriptor,wd=(o,e,t,i)=>{for(var n=i>1?void 0:i?C3(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&S3(e,t,n),n};const n_=x("debugui"),o_=x("debuguilayout");class YP{width;height}class KP{x;y;width;height}const Yn=new v,xd=new J,eg=new B,uc=class PO extends kn{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new ee),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new ee(100,100);pivot=new ee(.5,.5);anchorMin=new ee(0,0);anchorMax=new ee(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}lastMatrix;rectBlock;_transformNeedsUpdate=!1;_initialPosition;_parentRectTransform;_lastUpdateFrame=-1;awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new R,this.rectBlock.name=this.name,this.lastMatrix=new J,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new ee),$l(this,"_anchoredPosition",()=>{this.markDirty()}),$l(this,"sizeDelta",()=>{this.markDirty()}),$l(this,"pivot",()=>{this.markDirty()}),$l(this,"anchorMin",()=>{this.markDirty()}),$l(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new R),this.lastMatrix||(this.lastMatrix=new J),this._lastAnchoring||(this._lastAnchoring=new ee),this._initialPosition||(this._initialPosition=new v),this._anchoredPosition||(this._anchoredPosition=new ee),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(o_?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(o_&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=P.getComponentInParent(this.gameObject.parent,PO):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,o_&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,Yn.set(0,0,0),this.applyPivot(Yn),t.matrix.setPosition(Yn.x,Yn.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(eg.copy(this.gameObject.quaternion),eg.x*=-1,eg.z*=-1,xd.makeRotationFromQuaternion(eg),t.matrix.premultiply(xd)),Yn.set(0,0,0),this.applyAnchoring(Yn),this.canvas?.screenspace?Yn.z+=.1:Yn.z+=.01,xd.identity(),xd.setPosition(Yn.x,Yn.y,Yn.z),t.matrix.premultiply(xd),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of vb(this.gameObject,kn,i,1)){if(n===this||!n.activeAndEnabled)continue;const s=n;s.onParentRectTransformChanged&&s.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new ee);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const s=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*s,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},n_&&console.log(this.name,e);const t=new nw(e);return this._createdBlocks.push(t),t}createNewText(e){n_&&console.log(e),e={...this.getBasicOptions(),...e},n_&&console.log(this.name,e);const t=new iw(e);return this._createdTextBlocks.push(t),t}};wd([p(ee)],uc.prototype,"anchoredPosition",1),wd([p(ee)],uc.prototype,"sizeDelta",2),wd([p(ee)],uc.prototype,"pivot",2),wd([p(ee)],uc.prototype,"anchorMin",2),wd([p(ee)],uc.prototype,"anchorMax",2);let Kn=uc;var P3=Object.defineProperty,ZP=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&P3(e,t,n),n};class pc extends T{effectColor;effectDistance}ZP([p(he)],pc.prototype,"effectColor"),ZP([p(ee)],pc.prototype,"effectDistance");var k3=Object.defineProperty,O3=Object.getOwnPropertyDescriptor,JP=(o,e,t,i)=>{for(var n=i>1?void 0:i?O3(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&k3(e,t,n),n};const ka={backgroundColor:new oe(1,1,1),backgroundOpacity:1,borderColor:new oe(1,1,1),borderOpacity:1},s_=class ru extends kn{get isGraphic(){return!0}get color(){return this._color||(this._color=new he(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||("alpha"in e?this._color.alpha!==e.alpha:this._color.alpha!==1))&&(this._color||(this._color=new he(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_color=null;_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new oe(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),ka.backgroundColor=this.sRGBColor,ka.backgroundOpacity=this._color.alpha;const e=this.uiObject._simpleState__activeStates?.[0];if(e){const t=this.uiObject._simpleState__states?.[e];t&&("backgroundColor"in t&&(ka.backgroundColor=t.backgroundColor),"backgroundOpacity"in t&&(ka.backgroundOpacity=t.backgroundOpacity))}ka.backgroundOpacity*=this._alphaFactor,this.applyEffects(ka,this._alphaFactor),this.uiObject.set(ka),this.markDirty()}}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||(this._rect=P.getComponent(this.gameObject,Kn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new zR(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),$l(this,"_color",()=>TL(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(pc);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}static textureCache=new Map;async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(ru.textureCache.has(e))e=ru.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=Xo,ru.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),We.assignTextureLOD(e,0).then(t=>{t instanceof Pe&&(e&&ru.textureCache.set(e,t),this.setOptions({backgroundImage:t}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};JP([p(he)],s_.prototype,"color",1),JP([p()],s_.prototype,"raycastTarget",2);let Sd=s_;class Cd extends Sd{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var M3=Object.defineProperty,R3=Object.getOwnPropertyDescriptor,_s=(o,e,t,i)=>{for(var n=R3(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&M3(e,t,n),n};const pr=x("debugtext");var ut=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(ut||{}),ek=(o=>(o[o.Truncate=0]="Truncate",o[o.Overflow=1]="Overflow",o))(ek||{}),tk=(o=>(o[o.Wrap=0]="Wrap",o[o.Overflow=1]="Overflow",o))(tk||{}),tg=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(tg||{});class ii extends Sd{set alignment(e){e!==this._alignment&&(this._alignment=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get alignment(){return this._alignment}_alignment=0;set verticalOverflow(e){e!==this._verticalOverflow&&(this._verticalOverflow=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get verticalOverflow(){return this._verticalOverflow}_verticalOverflow=0;set horizontalOverflow(e){e!==this._horizontalOverflow&&(this._horizontalOverflow=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get horizontalOverflow(){return this._horizontalOverflow}_horizontalOverflow=0;set lineSpacing(e){e!==this._lineSpacing&&(this._lineSpacing=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get lineSpacing(){return this._lineSpacing}_lineSpacing=1;set fontStyle(e){e!==this._fontStyle&&(this._fontStyle=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get fontStyle(){return this._fontStyle}_fontStyle=0;set font(e){e!==this._font&&(this._font=e,this.uiObject?.set(this.getTextOpts()),this.markDirty(),this._assignedAtRuntime=this.__didAwake)}get font(){return this._font}_font="https://cdn.needle.tools/static/fonts/msdf/arial/arial";_assignedAtRuntime=!0;set supportRichText(e){e!==this._supportRichText&&(this._supportRichText=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get supportRichText(){return this._supportRichText}_supportRichText=!1;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty(),this.context.accessibility.updateElement(this,{label:this.text}))}_text="";set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}_fontSize=12;sRGBTextColor=new oe(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){const e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){pr&&console.log("[Text] onCreate",this),delete e.backgroundOpacity,delete e.backgroundColor,pr&&(e.backgroundColor=16750848,e.backgroundOpacity=.5),e={...e,...this.getTextOpts()},this.getAlignment(e),pr&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1);const t=this.rectTransform;this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_textMeshUi=null;getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.horizontalOverflow==1&&(t.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,t.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,t.lineHeight=this.lineSpacing,this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"text",label:this.text,hidden:!1}),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){super.onDestroy(),this.context.accessibility.removeElement(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){if(pr&&console.log("[Text] feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const s=new Mf({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(s)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const s=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(s){r.textContent=this.getText(e,i,s),this.handleTag(i,r,n);const a=new Mf(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new Mf(r);this.uiObject?.add(a)}i=s}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let s=0;s<this._textMeshUi.length;s++){if(e[s]===!0)continue;n=!0;const r=this._textMeshUi[s];r.textContent&&(Yp(r,i),e[s]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new r_(e,{color:t.color});if(i.push(n),e.type.length>6){const s=parseInt("0x"+e.type.substring(7));t.color=s}else t.color=new oe(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new r_(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new r_(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const s=e.substring(i+1,n);return{type:s,startIndex:i,endIndex:n+1,isEndTag:s.startsWith("/")}}return null}setFont(e,t){if(!this.font){pr&&console.warn("[Text] No font set for Text component, skipping font setup");return}const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);pr&&console.log(`[Text] Selected font family '${n}' from ${i} with style ${tg[t]}`);let s=ow.getFontFamily(n);switch(s||(s=ow.addFontFamily(n)),e.fontFamily=s,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let r=s.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=s.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){const i=e.startsWith("https:")||e.startsWith("http:"),n=e.lastIndexOf("-");if(n<0)return e;const s=e.substring(n+1)?.toLowerCase();if(T3.includes(s))return pr&&console.warn("[Text] Unsupported font style: "+s),e;const r=e.lastIndexOf("/");let a=e;r>=0&&(a=a.substring(r+1));const l=a[0]===a[0].toUpperCase(),c=e.substring(0,n>r?n:e.length);if(pr&&console.log("[Text] Select font: ",e,tg[t],a,l,c),i&&this._assignedAtRuntime&&!(e.endsWith("-msdf.json")||e.endsWith(".png")))return c;switch(t){case 0:return l?c+"-Regular":c+"-regular";case 1:return l?c+"-Bold":c+"-bold";case 2:return l?c+"-Italic":c+"-italic";case 3:return l?c+"-BoldItalic":c+"-bolditalic";default:return e}}}_s([p()],ii.prototype,"alignment"),_s([p()],ii.prototype,"verticalOverflow"),_s([p()],ii.prototype,"horizontalOverflow"),_s([p()],ii.prototype,"lineSpacing"),_s([p()],ii.prototype,"fontStyle"),_s([p(URL)],ii.prototype,"font"),_s([p()],ii.prototype,"supportRichText"),_s([p()],ii.prototype,"text"),_s([p()],ii.prototype,"fontSize");class r_{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const T3=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class mc{static global_id=0;static getId(){return this.global_id++}id;content="";font=[];pointSize=144;width;height;depth;wrapMode;horizontalAlignment;verticalAlignment;material;setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}constructor(e){this.id=e}writeTo(e,t){t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||=[],this.font?.push("sans-serif"));const i=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${i} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${Nm(this.material)}>`),t.closeBlock()}}class a_{static singleLine(e,t,i){const n=new mc("text_"+mc.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,s,r){const a=new mc("text_"+mc.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=s,r!==void 0&&(a.wrapMode=r),a}}const E3=new J().makeRotationY(Math.PI),A3=new J().makeScale(-1,1,-1);class ig{get extensionName(){return"text"}exportText(e,t,i){const n=P.getComponent(e,ii);if(!n)return;const s=P.getComponent(e,Kn);let r=100,a=100;s&&(r=s.width,a=s.height);const l=E3.clone();s&&l.premultiply(A3),t.setMatrix(l);const c=n.color.clone();t.material=new Mt({color:c,emissive:c}),t.addEventListener("serialize",(h,d)=>{let u=n.text;u=u.replace(/\r/g,""),u=u.replace(/\n/g,"\\n");const m=a_.multiLine(u,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,h)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case ut.LowerLeft:case ut.MiddleLeft:case ut.UpperLeft:e.horizontalAlignment="left";break;case ut.LowerCenter:case ut.MiddleCenter:case ut.UpperCenter:e.horizontalAlignment="center";break;case ut.LowerRight:case ut.MiddleRight:case ut.UpperRight:e.horizontalAlignment="right";break}switch(t){case ut.LowerLeft:case ut.LowerCenter:case ut.LowerRight:e.verticalAlignment="bottom";break;case ut.MiddleLeft:case ut.MiddleCenter:case ut.MiddleRight:e.verticalAlignment="middle";break;case ut.UpperLeft:case ut.UpperCenter:case ut.UpperRight:e.verticalAlignment="top";break}}}var I3=Object.defineProperty,pt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&I3(e,t,n),n};const ik=x("debuguilayout");class Oa{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}pt([p()],Oa.prototype,"left"),pt([p()],Oa.prototype,"right"),pt([p()],Oa.prototype,"top"),pt([p()],Oa.prototype,"bottom");class en extends T{_rectTransform=null;get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}_needsUpdate=!1;get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(ik&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}childAlignment=0;reverseArrangement=!1;spacing=0;padding;minWidth=0;minHeight=0;flexibleHeight=0;flexibleWidth=0;preferredHeight=0;preferredWidth=0;start(){this._needsUpdate=!0}onEnable(){ik&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Kn);const e=this.gameObject.getComponentInParent(gc);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(gc);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}pt([p()],en.prototype,"childAlignment"),pt([p()],en.prototype,"reverseArrangement"),pt([p()],en.prototype,"spacing"),pt([p(Oa)],en.prototype,"padding"),pt([p()],en.prototype,"minWidth"),pt([p()],en.prototype,"minHeight"),pt([p()],en.prototype,"flexibleHeight"),pt([p()],en.prototype,"flexibleWidth"),pt([p()],en.prototype,"preferredHeight"),pt([p()],en.prototype,"preferredWidth");class mr extends en{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const s=e.height;let r=s;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",c=a?this.childControlWidth:this.childControlHeight,h=a?this.childControlHeight:this.childControlWidth,d=a?this.childForceExpandWidth:this.childForceExpandHeight,u=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,g=a?i:s,y=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let b=0;a?b+=this.padding.left:b+=this.padding.top;let f=0,_=0;for(let D=0;D<this.gameObject.children.length;D++){const W=this.gameObject.children[D],$=P.getComponent(W,Kn);$?.activeAndEnabled&&(_+=1,a?f+=$.width:f+=$.height)}let w=0;const S=this.spacing*(_-1);if(d||c){let D=0;a?D=n-=S:D=r-=S,_>0&&(w=D/_)}let O=0;O+=this.padding.left,O-=this.padding.right,y!==0&&(b=g-f,b*=y,b-=S*y,a?(b-=this.padding.right*y,b+=this.padding.left*(1-y),b<this.padding.left&&(b=this.padding.left)):(b-=this.padding.bottom*y,b+=this.padding.top*(1-y),b<this.padding.top&&(b=this.padding.top)));let L=1;for(let D=0;D<this.gameObject.children.length;D++){const W=this.gameObject.children[D],$=P.getComponent(W,Kn);if($?.activeAndEnabled){$.pivot?.set(.5,.5),$.anchorMin.set(0,1),$.anchorMax.set(0,1);const H=i*.5+O*.5;$.anchoredPosition.x!==H&&($.anchoredPosition.x=H);const G=s*-.5;$.anchoredPosition.y!==G&&($.anchoredPosition.y=G),u&&h&&$.sizeDelta[l]!==m&&($.sizeDelta[l]=m),d&&c&&$.sizeDelta[t]!==w&&($.sizeDelta[t]=w);const E=a?$.width:$.height,z=E*.5;if(b+=z,d){const K=w*L-w*.5;K>b&&(b=K-w*.5+E+this.padding.left,b-=z)}let Y=b;t==="y"&&(Y=-Y),$.anchoredPosition[t]!==Y&&($.anchoredPosition[t]=Y),b+=z,b+=this.spacing,L+=1}}}}pt([p()],mr.prototype,"childControlHeight"),pt([p()],mr.prototype,"childControlWidth"),pt([p()],mr.prototype,"childForceExpandHeight"),pt([p()],mr.prototype,"childForceExpandWidth"),pt([p()],mr.prototype,"childScaleHeight"),pt([p()],mr.prototype,"childScaleWidth");class l_ extends mr{get primaryAxis(){return"y"}}class c_ extends mr{get primaryAxis(){return"x"}}class h_ extends en{onCalculateLayout(){}}var L3=Object.defineProperty,D3=Object.getOwnPropertyDescriptor,Eo=(o,e,t,i)=>{for(var n=i>1?void 0:i?D3(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&L3(e,t,n),n},nk=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(nk||{});const d_=x("debuguilayout"),yn=class kO extends vd{get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}_renderOnTop;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!1;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!1;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=2;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof kO||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}worldCamera;planeDistance=100;awake(){this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,d_&&console.log("Canvas.Awake()",this.previousParent?.name+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new J,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}_boundRenderSettingsChanged=this.onRenderSettingsChanged.bind(this);previousParent=null;_lastMatrixWorld=null;_rectTransforms=[];registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}_layoutGroups=new Map;registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}_receivers=[];registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}onEnterXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1)}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),wi.ensureUpdateMeshUI(sw,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);const e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),wi.ensureUpdateMeshUI(sw,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(const e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new J);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);d_&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(en)),(t.isDirty||i?.isDirty)&&(d_&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Ee.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Yp(this.shadowComponent,this);for(const e of P.getComponentsInChildren(this.gameObject,kn))Yp(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=j.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const s=this.gameObject.getComponent(Kn);let r=!1;s.sizeDelta.x!==this.context.domWidth&&(r=!0),s.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,r&&(s.sizeDelta.x=this.context.domWidth,s.sizeDelta.y=this.context.domHeight,s?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};Eo([p()],yn.prototype,"renderOnTop",1),Eo([p()],yn.prototype,"depthWrite",1),Eo([p()],yn.prototype,"doubleSided",1),Eo([p()],yn.prototype,"castShadows",1),Eo([p()],yn.prototype,"receiveShadows",1),Eo([p()],yn.prototype,"renderMode",1),Eo([p(yn)],yn.prototype,"rootCanvas",1),Eo([p()],yn.prototype,"scaleFactor",1),Eo([p(pi)],yn.prototype,"worldCamera",2),Eo([p()],yn.prototype,"planeDistance",2);let gc=yn;var j3=Object.defineProperty,F3=Object.getOwnPropertyDescriptor,u_=(o,e,t,i)=>{for(var n=i>1?void 0:i?F3(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&j3(e,t,n),n};class gr extends T{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Ee.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of P.getComponentsInChildren(this.gameObject,kn,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}u_([p()],gr.prototype,"alpha",1),u_([p()],gr.prototype,"interactable",2),u_([p()],gr.prototype,"blocksRaycasts",2);class p_{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=P.getComponent(e,gc);if(n&&n.enabled&&n.renderMode===nk.WorldSpace){const s=new ig,r=P.getComponent(e,Kn),a=P.getComponent(e,gr),l=new Array;if(r){if(!P.isActiveSelf(e)){const d=P.isActiveSelf(e);P.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),P.setActive(e,d)})}e.traverse(d=>{if(!P.isActiveInHierarchy(d)){const u=P.isActiveSelf(d);P.setActive(d,!0);const m=P.getComponent(d,kn);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const g=P.getComponent(d,Kn);g&&(g.onEnable(),g.updateTransform(),g.onApplyTransform(),l.push(()=>{g.onDisable()}));const y=P.getComponent(d,ii);y&&(y.onEnable(),l.push(()=>{y.onDisable()})),l.push(()=>{P.setActive(d,u)})}}),r.width,r.height;const c=vt.createEmpty(),h=r.shadowComponent;if(t.add(c),h){const d=h.matrix;c.setMatrix(d);const u=new Map,m=new Map;u.set(h,c),m.set(h,a?a.alpha:1),h.traverse(g=>{if(g===h)return;const y=vt.createEmpty();y.setMatrix(g.matrix);const b=g.parent,f=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let _=m.get(b)||1;const w=P.getComponent(g,gr);if(w&&(_*=w.alpha),g instanceof V&&f){const O=g[Gi];O?s.exportText(O.gameObject,y,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",g)}if(g instanceof V&&!f){const O=g.geometry.clone();O.scale(1,1,-1),this.flipWindingOrder(O),y.geometry=O;const L=new oe,D=g.material.opacity;L.copy(g.material.color),y.material=new Ie({color:L,opacity:D*_,map:g.material.map,transparent:!0})}u.set(g,y),m.set(g,_);const S=u.get(b);if(!S){console.error("Error when exporting UI: shadow component parent not found!",g,g.parent);return}S.add(y)})}}for(const c of l)c()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const s=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=s}e.index.needsUpdate=!0}}const Pd=x("debugusdz");function B3(o,e){const t=[],i=P.getComponentsInChildren(o,Et),n=P.getComponentsInChildren(o,Zt),s=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||s.includes(a))continue;const c=new ud;c.animator=a,c.stateName=l.name,c.trigger="start",c.name="PlayAnimationOnClick_implicitAtStart_"+c.stateName;const h=new R;P.addComponent(h,c),r.push(h),s.push(a),o.add(h)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;Pd&&console.log(a);const l=[];for(const c of a.runtimeAnimatorController.enumerateActions()){Pd&&console.log(c);const h=c.getClip();l.includes(h)||l.push(h)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||s.includes(a))continue;const l=new ud;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const c=new R;P.addComponent(c,l),r.push(c),s.push(a),o.add(c)}else for(const a of n){Pd&&console.log(a);const l=[];for(const c of a.animations)l.includes(c)||l.push(c);t.push({root:a.gameObject,clips:l})}Pd&&t?.length>0&&console.log("USDZ Animation Clips without behaviours",t);for(const a of t)for(const l of a.clips)e.registerAnimation(a.root,l);return r}function U3(o,e){const t=P.getComponentsInChildren(o,Yi),i=P.getComponentsInChildren(o,lr),n=new Array,s=new Array;Pd&&console.log({audioSources:t,playAudioOnClicks:i});for(const r of i){if(!r.target)continue;const a=t.indexOf(r.target);a>-1&&t.splice(a,1)}for(const r of t){if(!r||!r.clip||r.volume<=0||n.includes(r))continue;const a=new lr;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new R;P.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),s.push(l),n.push(r),o.add(l)}return s}function z3(o){return new qt("DisableAtStart",ei.sceneStartTrigger(),be.fadeAction(o,0,!1))}function ok(o,e){const t=o.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const r=document.createElement("img");return r.id="button",s.appendChild(r),o.domElement.shadowRoot.appendChild(i),s}var N3=Object.defineProperty,zt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&N3(e,t,n),n};const Nt=x("debugusdz"),$3=x("debugusdzpruning");class Ma{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}zt([p()],Ma.prototype,"callToAction"),zt([p()],Ma.prototype,"checkoutTitle"),zt([p()],Ma.prototype,"checkoutSubtitle"),zt([p()],Ma.prototype,"callToActionURL");const Ei=class Xa extends T{static beforeExport=new re;static afterExport=new re;static beforeLODExport=new re;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(){Nt&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{e.key==="t"&&this.exportAndOpen()})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=I.supportsQuickLookAR(),t=I.isiOS()||I.isiPad();!this.button&&(Nt||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=ok(this.context,e),this.link.addEventListener("message",this.lastCallback)),Nt&&Fe("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),Sh.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),Nt&&Fe("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),Sh.unregisterExporter(this)}onClickedOpenInARElement=e=>{e.preventDefault(),this.exportAndOpen()};async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){let e=this.exportFileName??this.objectToExport?.name??this.name;if(e+="-"+gP(),mo()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=ok(this.context,I.supportsQuickLookAR())),this.customUsdzFile)return Nt&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;Xa.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Xa.afterExport.invoke({exporter:this})});return t?(Nt&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){ue.start("export-usdz",{onProgress:S=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:S}}))}}),ue.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ue.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ue.start("export-usdz-textures","export-usdz");const t=P.getComponentsInChildren(e,Ri);for(const S of t)S&&S.enabled&&S.updateSprite(!0);const i=P.getComponentsInChildren(e,gi),n=new Array;let s=0;for(const S of i){for(const O of S.sharedMeshes)if(O){let L=0;const D={exporter:this,type:"mesh",object:S.gameObject,mesh:O};if(Xa.beforeLODExport.invoke(D),D.overrideLevel!==void 0)if(D.overrideLevel===-1){Nt&&console.warn("Skipping LOD export for mesh due to overrideLevel -1",S.gameObject,O);continue}else D.overrideLevel>=0&&(L=D.overrideLevel,Nt&&console.log("Overriding LOD level for mesh export to level "+L+" "+O.name));const W=We.assignMeshLOD(O,L);W instanceof Promise&&n.push(new Promise(($,H)=>{W.then(()=>{s++,ue.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:s,totalSteps:n.length}),$()}).catch(G=>H(G))}))}for(const O of S.sharedMaterials)if(O){let L=0;const D={exporter:this,type:"texture",object:S.gameObject,material:O};if(Xa.beforeLODExport.invoke(D),D.overrideLevel!==void 0)if(D.overrideLevel===-1){Nt&&console.warn("Skipping LOD assignment due to overrideLevel -1",S.gameObject,O);continue}else D.overrideLevel>=0&&(L=D.overrideLevel,Nt&&console.log("Overriding LOD level for texture export to level "+L+" "+O.name));const W=We.assignTextureLOD(O,L);W instanceof Promise&&n.push(new Promise(($,H)=>{W.then(()=>{s++,ue.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:n.length}),$()}).catch(G=>H(G))}))}}Nt&&Fe("Progressive Loading: "+n.length),await Promise.all(n),Nt&&Fe("Progressive Loading: done"),ue.end("export-usdz-textures");const r=vi.Global.Mask;vi.Global.Set(To.AR);const a=new wP,l=new Vm(this.quickLookCompatible);let c;const h=[];this.interactive&&(h.push(new t_),h.push(new Ya),globalThis.NEEDLE_USE_RAPIER&&P.getComponentsInChildren(e,rt).length>0&&(this.physics?(c=new i_,h.push(c)):M()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),h.push(new ig),h.push(new p_));const d=[l,...h,...this.extensions],u={self:this,exporter:a,extensions:d,object:e};ue.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:u})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,ue.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...B3(e,l)),d.find(S=>S.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...U3(e)),a.debug=Nt,a.pruneUnusedNodes=!$3;const g=Ka.instance.objs.map(S=>S.batchedMesh);a.keepObject=S=>{let O=!0;const L=P.getComponent(S,gi);return L&&!L.enabled&&(O=!1),O&&g.includes(S)&&(O=!1),O&&P.getComponentInParent(S,sd)&&(O=!1),O&&P.getComponentInParent(S,wo)&&(O=!1),Nt&&!O&&console.log("USDZExporter: Discarding object",S),O},a.beforeWritingDocument=()=>{if(M()&&l&&c){const S=l.animatedRoots;for(const O of S){const L=P.getComponentsInChildren(O,rt).filter(W=>W.enabled),D=P.getComponents(O,Ki).filter(W=>W.enabled&&!W.isTrigger);(L.length>0||D.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",O)}}};const y=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(S=>{S.visible||y.push(S)});const b=d.find(S=>S.extensionName==="Behaviour");this.interactive&&b&&y.length>0&&b.addBehavior(z3(y));let f=!0;this.quickLookCompatible&&!this.interactive&&(f=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),ue.report("export-usdz","Invoking exporter.parse");const _=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:d,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:f}),w=new Blob([_],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ue.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:u}));for(const S of m)P.destroy(S);return vi.Global.Set(r),ue.end("export-usdz"),w}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();Nt&&console.log("QuickLook Overlay",n);const s=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${s}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){Xa.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}lastCallback;quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){Nt&&ge("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");Nt&&Fe("Quicklook url: "+n),n&&(mo()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){const e={};return this.customBranding&&Object.assign(e,this.customBranding),mo()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="\u{1F335} 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 J().makeRotationY(Math.PI);static invertForwardQuaternion=new B().setFromEuler(new je(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new v;_rootRotationBeforeExport=new B;_rootScaleBeforeExport=new v;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=P.findObjectOfType(Zm);let t=P.getComponentInParent(this.objectToExport,Tn);t||(t=P.getComponentInChildren(this.objectToExport,Tn));let i=1,n=!1;const s=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:s,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),s=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(Xa.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&s&&i.matrix.premultiply(s)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const e=Tr.getOrCreate().createQuicklookButton();return e.parentNode||this.context.menu.appendChild(e),e}};zt([p(R)],Ei.prototype,"objectToExport"),zt([p()],Ei.prototype,"autoExportAnimations"),zt([p()],Ei.prototype,"autoExportAudioSources"),zt([p()],Ei.prototype,"exportFileName"),zt([p(URL)],Ei.prototype,"customUsdzFile"),zt([p(Ma)],Ei.prototype,"customBranding"),zt([p()],Ei.prototype,"anchoringType"),zt([p()],Ei.prototype,"maxTextureSize"),zt([p()],Ei.prototype,"planeAnchoringAlignment"),zt([p()],Ei.prototype,"interactive"),zt([p()],Ei.prototype,"physics"),zt([p()],Ei.prototype,"allowCreateQuicklookButton"),zt([p()],Ei.prototype,"quickLookCompatible");let Ao=Ei;Kj({find:()=>zl(Ao),create:()=>new Ao});var W3=Object.defineProperty,V3=Object.getOwnPropertyDescriptor,m_=(o,e,t,i)=>{for(var n=V3(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&W3(e,t,n),n};class fc extends T{get fog(){return this._fog||(this._fog=new Tv(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}_fog;onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}m_([p()],fc.prototype,"near"),m_([p()],fc.prototype,"far"),m_([p(oe)],fc.prototype,"color");const sk=Rt,G3=x("debugtypestore");G3&&console.log(k);function H3(o,e){const t=Fx(o,e);if(t!=null)return t;const i={name:k.getKey(o.constructor)||o.constructor.name};return typeof o.guid=="string"&&(i.guid=o.guid),o.enabled===!1&&(i.enabled=!1),i}const q3=new jx,g_=Symbol("deserialize-queue");function rk(o,e,t,i){const n=new e;i.gltfId!==void 0&&(n.sourceId=i.gltfId),bl(n,t,i.implementationInformation),n.context=i.context,"guid"in t&&(n[ts]=t.guid),n[Th]=t.name,aa(o,n,!1);const s=i.context;return n.isCamera&&s&&s.mainCamera===null&&n.tag==="MainCamera"&&s.setCurrentCamera(n),s?.physics?.engine?.isInitialized===!1&&(n.isCollider||n.isRigidbody)&&s.physics.engine?.initialize(),n}async function X3(o,e,t,i=null,n){if(!t){console.debug("Can not create component instances: gltf is null");return}const s=[];let r=i;typeof r=="number"&&(r=new _t(i));const a=e.indexOf("?");e=a===-1?e:e.substring(0,a);const l=new gh(t.scene);l.gltfId=e,l.context=o,l.gltf=t,l.nodeToObject=n?.nodeToObjectMap,l.implementationInformation=q3;let c=o[g_];if(c||(c=o[g_]=[]),t.scenes)for(const h of t.scenes)await f_(l,h,c,s,0);if(t.children)for(const h of t.children)await f_(l,h,c,s,0);o.new_scripts_pre_setup_callbacks.push(()=>{const h=o[g_];if(h){for(const d of h)Q3(d,l);h.length=0}if(r){const d={};ub(t,r,d);for(const u of t.scenes)ub(u,r,d);uS(t,d);for(const u of t.scenes)uS(u,d)}})}const kd=[];async function f_(o,e,t,i,n){if(!e)return;const s=e.userData;if(s){const r=s.builtin_components;if(r&&r.length>0)for(const a of r)try{if(a===null)continue;let l=k.get(a.name);if(l||(l=await k.getAsync(a.name)),l){const c=rk(e,l,a,o);t.push({instance:c,compData:a,obj:e})}else sk&&console.debug("unknown component: "+a.name),kd.includes(a.name)||kd.push(a.name)}catch(l){console.error(a.name+" - "+l.message,l)}}if(e.children)for(const r of e.children)await f_(o,r,t,i,n+1);if(kd.length>0&&n===0){const r=kd.join(", ");console.warn(`Unknown components in scene: ${r}`),kd.length=0,Ni()&&Fe(`<strong>Unknown components in scene</strong>:
1397
+ `)}r&&s.size&&console.log(d);const g=new Set;for(const f of m){f.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",f);let _=f.getPath();_.startsWith("<")&&(_=_.substring(1)),_.endsWith(">")&&(_=_.substring(0,_.length-1)),g.add({path:_,obj:f})}const y=Array.from(g).sort((f,_)=>f.path.length-_.path.length),b=new Array;for(let f=0;f<y.length;f++)for(let _=f+1;_<y.length;_++)if(y[_].path.startsWith(y[f].path)){const w=y[_],S=y[f];b.push({child:w.obj.displayName+" ("+w.path+")",parent:S.obj.displayName+" ("+S.path+")"})}b.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:b,playAnimationActions:s})}for(const d of new Set([...t,...i]))if(Array.isArray(d))for(const u of d)n.add(u.uuid);else n.add(d.uuid);Jm&&console.log("All Behavior trigger sources and action targets",t,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(e,t){if(this.behaviours?.length){t.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Jm&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:i}of this.audioClipsCopy){if(e.files[i])return;const n=await(await(await fetch(t)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class i_{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=P.getComponents(e,rt).filter(l=>l.enabled),s=P.getComponents(e,Ki).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=s.length>0?s[0]:null;a&&!r&&(r=new rt,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,c)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),s.length>0){const h=s[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const d=h.sharedMaterial;d&&d.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${h.sharedMaterial?.dynamicFriction}`),d&&d.bounciness!==void 0&&l.appendLine(`double restitution = ${h.sharedMaterial?.bounciness}`),d&&d.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${h.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,c)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const h=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${h}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof Hl){const d=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${d.radius}`)}else if(a instanceof hm){const d=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${d.size.x}, ${d.size.y}, ${d.size.z})`)}else if(a instanceof hs){const d=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${d.radius}`),l.appendLine(`float height = ${d.height}`)}else if(a instanceof sr&&a.sharedMesh?.geometry){const d=a.sharedMesh.geometry;d.boundingBox||d.computeBoundingBox();const u=a.sharedMesh.geometry.boundingBox;u&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${u.max.x-u.min.x}, ${u.max.y-u.min.y}, ${u.max.z-u.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),s.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const x3=x("debugshadowcomponents");nw.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class kn extends T{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){wi.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=P.getComponentInParent(this.gameObject,vd)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=P.getComponentInParent(i,kn),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Gi]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),mh&&e.add(new Ui(.5)),this.onAfterAddedToScene(),n&&UR(),x3&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Gi]===void 0||e[Gi]===this)&&(e[Gi]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[Gi]===t){i(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class vd extends kn{awake(){super.awake()}}var S3=Object.defineProperty,C3=Object.getOwnPropertyDescriptor,wd=(o,e,t,i)=>{for(var n=i>1?void 0:i?C3(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&S3(e,t,n),n};const n_=x("debugui"),o_=x("debuguilayout");class YP{width;height}class KP{x;y;width;height}const Yn=new v,xd=new J,eg=new B,uc=class PO extends kn{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new ee),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new ee(100,100);pivot=new ee(.5,.5);anchorMin=new ee(0,0);anchorMax=new ee(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}lastMatrix;rectBlock;_transformNeedsUpdate=!1;_initialPosition;_parentRectTransform;_lastUpdateFrame=-1;awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new R,this.rectBlock.name=this.name,this.lastMatrix=new J,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new ee),$l(this,"_anchoredPosition",()=>{this.markDirty()}),$l(this,"sizeDelta",()=>{this.markDirty()}),$l(this,"pivot",()=>{this.markDirty()}),$l(this,"anchorMin",()=>{this.markDirty()}),$l(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new R),this.lastMatrix||(this.lastMatrix=new J),this._lastAnchoring||(this._lastAnchoring=new ee),this._initialPosition||(this._initialPosition=new v),this._anchoredPosition||(this._anchoredPosition=new ee),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(o_?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(o_&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=P.getComponentInParent(this.gameObject.parent,PO):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,o_&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,Yn.set(0,0,0),this.applyPivot(Yn),t.matrix.setPosition(Yn.x,Yn.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(eg.copy(this.gameObject.quaternion),eg.x*=-1,eg.z*=-1,xd.makeRotationFromQuaternion(eg),t.matrix.premultiply(xd)),Yn.set(0,0,0),this.applyAnchoring(Yn),this.canvas?.screenspace?Yn.z+=.1:Yn.z+=.01,xd.identity(),xd.setPosition(Yn.x,Yn.y,Yn.z),t.matrix.premultiply(xd),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of vb(this.gameObject,kn,i,1)){if(n===this||!n.activeAndEnabled)continue;const s=n;s.onParentRectTransformChanged&&s.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new ee);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const s=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*s,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},n_&&console.log(this.name,e);const t=new nw(e);return this._createdBlocks.push(t),t}createNewText(e){n_&&console.log(e),e={...this.getBasicOptions(),...e},n_&&console.log(this.name,e);const t=new iw(e);return this._createdTextBlocks.push(t),t}};wd([p(ee)],uc.prototype,"anchoredPosition",1),wd([p(ee)],uc.prototype,"sizeDelta",2),wd([p(ee)],uc.prototype,"pivot",2),wd([p(ee)],uc.prototype,"anchorMin",2),wd([p(ee)],uc.prototype,"anchorMax",2);let Kn=uc;var P3=Object.defineProperty,ZP=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&P3(e,t,n),n};class pc extends T{effectColor;effectDistance}ZP([p(he)],pc.prototype,"effectColor"),ZP([p(ee)],pc.prototype,"effectDistance");var k3=Object.defineProperty,O3=Object.getOwnPropertyDescriptor,JP=(o,e,t,i)=>{for(var n=i>1?void 0:i?O3(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&k3(e,t,n),n};const ka={backgroundColor:new oe(1,1,1),backgroundOpacity:1,borderColor:new oe(1,1,1),borderOpacity:1},s_=class ru extends kn{get isGraphic(){return!0}get color(){return this._color||(this._color=new he(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||("alpha"in e?this._color.alpha!==e.alpha:this._color.alpha!==1))&&(this._color||(this._color=new he(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_color=null;_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new oe(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),ka.backgroundColor=this.sRGBColor,ka.backgroundOpacity=this._color.alpha;const e=this.uiObject._simpleState__activeStates?.[0];if(e){const t=this.uiObject._simpleState__states?.[e];t&&("backgroundColor"in t&&(ka.backgroundColor=t.backgroundColor),"backgroundOpacity"in t&&(ka.backgroundOpacity=t.backgroundOpacity))}ka.backgroundOpacity*=this._alphaFactor,this.applyEffects(ka,this._alphaFactor),this.uiObject.set(ka),this.markDirty()}}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||(this._rect=P.getComponent(this.gameObject,Kn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new zR(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),$l(this,"_color",()=>TL(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(pc);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}static textureCache=new Map;async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(ru.textureCache.has(e))e=ru.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=Xo,ru.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),We.assignTextureLOD(e,0).then(t=>{t instanceof ke&&(e&&ru.textureCache.set(e,t),this.setOptions({backgroundImage:t}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};JP([p(he)],s_.prototype,"color",1),JP([p()],s_.prototype,"raycastTarget",2);let Sd=s_;class Cd extends Sd{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var M3=Object.defineProperty,R3=Object.getOwnPropertyDescriptor,_s=(o,e,t,i)=>{for(var n=R3(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&M3(e,t,n),n};const pr=x("debugtext");var ut=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(ut||{}),ek=(o=>(o[o.Truncate=0]="Truncate",o[o.Overflow=1]="Overflow",o))(ek||{}),tk=(o=>(o[o.Wrap=0]="Wrap",o[o.Overflow=1]="Overflow",o))(tk||{}),tg=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(tg||{});class ii extends Sd{set alignment(e){e!==this._alignment&&(this._alignment=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get alignment(){return this._alignment}_alignment=0;set verticalOverflow(e){e!==this._verticalOverflow&&(this._verticalOverflow=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get verticalOverflow(){return this._verticalOverflow}_verticalOverflow=0;set horizontalOverflow(e){e!==this._horizontalOverflow&&(this._horizontalOverflow=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get horizontalOverflow(){return this._horizontalOverflow}_horizontalOverflow=0;set lineSpacing(e){e!==this._lineSpacing&&(this._lineSpacing=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get lineSpacing(){return this._lineSpacing}_lineSpacing=1;set fontStyle(e){e!==this._fontStyle&&(this._fontStyle=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get fontStyle(){return this._fontStyle}_fontStyle=0;set font(e){e!==this._font&&(this._font=e,this.uiObject?.set(this.getTextOpts()),this.markDirty(),this._assignedAtRuntime=this.__didAwake)}get font(){return this._font}_font="https://cdn.needle.tools/static/fonts/msdf/arial/arial";_assignedAtRuntime=!0;set supportRichText(e){e!==this._supportRichText&&(this._supportRichText=e,this.uiObject?.set(this.getTextOpts()),this.markDirty())}get supportRichText(){return this._supportRichText}_supportRichText=!1;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty(),this.context.accessibility.updateElement(this,{label:this.text}))}_text="";set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}_fontSize=12;sRGBTextColor=new oe(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){const e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){pr&&console.log("[Text] onCreate",this),delete e.backgroundOpacity,delete e.backgroundColor,pr&&(e.backgroundColor=16750848,e.backgroundOpacity=.5),e={...e,...this.getTextOpts()},this.getAlignment(e),pr&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1);const t=this.rectTransform;this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_textMeshUi=null;getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.horizontalOverflow==1&&(t.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,t.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,t.lineHeight=this.lineSpacing,this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"text",label:this.text,hidden:!1}),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){super.onDestroy(),this.context.accessibility.removeElement(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){if(pr&&console.log("[Text] feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const s=new Mf({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(s)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const s=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(s){r.textContent=this.getText(e,i,s),this.handleTag(i,r,n);const a=new Mf(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new Mf(r);this.uiObject?.add(a)}i=s}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let s=0;s<this._textMeshUi.length;s++){if(e[s]===!0)continue;n=!0;const r=this._textMeshUi[s];r.textContent&&(Yp(r,i),e[s]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new r_(e,{color:t.color});if(i.push(n),e.type.length>6){const s=parseInt("0x"+e.type.substring(7));t.color=s}else t.color=new oe(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new r_(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new r_(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const s=e.substring(i+1,n);return{type:s,startIndex:i,endIndex:n+1,isEndTag:s.startsWith("/")}}return null}setFont(e,t){if(!this.font){pr&&console.warn("[Text] No font set for Text component, skipping font setup");return}const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);pr&&console.log(`[Text] Selected font family '${n}' from ${i} with style ${tg[t]}`);let s=ow.getFontFamily(n);switch(s||(s=ow.addFontFamily(n)),e.fontFamily=s,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let r=s.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=s.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){const i=e.startsWith("https:")||e.startsWith("http:"),n=e.lastIndexOf("-");if(n<0)return e;const s=e.substring(n+1)?.toLowerCase();if(T3.includes(s))return pr&&console.warn("[Text] Unsupported font style: "+s),e;const r=e.lastIndexOf("/");let a=e;r>=0&&(a=a.substring(r+1));const l=a[0]===a[0].toUpperCase(),c=e.substring(0,n>r?n:e.length);if(pr&&console.log("[Text] Select font: ",e,tg[t],a,l,c),i&&this._assignedAtRuntime&&!(e.endsWith("-msdf.json")||e.endsWith(".png")))return c;switch(t){case 0:return l?c+"-Regular":c+"-regular";case 1:return l?c+"-Bold":c+"-bold";case 2:return l?c+"-Italic":c+"-italic";case 3:return l?c+"-BoldItalic":c+"-bolditalic";default:return e}}}_s([p()],ii.prototype,"alignment"),_s([p()],ii.prototype,"verticalOverflow"),_s([p()],ii.prototype,"horizontalOverflow"),_s([p()],ii.prototype,"lineSpacing"),_s([p()],ii.prototype,"fontStyle"),_s([p(URL)],ii.prototype,"font"),_s([p()],ii.prototype,"supportRichText"),_s([p()],ii.prototype,"text"),_s([p()],ii.prototype,"fontSize");class r_{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const T3=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class mc{static global_id=0;static getId(){return this.global_id++}id;content="";font=[];pointSize=144;width;height;depth;wrapMode;horizontalAlignment;verticalAlignment;material;setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}constructor(e){this.id=e}writeTo(e,t){t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||=[],this.font?.push("sans-serif"));const i=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${i} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${Nm(this.material)}>`),t.closeBlock()}}class a_{static singleLine(e,t,i){const n=new mc("text_"+mc.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,s,r){const a=new mc("text_"+mc.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=s,r!==void 0&&(a.wrapMode=r),a}}const E3=new J().makeRotationY(Math.PI),A3=new J().makeScale(-1,1,-1);class ig{get extensionName(){return"text"}exportText(e,t,i){const n=P.getComponent(e,ii);if(!n)return;const s=P.getComponent(e,Kn);let r=100,a=100;s&&(r=s.width,a=s.height);const l=E3.clone();s&&l.premultiply(A3),t.setMatrix(l);const c=n.color.clone();t.material=new Mt({color:c,emissive:c}),t.addEventListener("serialize",(h,d)=>{let u=n.text;u=u.replace(/\r/g,""),u=u.replace(/\n/g,"\\n");const m=a_.multiLine(u,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,h)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case ut.LowerLeft:case ut.MiddleLeft:case ut.UpperLeft:e.horizontalAlignment="left";break;case ut.LowerCenter:case ut.MiddleCenter:case ut.UpperCenter:e.horizontalAlignment="center";break;case ut.LowerRight:case ut.MiddleRight:case ut.UpperRight:e.horizontalAlignment="right";break}switch(t){case ut.LowerLeft:case ut.LowerCenter:case ut.LowerRight:e.verticalAlignment="bottom";break;case ut.MiddleLeft:case ut.MiddleCenter:case ut.MiddleRight:e.verticalAlignment="middle";break;case ut.UpperLeft:case ut.UpperCenter:case ut.UpperRight:e.verticalAlignment="top";break}}}var I3=Object.defineProperty,pt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&I3(e,t,n),n};const ik=x("debuguilayout");class Oa{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}pt([p()],Oa.prototype,"left"),pt([p()],Oa.prototype,"right"),pt([p()],Oa.prototype,"top"),pt([p()],Oa.prototype,"bottom");class en extends T{_rectTransform=null;get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}_needsUpdate=!1;get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(ik&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}childAlignment=0;reverseArrangement=!1;spacing=0;padding;minWidth=0;minHeight=0;flexibleHeight=0;flexibleWidth=0;preferredHeight=0;preferredWidth=0;start(){this._needsUpdate=!0}onEnable(){ik&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Kn);const e=this.gameObject.getComponentInParent(gc);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(gc);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}pt([p()],en.prototype,"childAlignment"),pt([p()],en.prototype,"reverseArrangement"),pt([p()],en.prototype,"spacing"),pt([p(Oa)],en.prototype,"padding"),pt([p()],en.prototype,"minWidth"),pt([p()],en.prototype,"minHeight"),pt([p()],en.prototype,"flexibleHeight"),pt([p()],en.prototype,"flexibleWidth"),pt([p()],en.prototype,"preferredHeight"),pt([p()],en.prototype,"preferredWidth");class mr extends en{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const s=e.height;let r=s;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",c=a?this.childControlWidth:this.childControlHeight,h=a?this.childControlHeight:this.childControlWidth,d=a?this.childForceExpandWidth:this.childForceExpandHeight,u=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,g=a?i:s,y=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let b=0;a?b+=this.padding.left:b+=this.padding.top;let f=0,_=0;for(let D=0;D<this.gameObject.children.length;D++){const W=this.gameObject.children[D],$=P.getComponent(W,Kn);$?.activeAndEnabled&&(_+=1,a?f+=$.width:f+=$.height)}let w=0;const S=this.spacing*(_-1);if(d||c){let D=0;a?D=n-=S:D=r-=S,_>0&&(w=D/_)}let O=0;O+=this.padding.left,O-=this.padding.right,y!==0&&(b=g-f,b*=y,b-=S*y,a?(b-=this.padding.right*y,b+=this.padding.left*(1-y),b<this.padding.left&&(b=this.padding.left)):(b-=this.padding.bottom*y,b+=this.padding.top*(1-y),b<this.padding.top&&(b=this.padding.top)));let L=1;for(let D=0;D<this.gameObject.children.length;D++){const W=this.gameObject.children[D],$=P.getComponent(W,Kn);if($?.activeAndEnabled){$.pivot?.set(.5,.5),$.anchorMin.set(0,1),$.anchorMax.set(0,1);const H=i*.5+O*.5;$.anchoredPosition.x!==H&&($.anchoredPosition.x=H);const G=s*-.5;$.anchoredPosition.y!==G&&($.anchoredPosition.y=G),u&&h&&$.sizeDelta[l]!==m&&($.sizeDelta[l]=m),d&&c&&$.sizeDelta[t]!==w&&($.sizeDelta[t]=w);const E=a?$.width:$.height,z=E*.5;if(b+=z,d){const K=w*L-w*.5;K>b&&(b=K-w*.5+E+this.padding.left,b-=z)}let Y=b;t==="y"&&(Y=-Y),$.anchoredPosition[t]!==Y&&($.anchoredPosition[t]=Y),b+=z,b+=this.spacing,L+=1}}}}pt([p()],mr.prototype,"childControlHeight"),pt([p()],mr.prototype,"childControlWidth"),pt([p()],mr.prototype,"childForceExpandHeight"),pt([p()],mr.prototype,"childForceExpandWidth"),pt([p()],mr.prototype,"childScaleHeight"),pt([p()],mr.prototype,"childScaleWidth");class l_ extends mr{get primaryAxis(){return"y"}}class c_ extends mr{get primaryAxis(){return"x"}}class h_ extends en{onCalculateLayout(){}}var L3=Object.defineProperty,D3=Object.getOwnPropertyDescriptor,Eo=(o,e,t,i)=>{for(var n=i>1?void 0:i?D3(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&L3(e,t,n),n},nk=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(nk||{});const d_=x("debuguilayout"),yn=class kO extends vd{get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}_renderOnTop;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!1;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!1;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=2;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof kO||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}worldCamera;planeDistance=100;awake(){this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,d_&&console.log("Canvas.Awake()",this.previousParent?.name+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new J,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}_boundRenderSettingsChanged=this.onRenderSettingsChanged.bind(this);previousParent=null;_lastMatrixWorld=null;_rectTransforms=[];registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}_layoutGroups=new Map;registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}_receivers=[];registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}onEnterXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1)}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),wi.ensureUpdateMeshUI(sw,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);const e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),wi.ensureUpdateMeshUI(sw,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(const e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new J);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);d_&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(en)),(t.isDirty||i?.isDirty)&&(d_&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),Ee.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Yp(this.shadowComponent,this);for(const e of P.getComponentsInChildren(this.gameObject,kn))Yp(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=j.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const s=this.gameObject.getComponent(Kn);let r=!1;s.sizeDelta.x!==this.context.domWidth&&(r=!0),s.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,r&&(s.sizeDelta.x=this.context.domWidth,s.sizeDelta.y=this.context.domHeight,s?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};Eo([p()],yn.prototype,"renderOnTop",1),Eo([p()],yn.prototype,"depthWrite",1),Eo([p()],yn.prototype,"doubleSided",1),Eo([p()],yn.prototype,"castShadows",1),Eo([p()],yn.prototype,"receiveShadows",1),Eo([p()],yn.prototype,"renderMode",1),Eo([p(yn)],yn.prototype,"rootCanvas",1),Eo([p()],yn.prototype,"scaleFactor",1),Eo([p(pi)],yn.prototype,"worldCamera",2),Eo([p()],yn.prototype,"planeDistance",2);let gc=yn;var j3=Object.defineProperty,F3=Object.getOwnPropertyDescriptor,u_=(o,e,t,i)=>{for(var n=i>1?void 0:i?F3(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&j3(e,t,n),n};class gr extends T{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),Ee.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of P.getComponentsInChildren(this.gameObject,kn,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}u_([p()],gr.prototype,"alpha",1),u_([p()],gr.prototype,"interactable",2),u_([p()],gr.prototype,"blocksRaycasts",2);class p_{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=P.getComponent(e,gc);if(n&&n.enabled&&n.renderMode===nk.WorldSpace){const s=new ig,r=P.getComponent(e,Kn),a=P.getComponent(e,gr),l=new Array;if(r){if(!P.isActiveSelf(e)){const d=P.isActiveSelf(e);P.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),P.setActive(e,d)})}e.traverse(d=>{if(!P.isActiveInHierarchy(d)){const u=P.isActiveSelf(d);P.setActive(d,!0);const m=P.getComponent(d,kn);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const g=P.getComponent(d,Kn);g&&(g.onEnable(),g.updateTransform(),g.onApplyTransform(),l.push(()=>{g.onDisable()}));const y=P.getComponent(d,ii);y&&(y.onEnable(),l.push(()=>{y.onDisable()})),l.push(()=>{P.setActive(d,u)})}}),r.width,r.height;const c=vt.createEmpty(),h=r.shadowComponent;if(t.add(c),h){const d=h.matrix;c.setMatrix(d);const u=new Map,m=new Map;u.set(h,c),m.set(h,a?a.alpha:1),h.traverse(g=>{if(g===h)return;const y=vt.createEmpty();y.setMatrix(g.matrix);const b=g.parent,f=!!b&&typeof b.textContent=="string"&&b.textContent.length>0;let _=m.get(b)||1;const w=P.getComponent(g,gr);if(w&&(_*=w.alpha),g instanceof V&&f){const O=g[Gi];O?s.exportText(O.gameObject,y,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",g)}if(g instanceof V&&!f){const O=g.geometry.clone();O.scale(1,1,-1),this.flipWindingOrder(O),y.geometry=O;const L=new oe,D=g.material.opacity;L.copy(g.material.color),y.material=new Ie({color:L,opacity:D*_,map:g.material.map,transparent:!0})}u.set(g,y),m.set(g,_);const S=u.get(b);if(!S){console.error("Error when exporting UI: shadow component parent not found!",g,g.parent);return}S.add(y)})}}for(const c of l)c()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const s=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=s}e.index.needsUpdate=!0}}const Pd=x("debugusdz");function B3(o,e){const t=[],i=P.getComponentsInChildren(o,Et),n=P.getComponentsInChildren(o,Zt),s=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||s.includes(a))continue;const c=new ud;c.animator=a,c.stateName=l.name,c.trigger="start",c.name="PlayAnimationOnClick_implicitAtStart_"+c.stateName;const h=new R;P.addComponent(h,c),r.push(h),s.push(a),o.add(h)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;Pd&&console.log(a);const l=[];for(const c of a.runtimeAnimatorController.enumerateActions()){Pd&&console.log(c);const h=c.getClip();l.includes(h)||l.push(h)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||s.includes(a))continue;const l=new ud;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const c=new R;P.addComponent(c,l),r.push(c),s.push(a),o.add(c)}else for(const a of n){Pd&&console.log(a);const l=[];for(const c of a.animations)l.includes(c)||l.push(c);t.push({root:a.gameObject,clips:l})}Pd&&t?.length>0&&console.log("USDZ Animation Clips without behaviours",t);for(const a of t)for(const l of a.clips)e.registerAnimation(a.root,l);return r}function U3(o,e){const t=P.getComponentsInChildren(o,Yi),i=P.getComponentsInChildren(o,lr),n=new Array,s=new Array;Pd&&console.log({audioSources:t,playAudioOnClicks:i});for(const r of i){if(!r.target)continue;const a=t.indexOf(r.target);a>-1&&t.splice(a,1)}for(const r of t){if(!r||!r.clip||r.volume<=0||n.includes(r))continue;const a=new lr;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new R;P.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),s.push(l),n.push(r),o.add(l)}return s}function z3(o){return new qt("DisableAtStart",ei.sceneStartTrigger(),be.fadeAction(o,0,!1))}function ok(o,e){const t=o.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const r=document.createElement("img");return r.id="button",s.appendChild(r),o.domElement.shadowRoot.appendChild(i),s}var N3=Object.defineProperty,zt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&N3(e,t,n),n};const Nt=x("debugusdz"),$3=x("debugusdzpruning");class Ma{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}zt([p()],Ma.prototype,"callToAction"),zt([p()],Ma.prototype,"checkoutTitle"),zt([p()],Ma.prototype,"checkoutSubtitle"),zt([p()],Ma.prototype,"callToActionURL");const Ei=class Xa extends T{static beforeExport=new re;static afterExport=new re;static beforeLODExport=new re;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(){Nt&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{e.key==="t"&&this.exportAndOpen()})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=I.supportsQuickLookAR(),t=I.isiOS()||I.isiPad();!this.button&&(Nt||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=ok(this.context,e),this.link.addEventListener("message",this.lastCallback)),Nt&&Fe("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),Sh.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),Nt&&Fe("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),Sh.unregisterExporter(this)}onClickedOpenInARElement=e=>{e.preventDefault(),this.exportAndOpen()};async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){let e=this.exportFileName??this.objectToExport?.name??this.name;if(e+="-"+gP(),mo()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=ok(this.context,I.supportsQuickLookAR())),this.customUsdzFile)return Nt&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;Xa.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Xa.afterExport.invoke({exporter:this})});return t?(Nt&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){ue.start("export-usdz",{onProgress:S=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:S}}))}}),ue.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ue.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ue.start("export-usdz-textures","export-usdz");const t=P.getComponentsInChildren(e,Ri);for(const S of t)S&&S.enabled&&S.updateSprite(!0);const i=P.getComponentsInChildren(e,gi),n=new Array;let s=0;for(const S of i){for(const O of S.sharedMeshes)if(O){let L=0;const D={exporter:this,type:"mesh",object:S.gameObject,mesh:O};if(Xa.beforeLODExport.invoke(D),D.overrideLevel!==void 0)if(D.overrideLevel===-1){Nt&&console.warn("Skipping LOD export for mesh due to overrideLevel -1",S.gameObject,O);continue}else D.overrideLevel>=0&&(L=D.overrideLevel,Nt&&console.log("Overriding LOD level for mesh export to level "+L+" "+O.name));const W=We.assignMeshLOD(O,L);W instanceof Promise&&n.push(new Promise(($,H)=>{W.then(()=>{s++,ue.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:s,totalSteps:n.length}),$()}).catch(G=>H(G))}))}for(const O of S.sharedMaterials)if(O){let L=0;const D={exporter:this,type:"texture",object:S.gameObject,material:O};if(Xa.beforeLODExport.invoke(D),D.overrideLevel!==void 0)if(D.overrideLevel===-1){Nt&&console.warn("Skipping LOD assignment due to overrideLevel -1",S.gameObject,O);continue}else D.overrideLevel>=0&&(L=D.overrideLevel,Nt&&console.log("Overriding LOD level for texture export to level "+L+" "+O.name));const W=We.assignTextureLOD(O,L);W instanceof Promise&&n.push(new Promise(($,H)=>{W.then(()=>{s++,ue.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:n.length}),$()}).catch(G=>H(G))}))}}Nt&&Fe("Progressive Loading: "+n.length),await Promise.all(n),Nt&&Fe("Progressive Loading: done"),ue.end("export-usdz-textures");const r=vi.Global.Mask;vi.Global.Set(To.AR);const a=new wP,l=new Vm(this.quickLookCompatible);let c;const h=[];this.interactive&&(h.push(new t_),h.push(new Ya),globalThis.NEEDLE_USE_RAPIER&&P.getComponentsInChildren(e,rt).length>0&&(this.physics?(c=new i_,h.push(c)):M()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),h.push(new ig),h.push(new p_));const d=[l,...h,...this.extensions],u={self:this,exporter:a,extensions:d,object:e};ue.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:u})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,ue.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...B3(e,l)),d.find(S=>S.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...U3(e)),a.debug=Nt,a.pruneUnusedNodes=!$3;const g=Ka.instance.objs.map(S=>S.batchedMesh);a.keepObject=S=>{let O=!0;const L=P.getComponent(S,gi);return L&&!L.enabled&&(O=!1),O&&g.includes(S)&&(O=!1),O&&P.getComponentInParent(S,sd)&&(O=!1),O&&P.getComponentInParent(S,wo)&&(O=!1),Nt&&!O&&console.log("USDZExporter: Discarding object",S),O},a.beforeWritingDocument=()=>{if(M()&&l&&c){const S=l.animatedRoots;for(const O of S){const L=P.getComponentsInChildren(O,rt).filter(W=>W.enabled),D=P.getComponents(O,Ki).filter(W=>W.enabled&&!W.isTrigger);(L.length>0||D.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",O)}}};const y=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(S=>{S.visible||y.push(S)});const b=d.find(S=>S.extensionName==="Behaviour");this.interactive&&b&&y.length>0&&b.addBehavior(z3(y));let f=!0;this.quickLookCompatible&&!this.interactive&&(f=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),ue.report("export-usdz","Invoking exporter.parse");const _=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:d,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:f}),w=new Blob([_],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ue.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:u}));for(const S of m)P.destroy(S);return vi.Global.Set(r),ue.end("export-usdz"),w}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();Nt&&console.log("QuickLook Overlay",n);const s=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${s}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){Xa.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}lastCallback;quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){Nt&&ge("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");Nt&&Fe("Quicklook url: "+n),n&&(mo()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){const e={};return this.customBranding&&Object.assign(e,this.customBranding),mo()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="\u{1F335} 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 J().makeRotationY(Math.PI);static invertForwardQuaternion=new B().setFromEuler(new je(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new v;_rootRotationBeforeExport=new B;_rootScaleBeforeExport=new v;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=P.findObjectOfType(Zm);let t=P.getComponentInParent(this.objectToExport,Tn);t||(t=P.getComponentInChildren(this.objectToExport,Tn));let i=1,n=!1;const s=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:s,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),s=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(Xa.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&s&&i.matrix.premultiply(s)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const e=Tr.getOrCreate().createQuicklookButton();return e.parentNode||this.context.menu.appendChild(e),e}};zt([p(R)],Ei.prototype,"objectToExport"),zt([p()],Ei.prototype,"autoExportAnimations"),zt([p()],Ei.prototype,"autoExportAudioSources"),zt([p()],Ei.prototype,"exportFileName"),zt([p(URL)],Ei.prototype,"customUsdzFile"),zt([p(Ma)],Ei.prototype,"customBranding"),zt([p()],Ei.prototype,"anchoringType"),zt([p()],Ei.prototype,"maxTextureSize"),zt([p()],Ei.prototype,"planeAnchoringAlignment"),zt([p()],Ei.prototype,"interactive"),zt([p()],Ei.prototype,"physics"),zt([p()],Ei.prototype,"allowCreateQuicklookButton"),zt([p()],Ei.prototype,"quickLookCompatible");let Ao=Ei;Kj({find:()=>zl(Ao),create:()=>new Ao});var W3=Object.defineProperty,V3=Object.getOwnPropertyDescriptor,m_=(o,e,t,i)=>{for(var n=V3(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&W3(e,t,n),n};class fc extends T{get fog(){return this._fog||(this._fog=new Tv(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}_fog;onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}m_([p()],fc.prototype,"near"),m_([p()],fc.prototype,"far"),m_([p(oe)],fc.prototype,"color");const sk=Rt,G3=x("debugtypestore");G3&&console.log(k);function H3(o,e){const t=Fx(o,e);if(t!=null)return t;const i={name:k.getKey(o.constructor)||o.constructor.name};return typeof o.guid=="string"&&(i.guid=o.guid),o.enabled===!1&&(i.enabled=!1),i}const q3=new jx,g_=Symbol("deserialize-queue");function rk(o,e,t,i){const n=new e;i.gltfId!==void 0&&(n.sourceId=i.gltfId),bl(n,t,i.implementationInformation),n.context=i.context,"guid"in t&&(n[ts]=t.guid),n[Th]=t.name,aa(o,n,!1);const s=i.context;return n.isCamera&&s&&s.mainCamera===null&&n.tag==="MainCamera"&&s.setCurrentCamera(n),s?.physics?.engine?.isInitialized===!1&&(n.isCollider||n.isRigidbody)&&s.physics.engine?.initialize(),n}async function X3(o,e,t,i=null,n){if(!t){console.debug("Can not create component instances: gltf is null");return}const s=[];let r=i;typeof r=="number"&&(r=new _t(i));const a=e.indexOf("?");e=a===-1?e:e.substring(0,a);const l=new gh(t.scene);l.gltfId=e,l.context=o,l.gltf=t,l.nodeToObject=n?.nodeToObjectMap,l.implementationInformation=q3;let c=o[g_];if(c||(c=o[g_]=[]),t.scenes)for(const h of t.scenes)await f_(l,h,c,s,0);if(t.children)for(const h of t.children)await f_(l,h,c,s,0);o.new_scripts_pre_setup_callbacks.push(()=>{const h=o[g_];if(h){for(const d of h)Q3(d,l);h.length=0}if(r){const d={};ub(t,r,d);for(const u of t.scenes)ub(u,r,d);uS(t,d);for(const u of t.scenes)uS(u,d)}})}const kd=[];async function f_(o,e,t,i,n){if(!e)return;const s=e.userData;if(s){const r=s.builtin_components;if(r&&r.length>0)for(const a of r)try{if(a===null)continue;let l=k.get(a.name);if(l||(l=await k.getAsync(a.name)),l){const c=rk(e,l,a,o);t.push({instance:c,compData:a,obj:e})}else sk&&console.debug("unknown component: "+a.name),kd.includes(a.name)||kd.push(a.name)}catch(l){console.error(a.name+" - "+l.message,l)}}if(e.children)for(const r of e.children)await f_(o,r,t,i,n+1);if(kd.length>0&&n===0){const r=kd.join(", ");console.warn(`Unknown components in scene: ${r}`),kd.length=0,Ni()&&Fe(`<strong>Unknown components in scene</strong>:
1398
1398
 
1399
1399
  ${r}
1400
1400
 
@@ -1404,7 +1404,7 @@ ${new Error().stack}`:""}`),r}switch(i){case"unsupported":return null;default:ca
1404
1404
  Use import { NeedleEngineModelLoader } from "@needle-tools/engine" namespace to register your loader.`,o);const n=new Zo;return await Rm(n,e,o,t),n}case"model/fbx":case"model/vnd.autodesk.fbx":return new Jv;case"model/obj":return new Sf;case"model/vnd.usdz+zip":case"model/vnd.usd+zip":case"model/vnd.usda+zip":return console.warn(i.toUpperCase()+" files are not supported."),null;case"model/gltf+json":case"model/gltf-binary":case"model/vrm":{const n=new Zo;return await Rm(n,e,o,t),n}case"application/materialx+xml":return new nj}}function mk(o,e){return y_(e?.context||Q.Current,o,o,e?.seed||null,e?.onprogress)}async function ng(o,e,t,i,n){typeof t!="string"&&(console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t),t=""),dk&&console.log("Parse glTF",t);const s=await uk(o,e,t);if(s)return s;const r=await pk(t,o,t);if(!r)return;const{componentsExtension:a}=gk(r,o);if(r instanceof Sf){typeof e!="string"&&(e=new TextDecoder().decode(e));const c=r.parse(e);return await Od(r,o,t,c,i,a)}if(!(r instanceof Zo)){if(!("parse"in r)||typeof r.parse!="function"){console.error("Loader does not support parse");return}const c=await r.parse(e,t);return await Od(r,o,t,c,i,a)}let l=n?.resolveUrl;return!l&&lk(t)&&(l=await ck(t)??void 0),new Promise((c,h)=>{try{let d=t.split("?")[0].trimEnd();const u=d.split("/");if(u.length>0&&u[u.length-1]!==""&&u.pop(),d=u.join("/"),d.endsWith("/")||(d+="/"),r.resourcePath=d,l){const m=new Gv;m.resolveURL=l,r.manager=m}r.parse(e,"",async m=>{const g=await Od(r,o,t,m,i,a);c(g)},m=>{console.error('Loading asset at "'+t+`" failed
1405
1405
  `,m),c(void 0)})}catch(d){console.error(d),h(d)}})}async function y_(o,e,t,i,n){if(sF(e),e.split("?")[0].toLowerCase().endsWith(".json")){const a=await fetch(e).then(l=>l.ok?l.text():null).catch(()=>null);if(a!==null)return await uk(o,a,e,n)||ng(o,a,e,i)}const s=await pk(e,o,t);if(!s)return;const{componentsExtension:r}=gk(s,o);if(!(s instanceof Zo)){const a=await s.loadAsync(e,n);return await Od(s,o,e,a,i,r)}if(lk(e)){const a=await ck(e);if(a){const l=new Gv;l.resolveURL=a,s.manager=l}}return new Promise((a,l)=>{try{s.load(e,async c=>{const h=await Od(s,o,t,c,i,r);a(h)},c=>{n?.call(s,c)},c=>{console.error('Loading asset at "'+e+`" failed
1406
1406
  `,c),a(void 0)})}catch(c){console.error(c),l(c)}})}function gk(o,e){const t=v0(o);return o instanceof Zo&&XP(o,e),{componentsExtension:t}}async function Od(o,e,t,i,n,s){if(dk&&console.warn("Loaded",t,i),i==null)return console.error(`Loaded model is null '${t}' - please make sure the loader is registered correctly`),{scene:new R,animations:[],scenes:[]};if(typeof i!="object")return console.error(`Loaded model is not an object '${t}' - please make sure the loader is registered correctly`),{scene:new R,animations:[],scenes:[]};if(i instanceof R)i={scene:i,animations:i.animations,scenes:[i]};else if(i instanceof Ln){const r=new Mt({color:new oe(14540253)}),a=new V(i,r);i={scene:a,animations:[],scenes:[a]}}else Array.isArray(i.scenes)===!1&&console.error(`[Needle Engine] The loaded model object does not have a scenes property '${t}' - please make sure the loader is registered correctly and three.js is not imported multiple times.`);return t.includes("?")&&(t=t.split("?")[0]),rF(o,i),ax(i)&&(nF(i),eP(t,i,e),await is().createBuiltinComponents(e,t,i,n,s||void 0)),i.scene&&await oF(i.scene,e,e.mainCamera),i}function nF(o){const e=o.parser;e?.json&&vR(e.json,e.associations,o.scenes);const t=e?.associations;if(t)for(const[i,n]of t){if(n==null)continue;const s=i;!s||typeof s!="object"||s.userData&&s.userData.associations===void 0&&(s.userData.associations=n)}}async function oF(o,e,t){t||(t=e.mainCamera);try{t?await e.renderer.compileAsync(o,t,e.scene).catch(i=>{console.warn(i.message)}):fI(o,e)}catch(i){console.warn(i?.message||i)}}function sF(o){if(new URL(o,window.location.href).href.startsWith("file://")){const e=`Hi - it looks like you are trying to load a local file which will not work. You need to use a webserver to serve your files.
1407
- Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;Fe(e),console.warn(e)}}function rF(o,e){if("scenes"in e){for(const t of e.scenes)if(t&&!t.animations?.length)for(const i of e.animations)t.animations.includes(i)||t.animations.push(i)}if(o instanceof Jv||o instanceof Sf){let t=e;t instanceof R||(t=e.scene||e.scenes.find(i=>i)),t.traverse(i=>{const n=i;n?.isMesh&&Zf(n,n.material)})}}var aF=Object.defineProperty,lF=Object.getOwnPropertyDescriptor,og=(o,e,t,i)=>{for(var n=lF(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&aF(e,t,n),n};class Ra extends T{set url(e){e!==this._url&&(this._url=e,e&&this.__internalDidAwake&&this.activeAndEnabled&&!this._loading&&this.load(e))}get url(){return this._url}_url;set opacity(e){this._opacity=e,this._splatMesh&&(this._splatMesh.opacity=e,this._splatMesh.updateVersion())}get opacity(){return this._opacity}_opacity=1;set raycastable(e){this._raycastable=e,this._splatMesh&&(this._splatMesh.raycastable=e)}get raycastable(){return this._raycastable}_raycastable=!0;set quality(e){e!==this._quality&&(this._quality=e,this._splatMesh&&Ny(this.context,this._splatMesh,e))}get quality(){return this._quality}_quality="auto";get splatMesh(){return this._splatMesh}get isLoaded(){return this._splatMesh?.isInitialized===!0}get initialized(){return this._initialized}_splatMesh=null;_initialized=Promise.resolve();_loading=!1;_loadGeneration=0;awake(){this._loadGeneration++,this._splatMesh=null,this._initialized=Promise.resolve(),this._loading=!1}onEnable(){this.url&&!this._splatMesh&&!this._loading&&this.load(this.url),this._splatMesh&&(this._splatMesh.visible=!0,this._splatMesh.updateVersion())}onDisable(){this._splatMesh&&(this._splatMesh.visible=!1,this._splatMesh.updateVersion())}onDestroy(){this._splatMesh&&(this._splatMesh.removeFromParent(),this._splatMesh.dispose(),this._splatMesh=null)}async load(e){const t=++this._loadGeneration;this._url=e,this._splatMesh&&(this._splatMesh.removeFromParent(),this._splatMesh.dispose(),this._splatMesh=null),this._loading=!0;const i=await mk(e,{context:this.context});if(t!==this._loadGeneration||this.destroyed)return i?.scene?.dispose(),null;const n=i?.scene;return n?(n.name="Gaussian Splat",n.hideFlags|=uo.DontExport|uo.DontInstantiate,n.opacity=this._opacity,n.raycastable=this.raycastable,this._splatMesh=n,this.gameObject.add(n),this.activeAndEnabled||(n.visible=!1),this._initialized=n.initialized.then(()=>{t===this._loadGeneration&&(this._loading=!1)}),await this._initialized,t!==this._loadGeneration||this.destroyed?null:(Ny(this.context,n,this._quality),n)):(this._loading=!1,null)}}og([p(URL)],Ra.prototype,"url"),og([p()],Ra.prototype,"opacity"),og([p()],Ra.prototype,"raycastable"),og([p()],Ra.prototype,"quality");var cF=Object.defineProperty,b_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&cF(e,t,n),n};class Ta extends T{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!mh||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new jM(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=sb(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Ee.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}b_([p()],Ta.prototype,"objectBounds"),b_([p(oe)],Ta.prototype,"color"),b_([p()],Ta.prototype,"isGizmo");var hF=Object.defineProperty,__=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&hF(e,t,n),n};class yc extends T{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!mh)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Ov(e,t,this.color0??new oe(.4,.4,.4),this.color1??new oe(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}__([p()],yc.prototype,"isGizmo"),__([p(oe)],yc.prototype,"color0"),__([p(oe)],yc.prototype,"color1");var dF=Object.defineProperty,v_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&dF(e,t,n),n};class w_ extends T{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;_jointHandle=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(rt)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}onDisable(){this._jointHandle&&(this.context.physics.engine?.removeJoint(this._jointHandle),this._jointHandle=null)}*create(){if(yield,!this._jointHandle&&this.rigidBody&&this.connectedBody&&this.activeAndEnabled){const e=this.createJoint(this.rigidBody,this.connectedBody);e instanceof Promise?yield e.then(t=>this._jointHandle=t):this._jointHandle=e}}}v_([p(rt)],w_.prototype,"connectedBody");class x_ extends w_{createJoint(e,t){return this.context.physics.engine?.addFixedJoint(e,t)??null}}class Md extends w_{anchor;axis;createJoint(e,t){return this.axis&&this.anchor?this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)??null:null}}v_([p(v)],Md.prototype,"anchor"),v_([p(v)],Md.prototype,"axis");var uF=Object.defineProperty,pF=Object.getOwnPropertyDescriptor,tn=(o,e,t,i)=>{for(var n=i>1?void 0:i?pF(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&uF(e,t,n),n};function bc(o){return o*Math.PI/180}const fk=300,Io=x("debuglights");var S_=(o=>(o[o.Spot=0]="Spot",o[o.Directional=1]="Directional",o[o.Point=2]="Point",o[o.Area=3]="Area",o[o.Rectangle=3]="Rectangle",o[o.Disc=4]="Disc",o))(S_||{});class $t extends T{get type(){return this._type}set type(e){if(this.light&&this.__didAwake)throw new Error("Changing the light type at runtime is not supported");switch(e){case 1:this._type="directional";break;case 2:this._type="point";break;case 0:this._type="spot";break;case"directional":case"point":case"spot":this._type=e;break;default:(Io||M())&&console.warn(`[Light] Unsupported light type: ${S_[e]} (${e}) on '${this.name}'`),this._type="unsupported";break}}_type="point";get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type==="SpotLight"||this.light.type==="PointLight")&&"distance"in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type==="SpotLight"&&"angle"in this.light&&(this.light.angle=bc(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type==="SpotLight"&&"penumbra"in this.light){const t=this.spotAngle,i=1-bc(e/2)/bc(t/2);this.light.penumbra=i}}_innerSpotAngle=10;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new oe(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.shadowLight?.shadow?.camera!==void 0)){const t=this.shadowLight.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.shadowLight?.shadow?.bias!==void 0&&(this.shadowLight.shadow.bias=e,this.shadowLight.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.shadowLight?.shadow?.normalBias!==void 0&&(this.shadowLight.shadow.normalBias=e,this.shadowLight.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){this._intensity=e,this.light&&(this.light.intensity=e),Io&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.shadowLight;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.shadowLight;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.shadowLight;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.shadowLight;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;get shadowLight(){const e=this.light;if(e&&"shadow"in e)return e}getWorldPosition(e){return this.light?this.type==="directional"?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new oe(this.color??16777215),Io&&console.log(this.name,this)}onEnable(){Io&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Io&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.context.lights.push(this))}onDisable(){Io&&console.log("DISABLE LIGHT",this.name);const e=this.context.lights.indexOf(this);e!==-1&&this.context.lights.splice(e,1),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}createLight(){const e=this.selfIsLight;if(e&&!this.light)this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type==="directional"&&this.setDirectionalLight(this.light);else if(!this.light)switch(this.type){case"directional":const t=new lf(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-fk*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),zr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Io){const r=new BM(this.light,.2,this.color);this.context.scene.add(r)}break;case"spot":const i=new FM(this.color,this.intensity*Math.PI,this.range,bc(this.spotAngle/2),1-bc(this.innerSpotAngle/2)/bc(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case"point":const s=new cf(this.color,this.intensity*Math.PI,this.range);this.light=s;break;default:Io&&console.warn(`[Light] Unsupported light type: ${S_[this.type]} (${this.type}) on '${this.name}'`);break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.shadowLight?.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.shadowLight.shadow.mapSize.width=this._shadowResolution,this.shadowLight.shadow.mapSize.height=this._shadowResolution):(this.shadowLight.shadow.mapSize.width=2048,this.shadowLight.shadow.mapSize.height=2048),Io&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.shadowLight.shadow.bias=this.shadowBias,this.shadowLight.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const t=this.shadowLight.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=fk*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{const i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.shadowLight.shadow.needsUpdate=!0,Io&&this.context.scene.add(new UM(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.shadowLight.shadow&&(this.shadows===2||(this.shadowLight.shadow.radius=1,this.shadowLight.shadow.blurSamples=1))}onEnterXR(e){this.applyXRScale(e.xr.rigScale)}onUpdateXR(e){this.applyXRScale(e.xr.rigScale)}onLeaveXR(e){this.applyXRScale(1)}applyXRScale(e){this.light&&("distance"in this.light?(this.light.intensity=this._intensity/e,this.light.distance=this._range/e):this.light.intensity=this._intensity)}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}tn([p()],$t.prototype,"type",1),tn([p()],$t.prototype,"range",1),tn([p()],$t.prototype,"spotAngle",1),tn([p()],$t.prototype,"innerSpotAngle",1),tn([p(oe)],$t.prototype,"color",1),tn([p()],$t.prototype,"shadowNearPlane",1),tn([p()],$t.prototype,"shadowBias",1),tn([p()],$t.prototype,"shadowNormalBias",1),tn([p()],$t.prototype,"shadows",1),tn([p()],$t.prototype,"lightmapBakeType",2),tn([p()],$t.prototype,"intensity",1),tn([p()],$t.prototype,"shadowDistance",1),tn([p()],$t.prototype,"shadowResolution",1);var mF=Object.defineProperty,sg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&mF(e,t,n),n};const C_=x("debuglods"),gF=x("nolods");class _c{screenRelativeTransitionHeight;distance;renderers}sg([p()],_c.prototype,"screenRelativeTransitionHeight"),sg([p()],_c.prototype,"distance"),sg([p(gi)],_c.prototype,"renderers");class fF{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class rg extends T{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(C_&&console.log("LODGROUP",this.name,this.lodModels,this),!gF&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new fF(i);this._lods.push(n);for(const s of n.renderers)e.includes(s)||e.push(s)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new zM;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new R;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],s=this._lodsHandler[i],r=n.gameObject;C_&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let c=null;if(a.renderers.includes(n)?c=r:c=t,c.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${c.name}`);continue}C_&&console.log("LEVEL",c.name,l),s.autoUpdate=!1,this.onAddLodLevel(s,c,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}sg([p(_c)],rg.prototype,"lodModels");var yF=Object.defineProperty,P_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&yF(e,t,n),n};const ag=x("debugnestedgltf");class vc extends T{filePath;loaded=new re;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;ag&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new $o;t.idProvider=new _t(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;ag&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);ag&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.loaded.invoke({component:this,instance:n,asset:this.filePath})),ag&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}P_([p(ie)],vc.prototype,"filePath"),P_([p(re)],vc.prototype,"loaded"),P_([p()],vc.prototype,"loadAssetInParent");var bF=Object.defineProperty,k_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&bF(e,t,n),n};const _F=x("debugnet"),lg=class Cv extends T{url=null;urlParameterName=null;localhost=null;awake(){_F&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Cv.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=x(this.urlParameterName);i&&typeof i=="string"&&(e=i)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t?.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let i=e;const n=Cv.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const s=n?i:window.location.origin;s?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=s+e}return i}static IsLocalNetwork(e=window.location.hostname){return Ni(e)}};k_([p()],lg.prototype,"url"),k_([p()],lg.prototype,"urlParameterName"),k_([p()],lg.prototype,"localhost");let O_=lg;var vF=Object.defineProperty,cg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vF(e,t,n),n};class Ea extends T{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new v(0,0,0);rotationOffset=new v(0,0,0);offset=new v(0,0,0);update(){if(!this.from)return;var e=le(this.from),t=Re(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new rl(this.gameObject.up,0),l=le(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const c=new v(0,0,0);a.projectPoint(e,c),e.copy(c)}this.affectPosition&&Vi(this.gameObject,e);const n=new je(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),s=new B().setFromEuler(n);this.affectRotation&&Fn(this.gameObject,t.multiply(s));const r=new v;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}cg([p(P)],Ea.prototype,"referenceSpace"),cg([p(P)],Ea.prototype,"from"),cg([p(v)],Ea.prototype,"positionOffset"),cg([p(v)],Ea.prototype,"rotationOffset");var wF=Object.defineProperty,fr=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&wF(e,t,n),n};class Ai{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}fr([p()],Ai.prototype,"time"),fr([p()],Ai.prototype,"value"),fr([p()],Ai.prototype,"inTangent"),fr([p()],Ai.prototype,"inWeight"),fr([p()],Ai.prototype,"outTangent"),fr([p()],Ai.prototype,"outWeight"),fr([p()],Ai.prototype,"weightedMode");const yk=class au{static linearFromTo(e,t,i){const n=new au,s=new Ai;s.time=0,s.value=e;const r=new Ai;return r.time=i,r.value=t,n.keys.push(s,r),n}static constant(e){const t=new au,i=new Ai;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new au;return e.keys=this.keys?.map(t=>{const i=new Ai;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<e)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:au.interpolateValue(e,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,s=t.value,r=t.outTangent,a=i.time,l=i.value,c=i.inTangent,h=a-n,d=h*h,u=d*h,m=((r+c)*h-2*(l-s))/u,g=(3*(l-s)-(c+2*r)*h)/d,y=r,b=s,f=e-n,_=f*f,w=_*f;return m*w+g*_+y*f+b}};fr([p(Ai)],yk.prototype,"keys");let Rd=yk;var xF=Object.defineProperty,C=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xF(e,t,n),n};const hg=x("debugparticles");var vs=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(vs||{});class Aa{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,s=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!s)&&(s=l,r=a)}if(s)if(r+1<this.colorKeys.length){const a=this.colorKeys[r+1],l=j.remap(e,s.time,a.time,0,1);t.r=j.lerp(s.color.r,a.color.r,l),t.g=j.lerp(s.color.g,a.color.g,l),t.b=j.lerp(s.color.b,a.color.b,l)}else t.r=s.color.r,t.g=s.color.g,t.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const a=this.alphaKeys[n+1],l=j.remap(e,i.time,a.time,0,1);t.alpha=j.lerp(i.alpha,a.alpha,l)}else t.alpha=i.alpha;return t}}C([p()],Aa.prototype,"alphaKeys"),C([p()],Aa.prototype,"colorKeys");var Td=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(Td||{}),dg=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(dg||{});const ws=class lu{static constant(e){const t=new lu;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new lu;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new lu;return i.setCurve(e,t),i}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new lu;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=j.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,s=e*this.curveMax.duration;return j.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return j.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};C([p()],ws.prototype,"mode"),C([p()],ws.prototype,"constant"),C([p()],ws.prototype,"constantMin"),C([p()],ws.prototype,"constantMax"),C([p(Rd)],ws.prototype,"curve"),C([p(Rd)],ws.prototype,"curveMin"),C([p(Rd)],ws.prototype,"curveMax"),C([p()],ws.prototype,"curveMultiplier");let Z=ws;const yr=class Ht{static constant(e){const t=new Ht;return t.constant(e),t}static betweenTwoColors(e,t){const i=new Ht;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new he(0,0,0,1);static _temp2=new he(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,Ht._temp),Ht._temp;case 2:case"TwoColors":return Ht._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,Ht._temp),this.gradientMax.evaluate(e,Ht._temp2),Ht._temp.lerp(Ht._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(e,Ht._temp),this.gradientMax.evaluate(e,Ht._temp2),Ht._temp.lerp(Ht._temp2,n)}return Ht._temp.set(16777215),Ht._temp.alpha=1,Ht._temp}};C([p()],yr.prototype,"mode"),C([p(he)],yr.prototype,"color"),C([p(he)],yr.prototype,"colorMin"),C([p(he)],yr.prototype,"colorMax"),C([p(Aa)],yr.prototype,"gradient"),C([p(Aa)],yr.prototype,"gradientMin"),C([p(Aa)],yr.prototype,"gradientMax");let Ia=yr;var M_=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(M_||{});class ni{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}C([p(Z)],ni.prototype,"gravityModifier"),C([p(Ia)],ni.prototype,"startColor"),C([p(Z)],ni.prototype,"startDelay"),C([p(Z)],ni.prototype,"startLifetime"),C([p(Z)],ni.prototype,"startRotation"),C([p(Z)],ni.prototype,"startRotationX"),C([p(Z)],ni.prototype,"startRotationY"),C([p(Z)],ni.prototype,"startRotationZ"),C([p(Z)],ni.prototype,"startSize"),C([p(Z)],ni.prototype,"startSizeX"),C([p(Z)],ni.prototype,"startSizeY"),C([p(Z)],ni.prototype,"startSizeZ"),C([p(Z)],ni.prototype,"startSpeed");class ug{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=j.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=j.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class xs{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}C([p()],xs.prototype,"enabled"),C([p()],xs.prototype,"bursts"),C([p(Z)],xs.prototype,"rateOverTime"),C([p()],xs.prototype,"rateOverTimeMultiplier"),C([p(Z)],xs.prototype,"rateOverDistance"),C([p()],xs.prototype,"rateOverDistanceMultiplier");class pg{enabled;color}C([p(Ia)],pg.prototype,"color");class La{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new v;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}C([p(Z)],La.prototype,"size"),C([p(Z)],La.prototype,"x"),C([p(Z)],La.prototype,"y"),C([p(Z)],La.prototype,"z");const mt=class cu{get type(){return dg[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new cu}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new je;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new J;_worldSpaceMatrixInverse=new J;constructor(){hg&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=j.toRadians(this.rotation.x),this._rotation.y=j.toRadians(this.rotation.y),this._rotation.z=j.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new v(0,0,0);_temp=new v(0,0,0);_triangle=new NM;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:hg&&F.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const s=this.meshRenderer;s?.destroyed==!1&&this.setMesh(s);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),c=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,c),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=c}break;case 1:break;case 2:{const l=a.index;if(l){let c=Math.random(),h=Math.random();c+h>1&&(c=1-c,h=1-h);const d=Math.floor(Math.random()*(l.count/3));let u=d*3,m=d*3+1,g=d*3+2;u=l.getX(u),m=l.getX(m),g=l.getX(g);const y=a.getAttribute("position");this._triangle.a.fromBufferAttribute(y,u),this._triangle.b.fromBufferAttribute(y,m),this._triangle.c.fromBufferAttribute(y,g),this._vector.set(0,0,0).addScaledVector(this._triangle.a,c).addScaledVector(this._triangle.b,h).addScaledVector(this._triangle.c,1-(c+h)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=d}}break}break;default:this._vector.set(0,0,0),M()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",dg[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),hg&&F.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new v;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,s=t.z;this._dir.set(i,n,s),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),c=e.mesh_normal;this._dir.fromBufferAttribute(l,c)}break;case 1:break;case 2:{const l=a.index;if(l){const c=e.mesh_normal,h=l.getX(c*3),d=l.getX(c*3+1),u=l.getX(c*3+2),m=a.getAttribute("position"),g=U(),y=U(),b=U();g.fromBufferAttribute(m,h),y.fromBufferAttribute(m,d),b.fromBufferAttribute(m,u),g.sub(y),b.sub(y),g.cross(b),this._dir.copy(g).multiplyScalar(-1);const f=Re(r);this._dir.applyQuaternion(f)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),hg&&(F.DrawSphere(t,.01,8925952,.5,!0),F.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new B;static _tempVec=new v;randomizePosition(e,t){if(t<=0)return;const i=cu._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=cu._randomQuat,n=cu._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),s=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new v(s,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,s){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),c=Math.acos(2*a-1),h=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,d=e.x+this.scale.x*(-h*Math.sin(c)*Math.cos(l)),u=e.y+this.scale.y*(h*Math.sin(c)*Math.sin(l)),m=e.z+this.scale.z*(h*Math.cos(c));s.x=d,s.y=u,s.z=m}randomCirclePoint(e,t,i,n,s){const r=Math.random(),a=2*Math.PI*r*(n/360),l=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,c=e.x+this.scale.x*l*Math.cos(a),h=e.y+this.scale.y*l*Math.sin(a),d=e.z;s.x=c,s.y=h,s.z=d}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,s,r,a){let l=0,c=0;switch(r){case 0:l=Math.random(),c=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,c=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let h=2*Math.PI*l*(s/360);switch(r){case 2:case 1:h+=Math.PI+.5,h+=this._loopTime*Math.PI*2,h%=j.toRadians(s);break}const d=Math.acos(2*c-1),u=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-u*Math.sin(d)*Math.cos(h),g=e.y+u*Math.sin(d)*Math.sin(h),y=e.z;a.x=m*this.scale.x,a.y=g*this.scale.y,a.z=y*this.scale.z}};C([p()],mt.prototype,"shapeType"),C([p()],mt.prototype,"enabled"),C([p()],mt.prototype,"alignToDirection"),C([p()],mt.prototype,"angle"),C([p()],mt.prototype,"arc"),C([p()],mt.prototype,"arcSpread"),C([p()],mt.prototype,"arcSpeedMultiplier"),C([p()],mt.prototype,"arcMode"),C([p(v)],mt.prototype,"boxThickness"),C([p(v)],mt.prototype,"position"),C([p(v)],mt.prototype,"rotation"),C([p(v)],mt.prototype,"scale"),C([p()],mt.prototype,"radius"),C([p()],mt.prototype,"radiusThickness"),C([p()],mt.prototype,"sphericalDirectionAmount"),C([p()],mt.prototype,"randomDirectionAmount"),C([p()],mt.prototype,"randomPositionAmount"),C([p()],mt.prototype,"meshShapeType"),C([p(cd)],mt.prototype,"meshRenderer");let R_=mt;class Se{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new v;apply(e,t,i,n,s,r){if(!this.enabled)return;this._noise||(this._noise=wR(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),c=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),h=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,c,h).normalize();const d=s/r;let u=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=u*this.strengthXMultiplier,this._temp.y*=u*this.strengthYMultiplier,this._temp.z*=u*this.strengthZMultiplier):(this.strengthX&&(u*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(u)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}C([p()],Se.prototype,"damping"),C([p()],Se.prototype,"enabled"),C([p()],Se.prototype,"frequency"),C([p()],Se.prototype,"octaveCount"),C([p()],Se.prototype,"octaveMultiplier"),C([p()],Se.prototype,"octaveScale"),C([p(Z)],Se.prototype,"positionAmount"),C([p()],Se.prototype,"quality"),C([p(Z)],Se.prototype,"remap"),C([p()],Se.prototype,"remapEnabled"),C([p()],Se.prototype,"remapMultiplier"),C([p(Z)],Se.prototype,"remapX"),C([p()],Se.prototype,"remapXMultiplier"),C([p(Z)],Se.prototype,"remapY"),C([p()],Se.prototype,"remapYMultiplier"),C([p(Z)],Se.prototype,"remapZ"),C([p()],Se.prototype,"remapZMultiplier"),C([p()],Se.prototype,"scrollSpeedMultiplier"),C([p()],Se.prototype,"separateAxes"),C([p()],Se.prototype,"strengthMultiplier"),C([p(Z)],Se.prototype,"strengthX"),C([p()],Se.prototype,"strengthXMultiplier"),C([p(Z)],Se.prototype,"strengthY"),C([p()],Se.prototype,"strengthYMultiplier"),C([p(Z)],Se.prototype,"strengthZ"),C([p()],Se.prototype,"strengthZMultiplier");class qe{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const s=this.widthOverTrail.evaluate(i,n);return e*=s,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(t);e.x*=n.r*s.r,e.y*=n.g*s.g,e.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(e.w*=n.alpha*s.alpha)}}C([p()],qe.prototype,"enabled"),C([p()],qe.prototype,"attachRibbonToTransform"),C([p(Ia)],qe.prototype,"colorOverLifetime"),C([p(Ia)],qe.prototype,"colorOverTrail"),C([p()],qe.prototype,"dieWithParticles"),C([p()],qe.prototype,"inheritParticleColor"),C([p(Z)],qe.prototype,"lifetime"),C([p()],qe.prototype,"lifetimeMultiplier"),C([p()],qe.prototype,"minVertexDistance"),C([p()],qe.prototype,"mode"),C([p()],qe.prototype,"ratio"),C([p()],qe.prototype,"ribbonCount"),C([p()],qe.prototype,"shadowBias"),C([p()],qe.prototype,"sizeAffectsLifetime"),C([p()],qe.prototype,"sizeAffectsWidth"),C([p()],qe.prototype,"splitSubEmitterRibbons"),C([p()],qe.prototype,"textureMode"),C([p(Z)],qe.prototype,"widthOverTrail"),C([p()],qe.prototype,"widthOverTrailMultiplier"),C([p()],qe.prototype,"worldSpace");class tt{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new v;_temp2=new v;_temp3=new v;_hasOrbital=!1;_index=0;_orbitalMatrix=new J;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,s,r,a){if(!this.enabled)return;const l=r/a,c=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,h=this.x.evaluate(l),d=this.y.evaluate(l),u=this.z.evaluate(l);if(this._temp.set(-h,d,u),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const m=this._temp2.set(i.x,i.y,i.z),g=this.orbitalXMultiplier,y=this.orbitalYMultiplier,b=this.orbitalZMultiplier,f=c*Math.PI*2*10,_=Math.cos(f*g),w=Math.sin(f*g),S=Math.cos(f*y),O=Math.sin(f*y),L=Math.cos(f*b),D=Math.sin(f*b),W=m.x*(S*L)+m.y*(S*D)+m.z*-O,$=m.x*(w*O*L-_*D)+m.y*(w*O*D+_*L)+m.z*(w*S),H=m.x*(_*O*L+w*D)+m.y*(_*O*D-w*L)+m.z*(_*S),G=this._temp3.set(m.x-W,m.y-$,m.z-H);G.normalize(),G.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=G.x,n.y+=G.y,n.z+=G.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=c,n.y*=c,n.z*=c}}C([p()],tt.prototype,"enabled"),C([p()],tt.prototype,"space"),C([p(Z)],tt.prototype,"orbitalX"),C([p(Z)],tt.prototype,"orbitalY"),C([p(Z)],tt.prototype,"orbitalZ"),C([p()],tt.prototype,"orbitalXMultiplier"),C([p()],tt.prototype,"orbitalYMultiplier"),C([p()],tt.prototype,"orbitalZMultiplier"),C([p()],tt.prototype,"orbitalOffsetX"),C([p()],tt.prototype,"orbitalOffsetY"),C([p()],tt.prototype,"orbitalOffsetZ"),C([p(Z)],tt.prototype,"speedModifier"),C([p()],tt.prototype,"speedModifierMultiplier"),C([p(Z)],tt.prototype,"x"),C([p()],tt.prototype,"xMultiplier"),C([p(Z)],tt.prototype,"y"),C([p()],tt.prototype,"yMultiplier"),C([p(Z)],tt.prototype,"z"),C([p()],tt.prototype,"zMultiplier");class oi{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}C([p()],oi.prototype,"animation"),C([p()],oi.prototype,"enabled"),C([p()],oi.prototype,"cycleCount"),C([p(Z)],oi.prototype,"frameOverTime"),C([p()],oi.prototype,"frameOverTimeMultiplier"),C([p()],oi.prototype,"numTilesX"),C([p()],oi.prototype,"numTilesY"),C([p(Z)],oi.prototype,"startFrame"),C([p()],oi.prototype,"startFrameMultiplier"),C([p()],oi.prototype,"rowMode"),C([p()],oi.prototype,"rowIndex"),C([p()],oi.prototype,"spriteCount"),C([p()],oi.prototype,"timeMode");class Zn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}C([p()],Zn.prototype,"enabled"),C([p()],Zn.prototype,"separateAxes"),C([p(Z)],Zn.prototype,"x"),C([p()],Zn.prototype,"xMultiplier"),C([p(Z)],Zn.prototype,"y"),C([p()],Zn.prototype,"yMultiplier"),C([p(Z)],Zn.prototype,"z"),C([p()],Zn.prototype,"zMultiplier");class bn{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=j.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}C([p()],bn.prototype,"enabled"),C([p()],bn.prototype,"range"),C([p()],bn.prototype,"separateAxes"),C([p(Z)],bn.prototype,"x"),C([p()],bn.prototype,"xMultiplier"),C([p(Z)],bn.prototype,"y"),C([p()],bn.prototype,"yMultiplier"),C([p(Z)],bn.prototype,"z"),C([p()],bn.prototype,"zMultiplier");class Ct{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new v;_temp2=new v;apply(e,t,i,n,s,r,a){if(this.enabled){const l=this.limit.evaluate(s)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const c=this.dampen*.5;t.x=j.lerp(t.x,this._temp.x,c),t.y=j.lerp(t.y,this._temp.y,c),t.z=j.lerp(t.z,this._temp.z,c),i.x=j.lerp(i.x,this._temp.x,c),i.y=j.lerp(i.y,this._temp.y,c),i.z=j.lerp(i.z,this._temp.z,c)}}}}C([p()],Ct.prototype,"enabled"),C([p()],Ct.prototype,"dampen"),C([p(Z)],Ct.prototype,"drag"),C([p()],Ct.prototype,"dragMultiplier"),C([p(Z)],Ct.prototype,"limit"),C([p()],Ct.prototype,"limitMultiplier"),C([p()],Ct.prototype,"separateAxes"),C([p(Z)],Ct.prototype,"limitX"),C([p()],Ct.prototype,"limitXMultiplier"),C([p(Z)],Ct.prototype,"limitY"),C([p()],Ct.prototype,"limitYMultiplier"),C([p(Z)],Ct.prototype,"limitZ"),C([p()],Ct.prototype,"limitZMultiplier"),C([p()],Ct.prototype,"multiplyDragByParticleSize"),C([p()],Ct.prototype,"multiplyDragByParticleVelocity"),C([p()],Ct.prototype,"space");const Ed=class OO{enabled;curve;curveMultiplier;mode;clone(){const e=new OO;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new v),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new v),this.system._iv_velocity}_temp=new v;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};C([p()],Ed.prototype,"enabled"),C([p(Z)],Ed.prototype,"curve"),C([p()],Ed.prototype,"curveMultiplier"),C([p()],Ed.prototype,"mode");let T_=Ed;class Ii{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const s=e.length(),r=j.remap(s,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}C([p()],Ii.prototype,"enabled"),C([p(ee)],Ii.prototype,"range"),C([p()],Ii.prototype,"separateAxes"),C([p(Z)],Ii.prototype,"size"),C([p()],Ii.prototype,"sizeMultiplier"),C([p(Z)],Ii.prototype,"x"),C([p()],Ii.prototype,"xMultiplier"),C([p(Z)],Ii.prototype,"y"),C([p()],Ii.prototype,"yMultiplier"),C([p(Z)],Ii.prototype,"z"),C([p()],Ii.prototype,"zMultiplier");class wc{enabled;range;color;evaluate(e,t,i){const n=e.length(),s=j.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(s,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}C([p()],wc.prototype,"enabled"),C([p(ee)],wc.prototype,"range"),C([p(Ia)],wc.prototype,"color");class E_{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new $i(()=>new kf,s)}system;particleSystem;subSystem;subParticleSystem;type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new B;v_=new v;v2_=new v;_emitterMatrix=new kf;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===A_.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===A_.Death){let n=e.life;if(e[xc]!==void 0&&(n=e[xc]),!(e.age+t*1.2>=n))return;const s=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=s}const i=new kf;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var SF=Object.defineProperty,Xe=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&SF(e,t,n),n};const br=x("debugparticles"),CF=x("noprogressive"),PF=x("debugprogressive");var A_=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(A_||{});class _n extends T{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&M()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){br&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=Xo,t.map.premultiplyAlpha=!1);const i=new Ie;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=Xo,t.map.premultiplyAlpha=!1),e&&t.side===Us&&(t=t.clone(),t.side=wu,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!CF&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,PF&&console.log("Load material LOD",t.name),We.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof V&&(t=this.particleMesh.geometry),t===null)){t=new In(1,1);const i=t.attributes.uv;for(let n=0;n<i.count;n++)i.setX(n,1-i.getX(n))}return new V(t,this.getMaterial())}}Xe([p()],_n.prototype,"renderMode"),Xe([p(ke)],_n.prototype,"particleMaterial"),Xe([p(ke)],_n.prototype,"trailMaterial"),Xe([p()],_n.prototype,"maxParticleSize"),Xe([p()],_n.prototype,"minParticleSize"),Xe([p()],_n.prototype,"velocityScale"),Xe([p()],_n.prototype,"cameraVelocityScale"),Xe([p()],_n.prototype,"lengthScale");class mg{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class I_{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class kF extends I_{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class OF extends I_{_lastPosition=new v;_lastDistance=0;update(){const e=le(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return j.clamp(e,0,i/this.system.deltaTime)}}class MF extends I_{genValue(){return this.system.isPlaying,0}}class _r{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class RF extends _r{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,s=i.evaluate(n);s!==void 0&&(e.uvTile=s)}}}const bk=Symbol("particleRotation");class TF extends _r{type="NeedleRotation";initialize(e){e[bk]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[bk])*t:this.system.renderer.renderMode===vs.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const _k=Symbol("sizeLerpFactor"),EF=new v;class AF extends _r{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[_k]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[_k]).x);let s=1;this.system.renderer.renderMode!==vs.Mesh&&(s=this.system.worldScale.x/this.system.cameraScale);const r=U(e.startSize).multiplyScalar(n*s);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=Sk(this.system,EF);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const xc=Symbol("particleLife"),L_=Symbol("trailLifetime"),vk=Symbol("trailStartLength"),D_=Symbol("trailWidthRandom");class IF extends _r{type="NeedleTrail";initialize(e){e instanceof tw&&(e[xc]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[L_]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[L_]),e[vk]=e.length,e[D_]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof tw){const t=e,i=e.age/e[xc],n=e.previous.values(),s=e.previous.length;for(let r=0;r<s;r++){const a=n.next().value,l=1-r/(s-1),c=e.size;if(c.x<=0&&!this.system.trails.sizeAffectsWidth){const h=20*this.system.trails.widthOverTrail.evaluate(.5,t[D_]);c.x=h,c.y=h,c.z=h}a.size=this.system.trails.getWidth(c.x,i,l,t[D_]),a.color.copy(e.color),this.system.trails.getColor(a.color,i,l)}if(e.age>e[xc]){e.velocity.set(0,0,0);const r=(e.age-e[xc])/e[L_];t.length=j.lerp(e[vk],0,r)}}}}const gg=Symbol("startVelocity"),wk=Symbol("gravityModifier"),j_=Symbol("gravitySpeed"),fg=Symbol("velocity lerp factor"),F_=new v;class LF extends _r{type="NeedleVelocity";_gravityDirection=new v;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[gg]?e[gg].copy(e.velocity):e[gg]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[wk]=n*t,e[j_]=n*t*.5,e[fg]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Td.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[gg],n=e[wk];if(n!==0){const d=n*e[j_];F_.copy(this._gravityDirection).multiplyScalar(d),e[j_]+=t*.05,i.add(F_)}e.velocity.copy(i);const s=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,s,e[fg]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,s,e[fg],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[fg],e.color);const c=this.system.velocityOverLifetime;c.enabled&&c.apply(e,0,e.position,e.velocity,t,e.age,e.life);const h=this.system.limitVelocityOverLifetime;if(h.enabled&&h.apply(e.position,i,e.velocity,e.size,s,t,1),this.system.worldspace){const d=this.system.worldScale;e.velocity.x*=d.x,e.velocity.y*=d.y,e.velocity.z*=d.z}}}const xk=Symbol("colorLerpFactor"),B_=new he(1,1,1,1),Da=new he(1,1,1,1);class DF extends _r{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Da.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(B_.copy(t.color),B_.alpha=t.opacity??1,Da.multiply(B_)),Da.convertLinearToSRGB(),e.startColor.set(Da.r,Da.g,Da.b,Da.alpha),e.color.copy(e.startColor),e[xk]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[xk]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class jF{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new OF(this.system)}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new mg(this.system.main.startLifetime)}get startSpeed(){return new mg(this.system.main.startSpeed)}get startRotation(){return new mg(this.system.main.startRotation)}get startSize(){return new mg(this.system.main.startSize)}startLength;get startColor(){return new CR(new PR(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new MF(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return Jo.Trail;switch(this.system.renderer.renderMode){case vs.Billboard:return Jo.BillBoard;case vs.Stretch:return Jo.StretchedBillBoard;case vs.HorizontalBillboard:return Jo.HorizontalBillBoard;case vs.VerticalBillboard:return Jo.VerticalBillBoard;case vs.Mesh:return Jo.Mesh}return Jo.BillBoard}rendererEmitterSettings={startLength:new kR(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===vs.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=Xo,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=jy(new he(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new kF(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??$M}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Td.World}}class FF{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const si=class Hg extends T{play(e=!1){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Hg&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Hg&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&P.foreachComponent(this.gameObject,i=>{i instanceof Hg&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new FF),this._state.waitEmiting=e,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===Td.World}get localspace(){return this.main.simulationSpace===Td.Local}__worldQuaternion=new B;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new B;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new v;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new v;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,le(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof _r&&(e.system=this),br&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(e);return i!==-1&&((M()||br)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),t.splice(i,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof ug)){const n=new ug;bl(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof yg)){const n=new yg;bl(n,i),e[t]=n}}br&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(_n),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new R,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new xR,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new jF(this),this._particleSystem=new SR(this._interface),this._particleSystem.addBehavior(new AF(this)),this._particleSystem.addBehavior(new DF(this)),this._particleSystem.addBehavior(new RF(this)),this._particleSystem.addBehavior(new TF(this)),this._particleSystem.addBehavior(new LF(this)),this._particleSystem.addBehavior(new IF(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),br&&(console.log(this),this.gameObject.add(new Ui(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof V&&this._interface.renderMode==Jo.Mesh&&We.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==Jo.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,i=this.main.startLifetime.getMax(),n=Math.min(Math.max(t,i)/Math.max(.01,this.main.simulationSpeed),1e3),s=Math.ceil(n/e),r=Date.now();br&&console.log(`Particles ${this.name} - Prewarm for ${s} frames (${n} sec). Duration: ${t}, Lifetime: ${i}`);for(let a=0;a<s&&!(this.currentParticles>=this.maxParticles);a++){const l=Date.now()-r;if(l>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${l}`);break}this.onUpdate(),this.onSimulate(e)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=Je(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(Re(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Je(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=Sk(this,F_);this._container.matrix.makeScale(n.x,n.y,n.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():M()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new E_(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else br&&console.warn("Could not add SubParticleSystem",e,this)}}};Xe([p(pg)],si.prototype,"colorOverLifetime"),Xe([p(ni)],si.prototype,"main"),Xe([p(xs)],si.prototype,"emission"),Xe([p(La)],si.prototype,"sizeOverLifetime"),Xe([p(R_)],si.prototype,"shape"),Xe([p(Se)],si.prototype,"noise"),Xe([p(qe)],si.prototype,"trails"),Xe([p(tt)],si.prototype,"velocityOverLifetime"),Xe([p(Ct)],si.prototype,"limitVelocityOverLifetime"),Xe([p(T_)],si.prototype,"inheritVelocity"),Xe([p(wc)],si.prototype,"colorBySpeed"),Xe([p(oi)],si.prototype,"textureSheetAnimation"),Xe([p(Zn)],si.prototype,"rotationOverLifetime"),Xe([p(bn)],si.prototype,"rotationBySpeed"),Xe([p(Ii)],si.prototype,"sizeBySpeed");let Ad=si;class yg{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof Ad)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=P.findByGuid(n,t)),br&&!(this.particleSystem instanceof Ad)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function Sk(o,e){if(e.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case M_.Local:e=Je(o.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+M_[o.main.scalingMode]+" is not supported";M()&&ge(t),console.warn(t,o.name,o)}e=Je(o.gameObject,e);break}return e}var BF=Object.defineProperty,U_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&BF(e,t,n),n};class Sc extends T{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),s=n.length();if(s>this.radius)return;let r=t;s>1?r/=s*s:r/=Math.max(.05,s),i.applyImpulse(n.multiplyScalar(r))})}}U_([p()],Sc.prototype,"strength"),U_([p()],Sc.prototype,"radius"),U_([p(rt)],Sc.prototype,"targets");class $c extends T{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(se.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(se.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Ry(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=P.getComponentInParent(this.gameObject,Ti);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=P.getComponentInParent(this.gameObject,wt);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=$c.hashCode(e),i=$c.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const s=n;s.material&&s.material.color&&this.assignColor(i,e,s)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new oe(t/255,i/255,n/255)}}var UF=Object.defineProperty,zF=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&UF(e,t,n),n};const z_=x("debugpost");class gt extends T{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof N?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;onEnable(){super.onEnable(),z_&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.active=!0,this.context.postprocessing.addEffect(this)}onDisable(){super.onDisable(),z_&&console.warn("Disable",this.constructor.name),this.context.postprocessing.removeEffect(this),this.active=!1}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){z_&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof N&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof N){const i=e.value;return this[t].value=i,!0}}}zF([p()],gt.prototype,"active");var NF=Object.defineProperty,$F=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&NF(e,t,n),n};const WF=x("debugpost"),N_={};function vn(o,e){N_[o]=e}function VF(o){return o.__type in N_?N_[o.__type]:(WF&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),gt)}class bg{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}$F([it([o=>VF(o),gt])],bg.prototype,"components");var GF=Object.defineProperty,HF=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&GF(e,t,n),n};const qF=x("debugpost");var Ck=(o=>(o[o.LOW=0]="LOW",o[o.MEDIUM=1]="MEDIUM",o[o.HIGH=2]="HIGH",o[o.ULTRA=3]="ULTRA",o))(Ck||{});class Id extends gt{get typeName(){return"Antialiasing"}preset=new N(2);onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??A.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:A.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{qF&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}HF([p(N)],Id.prototype,"preset"),vn("Antialiasing",Id);var XF=Object.defineProperty,$_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&XF(e,t,n),n};const _g=class MO extends gt{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new N(.9);intensity=new N(1);scatter=new N(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=MO.useSelectiveBloom),this.selectiveBloom){const t=e=new A.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new A.POSTPROCESSING.MODULE.BloomEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=Ko.lerp(.1,.9,t))},e}};$_([p(N)],_g.prototype,"threshold"),$_([p(N)],_g.prototype,"intensity"),$_([p(N)],_g.prototype,"scatter");let vg=_g;vn("Bloom",vg);var QF=Object.defineProperty,YF=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&QF(e,t,n),n};class Ld extends gt{get typeName(){return"ChromaticAberration"}intensity=new N(0);onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new ee(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}YF([p(N)],Ld.prototype,"intensity"),vn("ChromaticAberration",Ld);var Cc=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(Cc||{});const Pk=new Map;function W_(o){switch(o){case 0:return bf;case 1:return yf;case 2:return yu;case 3:return fu;case 4:return sl;default:return Pk.has(o)||(Pk.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),sl}}function KF(o){switch(o){case bf:return 0;case yu:return 2;case fu:return 3;case sl:return 1;case yf:return 1;default:return 0}}function wg(o){switch(o){case bf:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case yu:return A.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case fu:return A.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case sl:return A.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case yf:return A.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var ZF=Object.defineProperty,kk=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&ZF(e,t,n),n};const V_=x("debugpost");class ja extends gt{get typeName(){return"ToneMapping"}mode=new N(void 0);exposure=new N(1);setMode(e){const t=Cc[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}get threeToneMapping(){return this.mode.isInitialized&&this.mode.overrideState?W_(this.mode.value):this.context.renderer.toneMapping}get toneMappingExposure(){return this.exposure.overrideState&&this.exposure.value!==void 0?Math.max(0,this.exposure.value):this.context.renderer.toneMappingExposure}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=KF(this.context.renderer.toneMapping);V_&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=W_(this.mode.value),t=this._tonemappingEffect=new A.POSTPROCESSING.MODULE.ToneMappingEffect({mode:wg(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=w1(i),t.mode=wg(i);else{const n=W_(i);t.mode=wg(n)}t.name="ToneMapping ("+Cc[i]+")",V_&&console.log("[PostProcessing] ToneMapping mode changed to",Cc[i],e,t.mode)},V_&&console.log("[PostProcessing] Use ToneMapping",Cc[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}}kk([p(N)],ja.prototype,"mode"),kk([p(N)],ja.prototype,"exposure"),vn("Tonemapping",ja);var JF=Object.defineProperty,xg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&JF(e,t,n),n};class vr extends gt{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new N(1);contrast=new N(0);hueShift=new N(0);saturation=new N(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[],t=this.postprocessingContext?.components.find(r=>r instanceof ja);let i=!1;this.postExposure.onValueChanged=r=>{if(this.postExposure.overrideState){if(!t){i||(i=!0,console.warn("[PostProcessing] ColorAdjustments.PostExposure has no effect: add a ToneMappingEffect to your postprocessing stack."));return}t.exposure.value=r}};const n=new A.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=r=>n.contrast=r;const s=new A.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=r=>s.hue=r,this.saturation.onValueChanged=r=>s.saturation=r,e.push(n),e.push(s),e}}xg([p(N)],vr.prototype,"postExposure"),xg([p(N)],vr.prototype,"contrast"),xg([p(N)],vr.prototype,"hueShift"),xg([p(N)],vr.prototype,"saturation"),vn("ColorAdjustments",vr);var eB=Object.defineProperty,Fa=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&eB(e,t,n),n},Ok=(o=>(o[o.Off=0]="Off",o[o.Gaussian=1]="Gaussian",o[o.Bokeh=2]="Bokeh",o))(Ok||{});const tB=x("debugpost");class Jn extends gt{get typeName(){return"DepthOfField"}mode;focusDistance=new N(1);focalLength=new N(.2);aperture=new N(20);gaussianMaxRadius=new N;resolutionScale=new N(1/window.devicePixelRatio);bokehScale=new N;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return j.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return j.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){tB&&console.warn("DepthOfField: Mode is set to Off");return}const e=new A.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:this.focalLength.value,focalLength:1,bokehScale:this.aperture.value,resolutionScale:this.resolutionScale.value});return e.cocMaterial.worldFocusDistance=this.focusDistance.value,this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}Fa([p()],Jn.prototype,"mode"),Fa([p(N)],Jn.prototype,"focusDistance"),Fa([p(N)],Jn.prototype,"focalLength"),Fa([p(N)],Jn.prototype,"aperture"),Fa([p(N)],Jn.prototype,"gaussianMaxRadius"),Fa([p(N)],Jn.prototype,"resolutionScale"),Fa([p(N)],Jn.prototype,"bokehScale"),vn("DepthOfField",Jn);class Dd extends gt{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var iB=Object.defineProperty,nB=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&iB(e,t,n),n};const Mk=x("debugpost");class jd extends gt{get typeName(){return"PixelationEffect"}granularity=new N(10);_effect=null;_lastDpr=0;onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.PixelationEffect;this._effect=e;const t=this.context.renderer.getPixelRatio();return this._lastDpr=t,e.granularity=this.granularity.value*t,this.granularity.onValueChanged=i=>{const n=this.context.renderer.getPixelRatio();e.granularity=i*n,Mk&&console.debug(`[PixelationEffect] granularity changed: raw=${i}, dpr=${n}, effective=${e.granularity}`)},e}update(){if(!this._effect)return;const e=this.context.renderer.getPixelRatio();e!==this._lastDpr&&(this._lastDpr=e,this._effect.granularity=this.granularity.value*e,Mk&&console.debug(`[PixelationEffect] DPR changed to ${e}, updating granularity: raw=${this.granularity.value}, effective=${this._effect.granularity}`))}}nB([p(N)],jd.prototype,"granularity"),vn("PixelationEffect",jd);var oB=Object.defineProperty,Fd=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&oB(e,t,n),n};class Ss extends gt{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new N(2);falloff=new N(1);samples=new N(9);color=new N(new oe(0,0,0));luminanceInfluence=new N(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof me){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new A.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new A.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new A.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new oe),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const s=new Array;return s.push(t),s.push(i),s.push(n),s}}Fd([p(N)],Ss.prototype,"intensity"),Fd([p(N)],Ss.prototype,"falloff"),Fd([p(N)],Ss.prototype,"samples"),Fd([p(N)],Ss.prototype,"color"),Fd([p(N)],Ss.prototype,"luminanceInfluence"),vn("ScreenSpaceAmbientOcclusion",Ss);var sB=Object.defineProperty,Ba=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&sB(e,t,n),n};const rB=x("debugN8AO");var Sg=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(Sg||{});class eo extends gt{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new N(1);falloff=new N(1);intensity=new N(1);color=new N(new oe(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(Sg[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new A.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const s=Sg[this.quality];if(n.setQualityMode(s),n.configuration.transparencyAware=!1,n.configuration.halfRes=window.devicePixelRatio>1,n.effectCompositerQuad?.material){const a=n.effectCompositerQuad.material;a.fragmentShader=a.fragmentShader.replace(`if (depth == 1.0) {
1407
+ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;Fe(e),console.warn(e)}}function rF(o,e){if("scenes"in e){for(const t of e.scenes)if(t&&!t.animations?.length)for(const i of e.animations)t.animations.includes(i)||t.animations.push(i)}if(o instanceof Jv||o instanceof Sf){let t=e;t instanceof R||(t=e.scene||e.scenes.find(i=>i)),t.traverse(i=>{const n=i;n?.isMesh&&Zf(n,n.material)})}}var aF=Object.defineProperty,lF=Object.getOwnPropertyDescriptor,og=(o,e,t,i)=>{for(var n=lF(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&aF(e,t,n),n};class Ra extends T{set url(e){e!==this._url&&(this._url=e,e&&this.__internalDidAwake&&this.activeAndEnabled&&!this._loading&&this.load(e))}get url(){return this._url}_url;set opacity(e){this._opacity=e,this._splatMesh&&(this._splatMesh.opacity=e,this._splatMesh.updateVersion())}get opacity(){return this._opacity}_opacity=1;set raycastable(e){this._raycastable=e,this._splatMesh&&(this._splatMesh.raycastable=e)}get raycastable(){return this._raycastable}_raycastable=!0;set quality(e){e!==this._quality&&(this._quality=e,this._splatMesh&&Ny(this.context,this._splatMesh,e))}get quality(){return this._quality}_quality="auto";get splatMesh(){return this._splatMesh}get isLoaded(){return this._splatMesh?.isInitialized===!0}get initialized(){return this._initialized}_splatMesh=null;_initialized=Promise.resolve();_loading=!1;_loadGeneration=0;awake(){this._loadGeneration++,this._splatMesh=null,this._initialized=Promise.resolve(),this._loading=!1}onEnable(){this.url&&!this._splatMesh&&!this._loading&&this.load(this.url),this._splatMesh&&(this._splatMesh.visible=!0,this._splatMesh.updateVersion())}onDisable(){this._splatMesh&&(this._splatMesh.visible=!1,this._splatMesh.updateVersion())}onDestroy(){this._splatMesh&&(this._splatMesh.removeFromParent(),this._splatMesh.dispose(),this._splatMesh=null)}async load(e){const t=++this._loadGeneration;this._url=e,this._splatMesh&&(this._splatMesh.removeFromParent(),this._splatMesh.dispose(),this._splatMesh=null),this._loading=!0;const i=await mk(e,{context:this.context});if(t!==this._loadGeneration||this.destroyed)return i?.scene?.dispose(),null;const n=i?.scene;return n?(n.name="Gaussian Splat",n.hideFlags|=uo.DontExport|uo.DontInstantiate,n.opacity=this._opacity,n.raycastable=this.raycastable,this._splatMesh=n,this.gameObject.add(n),this.activeAndEnabled||(n.visible=!1),this._initialized=n.initialized.then(()=>{t===this._loadGeneration&&(this._loading=!1)}),await this._initialized,t!==this._loadGeneration||this.destroyed?null:(Ny(this.context,n,this._quality),n)):(this._loading=!1,null)}}og([p(URL)],Ra.prototype,"url"),og([p()],Ra.prototype,"opacity"),og([p()],Ra.prototype,"raycastable"),og([p()],Ra.prototype,"quality");var cF=Object.defineProperty,b_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&cF(e,t,n),n};class Ta extends T{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!mh||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new jM(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=sb(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Ee.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}b_([p()],Ta.prototype,"objectBounds"),b_([p(oe)],Ta.prototype,"color"),b_([p()],Ta.prototype,"isGizmo");var hF=Object.defineProperty,__=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&hF(e,t,n),n};class yc extends T{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!mh)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Ov(e,t,this.color0??new oe(.4,.4,.4),this.color1??new oe(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}__([p()],yc.prototype,"isGizmo"),__([p(oe)],yc.prototype,"color0"),__([p(oe)],yc.prototype,"color1");var dF=Object.defineProperty,v_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&dF(e,t,n),n};class w_ extends T{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;_jointHandle=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(rt)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}onDisable(){this._jointHandle&&(this.context.physics.engine?.removeJoint(this._jointHandle),this._jointHandle=null)}*create(){if(yield,!this._jointHandle&&this.rigidBody&&this.connectedBody&&this.activeAndEnabled){const e=this.createJoint(this.rigidBody,this.connectedBody);e instanceof Promise?yield e.then(t=>this._jointHandle=t):this._jointHandle=e}}}v_([p(rt)],w_.prototype,"connectedBody");class x_ extends w_{createJoint(e,t){return this.context.physics.engine?.addFixedJoint(e,t)??null}}class Md extends w_{anchor;axis;createJoint(e,t){return this.axis&&this.anchor?this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)??null:null}}v_([p(v)],Md.prototype,"anchor"),v_([p(v)],Md.prototype,"axis");var uF=Object.defineProperty,pF=Object.getOwnPropertyDescriptor,tn=(o,e,t,i)=>{for(var n=i>1?void 0:i?pF(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&uF(e,t,n),n};function bc(o){return o*Math.PI/180}const fk=300,Io=x("debuglights");var S_=(o=>(o[o.Spot=0]="Spot",o[o.Directional=1]="Directional",o[o.Point=2]="Point",o[o.Area=3]="Area",o[o.Rectangle=3]="Rectangle",o[o.Disc=4]="Disc",o))(S_||{});class $t extends T{get type(){return this._type}set type(e){if(this.light&&this.__didAwake)throw new Error("Changing the light type at runtime is not supported");switch(e){case 1:this._type="directional";break;case 2:this._type="point";break;case 0:this._type="spot";break;case"directional":case"point":case"spot":this._type=e;break;default:(Io||M())&&console.warn(`[Light] Unsupported light type: ${S_[e]} (${e}) on '${this.name}'`),this._type="unsupported";break}}_type="point";get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type==="SpotLight"||this.light.type==="PointLight")&&"distance"in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type==="SpotLight"&&"angle"in this.light&&(this.light.angle=bc(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type==="SpotLight"&&"penumbra"in this.light){const t=this.spotAngle,i=1-bc(e/2)/bc(t/2);this.light.penumbra=i}}_innerSpotAngle=10;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new oe(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.shadowLight?.shadow?.camera!==void 0)){const t=this.shadowLight.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.shadowLight?.shadow?.bias!==void 0&&(this.shadowLight.shadow.bias=e,this.shadowLight.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.shadowLight?.shadow?.normalBias!==void 0&&(this.shadowLight.shadow.normalBias=e,this.shadowLight.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){this._intensity=e,this.light&&(this.light.intensity=e),Io&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.shadowLight;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.shadowLight;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.shadowLight;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.shadowLight;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;get shadowLight(){const e=this.light;if(e&&"shadow"in e)return e}getWorldPosition(e){return this.light?this.type==="directional"?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new oe(this.color??16777215),Io&&console.log(this.name,this)}onEnable(){Io&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Io&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.context.lights.push(this))}onDisable(){Io&&console.log("DISABLE LIGHT",this.name);const e=this.context.lights.indexOf(this);e!==-1&&this.context.lights.splice(e,1),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}createLight(){const e=this.selfIsLight;if(e&&!this.light)this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type==="directional"&&this.setDirectionalLight(this.light);else if(!this.light)switch(this.type){case"directional":const t=new lf(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-fk*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),zr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Io){const r=new BM(this.light,.2,this.color);this.context.scene.add(r)}break;case"spot":const i=new FM(this.color,this.intensity*Math.PI,this.range,bc(this.spotAngle/2),1-bc(this.innerSpotAngle/2)/bc(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case"point":const s=new cf(this.color,this.intensity*Math.PI,this.range);this.light=s;break;default:Io&&console.warn(`[Light] Unsupported light type: ${S_[this.type]} (${this.type}) on '${this.name}'`);break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.shadowLight?.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.shadowLight.shadow.mapSize.width=this._shadowResolution,this.shadowLight.shadow.mapSize.height=this._shadowResolution):(this.shadowLight.shadow.mapSize.width=2048,this.shadowLight.shadow.mapSize.height=2048),Io&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.shadowLight.shadow.bias=this.shadowBias,this.shadowLight.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const t=this.shadowLight.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=fk*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{const i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.shadowLight.shadow.needsUpdate=!0,Io&&this.context.scene.add(new UM(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.shadowLight.shadow&&(this.shadows===2||(this.shadowLight.shadow.radius=1,this.shadowLight.shadow.blurSamples=1))}onEnterXR(e){this.applyXRScale(e.xr.rigScale)}onUpdateXR(e){this.applyXRScale(e.xr.rigScale)}onLeaveXR(e){this.applyXRScale(1)}applyXRScale(e){this.light&&("distance"in this.light?(this.light.intensity=this._intensity/e,this.light.distance=this._range/e):this.light.intensity=this._intensity)}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}tn([p()],$t.prototype,"type",1),tn([p()],$t.prototype,"range",1),tn([p()],$t.prototype,"spotAngle",1),tn([p()],$t.prototype,"innerSpotAngle",1),tn([p(oe)],$t.prototype,"color",1),tn([p()],$t.prototype,"shadowNearPlane",1),tn([p()],$t.prototype,"shadowBias",1),tn([p()],$t.prototype,"shadowNormalBias",1),tn([p()],$t.prototype,"shadows",1),tn([p()],$t.prototype,"lightmapBakeType",2),tn([p()],$t.prototype,"intensity",1),tn([p()],$t.prototype,"shadowDistance",1),tn([p()],$t.prototype,"shadowResolution",1);var mF=Object.defineProperty,sg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&mF(e,t,n),n};const C_=x("debuglods"),gF=x("nolods");class _c{screenRelativeTransitionHeight;distance;renderers}sg([p()],_c.prototype,"screenRelativeTransitionHeight"),sg([p()],_c.prototype,"distance"),sg([p(gi)],_c.prototype,"renderers");class fF{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class rg extends T{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(C_&&console.log("LODGROUP",this.name,this.lodModels,this),!gF&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new fF(i);this._lods.push(n);for(const s of n.renderers)e.includes(s)||e.push(s)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new zM;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new R;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],s=this._lodsHandler[i],r=n.gameObject;C_&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let c=null;if(a.renderers.includes(n)?c=r:c=t,c.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${c.name}`);continue}C_&&console.log("LEVEL",c.name,l),s.autoUpdate=!1,this.onAddLodLevel(s,c,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}sg([p(_c)],rg.prototype,"lodModels");var yF=Object.defineProperty,P_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&yF(e,t,n),n};const ag=x("debugnestedgltf");class vc extends T{filePath;loaded=new re;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;ag&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new $o;t.idProvider=new _t(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;ag&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);ag&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.loaded.invoke({component:this,instance:n,asset:this.filePath})),ag&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}P_([p(ie)],vc.prototype,"filePath"),P_([p(re)],vc.prototype,"loaded"),P_([p()],vc.prototype,"loadAssetInParent");var bF=Object.defineProperty,k_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&bF(e,t,n),n};const _F=x("debugnet"),lg=class Cv extends T{url=null;urlParameterName=null;localhost=null;awake(){_F&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Cv.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=x(this.urlParameterName);i&&typeof i=="string"&&(e=i)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t?.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let i=e;const n=Cv.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const s=n?i:window.location.origin;s?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=s+e}return i}static IsLocalNetwork(e=window.location.hostname){return Ni(e)}};k_([p()],lg.prototype,"url"),k_([p()],lg.prototype,"urlParameterName"),k_([p()],lg.prototype,"localhost");let O_=lg;var vF=Object.defineProperty,cg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vF(e,t,n),n};class Ea extends T{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new v(0,0,0);rotationOffset=new v(0,0,0);offset=new v(0,0,0);update(){if(!this.from)return;var e=le(this.from),t=Re(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new rl(this.gameObject.up,0),l=le(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const c=new v(0,0,0);a.projectPoint(e,c),e.copy(c)}this.affectPosition&&Vi(this.gameObject,e);const n=new je(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),s=new B().setFromEuler(n);this.affectRotation&&Fn(this.gameObject,t.multiply(s));const r=new v;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}cg([p(P)],Ea.prototype,"referenceSpace"),cg([p(P)],Ea.prototype,"from"),cg([p(v)],Ea.prototype,"positionOffset"),cg([p(v)],Ea.prototype,"rotationOffset");var wF=Object.defineProperty,fr=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&wF(e,t,n),n};class Ai{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}fr([p()],Ai.prototype,"time"),fr([p()],Ai.prototype,"value"),fr([p()],Ai.prototype,"inTangent"),fr([p()],Ai.prototype,"inWeight"),fr([p()],Ai.prototype,"outTangent"),fr([p()],Ai.prototype,"outWeight"),fr([p()],Ai.prototype,"weightedMode");const yk=class au{static linearFromTo(e,t,i){const n=new au,s=new Ai;s.time=0,s.value=e;const r=new Ai;return r.time=i,r.value=t,n.keys.push(s,r),n}static constant(e){const t=new au,i=new Ai;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new au;return e.keys=this.keys?.map(t=>{const i=new Ai;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<e)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:au.interpolateValue(e,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,s=t.value,r=t.outTangent,a=i.time,l=i.value,c=i.inTangent,h=a-n,d=h*h,u=d*h,m=((r+c)*h-2*(l-s))/u,g=(3*(l-s)-(c+2*r)*h)/d,y=r,b=s,f=e-n,_=f*f,w=_*f;return m*w+g*_+y*f+b}};fr([p(Ai)],yk.prototype,"keys");let Rd=yk;var xF=Object.defineProperty,C=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xF(e,t,n),n};const hg=x("debugparticles");var vs=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(vs||{});class Aa{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,s=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!s)&&(s=l,r=a)}if(s)if(r+1<this.colorKeys.length){const a=this.colorKeys[r+1],l=j.remap(e,s.time,a.time,0,1);t.r=j.lerp(s.color.r,a.color.r,l),t.g=j.lerp(s.color.g,a.color.g,l),t.b=j.lerp(s.color.b,a.color.b,l)}else t.r=s.color.r,t.g=s.color.g,t.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const a=this.alphaKeys[n+1],l=j.remap(e,i.time,a.time,0,1);t.alpha=j.lerp(i.alpha,a.alpha,l)}else t.alpha=i.alpha;return t}}C([p()],Aa.prototype,"alphaKeys"),C([p()],Aa.prototype,"colorKeys");var Td=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(Td||{}),dg=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(dg||{});const ws=class lu{static constant(e){const t=new lu;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new lu;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new lu;return i.setCurve(e,t),i}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new lu;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=j.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,s=e*this.curveMax.duration;return j.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return j.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};C([p()],ws.prototype,"mode"),C([p()],ws.prototype,"constant"),C([p()],ws.prototype,"constantMin"),C([p()],ws.prototype,"constantMax"),C([p(Rd)],ws.prototype,"curve"),C([p(Rd)],ws.prototype,"curveMin"),C([p(Rd)],ws.prototype,"curveMax"),C([p()],ws.prototype,"curveMultiplier");let Z=ws;const yr=class Ht{static constant(e){const t=new Ht;return t.constant(e),t}static betweenTwoColors(e,t){const i=new Ht;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new he(0,0,0,1);static _temp2=new he(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,Ht._temp),Ht._temp;case 2:case"TwoColors":return Ht._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,Ht._temp),this.gradientMax.evaluate(e,Ht._temp2),Ht._temp.lerp(Ht._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(e,Ht._temp),this.gradientMax.evaluate(e,Ht._temp2),Ht._temp.lerp(Ht._temp2,n)}return Ht._temp.set(16777215),Ht._temp.alpha=1,Ht._temp}};C([p()],yr.prototype,"mode"),C([p(he)],yr.prototype,"color"),C([p(he)],yr.prototype,"colorMin"),C([p(he)],yr.prototype,"colorMax"),C([p(Aa)],yr.prototype,"gradient"),C([p(Aa)],yr.prototype,"gradientMin"),C([p(Aa)],yr.prototype,"gradientMax");let Ia=yr;var M_=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(M_||{});class ni{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}C([p(Z)],ni.prototype,"gravityModifier"),C([p(Ia)],ni.prototype,"startColor"),C([p(Z)],ni.prototype,"startDelay"),C([p(Z)],ni.prototype,"startLifetime"),C([p(Z)],ni.prototype,"startRotation"),C([p(Z)],ni.prototype,"startRotationX"),C([p(Z)],ni.prototype,"startRotationY"),C([p(Z)],ni.prototype,"startRotationZ"),C([p(Z)],ni.prototype,"startSize"),C([p(Z)],ni.prototype,"startSizeX"),C([p(Z)],ni.prototype,"startSizeY"),C([p(Z)],ni.prototype,"startSizeZ"),C([p(Z)],ni.prototype,"startSpeed");class ug{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=j.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=j.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class xs{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}C([p()],xs.prototype,"enabled"),C([p()],xs.prototype,"bursts"),C([p(Z)],xs.prototype,"rateOverTime"),C([p()],xs.prototype,"rateOverTimeMultiplier"),C([p(Z)],xs.prototype,"rateOverDistance"),C([p()],xs.prototype,"rateOverDistanceMultiplier");class pg{enabled;color}C([p(Ia)],pg.prototype,"color");class La{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new v;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}C([p(Z)],La.prototype,"size"),C([p(Z)],La.prototype,"x"),C([p(Z)],La.prototype,"y"),C([p(Z)],La.prototype,"z");const mt=class cu{get type(){return dg[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new cu}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new je;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new J;_worldSpaceMatrixInverse=new J;constructor(){hg&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=j.toRadians(this.rotation.x),this._rotation.y=j.toRadians(this.rotation.y),this._rotation.z=j.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new v(0,0,0);_temp=new v(0,0,0);_triangle=new NM;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:hg&&F.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const s=this.meshRenderer;s?.destroyed==!1&&this.setMesh(s);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),c=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,c),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=c}break;case 1:break;case 2:{const l=a.index;if(l){let c=Math.random(),h=Math.random();c+h>1&&(c=1-c,h=1-h);const d=Math.floor(Math.random()*(l.count/3));let u=d*3,m=d*3+1,g=d*3+2;u=l.getX(u),m=l.getX(m),g=l.getX(g);const y=a.getAttribute("position");this._triangle.a.fromBufferAttribute(y,u),this._triangle.b.fromBufferAttribute(y,m),this._triangle.c.fromBufferAttribute(y,g),this._vector.set(0,0,0).addScaledVector(this._triangle.a,c).addScaledVector(this._triangle.b,h).addScaledVector(this._triangle.c,1-(c+h)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=d}}break}break;default:this._vector.set(0,0,0),M()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",dg[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),hg&&F.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new v;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,s=t.z;this._dir.set(i,n,s),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),c=e.mesh_normal;this._dir.fromBufferAttribute(l,c)}break;case 1:break;case 2:{const l=a.index;if(l){const c=e.mesh_normal,h=l.getX(c*3),d=l.getX(c*3+1),u=l.getX(c*3+2),m=a.getAttribute("position"),g=U(),y=U(),b=U();g.fromBufferAttribute(m,h),y.fromBufferAttribute(m,d),b.fromBufferAttribute(m,u),g.sub(y),b.sub(y),g.cross(b),this._dir.copy(g).multiplyScalar(-1);const f=Re(r);this._dir.applyQuaternion(f)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),hg&&(F.DrawSphere(t,.01,8925952,.5,!0),F.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new B;static _tempVec=new v;randomizePosition(e,t){if(t<=0)return;const i=cu._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=cu._randomQuat,n=cu._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),s=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new v(s,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,s){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),c=Math.acos(2*a-1),h=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,d=e.x+this.scale.x*(-h*Math.sin(c)*Math.cos(l)),u=e.y+this.scale.y*(h*Math.sin(c)*Math.sin(l)),m=e.z+this.scale.z*(h*Math.cos(c));s.x=d,s.y=u,s.z=m}randomCirclePoint(e,t,i,n,s){const r=Math.random(),a=2*Math.PI*r*(n/360),l=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,c=e.x+this.scale.x*l*Math.cos(a),h=e.y+this.scale.y*l*Math.sin(a),d=e.z;s.x=c,s.y=h,s.z=d}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,s,r,a){let l=0,c=0;switch(r){case 0:l=Math.random(),c=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,c=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let h=2*Math.PI*l*(s/360);switch(r){case 2:case 1:h+=Math.PI+.5,h+=this._loopTime*Math.PI*2,h%=j.toRadians(s);break}const d=Math.acos(2*c-1),u=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-u*Math.sin(d)*Math.cos(h),g=e.y+u*Math.sin(d)*Math.sin(h),y=e.z;a.x=m*this.scale.x,a.y=g*this.scale.y,a.z=y*this.scale.z}};C([p()],mt.prototype,"shapeType"),C([p()],mt.prototype,"enabled"),C([p()],mt.prototype,"alignToDirection"),C([p()],mt.prototype,"angle"),C([p()],mt.prototype,"arc"),C([p()],mt.prototype,"arcSpread"),C([p()],mt.prototype,"arcSpeedMultiplier"),C([p()],mt.prototype,"arcMode"),C([p(v)],mt.prototype,"boxThickness"),C([p(v)],mt.prototype,"position"),C([p(v)],mt.prototype,"rotation"),C([p(v)],mt.prototype,"scale"),C([p()],mt.prototype,"radius"),C([p()],mt.prototype,"radiusThickness"),C([p()],mt.prototype,"sphericalDirectionAmount"),C([p()],mt.prototype,"randomDirectionAmount"),C([p()],mt.prototype,"randomPositionAmount"),C([p()],mt.prototype,"meshShapeType"),C([p(cd)],mt.prototype,"meshRenderer");let R_=mt;class Ce{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new v;apply(e,t,i,n,s,r){if(!this.enabled)return;this._noise||(this._noise=wR(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),c=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),h=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,c,h).normalize();const d=s/r;let u=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=u*this.strengthXMultiplier,this._temp.y*=u*this.strengthYMultiplier,this._temp.z*=u*this.strengthZMultiplier):(this.strengthX&&(u*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(u)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}C([p()],Ce.prototype,"damping"),C([p()],Ce.prototype,"enabled"),C([p()],Ce.prototype,"frequency"),C([p()],Ce.prototype,"octaveCount"),C([p()],Ce.prototype,"octaveMultiplier"),C([p()],Ce.prototype,"octaveScale"),C([p(Z)],Ce.prototype,"positionAmount"),C([p()],Ce.prototype,"quality"),C([p(Z)],Ce.prototype,"remap"),C([p()],Ce.prototype,"remapEnabled"),C([p()],Ce.prototype,"remapMultiplier"),C([p(Z)],Ce.prototype,"remapX"),C([p()],Ce.prototype,"remapXMultiplier"),C([p(Z)],Ce.prototype,"remapY"),C([p()],Ce.prototype,"remapYMultiplier"),C([p(Z)],Ce.prototype,"remapZ"),C([p()],Ce.prototype,"remapZMultiplier"),C([p()],Ce.prototype,"scrollSpeedMultiplier"),C([p()],Ce.prototype,"separateAxes"),C([p()],Ce.prototype,"strengthMultiplier"),C([p(Z)],Ce.prototype,"strengthX"),C([p()],Ce.prototype,"strengthXMultiplier"),C([p(Z)],Ce.prototype,"strengthY"),C([p()],Ce.prototype,"strengthYMultiplier"),C([p(Z)],Ce.prototype,"strengthZ"),C([p()],Ce.prototype,"strengthZMultiplier");class qe{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const s=this.widthOverTrail.evaluate(i,n);return e*=s,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(t);e.x*=n.r*s.r,e.y*=n.g*s.g,e.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(e.w*=n.alpha*s.alpha)}}C([p()],qe.prototype,"enabled"),C([p()],qe.prototype,"attachRibbonToTransform"),C([p(Ia)],qe.prototype,"colorOverLifetime"),C([p(Ia)],qe.prototype,"colorOverTrail"),C([p()],qe.prototype,"dieWithParticles"),C([p()],qe.prototype,"inheritParticleColor"),C([p(Z)],qe.prototype,"lifetime"),C([p()],qe.prototype,"lifetimeMultiplier"),C([p()],qe.prototype,"minVertexDistance"),C([p()],qe.prototype,"mode"),C([p()],qe.prototype,"ratio"),C([p()],qe.prototype,"ribbonCount"),C([p()],qe.prototype,"shadowBias"),C([p()],qe.prototype,"sizeAffectsLifetime"),C([p()],qe.prototype,"sizeAffectsWidth"),C([p()],qe.prototype,"splitSubEmitterRibbons"),C([p()],qe.prototype,"textureMode"),C([p(Z)],qe.prototype,"widthOverTrail"),C([p()],qe.prototype,"widthOverTrailMultiplier"),C([p()],qe.prototype,"worldSpace");class tt{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new v;_temp2=new v;_temp3=new v;_hasOrbital=!1;_index=0;_orbitalMatrix=new J;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,s,r,a){if(!this.enabled)return;const l=r/a,c=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,h=this.x.evaluate(l),d=this.y.evaluate(l),u=this.z.evaluate(l);if(this._temp.set(-h,d,u),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const m=this._temp2.set(i.x,i.y,i.z),g=this.orbitalXMultiplier,y=this.orbitalYMultiplier,b=this.orbitalZMultiplier,f=c*Math.PI*2*10,_=Math.cos(f*g),w=Math.sin(f*g),S=Math.cos(f*y),O=Math.sin(f*y),L=Math.cos(f*b),D=Math.sin(f*b),W=m.x*(S*L)+m.y*(S*D)+m.z*-O,$=m.x*(w*O*L-_*D)+m.y*(w*O*D+_*L)+m.z*(w*S),H=m.x*(_*O*L+w*D)+m.y*(_*O*D-w*L)+m.z*(_*S),G=this._temp3.set(m.x-W,m.y-$,m.z-H);G.normalize(),G.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=G.x,n.y+=G.y,n.z+=G.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=c,n.y*=c,n.z*=c}}C([p()],tt.prototype,"enabled"),C([p()],tt.prototype,"space"),C([p(Z)],tt.prototype,"orbitalX"),C([p(Z)],tt.prototype,"orbitalY"),C([p(Z)],tt.prototype,"orbitalZ"),C([p()],tt.prototype,"orbitalXMultiplier"),C([p()],tt.prototype,"orbitalYMultiplier"),C([p()],tt.prototype,"orbitalZMultiplier"),C([p()],tt.prototype,"orbitalOffsetX"),C([p()],tt.prototype,"orbitalOffsetY"),C([p()],tt.prototype,"orbitalOffsetZ"),C([p(Z)],tt.prototype,"speedModifier"),C([p()],tt.prototype,"speedModifierMultiplier"),C([p(Z)],tt.prototype,"x"),C([p()],tt.prototype,"xMultiplier"),C([p(Z)],tt.prototype,"y"),C([p()],tt.prototype,"yMultiplier"),C([p(Z)],tt.prototype,"z"),C([p()],tt.prototype,"zMultiplier");class oi{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}C([p()],oi.prototype,"animation"),C([p()],oi.prototype,"enabled"),C([p()],oi.prototype,"cycleCount"),C([p(Z)],oi.prototype,"frameOverTime"),C([p()],oi.prototype,"frameOverTimeMultiplier"),C([p()],oi.prototype,"numTilesX"),C([p()],oi.prototype,"numTilesY"),C([p(Z)],oi.prototype,"startFrame"),C([p()],oi.prototype,"startFrameMultiplier"),C([p()],oi.prototype,"rowMode"),C([p()],oi.prototype,"rowIndex"),C([p()],oi.prototype,"spriteCount"),C([p()],oi.prototype,"timeMode");class Zn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}C([p()],Zn.prototype,"enabled"),C([p()],Zn.prototype,"separateAxes"),C([p(Z)],Zn.prototype,"x"),C([p()],Zn.prototype,"xMultiplier"),C([p(Z)],Zn.prototype,"y"),C([p()],Zn.prototype,"yMultiplier"),C([p(Z)],Zn.prototype,"z"),C([p()],Zn.prototype,"zMultiplier");class bn{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=j.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}C([p()],bn.prototype,"enabled"),C([p()],bn.prototype,"range"),C([p()],bn.prototype,"separateAxes"),C([p(Z)],bn.prototype,"x"),C([p()],bn.prototype,"xMultiplier"),C([p(Z)],bn.prototype,"y"),C([p()],bn.prototype,"yMultiplier"),C([p(Z)],bn.prototype,"z"),C([p()],bn.prototype,"zMultiplier");class Ct{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new v;_temp2=new v;apply(e,t,i,n,s,r,a){if(this.enabled){const l=this.limit.evaluate(s)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const c=this.dampen*.5;t.x=j.lerp(t.x,this._temp.x,c),t.y=j.lerp(t.y,this._temp.y,c),t.z=j.lerp(t.z,this._temp.z,c),i.x=j.lerp(i.x,this._temp.x,c),i.y=j.lerp(i.y,this._temp.y,c),i.z=j.lerp(i.z,this._temp.z,c)}}}}C([p()],Ct.prototype,"enabled"),C([p()],Ct.prototype,"dampen"),C([p(Z)],Ct.prototype,"drag"),C([p()],Ct.prototype,"dragMultiplier"),C([p(Z)],Ct.prototype,"limit"),C([p()],Ct.prototype,"limitMultiplier"),C([p()],Ct.prototype,"separateAxes"),C([p(Z)],Ct.prototype,"limitX"),C([p()],Ct.prototype,"limitXMultiplier"),C([p(Z)],Ct.prototype,"limitY"),C([p()],Ct.prototype,"limitYMultiplier"),C([p(Z)],Ct.prototype,"limitZ"),C([p()],Ct.prototype,"limitZMultiplier"),C([p()],Ct.prototype,"multiplyDragByParticleSize"),C([p()],Ct.prototype,"multiplyDragByParticleVelocity"),C([p()],Ct.prototype,"space");const Ed=class OO{enabled;curve;curveMultiplier;mode;clone(){const e=new OO;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new v),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new v),this.system._iv_velocity}_temp=new v;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};C([p()],Ed.prototype,"enabled"),C([p(Z)],Ed.prototype,"curve"),C([p()],Ed.prototype,"curveMultiplier"),C([p()],Ed.prototype,"mode");let T_=Ed;class Ii{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const s=e.length(),r=j.remap(s,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}C([p()],Ii.prototype,"enabled"),C([p(ee)],Ii.prototype,"range"),C([p()],Ii.prototype,"separateAxes"),C([p(Z)],Ii.prototype,"size"),C([p()],Ii.prototype,"sizeMultiplier"),C([p(Z)],Ii.prototype,"x"),C([p()],Ii.prototype,"xMultiplier"),C([p(Z)],Ii.prototype,"y"),C([p()],Ii.prototype,"yMultiplier"),C([p(Z)],Ii.prototype,"z"),C([p()],Ii.prototype,"zMultiplier");class wc{enabled;range;color;evaluate(e,t,i){const n=e.length(),s=j.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(s,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}C([p()],wc.prototype,"enabled"),C([p(ee)],wc.prototype,"range"),C([p(Ia)],wc.prototype,"color");class E_{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new $i(()=>new kf,s)}system;particleSystem;subSystem;subParticleSystem;type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new B;v_=new v;v2_=new v;_emitterMatrix=new kf;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===A_.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===A_.Death){let n=e.life;if(e[xc]!==void 0&&(n=e[xc]),!(e.age+t*1.2>=n))return;const s=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=s}const i=new kf;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var SF=Object.defineProperty,Xe=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&SF(e,t,n),n};const br=x("debugparticles"),CF=x("noprogressive"),PF=x("debugprogressive");var A_=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(A_||{});class _n extends T{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&M()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){br&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=Xo,t.map.premultiplyAlpha=!1);const i=new Ie;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=Xo,t.map.premultiplyAlpha=!1),e&&t.side===Us&&(t=t.clone(),t.side=wu,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!CF&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,PF&&console.log("Load material LOD",t.name),We.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof V&&(t=this.particleMesh.geometry),t===null)){t=new In(1,1);const i=t.attributes.uv;for(let n=0;n<i.count;n++)i.setX(n,1-i.getX(n))}return new V(t,this.getMaterial())}}Xe([p()],_n.prototype,"renderMode"),Xe([p(Oe)],_n.prototype,"particleMaterial"),Xe([p(Oe)],_n.prototype,"trailMaterial"),Xe([p()],_n.prototype,"maxParticleSize"),Xe([p()],_n.prototype,"minParticleSize"),Xe([p()],_n.prototype,"velocityScale"),Xe([p()],_n.prototype,"cameraVelocityScale"),Xe([p()],_n.prototype,"lengthScale");class mg{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class I_{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class kF extends I_{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class OF extends I_{_lastPosition=new v;_lastDistance=0;update(){const e=le(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return j.clamp(e,0,i/this.system.deltaTime)}}class MF extends I_{genValue(){return this.system.isPlaying,0}}class _r{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class RF extends _r{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,s=i.evaluate(n);s!==void 0&&(e.uvTile=s)}}}const bk=Symbol("particleRotation");class TF extends _r{type="NeedleRotation";initialize(e){e[bk]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[bk])*t:this.system.renderer.renderMode===vs.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const _k=Symbol("sizeLerpFactor"),EF=new v;class AF extends _r{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[_k]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[_k]).x);let s=1;this.system.renderer.renderMode!==vs.Mesh&&(s=this.system.worldScale.x/this.system.cameraScale);const r=U(e.startSize).multiplyScalar(n*s);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=Sk(this.system,EF);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const xc=Symbol("particleLife"),L_=Symbol("trailLifetime"),vk=Symbol("trailStartLength"),D_=Symbol("trailWidthRandom");class IF extends _r{type="NeedleTrail";initialize(e){e instanceof tw&&(e[xc]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[L_]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[L_]),e[vk]=e.length,e[D_]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof tw){const t=e,i=e.age/e[xc],n=e.previous.values(),s=e.previous.length;for(let r=0;r<s;r++){const a=n.next().value,l=1-r/(s-1),c=e.size;if(c.x<=0&&!this.system.trails.sizeAffectsWidth){const h=20*this.system.trails.widthOverTrail.evaluate(.5,t[D_]);c.x=h,c.y=h,c.z=h}a.size=this.system.trails.getWidth(c.x,i,l,t[D_]),a.color.copy(e.color),this.system.trails.getColor(a.color,i,l)}if(e.age>e[xc]){e.velocity.set(0,0,0);const r=(e.age-e[xc])/e[L_];t.length=j.lerp(e[vk],0,r)}}}}const gg=Symbol("startVelocity"),wk=Symbol("gravityModifier"),j_=Symbol("gravitySpeed"),fg=Symbol("velocity lerp factor"),F_=new v;class LF extends _r{type="NeedleVelocity";_gravityDirection=new v;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[gg]?e[gg].copy(e.velocity):e[gg]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[wk]=n*t,e[j_]=n*t*.5,e[fg]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Td.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[gg],n=e[wk];if(n!==0){const d=n*e[j_];F_.copy(this._gravityDirection).multiplyScalar(d),e[j_]+=t*.05,i.add(F_)}e.velocity.copy(i);const s=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,s,e[fg]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,s,e[fg],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[fg],e.color);const c=this.system.velocityOverLifetime;c.enabled&&c.apply(e,0,e.position,e.velocity,t,e.age,e.life);const h=this.system.limitVelocityOverLifetime;if(h.enabled&&h.apply(e.position,i,e.velocity,e.size,s,t,1),this.system.worldspace){const d=this.system.worldScale;e.velocity.x*=d.x,e.velocity.y*=d.y,e.velocity.z*=d.z}}}const xk=Symbol("colorLerpFactor"),B_=new he(1,1,1,1),Da=new he(1,1,1,1);class DF extends _r{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Da.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(B_.copy(t.color),B_.alpha=t.opacity??1,Da.multiply(B_)),Da.convertLinearToSRGB(),e.startColor.set(Da.r,Da.g,Da.b,Da.alpha),e.color.copy(e.startColor),e[xk]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[xk]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class jF{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new OF(this.system)}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new mg(this.system.main.startLifetime)}get startSpeed(){return new mg(this.system.main.startSpeed)}get startRotation(){return new mg(this.system.main.startRotation)}get startSize(){return new mg(this.system.main.startSize)}startLength;get startColor(){return new CR(new PR(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new MF(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return Jo.Trail;switch(this.system.renderer.renderMode){case vs.Billboard:return Jo.BillBoard;case vs.Stretch:return Jo.StretchedBillBoard;case vs.HorizontalBillboard:return Jo.HorizontalBillBoard;case vs.VerticalBillboard:return Jo.VerticalBillBoard;case vs.Mesh:return Jo.Mesh}return Jo.BillBoard}rendererEmitterSettings={startLength:new kR(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===vs.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=Xo,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=jy(new he(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new kF(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??$M}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Td.World}}class FF{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const si=class Hg extends T{play(e=!1){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Hg&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Hg&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&P.foreachComponent(this.gameObject,i=>{i instanceof Hg&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new FF),this._state.waitEmiting=e,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===Td.World}get localspace(){return this.main.simulationSpace===Td.Local}__worldQuaternion=new B;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new B;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new v;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new v;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,le(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof _r&&(e.system=this),br&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(e);return i!==-1&&((M()||br)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),t.splice(i,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof ug)){const n=new ug;bl(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof yg)){const n=new yg;bl(n,i),e[t]=n}}br&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(_n),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new R,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new xR,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new jF(this),this._particleSystem=new SR(this._interface),this._particleSystem.addBehavior(new AF(this)),this._particleSystem.addBehavior(new DF(this)),this._particleSystem.addBehavior(new RF(this)),this._particleSystem.addBehavior(new TF(this)),this._particleSystem.addBehavior(new LF(this)),this._particleSystem.addBehavior(new IF(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),br&&(console.log(this),this.gameObject.add(new Ui(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof V&&this._interface.renderMode==Jo.Mesh&&We.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==Jo.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,i=this.main.startLifetime.getMax(),n=Math.min(Math.max(t,i)/Math.max(.01,this.main.simulationSpeed),1e3),s=Math.ceil(n/e),r=Date.now();br&&console.log(`Particles ${this.name} - Prewarm for ${s} frames (${n} sec). Duration: ${t}, Lifetime: ${i}`);for(let a=0;a<s&&!(this.currentParticles>=this.maxParticles);a++){const l=Date.now()-r;if(l>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${l}`);break}this.onUpdate(),this.onSimulate(e)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=Je(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(Re(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Je(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=Sk(this,F_);this._container.matrix.makeScale(n.x,n.y,n.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():M()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new E_(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else br&&console.warn("Could not add SubParticleSystem",e,this)}}};Xe([p(pg)],si.prototype,"colorOverLifetime"),Xe([p(ni)],si.prototype,"main"),Xe([p(xs)],si.prototype,"emission"),Xe([p(La)],si.prototype,"sizeOverLifetime"),Xe([p(R_)],si.prototype,"shape"),Xe([p(Ce)],si.prototype,"noise"),Xe([p(qe)],si.prototype,"trails"),Xe([p(tt)],si.prototype,"velocityOverLifetime"),Xe([p(Ct)],si.prototype,"limitVelocityOverLifetime"),Xe([p(T_)],si.prototype,"inheritVelocity"),Xe([p(wc)],si.prototype,"colorBySpeed"),Xe([p(oi)],si.prototype,"textureSheetAnimation"),Xe([p(Zn)],si.prototype,"rotationOverLifetime"),Xe([p(bn)],si.prototype,"rotationBySpeed"),Xe([p(Ii)],si.prototype,"sizeBySpeed");let Ad=si;class yg{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof Ad)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=P.findByGuid(n,t)),br&&!(this.particleSystem instanceof Ad)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function Sk(o,e){if(e.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case M_.Local:e=Je(o.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+M_[o.main.scalingMode]+" is not supported";M()&&ge(t),console.warn(t,o.name,o)}e=Je(o.gameObject,e);break}return e}var BF=Object.defineProperty,U_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&BF(e,t,n),n};class Sc extends T{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),s=n.length();if(s>this.radius)return;let r=t;s>1?r/=s*s:r/=Math.max(.05,s),i.applyImpulse(n.multiplyScalar(r))})}}U_([p()],Sc.prototype,"strength"),U_([p()],Sc.prototype,"radius"),U_([p(rt)],Sc.prototype,"targets");class $c extends T{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(se.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(se.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Ry(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=P.getComponentInParent(this.gameObject,Ti);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=P.getComponentInParent(this.gameObject,wt);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=$c.hashCode(e),i=$c.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const s=n;s.material&&s.material.color&&this.assignColor(i,e,s)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new oe(t/255,i/255,n/255)}}var UF=Object.defineProperty,zF=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&UF(e,t,n),n};const z_=x("debugpost");class gt extends T{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof N?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;onEnable(){super.onEnable(),z_&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.active=!0,this.context.postprocessing.addEffect(this)}onDisable(){super.onDisable(),z_&&console.warn("Disable",this.constructor.name),this.context.postprocessing.removeEffect(this),this.active=!1}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){z_&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof N&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof N){const i=e.value;return this[t].value=i,!0}}}zF([p()],gt.prototype,"active");var NF=Object.defineProperty,$F=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&NF(e,t,n),n};const WF=x("debugpost"),N_={};function vn(o,e){N_[o]=e}function VF(o){return o.__type in N_?N_[o.__type]:(WF&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),gt)}class bg{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}$F([it([o=>VF(o),gt])],bg.prototype,"components");var GF=Object.defineProperty,HF=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&GF(e,t,n),n};const qF=x("debugpost");var Ck=(o=>(o[o.LOW=0]="LOW",o[o.MEDIUM=1]="MEDIUM",o[o.HIGH=2]="HIGH",o[o.ULTRA=3]="ULTRA",o))(Ck||{});class Id extends gt{get typeName(){return"Antialiasing"}preset=new N(2);onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??A.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:A.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{qF&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}HF([p(N)],Id.prototype,"preset"),vn("Antialiasing",Id);var XF=Object.defineProperty,$_=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&XF(e,t,n),n};const _g=class MO extends gt{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new N(.9);intensity=new N(1);scatter=new N(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=MO.useSelectiveBloom),this.selectiveBloom){const t=e=new A.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new A.POSTPROCESSING.MODULE.BloomEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=Ko.lerp(.1,.9,t))},e}};$_([p(N)],_g.prototype,"threshold"),$_([p(N)],_g.prototype,"intensity"),$_([p(N)],_g.prototype,"scatter");let vg=_g;vn("Bloom",vg);var QF=Object.defineProperty,YF=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&QF(e,t,n),n};class Ld extends gt{get typeName(){return"ChromaticAberration"}intensity=new N(0);onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new ee(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}YF([p(N)],Ld.prototype,"intensity"),vn("ChromaticAberration",Ld);var Cc=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(Cc||{});const Pk=new Map;function W_(o){switch(o){case 0:return bf;case 1:return yf;case 2:return yu;case 3:return fu;case 4:return sl;default:return Pk.has(o)||(Pk.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),sl}}function KF(o){switch(o){case bf:return 0;case yu:return 2;case fu:return 3;case sl:return 1;case yf:return 1;default:return 0}}function wg(o){switch(o){case bf:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case yu:return A.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case fu:return A.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case sl:return A.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case yf:return A.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var ZF=Object.defineProperty,kk=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&ZF(e,t,n),n};const V_=x("debugpost");class ja extends gt{get typeName(){return"ToneMapping"}mode=new N(void 0);exposure=new N(1);setMode(e){const t=Cc[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}get threeToneMapping(){return this.mode.isInitialized&&this.mode.overrideState?W_(this.mode.value):this.context.renderer.toneMapping}get toneMappingExposure(){return this.exposure.overrideState&&this.exposure.value!==void 0?Math.max(0,this.exposure.value):this.context.renderer.toneMappingExposure}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=KF(this.context.renderer.toneMapping);V_&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=W_(this.mode.value),t=this._tonemappingEffect=new A.POSTPROCESSING.MODULE.ToneMappingEffect({mode:wg(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=w1(i),t.mode=wg(i);else{const n=W_(i);t.mode=wg(n)}t.name="ToneMapping ("+Cc[i]+")",V_&&console.log("[PostProcessing] ToneMapping mode changed to",Cc[i],e,t.mode)},V_&&console.log("[PostProcessing] Use ToneMapping",Cc[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}}kk([p(N)],ja.prototype,"mode"),kk([p(N)],ja.prototype,"exposure"),vn("Tonemapping",ja);var JF=Object.defineProperty,xg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&JF(e,t,n),n};class vr extends gt{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new N(1);contrast=new N(0);hueShift=new N(0);saturation=new N(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[],t=this.postprocessingContext?.components.find(r=>r instanceof ja);let i=!1;this.postExposure.onValueChanged=r=>{if(this.postExposure.overrideState){if(!t){i||(i=!0,console.warn("[PostProcessing] ColorAdjustments.PostExposure has no effect: add a ToneMappingEffect to your postprocessing stack."));return}t.exposure.value=r}};const n=new A.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=r=>n.contrast=r;const s=new A.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=r=>s.hue=r,this.saturation.onValueChanged=r=>s.saturation=r,e.push(n),e.push(s),e}}xg([p(N)],vr.prototype,"postExposure"),xg([p(N)],vr.prototype,"contrast"),xg([p(N)],vr.prototype,"hueShift"),xg([p(N)],vr.prototype,"saturation"),vn("ColorAdjustments",vr);var eB=Object.defineProperty,Fa=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&eB(e,t,n),n},Ok=(o=>(o[o.Off=0]="Off",o[o.Gaussian=1]="Gaussian",o[o.Bokeh=2]="Bokeh",o))(Ok||{});const tB=x("debugpost");class Jn extends gt{get typeName(){return"DepthOfField"}mode;focusDistance=new N(1);focalLength=new N(.2);aperture=new N(20);gaussianMaxRadius=new N;resolutionScale=new N(1/window.devicePixelRatio);bokehScale=new N;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return j.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return j.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){tB&&console.warn("DepthOfField: Mode is set to Off");return}const e=new A.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:this.focalLength.value,focalLength:1,bokehScale:this.aperture.value,resolutionScale:this.resolutionScale.value});return e.cocMaterial.worldFocusDistance=this.focusDistance.value,this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}Fa([p()],Jn.prototype,"mode"),Fa([p(N)],Jn.prototype,"focusDistance"),Fa([p(N)],Jn.prototype,"focalLength"),Fa([p(N)],Jn.prototype,"aperture"),Fa([p(N)],Jn.prototype,"gaussianMaxRadius"),Fa([p(N)],Jn.prototype,"resolutionScale"),Fa([p(N)],Jn.prototype,"bokehScale"),vn("DepthOfField",Jn);class Dd extends gt{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var iB=Object.defineProperty,nB=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&iB(e,t,n),n};const Mk=x("debugpost");class jd extends gt{get typeName(){return"PixelationEffect"}granularity=new N(10);_effect=null;_lastDpr=0;onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.PixelationEffect;this._effect=e;const t=this.context.renderer.getPixelRatio();return this._lastDpr=t,e.granularity=this.granularity.value*t,this.granularity.onValueChanged=i=>{const n=this.context.renderer.getPixelRatio();e.granularity=i*n,Mk&&console.debug(`[PixelationEffect] granularity changed: raw=${i}, dpr=${n}, effective=${e.granularity}`)},e}update(){if(!this._effect)return;const e=this.context.renderer.getPixelRatio();e!==this._lastDpr&&(this._lastDpr=e,this._effect.granularity=this.granularity.value*e,Mk&&console.debug(`[PixelationEffect] DPR changed to ${e}, updating granularity: raw=${this.granularity.value}, effective=${this._effect.granularity}`))}}nB([p(N)],jd.prototype,"granularity"),vn("PixelationEffect",jd);var oB=Object.defineProperty,Fd=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&oB(e,t,n),n};class Ss extends gt{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new N(2);falloff=new N(1);samples=new N(9);color=new N(new oe(0,0,0));luminanceInfluence=new N(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof me){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new A.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new A.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new A.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new oe),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const s=new Array;return s.push(t),s.push(i),s.push(n),s}}Fd([p(N)],Ss.prototype,"intensity"),Fd([p(N)],Ss.prototype,"falloff"),Fd([p(N)],Ss.prototype,"samples"),Fd([p(N)],Ss.prototype,"color"),Fd([p(N)],Ss.prototype,"luminanceInfluence"),vn("ScreenSpaceAmbientOcclusion",Ss);var sB=Object.defineProperty,Ba=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&sB(e,t,n),n};const rB=x("debugN8AO");var Sg=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(Sg||{});class eo extends gt{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new N(1);falloff=new N(1);intensity=new N(1);color=new N(new oe(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(Sg[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new A.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const s=Sg[this.quality];if(n.setQualityMode(s),n.configuration.transparencyAware=!1,n.configuration.halfRes=window.devicePixelRatio>1,n.effectCompositerQuad?.material){const a=n.effectCompositerQuad.material;a.fragmentShader=a.fragmentShader.replace(`if (depth == 1.0) {
1408
1408
  texel = vec4(0.0, 0.0, 0.0, 1.0);`,`if (depth == 1.0) {
1409
1409
  gl_FragColor = sceneTexel;
1410
1410
  return;`),a.needsUpdate=!0}const r=new ro(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,rB&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=a=>{n.configuration.intensity=a},this.falloff.onValueChanged=a=>{n.configuration.distanceFalloff=a},this.aoRadius.onValueChanged=a=>{n.configuration.aoRadius=a},this.color.onValueChanged=a=>{n.color||(n.color=new oe),n.configuration.color.copy(a)},n}}Ba([Ve(),p()],eo.prototype,"gammaCorrection"),Ba([p(N)],eo.prototype,"aoRadius"),Ba([p(N)],eo.prototype,"falloff"),Ba([p(N)],eo.prototype,"intensity"),Ba([p(N)],eo.prototype,"color"),Ba([Ve(),p()],eo.prototype,"screenspaceRadius"),Ba([Ve(),p()],eo.prototype,"quality"),vn("ScreenSpaceAmbientOcclusionN8",eo);const Cg=x("debugpost"),Pt={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let ft=null;function aB(o){if(Cg==="verbose"&&console.debug("Before ordering effects",[...o]),!ft){ft=new Map,ft.set(A.POSTPROCESSING.MODULE.NormalPass,Pt.NormalPass),ft.set(A.POSTPROCESSING.MODULE.DepthDownsamplingPass,Pt.DepthDownsamplingPass),ft.set(A.POSTPROCESSING.MODULE.SMAAEffect,Pt.SMAA),ft.set(A.POSTPROCESSING.MODULE.SSAOEffect,Pt.SSAO);const e=A.POSTPROCESSING_AO.MAYBEMODULE;e&&(ft.set(e.N8AOPostPass,Pt.SSAO),ft.set(e.N8AOPass,Pt.SSAO)),ft.set(A.POSTPROCESSING.MODULE.TiltShiftEffect,Pt.TiltShift),ft.set(A.POSTPROCESSING.MODULE.DepthOfFieldEffect,Pt.DepthOfField),ft.set(A.POSTPROCESSING.MODULE.ChromaticAberrationEffect,Pt.ChromaticAberration),ft.set(A.POSTPROCESSING.MODULE.BloomEffect,Pt.Bloom),ft.set(A.POSTPROCESSING.MODULE.SelectiveBloomEffect,Pt.Bloom),ft.set(A.POSTPROCESSING.MODULE.VignetteEffect,Pt.Vignette),ft.set(A.POSTPROCESSING.MODULE.PixelationEffect,Pt.Pixelation),ft.set(A.POSTPROCESSING.MODULE.ToneMappingEffect,Pt.ToneMapping),ft.set(A.POSTPROCESSING.MODULE.HueSaturationEffect,Pt.HueSaturation),ft.set(A.POSTPROCESSING.MODULE.BrightnessContrastEffect,Pt.BrightnessContrast)}o.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:ft.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:ft.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Cg&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Cg&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Cg==="verbose"&&console.debug("After ordering effects",[...o])}var lB=Object.defineProperty,cB=Object.getOwnPropertyDescriptor,Rk=(o,e,t,i)=>{for(var n=cB(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&lB(e,t,n),n};class Bd extends gt{get typeName(){return"Sharpening"}order=Pt.Sharpening;_effect;onCreateEffect(){return this._effect??=new(hB()),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}_amount=1;set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}_radius=1}Rk([p()],Bd.prototype,"amount"),Rk([p()],Bd.prototype,"radius");function hB(){const o=`
@@ -1455,7 +1455,7 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
1455
1455
  Audio:`,s.getAudioTracks(),`
1456
1456
  Video:`,s.getVideoTracks()),this._stream=s,i==="incoming"){const r=new Ek(e,s,this);this.dispatchEvent(r)}}),t.on("close",()=>{this.dispatchEvent(new H_(e,i))})}}function Ik(o){return o=o.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),o}const kg=class qg extends _f{static getOrCreate(e,t){let i=qg.instances.get(e);i||(i=new Map,qg.instances.set(e,i));let n=i.get(t);return n||(n=new qg(e,t),i.set(t,n)),n}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(this._disposed)return;if(!t?.id){Qe?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const i={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:s=>Ik(s)},n=this._peer?.call(e,t,i);if(n){const s=this.registerCall(n,"outgoing",t);return Qe&&console.warn(`\u{1F4DE} CALL ${e}`,`
1457
1457
  Outgoing:`,this._outgoingCalls,`
1458
- Incoming:`,this._incomingCalls),s}else Qe&&console.error("Failed to make call",e,t,this._peer)}closeAll(){for(const e of[...this._incomingCalls,...this._outgoingCalls])e.close();this.updateCalls()}updateCalls=()=>{for(let e=this._incomingCalls.length-1;e>=0;e--){const t=this._incomingCalls[e];t.isClosed&&!t.isOpening&&this._incomingCalls.splice(e,1)}for(let e=this._outgoingCalls.length-1;e>=0;e--){const t=this._outgoingCalls[e];let i=!1;t.isClosed&&!t.isOpening&&(t.stream?.active?Qe&&console.warn("!!! Stream is still active, don't remove call",t.userId,"Your id: "+this.context.connection.connectionId):(Qe&&console.warn("!!! Remove closed call",t.userId),i=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(Qe&&console.warn("!!! User is not in room anymore, remove call",t.userId),i=!0),i&&(t.close(),this._outgoingCalls.splice(e,1))}};get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}id;context;_incomingCalls=[];_outgoingCalls=[];_peer;constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer();const i=Object.getOwnPropertyDescriptor(navigator,"getUserMedia")?.writable;try{i?navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia:Qe&&console.warn("[PeerJs] getUserMedia is not writable")}catch(n){Qe&&console.error("[PeerJs] Error setting getUserMedia",n)}}_disposed=!1;_callIntervals=new Set;dispose(){if(!this._disposed){this._disposed=!0,this.disable(),this.unsubscribePeerEvents();for(const e of this._callIntervals)clearInterval(e);this._callIntervals.clear(),this.closeAll(),this._incomingCalls.length=0,this._outgoingCalls.length=0,this._peer?.destroy(),this._peer=void 0}}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);enable(){this._disposed||this._enabled||(this._enabled=!0,this.context.connection.beginListen(se.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(se.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}async setupPeer(){if(!(this._disposed||!this.context.connection.connectionId)&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();if(e){const t=await t1(e);if(this._disposed){t.destroy();return}this._peer=t}else 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(Qe&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new gB(this,e))};onPeerClose=()=>{Qe&&console.log("PEER closed"),this.updateCalls()};onPeerDisconnected=()=>{Qe&&console.log("PEER disconnected"),this.updateCalls()};onPeerError=e=>{Qe&&console.error("PEER error",e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:t=>Ik(t)}),this.registerCall(e,"incoming",null)};registerCall(e,t,i){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const s=n.userId;t==="incoming"&&Qe?console.warn("\u2190 Receive call from",e.metadata,e.connectionId):Qe&&console.warn("\u2192 Make call to",e.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,a=new fB(s,e,t,i);return r.push(a),e.on("error",l=>{console.error("Call error",l)}),e.on("close",()=>{Qe&&console.log("Call ended",e.metadata);const l=r.indexOf(a);l!==-1&&r.splice(l,1),a.close(),this.dispatchEvent(new H_(s,t))}),a.addEventListener("call-ended",l=>{this.dispatchEvent(l)}),t==="incoming"&&(a.addEventListener("receive-stream",l=>{this.dispatchEvent(l)}),e.on("stream",()=>{if(this._disposed)return;Qe&&console.log("Received stream for call",e.metadata);let l=0;const c=setInterval(()=>{const h=l===0;!a.isOpen&&h&&(Qe&&console.warn("Close call because stream is not active",e.metadata),l+=1,clearInterval(c),this._callIntervals.delete(c),a.close())},2e3);this._callIntervals.add(c),e.on("close",()=>{clearInterval(c),this._callIntervals.delete(c)})})),a}};LO(kg,"instances",new WeakMap),ce.registerCallback(de.ContextDestroying,({context:o})=>{const e=kg.instances.get(o);if(e){kg.instances.delete(o);for(const t of e.values())t.dispose();e.clear()}});let Og=kg;class du extends _f{static create(e,t){const i=Og.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new du(e.context,i)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),Gu(e)){const i=e;e=i.context,t=Og.getOrCreate(i.context,i.guid)}else typeof t=="string"&&(t=Og.getOrCreate(e,t));if(e){if(!(e instanceof Q))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!t)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=t,Qe&&(this.debug=!0)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){for(const i of t)i.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}_enabled=!1;get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(se.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(se.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}_tickIntervalId;tick=()=>{this.updateSendingCalls()};onJoinedRoom=e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e?.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())};onLeftRoom=e=>{this.debug&&console.warn(`${e?.userId||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()};onCallStreamReceived=e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()};onCallEnded=e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()};onUserConnected=e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const t=this._sendingStreams.keys().next().value;if(!t)return;this.peer.makeCall(e.peerId,t)}else Qe&&console.log("Unknown user connected",e.guid,e.peerId)};onUserLeft=e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()};updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t)||[];for(const n of this.context.connection.usersInRoom()){if(n===e)continue;const s=this.peer.getPeerIdFromUserId(n);if(i.find(r=>r.peerId===s&&r.direction==="outgoing"&&!r.isClosed&&r.stream?.active))Qe&&console.debug("Already have a call with user "+n+" / peer "+s);else{const r=this.peer.makeCall(s,t);r&&i.push(r)}}this._sendingStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const n=t[i];this.context.connection.userIsInRoom(n.userId)?Qe&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${i}] ${n.userId}`):console.log(`User is still in room [${i}] ${n.userId}`)):(Qe&&console.log(`Remove call ${[i]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(i,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function wn(o){if(o&&o instanceof MediaStream)for(const e of o.getTracks())e.stop()}function yB(){return new Promise((o,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),o())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function bB(o){await yB(),o()}var _B=Object.defineProperty,vB=Object.getOwnPropertyDescriptor,nn=(o,e,t,i)=>{for(var n=i>1?void 0:i?vB(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&_B(e,t,n),n};const yt=x("debugvideo");var Lk=(o=>(o[o.None=0]="None",o[o.AdjustHeight=1]="AdjustHeight",o[o.AdjustWidth=2]="AdjustWidth",o))(Lk||{}),Dk=(o=>(o[o.VideoClip=0]="VideoClip",o[o.Url=1]="Url",o))(Dk||{}),jk=(o=>(o[o.CameraFarPlane=0]="CameraFarPlane",o[o.CameraNearPlane=1]="CameraNearPlane",o[o.RenderTexture=2]="RenderTexture",o[o.MaterialOverride=3]="MaterialOverride",o))(jk||{});class kt extends T{playOnAwake=!0;aspectMode=0;clip=null;source=1;get url(){return this._url}set url(e){const t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??""):this._url=e}_url=null;renderMode=3;targetMaterialProperty;targetMaterialRenderer;targetTexture;time=0;_playbackSpeed=1;get playbackSpeed(){return this._videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this._videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){return this._videoElement?.currentTime??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!e||e.paused||e.ended?!1:e.srcObject?e.srcObject.active:e.currentTime>0&&e.readyState>e.HAVE_CURRENT_DATA}get crossOrigin(){return this._videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){return this._videoElement?.muted??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}_muted=!1;get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&M()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}_audioOutputMode=2;playInBackground=!0;_crossOrigin="anonymous";_videoElement=null;_videoTexture=null;_videoMaterial=null;_isPlaying=!1;wasPlaying=!1;preloadVideo(){yt&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,yt&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){yt&&console.log("VideoPlayer.onEnable",Dk[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?this._overlay?.start():this._overlay?.stop()}onDisable(){window.removeEventListener("visibilitychange",this.visibilityChanged),this._overlay?.stop(),this.pause()}visibilityChanged=e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}};onDestroy(){this._videoElement&&(this.videoElement?.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}_receivedInput=!1;constructor(){super(),bB(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],x("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}_playErrors=0;async play(e){if(e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(M()&&console.warn("[VideoPlayer] Called play with unknown argument type. Using assigned source instead.",e),e=void 0),typeof e=="string"?this.setClipURL(e):e instanceof MediaStream&&this.setVideo(e),this._videoElement||this.create(!1),!this._videoElement)return yt&&console.warn("Can not play: no video element found",this),!1;if(this._isPlaying&&!this._videoElement?.ended&&!this._videoElement?.paused)return!0;if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U)return this.ensureM3UCanBePlayed(),!0;yt&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time;try{return await this._videoElement.play(),yt&&console.log("play",this._videoElement,this.time),!0}catch(t){return this._playErrors++<10?console.error(t):this._playErrors===10&&console.error("Multiple errors playing video, further errors will be suppressed. Use 'debugvideo' param to see all errors."),yt&&console.error("Error playing video",t,"CODE="+t.code,this.videoElement?.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3),!1}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),yt&&console.log("STOP",this))}pause(){this.time=this._videoElement?.currentTime??0,this._isPlaying=!1,this._videoElement?.pause(),yt&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!t?.length&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(yt&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(yt&&console.log("Set Video src",t),this._videoElement.src=t):(yt&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new WM(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=Yo,e&&this.handleBeginPlaying(e),yt&&console.log("Video: handle playing done...",t,e),!0):(yt&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new wB(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),yt&&console.log("created video element",e),e}handleBeginPlaying(e){if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=P.getComponent(this.gameObject,gi)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,jk[this.renderMode],this);return}const i=t.material;if(i){this._targetObjects.push(t),i!==this._videoMaterial&&(this._videoMaterial=i.clone(),t.material=this._videoMaterial);const n="map",s=this._videoMaterial;if(!this.targetMaterialProperty)yt&&s[n]===void 0&&console.warn(`The target material does not have a '${n}' property, video might not render correctly.`),s[n]=this._videoTexture;else switch(this.targetMaterialProperty){default:yt&&s[this.targetMaterialProperty]===void 0&&console.warn(`The target material does not have a '${this.targetMaterialProperty}' property, video might not render correctly.`),s[n]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let n;for(const s of i.getVideoTracks()){const r=s.getSettings();if(r&&r.width&&r.height){n=r.width/r.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let s=0;s<10;s++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(const s of this._targetObjects){let r=1;if(s.parent){const a=Je(s.parent);r=a.x/a.y}switch(this.aspectMode){case 1:s.scale.y=1/n*s.scale.x*r;break;case 2:s.scale.x=n*s.scale.y*r;break}}for(let s=0;s<3;s++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(yt&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}_hls;onHlsAvailable=()=>{yt&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),this._videoElement?.play(),yt&&console.log("HLS: loaded",this.clip))}}nn([p()],kt.prototype,"playOnAwake",2),nn([p()],kt.prototype,"aspectMode",2),nn([p(URL)],kt.prototype,"clip",2),nn([p()],kt.prototype,"source",2),nn([p(URL)],kt.prototype,"url",1),nn([p()],kt.prototype,"renderMode",2),nn([p()],kt.prototype,"targetMaterialProperty",2),nn([p(gi)],kt.prototype,"targetMaterialRenderer",2),nn([p(Pe)],kt.prototype,"targetTexture",2),nn([p()],kt.prototype,"time",2),nn([p()],kt.prototype,"playbackSpeed",1),nn([p()],kt.prototype,"isLooping",1),nn([p()],kt.prototype,"audioOutputMode",1);class wB{context;constructor(e){this.context=e,this._input=new xB(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;const e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Gs.createPrimitive(_l.Quad,{material:new SB(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();const i=t.material;i?.reset(),this._input?.enable(i)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){const e=this._screenspaceModeQuad?.material;e&&(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input}class xB{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const t=new ee;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const s=new ee(n.movementX,n.movementY);s.x/=this.context.domElement.clientWidth,s.y/=this.context.domElement.clientHeight,t.set(s.x,s.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const s=n.touches[0],r=n.touches[1],a=s.clientX-r.clientX,l=s.clientY-r.clientY,c=Math.sqrt(a*a+l*l);if(this._lastPinch!==0){const h=c-this._lastPinch;this._material.zoom-=h*.004}this._lastPinch=c}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class SB extends oo{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){const t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new ee;get offset(){const e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){const t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new ve(0,0,1,1)}},this.vertexShader=`
1458
+ Incoming:`,this._incomingCalls),s}else Qe&&console.error("Failed to make call",e,t,this._peer)}closeAll(){for(const e of[...this._incomingCalls,...this._outgoingCalls])e.close();this.updateCalls()}updateCalls=()=>{for(let e=this._incomingCalls.length-1;e>=0;e--){const t=this._incomingCalls[e];t.isClosed&&!t.isOpening&&this._incomingCalls.splice(e,1)}for(let e=this._outgoingCalls.length-1;e>=0;e--){const t=this._outgoingCalls[e];let i=!1;t.isClosed&&!t.isOpening&&(t.stream?.active?Qe&&console.warn("!!! Stream is still active, don't remove call",t.userId,"Your id: "+this.context.connection.connectionId):(Qe&&console.warn("!!! Remove closed call",t.userId),i=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(Qe&&console.warn("!!! User is not in room anymore, remove call",t.userId),i=!0),i&&(t.close(),this._outgoingCalls.splice(e,1))}};get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}id;context;_incomingCalls=[];_outgoingCalls=[];_peer;constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer();const i=Object.getOwnPropertyDescriptor(navigator,"getUserMedia")?.writable;try{i?navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia:Qe&&console.warn("[PeerJs] getUserMedia is not writable")}catch(n){Qe&&console.error("[PeerJs] Error setting getUserMedia",n)}}_disposed=!1;_callIntervals=new Set;dispose(){if(!this._disposed){this._disposed=!0,this.disable(),this.unsubscribePeerEvents();for(const e of this._callIntervals)clearInterval(e);this._callIntervals.clear(),this.closeAll(),this._incomingCalls.length=0,this._outgoingCalls.length=0,this._peer?.destroy(),this._peer=void 0}}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);enable(){this._disposed||this._enabled||(this._enabled=!0,this.context.connection.beginListen(se.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(se.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}async setupPeer(){if(!(this._disposed||!this.context.connection.connectionId)&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();if(e){const t=await t1(e);if(this._disposed){t.destroy();return}this._peer=t}else 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(Qe&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new gB(this,e))};onPeerClose=()=>{Qe&&console.log("PEER closed"),this.updateCalls()};onPeerDisconnected=()=>{Qe&&console.log("PEER disconnected"),this.updateCalls()};onPeerError=e=>{Qe&&console.error("PEER error",e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:t=>Ik(t)}),this.registerCall(e,"incoming",null)};registerCall(e,t,i){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const s=n.userId;t==="incoming"&&Qe?console.warn("\u2190 Receive call from",e.metadata,e.connectionId):Qe&&console.warn("\u2192 Make call to",e.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,a=new fB(s,e,t,i);return r.push(a),e.on("error",l=>{console.error("Call error",l)}),e.on("close",()=>{Qe&&console.log("Call ended",e.metadata);const l=r.indexOf(a);l!==-1&&r.splice(l,1),a.close(),this.dispatchEvent(new H_(s,t))}),a.addEventListener("call-ended",l=>{this.dispatchEvent(l)}),t==="incoming"&&(a.addEventListener("receive-stream",l=>{this.dispatchEvent(l)}),e.on("stream",()=>{if(this._disposed)return;Qe&&console.log("Received stream for call",e.metadata);let l=0;const c=setInterval(()=>{const h=l===0;!a.isOpen&&h&&(Qe&&console.warn("Close call because stream is not active",e.metadata),l+=1,clearInterval(c),this._callIntervals.delete(c),a.close())},2e3);this._callIntervals.add(c),e.on("close",()=>{clearInterval(c),this._callIntervals.delete(c)})})),a}};LO(kg,"instances",new WeakMap),ce.registerCallback(de.ContextDestroying,({context:o})=>{const e=kg.instances.get(o);if(e){kg.instances.delete(o);for(const t of e.values())t.dispose();e.clear()}});let Og=kg;class du extends _f{static create(e,t){const i=Og.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new du(e.context,i)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),Gu(e)){const i=e;e=i.context,t=Og.getOrCreate(i.context,i.guid)}else typeof t=="string"&&(t=Og.getOrCreate(e,t));if(e){if(!(e instanceof Q))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!t)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=t,Qe&&(this.debug=!0)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){for(const i of t)i.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}_enabled=!1;get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(se.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(se.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}_tickIntervalId;tick=()=>{this.updateSendingCalls()};onJoinedRoom=e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e?.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())};onLeftRoom=e=>{this.debug&&console.warn(`${e?.userId||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()};onCallStreamReceived=e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()};onCallEnded=e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()};onUserConnected=e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const t=this._sendingStreams.keys().next().value;if(!t)return;this.peer.makeCall(e.peerId,t)}else Qe&&console.log("Unknown user connected",e.guid,e.peerId)};onUserLeft=e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()};updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t)||[];for(const n of this.context.connection.usersInRoom()){if(n===e)continue;const s=this.peer.getPeerIdFromUserId(n);if(i.find(r=>r.peerId===s&&r.direction==="outgoing"&&!r.isClosed&&r.stream?.active))Qe&&console.debug("Already have a call with user "+n+" / peer "+s);else{const r=this.peer.makeCall(s,t);r&&i.push(r)}}this._sendingStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const n=t[i];this.context.connection.userIsInRoom(n.userId)?Qe&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${i}] ${n.userId}`):console.log(`User is still in room [${i}] ${n.userId}`)):(Qe&&console.log(`Remove call ${[i]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(i,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function wn(o){if(o&&o instanceof MediaStream)for(const e of o.getTracks())e.stop()}function yB(){return new Promise((o,e)=>{const t=()=>{t!=null&&(document.removeEventListener("pointerdown",t),document.removeEventListener("click",t),document.removeEventListener("dragstart",t),document.removeEventListener("touchstart",t),o())};document.addEventListener("pointerdown",t),document.addEventListener("click",t),document.addEventListener("dragstart",t),document.addEventListener("touchstart",t)})}async function bB(o){await yB(),o()}var _B=Object.defineProperty,vB=Object.getOwnPropertyDescriptor,nn=(o,e,t,i)=>{for(var n=i>1?void 0:i?vB(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&_B(e,t,n),n};const yt=x("debugvideo");var Lk=(o=>(o[o.None=0]="None",o[o.AdjustHeight=1]="AdjustHeight",o[o.AdjustWidth=2]="AdjustWidth",o))(Lk||{}),Dk=(o=>(o[o.VideoClip=0]="VideoClip",o[o.Url=1]="Url",o))(Dk||{}),jk=(o=>(o[o.CameraFarPlane=0]="CameraFarPlane",o[o.CameraNearPlane=1]="CameraNearPlane",o[o.RenderTexture=2]="RenderTexture",o[o.MaterialOverride=3]="MaterialOverride",o))(jk||{});class kt extends T{playOnAwake=!0;aspectMode=0;clip=null;source=1;get url(){return this._url}set url(e){const t=this._url!==e;this.__didAwake?t&&this.setClipURL(e??""):this._url=e}_url=null;renderMode=3;targetMaterialProperty;targetMaterialRenderer;targetTexture;time=0;_playbackSpeed=1;get playbackSpeed(){return this._videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this._videoElement&&(this._videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this._videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this._videoElement&&(this._videoElement.loop=e)}get currentTime(){return this._videoElement?.currentTime??this.time}set currentTime(e){this._videoElement?this._videoElement.currentTime=e:this.time=e}get isPlaying(){const e=this._videoElement;return!e||e.paused||e.ended?!1:e.srcObject?e.srcObject.active:e.currentTime>0&&e.readyState>e.HAVE_CURRENT_DATA}get crossOrigin(){return this._videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this._videoElement&&(e!==null?this._videoElement.setAttribute("crossorigin",e):this._videoElement.removeAttribute("crossorigin"))}get videoMaterial(){return!this._videoMaterial&&!this.create(!1)?null:this._videoMaterial}get videoTexture(){return!this._videoTexture&&!this.create(!1)?null:this._videoTexture}get videoElement(){return!this._videoElement&&!this.create(!1)?null:this._videoElement}requestPictureInPicture(){return this._videoElement?this._videoElement.requestPictureInPicture():null}get muted(){return this._videoElement?.muted??this._muted}set muted(e){this._muted=e,this._videoElement&&(this._videoElement.muted=e)}_muted=!1;get currentVideo(){return this.clip}set audioOutputMode(e){e!==this._audioOutputMode&&(e===1&&M()&&console.warn("VideoAudioOutputMode.AudioSource is not yet implemented"),this._audioOutputMode=e,this.updateVideoElementSettings())}get audioOutputMode(){return this._audioOutputMode}_audioOutputMode=2;playInBackground=!0;_crossOrigin="anonymous";_videoElement=null;_videoTexture=null;_videoMaterial=null;_isPlaying=!1;wasPlaying=!1;preloadVideo(){yt&&console.log("Video Preload: "+this.name,this.clip),this.create(!1)}preload(){this.preloadVideo()}setVideo(e){this.clip=e,this.source=0,this._videoElement?(this._videoElement.srcObject=e,this._isPlaying&&this.play(),this.updateAspect()):this.create(this.playOnAwake)}setClipURL(e){this._url!==e&&(this._url=e,this.source=1,yt&&console.log("set url",e),this._videoElement?e.endsWith(".m3u8")||e.includes(".m3u")?this.ensureM3UCanBePlayed():(this._videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(this.playOnAwake))}onEnable(){yt&&console.log("VideoPlayer.onEnable",Dk[this.source],this.clip,this.url,this),window.addEventListener("visibilitychange",this.visibilityChanged),this.playOnAwake===!0?this.create(!0):this.preloadVideo(),this.screenspace?this._overlay?.start():this._overlay?.stop()}onDisable(){window.removeEventListener("visibilitychange",this.visibilityChanged),this._overlay?.stop(),this.pause()}visibilityChanged=e=>{switch(document.visibilityState){case"hidden":this.playInBackground||(this.wasPlaying=this._isPlaying,this.pause());break;case"visible":this.wasPlaying&&!this._isPlaying&&this.play();break}};onDestroy(){this._videoElement&&(this.videoElement?.remove(),this._videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}_receivedInput=!1;constructor(){super(),bB(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],x("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}_playErrors=0;async play(e){if(e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(M()&&console.warn("[VideoPlayer] Called play with unknown argument type. Using assigned source instead.",e),e=void 0),typeof e=="string"?this.setClipURL(e):e instanceof MediaStream&&this.setVideo(e),this._videoElement||this.create(!1),!this._videoElement)return yt&&console.warn("Can not play: no video element found",this),!1;if(this._isPlaying&&!this._videoElement?.ended&&!this._videoElement?.paused)return!0;if(this._isPlaying=!0,this._receivedInput||(this._videoElement.muted=!0),this.handleBeginPlaying(!1),this.shouldUseM3U)return this.ensureM3UCanBePlayed(),!0;yt&&console.log("Video Play()",this.clip,this._videoElement,this.time),this._videoElement.currentTime=this.time;try{return await this._videoElement.play(),yt&&console.log("play",this._videoElement,this.time),!0}catch(t){return this._playErrors++<10?console.error(t):this._playErrors===10&&console.error("Multiple errors playing video, further errors will be suppressed. Use 'debugvideo' param to see all errors."),yt&&console.error("Error playing video",t,"CODE="+t.code,this.videoElement?.src,this),setTimeout(()=>{this._isPlaying&&!this.destroyed&&this.activeAndEnabled&&this.play()},1e3),!1}}stop(){this._isPlaying=!1,this.time=0,this._videoElement&&(this._videoElement.currentTime=0,this._videoElement.pause(),yt&&console.log("STOP",this))}pause(){this.time=this._videoElement?.currentTime??0,this._isPlaying=!1,this._videoElement?.pause(),yt&&console.log("PAUSE",this,this.currentTime)}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url,!t?.length&&typeof this.clip=="string"&&(t=this.clip);break}return t?(this._videoElement||(yt&&console.warn("Create VideoElement",this),this._videoElement=this.createVideoElement(),this.context.domElement.shadowRoot.prepend(this._videoElement),this.updateVideoElementStyles()),typeof t=="string"?(yt&&console.log("Set Video src",t),this._videoElement.src=t):(yt&&console.log("Set Video srcObject",t),this._videoElement.srcObject=t),this._videoTexture||(this._videoTexture=new WM(this._videoElement)),this._videoTexture.flipY=!1,this._videoTexture.colorSpace=Yo,e&&this.handleBeginPlaying(e),yt&&console.log("Video: handle playing done...",t,e),!0):(yt&&console.warn("No video source set",this),!1)}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new wB(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){const e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),yt&&console.log("created video element",e),e}handleBeginPlaying(e){if(!this.activeAndEnabled||!this._videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=P.getComponent(this.gameObject,gi)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,jk[this.renderMode],this);return}const i=t.material;if(i){this._targetObjects.push(t),i!==this._videoMaterial&&(this._videoMaterial=i.clone(),t.material=this._videoMaterial);const n="map",s=this._videoMaterial;if(!this.targetMaterialProperty)yt&&s[n]===void 0&&console.warn(`The target material does not have a '${n}' property, video might not render correctly.`),s[n]=this._videoTexture;else switch(this.targetMaterialProperty){default:yt&&s[this.targetMaterialProperty]===void 0&&console.warn(`The target material does not have a '${this.targetMaterialProperty}' property, video might not render correctly.`),s[n]=this._videoTexture;break}}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&(this.shouldUseM3U&&this.ensureM3UCanBePlayed(),this.play())}updateVideoElementSettings(){if(!this._videoElement)return;this._videoElement.loop=this._isLooping,this._videoElement.currentTime=this.currentTime,this._videoElement.playbackRate=this._playbackSpeed,this._videoElement.playsInline=!0;let e=!this._receivedInput||this.audioOutputMode===0;!e&&this._muted&&(e=!0),this._videoElement.muted=e,this.playOnAwake&&(this._videoElement.autoplay=!0)}updateVideoElementStyles(){this._videoElement&&(this._videoElement.style.userSelect="none",this._videoElement.style.visibility="hidden",this._videoElement.style.display="none",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){const e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let n;for(const s of i.getVideoTracks()){const r=s.getSettings();if(r&&r.width&&r.height){n=r.width/r.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let s=0;s<10;s++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(const s of this._targetObjects){let r=1;if(s.parent){const a=Je(s.parent);r=a.x/a.y}switch(this.aspectMode){case 1:s.scale.y=1/n*s.scale.x*r;break;case 2:s.scale.x=n*s.scale.y*r;break}}for(let s=0;s<3;s++)yield}}get shouldUseM3U(){return this.url!=null&&(this.url.endsWith(".m3u8")||this.url.endsWith(".m3u"))&&this.source===1}ensureM3UCanBePlayed(){if(!this.shouldUseM3U)return;let e=document.head.querySelector("script[data-hls_library]");e?globalThis.Hls?this.onHlsAvailable():e.addEventListener("load",this.onHlsAvailable):(yt&&console.log("HLS: load script"),e=document.createElement("script"),e.dataset.hls_library="hls.js",e.src="https://cdn.jsdelivr.net/npm/hls.js@1",e.addEventListener("load",this.onHlsAvailable),document.head.append(e))}_hls;onHlsAvailable=()=>{yt&&console.log("HLS: available",this.clip),!(!this.shouldUseM3U||!this.url)&&(this._hls||(this._hls=new Hls),this.videoElement.autoplay=!0,this._hls.loadSource(this.url),this._hls.attachMedia(this.videoElement),this._videoElement?.play(),yt&&console.log("HLS: loaded",this.clip))}}nn([p()],kt.prototype,"playOnAwake",2),nn([p()],kt.prototype,"aspectMode",2),nn([p(URL)],kt.prototype,"clip",2),nn([p()],kt.prototype,"source",2),nn([p(URL)],kt.prototype,"url",1),nn([p()],kt.prototype,"renderMode",2),nn([p()],kt.prototype,"targetMaterialProperty",2),nn([p(gi)],kt.prototype,"targetMaterialRenderer",2),nn([p(ke)],kt.prototype,"targetTexture",2),nn([p()],kt.prototype,"time",2),nn([p()],kt.prototype,"playbackSpeed",1),nn([p()],kt.prototype,"isLooping",1),nn([p()],kt.prototype,"audioOutputMode",1);class wB{context;constructor(e){this.context=e,this._input=new xB(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;const t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;const e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Gs.createPrimitive(_l.Quad,{material:new SB(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}const t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();const i=t.material;i?.reset(),this._input?.enable(i)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){const e=this._screenspaceModeQuad?.material;e&&(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input}class xB{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});const t=new ee;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){const s=new ee(n.movementX,n.movementY);s.x/=this.context.domElement.clientWidth,s.y/=this.context.domElement.clientHeight,t.set(s.x,s.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;const s=n.touches[0],r=n.touches[1],a=s.clientX-r.clientX,l=s.clientY-r.clientY,c=Math.sqrt(a*a+l*l);if(this._lastPinch!==0){const h=c-this._lastPinch;this._material.zoom-=h*.004}this._lastPinch=c}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}}class SB extends oo{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){const t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new ee;get offset(){const e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){const t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new ve(0,0,1,1)}},this.vertexShader=`
1459
1459
  uniform sampler2D map;
1460
1460
  uniform float screenAspect;
1461
1461
  uniform vec4 offsetScale;
@@ -1525,7 +1525,7 @@ To allow joining a room without a query parameter you can set "requireRoomParame
1525
1525
  Please choose one of the following options to fix this:
1526
1526
  A) Set a room name in the SyncedRoom component
1527
1527
  B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
1528
- C) Set "joinRandomRoom" to true`),!1):(Ig&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}_lastPingTime=0;_lastRoomTime=-1;_userWantsToBeInARoom=!1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):M()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Q_,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Zc(),t=this.generateRoomName();x(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Af(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_roomButton;_roomButtonIconJoin;_roomButtonIconLeave;createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Jc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=x(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?Jc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Tt("group"),this._roomButtonIconLeave=Tt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(se.LeftRoom,this.updateRoomButtonState),e}updateRoomButtonState=()=>{this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",this._roomButtonIconJoin?.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",this._roomButtonIconLeave?.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))};destroyRoomButton(){this.context.connection.stopListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(se.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(se.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),this._viewOnlyButton?.remove()}onCreateViewOnlyButton=()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{const t=this.getViewOnlyUrl();t?.length?navigator.canShare({url:t})?navigator.share({url:t})?.catch(i=>{console.warn(i)}):(navigator.clipboard.writeText(t),Fe("View only URL copied to clipboard")):ge("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(Tt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}Sr([p()],to.prototype,"roomName",2),Sr([p()],to.prototype,"urlParameterName",2),Sr([p()],to.prototype,"joinRandomRoom",2),Sr([p()],to.prototype,"requireRoomParameter",2),Sr([p()],to.prototype,"autoRejoin",2),Sr([p()],to.prototype,"createJoinButton",2),Sr([p()],to.prototype,"createViewOnlyButton",2),Sr([p()],to.prototype,"roomPrefix",1);var KB=Object.defineProperty,ZB=Object.getOwnPropertyDescriptor,Mc=(o,e,t,i)=>{for(var n=i>1?void 0:i?ZB(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&KB(e,t,n),n};const JB="noVoip",e5=x("debugvoip");class Cs extends T{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_volume=1;get volume(){return this._volume}set volume(e){if(Number.isNaN(e))return;const t=Math.max(0,Math.min(1,e));this._volume=t;for(const i of this._incomingStreams.values())i.volume=t}getAudioElement(e){return this._incomingStreams.get(e)}get incomingStreams(){return this._incomingStreams}speakingThreshold=.1;onSpeakingChanged=new re;_speakingStates=new Map;_analysers=new Map;_sharedAudioContext;_lastSpeakingPollMs=0;_net;_menubutton;awake(){e5&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle incoming mute, 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("VOIP: toggle incoming mute \u2192 ",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}))}onEnable(){this._net||(this._net=du.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Do.StreamReceived,this.onReceiveStream),this._net.addEventListener(Do.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Do.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Do.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged);for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext()}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0;for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext();for(const e of this._incomingStreams.values())wn(e.srcObject);this._incomingStreams.clear(),this._speakingStates.clear()}_allowSending=!0;_outputStream=null;_connectInFlight;get isSending(){return this._outputStream!=null&&this._outputStream.active}connect(e){return this._connectInFlight?this._connectInFlight:(this._connectInFlight=this._connectImpl(e).finally(()=>{this._connectInFlight=void 0}),this._connectInFlight)}async _connectImpl(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await I.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),wn(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 I.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):ul("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||M())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),wn(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){for(const t of this._incomingStreams.values())t.muted=e}get isMuted(){if(this._incomingStreams.size===0)return!1;for(const e of this._incomingStreams.values())if(!e.muted)return!1;return!0}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(),I.microphonePermissionsGranted().then(e=>{e||ge("<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 I.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(Tt(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,M()&&ge("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(s=>(console.warn("VOIP failed getting audio stream",s),null)),i=await t(e);if(!i)return null;if(I.isiOS()&&e?.deviceId===void 0){const n=(await navigator.mediaDevices.enumerateDevices()).find(s=>(s.kind==="audioinput"||s.kind==="audiooutput")&&!s.label.includes("iPhone"));if(n){const s=Object.assign({},e);s.deviceId=n.deviceId;const r=await t(s);if(r)return wn(i),r}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await es(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())wn(e.srcObject);this._incomingStreams.clear();for(const e of this._analysers.keys())this.cleanupAnalyser(e)};_incomingStreams=new Map;update(){if(!this.onSpeakingChanged||this.onSpeakingChanged.listenerCount<=0)return;const e=performance.now();if(!(e-this._lastSpeakingPollMs<100)){this._lastSpeakingPollMs=e;for(const[t,i]of this._analysers){i.analyser.getByteFrequencyData(i.data);let n=0;for(let l=0;l<i.data.length;l++)n+=i.data[l];const s=n/i.data.length/255,r=this._speakingStates.get(t)??!1,a=s>this.speakingThreshold;a!==r&&(this._speakingStates.set(t,a),this.onSpeakingChanged.invoke({userId:t,isSpeaking:a,volume:s}))}}}setupAnalyser(e,t,i){if(!this._analysers.has(e))try{this._sharedAudioContext||(this._sharedAudioContext=new AudioContext);const n=this._sharedAudioContext,s=n.createMediaStreamSource(i),r=n.createAnalyser();r.fftSize=256,s.connect(r);const a=new Uint8Array(r.frequencyBinCount);this._analysers.set(e,{source:s,analyser:r,data:a})}catch(n){this.debug&&console.warn("VOIP: Failed to create analyser for",e,n)}}cleanupAnalyser(e){const t=this._analysers.get(e);t&&(t.source.disconnect(),t.analyser.disconnect(),this._analysers.delete(e)),this._speakingStates.delete(e)}closeSharedAudioContext(){this._sharedAudioContext&&(this._sharedAudioContext.close(),this._sharedAudioContext=void 0)}onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.volume=this._volume,n.setAttribute("autoplay","true"),this.setupAnalyser(t,n,i),no.registerWaitForInteraction(()=>{n?.play().catch(s=>{console.error("VOIP: Failed to play audio",s)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);wn(t?.srcObject),this._incomingStreams.delete(e.userId),this.cleanupAnalyser(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}}Mc([p()],Cs.prototype,"autoConnect",2),Mc([p()],Cs.prototype,"runInBackground",2),Mc([p()],Cs.prototype,"createMenuButton",2),Mc([p()],Cs.prototype,"volume",1),Mc([p()],Cs.prototype,"speakingThreshold",2),Mc([p(re)],Cs.prototype,"onSpeakingChanged",2);function t5(){const o=x("testwindowcount")||0;o&&o>0&&i5(o)}function i5(o){if(x("testwindow"))return null;const e=new URL(window.location.href);Ef(e.searchParams,JB,1),Ef(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,s=128;let r=0,a=0;for(let l=0;l<o;l++){r*s+s*.01>=window.innerWidth&&(a+=1,r=0);const c=r*(s*(1+n))+window.screenLeft,h=a*(s*(1+n))+window.screenTop+90+60*a;r+=1;const d=window.open(t,"test window "+l,`popup=yes width=${s} height=${s} top=${h} left=${c}`);if(!d){console.warn("Failed to open window");continue}i.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let u=0;u<i.length;u++){const m=i[u];m!==d&&m.close()}i.length=0}}}return i}class Y_ extends T{awake(){t5()}}class K_ extends T{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Gh,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new n5(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new Pf(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=cC(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class n5{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new v;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const s=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=s.x,this.velocity.y=s.y,this.velocity.z=s.z}}}var o5=Object.defineProperty,Lg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&o5(e,t,n),n};class $a extends T{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!mh)&&this.context.mainCamera&&(this._control||(this._control=new uR(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(e=>{const t=e;if(t.layers.set(2),t){const i=t.material;i&&(i.opacity=.3)}}),this.orbit=P.getComponentInParent(this.context.mainCamera,fe)??void 0),this._control)){const e=this._control.getHelper();this.context.scene.add(e),this._control.attach(this.gameObject),this._control?.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){this._control?.getHelper()?.removeFromParent(),this._control?.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(Ko.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}onControlChangedEvent=e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=this.gameObject.getComponentInParent(Gn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(Gn);i&&(i.fastMode=!1)}};windowKeyDownListener=e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}};windowKeyUpListener=e=>{this.enabled&&e.keyCode===16&&this.disableSnapping()}}Lg([p()],$a.prototype,"isGizmo"),Lg([p()],$a.prototype,"translationSnap"),Lg([p()],$a.prototype,"rotationSnapAngle"),Lg([p()],$a.prototype,"scaleSnap");var s5=Object.defineProperty,r5=Object.getOwnPropertyDescriptor,Dg=(o,e,t,i)=>{for(var n=i>1?void 0:i?r5(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&s5(e,t,n),n};class Z_{texture=null;rect}Dg([p(Pe)],Z_.prototype,"texture",2);let Rc=class extends Cd{set image(o){this.sprite||(this.sprite=new Z_),this.sprite.texture=o,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(o){this._sprite!==o&&(this._sprite=o,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const o=this.sprite;switch(o?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}const e=o?.texture?.image;return!!(!o?.texture?.name?.length&&ih(e)&&e.width===32&&e.height===32)}onBeforeCreate(o){super.onBeforeCreate(o),this.isBuiltinSprite()&&(o.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(o.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};Dg([p(Z_)],Rc.prototype,"sprite",1),Dg([p()],Rc.prototype,"pixelsPerUnitMultiplier",2);class jg extends Cd{get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}_mainTexture;onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Dg([p(Pe)],jg.prototype,"mainTexture",1);var a5=Object.defineProperty,l5=Object.getOwnPropertyDescriptor,rn=(o,e,t,i)=>{for(var n=i>1?void 0:i?l5(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&a5(e,t,n),n};const Wa=x("debugbutton");class Cr{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}rn([p()],Cr.prototype,"colorMultiplier",2),rn([p(he)],Cr.prototype,"disabledColor",2),rn([p()],Cr.prototype,"fadeDuration",2),rn([p(he)],Cr.prototype,"highlightedColor",2),rn([p(he)],Cr.prototype,"normalColor",2),rn([p(he)],Cr.prototype,"pressedColor",2),rn([p(he)],Cr.prototype,"selectedColor",2);class c5{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class Ps extends T{click(){this.onClick?.invoke()}onClick=new re;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),Wa&&console.warn("Button Enter",t,this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered"),t&&this.context.input.setCursor("pointer"))}onPointerExit(){this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),Wa&&console.log("Button Exit",this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal"),this.context.input.unsetCursor("pointer")))}onPointerDown(e){Wa&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed"))}onPointerUp(e){Wa&&console.warn("Button Up",this.animationTriggers?.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal"))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===lp.Mouse)&&(Wa&&(console.warn("Button Click",this.onClick),Fe("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),this.context.accessibility.focus(this),Wa))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),F.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),Wa&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(qh)||this.gameObject.addComponent(Qp)}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"button",label:this.gameObject.name+" button",hidden:!1})}onDisable(){super.onDisable(),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this),this._isHovered&&this.context.input.unsetCursor("pointer")}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.setTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=P.getComponent(this.gameObject,Rc),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),s={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(s);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),c={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);const h=this.getFinalColor(e.color,this.colors?.disabledColor),d={state:"disabled",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(d)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}rn([p(re)],Ps.prototype,"onClick",2),rn([p(Cr)],Ps.prototype,"colors",2),rn([p()],Ps.prototype,"transition",2),rn([p(c5)],Ps.prototype,"animationTriggers",2),rn([p(Et)],Ps.prototype,"animator",2),rn([p()],Ps.prototype,"interactable",1);var h5=Object.defineProperty,Fg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&h5(e,t,n),n};const Pr=x("debuginputfield"),Gd=class X extends T{get text(){return this.textComponent?.text??""}set text(e){this.textComponent&&(this.textComponent.text=e,this.placeholder&&(e.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return X.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){Pr&&console.log(this.name,this)}onEnable(){X.htmlField||(X.htmlField=document.createElement("input"),X.htmlField.style.width="0px",X.htmlField.style.height="0px",X.htmlField.style.padding="0px",X.htmlField.style.border="none",X.htmlField.style.overflow="hidden",X.htmlField.style.caretColor="transparent",X.htmlField.style.outline="none",X.htmlField.classList.add("ar"),X.htmlField.onfocus=()=>X.htmlFieldFocused=!0,X.htmlField.onblur=()=>X.htmlFieldFocused=!1,document.body.append(X.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),X.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&P.setActive(this.placeholder.gameObject,!1),I.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){X.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){X.active===this&&X.htmlField?(X.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&P.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(e){e.event.pointerType==="mouse"&&e.button===0&&this.context.input.setCursor("text")}onPointerExit(e){this.context.input.unsetCursor("text")}onPointerClick(e){Pr&&console.log("CLICK",e,X.active),X.activeTime=this.context.time.time,X.active!==this&&this.startCoroutine(this.activeLoop(),Ee.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();X.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-X.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(X.active!==this&&(Pr&&console.log("Select",this.name,this,X.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,X.htmlField?.value),X.active?.onDeselected(),X.active=this,this.placeholder&&P.setActive(this.placeholder.gameObject,!1),X.htmlField)){if(X.htmlField.value=this.textComponent?.text||"",Pr&&console.log("set input field value",X.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(X.htmlField)}this.selectInputField()}}onDeselected(){X.active===this&&(X.active=null,Pr&&console.log("Deselect",this.name,this),X.htmlField&&(X.htmlField.blur(),document.body.append(X.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&P.setActive(this.placeholder.gameObject,!0),X.htmlField&&this.onEndEdit?.invoke(X.htmlField.value))}update(){X.active===this&&this.textComponent?.markDirty()}onInput(e){if(X.active===this){if(Pr&&console.log(e.code,e,X.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}X.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&P.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&X.htmlField){const e=this.textComponent.text,t=X.htmlField.value,i=this.textComponent.text!==X.htmlField.value;this.textComponent.text=X.htmlField.value,i&&(Pr&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){X.htmlField&&(Pr&&console.log("Focus Inputfield",X.htmlFieldFocused,X.htmlField),X.htmlField.setSelectionRange(X.htmlField.value.length,X.htmlField.value.length),I.isiOS()?(X.htmlField.style.display="block",X.htmlField.focus({preventScroll:!0})):setTimeout(()=>X.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const t=e[0].object,i=Ub(t);(i?.gameObject===this.gameObject||i?.gameObject.parent===this.gameObject)&&this.selectInputField()}};Fg([p(ii)],Gd.prototype,"textComponent"),Fg([p(ii)],Gd.prototype,"placeholder"),Fg([p(re)],Gd.prototype,"onValueChanged"),Fg([p(re)],Gd.prototype,"onEndEdit");let J_=Gd;var d5=Object.defineProperty,Vk=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&d5(e,t,n),n};class Hd extends T{id=null;keepAspect=!1;_object=null;onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new pR;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new mR(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const s=Iu(this.gameObject).clone();oh(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new ri;r.setFromObject(t),this.setWorldRotation(s.x,s.y,s.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const h=a/l;a>l?i.scale.set(1/a,1/l/h,1):i.scale.set(1/a*h,1/l,1)}else i.scale.set(1/a,1/l,1);const c=this.gameObject.scale;i.scale.multiply(c)},1)}onDisable(){this._object?.removeFromParent()}}Vk([p()],Hd.prototype,"id"),Vk([p()],Hd.prototype,"keepAspect");var u5=Object.defineProperty,Bg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&u5(e,t,n),n};const qd=class EO extends T{target;invertForward=!1;keepUpDirection=!0;copyTargetRotation=!1;static flipYQuat=new B().setFromAxisAngle(new v(0,1,0),Math.PI);onBeforeRender(){let e=this.target;if(e||(e=this.context.mainCamera,M()&&!this.__did_warn&&(this.__did_warn=!0,console.debug(`[LookAt] No target set on ${this.name}, using main camera as target.`))),!e)return;let t=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(t=!1),nh(this.gameObject,e,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(EO.flipYQuat)}createBehaviours(e,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=vt.createEmptyParent(t);n=r;const a=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new J().makeRotationZ(Math.PI/2*a))),t.setMatrix(t.getMatrix().multiply(new J().makeRotationZ(-Math.PI/2*a)))}const s=new qt("lookat "+this.name,ei.sceneStartTrigger(),be.lookAtCameraAction(n,void 0,this.invertForward?En.back:En.forward,this.keepUpDirection?En.up:En.zero));e.addBehavior(s)}}};Bg([p(R)],qd.prototype,"target"),Bg([p()],qd.prototype,"invertForward"),Bg([p()],qd.prototype,"keepUpDirection"),Bg([p()],qd.prototype,"copyTargetRotation");let ev=qd;var p5=Object.defineProperty,tv=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&p5(e,t,n),n};class Tc extends T{url;mode=0;clickable=!0;async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),this.mode){case 0:I.isSafari(),globalThis.open(e,"_blank");break;case 1:I.isSafari()&&I.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:I.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(pn)||this.gameObject.addComponent(pn)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){this.clickable&&!e.used&&this.url?.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(M()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}tv([p()],Tc.prototype,"url"),tv([p()],Tc.prototype,"mode"),tv([p()],Tc.prototype,"clickable"),Qu(o=>{const e=o.domElement.getAttribute("clickthrough");if(t(e)){const i=o.scene.addComponent(Ug);Ou(o.domElement,"clickthrough",()=>{const n=o.domElement.getAttribute("clickthrough");i.enabled=t(n)})}function t(i){return i!==null&&i!=="0"&&i!=="false"}});class Ug extends T{_previousPointerEvents="all";onEnable(){this.context.input.addEventListener("pointerdown",this.onPointerEvent),this.context.input.addEventListener("pointermove",this.onPointerEvent,{queue:100}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._previousPointerEvents=this.context.domElement.style.pointerEvents}onDisable(){this.context.input.removeEventListener("pointerdown",this.onPointerEvent),this.context.input.removeEventListener("pointermove",this.onPointerEvent),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchend",this.onTouchEnd),this.context.domElement.style.pointerEvents=this._previousPointerEvents}onPointerEnter(){}onPointerEvent=e=>{e.pointerId>0||(e.intersections?.length<=0?this.context.domElement.style.pointerEvents="none":this.context.domElement.style.pointerEvents="all")};_touchDidHitAnything=!1;onTouchStart=e=>{const t=e.touches[0];if(!t)return;const i=t.clientX/window.innerWidth*2-1,n=-(t.clientY/window.innerHeight)*2+1;this.context.physics.raycast({screenPoint:new ee(i,n)}).length>0&&(this._touchDidHitAnything=!0)};onTouchEnd=e=>{const t=this._touchDidHitAnything;this._touchDidHitAnything=!1,setTimeout(()=>{t&&(this.context.domElement.style.pointerEvents="all")},100)}}var m5=Object.defineProperty,zg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&m5(e,t,n),n};const g5=x("debugcursor");class Va extends T{static NAME="CursorFollow";damping=0;useFullPage=!0;keepDistance=!0;snapToSurface=!1;_distance=-1;updateDistance(e=!1){!e&&this.keepDistance&&this._distance!==-1||(this._distance=this.gameObject.worldPosition.distanceTo(this.context.mainCamera.worldPosition))}awake(){this._distance=-1}onEnable(){this._distance=-1,window.addEventListener("pointermove",this._onPointerMove)}onDisable(){window.removeEventListener("pointermove",this._onPointerMove)}_ndc_x=0;_ndc_y=0;_onPointerMove=e=>{if(!this.useFullPage)return;const t=e.clientX,i=e.clientY,n=this.context.domX,s=this.context.domY,r=this.context.domWidth,a=this.context.domHeight;this._ndc_x=(t-n)/r*2-1,this._ndc_y=-(i-s)/a*2+1};lateUpdate(){this.updateDistance();const e=this.useFullPage?this._ndc_x:this.context.input.mousePositionRC.x,t=this.useFullPage?this._ndc_y:this.context.input.mousePositionRC.y,i=this.context.mainCamera,n=i.worldPosition,s=U(e,t,1).unproject(i);s.sub(n).normalize();const r=U(s).multiplyScalar(this._distance).add(n);let a=r;if(this.damping>0){const l=this.gameObject.worldPosition;l.lerp(r,this.context.time.deltaTime/this.damping),this.gameObject.worldPosition=l,a=l}else this.gameObject.worldPosition=r;if(this.snapToSurface){iv.origin=n,iv.direction=s;const l=this.context.physics.raycastFromRay(iv,{testObject:c=>c!==this.gameObject&&!this.gameObject.contains(c)});if(l?.length){const c=l[0];c&&(this.damping>0?this.gameObject.worldPosition=a.lerp(c.point,this.context.time.deltaTime/this.damping):this.gameObject.worldPosition=c.point,g5&&F.DrawLine(c.point,c.normal.add(c.point),65280))}}}}zg([p()],Va.prototype,"damping"),zg([p()],Va.prototype,"useFullPage"),zg([p()],Va.prototype,"keepDistance"),zg([p()],Va.prototype,"snapToSurface");const iv=new so;var f5=Object.defineProperty,y5=Object.getOwnPropertyDescriptor,Ec=(o,e,t,i)=>{for(var n=i>1?void 0:i?y5(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&f5(e,t,n),n};let Bo=class extends T{type="linear";duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||(this.idle=li.emptyClip()),(!this.hovered||!(this.hovered instanceof Yt))&&(this.hovered=li.createScaleClip({type:"linear",duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Zt),this.animation.playAutomatically=!1,this.playIdle()}onEnable(){this.animation&&(this.animation.enabled=!0),this.playIdle()}onDisable(){this.animation&&(this.animation.enabled=!1),this.playIdle()}onPointerEnter(){this.playHover()}onPointerExit(){this.playIdle()}playIdle(){this.idle&&this.animation?.play(this.idle,{exclusive:!0,fadeDuration:.1,loop:!0})}playHover(){this.hovered&&this.animation?.play(this.hovered,{exclusive:!0,fadeDuration:.1,loop:!1,clampWhenFinished:!0})}};Ec([p()],Bo.prototype,"type",2),Ec([p()],Bo.prototype,"duration",2),Ec([p()],Bo.prototype,"scaleFactor",2),Ec([p(Yt)],Bo.prototype,"hovered",2),Ec([p(Yt)],Bo.prototype,"idle",2),Bo=Ec([iy],Bo);var b5=Object.defineProperty,Ga=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&b5(e,t,n),n};typeof window<"u"&&import("./vendor-CdNldo8c.min.js").then(o=>o.scrollTimeline);const ks=x("debugscroll");class Uo extends T{target=null;damping=0;invert=!1;htmlSelector=null;mode="window";useTopWindowScroll=!0;changed=new re;get currentValue(){return this._current_value}_current_value=0;_target_value=0;_appliedValue=-1;_needsUpdate=!1;_firstUpdate=!1;_scrollWindow=null;_wheelTarget=null;_crossOriginWarned=!1;_viewTimelineWarned=!1;awake(){this._firstUpdate=!0}onEnable(){this.rebindScrollListener(),this._appliedValue=-1,this._needsUpdate=!0}onDisable(){this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=null}onValidate(e){e==="useTopWindowScroll"&&this._wheelTarget&&(this.rebindScrollListener(),this._needsUpdate=!0)}resolveScrollWindow(){if(!this.useTopWindowScroll)return window;const e=window.top;if(!e||e===window.self)return window;try{return e.document,e}catch{return this._crossOriginWarned||(this._crossOriginWarned=!0,(ks||M())&&console.warn("[ScrollFollow] useTopWindowScroll is enabled but the top-level window is cross-origin and cannot be read. Falling back to the local window. Supporting cross-origin embeds requires a postMessage scroll bridge from the host page.")),window}}rebindScrollListener(){const e=this.resolveScrollWindow();this._scrollWindow=e,e!==this._wheelTarget&&(this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=e,e.addEventListener("wheel",this.updateCurrentScrollValue,{passive:!0}),this._lastSelectorValue=null,this._lastSelectorElement=null,ks&&console.debug(`[ScrollFollow] Scroll listener bound to ${e===window?"local window":"top-level window"}`,{scrollWindow:this._scrollWindow,isTopWindow:e===window}))}lateUpdate(){if(this.updateCurrentScrollValue(),this._target_value>=0&&(this.damping>0&&!this._firstUpdate?(this._current_value=j.lerp(this._current_value,this._target_value,this.context.time.deltaTime/this.damping),Math.abs(this._current_value-this._target_value)<.001&&(this._current_value=this._target_value)):this._current_value=this._target_value),this._needsUpdate||this._current_value!==this._appliedValue){this._appliedValue=this._current_value,this._needsUpdate=!1;let e=!1;if(this.changed.listenerCount>0){const t={type:"change",value:this._current_value,component:this,preventDefault:()=>{t.defaultPrevented=!0},defaultPrevented:!1};this.changed.invoke(t),e=t.defaultPrevented}if(!e){const t=this.invert?1-this._current_value:this._current_value;Array.isArray(this.target)?this.target.forEach(i=>i&&this.applyScroll(i,t)):this.target&&this.applyScroll(this.target,t),ks&&this.context.time.frame%30===0&&console.debug(`[ScrollFollow] ${this._current_value.toFixed(5)} \u2014 ${(this._target_value*100).toFixed(0)}%, targets [${Array.isArray(this.target)?this.target.length:1}]`)}this._firstUpdate=!1}}_lastSelectorValue=null;_lastSelectorElement=null;updateCurrentScrollValue=()=>{const e=this._scrollWindow??window,t=e.document,i=t.scrollingElement??t.documentElement;switch(this.mode){case"window":if(this.htmlSelector?.length){if(this.htmlSelector!==this._lastSelectorValue&&(this._lastSelectorElement=t.querySelector(this.htmlSelector),this._lastSelectorValue=this.htmlSelector),this._lastSelectorElement){const n=this._lastSelectorElement.getBoundingClientRect();this._target_value=-n.top/(n.height-e.innerHeight);break}}else{const n=i.scrollHeight-i.clientHeight;n<=0||(this._target_value=i.scrollTop/n)}break}(isNaN(this._target_value)||!isFinite(this._target_value))&&(this._target_value=-1),ks&&console.debug(`[ScrollFollow] Scroll value updated: ${this._target_value.toFixed(5)} (ScrollTop: ${i.scrollTop}, ScrollHeight: ${i.scrollHeight}, ClientHeight: ${i.clientHeight})`)};applyScroll(e,t){if(e)if(e instanceof Vl)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof Et)e.setFloat("scroll",t);else if(e instanceof Zt)e.time=t*e.duration;else if(e instanceof Yi){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof xn)e.position01=t;else if(e instanceof $t)e.intensity=t;else if(e instanceof R){const i=e;i["needle:scrollbounds"]===void 0&&(i["needle:scrollbounds"]=Si(e)||null);const n=i["needle:scrollbounds"];n&&(e.position.y=-n.min.y-t*(n.max.y-n.min.y))}else"scroll"in e&&(typeof e.scroll=="number"?e.scroll=t:typeof e.scroll=="function"&&e.scroll(t))}handleTimelineTarget(e,t){const i=this._scrollWindow??window,n=i.document,s=e.duration;let r=nv.get(e);if(!r){r=[],nv.set(e,r);let h=0;for(const u of e.foreachMarker("ScrollMarker")){const m=h++;if(u.element===void 0||u.needsUpdate===!0||u.element&&!u.element?.parentNode){u.needsUpdate=!1;try{if(u.element=Gk(m,n),ks&&console.debug(`ScrollMarker #${m} (${u.time.toFixed(2)}) found`,u.element),!u.element){(ks||M())&&console.warn(`No HTML element found for ScrollMarker: ${u.name} (index ${m})`);continue}}catch(g){u.element=null,console.error("ScrollMarker selector is not valid: "+u.name+`
1528
+ C) Set "joinRandomRoom" to true`),!1):(Ig&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}_lastPingTime=0;_lastRoomTime=-1;_userWantsToBeInARoom=!1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):M()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Q_,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Zc(),t=this.generateRoomName();x(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Af(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_roomButton;_roomButtonIconJoin;_roomButtonIconLeave;createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Jc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=x(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?Jc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Tt("group"),this._roomButtonIconLeave=Tt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(se.LeftRoom,this.updateRoomButtonState),e}updateRoomButtonState=()=>{this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",this._roomButtonIconJoin?.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",this._roomButtonIconLeave?.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))};destroyRoomButton(){this.context.connection.stopListen(se.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(se.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(se.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(se.JoinedRoom,this.onCreateViewOnlyButton),this._viewOnlyButton?.remove()}onCreateViewOnlyButton=()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{const t=this.getViewOnlyUrl();t?.length?navigator.canShare({url:t})?navigator.share({url:t})?.catch(i=>{console.warn(i)}):(navigator.clipboard.writeText(t),Fe("View only URL copied to clipboard")):ge("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(Tt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}Sr([p()],to.prototype,"roomName",2),Sr([p()],to.prototype,"urlParameterName",2),Sr([p()],to.prototype,"joinRandomRoom",2),Sr([p()],to.prototype,"requireRoomParameter",2),Sr([p()],to.prototype,"autoRejoin",2),Sr([p()],to.prototype,"createJoinButton",2),Sr([p()],to.prototype,"createViewOnlyButton",2),Sr([p()],to.prototype,"roomPrefix",1);var KB=Object.defineProperty,ZB=Object.getOwnPropertyDescriptor,Mc=(o,e,t,i)=>{for(var n=i>1?void 0:i?ZB(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&KB(e,t,n),n};const JB="noVoip",e5=x("debugvoip");class Cs extends T{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_volume=1;get volume(){return this._volume}set volume(e){if(Number.isNaN(e))return;const t=Math.max(0,Math.min(1,e));this._volume=t;for(const i of this._incomingStreams.values())i.volume=t}getAudioElement(e){return this._incomingStreams.get(e)}get incomingStreams(){return this._incomingStreams}speakingThreshold=.1;onSpeakingChanged=new re;_speakingStates=new Map;_analysers=new Map;_sharedAudioContext;_lastSpeakingPollMs=0;_net;_menubutton;awake(){e5&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle incoming mute, 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("VOIP: toggle incoming mute \u2192 ",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}))}onEnable(){this._net||(this._net=du.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Do.StreamReceived,this.onReceiveStream),this._net.addEventListener(Do.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(se.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Do.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Do.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(se.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(se.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged);for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext()}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0;for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext();for(const e of this._incomingStreams.values())wn(e.srcObject);this._incomingStreams.clear(),this._speakingStates.clear()}_allowSending=!0;_outputStream=null;_connectInFlight;get isSending(){return this._outputStream!=null&&this._outputStream.active}connect(e){return this._connectInFlight?this._connectInFlight:(this._connectInFlight=this._connectImpl(e).finally(()=>{this._connectInFlight=void 0}),this._connectInFlight)}async _connectImpl(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await I.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),wn(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 I.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):ul("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||M())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),wn(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){for(const t of this._incomingStreams.values())t.muted=e}get isMuted(){if(this._incomingStreams.size===0)return!1;for(const e of this._incomingStreams.values())if(!e.muted)return!1;return!0}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(),I.microphonePermissionsGranted().then(e=>{e||ge("<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 I.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(Tt(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,M()&&ge("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(s=>(console.warn("VOIP failed getting audio stream",s),null)),i=await t(e);if(!i)return null;if(I.isiOS()&&e?.deviceId===void 0){const n=(await navigator.mediaDevices.enumerateDevices()).find(s=>(s.kind==="audioinput"||s.kind==="audiooutput")&&!s.label.includes("iPhone"));if(n){const s=Object.assign({},e);s.deviceId=n.deviceId;const r=await t(s);if(r)return wn(i),r}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await es(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())wn(e.srcObject);this._incomingStreams.clear();for(const e of this._analysers.keys())this.cleanupAnalyser(e)};_incomingStreams=new Map;update(){if(!this.onSpeakingChanged||this.onSpeakingChanged.listenerCount<=0)return;const e=performance.now();if(!(e-this._lastSpeakingPollMs<100)){this._lastSpeakingPollMs=e;for(const[t,i]of this._analysers){i.analyser.getByteFrequencyData(i.data);let n=0;for(let l=0;l<i.data.length;l++)n+=i.data[l];const s=n/i.data.length/255,r=this._speakingStates.get(t)??!1,a=s>this.speakingThreshold;a!==r&&(this._speakingStates.set(t,a),this.onSpeakingChanged.invoke({userId:t,isSpeaking:a,volume:s}))}}}setupAnalyser(e,t,i){if(!this._analysers.has(e))try{this._sharedAudioContext||(this._sharedAudioContext=new AudioContext);const n=this._sharedAudioContext,s=n.createMediaStreamSource(i),r=n.createAnalyser();r.fftSize=256,s.connect(r);const a=new Uint8Array(r.frequencyBinCount);this._analysers.set(e,{source:s,analyser:r,data:a})}catch(n){this.debug&&console.warn("VOIP: Failed to create analyser for",e,n)}}cleanupAnalyser(e){const t=this._analysers.get(e);t&&(t.source.disconnect(),t.analyser.disconnect(),this._analysers.delete(e)),this._speakingStates.delete(e)}closeSharedAudioContext(){this._sharedAudioContext&&(this._sharedAudioContext.close(),this._sharedAudioContext=void 0)}onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.volume=this._volume,n.setAttribute("autoplay","true"),this.setupAnalyser(t,n,i),no.registerWaitForInteraction(()=>{n?.play().catch(s=>{console.error("VOIP: Failed to play audio",s)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);wn(t?.srcObject),this._incomingStreams.delete(e.userId),this.cleanupAnalyser(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}}Mc([p()],Cs.prototype,"autoConnect",2),Mc([p()],Cs.prototype,"runInBackground",2),Mc([p()],Cs.prototype,"createMenuButton",2),Mc([p()],Cs.prototype,"volume",1),Mc([p()],Cs.prototype,"speakingThreshold",2),Mc([p(re)],Cs.prototype,"onSpeakingChanged",2);function t5(){const o=x("testwindowcount")||0;o&&o>0&&i5(o)}function i5(o){if(x("testwindow"))return null;const e=new URL(window.location.href);Ef(e.searchParams,JB,1),Ef(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,s=128;let r=0,a=0;for(let l=0;l<o;l++){r*s+s*.01>=window.innerWidth&&(a+=1,r=0);const c=r*(s*(1+n))+window.screenLeft,h=a*(s*(1+n))+window.screenTop+90+60*a;r+=1;const d=window.open(t,"test window "+l,`popup=yes width=${s} height=${s} top=${h} left=${c}`);if(!d){console.warn("Failed to open window");continue}i.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let u=0;u<i.length;u++){const m=i[u];m!==d&&m.close()}i.length=0}}}return i}class Y_ extends T{awake(){t5()}}class K_ extends T{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Gh,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new n5(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new Pf(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=cC(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class n5{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new v;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const s=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=s.x,this.velocity.y=s.y,this.velocity.z=s.z}}}var o5=Object.defineProperty,Lg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&o5(e,t,n),n};class $a extends T{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!mh)&&this.context.mainCamera&&(this._control||(this._control=new uR(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(e=>{const t=e;if(t.layers.set(2),t){const i=t.material;i&&(i.opacity=.3)}}),this.orbit=P.getComponentInParent(this.context.mainCamera,fe)??void 0),this._control)){const e=this._control.getHelper();this.context.scene.add(e),this._control.attach(this.gameObject),this._control?.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){this._control?.getHelper()?.removeFromParent(),this._control?.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(Ko.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}onControlChangedEvent=e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=this.gameObject.getComponentInParent(Gn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(Gn);i&&(i.fastMode=!1)}};windowKeyDownListener=e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}};windowKeyUpListener=e=>{this.enabled&&e.keyCode===16&&this.disableSnapping()}}Lg([p()],$a.prototype,"isGizmo"),Lg([p()],$a.prototype,"translationSnap"),Lg([p()],$a.prototype,"rotationSnapAngle"),Lg([p()],$a.prototype,"scaleSnap");var s5=Object.defineProperty,r5=Object.getOwnPropertyDescriptor,Dg=(o,e,t,i)=>{for(var n=i>1?void 0:i?r5(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&s5(e,t,n),n};class Z_{texture=null;rect}Dg([p(ke)],Z_.prototype,"texture",2);let Rc=class extends Cd{set image(o){this.sprite||(this.sprite=new Z_),this.sprite.texture=o,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(o){this._sprite!==o&&(this._sprite=o,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const o=this.sprite;switch(o?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}const e=o?.texture?.image;return!!(!o?.texture?.name?.length&&ih(e)&&e.width===32&&e.height===32)}onBeforeCreate(o){super.onBeforeCreate(o),this.isBuiltinSprite()&&(o.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(o.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};Dg([p(Z_)],Rc.prototype,"sprite",1),Dg([p()],Rc.prototype,"pixelsPerUnitMultiplier",2);class jg extends Cd{get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}_mainTexture;onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Dg([p(ke)],jg.prototype,"mainTexture",1);var a5=Object.defineProperty,l5=Object.getOwnPropertyDescriptor,rn=(o,e,t,i)=>{for(var n=i>1?void 0:i?l5(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&a5(e,t,n),n};const Wa=x("debugbutton");class Cr{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}rn([p()],Cr.prototype,"colorMultiplier",2),rn([p(he)],Cr.prototype,"disabledColor",2),rn([p()],Cr.prototype,"fadeDuration",2),rn([p(he)],Cr.prototype,"highlightedColor",2),rn([p(he)],Cr.prototype,"normalColor",2),rn([p(he)],Cr.prototype,"pressedColor",2),rn([p(he)],Cr.prototype,"selectedColor",2);class c5{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class Ps extends T{click(){this.onClick?.invoke()}onClick=new re;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),Wa&&console.warn("Button Enter",t,this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered"),t&&this.context.input.setCursor("pointer"))}onPointerExit(){this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),Wa&&console.log("Button Exit",this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal"),this.context.input.unsetCursor("pointer")))}onPointerDown(e){Wa&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed"))}onPointerUp(e){Wa&&console.warn("Button Up",this.animationTriggers?.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal"))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===lp.Mouse)&&(Wa&&(console.warn("Button Click",this.onClick),Fe("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),this.context.accessibility.focus(this),Wa))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),F.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),Wa&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(qh)||this.gameObject.addComponent(Qp)}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"button",label:this.gameObject.name+" button",hidden:!1})}onDisable(){super.onDisable(),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this),this._isHovered&&this.context.input.unsetCursor("pointer")}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.setTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=P.getComponent(this.gameObject,Rc),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),s={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(s);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),c={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);const h=this.getFinalColor(e.color,this.colors?.disabledColor),d={state:"disabled",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(d)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}rn([p(re)],Ps.prototype,"onClick",2),rn([p(Cr)],Ps.prototype,"colors",2),rn([p()],Ps.prototype,"transition",2),rn([p(c5)],Ps.prototype,"animationTriggers",2),rn([p(Et)],Ps.prototype,"animator",2),rn([p()],Ps.prototype,"interactable",1);var h5=Object.defineProperty,Fg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&h5(e,t,n),n};const Pr=x("debuginputfield"),Gd=class X extends T{get text(){return this.textComponent?.text??""}set text(e){this.textComponent&&(this.textComponent.text=e,this.placeholder&&(e.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return X.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){Pr&&console.log(this.name,this)}onEnable(){X.htmlField||(X.htmlField=document.createElement("input"),X.htmlField.style.width="0px",X.htmlField.style.height="0px",X.htmlField.style.padding="0px",X.htmlField.style.border="none",X.htmlField.style.overflow="hidden",X.htmlField.style.caretColor="transparent",X.htmlField.style.outline="none",X.htmlField.classList.add("ar"),X.htmlField.onfocus=()=>X.htmlFieldFocused=!0,X.htmlField.onblur=()=>X.htmlFieldFocused=!1,document.body.append(X.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),X.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&P.setActive(this.placeholder.gameObject,!1),I.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){X.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){X.active===this&&X.htmlField?(X.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&P.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(e){e.event.pointerType==="mouse"&&e.button===0&&this.context.input.setCursor("text")}onPointerExit(e){this.context.input.unsetCursor("text")}onPointerClick(e){Pr&&console.log("CLICK",e,X.active),X.activeTime=this.context.time.time,X.active!==this&&this.startCoroutine(this.activeLoop(),Ee.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();X.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-X.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(X.active!==this&&(Pr&&console.log("Select",this.name,this,X.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,X.htmlField?.value),X.active?.onDeselected(),X.active=this,this.placeholder&&P.setActive(this.placeholder.gameObject,!1),X.htmlField)){if(X.htmlField.value=this.textComponent?.text||"",Pr&&console.log("set input field value",X.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(X.htmlField)}this.selectInputField()}}onDeselected(){X.active===this&&(X.active=null,Pr&&console.log("Deselect",this.name,this),X.htmlField&&(X.htmlField.blur(),document.body.append(X.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&P.setActive(this.placeholder.gameObject,!0),X.htmlField&&this.onEndEdit?.invoke(X.htmlField.value))}update(){X.active===this&&this.textComponent?.markDirty()}onInput(e){if(X.active===this){if(Pr&&console.log(e.code,e,X.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}X.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&P.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&X.htmlField){const e=this.textComponent.text,t=X.htmlField.value,i=this.textComponent.text!==X.htmlField.value;this.textComponent.text=X.htmlField.value,i&&(Pr&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){X.htmlField&&(Pr&&console.log("Focus Inputfield",X.htmlFieldFocused,X.htmlField),X.htmlField.setSelectionRange(X.htmlField.value.length,X.htmlField.value.length),I.isiOS()?(X.htmlField.style.display="block",X.htmlField.focus({preventScroll:!0})):setTimeout(()=>X.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const t=e[0].object,i=Ub(t);(i?.gameObject===this.gameObject||i?.gameObject.parent===this.gameObject)&&this.selectInputField()}};Fg([p(ii)],Gd.prototype,"textComponent"),Fg([p(ii)],Gd.prototype,"placeholder"),Fg([p(re)],Gd.prototype,"onValueChanged"),Fg([p(re)],Gd.prototype,"onEndEdit");let J_=Gd;var d5=Object.defineProperty,Vk=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&d5(e,t,n),n};class Hd extends T{id=null;keepAspect=!1;_object=null;onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new pR;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new mR(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const s=Iu(this.gameObject).clone();oh(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new ri;r.setFromObject(t),this.setWorldRotation(s.x,s.y,s.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const h=a/l;a>l?i.scale.set(1/a,1/l/h,1):i.scale.set(1/a*h,1/l,1)}else i.scale.set(1/a,1/l,1);const c=this.gameObject.scale;i.scale.multiply(c)},1)}onDisable(){this._object?.removeFromParent()}}Vk([p()],Hd.prototype,"id"),Vk([p()],Hd.prototype,"keepAspect");var u5=Object.defineProperty,Bg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&u5(e,t,n),n};const qd=class EO extends T{target;invertForward=!1;keepUpDirection=!0;copyTargetRotation=!1;static flipYQuat=new B().setFromAxisAngle(new v(0,1,0),Math.PI);onBeforeRender(){let e=this.target;if(e||(e=this.context.mainCamera,M()&&!this.__did_warn&&(this.__did_warn=!0,console.debug(`[LookAt] No target set on ${this.name}, using main camera as target.`))),!e)return;let t=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(t=!1),nh(this.gameObject,e,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(EO.flipYQuat)}createBehaviours(e,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=vt.createEmptyParent(t);n=r;const a=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new J().makeRotationZ(Math.PI/2*a))),t.setMatrix(t.getMatrix().multiply(new J().makeRotationZ(-Math.PI/2*a)))}const s=new qt("lookat "+this.name,ei.sceneStartTrigger(),be.lookAtCameraAction(n,void 0,this.invertForward?En.back:En.forward,this.keepUpDirection?En.up:En.zero));e.addBehavior(s)}}};Bg([p(R)],qd.prototype,"target"),Bg([p()],qd.prototype,"invertForward"),Bg([p()],qd.prototype,"keepUpDirection"),Bg([p()],qd.prototype,"copyTargetRotation");let ev=qd;var p5=Object.defineProperty,tv=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&p5(e,t,n),n};class Tc extends T{url;mode=0;clickable=!0;async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),this.mode){case 0:I.isSafari(),globalThis.open(e,"_blank");break;case 1:I.isSafari()&&I.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:I.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(pn)||this.gameObject.addComponent(pn)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){this.clickable&&!e.used&&this.url?.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(M()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}tv([p()],Tc.prototype,"url"),tv([p()],Tc.prototype,"mode"),tv([p()],Tc.prototype,"clickable"),Qu(o=>{const e=o.domElement.getAttribute("clickthrough");if(t(e)){const i=o.scene.addComponent(Ug);Ou(o.domElement,"clickthrough",()=>{const n=o.domElement.getAttribute("clickthrough");i.enabled=t(n)})}function t(i){return i!==null&&i!=="0"&&i!=="false"}});class Ug extends T{_previousPointerEvents="all";onEnable(){this.context.input.addEventListener("pointerdown",this.onPointerEvent),this.context.input.addEventListener("pointermove",this.onPointerEvent,{queue:100}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._previousPointerEvents=this.context.domElement.style.pointerEvents}onDisable(){this.context.input.removeEventListener("pointerdown",this.onPointerEvent),this.context.input.removeEventListener("pointermove",this.onPointerEvent),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchend",this.onTouchEnd),this.context.domElement.style.pointerEvents=this._previousPointerEvents}onPointerEnter(){}onPointerEvent=e=>{e.pointerId>0||(e.intersections?.length<=0?this.context.domElement.style.pointerEvents="none":this.context.domElement.style.pointerEvents="all")};_touchDidHitAnything=!1;onTouchStart=e=>{const t=e.touches[0];if(!t)return;const i=t.clientX/window.innerWidth*2-1,n=-(t.clientY/window.innerHeight)*2+1;this.context.physics.raycast({screenPoint:new ee(i,n)}).length>0&&(this._touchDidHitAnything=!0)};onTouchEnd=e=>{const t=this._touchDidHitAnything;this._touchDidHitAnything=!1,setTimeout(()=>{t&&(this.context.domElement.style.pointerEvents="all")},100)}}var m5=Object.defineProperty,zg=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&m5(e,t,n),n};const g5=x("debugcursor");class Va extends T{static NAME="CursorFollow";damping=0;useFullPage=!0;keepDistance=!0;snapToSurface=!1;_distance=-1;updateDistance(e=!1){!e&&this.keepDistance&&this._distance!==-1||(this._distance=this.gameObject.worldPosition.distanceTo(this.context.mainCamera.worldPosition))}awake(){this._distance=-1}onEnable(){this._distance=-1,window.addEventListener("pointermove",this._onPointerMove)}onDisable(){window.removeEventListener("pointermove",this._onPointerMove)}_ndc_x=0;_ndc_y=0;_onPointerMove=e=>{if(!this.useFullPage)return;const t=e.clientX,i=e.clientY,n=this.context.domX,s=this.context.domY,r=this.context.domWidth,a=this.context.domHeight;this._ndc_x=(t-n)/r*2-1,this._ndc_y=-(i-s)/a*2+1};lateUpdate(){this.updateDistance();const e=this.useFullPage?this._ndc_x:this.context.input.mousePositionRC.x,t=this.useFullPage?this._ndc_y:this.context.input.mousePositionRC.y,i=this.context.mainCamera,n=i.worldPosition,s=U(e,t,1).unproject(i);s.sub(n).normalize();const r=U(s).multiplyScalar(this._distance).add(n);let a=r;if(this.damping>0){const l=this.gameObject.worldPosition;l.lerp(r,this.context.time.deltaTime/this.damping),this.gameObject.worldPosition=l,a=l}else this.gameObject.worldPosition=r;if(this.snapToSurface){iv.origin=n,iv.direction=s;const l=this.context.physics.raycastFromRay(iv,{testObject:c=>c!==this.gameObject&&!this.gameObject.contains(c)});if(l?.length){const c=l[0];c&&(this.damping>0?this.gameObject.worldPosition=a.lerp(c.point,this.context.time.deltaTime/this.damping):this.gameObject.worldPosition=c.point,g5&&F.DrawLine(c.point,c.normal.add(c.point),65280))}}}}zg([p()],Va.prototype,"damping"),zg([p()],Va.prototype,"useFullPage"),zg([p()],Va.prototype,"keepDistance"),zg([p()],Va.prototype,"snapToSurface");const iv=new so;var f5=Object.defineProperty,y5=Object.getOwnPropertyDescriptor,Ec=(o,e,t,i)=>{for(var n=i>1?void 0:i?y5(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&f5(e,t,n),n};let Bo=class extends T{type="linear";duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||(this.idle=li.emptyClip()),(!this.hovered||!(this.hovered instanceof Yt))&&(this.hovered=li.createScaleClip({type:"linear",duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Zt),this.animation.playAutomatically=!1,this.playIdle()}onEnable(){this.animation&&(this.animation.enabled=!0),this.playIdle()}onDisable(){this.animation&&(this.animation.enabled=!1),this.playIdle()}onPointerEnter(){this.playHover()}onPointerExit(){this.playIdle()}playIdle(){this.idle&&this.animation?.play(this.idle,{exclusive:!0,fadeDuration:.1,loop:!0})}playHover(){this.hovered&&this.animation?.play(this.hovered,{exclusive:!0,fadeDuration:.1,loop:!1,clampWhenFinished:!0})}};Ec([p()],Bo.prototype,"type",2),Ec([p()],Bo.prototype,"duration",2),Ec([p()],Bo.prototype,"scaleFactor",2),Ec([p(Yt)],Bo.prototype,"hovered",2),Ec([p(Yt)],Bo.prototype,"idle",2),Bo=Ec([iy],Bo);var b5=Object.defineProperty,Ga=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&b5(e,t,n),n};typeof window<"u"&&import("./vendor-T07c_9f_.min.js").then(o=>o.scrollTimeline);const ks=x("debugscroll");class Uo extends T{target=null;damping=0;invert=!1;htmlSelector=null;mode="window";useTopWindowScroll=!0;changed=new re;get currentValue(){return this._current_value}_current_value=0;_target_value=0;_appliedValue=-1;_needsUpdate=!1;_firstUpdate=!1;_scrollWindow=null;_wheelTarget=null;_crossOriginWarned=!1;_viewTimelineWarned=!1;awake(){this._firstUpdate=!0}onEnable(){this.rebindScrollListener(),this._appliedValue=-1,this._needsUpdate=!0}onDisable(){this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=null}onValidate(e){e==="useTopWindowScroll"&&this._wheelTarget&&(this.rebindScrollListener(),this._needsUpdate=!0)}resolveScrollWindow(){if(!this.useTopWindowScroll)return window;const e=window.top;if(!e||e===window.self)return window;try{return e.document,e}catch{return this._crossOriginWarned||(this._crossOriginWarned=!0,(ks||M())&&console.warn("[ScrollFollow] useTopWindowScroll is enabled but the top-level window is cross-origin and cannot be read. Falling back to the local window. Supporting cross-origin embeds requires a postMessage scroll bridge from the host page.")),window}}rebindScrollListener(){const e=this.resolveScrollWindow();this._scrollWindow=e,e!==this._wheelTarget&&(this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=e,e.addEventListener("wheel",this.updateCurrentScrollValue,{passive:!0}),this._lastSelectorValue=null,this._lastSelectorElement=null,ks&&console.debug(`[ScrollFollow] Scroll listener bound to ${e===window?"local window":"top-level window"}`,{scrollWindow:this._scrollWindow,isTopWindow:e===window}))}lateUpdate(){if(this.updateCurrentScrollValue(),this._target_value>=0&&(this.damping>0&&!this._firstUpdate?(this._current_value=j.lerp(this._current_value,this._target_value,this.context.time.deltaTime/this.damping),Math.abs(this._current_value-this._target_value)<.001&&(this._current_value=this._target_value)):this._current_value=this._target_value),this._needsUpdate||this._current_value!==this._appliedValue){this._appliedValue=this._current_value,this._needsUpdate=!1;let e=!1;if(this.changed.listenerCount>0){const t={type:"change",value:this._current_value,component:this,preventDefault:()=>{t.defaultPrevented=!0},defaultPrevented:!1};this.changed.invoke(t),e=t.defaultPrevented}if(!e){const t=this.invert?1-this._current_value:this._current_value;Array.isArray(this.target)?this.target.forEach(i=>i&&this.applyScroll(i,t)):this.target&&this.applyScroll(this.target,t),ks&&this.context.time.frame%30===0&&console.debug(`[ScrollFollow] ${this._current_value.toFixed(5)} \u2014 ${(this._target_value*100).toFixed(0)}%, targets [${Array.isArray(this.target)?this.target.length:1}]`)}this._firstUpdate=!1}}_lastSelectorValue=null;_lastSelectorElement=null;updateCurrentScrollValue=()=>{const e=this._scrollWindow??window,t=e.document,i=t.scrollingElement??t.documentElement;switch(this.mode){case"window":if(this.htmlSelector?.length){if(this.htmlSelector!==this._lastSelectorValue&&(this._lastSelectorElement=t.querySelector(this.htmlSelector),this._lastSelectorValue=this.htmlSelector),this._lastSelectorElement){const n=this._lastSelectorElement.getBoundingClientRect();this._target_value=-n.top/(n.height-e.innerHeight);break}}else{const n=i.scrollHeight-i.clientHeight;n<=0||(this._target_value=i.scrollTop/n)}break}(isNaN(this._target_value)||!isFinite(this._target_value))&&(this._target_value=-1),ks&&console.debug(`[ScrollFollow] Scroll value updated: ${this._target_value.toFixed(5)} (ScrollTop: ${i.scrollTop}, ScrollHeight: ${i.scrollHeight}, ClientHeight: ${i.clientHeight})`)};applyScroll(e,t){if(e)if(e instanceof Vl)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof Et)e.setFloat("scroll",t);else if(e instanceof Zt)e.time=t*e.duration;else if(e instanceof Yi){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof xn)e.position01=t;else if(e instanceof $t)e.intensity=t;else if(e instanceof R){const i=e;i["needle:scrollbounds"]===void 0&&(i["needle:scrollbounds"]=Si(e)||null);const n=i["needle:scrollbounds"];n&&(e.position.y=-n.min.y-t*(n.max.y-n.min.y))}else"scroll"in e&&(typeof e.scroll=="number"?e.scroll=t:typeof e.scroll=="function"&&e.scroll(t))}handleTimelineTarget(e,t){const i=this._scrollWindow??window,n=i.document,s=e.duration;let r=nv.get(e);if(!r){r=[],nv.set(e,r);let h=0;for(const u of e.foreachMarker("ScrollMarker")){const m=h++;if(u.element===void 0||u.needsUpdate===!0||u.element&&!u.element?.parentNode){u.needsUpdate=!1;try{if(u.element=Gk(m,n),ks&&console.debug(`ScrollMarker #${m} (${u.time.toFixed(2)}) found`,u.element),!u.element){(ks||M())&&console.warn(`No HTML element found for ScrollMarker: ${u.name} (index ${m})`);continue}}catch(g){u.element=null,console.error("ScrollMarker selector is not valid: "+u.name+`
1529
1529
  `,g)}}u.element&&r.push(u)}r.length<=0&&n.querySelectorAll("[data-timeline-marker]").forEach(u=>{const m=u.getAttribute("data-timeline-marker"),g=parseFloat(m||"NaN");isNaN(g)?(M()||ks)&&console.warn('[ScrollFollow] data-timeline-marker attribute is not a valid number. Supported are numbers only (e.g. <div data-timeline-marker="0.5">)'):r.push({time:g,element:u})});const d=i.ViewTimeline;if(!d)!this._viewTimelineWarned&&(ks||M())&&(this._viewTimelineWarned=!0,console.warn("[ScrollFollow] ViewTimeline is not available on the target window \u2014 falling back to linear scroll. If this persists with useTopWindowScroll, the scroll-timeline polyfill must be present on the host page.")),nv.delete(e),r.length=0;else for(const u of r)u.element&&(u.timeline=new d({subject:u.element,axis:"block"}))}zo.length=0;let a=0;const l=1/60;let c=0;for(let h=0;h<r.length;h++){const d=r[h];if(!d.element)continue;const u=r[h+1],m=u?u.time-l:s;c+=1;const g=d.timeline;if(g){const y=_5(g),b=1-Math.abs(y-.5)*2,f=`marker${h}`;if(y>0&&y<=1){const _=d.time+(m-d.time)*y;zo.push({name:f,time:_,weight:b}),a+=b}else h===0&&y<=0?(zo.push({name:f,time:0,weight:1}),a+=1):h===r.length-1&&y>=1&&(zo.push({name:f,time:s,weight:1}),a+=1)}}if(zo.length<=0&&c<=0)e.time=t*s;else if(zo.length>0){let h=zo[0].time;if(zo.length>1)for(const d of zo){const u=d.weight/Math.max(1e-5,a),m=Math.abs(d.time-h);h+=m*u}this.damping<=0||this._firstUpdate?e.time=h:e.time=j.lerp(e.time,h,this.context.time.deltaTime/this.damping),Math.abs(e.time-h)>.001&&(this._needsUpdate=!0),ks&&this.context.time.frame%30===0&&console.log(`[ScrollFollow ] Timeline ${e.name}: ${h.toFixed(3)}`,zo.map(d=>`[${d.name} ${(d.weight*100).toFixed(0)}%]`).join(", "))}}}Ga([p([T,R])],Uo.prototype,"target"),Ga([p()],Uo.prototype,"damping"),Ga([p()],Uo.prototype,"invert"),Ga([p()],Uo.prototype,"htmlSelector"),Ga([p()],Uo.prototype,"mode"),Ga([Ve(),p()],Uo.prototype,"useTopWindowScroll"),Ga([p(re)],Uo.prototype,"changed");const nv=new WeakMap,zo=[],ov=new Array;let sv=!0;function Gk(o,e){return sv?(sv=!1,ov.length=0,e.querySelectorAll("[data-timeline-marker]").forEach((t,i)=>{ov[i]=t}),sv=!1,Gk(o,e)):ov[o]||null}function _5(o){if(!o.source)return 0;const e=o.currentTime,t=o.duration;let i=1;return(t.unit==="seconds"||t.unit==="percent")&&(i=t.value),e.unit==="seconds"?e.value/i:e.value/100}var Hk=Object.defineProperty,v5=Object.getOwnPropertyDescriptor,w5=(o,e,t)=>e in o?Hk(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,Ng=(o,e,t,i)=>{for(var n=i>1?void 0:i?v5(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&Hk(e,t,n),n},rv=(o,e,t)=>w5(o,typeof e!="symbol"?e+"":e,t);const kr=x("debugviewbox"),x5=new he(.5,.5,.5,.5);let bt=class extends T{referenceFieldOfView=-1;get mode(){return this._mode}set mode(o){o!==this._mode&&(this._mode=o,o==="once"&&(this._applyCount=0),(kr||this.debug)&&console.debug("[ViewBox] Set mode:",o))}_mode="continuous";debug=!1;onEnable(){(kr||this.debug||M())&&console.debug("[ViewBox] Using camera fov:",this.referenceFieldOfView),bt.instances.push(this),this._applyCount=0,this.removeUpdateCallback(),this.context.pre_render_callbacks.push(this.internalUpdate)}onDisable(){(kr||this.debug)&&console.debug("[ViewBox] Disabled");const o=bt.instances.indexOf(this);o!==-1&&bt.instances.splice(o,1),this._projectedBoxElement?.remove(),this.removeUpdateCallback()}removeUpdateCallback(){const o=this.context.pre_render_callbacks.indexOf(this.internalUpdate);o!==-1&&this.context.pre_render_callbacks.splice(o,1)}_applyCount=0;internalUpdate=()=>{if(this.context.isInXR||this.destroyed||!this.activeAndEnabled)return;if(bt.instances[bt.instances.length-1]!==this){(kr||this.debug)&&F.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,x5);return}(kr||this.debug)&&F.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,14540032,0,!0,this.gameObject.worldQuaternion);const o=this.context.mainCamera;if(!o||!(o instanceof me))return;if((this.referenceFieldOfView===void 0||this.referenceFieldOfView===-1)&&(this.referenceFieldOfView=o.fov,console.debug("[ViewBox] No referenceFieldOfView set, using camera fov:",this.referenceFieldOfView)),this.referenceFieldOfView===void 0||this.referenceFieldOfView<=0){(kr||this.debug)&&console.warn("[ViewBox] No valid referenceFieldOfView set, cannot adjust box size:",this.referenceFieldOfView);return}if(this._applyCount>=1&&this.mode==="once")return;this._applyCount++;const e=this.context.domWidth,t=this.context.domHeight;let i=e,n=t,s=1,r=1;const a=this.context.focusRectSize;a&&(i=a.width,n=a.height,s=e/i,r=t/n),bt._tempProjectionMatrix.copy(o.projectionMatrix),bt._tempProjectionMatrixInverse.copy(o.projectionMatrixInverse);const l=o.view,c=o.zoom,h=o.aspect,d=o.fov;o.view=null,o.zoom=1,o.fov=this.referenceFieldOfView,o.updateProjectionMatrix();const u=this.gameObject.worldPosition,m=this.gameObject.worldScale,g=o.worldPosition,y=g.distanceTo(u),b=Math.max(m.x,m.y,m.z),f=U(g).sub(u);if(y<b){(this.debug||kr)&&console.warn("[ViewBox] Moving camera out of bounds",y,"<",b);const G=U(f);G.y*=1e-8,G.normalize();const E=b-y,z=g.add(G.multiplyScalar(E));o.worldPosition=z.lerp(g,1-this.context.time.deltaTime)}const _=U(u);o.worldToLocal(_),o.lookAt(u),o.updateMatrixWorld();const w=this.referenceFieldOfView*Math.PI/180,S=2*Math.tan(w/2)*y,O=S*o.aspect,L=this.projectBoxIntoCamera(o,1),D=L.maxX-L.minX,W=L.maxY-L.minY,$=this.fit(D*o.aspect,W,O/s,S/r)/(S*.5),H=U(u);H.project(o),this.context.focusRectSettings.offsetX=H.x,this.context.focusRectSettings.offsetY=H.y,this.context.focusRectSettings.zoom=$,this.context.focusRect||this.context.setCameraFocusRect(this.context.domElement),o.view=l,o.zoom=c,o.aspect=h,o.fov=d,o.projectionMatrix.copy(bt._tempProjectionMatrix),o.projectionMatrixInverse.copy(bt._tempProjectionMatrixInverse)};fit(o,e,t,i){const n=t/o,s=i/e;return Math.min(n,s)}projectBoxIntoCamera(o,e){const t=.5*e,i=[U(-t,-t,-t),U(t,-t,-t),U(-t,t,-t),U(t,t,-t),U(-t,-t,t),U(t,-t,t),U(-t,t,t),U(t,t,t)];let n=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,r=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let l=0;l<i.length;l++){const c=i[l];c.applyMatrix4(this.gameObject.matrixWorld),c.project(o),c.x<n&&(n=c.x),c.x>s&&(s=c.x),c.y<r&&(r=c.y),c.y>a&&(a=c.y)}return kr&&(this._projectedBoxElement||(this._projectedBoxElement=document.createElement("div")),this._projectedBoxElement.parentElement!==this.context.domElement&&this.context.domElement.appendChild(this._projectedBoxElement),this._projectedBoxElement.style.position="fixed",this._projectedBoxElement.style.outline="2px dashed rgba(255,0,0,.5)",this._projectedBoxElement.style.left=(n*.5+.5)*this.context.domWidth+"px",this._projectedBoxElement.style.top=(-a*.5+.5)*this.context.domHeight+"px",this._projectedBoxElement.style.width=(s-n)*.5*this.context.domWidth+"px",this._projectedBoxElement.style.height=(a-r)*.5*this.context.domHeight+"px",this._projectedBoxElement.style.pointerEvents="none",this._projectedBoxElement.style.zIndex="1000"),{minX:n,maxX:s,minY:r,maxY:a}}_projectedBoxElement=null};rv(bt,"instances",[]),rv(bt,"_tempProjectionMatrix",new J),rv(bt,"_tempProjectionMatrixInverse",new J),Ng([p()],bt.prototype,"referenceFieldOfView",2),Ng([p()],bt.prototype,"mode",1),Ng([p()],bt.prototype,"debug",2),bt=Ng([iy],bt);var S5=Object.defineProperty,Ac=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&S5(e,t,n),n};class Os extends T{get activeAndEnabled(){return!0}side="none";controller=!0;hands=!1;controlVisibility=!0;useGripSpace=!1;resetTransformAfterXRSession=!0;_startPosition=new v;_startRotation=new B;_startScale=new v;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;const 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=U(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=U(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))}}Ac([p()],Os.prototype,"side"),Ac([p()],Os.prototype,"controller"),Ac([p()],Os.prototype,"hands"),Ac([p()],Os.prototype,"controlVisibility"),Ac([p()],Os.prototype,"useGripSpace"),Ac([p()],Os.prototype,"resetTransformAfterXRSession");function C5(){if(typeof window>"u"||!I.isNeedleAppClip())return null;const o=window.NeedleGoNativeScreenshot;return typeof o=="function"?o:null}function qk(o,e){const t=o.xr.getFrame();if(!t)return console.warn("No XRFrame available"),!1;const i=t.session.enabledFeatures;if(i&&!i.some(s=>s==="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.
1530
1530
 
1531
1531
  Example to request camera-access in global scope:
@@ -1533,7 +1533,7 @@ NeedleXRSession.onSessionRequestStart(evt => {
1533
1533
  evt.init.optionalFeatures = evt.init.optionalFeatures || [];
1534
1534
  evt.init.optionalFeatures.push('camera-access');
1535
1535
  });
1536
- `),M()&&ul("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene",{duration:3e5}),!1;const n=t.getViewerPose(o.xr.getReferenceSpace());if(n)for(const s of n.views)if("camera"in s&&s.camera){let r=o.xr.getBinding();if(r||(r=new XRWebGLBinding(t.session,o.getContext())),r){let a=null;if("getCameraImage"in r){P5(o,e);const l=o.properties.get(e);if(l)return a=r.getCameraImage(s.camera),l.__webglTexture=a,!0;console.warn("No texture properties found for target texture")}}else console.error(s.camera,o.xr)}else console.error("NO CAMERA IN VIEW");else console.error(o.xr.getReferenceSpace(),t);return!1}const Xk=new WeakMap;function P5(o,e){const t=Xk.get(e)||new WeakSet;if(t.has(o))return;t.add(o),Xk.set(e,t),console.debug("Initialize texture for camera feed");const i=new Ie,n=new In,s=new Fi;s.add(new V(n,i));const r=new me;i.map=e,o.render(s,r)}function k5(o,e,t,i="image/webp",n){return av({context:o,width:e,height:t,mimeType:i,camera:n})}function av(o){o||(o={});const{transparent:e=!1}=o;let{mimeType:t,context:i,width:n,height:s,camera:r}=o;if(!i&&(i=ce.Current,!i))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!r&&(r=i.mainCamera,!r))return console.error("No camera found"),null;const a=i.renderer,l=a.xr.enabled&&a.xr.isPresenting,c="type"in o&&(o.type==="share"||o.type==="blob"&&l)?C5():null;if(l&&i.currentFrameEvent!=Ee.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise($=>{ns(H=>{const G=av(o);$(G)},Ee.EarlyUpdate,{once:!0})});const h=a.domElement,d=h.width,u=h.height,m=h.style.width,g=h.style.height;n||(n=d),s||(s=u);const y=n,b=s;let f=window.devicePixelRatio||1,_=1;i.devicePixelRatio==="auto"||i.devicePixelRatio==="manual"?_=1:_=i.devicePixelRatio/window.devicePixelRatio,f*=_,n/=f,s/=f,n=Math.floor(n),s=Math.floor(s),a.xr.isPresenting&&a.xr.getFrame();const w=a.xr.enabled;a.xr.enabled=!1,a.xr.isPresenting=!1,h.style.width=`${n}px`,h.style.height=`${s}px`;const S=a.getRenderTarget(),O=a.getClearColor(new oe),L=a.getClearAlpha(),D=i.scene.background,W="aspect"in r?r.aspect:null;try{const $=o.render_events!==!1,H=new Array;$&&(Ul(i.scene,gi,H),H.forEach(K=>{if(K?.onBeforeRender(),K.isInstancingActive&&K.instances)for(let ne=0;ne<K.instances?.length;ne++){const ae=K.instances[ne];So(ae.object,!0)}})),e&&(i.scene.background=null,a.setClearColor(0,0)),o.background&&(i.scene.background=null,a.setClearColor(o.background),o.background instanceof he&&a.setClearAlpha(o.background.a)),e&&a.setClearAlpha(0),a.setSize(n,s,!1),"cam"in r&&(r=r.threeCamera),r instanceof me&&(r.aspect=n/s,r.updateProjectionMatrix());const G="type"in o&&o.type==="texture";let E=null;G&&(E=new ro(n,s,{wrapS:Hv,wrapT:Hv,format:1023}),a.setRenderTarget(E));let z=h;if(l?(E&&console.error('Taking XR screenshots with { type: "texture" } is currently not supported.'),z=Qd.compositeWithCameraImage({width:y,height:b,scene:i.scene,camera:r,renderer:a,skipCameraImage:c!=null})):i.renderNow(r||null),r instanceof me&&W!=null&&(r.aspect=W,r.updateProjectionMatrix()),$&&H.forEach(K=>K.onAfterRender()),!t&&"download_filename"in o&&o.download_filename)switch(o.download_filename.split(".").pop()?.toLowerCase()){case"png":t="image/png";break;case"jpg":case"jpeg":t="image/jpeg";break;case"webp":t="image/webp";break}if(e&&o.trim===!0){const K=M5(z);K&&(z=K)}if("type"in o){if(o.type==="texture")return E?(o.target&&(o.target.image=E?.texture.image,o.target.needsUpdate=!0),E.texture.offset.set(0,-1),E.texture.needsUpdate=!0,E.texture):(console.error("No target texture found"),null);if(o.type==="blob"){if(c){const K=z;return c({image:z.toDataURL("image/png"),action:"return",mimeType:t}).then(ne=>ne?.image?O5(ne.image):null).catch(ne=>(console.warn("Native screenshot failed, falling back to canvas capture",ne),new Promise(ae=>K.toBlob(ae,t))))}return new Promise((K,ne)=>{z.toBlob(ae=>{K(ae)},t)})}else if(o.type==="share")return c?c({image:z.toDataURL("image/png"),action:"share",title:"title"in o?o.title:void 0,text:"text"in o?o.text:void 0,url:"url"in o?o.url:void 0}).then(K=>({blob:null,shared:K?.shared===!0})).catch(K=>(console.warn("Native share failed",K),{blob:null,shared:!1})):new Promise((K,ne)=>{z.toBlob(ae=>{if(ae&&"share"in navigator){let te="file_type"in o&&o.file_type||t;t||(te="image/png");const _e=te?.split("/")[1]||"png",Qt=new File([ae],"filename"in o?o.filename||`screenshot.${_e}`:`screenshot.${_e}`,{type:te});return navigator.share({title:"title"in o?o.title:void 0,text:"text"in o?o.text:void 0,url:"url"in o?o.url:void 0,files:[Qt]}).catch(tl=>{console.warn("User cancelled share",tl.message)}).finally(()=>{K({blob:ae,shared:!0})})}return{blob:ae,shared:!1}},t)})}const Y=z.toDataURL(t);if("download_filename"in o&&o.download_filename){let K=o.download_filename;if(I.isMobileDevice()&&typeof window<"u"){const ne=K+"_screenshots",ae=K.split("."),te=ae.pop()?.toLowerCase();let _e=0;localStorage.getItem(ne)&&(_e=parseInt(sessionStorage.getItem(ne)||"0")),_e>0&&(K=`${ae.join()}-${_e}.${te}`),_e+=1,sessionStorage.setItem(ne,_e.toString())}Qk(Y,K)}return Y}finally{a.setRenderTarget(S),i.scene.background=D;const $=a.getPixelRatio()||1;a.setSize(d/$,u/$,!1),h.style.width=m,h.style.height=g,a.setClearColor(O,L),W!=null&&r instanceof me&&(r.aspect=W,r.updateProjectionMatrix()),a.xr.enabled=w,a.xr.isPresenting=l,l||i.updateSize(!0)}return null}function O5(o){return fetch(o).then(e=>e.blob()).catch(()=>null)}function M5(o){if(!("document"in globalThis))return null;const e=document.createElement("canvas");e.width=o.width,e.height=o.height;const t=e.getContext("2d");if(!t)return null;t.drawImage(o,0,0);const i=e.width,n=e.height,s=t.getImageData(0,0,i,n).data;let r=n,a=i,l=0,c=0;for(let g=0;g<n;g++)for(let y=0;y<i;y++){const b=(g*i+y)*4;s[b+3]!==0&&(y<a&&(a=y),y>c&&(c=y),g<r&&(r=g),g>l&&(l=g))}const h=c-a+1,d=l-r+1,u=document.createElement("canvas"),m=u.getContext("2d");return m?(u.width=h,u.height=d,m.drawImage(e,a,r,h,d,0,0,h,d),u):null}let Xd=null;function Qk(o,e){if(o){if(!o.startsWith("data:image")){console.error("Can not save image: Data url is not an image",o);return}Xd||(Xd=document.createElement("a")),Xd.href=o,Xd.download=e,Xd.click()}}var Qd;(o=>{let e=null,t=null,i=null,n=null,s=null;function r(c){const{renderer:h,width:d,height:u}=c,m=h.xr.enabled,g=h.getRenderTarget(),y=h.autoClear,b=d,f=u,_=d/u;(!i||i.width!==b||i.height!==f)&&(i??=new ro(b,f,{colorSpace:Yo}),i.width=b,i.height=f,i.samples=4,i.texture.repeat.y=-1,i.texture.offset.y=1),(!s||s.width!==b||s.height!==f)&&(s=document.createElement("canvas"),s.width=b,s.height=f,s.style.position="fixed",s.style.top="0px",s.style.right="0px",s.style.width="300px",s.style.height=`${300/_}px`,s.style.zIndex="1000",s.style.pointerEvents="none",s.style.opacity="1.0",s.style.willChange="contents"),e||(e=l({defines:{DECODE_VIDEO_TEXTURE:!0}})),t||(t=l({defines:{PREMULTIPLY_ALPHA:!0}})),n||(n=new Pe),h.xr.updateCamera(c.camera),h.xr.enabled=!1,h.autoClear=!1,h.clear(),h.setSize(b,f,!1),h.setRenderTarget(i);const w=h.getClearColor(new oe),S=h.getClearAlpha();if(h.setClearColor(0,0),h.clear(),h.setClearColor(w,S),!c.skipCameraImage){qk(c.renderer,n)||console.error("Could not update texture from XR frame");const L=P.findObjectOfType(Yd);L?L.setTexture(n):(e.setTexture(n),h.render(e,c.camera))}h.clearDepth(),h.setSize(b,f,!1),h.render(c.scene,c.camera),h.setRenderTarget(null),t.setTexture(i.texture),h.render(t,c.camera);const O=s.getContext("2d");return O.clearRect(0,0,s.width,s.height),O.drawImage(h.domElement,0,0,s.width,s.height),h.setRenderTarget(g),h.xr.enabled=m,h.autoClear=y,s}o.compositeWithCameraImage=r;const a=`
1536
+ `),M()&&ul("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene",{duration:3e5}),!1;const n=t.getViewerPose(o.xr.getReferenceSpace());if(n)for(const s of n.views)if("camera"in s&&s.camera){let r=o.xr.getBinding();if(r||(r=new XRWebGLBinding(t.session,o.getContext())),r){let a=null;if("getCameraImage"in r){P5(o,e);const l=o.properties.get(e);if(l)return a=r.getCameraImage(s.camera),l.__webglTexture=a,!0;console.warn("No texture properties found for target texture")}}else console.error(s.camera,o.xr)}else console.error("NO CAMERA IN VIEW");else console.error(o.xr.getReferenceSpace(),t);return!1}const Xk=new WeakMap;function P5(o,e){const t=Xk.get(e)||new WeakSet;if(t.has(o))return;t.add(o),Xk.set(e,t),console.debug("Initialize texture for camera feed");const i=new Ie,n=new In,s=new Fi;s.add(new V(n,i));const r=new me;i.map=e,o.render(s,r)}function k5(o,e,t,i="image/webp",n){return av({context:o,width:e,height:t,mimeType:i,camera:n})}function av(o){o||(o={});const{transparent:e=!1}=o;let{mimeType:t,context:i,width:n,height:s,camera:r}=o;if(!i&&(i=ce.Current,!i))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!r&&(r=i.mainCamera,!r))return console.error("No camera found"),null;const a=i.renderer,l=a.xr.enabled&&a.xr.isPresenting,c="type"in o&&(o.type==="share"||o.type==="blob"&&l)?C5():null;if(l&&i.currentFrameEvent!=Ee.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise($=>{ns(H=>{const G=av(o);$(G)},Ee.EarlyUpdate,{once:!0})});const h=a.domElement,d=h.width,u=h.height,m=h.style.width,g=h.style.height;n||(n=d),s||(s=u);const y=n,b=s;let f=window.devicePixelRatio||1,_=1;i.devicePixelRatio==="auto"||i.devicePixelRatio==="manual"?_=1:_=i.devicePixelRatio/window.devicePixelRatio,f*=_,n/=f,s/=f,n=Math.floor(n),s=Math.floor(s),a.xr.isPresenting&&a.xr.getFrame();const w=a.xr.enabled;a.xr.enabled=!1,a.xr.isPresenting=!1,h.style.width=`${n}px`,h.style.height=`${s}px`;const S=a.getRenderTarget(),O=a.getClearColor(new oe),L=a.getClearAlpha(),D=i.scene.background,W="aspect"in r?r.aspect:null;try{const $=o.render_events!==!1,H=new Array;$&&(Ul(i.scene,gi,H),H.forEach(K=>{if(K?.onBeforeRender(),K.isInstancingActive&&K.instances)for(let ne=0;ne<K.instances?.length;ne++){const ae=K.instances[ne];So(ae.object,!0)}})),e&&(i.scene.background=null,a.setClearColor(0,0)),o.background&&(i.scene.background=null,a.setClearColor(o.background),o.background instanceof he&&a.setClearAlpha(o.background.a)),e&&a.setClearAlpha(0),a.setSize(n,s,!1),"cam"in r&&(r=r.threeCamera),r instanceof me&&(r.aspect=n/s,r.updateProjectionMatrix());const G="type"in o&&o.type==="texture";let E=null;G&&(E=new ro(n,s,{wrapS:Hv,wrapT:Hv,format:1023}),a.setRenderTarget(E));let z=h;if(l?(E&&console.error('Taking XR screenshots with { type: "texture" } is currently not supported.'),z=Qd.compositeWithCameraImage({width:y,height:b,scene:i.scene,camera:r,renderer:a,skipCameraImage:c!=null})):i.renderNow(r||null),r instanceof me&&W!=null&&(r.aspect=W,r.updateProjectionMatrix()),$&&H.forEach(K=>K.onAfterRender()),!t&&"download_filename"in o&&o.download_filename)switch(o.download_filename.split(".").pop()?.toLowerCase()){case"png":t="image/png";break;case"jpg":case"jpeg":t="image/jpeg";break;case"webp":t="image/webp";break}if(e&&o.trim===!0){const K=M5(z);K&&(z=K)}if("type"in o){if(o.type==="texture")return E?(o.target&&(o.target.image=E?.texture.image,o.target.needsUpdate=!0),E.texture.offset.set(0,-1),E.texture.needsUpdate=!0,E.texture):(console.error("No target texture found"),null);if(o.type==="blob"){if(c){const K=z;return c({image:z.toDataURL("image/png"),action:"return",mimeType:t}).then(ne=>ne?.image?O5(ne.image):null).catch(ne=>(console.warn("Native screenshot failed, falling back to canvas capture",ne),new Promise(ae=>K.toBlob(ae,t))))}return new Promise((K,ne)=>{z.toBlob(ae=>{K(ae)},t)})}else if(o.type==="share")return c?c({image:z.toDataURL("image/png"),action:"share",title:"title"in o?o.title:void 0,text:"text"in o?o.text:void 0,url:"url"in o?o.url:void 0}).then(K=>({blob:null,shared:K?.shared===!0})).catch(K=>(console.warn("Native share failed",K),{blob:null,shared:!1})):new Promise((K,ne)=>{z.toBlob(ae=>{if(ae&&"share"in navigator){let te="file_type"in o&&o.file_type||t;t||(te="image/png");const _e=te?.split("/")[1]||"png",Qt=new File([ae],"filename"in o?o.filename||`screenshot.${_e}`:`screenshot.${_e}`,{type:te});return navigator.share({title:"title"in o?o.title:void 0,text:"text"in o?o.text:void 0,url:"url"in o?o.url:void 0,files:[Qt]}).catch(tl=>{console.warn("User cancelled share",tl.message)}).finally(()=>{K({blob:ae,shared:!0})})}return{blob:ae,shared:!1}},t)})}const Y=z.toDataURL(t);if("download_filename"in o&&o.download_filename){let K=o.download_filename;if(I.isMobileDevice()&&typeof window<"u"){const ne=K+"_screenshots",ae=K.split("."),te=ae.pop()?.toLowerCase();let _e=0;localStorage.getItem(ne)&&(_e=parseInt(sessionStorage.getItem(ne)||"0")),_e>0&&(K=`${ae.join()}-${_e}.${te}`),_e+=1,sessionStorage.setItem(ne,_e.toString())}Qk(Y,K)}return Y}finally{a.setRenderTarget(S),i.scene.background=D;const $=a.getPixelRatio()||1;a.setSize(d/$,u/$,!1),h.style.width=m,h.style.height=g,a.setClearColor(O,L),W!=null&&r instanceof me&&(r.aspect=W,r.updateProjectionMatrix()),a.xr.enabled=w,a.xr.isPresenting=l,l||i.updateSize(!0)}return null}function O5(o){return fetch(o).then(e=>e.blob()).catch(()=>null)}function M5(o){if(!("document"in globalThis))return null;const e=document.createElement("canvas");e.width=o.width,e.height=o.height;const t=e.getContext("2d");if(!t)return null;t.drawImage(o,0,0);const i=e.width,n=e.height,s=t.getImageData(0,0,i,n).data;let r=n,a=i,l=0,c=0;for(let g=0;g<n;g++)for(let y=0;y<i;y++){const b=(g*i+y)*4;s[b+3]!==0&&(y<a&&(a=y),y>c&&(c=y),g<r&&(r=g),g>l&&(l=g))}const h=c-a+1,d=l-r+1,u=document.createElement("canvas"),m=u.getContext("2d");return m?(u.width=h,u.height=d,m.drawImage(e,a,r,h,d,0,0,h,d),u):null}let Xd=null;function Qk(o,e){if(o){if(!o.startsWith("data:image")){console.error("Can not save image: Data url is not an image",o);return}Xd||(Xd=document.createElement("a")),Xd.href=o,Xd.download=e,Xd.click()}}var Qd;(o=>{let e=null,t=null,i=null,n=null,s=null;function r(c){const{renderer:h,width:d,height:u}=c,m=h.xr.enabled,g=h.getRenderTarget(),y=h.autoClear,b=d,f=u,_=d/u;(!i||i.width!==b||i.height!==f)&&(i??=new ro(b,f,{colorSpace:Yo}),i.width=b,i.height=f,i.samples=4,i.texture.repeat.y=-1,i.texture.offset.y=1),(!s||s.width!==b||s.height!==f)&&(s=document.createElement("canvas"),s.width=b,s.height=f,s.style.position="fixed",s.style.top="0px",s.style.right="0px",s.style.width="300px",s.style.height=`${300/_}px`,s.style.zIndex="1000",s.style.pointerEvents="none",s.style.opacity="1.0",s.style.willChange="contents"),e||(e=l({defines:{DECODE_VIDEO_TEXTURE:!0}})),t||(t=l({defines:{PREMULTIPLY_ALPHA:!0}})),n||(n=new ke),h.xr.updateCamera(c.camera),h.xr.enabled=!1,h.autoClear=!1,h.clear(),h.setSize(b,f,!1),h.setRenderTarget(i);const w=h.getClearColor(new oe),S=h.getClearAlpha();if(h.setClearColor(0,0),h.clear(),h.setClearColor(w,S),!c.skipCameraImage){qk(c.renderer,n)||console.error("Could not update texture from XR frame");const L=P.findObjectOfType(Yd);L?L.setTexture(n):(e.setTexture(n),h.render(e,c.camera))}h.clearDepth(),h.setSize(b,f,!1),h.render(c.scene,c.camera),h.setRenderTarget(null),t.setTexture(i.texture),h.render(t,c.camera);const O=s.getContext("2d");return O.clearRect(0,0,s.width,s.height),O.drawImage(h.domElement,0,0,s.width,s.height),h.setRenderTarget(g),h.xr.enabled=m,h.autoClear=y,s}o.compositeWithCameraImage=r;const a=`
1537
1537
  uniform sampler2D t2D;
1538
1538
  varying vec2 vUv;
1539
1539
 
@@ -1558,7 +1558,7 @@ void main() {
1558
1558
 
1559
1559
  #endif
1560
1560
  }
1561
- `;function l(c){const h=c?.material||new oo({name:"BackgroundMaterial",uniforms:qv.clone(Su.background.uniforms),vertexShader:Su.background.vertexShader,fragmentShader:a,defines:c?.defines,side:Us,depthTest:!1,depthWrite:!1,fog:!1});Object.defineProperty(h,"map",{get:function(){return this.threeTexture}});const d=new V(new In(2,2),h);return Eu(d,!1),d.geometry.deleteAttribute("normal"),d.renderOrder=-1e6,d.setTexture=function(u){h.uniforms.t2D.value=u},d}o.makeFullscreenPlane=l})(Qd||(Qd={}));var R5=Object.defineProperty,T5=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&R5(e,t,n),n};const Yk=x("debugarcamera");class Yd extends T{onBeforeXR(e,t){e==="immersive-ar"&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("camera-access"),Yk&&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();const t=this.context.pre_render_callbacks.indexOf(this.preRender);t>=0&&this.context.pre_render_callbacks.splice(t,1)}backgroundTint=new he(1,1,1,1);get background(){return this.backgroundPlane}backgroundPlane;threeTexture;forceTextureInitialization=function(){const e=new Ie,t=new In,i=new Fi;i.add(new V(t,e));const n=new me;return function(s,r){e.map=r,s.render(i,n),Yk&&console.warn("Force texture initialization")}}();preRender=()=>{if(!(!this||!this.gameObject)&&this.context.renderer.xr.getFrame()){if(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new Pe,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0){const e=this.backgroundTint;this.backgroundPlane=Qd.makeFullscreenPlane({material:new oo({name:"BackgroundMaterial",uniforms:{...qv.clone(Su.background.uniforms),tint:{value:new ve(e.r,e.g,e.b,e.a)}},vertexShader:Su.background.vertexShader,fragmentShader:E5,side:Bi,depthTest:!1,depthWrite:!1,fog:!1})})}this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.backgroundPlane.material instanceof oo&&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"&&(qk(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)}}T5([p(he)],Yd.prototype,"backgroundTint");const E5=`
1561
+ `;function l(c){const h=c?.material||new oo({name:"BackgroundMaterial",uniforms:qv.clone(Su.background.uniforms),vertexShader:Su.background.vertexShader,fragmentShader:a,defines:c?.defines,side:Us,depthTest:!1,depthWrite:!1,fog:!1});Object.defineProperty(h,"map",{get:function(){return this.threeTexture}});const d=new V(new In(2,2),h);return Eu(d,!1),d.geometry.deleteAttribute("normal"),d.renderOrder=-1e6,d.setTexture=function(u){h.uniforms.t2D.value=u},d}o.makeFullscreenPlane=l})(Qd||(Qd={}));var R5=Object.defineProperty,T5=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&R5(e,t,n),n};const Yk=x("debugarcamera");class Yd extends T{onBeforeXR(e,t){e==="immersive-ar"&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("camera-access"),Yk&&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();const t=this.context.pre_render_callbacks.indexOf(this.preRender);t>=0&&this.context.pre_render_callbacks.splice(t,1)}backgroundTint=new he(1,1,1,1);get background(){return this.backgroundPlane}backgroundPlane;threeTexture;forceTextureInitialization=function(){const e=new Ie,t=new In,i=new Fi;i.add(new V(t,e));const n=new me;return function(s,r){e.map=r,s.render(i,n),Yk&&console.warn("Force texture initialization")}}();preRender=()=>{if(!(!this||!this.gameObject)&&this.context.renderer.xr.getFrame()){if(!this.threeTexture&&this.context.renderer&&(this.threeTexture=new ke,this.forceTextureInitialization(this.context.renderer,this.threeTexture)),this.backgroundPlane===void 0){const e=this.backgroundTint;this.backgroundPlane=Qd.makeFullscreenPlane({material:new oo({name:"BackgroundMaterial",uniforms:{...qv.clone(Su.background.uniforms),tint:{value:new ve(e.r,e.g,e.b,e.a)}},vertexShader:Su.background.vertexShader,fragmentShader:E5,side:Bi,depthTest:!1,depthWrite:!1,fog:!1})})}this.backgroundPlane.parent!==this.scene&&this.scene.add(this.backgroundPlane),this.backgroundPlane.material instanceof oo&&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"&&(qk(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)}}T5([p(he)],Yd.prototype,"backgroundTint");const E5=`
1562
1562
  uniform sampler2D t2D;
1563
1563
  uniform vec4 tint;
1564
1564
 
@@ -1857,4 +1857,4 @@ Needle Engine: finished loading `+i+`
1857
1857
  ---------------------------------
1858
1858
  \u2022 `+r.passes.map(d=>d.name||d.constructor.name+"*").join(`
1859
1859
  \u2022 `)+`
1860
- `),Li&&this._onCreateEffectsDebug(this._composer,s)}createPassForMergeableEffects(e,t,i,n){if(e.length>0){const s=new A.POSTPROCESSING.MODULE.EffectPass(i,...e);s.name=e.map(r=>r.name).join(", "),s.mainScene=n,s.enabled=!0,s.renderToScreen=!1,t.addPass(s),e.length=0}}handleDevicePixelRatio(){typeof this.context.devicePixelRatio=="number"&&this.context.requestSizeUpdate()}_menuEntry=null;_passIndices=null;_onCreateEffectsDebug(e,t){if(Li==="passes"){const i=new A.POSTPROCESSING.MODULE.DepthEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new A.POSTPROCESSING.MODULE.EffectPass(t,i);if(n.name="Depth Effect Pass",n.enabled=!1,e.passes.push(n),this._passIndices!==null){const r=[e.passes[0]];this._passIndices.length>0&&r.push(...this._passIndices.filter(a=>a!==0).map(a=>e.passes[a]).filter(a=>a)),r.length>0&&console.log("[PostProcessing] Passes (selected) \u2192",r),e.passes.length=0;for(const a of r)a.enabled=!0,a.renderToScreen=!1,e.addPass(a)}const s=this.context.menu;if(s&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const r=document.createElement("select");r.multiple=!0;const a=document.createElement("option");a.innerText="Final Output",a.value="-1",r.appendChild(a);for(const l of e.passes){const c=document.createElement("option");c.innerText=l.name,c.value=`${e.passes.indexOf(l)}`,c.title=l.name,r.appendChild(c)}s.appendChild(r),this._menuEntry=r,r.addEventListener("change",()=>{const l=Array.from(r.selectedOptions).map(c=>parseInt(c.value));l.length===1&&l[0]===-1?this._passIndices=null:this._passIndices=l,this.applyEffects(this.context)})}}}}const d4=Object.freeze(Object.defineProperty({__proto__:null,PostProcessingHandler:Gc},Symbol.toStringTag,{value:"Module"}));class nf{_name;_tracks=[];_currentTrack=null;_pendingSignals=[];_idProvider;constructor(e,t){this._name=e,this._idProvider=new _t(t??Date.now())}static create(e,t){return new nf(e??"Timeline",t)}animationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Animation,t??null),this}audioTrack(e,t,i){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Audio,t??null),this._currentTrack.volume=i,this}activationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Activation,t??null),this}controlTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Control,null),this}signalTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Signal,t??null),this}markerTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Marker,null),this}clip(e,t){if(!this._currentTrack)throw new Error("TimelineBuilder: .clip() must be called after a track method (e.g. .animationTrack())");this.commitInlineTracks();const i=this._currentTrack;switch(i.type){case Me.Animation:{let n;if(e instanceof Yt)n=e;else{const h=Array.isArray(e)?e:[e],d=i.outputs[0],u=d instanceof R?d:d!=null&&"gameObject"in d?d.gameObject:void 0;n=Nh(h,u)}const s=t??{},r=s.duration??n.duration,a=s.start??i.cursor,l=a+r,c={start:a,end:l,duration:r,timeScale:s.speed??1,clipIn:s.clipIn??0,easeInDuration:s.easeIn??0,easeOutDuration:s.easeOut??0,preExtrapolationMode:s.preExtrapolation??ht.None,postExtrapolationMode:s.postExtrapolation??ht.None,reversed:s.reversed,asset:{clip:n,loop:s.loop??!1,duration:n.duration,removeStartOffset:s.removeStartOffset??!1}};i.clips.push(c),i.cursor=l;break}case Me.Audio:{const n=e,s=t??{},r=s.duration,a=s.start??i.cursor,l=a+r,c={start:a,end:l,duration:r,timeScale:s.speed??1,clipIn:0,easeInDuration:s.easeIn??0,easeOutDuration:s.easeOut??0,preExtrapolationMode:ht.None,postExtrapolationMode:ht.None,asset:{clip:n,loop:s.loop??!1,volume:s.volume??1}};i.clips.push(c),i.cursor=l;break}case Me.Activation:{const n=e,s=n.start??i.cursor,r=s+n.duration,a={start:s,end:r,duration:n.duration,timeScale:1,clipIn:0,easeInDuration:n.easeIn??0,easeOutDuration:n.easeOut??0,preExtrapolationMode:ht.None,postExtrapolationMode:ht.None,asset:{}};i.clips.push(a),i.cursor=r;break}case Me.Control:{const n=e,s=t??{},r=s.start??i.cursor,a=s.duration,l=r+a,c={start:r,end:l,duration:a,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:ht.None,postExtrapolationMode:ht.None,asset:{sourceObject:n,controlActivation:s.controlActivation??!0,updateDirector:s.updateDirector??!0}};i.clips.push(c),i.cursor=l;break}default:throw new Error(`TimelineBuilder: .clip() is not supported on track type "${i.type}"`)}return this}marker(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .marker() must be called after a track method");if(this._currentTrack.type!==Me.Signal&&this._currentTrack.type!==Me.Marker)throw new Error(`TimelineBuilder: .marker() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n={type:Kh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:t};return this._currentTrack.markers.push(n),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}signal(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .signal() must be called after a track method");if(this._currentTrack.type!==Me.Signal&&this._currentTrack.type!==Me.Marker)throw new Error(`TimelineBuilder: .signal() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n=this._idProvider.generateUUID(),s=this._tracks.indexOf(this._currentTrack),r={type:Kh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:n};return this._currentTrack.markers.push(r),this._pendingSignals.push({trackIndex:s,guid:n,callback:t}),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}muted(e=!0){if(!this._currentTrack)throw new Error("TimelineBuilder: .muted() must be called after a track method");return this._currentTrack.muted=e,this}track(e,t,i,n){if(!this._currentTrack)throw new Error("TimelineBuilder: .track() must be called after .animationTrack()");if(this._currentTrack.type!==Me.Animation)throw new Error("TimelineBuilder: .track() is only supported on animation tracks");return this._currentTrack.inlineTracks.push(Rb(e,t,i,n)),this}build(){this.commitInlineTracks();const e=this._tracks.map(t=>{const i={name:t.name,type:t.type,muted:t.muted,outputs:t.outputs};return t.clips.length>0&&(i.clips=t.clips),t.markers.length>0&&(i.markers=t.markers),t.volume!==void 0&&(i.volume=t.volume),t.trackOffset!==void 0&&(i.trackOffset=t.trackOffset),i});return{name:this._name,tracks:e}}install(e){const t=this.build();if(this._pendingSignals.length>0){const i=e.gameObject;let n=P.getComponent(i,pa);n||(n=P.addComponent(i,pa)),n.events||(n.events=[]);for(const s of this._pendingSignals){const r=new Yh;r.guid=s.guid;const a=new Wl;a.signal=r,a.reaction=new re([s.callback]),n.events.push(a);const l=t.tracks[s.trackIndex];l&&!l.outputs.includes(n)&&l.outputs.push(n)}}return e.playableAsset=t,t}pushTrack(e,t,i){const n={name:e,type:t,muted:!1,outputs:i?[i]:[],clips:[],markers:[],cursor:0,inlineTracks:[]};return this._tracks.push(n),n}commitInlineTracks(){if(!this._currentTrack||this._currentTrack.inlineTracks.length===0)return;const e=this._currentTrack,t=e.outputs[0],i=t instanceof R?t:t!=null&&"gameObject"in t?t.gameObject:void 0,n=Nh(e.inlineTracks,i),s=e.cursor,r=n.duration,a={start:s,end:s+r,duration:r,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:ht.None,postExtrapolationMode:ht.None,asset:{clip:n,loop:!1,duration:n.duration,removeStartOffset:!1}};e.clips.push(a),e.cursor=s+r,e.inlineTracks=[]}}class vO{}const u4=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:be,ActionCollection:jP,ActionModel:ji,AlignmentConstraint:od,Animation:Zt,AnimationBuilder:Jg,AnimationCurve:Rd,AnimationExtension:Vm,Animator:Et,AnimatorController:_o,Antialiasing:Id,Attractor:Sc,AudioExtension:Ya,AudioListener:cs,AudioSource:Yi,Avatar:cr,AvatarMarker:wt,AxesHelper:Gl,AxisRotationConstraint:s0,BaseUIComponent:kn,BasicIKConstraint:Kb,BehaviorExtension:t_,BehaviorModel:qt,BloomEffect:vg,BoxCollider:hm,BoxGizmo:Ta,BoxHelperComponent:Xt,Button:Ps,CallInfo:Wn,Camera:pi,CameraTargetReachedEvent:Qh,Canvas:gc,CanvasGroup:gr,CapsuleCollider:hs,ChangeMaterialOnClick:W0,ChangeTransformOnClick:Pa,CharacterController:fa,CharacterControllerInput:us,ChromaticAberration:Ld,ClickThrough:Ug,ColorAdjustments:vr,ColorBySpeedModule:wc,ColorOverLifetimeModule:pg,ContactShadows:sd,CursorFollow:Va,CustomBranding:Ma,Deletable:i0,DeleteBox:Ir,DepthOfField:Jn,DeviceFlag:dm,DocumentExtension:_O,DragControls:va,DragProfile:fm,DropListener:gs,Duplicatable:O0,EffectWrapper:Dd,EmissionModule:xs,EmphasizeOnClick:rc,EnvironmentScene:nm,EventList:re,EventListEvent:Tb,EventSystem:wi,EventTrigger:Lm,FieldWithDefault:aP,FixedJoint:x_,FixedRotationAxesConstraint:DC,Fog:fc,GaussianSplat:Ra,GltfExport:A0,GltfExportBox:T0,GrabPointPlaneConstraint:ad,Gradient:Aa,Graphic:Sd,GraphicRaycaster:Qp,GridHelper:yc,GridLayoutGroup:h_,GridSnapConstraint:um,GroundProjectedEnv:wo,GroupActionModel:Ca,HideOnStart:Rn,HingeJoint:Md,HorizontalLayoutGroup:c_,get HoverAnimation(){return Bo},Image:Rc,InheritVelocityModule:T_,InputField:J_,InstanceHandle:Ja,InstancingHandler:Ka,Interactable:t0,KeepRotationConstraint:pm,KeepScaleConstraint:IC,Keyframe:Ai,LODGroup:rg,LODModel:_c,Light:$t,LimitVelocityOverLifetimeModule:Ct,LogStats:e0,LookAt:ev,LookAtConstraint:ha,MainModule:ni,MaskableGraphic:Cd,MeshCollider:sr,MeshRenderer:cd,MinMaxCurve:Z,MinMaxGradient:Ia,NeedleMenu:Ro,NestedGltf:vc,Networking:O_,NoiseModule:Se,ObjectRaycaster:pn,OffsetConstraint:Ea,OpenURL:Tc,OrbitControls:fe,Outline:pc,Padding:Oa,ParticleBurst:ug,ParticleSubEmitter:E_,ParticleSystem:Ad,ParticleSystemRenderer:_n,PhysicsExtension:i_,PixelationEffect:jd,PlaneHeightLockConstraint:r0,PlayAnimationOnClick:ud,PlayAudioOnClick:lr,PlayableDirector:Vl,PlayerColor:$c,PointerEventData:hu,PostProcessingHandler:Gc,PreliminaryAction:ac,PreliminaryTrigger:pd,RawImage:jg,Rect:KP,RectTransform:Kn,ReflectionProbe:ps,RegisteredAnimationInfo:Lr,RemoteSkybox:Qb,Renderer:gi,RendererLightmap:C0,Rigidbody:rt,RotationBySpeedModule:bn,RotationOverLifetimeModule:Zn,ScaleLimitConstraint:n0,SceneSwitcher:at,ScreenCapture:wr,ScreenSpaceAmbientOcclusion:Ss,ScreenSpaceAmbientOcclusionN8:eo,ScrollFollow:Uo,SeeThrough:q_,SetActiveOnClick:V0,ShadowCatcher:Nd,ShapeModule:R_,SharpeningEffect:Bd,SignalAsset:Yh,SignalReceiver:pa,SignalReceiverEvent:Wl,SignalTrackHandler:Jh,Size:YP,SizeBySpeedModule:Ii,SizeOverLifetimeModule:La,SkinnedMeshRenderer:P0,SmoothFollow:Rg,SnapToSurfaceConstraint:gm,SpatialGrabRaycaster:Qa,SpatialHtml:Hd,SpatialTrigger:Tg,SpatialTriggerReceiver:jo,SpectatorCamera:Eg,SphereCollider:Hl,SplineContainer:Na,SplineData:Fo,SplineWalker:xn,Sprite:ys,SpriteData:cc,SpriteRenderer:Ri,SpriteSheet:lc,SubEmitterSystem:yg,SyncedCamera:X_,SyncedRoom:to,SyncedTransform:Gn,TapGestureTrigger:H0,TeleportTarget:Km,TestRunner:Y_,TestSimulateUserData:K_,Text:ii,TextBuilder:a_,TextExtension:ig,TextureSheetAnimationModule:oi,TiltShiftEffect:Lo,TimelineActivationTrack:em,TimelineAnimationTrack:Zh,TimelineAudioTrack:Ds,TimelineBuilder:nf,TimelineControlTrack:tm,TimelineMarkerTrack:Jp,ToneMappingEffect:ja,TrailModule:qe,TransformData:Ze,TransformGizmo:$a,TriggerBuilder:ei,TriggerModel:Rr,UIRaycastUtils:Bb,UIRootComponent:vd,USDZExporter:Ao,USDZText:mc,USDZUIExtension:p_,UsageMarker:rd,VariantAction:N0,VelocityOverLifetimeModule:tt,VerticalLayoutGroup:l_,VideoPlayer:kt,get ViewBox(){return bt},Vignette:Ua,VisibilityAction:md,Voip:Cs,Volume:Ud,VolumeParameter:N,VolumeProfile:bg,WebARCameraBackground:Yd,WebARSessionRoot:Tn,WebXR:Zm,WebXRImageTracking:Lc,WebXRImageTrackingModel:Sn,WebXRPlaneTracking:Rs,WebXRTrackedImage:Wc,XRControllerFollow:Os,XRControllerModel:bs,XRControllerMovement:Ji,XRFlag:Qn,XRRig:$g,XRState:vi,__Ignore:vO},Symbol.toStringTag,{value:"Module"}));var vv;(o=>{function e(t,i=!1,n=.75){const s=new Na,r=1-j.clamp(n,0,1);return t.forEach((a,l)=>{const c=new v;l<t.length-1?c.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&c.subVectors(t[0],a).normalize().multiplyScalar(r);const h=new Fo;h.position.copy(a),h.tangentIn.copy(c),h.tangentOut.copy(c),s.addKnot(h)}),s.closed=i,s}o.createFromPoints=e})(vv||(vv={}));class p4 extends FR{constructor(){super(new Worker(URL.createObjectURL(new Blob([`import '${new URL("./generateMeshBVH.worker-Be19n6m6.js",import.meta.url).toString()}';`],{type:"text/javascript"})),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,s)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=c=>{s(new Error(`[GenerateMeshBVHWorker] ${c.message||"Could not load worker."}`))},e.onmessage=c=>{const{data:h}=c;if(h.error)s(new Error(h.error)),e.onmessage=null;else if(h.serialized){const{serialized:d,position:u}=h,m=BR.deserialize(d,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=u,d.index)if(t.index)t.index.array=d.index;else{const y=new lt(d.index,1,!1);t.setIndex(y)}g.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new ri)),i.onProgress&&i.onProgress(h.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(h.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(c=>c.buffer).filter(c=>typeof SharedArrayBuffer>"u"||!(c instanceof SharedArrayBuffer)))}).finally(()=>{e.onmessage=null,e.onerror=null})}}const m4=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:p4},Symbol.toStringTag,{value:"Module"}));export{hh as $TNE,Vu as $componentName,wE as $physicsKey,mo as $vnStLM,be as ActionBuilder,jP as ActionCollection,ji as ActionModel,Nx as Addressables,od as AlignmentConstraint,Cl as AmbientMode,Zt as Animation,Jg as AnimationBuilder,Rd as AnimationCurve,Vm as AnimationExtension,li as AnimationUtils,Et as Animator,Oi as AnimatorConditionMode,_o as AnimatorController,ef as AnimatorControllerBuilder,ca as AnimatorControllerParameterType,zh as AnimatorStateInfo,Id as Antialiasing,no as Application,oS as AssetDatabase,ie as AssetReference,Sc as Attractor,Eb as AudioClip,Ya as AudioExtension,cs as AudioListener,uC as AudioRolloffMode,Yi as AudioSource,cr as Avatar,wt as AvatarMarker,Nl as Axes,Gl as AxesHelper,s0 as AxisRotationConstraint,lh as BUILD_TIME,kn as BaseUIComponent,Kb as BasicIKConstraint,t_ as BehaviorExtension,qt as BehaviorModel,Hr as BlobStorage,vg as BloomEffect,hm as BoxCollider,Ta as BoxGizmo,Xt as BoxHelperComponent,Ps as Button,On as ButtonsFactory,Ak as CallDirection,Wn as CallInfo,pi as Camera,Qh as CameraTargetReachedEvent,gc as Canvas,gr as CanvasGroup,hs as CapsuleCollider,W0 as ChangeMaterialOnClick,Pa as ChangeTransformOnClick,fa as CharacterController,us as CharacterControllerInput,Ld as ChromaticAberration,$i as CircularBuffer,ua as ClearFlags,Ug as ClickThrough,ht as ClipExtrapolation,Ki as Collider,cx as Collision,qp as CollisionDetectionMode,vr as ColorAdjustments,wc as ColorBySpeedModule,pg as ColorOverLifetimeModule,AI as Component,T as Component$1,Nu as ComponentLifecycleEvents,u4 as Components,s1 as ConnectionEvents,lx as ContactPoint,sd as ContactShadows,Q as Context,U2 as ContextArgs,de as ContextEvent,ce as ContextRegistry,Va as CursorFollow,Ma as CustomBranding,ze as CustomShader,mp as DefaultReflectionMode,i0 as Deletable,Ir as DeleteBox,Jn as DepthOfField,Ok as DepthOfFieldMode,dm as DeviceFlag,I as DeviceUtilities,mC as DirectorWrapMode,Wp as DisposableStore,_O as DocumentExtension,va as DragControls,l0 as DragMode,fm as DragProfile,gs as DropListener,O0 as Duplicatable,Dd as EffectWrapper,xs as EmissionModule,rc as EmphasizeOnClick,el as EngineLoadingView,nm as EnvironmentScene,My as EventBus,re as EventList,Tb as EventListEvent,wi as EventSystem,Lm as EventTrigger,aP as FieldWithDefault,Ho as FileReference,Wx as FileReferenceSerializer,jD as FileSpawnModel,zC as File_Event,x_ as FixedJoint,DC as FixedRotationAxesConstraint,fc as Fog,tg as FontStyle,Ee as FrameEvent,pl as GENERATOR,P as GameObject,Ra as GaussianSplat,F as Gizmos,A0 as GltfExport,T0 as GltfExportBox,ad as GrabPointPlaneConstraint,Aa as Gradient,Sd as Graphic,Qp as GraphicRaycaster,Er as Graphics,yc as GridHelper,h_ as GridLayoutGroup,um as GridSnapConstraint,wo as GroundProjectedEnv,Ca as GroupActionModel,uo as HideFlags,Rn as HideOnStart,Md as HingeJoint,c_ as HorizontalLayoutGroup,tk as HorizontalWrapMode,VE as HostData,Bo as HoverAnimation,Rc as Image,Go as ImageReference,$x as ImageReferenceSerializer,T_ as InheritVelocityModule,Qx as Input,Hs as InputEventQueue,Te as InputEvents,J_ as InputField,Ja as InstanceHandle,Ka as InstancingHandler,Mn as InstancingUtil,Cx as InstantiateEvent,_t as InstantiateIdProvider,$o as InstantiateOptions,t0 as Interactable,Qd as InternalScreenshotUtils,SA as JoinedRoomResponse,pm as KeepRotationConstraint,IC as KeepScaleConstraint,gA as KeyEventArgs,Ai as Keyframe,rg as LODGroup,_c as LODModel,Zx as LODsManager,CA as LeftRoomResponse,$t as Light,f1 as LightData,Ct as LimitVelocityOverLifetimeModule,G5 as LoadingElementOptions,e0 as LogStats,Wi as LogType,ev as LookAt,ha as LookAtConstraint,A as MODULES,ni as MainModule,Kh as MarkerType,Cd as MaskableGraphic,Ls as MaterialPropertyBlock,Om as MaterialX,j as Mathf,sr as MeshCollider,cd as MeshRenderer,Z as MinMaxCurve,Ia as MinMaxGradient,ny as NEEDLE_ENGINE_FEATURE_FLAGS,bh as NEKeyboardEvent,os as NEPointerEvent,Cc as NEToneMappingMode,oO as NeedleButtonElement,fp as NeedleEngineModelLoader,fv as NeedleEngineWebComponent,Ro as NeedleMenu,Wu as NeedlePatchesKey,Vy as NeedleXRController,q as NeedleXRSession,L1 as NeedleXRSync,Y1 as NeedleXRUtils,vc as NestedGltf,uu as NetworkConnection,Do as NetworkedStreamEvents,du as NetworkedStreams,O_ as Networking,kx as NewInstanceModel,Se as NoiseModule,pn as ObjectRaycaster,Gs as ObjectUtils,Ea as OffsetConstraint,Ru as OneEuroFilter,$f as OneEuroFilterXYZ,Tc as OpenURL,fe as OrbitControls,pc as Outline,r1 as OwnershipEvent,a1 as OwnershipModel,Ns as PUBLIC_KEY,Oa as Padding,ug as ParticleBurst,E_ as ParticleSubEmitter,Ad as ParticleSystem,_r as ParticleSystemBaseBehaviour,_n as ParticleSystemRenderer,dg as ParticleSystemShapeType,Og as PeerHandle,n1 as PeerNetworking,zc as Physics,i_ as PhysicsExtension,At as PhysicsMaterialCombine,jd as PixelationEffect,r0 as PlaneHeightLockConstraint,ud as PlayAnimationOnClick,lr as PlayAudioOnClick,Vl as PlayableDirector,$c as PlayerColor,Ti as PlayerState,zP as PlayerStateEvent,Y0 as PlayerSync,l1 as PlayerView,c1 as PlayerViewManager,hu as PointerEventData,lp as PointerType,x1 as PostProcessing,gt as PostProcessingEffect,Pt as PostProcessingEffectOrder,Gc as PostProcessingHandler,fl as Prefabs,ac as PreliminaryAction,pd as PreliminaryTrigger,Ql as PreviewHelper,_l as PrimitiveType,ue as Progress,Df as PromiseAllWithErrors,Lf as PromiseErrorResult,Ck as QualityLevel,he as RGBAColor,Vc as RapierPhysics,jg as RawImage,Jr as RaycastOptions,KP as Rect,Kn as RectTransform,ps as ReflectionProbe,rP as ReflectionProbeUsage,Lr as RegisteredAnimationInfo,Qb as RemoteSkybox,qo as RenderTexture,JS as RenderTextureSerializer,gi as Renderer,g1 as RendererData,C0 as RendererLightmap,rt as Rigidbody,st as RigidbodyConstraints,se as RoomEvents,bn as RotationBySpeedModule,Zn as RotationOverLifetimeModule,n0 as ScaleLimitConstraint,km as SceneLightSettings,at as SceneSwitcher,wr as ScreenCapture,Ss as ScreenSpaceAmbientOcclusion,eo as ScreenSpaceAmbientOcclusionN8,Sg as ScreenSpaceAmbientOcclusionN8QualityMode,Uo as ScrollFollow,q_ as SeeThrough,Bn as SendQueue,gh as SerializationContext,V0 as SetActiveOnClick,Em as ShadowCastingMode,Nd as ShadowCatcher,R_ as ShapeModule,hx as ShapeOverlapResult,Bd as SharpeningEffect,Yh as SignalAsset,pa as SignalReceiver,Wl as SignalReceiverEvent,Jh as SignalTrackHandler,YP as Size,Ii as SizeBySpeedModule,La as SizeOverLifetimeModule,P0 as SkinnedMeshRenderer,Rg as SmoothFollow,gm as SnapToSurfaceConstraint,Qa as SpatialGrabRaycaster,Hd as SpatialHtml,Tg as SpatialTrigger,jo as SpatialTriggerReceiver,Eg as SpectatorCamera,Hl as SphereCollider,ab as SphereIntersection,Na as SplineContainer,Fo as SplineData,vv as SplineUtils,xn as SplineWalker,ys as Sprite,cc as SpriteData,Ri as SpriteRenderer,lc as SpriteSheet,FI as StateMachineBehaviour,H_ as StreamEndedEvent,Ek as StreamReceivedEvent,yg as SubEmitterSystem,X_ as SyncedCamera,to as SyncedRoom,Gn as SyncedTransform,H0 as TapGestureTrigger,Km as TeleportTarget,Y_ as TestRunner,K_ as TestSimulateUserData,ii as Text,ut as TextAnchor,a_ as TextBuilder,ig as TextExtension,oi as TextureSheetAnimationModule,Lo as TiltShiftEffect,b1 as Time,em as TimelineActivationTrack,Zh as TimelineAnimationTrack,Ds as TimelineAudioTrack,nf as TimelineBuilder,tm as TimelineControlTrack,Jp as TimelineMarkerTrack,ma as TimelineTrackHandler,ja as ToneMappingEffect,Me as TrackType,qe as TrailModule,Ze as TransformData,$a as TransformGizmo,ei as TriggerBuilder,Rr as TriggerModel,k as TypeStore,Bb as UIRaycastUtils,vd as UIRootComponent,I0 as USDDocument,vt as USDObject,_P as USDWriter,wP as USDZExporter,Ao as USDZExporter$1,mc as USDZText,p_ as USDZUIExtension,eC as UriSerializer,rd as UsageMarker,PA as UserJoinedOrLeftRoomModel,ci as VERSION,N0 as VariantAction,tt as VelocityOverLifetimeModule,l_ as VerticalLayoutGroup,ek as VerticalWrapMode,kt as VideoPlayer,bt as ViewBox,rs as ViewDevice,Ua as Vignette,md as VisibilityAction,Cs as Voip,Ud as Volume,N as VolumeParameter,bg as VolumeProfile,dA as WaitForFrames,Hx as WaitForPromise,Ry as WaitForSeconds,Is as Watch,Yd as WebARCameraBackground,Tn as WebARSessionRoot,Zm as WebXR,Tr as WebXRButtonFactory,Lc as WebXRImageTracking,Sn as WebXRImageTrackingModel,Rs as WebXRPlaneTracking,Wc as WebXRTrackedImage,Os as XRControllerFollow,bs as XRControllerModel,Ji as XRControllerMovement,Qn as XRFlag,$g as XRRig,vi as XRState,To as XRStateFlag,cn as _$IqaqwY,vO as __Ignore,X2 as __internalNotifyObjectDestroyed,O1 as __internalStepGaussianSplatAdaptation,ho as activeInHierarchyFieldName,$y as adaptGaussianSplatQuality,Ou as addAttributeChangeCallback,bo as addComponent,cj as addCustomExtensionPlugin,aa as addNewComponent,$u as addPatch,Eh as apply,gO as applyDef,Ny as applyGaussianSplatQuality,EI as applyHMRChanges,fO as applyOver,mS as applyPrototypeExtensions,Px as beginListenDestroy,Rx as beginListenInstantiate,Iy as binaryIdentifierCasts,B2 as build_scene_functions,Gr as builtinComponentKeyName,gv as calculateProgress01,gT as clearMessages,tC as colorSerializer,Ax as compareAssociation,$h as componentSerializer,Uw as copyTexture,yv as createDefSerializationContext,WS as createMotion,Pi as debugNet,xl as debugOwner,kP as decompressGpuTexture,th as deepClone,es as delay,Cu as delayForFrames,fh as deserializeObject,ki as destroy,DS as destroyComponentInstance,d0 as determineMimeTypeFromExtension,Be as disposeObjectResources,wn as disposeStream,ts as editorGuidKeyName,dl as enableSpatialConsole,mO as evaluateProjectDocument,iC as eventListSerializer,l4 as exportAsGLTF,yb as findByGuid,zl as findObjectOfType,BS as findObjectsOfType,hb as findResourceUsers,aC as fitCamera,$w as fitObjectIntoVolume,$n as foreachComponent,vb as foreachComponentEnumerator,DT as forward,V1 as generateQRCode,Mx as generateSeed,Si as getBoundingBox,kw as getCameraController,ls as getComponent,jh as getComponentInChildren,Fh as getComponentInParent,Bl as getComponents,Ul as getComponentsInChildren,$p as getComponentsInParent,Gx as getContextResetBehaviors,gP as getFormattedDate,NA as getGaussianSplatQualityInfo,Tt as getIconElement,Zy as getIconTexture,is as getLoader,Dh as getOrAddComponent,x as getParam,BT as getParentHierarchyPath,qR as getPath,_A as getPeerOptions,t1 as getPeerjsInstance,Y2 as getResourceUserCount,u1 as getSceneData,Tw as getTempColor,xi as getTempQuaternion,U as getTempVector,Zc as getUrlParams,Nw as getVisibleInCustomShadowRendering,Lw as getWorldDirection,Qf as getWorldEuler,le as getWorldPosition,Re as getWorldQuaternion,Iu as getWorldRotation,Je as getWorldScale,Xp as hasPointerEventComponent,Xw as hideDebugConsole,OP as imageToCanvas,Vx as initAddressableSerializers,nC as initBuiltinSerializers,i4 as initEngine,tO as initPhysics,_C as initVolumeParameterSerializer,Ks as instantiate,eP as invokeLoadedImportPluginHooks,W1 as invokeXRSessionEnd,$1 as invokeXRSessionStart,fS as isActiveInHierarchy,Ll as isActiveSelf,JR as isAndroidDevice,Bw as isAnimationAction,Gu as isComponent,$R as isDebugMode,QR as isDesktop,Ys as isDestroyed,M as isDevEnvironment,OI as isDisposable,q2 as isDisposed,r4 as isExporting,ax as isGLTFModel,aw as isHostedOnGlitch,Mb as isHotReloadEnabled,RI as isHotReloading,KR as isIPad,G1 as isIconElement,Ni as isLocalNetwork,tT as isMacOS,YR as isMobileDevice,eT as isMozillaXR,oT as isQuest,rS as isResourceTrackingEnabled,nT as isSafari,WL as isTrackModel,Ap as isUsingInstancing,iT as isiOS,ZR as isiPad,cb as isolateChildrenDuring,mk as loadAsset,id as loadPMREM,y_ as loadSync,Lu as logHierarchy,OT as lookAtInverse,nh as lookAtObject,MT as lookAtScreenPoint,VR as makeId,uw as makeIdFromRandomWords,Zi as makeNameSafe,yS as markAsInstancedRendered,Kr as maxGaussianSplatAdaptationLevel,sT as microphonePermissionsGranted,NR as nameof,lw as nameofFactory,OA as needle,Ib as objectSerializer,N1 as offBeforeXRSession,z1 as offXRSessionEnd,Qy as offXRSessionStart,MI as on,ME as onAfterRender,OE as onBeforeRender,k2 as onBeforeXRSession,PE as onClear,kE as onDestroy,cy as onInitialized,Qu as onStart,WE as onSyncDestroy,Ox as onSyncInstantiate,bx as onUpdate,Yy as onXRSessionEnd,wp as onXRSessionStart,Th as originalComponentNameKey,ng as parseSync,Ww as placeOnSurface,Zf as postprocessFBXMaterials,SL as prefix,cw as pushState,GR as randomNumber,Ly as registerBinaryType,kp as registerComponent,v0 as registerComponentExtension,vn as registerCustomEffectType,w0 as registerExportExtensions,Rm as registerExtensions,US as registerHotReloadType,px as registerLoader,Tx as registerPrefabProvider,fb as registerPrototypeExtensions,iy as registerType,mw as relativePathPrefix,fw as removeAttributeChangeCallback,Np as removeComponent,hj as removeCustomImportExtensionType,bE as removePatch,yp as resolveGaussianSplatQuality,ao as resolveUrl,pw as sanitizeString,Qk as saveImage,k5 as screenshot,av as screenshot2,by as sendDestroyed,p as serializable,Fx as serializeObject,it as serializeable,oa as setActive,_w as setAllowBalloonMessages,dT as setAllowOverlayMessages,Eu as setAutoFitEnabled,Wf as setCameraController,_S as setDestroyed,vT as setDevEnvironment,lS as setDisposable,Dl as setDontDestroy,Ef as setOrAddParamsToUrl,WR as setParam,Jc as setParamWithoutReload,vA as setPeerOptions,tS as setPhysicsEngineFactory,H2 as setResourceTrackingEnabled,Af as setState,Kf as setVisibleInCustomShadowRendering,Yf as setWorldEuler,Vi as setWorldPosition,zr as setWorldPositionXYZ,Fn as setWorldQuaternion,Xf as setWorldQuaternionXYZW,Fw as setWorldRotation,oh as setWorldRotationXYZ,hl as setWorldScale,ul as showBalloonError,Fe as showBalloonMessage,ge as showBalloonWarning,ey as showDebugConsole,Mw as slerp,ph as syncDestroy,qb as syncField,_y as syncInstantiate,UT as textureToCanvas,gw as toSourceId,Jx as tryCastBinary,VC as tryDetermineMimetypeFromBinary,WC as tryDetermineMimetypeFromURL,eh as tryFindObject,$C as tryGetExtensionFromUrl,e1 as tryGetGuid,zS as unregisterHotReloadType,HE as unregisterPrefabProvider,If as unwatchWrite,Ow as useForAutoFit,Ve as validate,ku as watchWrite};
1860
+ `),Li&&this._onCreateEffectsDebug(this._composer,s)}createPassForMergeableEffects(e,t,i,n){if(e.length>0){const s=new A.POSTPROCESSING.MODULE.EffectPass(i,...e);s.name=e.map(r=>r.name).join(", "),s.mainScene=n,s.enabled=!0,s.renderToScreen=!1,t.addPass(s),e.length=0}}handleDevicePixelRatio(){typeof this.context.devicePixelRatio=="number"&&this.context.requestSizeUpdate()}_menuEntry=null;_passIndices=null;_onCreateEffectsDebug(e,t){if(Li==="passes"){const i=new A.POSTPROCESSING.MODULE.DepthEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new A.POSTPROCESSING.MODULE.EffectPass(t,i);if(n.name="Depth Effect Pass",n.enabled=!1,e.passes.push(n),this._passIndices!==null){const r=[e.passes[0]];this._passIndices.length>0&&r.push(...this._passIndices.filter(a=>a!==0).map(a=>e.passes[a]).filter(a=>a)),r.length>0&&console.log("[PostProcessing] Passes (selected) \u2192",r),e.passes.length=0;for(const a of r)a.enabled=!0,a.renderToScreen=!1,e.addPass(a)}const s=this.context.menu;if(s&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const r=document.createElement("select");r.multiple=!0;const a=document.createElement("option");a.innerText="Final Output",a.value="-1",r.appendChild(a);for(const l of e.passes){const c=document.createElement("option");c.innerText=l.name,c.value=`${e.passes.indexOf(l)}`,c.title=l.name,r.appendChild(c)}s.appendChild(r),this._menuEntry=r,r.addEventListener("change",()=>{const l=Array.from(r.selectedOptions).map(c=>parseInt(c.value));l.length===1&&l[0]===-1?this._passIndices=null:this._passIndices=l,this.applyEffects(this.context)})}}}}const d4=Object.freeze(Object.defineProperty({__proto__:null,PostProcessingHandler:Gc},Symbol.toStringTag,{value:"Module"}));class nf{_name;_tracks=[];_currentTrack=null;_pendingSignals=[];_idProvider;constructor(e,t){this._name=e,this._idProvider=new _t(t??Date.now())}static create(e,t){return new nf(e??"Timeline",t)}animationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Animation,t??null),this}audioTrack(e,t,i){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Audio,t??null),this._currentTrack.volume=i,this}activationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Activation,t??null),this}controlTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Control,null),this}signalTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Signal,t??null),this}markerTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,Me.Marker,null),this}clip(e,t){if(!this._currentTrack)throw new Error("TimelineBuilder: .clip() must be called after a track method (e.g. .animationTrack())");this.commitInlineTracks();const i=this._currentTrack;switch(i.type){case Me.Animation:{let n;if(e instanceof Yt)n=e;else{const h=Array.isArray(e)?e:[e],d=i.outputs[0],u=d instanceof R?d:d!=null&&"gameObject"in d?d.gameObject:void 0;n=Nh(h,u)}const s=t??{},r=s.duration??n.duration,a=s.start??i.cursor,l=a+r,c={start:a,end:l,duration:r,timeScale:s.speed??1,clipIn:s.clipIn??0,easeInDuration:s.easeIn??0,easeOutDuration:s.easeOut??0,preExtrapolationMode:s.preExtrapolation??ht.None,postExtrapolationMode:s.postExtrapolation??ht.None,reversed:s.reversed,asset:{clip:n,loop:s.loop??!1,duration:n.duration,removeStartOffset:s.removeStartOffset??!1}};i.clips.push(c),i.cursor=l;break}case Me.Audio:{const n=e,s=t??{},r=s.duration,a=s.start??i.cursor,l=a+r,c={start:a,end:l,duration:r,timeScale:s.speed??1,clipIn:0,easeInDuration:s.easeIn??0,easeOutDuration:s.easeOut??0,preExtrapolationMode:ht.None,postExtrapolationMode:ht.None,asset:{clip:n,loop:s.loop??!1,volume:s.volume??1}};i.clips.push(c),i.cursor=l;break}case Me.Activation:{const n=e,s=n.start??i.cursor,r=s+n.duration,a={start:s,end:r,duration:n.duration,timeScale:1,clipIn:0,easeInDuration:n.easeIn??0,easeOutDuration:n.easeOut??0,preExtrapolationMode:ht.None,postExtrapolationMode:ht.None,asset:{}};i.clips.push(a),i.cursor=r;break}case Me.Control:{const n=e,s=t??{},r=s.start??i.cursor,a=s.duration,l=r+a,c={start:r,end:l,duration:a,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:ht.None,postExtrapolationMode:ht.None,asset:{sourceObject:n,controlActivation:s.controlActivation??!0,updateDirector:s.updateDirector??!0}};i.clips.push(c),i.cursor=l;break}default:throw new Error(`TimelineBuilder: .clip() is not supported on track type "${i.type}"`)}return this}marker(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .marker() must be called after a track method");if(this._currentTrack.type!==Me.Signal&&this._currentTrack.type!==Me.Marker)throw new Error(`TimelineBuilder: .marker() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n={type:Kh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:t};return this._currentTrack.markers.push(n),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}signal(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .signal() must be called after a track method");if(this._currentTrack.type!==Me.Signal&&this._currentTrack.type!==Me.Marker)throw new Error(`TimelineBuilder: .signal() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n=this._idProvider.generateUUID(),s=this._tracks.indexOf(this._currentTrack),r={type:Kh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:n};return this._currentTrack.markers.push(r),this._pendingSignals.push({trackIndex:s,guid:n,callback:t}),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}muted(e=!0){if(!this._currentTrack)throw new Error("TimelineBuilder: .muted() must be called after a track method");return this._currentTrack.muted=e,this}track(e,t,i,n){if(!this._currentTrack)throw new Error("TimelineBuilder: .track() must be called after .animationTrack()");if(this._currentTrack.type!==Me.Animation)throw new Error("TimelineBuilder: .track() is only supported on animation tracks");return this._currentTrack.inlineTracks.push(Rb(e,t,i,n)),this}build(){this.commitInlineTracks();const e=this._tracks.map(t=>{const i={name:t.name,type:t.type,muted:t.muted,outputs:t.outputs};return t.clips.length>0&&(i.clips=t.clips),t.markers.length>0&&(i.markers=t.markers),t.volume!==void 0&&(i.volume=t.volume),t.trackOffset!==void 0&&(i.trackOffset=t.trackOffset),i});return{name:this._name,tracks:e}}install(e){const t=this.build();if(this._pendingSignals.length>0){const i=e.gameObject;let n=P.getComponent(i,pa);n||(n=P.addComponent(i,pa)),n.events||(n.events=[]);for(const s of this._pendingSignals){const r=new Yh;r.guid=s.guid;const a=new Wl;a.signal=r,a.reaction=new re([s.callback]),n.events.push(a);const l=t.tracks[s.trackIndex];l&&!l.outputs.includes(n)&&l.outputs.push(n)}}return e.playableAsset=t,t}pushTrack(e,t,i){const n={name:e,type:t,muted:!1,outputs:i?[i]:[],clips:[],markers:[],cursor:0,inlineTracks:[]};return this._tracks.push(n),n}commitInlineTracks(){if(!this._currentTrack||this._currentTrack.inlineTracks.length===0)return;const e=this._currentTrack,t=e.outputs[0],i=t instanceof R?t:t!=null&&"gameObject"in t?t.gameObject:void 0,n=Nh(e.inlineTracks,i),s=e.cursor,r=n.duration,a={start:s,end:s+r,duration:r,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:ht.None,postExtrapolationMode:ht.None,asset:{clip:n,loop:!1,duration:n.duration,removeStartOffset:!1}};e.clips.push(a),e.cursor=s+r,e.inlineTracks=[]}}class vO{}const u4=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:be,ActionCollection:jP,ActionModel:ji,AlignmentConstraint:od,Animation:Zt,AnimationBuilder:Jg,AnimationCurve:Rd,AnimationExtension:Vm,Animator:Et,AnimatorController:_o,Antialiasing:Id,Attractor:Sc,AudioExtension:Ya,AudioListener:cs,AudioSource:Yi,Avatar:cr,AvatarMarker:wt,AxesHelper:Gl,AxisRotationConstraint:s0,BaseUIComponent:kn,BasicIKConstraint:Kb,BehaviorExtension:t_,BehaviorModel:qt,BloomEffect:vg,BoxCollider:hm,BoxGizmo:Ta,BoxHelperComponent:Xt,Button:Ps,CallInfo:Wn,Camera:pi,CameraTargetReachedEvent:Qh,Canvas:gc,CanvasGroup:gr,CapsuleCollider:hs,ChangeMaterialOnClick:W0,ChangeTransformOnClick:Pa,CharacterController:fa,CharacterControllerInput:us,ChromaticAberration:Ld,ClickThrough:Ug,ColorAdjustments:vr,ColorBySpeedModule:wc,ColorOverLifetimeModule:pg,ContactShadows:sd,CursorFollow:Va,CustomBranding:Ma,Deletable:i0,DeleteBox:Ir,DepthOfField:Jn,DeviceFlag:dm,DocumentExtension:_O,DragControls:va,DragProfile:fm,DropListener:gs,Duplicatable:O0,EffectWrapper:Dd,EmissionModule:xs,EmphasizeOnClick:rc,EnvironmentScene:nm,EventList:re,EventListEvent:Tb,EventSystem:wi,EventTrigger:Lm,FieldWithDefault:aP,FixedJoint:x_,FixedRotationAxesConstraint:DC,Fog:fc,GaussianSplat:Ra,GltfExport:A0,GltfExportBox:T0,GrabPointPlaneConstraint:ad,Gradient:Aa,Graphic:Sd,GraphicRaycaster:Qp,GridHelper:yc,GridLayoutGroup:h_,GridSnapConstraint:um,GroundProjectedEnv:wo,GroupActionModel:Ca,HideOnStart:Rn,HingeJoint:Md,HorizontalLayoutGroup:c_,get HoverAnimation(){return Bo},Image:Rc,InheritVelocityModule:T_,InputField:J_,InstanceHandle:Ja,InstancingHandler:Ka,Interactable:t0,KeepRotationConstraint:pm,KeepScaleConstraint:IC,Keyframe:Ai,LODGroup:rg,LODModel:_c,Light:$t,LimitVelocityOverLifetimeModule:Ct,LogStats:e0,LookAt:ev,LookAtConstraint:ha,MainModule:ni,MaskableGraphic:Cd,MeshCollider:sr,MeshRenderer:cd,MinMaxCurve:Z,MinMaxGradient:Ia,NeedleMenu:Ro,NestedGltf:vc,Networking:O_,NoiseModule:Ce,ObjectRaycaster:pn,OffsetConstraint:Ea,OpenURL:Tc,OrbitControls:fe,Outline:pc,Padding:Oa,ParticleBurst:ug,ParticleSubEmitter:E_,ParticleSystem:Ad,ParticleSystemRenderer:_n,PhysicsExtension:i_,PixelationEffect:jd,PlaneHeightLockConstraint:r0,PlayAnimationOnClick:ud,PlayAudioOnClick:lr,PlayableDirector:Vl,PlayerColor:$c,PointerEventData:hu,PostProcessingHandler:Gc,PreliminaryAction:ac,PreliminaryTrigger:pd,RawImage:jg,Rect:KP,RectTransform:Kn,ReflectionProbe:ps,RegisteredAnimationInfo:Lr,RemoteSkybox:Qb,Renderer:gi,RendererLightmap:C0,Rigidbody:rt,RotationBySpeedModule:bn,RotationOverLifetimeModule:Zn,ScaleLimitConstraint:n0,SceneSwitcher:at,ScreenCapture:wr,ScreenSpaceAmbientOcclusion:Ss,ScreenSpaceAmbientOcclusionN8:eo,ScrollFollow:Uo,SeeThrough:q_,SetActiveOnClick:V0,ShadowCatcher:Nd,ShapeModule:R_,SharpeningEffect:Bd,SignalAsset:Yh,SignalReceiver:pa,SignalReceiverEvent:Wl,SignalTrackHandler:Jh,Size:YP,SizeBySpeedModule:Ii,SizeOverLifetimeModule:La,SkinnedMeshRenderer:P0,SmoothFollow:Rg,SnapToSurfaceConstraint:gm,SpatialGrabRaycaster:Qa,SpatialHtml:Hd,SpatialTrigger:Tg,SpatialTriggerReceiver:jo,SpectatorCamera:Eg,SphereCollider:Hl,SplineContainer:Na,SplineData:Fo,SplineWalker:xn,Sprite:ys,SpriteData:cc,SpriteRenderer:Ri,SpriteSheet:lc,SubEmitterSystem:yg,SyncedCamera:X_,SyncedRoom:to,SyncedTransform:Gn,TapGestureTrigger:H0,TeleportTarget:Km,TestRunner:Y_,TestSimulateUserData:K_,Text:ii,TextBuilder:a_,TextExtension:ig,TextureSheetAnimationModule:oi,TiltShiftEffect:Lo,TimelineActivationTrack:em,TimelineAnimationTrack:Zh,TimelineAudioTrack:Ds,TimelineBuilder:nf,TimelineControlTrack:tm,TimelineMarkerTrack:Jp,ToneMappingEffect:ja,TrailModule:qe,TransformData:Ze,TransformGizmo:$a,TriggerBuilder:ei,TriggerModel:Rr,UIRaycastUtils:Bb,UIRootComponent:vd,USDZExporter:Ao,USDZText:mc,USDZUIExtension:p_,UsageMarker:rd,VariantAction:N0,VelocityOverLifetimeModule:tt,VerticalLayoutGroup:l_,VideoPlayer:kt,get ViewBox(){return bt},Vignette:Ua,VisibilityAction:md,Voip:Cs,Volume:Ud,VolumeParameter:N,VolumeProfile:bg,WebARCameraBackground:Yd,WebARSessionRoot:Tn,WebXR:Zm,WebXRImageTracking:Lc,WebXRImageTrackingModel:Sn,WebXRPlaneTracking:Rs,WebXRTrackedImage:Wc,XRControllerFollow:Os,XRControllerModel:bs,XRControllerMovement:Ji,XRFlag:Qn,XRRig:$g,XRState:vi,__Ignore:vO},Symbol.toStringTag,{value:"Module"}));var vv;(o=>{function e(t,i=!1,n=.75){const s=new Na,r=1-j.clamp(n,0,1);return t.forEach((a,l)=>{const c=new v;l<t.length-1?c.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&c.subVectors(t[0],a).normalize().multiplyScalar(r);const h=new Fo;h.position.copy(a),h.tangentIn.copy(c),h.tangentOut.copy(c),s.addKnot(h)}),s.closed=i,s}o.createFromPoints=e})(vv||(vv={}));class p4 extends FR{constructor(){super(new Worker(URL.createObjectURL(new Blob([`import '${new URL("./generateMeshBVH.worker-Be19n6m6.js",import.meta.url).toString()}';`],{type:"text/javascript"})),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,s)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=c=>{s(new Error(`[GenerateMeshBVHWorker] ${c.message||"Could not load worker."}`))},e.onmessage=c=>{const{data:h}=c;if(h.error)s(new Error(h.error)),e.onmessage=null;else if(h.serialized){const{serialized:d,position:u}=h,m=BR.deserialize(d,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=u,d.index)if(t.index)t.index.array=d.index;else{const y=new lt(d.index,1,!1);t.setIndex(y)}g.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new ri)),i.onProgress&&i.onProgress(h.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(h.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(c=>c.buffer).filter(c=>typeof SharedArrayBuffer>"u"||!(c instanceof SharedArrayBuffer)))}).finally(()=>{e.onmessage=null,e.onerror=null})}}const m4=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:p4},Symbol.toStringTag,{value:"Module"}));export{Vu as $componentName,mo as $jVksoCHS,wE as $physicsKey,be as ActionBuilder,jP as ActionCollection,ji as ActionModel,Nx as Addressables,od as AlignmentConstraint,Cl as AmbientMode,Zt as Animation,Jg as AnimationBuilder,Rd as AnimationCurve,Vm as AnimationExtension,li as AnimationUtils,Et as Animator,Oi as AnimatorConditionMode,_o as AnimatorController,ef as AnimatorControllerBuilder,ca as AnimatorControllerParameterType,zh as AnimatorStateInfo,Id as Antialiasing,no as Application,oS as AssetDatabase,ie as AssetReference,Sc as Attractor,Eb as AudioClip,Ya as AudioExtension,cs as AudioListener,uC as AudioRolloffMode,Yi as AudioSource,cr as Avatar,wt as AvatarMarker,Nl as Axes,Gl as AxesHelper,s0 as AxisRotationConstraint,lh as BUILD_TIME,kn as BaseUIComponent,Kb as BasicIKConstraint,t_ as BehaviorExtension,qt as BehaviorModel,Hr as BlobStorage,vg as BloomEffect,hm as BoxCollider,Ta as BoxGizmo,Xt as BoxHelperComponent,Ps as Button,On as ButtonsFactory,Ak as CallDirection,Wn as CallInfo,pi as Camera,Qh as CameraTargetReachedEvent,gc as Canvas,gr as CanvasGroup,hs as CapsuleCollider,W0 as ChangeMaterialOnClick,Pa as ChangeTransformOnClick,fa as CharacterController,us as CharacterControllerInput,Ld as ChromaticAberration,$i as CircularBuffer,ua as ClearFlags,Ug as ClickThrough,ht as ClipExtrapolation,Ki as Collider,cx as Collision,qp as CollisionDetectionMode,vr as ColorAdjustments,wc as ColorBySpeedModule,pg as ColorOverLifetimeModule,AI as Component,T as Component$1,Nu as ComponentLifecycleEvents,u4 as Components,s1 as ConnectionEvents,lx as ContactPoint,sd as ContactShadows,Q as Context,U2 as ContextArgs,de as ContextEvent,ce as ContextRegistry,Va as CursorFollow,Ma as CustomBranding,ze as CustomShader,mp as DefaultReflectionMode,i0 as Deletable,Ir as DeleteBox,Jn as DepthOfField,Ok as DepthOfFieldMode,dm as DeviceFlag,I as DeviceUtilities,mC as DirectorWrapMode,Wp as DisposableStore,_O as DocumentExtension,va as DragControls,l0 as DragMode,fm as DragProfile,gs as DropListener,O0 as Duplicatable,Dd as EffectWrapper,xs as EmissionModule,rc as EmphasizeOnClick,el as EngineLoadingView,nm as EnvironmentScene,My as EventBus,re as EventList,Tb as EventListEvent,wi as EventSystem,Lm as EventTrigger,aP as FieldWithDefault,Ho as FileReference,Wx as FileReferenceSerializer,jD as FileSpawnModel,zC as File_Event,x_ as FixedJoint,DC as FixedRotationAxesConstraint,fc as Fog,tg as FontStyle,Ee as FrameEvent,pl as GENERATOR,P as GameObject,Ra as GaussianSplat,F as Gizmos,A0 as GltfExport,T0 as GltfExportBox,ad as GrabPointPlaneConstraint,Aa as Gradient,Sd as Graphic,Qp as GraphicRaycaster,Er as Graphics,yc as GridHelper,h_ as GridLayoutGroup,um as GridSnapConstraint,wo as GroundProjectedEnv,Ca as GroupActionModel,uo as HideFlags,Rn as HideOnStart,Md as HingeJoint,c_ as HorizontalLayoutGroup,tk as HorizontalWrapMode,VE as HostData,Bo as HoverAnimation,Rc as Image,Go as ImageReference,$x as ImageReferenceSerializer,T_ as InheritVelocityModule,Qx as Input,Hs as InputEventQueue,Te as InputEvents,J_ as InputField,Ja as InstanceHandle,Ka as InstancingHandler,Mn as InstancingUtil,Cx as InstantiateEvent,_t as InstantiateIdProvider,$o as InstantiateOptions,t0 as Interactable,Qd as InternalScreenshotUtils,SA as JoinedRoomResponse,cn as KLnyx,pm as KeepRotationConstraint,IC as KeepScaleConstraint,gA as KeyEventArgs,Ai as Keyframe,rg as LODGroup,_c as LODModel,Zx as LODsManager,CA as LeftRoomResponse,$t as Light,f1 as LightData,Ct as LimitVelocityOverLifetimeModule,G5 as LoadingElementOptions,e0 as LogStats,Wi as LogType,ev as LookAt,ha as LookAtConstraint,A as MODULES,ni as MainModule,Kh as MarkerType,Cd as MaskableGraphic,Ls as MaterialPropertyBlock,Om as MaterialX,j as Mathf,sr as MeshCollider,cd as MeshRenderer,Z as MinMaxCurve,Ia as MinMaxGradient,ny as NEEDLE_ENGINE_FEATURE_FLAGS,bh as NEKeyboardEvent,os as NEPointerEvent,Cc as NEToneMappingMode,oO as NeedleButtonElement,fp as NeedleEngineModelLoader,fv as NeedleEngineWebComponent,Ro as NeedleMenu,Wu as NeedlePatchesKey,Vy as NeedleXRController,q as NeedleXRSession,L1 as NeedleXRSync,Y1 as NeedleXRUtils,vc as NestedGltf,uu as NetworkConnection,Do as NetworkedStreamEvents,du as NetworkedStreams,O_ as Networking,kx as NewInstanceModel,Ce as NoiseModule,pn as ObjectRaycaster,Gs as ObjectUtils,Ea as OffsetConstraint,Ru as OneEuroFilter,$f as OneEuroFilterXYZ,Tc as OpenURL,fe as OrbitControls,pc as Outline,r1 as OwnershipEvent,a1 as OwnershipModel,Ns as PUBLIC_KEY,Oa as Padding,ug as ParticleBurst,E_ as ParticleSubEmitter,Ad as ParticleSystem,_r as ParticleSystemBaseBehaviour,_n as ParticleSystemRenderer,dg as ParticleSystemShapeType,Og as PeerHandle,n1 as PeerNetworking,zc as Physics,i_ as PhysicsExtension,At as PhysicsMaterialCombine,jd as PixelationEffect,r0 as PlaneHeightLockConstraint,ud as PlayAnimationOnClick,lr as PlayAudioOnClick,Vl as PlayableDirector,$c as PlayerColor,Ti as PlayerState,zP as PlayerStateEvent,Y0 as PlayerSync,l1 as PlayerView,c1 as PlayerViewManager,hu as PointerEventData,lp as PointerType,x1 as PostProcessing,gt as PostProcessingEffect,Pt as PostProcessingEffectOrder,Gc as PostProcessingHandler,fl as Prefabs,ac as PreliminaryAction,pd as PreliminaryTrigger,Ql as PreviewHelper,_l as PrimitiveType,ue as Progress,Df as PromiseAllWithErrors,Lf as PromiseErrorResult,Ck as QualityLevel,he as RGBAColor,Vc as RapierPhysics,jg as RawImage,Jr as RaycastOptions,KP as Rect,Kn as RectTransform,ps as ReflectionProbe,rP as ReflectionProbeUsage,Lr as RegisteredAnimationInfo,Qb as RemoteSkybox,qo as RenderTexture,JS as RenderTextureSerializer,gi as Renderer,g1 as RendererData,C0 as RendererLightmap,rt as Rigidbody,st as RigidbodyConstraints,se as RoomEvents,bn as RotationBySpeedModule,Zn as RotationOverLifetimeModule,n0 as ScaleLimitConstraint,km as SceneLightSettings,at as SceneSwitcher,wr as ScreenCapture,Ss as ScreenSpaceAmbientOcclusion,eo as ScreenSpaceAmbientOcclusionN8,Sg as ScreenSpaceAmbientOcclusionN8QualityMode,Uo as ScrollFollow,q_ as SeeThrough,Bn as SendQueue,gh as SerializationContext,V0 as SetActiveOnClick,Em as ShadowCastingMode,Nd as ShadowCatcher,R_ as ShapeModule,hx as ShapeOverlapResult,Bd as SharpeningEffect,Yh as SignalAsset,pa as SignalReceiver,Wl as SignalReceiverEvent,Jh as SignalTrackHandler,YP as Size,Ii as SizeBySpeedModule,La as SizeOverLifetimeModule,P0 as SkinnedMeshRenderer,Rg as SmoothFollow,gm as SnapToSurfaceConstraint,Qa as SpatialGrabRaycaster,Hd as SpatialHtml,Tg as SpatialTrigger,jo as SpatialTriggerReceiver,Eg as SpectatorCamera,Hl as SphereCollider,ab as SphereIntersection,Na as SplineContainer,Fo as SplineData,vv as SplineUtils,xn as SplineWalker,ys as Sprite,cc as SpriteData,Ri as SpriteRenderer,lc as SpriteSheet,FI as StateMachineBehaviour,H_ as StreamEndedEvent,Ek as StreamReceivedEvent,yg as SubEmitterSystem,X_ as SyncedCamera,to as SyncedRoom,Gn as SyncedTransform,H0 as TapGestureTrigger,Km as TeleportTarget,Y_ as TestRunner,K_ as TestSimulateUserData,ii as Text,ut as TextAnchor,a_ as TextBuilder,ig as TextExtension,oi as TextureSheetAnimationModule,Lo as TiltShiftEffect,b1 as Time,em as TimelineActivationTrack,Zh as TimelineAnimationTrack,Ds as TimelineAudioTrack,nf as TimelineBuilder,tm as TimelineControlTrack,Jp as TimelineMarkerTrack,ma as TimelineTrackHandler,ja as ToneMappingEffect,Me as TrackType,qe as TrailModule,Ze as TransformData,$a as TransformGizmo,ei as TriggerBuilder,Rr as TriggerModel,k as TypeStore,Bb as UIRaycastUtils,vd as UIRootComponent,I0 as USDDocument,vt as USDObject,_P as USDWriter,wP as USDZExporter,Ao as USDZExporter$1,mc as USDZText,p_ as USDZUIExtension,eC as UriSerializer,rd as UsageMarker,PA as UserJoinedOrLeftRoomModel,ci as VERSION,N0 as VariantAction,tt as VelocityOverLifetimeModule,l_ as VerticalLayoutGroup,ek as VerticalWrapMode,kt as VideoPlayer,bt as ViewBox,rs as ViewDevice,Ua as Vignette,md as VisibilityAction,Cs as Voip,Ud as Volume,N as VolumeParameter,bg as VolumeProfile,dA as WaitForFrames,Hx as WaitForPromise,Ry as WaitForSeconds,Is as Watch,Yd as WebARCameraBackground,Tn as WebARSessionRoot,Zm as WebXR,Tr as WebXRButtonFactory,Lc as WebXRImageTracking,Sn as WebXRImageTrackingModel,Rs as WebXRPlaneTracking,Wc as WebXRTrackedImage,Os as XRControllerFollow,bs as XRControllerModel,Ji as XRControllerMovement,Qn as XRFlag,$g as XRRig,vi as XRState,To as XRStateFlag,hh as _$sHuA,vO as __Ignore,X2 as __internalNotifyObjectDestroyed,O1 as __internalStepGaussianSplatAdaptation,ho as activeInHierarchyFieldName,$y as adaptGaussianSplatQuality,Ou as addAttributeChangeCallback,bo as addComponent,cj as addCustomExtensionPlugin,aa as addNewComponent,$u as addPatch,Eh as apply,gO as applyDef,Ny as applyGaussianSplatQuality,EI as applyHMRChanges,fO as applyOver,mS as applyPrototypeExtensions,Px as beginListenDestroy,Rx as beginListenInstantiate,Iy as binaryIdentifierCasts,B2 as build_scene_functions,Gr as builtinComponentKeyName,gv as calculateProgress01,gT as clearMessages,tC as colorSerializer,Ax as compareAssociation,$h as componentSerializer,Uw as copyTexture,yv as createDefSerializationContext,WS as createMotion,Pi as debugNet,xl as debugOwner,kP as decompressGpuTexture,th as deepClone,es as delay,Cu as delayForFrames,fh as deserializeObject,ki as destroy,DS as destroyComponentInstance,d0 as determineMimeTypeFromExtension,Be as disposeObjectResources,wn as disposeStream,ts as editorGuidKeyName,dl as enableSpatialConsole,mO as evaluateProjectDocument,iC as eventListSerializer,l4 as exportAsGLTF,yb as findByGuid,zl as findObjectOfType,BS as findObjectsOfType,hb as findResourceUsers,aC as fitCamera,$w as fitObjectIntoVolume,$n as foreachComponent,vb as foreachComponentEnumerator,DT as forward,V1 as generateQRCode,Mx as generateSeed,Si as getBoundingBox,kw as getCameraController,ls as getComponent,jh as getComponentInChildren,Fh as getComponentInParent,Bl as getComponents,Ul as getComponentsInChildren,$p as getComponentsInParent,Gx as getContextResetBehaviors,gP as getFormattedDate,NA as getGaussianSplatQualityInfo,Tt as getIconElement,Zy as getIconTexture,is as getLoader,Dh as getOrAddComponent,x as getParam,BT as getParentHierarchyPath,qR as getPath,_A as getPeerOptions,t1 as getPeerjsInstance,Y2 as getResourceUserCount,u1 as getSceneData,Tw as getTempColor,xi as getTempQuaternion,U as getTempVector,Zc as getUrlParams,Nw as getVisibleInCustomShadowRendering,Lw as getWorldDirection,Qf as getWorldEuler,le as getWorldPosition,Re as getWorldQuaternion,Iu as getWorldRotation,Je as getWorldScale,Xp as hasPointerEventComponent,Xw as hideDebugConsole,OP as imageToCanvas,Vx as initAddressableSerializers,nC as initBuiltinSerializers,i4 as initEngine,tO as initPhysics,_C as initVolumeParameterSerializer,Ks as instantiate,eP as invokeLoadedImportPluginHooks,W1 as invokeXRSessionEnd,$1 as invokeXRSessionStart,fS as isActiveInHierarchy,Ll as isActiveSelf,JR as isAndroidDevice,Bw as isAnimationAction,Gu as isComponent,$R as isDebugMode,QR as isDesktop,Ys as isDestroyed,M as isDevEnvironment,OI as isDisposable,q2 as isDisposed,r4 as isExporting,ax as isGLTFModel,aw as isHostedOnGlitch,Mb as isHotReloadEnabled,RI as isHotReloading,KR as isIPad,G1 as isIconElement,Ni as isLocalNetwork,tT as isMacOS,YR as isMobileDevice,eT as isMozillaXR,oT as isQuest,rS as isResourceTrackingEnabled,nT as isSafari,WL as isTrackModel,Ap as isUsingInstancing,iT as isiOS,ZR as isiPad,cb as isolateChildrenDuring,mk as loadAsset,id as loadPMREM,y_ as loadSync,Lu as logHierarchy,OT as lookAtInverse,nh as lookAtObject,MT as lookAtScreenPoint,VR as makeId,uw as makeIdFromRandomWords,Zi as makeNameSafe,yS as markAsInstancedRendered,Kr as maxGaussianSplatAdaptationLevel,sT as microphonePermissionsGranted,NR as nameof,lw as nameofFactory,OA as needle,Ib as objectSerializer,N1 as offBeforeXRSession,z1 as offXRSessionEnd,Qy as offXRSessionStart,MI as on,ME as onAfterRender,OE as onBeforeRender,k2 as onBeforeXRSession,PE as onClear,kE as onDestroy,cy as onInitialized,Qu as onStart,WE as onSyncDestroy,Ox as onSyncInstantiate,bx as onUpdate,Yy as onXRSessionEnd,wp as onXRSessionStart,Th as originalComponentNameKey,ng as parseSync,Ww as placeOnSurface,Zf as postprocessFBXMaterials,SL as prefix,cw as pushState,GR as randomNumber,Ly as registerBinaryType,kp as registerComponent,v0 as registerComponentExtension,vn as registerCustomEffectType,w0 as registerExportExtensions,Rm as registerExtensions,US as registerHotReloadType,px as registerLoader,Tx as registerPrefabProvider,fb as registerPrototypeExtensions,iy as registerType,mw as relativePathPrefix,fw as removeAttributeChangeCallback,Np as removeComponent,hj as removeCustomImportExtensionType,bE as removePatch,yp as resolveGaussianSplatQuality,ao as resolveUrl,pw as sanitizeString,Qk as saveImage,k5 as screenshot,av as screenshot2,by as sendDestroyed,p as serializable,Fx as serializeObject,it as serializeable,oa as setActive,_w as setAllowBalloonMessages,dT as setAllowOverlayMessages,Eu as setAutoFitEnabled,Wf as setCameraController,_S as setDestroyed,vT as setDevEnvironment,lS as setDisposable,Dl as setDontDestroy,Ef as setOrAddParamsToUrl,WR as setParam,Jc as setParamWithoutReload,vA as setPeerOptions,tS as setPhysicsEngineFactory,H2 as setResourceTrackingEnabled,Af as setState,Kf as setVisibleInCustomShadowRendering,Yf as setWorldEuler,Vi as setWorldPosition,zr as setWorldPositionXYZ,Fn as setWorldQuaternion,Xf as setWorldQuaternionXYZW,Fw as setWorldRotation,oh as setWorldRotationXYZ,hl as setWorldScale,ul as showBalloonError,Fe as showBalloonMessage,ge as showBalloonWarning,ey as showDebugConsole,Mw as slerp,ph as syncDestroy,qb as syncField,_y as syncInstantiate,UT as textureToCanvas,gw as toSourceId,Jx as tryCastBinary,VC as tryDetermineMimetypeFromBinary,WC as tryDetermineMimetypeFromURL,eh as tryFindObject,$C as tryGetExtensionFromUrl,e1 as tryGetGuid,zS as unregisterHotReloadType,HE as unregisterPrefabProvider,If as unwatchWrite,Ow as useForAutoFit,Ve as validate,ku as watchWrite};