@needle-tools/engine 6.0.0-alpha.5 → 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 (57) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/{materialx-B3qY8vPU.js → materialx-Bd9BE6LR.js} +1 -1
  3. package/dist/{materialx-BwYvA-4x.umd.cjs → materialx-CzRx9AGf.umd.cjs} +2 -2
  4. package/dist/{materialx-CTPhpPxI.min.js → materialx-x1m4IJd1.min.js} +1 -1
  5. package/dist/{needle-engine.bundle-_kAszB-k.min.js → needle-engine.bundle-D6mZl1dR.min.js} +9 -9
  6. package/dist/{needle-engine.bundle-D3nBMgfk.umd.cjs → needle-engine.bundle-DOHf03pR.umd.cjs} +9 -9
  7. package/dist/{needle-engine.bundle-4xlWxOTF.js → needle-engine.bundle-Hu7ZAxEI.js} +550 -555
  8. package/dist/needle-engine.d.ts +14 -14
  9. package/dist/needle-engine.js +562 -562
  10. package/dist/needle-engine.min.js +1 -1
  11. package/dist/needle-engine.umd.cjs +1 -1
  12. package/dist/{vendor-BQUQwut5.js → vendor-BatPc34p.js} +50 -41
  13. package/dist/{vendor-BJviq-Oq.umd.cjs → vendor-CDN1hirK.umd.cjs} +1 -1
  14. package/dist/{vendor-CdNldo8c.min.js → vendor-T07c_9f_.min.js} +1 -1
  15. package/lib/engine/api.d.ts +1 -1
  16. package/lib/engine/api.js +1 -1
  17. package/lib/engine/api.js.map +1 -1
  18. package/lib/engine/engine_init.js +2 -2
  19. package/lib/engine/engine_init.js.map +1 -1
  20. package/lib/engine/engine_license.d.ts +7 -7
  21. package/lib/engine/engine_license.js +73 -73
  22. package/lib/engine/engine_license.js.map +1 -1
  23. package/lib/engine/engine_networking_blob.js +3 -3
  24. package/lib/engine/engine_networking_blob.js.map +1 -1
  25. package/lib/engine/engine_utils_qrcode.js +2 -2
  26. package/lib/engine/engine_utils_qrcode.js.map +1 -1
  27. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js +2 -2
  28. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js.map +1 -1
  29. package/lib/engine/webcomponents/needle menu/needle-menu.js +5 -5
  30. package/lib/engine/webcomponents/needle menu/needle-menu.js.map +1 -1
  31. package/lib/engine/webcomponents/needle-engine.js +2 -2
  32. package/lib/engine/webcomponents/needle-engine.js.map +1 -1
  33. package/lib/engine/webcomponents/needle-engine.loading.js +2 -2
  34. package/lib/engine/webcomponents/needle-engine.loading.js.map +1 -1
  35. package/lib/engine/xr/TempXRContext.js +2 -2
  36. package/lib/engine/xr/TempXRContext.js.map +1 -1
  37. package/lib/engine-components/Renderer.d.ts +1 -1
  38. package/lib/engine-components/Renderer.js +2 -11
  39. package/lib/engine-components/Renderer.js.map +1 -1
  40. package/lib/engine-components/export/usdz/USDZExporter.js +4 -4
  41. package/lib/engine-components/export/usdz/USDZExporter.js.map +1 -1
  42. package/package.json +2 -2
  43. package/plugins/common/license.js +4 -4
  44. package/plugins/license/cli.js +7 -4
  45. package/plugins/vite/license.js +4 -4
  46. package/src/engine/api.ts +1 -1
  47. package/src/engine/engine_init.ts +2 -2
  48. package/src/engine/engine_license.ts +70 -70
  49. package/src/engine/engine_networking_blob.ts +3 -3
  50. package/src/engine/engine_utils_qrcode.ts +2 -2
  51. package/src/engine/webcomponents/needle menu/needle-menu-spatial.ts +2 -2
  52. package/src/engine/webcomponents/needle menu/needle-menu.ts +5 -5
  53. package/src/engine/webcomponents/needle-engine.loading.ts +2 -2
  54. package/src/engine/webcomponents/needle-engine.ts +2 -2
  55. package/src/engine/xr/TempXRContext.ts +2 -2
  56. package/src/engine-components/Renderer.ts +4 -13
  57. package/src/engine-components/export/usdz/USDZExporter.ts +4 -4
@@ -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 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-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,`
@@ -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.5";'),$s('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),$s('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Oct 05 2026 13:00:42 GMT+0000 (Coordinated Universal Time)";'),$s('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const ci="6.0.0-alpha.5",pl="undefined",lh="Mon Oct 05 2026 13:00:42 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;
@@ -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+=`
@@ -879,7 +879,7 @@ Possible solutions:
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&&(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-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:
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
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.
@@ -1084,7 +1084,7 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
1084
1084
  Content-Type: "${t.headers.get("content-type")}"
1085
1085
  "Text: "${s}"
1086
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-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()})
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 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(){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 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),`
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}"
@@ -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(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-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:
@@ -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: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,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,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,vO as __Ignore,cn as __Pekxq,X2 as __internalNotifyObjectDestroyed,O1 as __internalStepGaussianSplatAdaptation,mo as _fncZ,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,hh as sUknx,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};