@needle-tools/engine 2.36.0-pre → 2.37.0-pre

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 (102) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/needle-engine.d.ts +171 -141
  3. package/dist/needle-engine.js +451 -437
  4. package/dist/needle-engine.js.map +4 -4
  5. package/dist/needle-engine.min.js +82 -82
  6. package/dist/needle-engine.min.js.map +4 -4
  7. package/lib/engine/api.d.ts +1 -0
  8. package/lib/engine/api.js +1 -0
  9. package/lib/engine/api.js.map +1 -1
  10. package/lib/engine/debug/debug.d.ts +1 -0
  11. package/lib/engine/debug/debug.js +3 -0
  12. package/lib/engine/debug/debug.js.map +1 -1
  13. package/lib/engine/engine_gameobject.js +2 -1
  14. package/lib/engine/engine_gameobject.js.map +1 -1
  15. package/lib/engine/engine_physics.d.ts +33 -42
  16. package/lib/engine/engine_physics.js +431 -383
  17. package/lib/engine/engine_physics.js.map +1 -1
  18. package/lib/engine/engine_physics.types.d.ts +16 -0
  19. package/lib/engine/engine_physics.types.js +19 -0
  20. package/lib/engine/engine_physics.types.js.map +1 -0
  21. package/lib/engine/engine_serialization_core.d.ts +3 -0
  22. package/lib/engine/engine_serialization_core.js +5 -0
  23. package/lib/engine/engine_serialization_core.js.map +1 -1
  24. package/lib/engine/engine_setup.js +3 -1
  25. package/lib/engine/engine_setup.js.map +1 -1
  26. package/lib/engine/engine_types.d.ts +45 -26
  27. package/lib/engine/engine_types.js +24 -37
  28. package/lib/engine/engine_types.js.map +1 -1
  29. package/lib/engine/engine_util_decorator.d.ts +6 -0
  30. package/lib/engine/engine_util_decorator.js +54 -0
  31. package/lib/engine/engine_util_decorator.js.map +1 -0
  32. package/lib/engine/engine_utils.d.ts +1 -1
  33. package/lib/engine/engine_utils.js +1 -1
  34. package/lib/engine/engine_utils.js.map +1 -1
  35. package/lib/engine/extensions/NEEDLE_gameobject_data.js +2 -0
  36. package/lib/engine/extensions/NEEDLE_gameobject_data.js.map +1 -1
  37. package/lib/engine-components/Animation.d.ts +6 -5
  38. package/lib/engine-components/Animation.js +0 -7
  39. package/lib/engine-components/Animation.js.map +1 -1
  40. package/lib/engine-components/BoxHelperComponent.js +1 -0
  41. package/lib/engine-components/BoxHelperComponent.js.map +1 -1
  42. package/lib/engine-components/Collider.d.ts +7 -2
  43. package/lib/engine-components/Collider.js +27 -15
  44. package/lib/engine-components/Collider.js.map +1 -1
  45. package/lib/engine-components/Component.d.ts +6 -15
  46. package/lib/engine-components/Component.js +7 -112
  47. package/lib/engine-components/Component.js.map +1 -1
  48. package/lib/engine-components/DragControls.js +9 -6
  49. package/lib/engine-components/DragControls.js.map +1 -1
  50. package/lib/engine-components/NavMesh.d.ts +0 -5
  51. package/lib/engine-components/NavMesh.js +100 -10
  52. package/lib/engine-components/NavMesh.js.map +1 -1
  53. package/lib/engine-components/NestedGltf.js +2 -0
  54. package/lib/engine-components/NestedGltf.js.map +1 -1
  55. package/lib/engine-components/RigidBody.d.ts +40 -25
  56. package/lib/engine-components/RigidBody.js +253 -142
  57. package/lib/engine-components/RigidBody.js.map +1 -1
  58. package/lib/engine-components/SpatialTrigger.js +1 -1
  59. package/lib/engine-components/SpatialTrigger.js.map +1 -1
  60. package/lib/engine-components/SpectatorCamera.d.ts +1 -0
  61. package/lib/engine-components/SpectatorCamera.js +9 -2
  62. package/lib/engine-components/SpectatorCamera.js.map +1 -1
  63. package/lib/engine-components/SpringJoint.d.ts +0 -13
  64. package/lib/engine-components/SpringJoint.js +42 -41
  65. package/lib/engine-components/SpringJoint.js.map +1 -1
  66. package/lib/engine-components/VideoPlayer.js.map +1 -1
  67. package/lib/engine-components/WebXR.d.ts +1 -0
  68. package/lib/engine-components/WebXR.js +10 -2
  69. package/lib/engine-components/WebXR.js.map +1 -1
  70. package/lib/engine-components/WebXRController.js +12 -6
  71. package/lib/engine-components/WebXRController.js.map +1 -1
  72. package/lib/engine-components/codegen/components.d.ts +1 -3
  73. package/lib/engine-components/codegen/components.js +1 -3
  74. package/lib/engine-components/codegen/components.js.map +1 -1
  75. package/package.json +3 -4
  76. package/src/engine/api.ts +2 -1
  77. package/src/engine/codegen/register_types.js +4 -12
  78. package/src/engine/debug/debug.ts +4 -0
  79. package/src/engine/engine_gameobject.ts +4 -4
  80. package/src/engine/engine_physics.ts +460 -421
  81. package/src/engine/engine_physics.types.ts +19 -0
  82. package/src/engine/engine_serialization_core.ts +8 -1
  83. package/src/engine/engine_setup.ts +5 -1
  84. package/src/engine/engine_types.ts +82 -56
  85. package/src/engine/engine_util_decorator.ts +69 -0
  86. package/src/engine/engine_utils.ts +3 -3
  87. package/src/engine/extensions/NEEDLE_gameobject_data.ts +2 -0
  88. package/src/engine-components/Animation.ts +10 -12
  89. package/src/engine-components/BoxHelperComponent.ts +1 -0
  90. package/src/engine-components/Collider.ts +29 -29
  91. package/src/engine-components/Component.ts +15 -130
  92. package/src/engine-components/DragControls.ts +9 -5
  93. package/src/engine-components/NavMesh.ts +114 -115
  94. package/src/engine-components/NestedGltf.ts +2 -0
  95. package/src/engine-components/RigidBody.ts +258 -149
  96. package/src/engine-components/SpatialTrigger.ts +1 -1
  97. package/src/engine-components/SpectatorCamera.ts +10 -2
  98. package/src/engine-components/SpringJoint.ts +41 -41
  99. package/src/engine-components/VideoPlayer.ts +1 -2
  100. package/src/engine-components/WebXR.ts +12 -2
  101. package/src/engine-components/WebXRController.ts +16 -7
  102. package/src/engine-components/codegen/components.ts +1 -3
@@ -1,83 +1,83 @@
1
- var ag=Object.create;var bs=Object.defineProperty;var pu=Object.getOwnPropertyDescriptor;var lg=Object.getOwnPropertyNames;var cg=Object.getPrototypeOf,dg=Object.prototype.hasOwnProperty;var hg=(a,e,t)=>e in a?bs(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var lc=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+a+'" is not supported')});var vs=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),fu=(a,e)=>{for(var t in e)bs(a,t,{get:e[t],enumerable:!0})},ug=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of lg(e))!dg.call(a,n)&&n!==t&&bs(a,n,{get:()=>e[n],enumerable:!(i=pu(e,n))||i.enumerable});return a};var ca=(a,e,t)=>(t=a!=null?ag(cg(a)):{},ug(e||!a||!a.__esModule?bs(t,"default",{value:a,enumerable:!0}):t,a));var P=(a,e,t,i)=>{for(var n=i>1?void 0:i?pu(e,t):e,r=a.length-1,o;r>=0;r--)(o=a[r])&&(n=(i?o(e,t,n):o(n))||n);return i&&n&&bs(e,t,n),n};var U=(a,e,t)=>(hg(a,typeof e!="symbol"?e+"":e,t),t);var el=vs((hf,sd)=>{parcelRequire=function(a,e,t,i){var n,r=typeof parcelRequire=="function"&&parcelRequire,o=typeof lc=="function"&&lc;function s(l,h){if(!e[l]){if(!a[l]){var u=typeof parcelRequire=="function"&&parcelRequire;if(!h&&u)return u(l,!0);if(r)return r(l,!0);if(o&&typeof l=="string")return o(l);var f=new Error("Cannot find module '"+l+"'");throw f.code="MODULE_NOT_FOUND",f}b.resolve=function(y){return a[l][1][y]||y},b.cache={};var x=e[l]=new s.Module(l);a[l][0].call(x.exports,b,x,x.exports,this)}return e[l].exports;function b(y){return s(b.resolve(y))}}s.isParcelRequire=!0,s.Module=function(l){this.id=l,this.bundle=s,this.exports={}},s.modules=a,s.cache=e,s.parent=r,s.register=function(l,h){a[l]=[function(u,f){f.exports=h},{}]};for(var c=0;c<t.length;c++)try{s(t[c])}catch(l){n||(n=l)}if(t.length){var d=s(t[t.length-1]);typeof hf=="object"&&typeof sd<"u"?sd.exports=d:typeof define=="function"&&define.amd?define(function(){return d}):i&&(this[i]=d)}if(parcelRequire=s,n)throw n;return s}({EgBh:[function(a,e,t){var i={};i.useBlobBuilder=function(){try{return new Blob([]),!1}catch{return!0}}(),i.useArrayBufferView=!i.useBlobBuilder&&function(){try{return new Blob([new Uint8Array([])]).size===0}catch{return!0}}(),e.exports.binaryFeatures=i;var n=e.exports.BlobBuilder;function r(){this._pieces=[],this._parts=[]}typeof window<"u"&&(n=e.exports.BlobBuilder=window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder||window.BlobBuilder),r.prototype.append=function(o){typeof o=="number"?this._pieces.push(o):(this.flush(),this._parts.push(o))},r.prototype.flush=function(){if(this._pieces.length>0){var o=new Uint8Array(this._pieces);i.useArrayBufferView||(o=o.buffer),this._parts.push(o),this._pieces=[]}},r.prototype.getBuffer=function(){if(this.flush(),i.useBlobBuilder){for(var o=new n,s=0,c=this._parts.length;s<c;s++)o.append(this._parts[s]);return o.getBlob()}return new Blob(this._parts)},e.exports.BufferBuilder=r},{}],kdPp:[function(a,e,t){var i=a("./bufferbuilder").BufferBuilder,n=a("./bufferbuilder").binaryFeatures,r={unpack:function(l){return new o(l).unpack()},pack:function(l){var h=new s;return h.pack(l),h.getBuffer()}};function o(l){this.index=0,this.dataBuffer=l,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}function s(){this.bufferBuilder=new i}function c(l){var h=l.charCodeAt(0);return h<=2047?"00":h<=65535?"000":h<=2097151?"0000":h<=67108863?"00000":"000000"}function d(l){return l.length>600?new Blob([l]).size:l.replace(/[^\u0000-\u007F]/g,c).length}e.exports=r,o.prototype.unpack=function(){var l,h=this.unpack_uint8();if(h<128)return h;if((224^h)<32)return(224^h)-32;if((l=160^h)<=15)return this.unpack_raw(l);if((l=176^h)<=15)return this.unpack_string(l);if((l=144^h)<=15)return this.unpack_array(l);if((l=128^h)<=15)return this.unpack_map(l);switch(h){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:case 213:case 214:case 215:return;case 216:return l=this.unpack_uint16(),this.unpack_string(l);case 217:return l=this.unpack_uint32(),this.unpack_string(l);case 218:return l=this.unpack_uint16(),this.unpack_raw(l);case 219:return l=this.unpack_uint32(),this.unpack_raw(l);case 220:return l=this.unpack_uint16(),this.unpack_array(l);case 221:return l=this.unpack_uint32(),this.unpack_array(l);case 222:return l=this.unpack_uint16(),this.unpack_map(l);case 223:return l=this.unpack_uint32(),this.unpack_map(l)}},o.prototype.unpack_uint8=function(){var l=255&this.dataView[this.index];return this.index++,l},o.prototype.unpack_uint16=function(){var l=this.read(2),h=256*(255&l[0])+(255&l[1]);return this.index+=2,h},o.prototype.unpack_uint32=function(){var l=this.read(4),h=256*(256*(256*l[0]+l[1])+l[2])+l[3];return this.index+=4,h},o.prototype.unpack_uint64=function(){var l=this.read(8),h=256*(256*(256*(256*(256*(256*(256*l[0]+l[1])+l[2])+l[3])+l[4])+l[5])+l[6])+l[7];return this.index+=8,h},o.prototype.unpack_int8=function(){var l=this.unpack_uint8();return l<128?l:l-256},o.prototype.unpack_int16=function(){var l=this.unpack_uint16();return l<32768?l:l-65536},o.prototype.unpack_int32=function(){var l=this.unpack_uint32();return l<Math.pow(2,31)?l:l-Math.pow(2,32)},o.prototype.unpack_int64=function(){var l=this.unpack_uint64();return l<Math.pow(2,63)?l:l-Math.pow(2,64)},o.prototype.unpack_raw=function(l){if(this.length<this.index+l)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+l+" "+this.length);var h=this.dataBuffer.slice(this.index,this.index+l);return this.index+=l,h},o.prototype.unpack_string=function(l){for(var h,u,f=this.read(l),x=0,b="";x<l;)(h=f[x])<128?(b+=String.fromCharCode(h),x++):(192^h)<32?(u=(192^h)<<6|63&f[x+1],b+=String.fromCharCode(u),x+=2):(u=(15&h)<<12|(63&f[x+1])<<6|63&f[x+2],b+=String.fromCharCode(u),x+=3);return this.index+=l,b},o.prototype.unpack_array=function(l){for(var h=new Array(l),u=0;u<l;u++)h[u]=this.unpack();return h},o.prototype.unpack_map=function(l){for(var h={},u=0;u<l;u++){var f=this.unpack(),x=this.unpack();h[f]=x}return h},o.prototype.unpack_float=function(){var l=this.unpack_uint32(),h=(l>>23&255)-127;return(l>>31===0?1:-1)*(8388607&l|8388608)*Math.pow(2,h-23)},o.prototype.unpack_double=function(){var l=this.unpack_uint32(),h=this.unpack_uint32(),u=(l>>20&2047)-1023;return(l>>31===0?1:-1)*((1048575&l|1048576)*Math.pow(2,u-20)+h*Math.pow(2,u-52))},o.prototype.read=function(l){var h=this.index;if(h+l<=this.length)return this.dataView.subarray(h,h+l);throw new Error("BinaryPackFailure: read index out of range")},s.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},s.prototype.pack=function(l){var h=typeof l;if(h==="string")this.pack_string(l);else if(h==="number")Math.floor(l)===l?this.pack_integer(l):this.pack_double(l);else if(h==="boolean")l===!0?this.bufferBuilder.append(195):l===!1&&this.bufferBuilder.append(194);else if(h==="undefined")this.bufferBuilder.append(192);else{if(h!=="object")throw new Error('Type "'+h+'" not yet supported');if(l===null)this.bufferBuilder.append(192);else{var u=l.constructor;if(u==Array)this.pack_array(l);else if(u==Blob||u==File||l instanceof Blob||l instanceof File)this.pack_bin(l);else if(u==ArrayBuffer)n.useArrayBufferView?this.pack_bin(new Uint8Array(l)):this.pack_bin(l);else if("BYTES_PER_ELEMENT"in l)n.useArrayBufferView?this.pack_bin(new Uint8Array(l.buffer)):this.pack_bin(l.buffer);else if(u==Object||u.toString().startsWith("class"))this.pack_object(l);else if(u==Date)this.pack_string(l.toString());else{if(typeof l.toBinaryPack!="function")throw new Error('Type "'+u.toString()+'" not yet supported');this.bufferBuilder.append(l.toBinaryPack())}}}this.bufferBuilder.flush()},s.prototype.pack_bin=function(l){var h=l.length||l.byteLength||l.size;if(h<=15)this.pack_uint8(160+h);else if(h<=65535)this.bufferBuilder.append(218),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(219),this.pack_uint32(h)}this.bufferBuilder.append(l)},s.prototype.pack_string=function(l){var h=d(l);if(h<=15)this.pack_uint8(176+h);else if(h<=65535)this.bufferBuilder.append(216),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(217),this.pack_uint32(h)}this.bufferBuilder.append(l)},s.prototype.pack_array=function(l){var h=l.length;if(h<=15)this.pack_uint8(144+h);else if(h<=65535)this.bufferBuilder.append(220),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(221),this.pack_uint32(h)}for(var u=0;u<h;u++)this.pack(l[u])},s.prototype.pack_integer=function(l){if(l>=-32&&l<=127)this.bufferBuilder.append(255&l);else if(l>=0&&l<=255)this.bufferBuilder.append(204),this.pack_uint8(l);else if(l>=-128&&l<=127)this.bufferBuilder.append(208),this.pack_int8(l);else if(l>=0&&l<=65535)this.bufferBuilder.append(205),this.pack_uint16(l);else if(l>=-32768&&l<=32767)this.bufferBuilder.append(209),this.pack_int16(l);else if(l>=0&&l<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(l);else if(l>=-2147483648&&l<=2147483647)this.bufferBuilder.append(210),this.pack_int32(l);else if(l>=-9223372036854776e3&&l<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(l);else{if(!(l>=0&&l<=18446744073709552e3))throw new Error("Invalid integer");this.bufferBuilder.append(207),this.pack_uint64(l)}},s.prototype.pack_double=function(l){var h=0;l<0&&(h=1,l=-l);var u=Math.floor(Math.log(l)/Math.LN2),f=l/Math.pow(2,u)-1,x=Math.floor(f*Math.pow(2,52)),b=Math.pow(2,32),y=h<<31|u+1023<<20|x/b&1048575,g=x%b;this.bufferBuilder.append(203),this.pack_int32(y),this.pack_int32(g)},s.prototype.pack_object=function(l){var h=Object.keys(l).length;if(h<=15)this.pack_uint8(128+h);else if(h<=65535)this.bufferBuilder.append(222),this.pack_uint16(h);else{if(!(h<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(223),this.pack_uint32(h)}for(var u in l)l.hasOwnProperty(u)&&(this.pack(u),this.pack(l[u]))},s.prototype.pack_uint8=function(l){this.bufferBuilder.append(l)},s.prototype.pack_uint16=function(l){this.bufferBuilder.append(l>>8),this.bufferBuilder.append(255&l)},s.prototype.pack_uint32=function(l){var h=4294967295&l;this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h)},s.prototype.pack_uint64=function(l){var h=l/Math.pow(2,32),u=l%Math.pow(2,32);this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h),this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u)},s.prototype.pack_int8=function(l){this.bufferBuilder.append(255&l)},s.prototype.pack_int16=function(l){this.bufferBuilder.append((65280&l)>>8),this.bufferBuilder.append(255&l)},s.prototype.pack_int32=function(l){this.bufferBuilder.append(l>>>24&255),this.bufferBuilder.append((16711680&l)>>>16),this.bufferBuilder.append((65280&l)>>>8),this.bufferBuilder.append(255&l)},s.prototype.pack_int64=function(l){var h=Math.floor(l/Math.pow(2,32)),u=l%Math.pow(2,32);this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h),this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u)}},{"./bufferbuilder":"EgBh"}],iSxC:[function(a,e,t){"use strict";function i(p,m,v){return m in p?Object.defineProperty(p,m,{value:v,enumerable:!0,configurable:!0,writable:!0}):p[m]=v,p}function n(p){return(n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(m){return typeof m}:function(m){return m&&typeof Symbol=="function"&&m.constructor===Symbol&&m!==Symbol.prototype?"symbol":typeof m})(p)}Object.defineProperty(t,"__esModule",{value:!0}),t.extractVersion=s,t.wrapPeerConnectionEvent=c,t.disableLog=d,t.disableWarnings=l,t.log=h,t.deprecated=u,t.detectBrowser=f,t.compactObject=b,t.walkStats=y,t.filterStats=g;var r=!0,o=!0;function s(p,m,v){var w=p.match(m);return w&&w.length>=v&&parseInt(w[v],10)}function c(p,m,v){if(p.RTCPeerConnection){var w=p.RTCPeerConnection.prototype,E=w.addEventListener;w.addEventListener=function(T,R){if(T!==m)return E.apply(this,arguments);var I=function(O){var L=v(O);L&&(R.handleEvent?R.handleEvent(L):R(L))};return this._eventMap=this._eventMap||{},this._eventMap[m]||(this._eventMap[m]=new Map),this._eventMap[m].set(R,I),E.apply(this,[T,I])};var C=w.removeEventListener;w.removeEventListener=function(T,R){if(T!==m||!this._eventMap||!this._eventMap[m])return C.apply(this,arguments);if(!this._eventMap[m].has(R))return C.apply(this,arguments);var I=this._eventMap[m].get(R);return this._eventMap[m].delete(R),this._eventMap[m].size===0&&delete this._eventMap[m],Object.keys(this._eventMap).length===0&&delete this._eventMap,C.apply(this,[T,I])},Object.defineProperty(w,"on"+m,{get:function(){return this["_on"+m]},set:function(T){this["_on"+m]&&(this.removeEventListener(m,this["_on"+m]),delete this["_on"+m]),T&&this.addEventListener(m,this["_on"+m]=T)},enumerable:!0,configurable:!0})}}function d(p){return typeof p!="boolean"?new Error("Argument type: "+n(p)+". Please use a boolean."):(r=p,p?"adapter.js logging disabled":"adapter.js logging enabled")}function l(p){return typeof p!="boolean"?new Error("Argument type: "+n(p)+". Please use a boolean."):(o=!p,"adapter.js deprecation warnings "+(p?"disabled":"enabled"))}function h(){if((typeof window>"u"?"undefined":n(window))==="object"){if(r)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function u(p,m){o&&console.warn(p+" is deprecated, please use "+m+" instead.")}function f(p){var m={browser:null,version:null};if(p===void 0||!p.navigator)return m.browser="Not a browser.",m;var{navigator:v}=p;if(v.mozGetUserMedia)m.browser="firefox",m.version=s(v.userAgent,/Firefox\/(\d+)\./,1);else if(v.webkitGetUserMedia||p.isSecureContext===!1&&p.webkitRTCPeerConnection&&!p.RTCIceGatherer)m.browser="chrome",m.version=s(v.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(v.mediaDevices&&v.userAgent.match(/Edge\/(\d+).(\d+)$/))m.browser="edge",m.version=s(v.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!p.RTCPeerConnection||!v.userAgent.match(/AppleWebKit\/(\d+)\./))return m.browser="Not a supported browser.",m;m.browser="safari",m.version=s(v.userAgent,/AppleWebKit\/(\d+)\./,1),m.supportsUnifiedPlan=p.RTCRtpTransceiver&&"currentDirection"in p.RTCRtpTransceiver.prototype}return m}function x(p){return Object.prototype.toString.call(p)==="[object Object]"}function b(p){return x(p)?Object.keys(p).reduce(function(m,v){var w=x(p[v]),E=w?b(p[v]):p[v],C=w&&!Object.keys(E).length;return E===void 0||C?m:Object.assign(m,i({},v,E))},{}):p}function y(p,m,v){m&&!v.has(m.id)&&(v.set(m.id,m),Object.keys(m).forEach(function(w){w.endsWith("Id")?y(p,p.get(m[w]),v):w.endsWith("Ids")&&m[w].forEach(function(E){y(p,p.get(E),v)})}))}function g(p,m,v){var w=v?"outbound-rtp":"inbound-rtp",E=new Map;if(m===null)return E;var C=[];return p.forEach(function(T){T.type==="track"&&T.trackIdentifier===m.id&&C.push(T)}),C.forEach(function(T){p.forEach(function(R){R.type===w&&R.trackId===T.id&&y(p,R,E)})}),E}},{}],s6SN:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=c;var i=r(a("../utils.js"));function n(){if(typeof WeakMap!="function")return null;var d=new WeakMap;return n=function(){return d},d}function r(d){if(d&&d.__esModule)return d;if(d===null||typeof d!="object"&&typeof d!="function")return{default:d};var l=n();if(l&&l.has(d))return l.get(d);var h={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var f in d)if(Object.prototype.hasOwnProperty.call(d,f)){var x=u?Object.getOwnPropertyDescriptor(d,f):null;x&&(x.get||x.set)?Object.defineProperty(h,f,x):h[f]=d[f]}return h.default=d,l&&l.set(d,h),h}function o(d){return(o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l})(d)}var s=i.log;function c(d,l){var h=d&&d.navigator;if(h.mediaDevices){var u=function(y){if(o(y)!=="object"||y.mandatory||y.optional)return y;var g={};return Object.keys(y).forEach(function(p){if(p!=="require"&&p!=="advanced"&&p!=="mediaSource"){var m=o(y[p])==="object"?y[p]:{ideal:y[p]};m.exact!==void 0&&typeof m.exact=="number"&&(m.min=m.max=m.exact);var v=function(E,C){return E?E+C.charAt(0).toUpperCase()+C.slice(1):C==="deviceId"?"sourceId":C};if(m.ideal!==void 0){g.optional=g.optional||[];var w={};typeof m.ideal=="number"?(w[v("min",p)]=m.ideal,g.optional.push(w),(w={})[v("max",p)]=m.ideal,g.optional.push(w)):(w[v("",p)]=m.ideal,g.optional.push(w))}m.exact!==void 0&&typeof m.exact!="number"?(g.mandatory=g.mandatory||{},g.mandatory[v("",p)]=m.exact):["min","max"].forEach(function(E){m[E]!==void 0&&(g.mandatory=g.mandatory||{},g.mandatory[v(E,p)]=m[E])})}}),y.advanced&&(g.optional=(g.optional||[]).concat(y.advanced)),g},f=function(y,g){if(l.version>=61)return g(y);if((y=JSON.parse(JSON.stringify(y)))&&o(y.audio)==="object"){var p=function(E,C,T){C in E&&!(T in E)&&(E[T]=E[C],delete E[C])};p((y=JSON.parse(JSON.stringify(y))).audio,"autoGainControl","googAutoGainControl"),p(y.audio,"noiseSuppression","googNoiseSuppression"),y.audio=u(y.audio)}if(y&&o(y.video)==="object"){var m=y.video.facingMode;m=m&&(o(m)==="object"?m:{ideal:m});var v,w=l.version<66;if(m&&(m.exact==="user"||m.exact==="environment"||m.ideal==="user"||m.ideal==="environment")&&(!h.mediaDevices.getSupportedConstraints||!h.mediaDevices.getSupportedConstraints().facingMode||w)&&(delete y.video.facingMode,m.exact==="environment"||m.ideal==="environment"?v=["back","rear"]:m.exact!=="user"&&m.ideal!=="user"||(v=["front"]),v))return h.mediaDevices.enumerateDevices().then(function(E){var C=(E=E.filter(function(T){return T.kind==="videoinput"})).find(function(T){return v.some(function(R){return T.label.toLowerCase().includes(R)})});return!C&&E.length&&v.includes("back")&&(C=E[E.length-1]),C&&(y.video.deviceId=m.exact?{exact:C.deviceId}:{ideal:C.deviceId}),y.video=u(y.video),s("chrome: "+JSON.stringify(y)),g(y)});y.video=u(y.video)}return s("chrome: "+JSON.stringify(y)),g(y)},x=function(y){return l.version>=64?y:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[y.name]||y.name,message:y.message,constraint:y.constraint||y.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(h.getUserMedia=function(y,g,p){f(y,function(m){h.webkitGetUserMedia(m,g,function(v){p&&p(x(v))})})}.bind(h),h.mediaDevices.getUserMedia){var b=h.mediaDevices.getUserMedia.bind(h.mediaDevices);h.mediaDevices.getUserMedia=function(y){return f(y,function(g){return b(g).then(function(p){if(g.audio&&!p.getAudioTracks().length||g.video&&!p.getVideoTracks().length)throw p.getTracks().forEach(function(m){m.stop()}),new DOMException("","NotFoundError");return p},function(p){return Promise.reject(x(p))})})}}}}},{"../utils.js":"iSxC"}],VHa8:[function(a,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(typeof r=="function"?n.navigator.mediaDevices.getDisplayMedia=function(o){return r(o).then(function(s){var c=o.video&&o.video.width,d=o.video&&o.video.height,l=o.video&&o.video.frameRate;return o.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:s,maxFrameRate:l||3}},c&&(o.video.mandatory.maxWidth=c),d&&(o.video.mandatory.maxHeight=d),n.navigator.mediaDevices.getUserMedia(o)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],uI5X:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimMediaStream=l,t.shimOnTrack=h,t.shimGetSendersWithDtmf=u,t.shimGetStats=f,t.shimSenderReceiverGetStats=x,t.shimAddTrackRemoveTrackWithNative=b,t.shimAddTrackRemoveTrack=y,t.shimPeerConnection=g,t.fixNegotiationNeeded=p,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}});var i=s(a("../utils.js")),n=a("./getusermedia"),r=a("./getdisplaymedia");function o(){if(typeof WeakMap!="function")return null;var m=new WeakMap;return o=function(){return m},m}function s(m){if(m&&m.__esModule)return m;if(m===null||typeof m!="object"&&typeof m!="function")return{default:m};var v=o();if(v&&v.has(m))return v.get(m);var w={},E=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var C in m)if(Object.prototype.hasOwnProperty.call(m,C)){var T=E?Object.getOwnPropertyDescriptor(m,C):null;T&&(T.get||T.set)?Object.defineProperty(w,C,T):w[C]=m[C]}return w.default=m,v&&v.set(m,w),w}function c(m,v,w){return v in m?Object.defineProperty(m,v,{value:w,enumerable:!0,configurable:!0,writable:!0}):m[v]=w,m}function d(m){return(d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(v){return typeof v}:function(v){return v&&typeof Symbol=="function"&&v.constructor===Symbol&&v!==Symbol.prototype?"symbol":typeof v})(m)}function l(m){m.MediaStream=m.MediaStream||m.webkitMediaStream}function h(m){if(d(m)!=="object"||!m.RTCPeerConnection||"ontrack"in m.RTCPeerConnection.prototype)i.wrapPeerConnectionEvent(m,"track",function(w){return w.transceiver||Object.defineProperty(w,"transceiver",{value:{receiver:w.receiver}}),w});else{Object.defineProperty(m.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(w){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=w)},enumerable:!0,configurable:!0});var v=m.RTCPeerConnection.prototype.setRemoteDescription;m.RTCPeerConnection.prototype.setRemoteDescription=function(){var w=this;return this._ontrackpoly||(this._ontrackpoly=function(E){E.stream.addEventListener("addtrack",function(C){var T;T=m.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(I){return I.track&&I.track.id===C.track.id}):{track:C.track};var R=new Event("track");R.track=C.track,R.receiver=T,R.transceiver={receiver:T},R.streams=[E.stream],w.dispatchEvent(R)}),E.stream.getTracks().forEach(function(C){var T;T=m.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(I){return I.track&&I.track.id===C.id}):{track:C};var R=new Event("track");R.track=C,R.receiver=T,R.transceiver={receiver:T},R.streams=[E.stream],w.dispatchEvent(R)})},this.addEventListener("addstream",this._ontrackpoly)),v.apply(this,arguments)}}}function u(m){if(d(m)==="object"&&m.RTCPeerConnection&&!("getSenders"in m.RTCPeerConnection.prototype)&&"createDTMFSender"in m.RTCPeerConnection.prototype){var v=function(I,O){return{track:O,get dtmf(){return this._dtmf===void 0&&(O.kind==="audio"?this._dtmf=I.createDTMFSender(O):this._dtmf=null),this._dtmf},_pc:I}};if(!m.RTCPeerConnection.prototype.getSenders){m.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var w=m.RTCPeerConnection.prototype.addTrack;m.RTCPeerConnection.prototype.addTrack=function(I,O){var L=w.apply(this,arguments);return L||(L=v(this,I),this._senders.push(L)),L};var E=m.RTCPeerConnection.prototype.removeTrack;m.RTCPeerConnection.prototype.removeTrack=function(I){E.apply(this,arguments);var O=this._senders.indexOf(I);O!==-1&&this._senders.splice(O,1)}}var C=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(I){var O=this;this._senders=this._senders||[],C.apply(this,[I]),I.getTracks().forEach(function(L){O._senders.push(v(O,L))})};var T=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(I){var O=this;this._senders=this._senders||[],T.apply(this,[I]),I.getTracks().forEach(function(L){var A=O._senders.find(function(F){return F.track===L});A&&O._senders.splice(O._senders.indexOf(A),1)})}}else if(d(m)==="object"&&m.RTCPeerConnection&&"getSenders"in m.RTCPeerConnection.prototype&&"createDTMFSender"in m.RTCPeerConnection.prototype&&m.RTCRtpSender&&!("dtmf"in m.RTCRtpSender.prototype)){var R=m.RTCPeerConnection.prototype.getSenders;m.RTCPeerConnection.prototype.getSenders=function(){var I=this,O=R.apply(this,[]);return O.forEach(function(L){return L._pc=I}),O},Object.defineProperty(m.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function f(m){if(m.RTCPeerConnection){var v=m.RTCPeerConnection.prototype.getStats;m.RTCPeerConnection.prototype.getStats=function(){var w=this,[E,C,T]=arguments;if(arguments.length>0&&typeof E=="function")return v.apply(this,arguments);if(v.length===0&&(arguments.length===0||typeof E!="function"))return v.apply(this,[]);var R=function(O){var L={};return O.result().forEach(function(A){var F={id:A.id,timestamp:A.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[A.type]||A.type};A.names().forEach(function(H){F[H]=A.stat(H)}),L[F.id]=F}),L},I=function(O){return new Map(Object.keys(O).map(function(L){return[L,O[L]]}))};return arguments.length>=2?v.apply(this,[function(O){C(I(R(O)))},E]):new Promise(function(O,L){v.apply(w,[function(A){O(I(R(A)))},L])}).then(C,T)}}}function x(m){if(d(m)==="object"&&m.RTCPeerConnection&&m.RTCRtpSender&&m.RTCRtpReceiver){if(!("getStats"in m.RTCRtpSender.prototype)){var v=m.RTCPeerConnection.prototype.getSenders;v&&(m.RTCPeerConnection.prototype.getSenders=function(){var T=this,R=v.apply(this,[]);return R.forEach(function(I){return I._pc=T}),R});var w=m.RTCPeerConnection.prototype.addTrack;w&&(m.RTCPeerConnection.prototype.addTrack=function(){var T=w.apply(this,arguments);return T._pc=this,T}),m.RTCRtpSender.prototype.getStats=function(){var T=this;return this._pc.getStats().then(function(R){return i.filterStats(R,T.track,!0)})}}if(!("getStats"in m.RTCRtpReceiver.prototype)){var E=m.RTCPeerConnection.prototype.getReceivers;E&&(m.RTCPeerConnection.prototype.getReceivers=function(){var T=this,R=E.apply(this,[]);return R.forEach(function(I){return I._pc=T}),R}),i.wrapPeerConnectionEvent(m,"track",function(T){return T.receiver._pc=T.srcElement,T}),m.RTCRtpReceiver.prototype.getStats=function(){var T=this;return this._pc.getStats().then(function(R){return i.filterStats(R,T.track,!1)})}}if("getStats"in m.RTCRtpSender.prototype&&"getStats"in m.RTCRtpReceiver.prototype){var C=m.RTCPeerConnection.prototype.getStats;m.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof m.MediaStreamTrack){var T,R,I,O=arguments[0];return this.getSenders().forEach(function(L){L.track===O&&(T?I=!0:T=L)}),this.getReceivers().forEach(function(L){return L.track===O&&(R?I=!0:R=L),L.track===O}),I||T&&R?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):T?T.getStats():R?R.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return C.apply(this,arguments)}}}}function b(m){m.RTCPeerConnection.prototype.getLocalStreams=function(){var T=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(R){return T._shimmedLocalStreams[R][0]})};var v=m.RTCPeerConnection.prototype.addTrack;m.RTCPeerConnection.prototype.addTrack=function(T,R){if(!R)return v.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var I=v.apply(this,arguments);return this._shimmedLocalStreams[R.id]?this._shimmedLocalStreams[R.id].indexOf(I)===-1&&this._shimmedLocalStreams[R.id].push(I):this._shimmedLocalStreams[R.id]=[R,I],I};var w=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(T){var R=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},T.getTracks().forEach(function(L){if(R.getSenders().find(function(A){return A.track===L}))throw new DOMException("Track already exists.","InvalidAccessError")});var I=this.getSenders();w.apply(this,arguments);var O=this.getSenders().filter(function(L){return I.indexOf(L)===-1});this._shimmedLocalStreams[T.id]=[T].concat(O)};var E=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(T){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[T.id],E.apply(this,arguments)};var C=m.RTCPeerConnection.prototype.removeTrack;m.RTCPeerConnection.prototype.removeTrack=function(T){var R=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},T&&Object.keys(this._shimmedLocalStreams).forEach(function(I){var O=R._shimmedLocalStreams[I].indexOf(T);O!==-1&&R._shimmedLocalStreams[I].splice(O,1),R._shimmedLocalStreams[I].length===1&&delete R._shimmedLocalStreams[I]}),C.apply(this,arguments)}}function y(m,v){if(m.RTCPeerConnection){if(m.RTCPeerConnection.prototype.addTrack&&v.version>=65)return b(m);var w=m.RTCPeerConnection.prototype.getLocalStreams;m.RTCPeerConnection.prototype.getLocalStreams=function(){var O=this,L=w.apply(this);return this._reverseStreams=this._reverseStreams||{},L.map(function(A){return O._reverseStreams[A.id]})};var E=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(O){var L=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},O.getTracks().forEach(function(F){if(L.getSenders().find(function(H){return H.track===F}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[O.id]){var A=new m.MediaStream(O.getTracks());this._streams[O.id]=A,this._reverseStreams[A.id]=O,O=A}E.apply(this,[O])};var C=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(O){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},C.apply(this,[this._streams[O.id]||O]),delete this._reverseStreams[this._streams[O.id]?this._streams[O.id].id:O.id],delete this._streams[O.id]},m.RTCPeerConnection.prototype.addTrack=function(O,L){var A=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var F=[].slice.call(arguments,1);if(F.length!==1||!F[0].getTracks().find(function(q){return q===O}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(function(q){return q.track===O}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var H=this._streams[L.id];if(H)H.addTrack(O),Promise.resolve().then(function(){A.dispatchEvent(new Event("negotiationneeded"))});else{var z=new m.MediaStream([O]);this._streams[L.id]=z,this._reverseStreams[z.id]=L,this.addStream(z)}return this.getSenders().find(function(q){return q.track===O})},["createOffer","createAnswer"].forEach(function(O){var L=m.RTCPeerConnection.prototype[O],A=c({},O,function(){var F=this,H=arguments;return arguments.length&&typeof arguments[0]=="function"?L.apply(this,[function(z){var q=I(F,z);H[0].apply(null,[q])},function(z){H[1]&&H[1].apply(null,z)},arguments[2]]):L.apply(this,arguments).then(function(z){return I(F,z)})});m.RTCPeerConnection.prototype[O]=A[O]});var T=m.RTCPeerConnection.prototype.setLocalDescription;m.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(O=this,L=arguments[0],A=L.sdp,Object.keys(O._reverseStreams||[]).forEach(function(F){var H=O._reverseStreams[F],z=O._streams[H.id];A=A.replace(new RegExp(H.id,"g"),z.id)}),new RTCSessionDescription({type:L.type,sdp:A})),T.apply(this,arguments)):T.apply(this,arguments);var O,L,A};var R=Object.getOwnPropertyDescriptor(m.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(m.RTCPeerConnection.prototype,"localDescription",{get:function(){var O=R.get.apply(this);return O.type===""?O:I(this,O)}}),m.RTCPeerConnection.prototype.removeTrack=function(O){var L,A=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!O._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(O._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(function(F){A._streams[F].getTracks().find(function(H){return O.track===H})&&(L=A._streams[F])}),L&&(L.getTracks().length===1?this.removeStream(this._reverseStreams[L.id]):L.removeTrack(O.track),this.dispatchEvent(new Event("negotiationneeded")))}}function I(O,L){var A=L.sdp;return Object.keys(O._reverseStreams||[]).forEach(function(F){var H=O._reverseStreams[F],z=O._streams[H.id];A=A.replace(new RegExp(z.id,"g"),H.id)}),new RTCSessionDescription({type:L.type,sdp:A})}}function g(m,v){!m.RTCPeerConnection&&m.webkitRTCPeerConnection&&(m.RTCPeerConnection=m.webkitRTCPeerConnection),m.RTCPeerConnection&&v.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(w){var E=m.RTCPeerConnection.prototype[w],C=c({},w,function(){return arguments[0]=new(w==="addIceCandidate"?m.RTCIceCandidate:m.RTCSessionDescription)(arguments[0]),E.apply(this,arguments)});m.RTCPeerConnection.prototype[w]=C[w]})}function p(m,v){i.wrapPeerConnectionEvent(m,"negotiationneeded",function(w){var E=w.target;if(!(v.version<72||E.getConfiguration&&E.getConfiguration().sdpSemantics==="plan-b")||E.signalingState==="stable")return w})}},{"../utils.js":"iSxC","./getusermedia":"s6SN","./getdisplaymedia":"VHa8"}],NZ1C:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterIceServers=o;var i=r(a("../utils"));function n(){if(typeof WeakMap!="function")return null;var s=new WeakMap;return n=function(){return s},s}function r(s){if(s&&s.__esModule)return s;if(s===null||typeof s!="object"&&typeof s!="function")return{default:s};var c=n();if(c&&c.has(s))return c.get(s);var d={},l=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in s)if(Object.prototype.hasOwnProperty.call(s,h)){var u=l?Object.getOwnPropertyDescriptor(s,h):null;u&&(u.get||u.set)?Object.defineProperty(d,h,u):d[h]=s[h]}return d.default=s,c&&c.set(s,d),d}function o(s,c){var d=!1;return(s=JSON.parse(JSON.stringify(s))).filter(function(l){if(l&&(l.urls||l.url)){var h=l.urls||l.url;l.url&&!l.urls&&i.deprecated("RTCIceServer.url","RTCIceServer.urls");var u=typeof h=="string";return u&&(h=[h]),h=h.filter(function(f){if(f.indexOf("stun:")===0)return!1;var x=f.startsWith("turn")&&!f.startsWith("turn:[")&&f.includes("transport=udp");return x&&!d?(d=!0,!0):x&&!d}),delete l.url,l.urls=u?h[0]:h,!!h.length}})}},{"../utils":"iSxC"}],YHvh:[function(a,e,t){"use strict";var i={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};i.localCName=i.generateIdentifier(),i.splitLines=function(n){return n.trim().split(`
2
- `).map(function(r){return r.trim()})},i.splitSections=function(n){return n.split(`
3
- m=`).map(function(r,o){return(o>0?"m="+r:r).trim()+`\r
4
- `})},i.getDescription=function(n){var r=i.splitSections(n);return r&&r[0]},i.getMediaSections=function(n){var r=i.splitSections(n);return r.shift(),r},i.matchPrefix=function(n,r){return i.splitLines(n).filter(function(o){return o.indexOf(r)===0})},i.parseCandidate=function(n){for(var r,o={foundation:(r=n.indexOf("a=candidate:")===0?n.substring(12).split(" "):n.substring(10).split(" "))[0],component:parseInt(r[1],10),protocol:r[2].toLowerCase(),priority:parseInt(r[3],10),ip:r[4],address:r[4],port:parseInt(r[5],10),type:r[7]},s=8;s<r.length;s+=2)switch(r[s]){case"raddr":o.relatedAddress=r[s+1];break;case"rport":o.relatedPort=parseInt(r[s+1],10);break;case"tcptype":o.tcpType=r[s+1];break;case"ufrag":o.ufrag=r[s+1],o.usernameFragment=r[s+1];break;default:o[r[s]]=r[s+1]}return o},i.writeCandidate=function(n){var r=[];r.push(n.foundation),r.push(n.component),r.push(n.protocol.toUpperCase()),r.push(n.priority),r.push(n.address||n.ip),r.push(n.port);var o=n.type;return r.push("typ"),r.push(o),o!=="host"&&n.relatedAddress&&n.relatedPort&&(r.push("raddr"),r.push(n.relatedAddress),r.push("rport"),r.push(n.relatedPort)),n.tcpType&&n.protocol.toLowerCase()==="tcp"&&(r.push("tcptype"),r.push(n.tcpType)),(n.usernameFragment||n.ufrag)&&(r.push("ufrag"),r.push(n.usernameFragment||n.ufrag)),"candidate:"+r.join(" ")},i.parseIceOptions=function(n){return n.substr(14).split(" ")},i.parseRtpMap=function(n){var r=n.substr(9).split(" "),o={payloadType:parseInt(r.shift(),10)};return r=r[0].split("/"),o.name=r[0],o.clockRate=parseInt(r[1],10),o.channels=r.length===3?parseInt(r[2],10):1,o.numChannels=o.channels,o},i.writeRtpMap=function(n){var r=n.payloadType;n.preferredPayloadType!==void 0&&(r=n.preferredPayloadType);var o=n.channels||n.numChannels||1;return"a=rtpmap:"+r+" "+n.name+"/"+n.clockRate+(o!==1?"/"+o:"")+`\r
5
- `},i.parseExtmap=function(n){var r=n.substr(9).split(" ");return{id:parseInt(r[0],10),direction:r[0].indexOf("/")>0?r[0].split("/")[1]:"sendrecv",uri:r[1]}},i.writeExtmap=function(n){return"a=extmap:"+(n.id||n.preferredId)+(n.direction&&n.direction!=="sendrecv"?"/"+n.direction:"")+" "+n.uri+`\r
6
- `},i.parseFmtp=function(n){for(var r,o={},s=n.substr(n.indexOf(" ")+1).split(";"),c=0;c<s.length;c++)o[(r=s[c].trim().split("="))[0].trim()]=r[1];return o},i.writeFmtp=function(n){var r="",o=n.payloadType;if(n.preferredPayloadType!==void 0&&(o=n.preferredPayloadType),n.parameters&&Object.keys(n.parameters).length){var s=[];Object.keys(n.parameters).forEach(function(c){n.parameters[c]?s.push(c+"="+n.parameters[c]):s.push(c)}),r+="a=fmtp:"+o+" "+s.join(";")+`\r
7
- `}return r},i.parseRtcpFb=function(n){var r=n.substr(n.indexOf(" ")+1).split(" ");return{type:r.shift(),parameter:r.join(" ")}},i.writeRtcpFb=function(n){var r="",o=n.payloadType;return n.preferredPayloadType!==void 0&&(o=n.preferredPayloadType),n.rtcpFeedback&&n.rtcpFeedback.length&&n.rtcpFeedback.forEach(function(s){r+="a=rtcp-fb:"+o+" "+s.type+(s.parameter&&s.parameter.length?" "+s.parameter:"")+`\r
8
- `}),r},i.parseSsrcMedia=function(n){var r=n.indexOf(" "),o={ssrc:parseInt(n.substr(7,r-7),10)},s=n.indexOf(":",r);return s>-1?(o.attribute=n.substr(r+1,s-r-1),o.value=n.substr(s+1)):o.attribute=n.substr(r+1),o},i.parseSsrcGroup=function(n){var r=n.substr(13).split(" ");return{semantics:r.shift(),ssrcs:r.map(function(o){return parseInt(o,10)})}},i.getMid=function(n){var r=i.matchPrefix(n,"a=mid:")[0];if(r)return r.substr(6)},i.parseFingerprint=function(n){var r=n.substr(14).split(" ");return{algorithm:r[0].toLowerCase(),value:r[1]}},i.getDtlsParameters=function(n,r){return{role:"auto",fingerprints:i.matchPrefix(n+r,"a=fingerprint:").map(i.parseFingerprint)}},i.writeDtlsParameters=function(n,r){var o="a=setup:"+r+`\r
9
- `;return n.fingerprints.forEach(function(s){o+="a=fingerprint:"+s.algorithm+" "+s.value+`\r
10
- `}),o},i.parseCryptoLine=function(n){var r=n.substr(9).split(" ");return{tag:parseInt(r[0],10),cryptoSuite:r[1],keyParams:r[2],sessionParams:r.slice(3)}},i.writeCryptoLine=function(n){return"a=crypto:"+n.tag+" "+n.cryptoSuite+" "+(typeof n.keyParams=="object"?i.writeCryptoKeyParams(n.keyParams):n.keyParams)+(n.sessionParams?" "+n.sessionParams.join(" "):"")+`\r
11
- `},i.parseCryptoKeyParams=function(n){if(n.indexOf("inline:")!==0)return null;var r=n.substr(7).split("|");return{keyMethod:"inline",keySalt:r[0],lifeTime:r[1],mkiValue:r[2]?r[2].split(":")[0]:void 0,mkiLength:r[2]?r[2].split(":")[1]:void 0}},i.writeCryptoKeyParams=function(n){return n.keyMethod+":"+n.keySalt+(n.lifeTime?"|"+n.lifeTime:"")+(n.mkiValue&&n.mkiLength?"|"+n.mkiValue+":"+n.mkiLength:"")},i.getCryptoParameters=function(n,r){return i.matchPrefix(n+r,"a=crypto:").map(i.parseCryptoLine)},i.getIceParameters=function(n,r){var o=i.matchPrefix(n+r,"a=ice-ufrag:")[0],s=i.matchPrefix(n+r,"a=ice-pwd:")[0];return o&&s?{usernameFragment:o.substr(12),password:s.substr(10)}:null},i.writeIceParameters=function(n){return"a=ice-ufrag:"+n.usernameFragment+`\r
12
- a=ice-pwd:`+n.password+`\r
13
- `},i.parseRtpParameters=function(n){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},o=i.splitLines(n)[0].split(" "),s=3;s<o.length;s++){var c=o[s],d=i.matchPrefix(n,"a=rtpmap:"+c+" ")[0];if(d){var l=i.parseRtpMap(d),h=i.matchPrefix(n,"a=fmtp:"+c+" ");switch(l.parameters=h.length?i.parseFmtp(h[0]):{},l.rtcpFeedback=i.matchPrefix(n,"a=rtcp-fb:"+c+" ").map(i.parseRtcpFb),r.codecs.push(l),l.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(l.name.toUpperCase())}}}return i.matchPrefix(n,"a=extmap:").forEach(function(u){r.headerExtensions.push(i.parseExtmap(u))}),r},i.writeRtpDescription=function(n,r){var o="";o+="m="+n+" ",o+=r.codecs.length>0?"9":"0",o+=" UDP/TLS/RTP/SAVPF ",o+=r.codecs.map(function(c){return c.preferredPayloadType!==void 0?c.preferredPayloadType:c.payloadType}).join(" ")+`\r
14
- `,o+=`c=IN IP4 0.0.0.0\r
15
- `,o+=`a=rtcp:9 IN IP4 0.0.0.0\r
16
- `,r.codecs.forEach(function(c){o+=i.writeRtpMap(c),o+=i.writeFmtp(c),o+=i.writeRtcpFb(c)});var s=0;return r.codecs.forEach(function(c){c.maxptime>s&&(s=c.maxptime)}),s>0&&(o+="a=maxptime:"+s+`\r
17
- `),o+=`a=rtcp-mux\r
18
- `,r.headerExtensions&&r.headerExtensions.forEach(function(c){o+=i.writeExtmap(c)}),o},i.parseRtpEncodingParameters=function(n){var r,o=[],s=i.parseRtpParameters(n),c=s.fecMechanisms.indexOf("RED")!==-1,d=s.fecMechanisms.indexOf("ULPFEC")!==-1,l=i.matchPrefix(n,"a=ssrc:").map(function(x){return i.parseSsrcMedia(x)}).filter(function(x){return x.attribute==="cname"}),h=l.length>0&&l[0].ssrc,u=i.matchPrefix(n,"a=ssrc-group:FID").map(function(x){return x.substr(17).split(" ").map(function(b){return parseInt(b,10)})});u.length>0&&u[0].length>1&&u[0][0]===h&&(r=u[0][1]),s.codecs.forEach(function(x){if(x.name.toUpperCase()==="RTX"&&x.parameters.apt){var b={ssrc:h,codecPayloadType:parseInt(x.parameters.apt,10)};h&&r&&(b.rtx={ssrc:r}),o.push(b),c&&((b=JSON.parse(JSON.stringify(b))).fec={ssrc:h,mechanism:d?"red+ulpfec":"red"},o.push(b))}}),o.length===0&&h&&o.push({ssrc:h});var f=i.matchPrefix(n,"b=");return f.length&&(f=f[0].indexOf("b=TIAS:")===0?parseInt(f[0].substr(7),10):f[0].indexOf("b=AS:")===0?1e3*parseInt(f[0].substr(5),10)*.95-16e3:void 0,o.forEach(function(x){x.maxBitrate=f})),o},i.parseRtcpParameters=function(n){var r={},o=i.matchPrefix(n,"a=ssrc:").map(function(d){return i.parseSsrcMedia(d)}).filter(function(d){return d.attribute==="cname"})[0];o&&(r.cname=o.value,r.ssrc=o.ssrc);var s=i.matchPrefix(n,"a=rtcp-rsize");r.reducedSize=s.length>0,r.compound=s.length===0;var c=i.matchPrefix(n,"a=rtcp-mux");return r.mux=c.length>0,r},i.parseMsid=function(n){var r,o=i.matchPrefix(n,"a=msid:");if(o.length===1)return{stream:(r=o[0].substr(7).split(" "))[0],track:r[1]};var s=i.matchPrefix(n,"a=ssrc:").map(function(c){return i.parseSsrcMedia(c)}).filter(function(c){return c.attribute==="msid"});return s.length>0?{stream:(r=s[0].value.split(" "))[0],track:r[1]}:void 0},i.parseSctpDescription=function(n){var r,o=i.parseMLine(n),s=i.matchPrefix(n,"a=max-message-size:");s.length>0&&(r=parseInt(s[0].substr(19),10)),isNaN(r)&&(r=65536);var c=i.matchPrefix(n,"a=sctp-port:");if(c.length>0)return{port:parseInt(c[0].substr(12),10),protocol:o.fmt,maxMessageSize:r};if(i.matchPrefix(n,"a=sctpmap:").length>0){var d=i.matchPrefix(n,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:r}}},i.writeSctpDescription=function(n,r){var o=[];return o=n.protocol!=="DTLS/SCTP"?["m="+n.kind+" 9 "+n.protocol+" "+r.protocol+`\r
1
+ var Kp=Object.create;var Fo=Object.defineProperty;var nu=Object.getOwnPropertyDescriptor;var Jp=Object.getOwnPropertyNames;var Zp=Object.getPrototypeOf,$p=Object.prototype.hasOwnProperty;var ef=(o,e,t)=>e in o?Fo(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var hl=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+o+'" is not supported')});var Bo=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),iu=(o,e)=>{for(var t in e)Fo(o,t,{get:e[t],enumerable:!0})},tf=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Jp(e))!$p.call(o,i)&&i!==t&&Fo(o,i,{get:()=>e[i],enumerable:!(n=nu(e,i))||n.enumerable});return o};var Cs=(o,e,t)=>(t=o!=null?Kp(Zp(o)):{},tf(e||!o||!o.__esModule?Fo(t,"default",{value:o,enumerable:!0}):t,o));var C=(o,e,t,n)=>{for(var i=n>1?void 0:n?nu(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Fo(e,t,i),i};var j=(o,e,t)=>(ef(o,typeof e!="symbol"?e+"":e,t),t);var ta=Bo((eh,Xl)=>{parcelRequire=function(o,e,t,n){var i,r=typeof parcelRequire=="function"&&parcelRequire,s=typeof hl=="function"&&hl;function a(l,u){if(!e[l]){if(!o[l]){var h=typeof parcelRequire=="function"&&parcelRequire;if(!u&&h)return h(l,!0);if(r)return r(l,!0);if(s&&typeof l=="string")return s(l);var b=new Error("Cannot find module '"+l+"'");throw b.code="MODULE_NOT_FOUND",b}v.resolve=function(y){return o[l][1][y]||y},v.cache={};var _=e[l]=new a.Module(l);o[l][0].call(_.exports,v,_,_.exports,this)}return e[l].exports;function v(y){return a(v.resolve(y))}}a.isParcelRequire=!0,a.Module=function(l){this.id=l,this.bundle=a,this.exports={}},a.modules=o,a.cache=e,a.parent=r,a.register=function(l,u){o[l]=[function(h,b){b.exports=u},{}]};for(var c=0;c<t.length;c++)try{a(t[c])}catch(l){i||(i=l)}if(t.length){var d=a(t[t.length-1]);typeof eh=="object"&&typeof Xl<"u"?Xl.exports=d:typeof define=="function"&&define.amd?define(function(){return d}):n&&(this[n]=d)}if(parcelRequire=a,i)throw i;return a}({EgBh:[function(o,e,t){var n={};n.useBlobBuilder=function(){try{return new Blob([]),!1}catch{return!0}}(),n.useArrayBufferView=!n.useBlobBuilder&&function(){try{return new Blob([new Uint8Array([])]).size===0}catch{return!0}}(),e.exports.binaryFeatures=n;var i=e.exports.BlobBuilder;function r(){this._pieces=[],this._parts=[]}typeof window<"u"&&(i=e.exports.BlobBuilder=window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder||window.BlobBuilder),r.prototype.append=function(s){typeof s=="number"?this._pieces.push(s):(this.flush(),this._parts.push(s))},r.prototype.flush=function(){if(this._pieces.length>0){var s=new Uint8Array(this._pieces);n.useArrayBufferView||(s=s.buffer),this._parts.push(s),this._pieces=[]}},r.prototype.getBuffer=function(){if(this.flush(),n.useBlobBuilder){for(var s=new i,a=0,c=this._parts.length;a<c;a++)s.append(this._parts[a]);return s.getBlob()}return new Blob(this._parts)},e.exports.BufferBuilder=r},{}],kdPp:[function(o,e,t){var n=o("./bufferbuilder").BufferBuilder,i=o("./bufferbuilder").binaryFeatures,r={unpack:function(l){return new s(l).unpack()},pack:function(l){var u=new a;return u.pack(l),u.getBuffer()}};function s(l){this.index=0,this.dataBuffer=l,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}function a(){this.bufferBuilder=new n}function c(l){var u=l.charCodeAt(0);return u<=2047?"00":u<=65535?"000":u<=2097151?"0000":u<=67108863?"00000":"000000"}function d(l){return l.length>600?new Blob([l]).size:l.replace(/[^\u0000-\u007F]/g,c).length}e.exports=r,s.prototype.unpack=function(){var l,u=this.unpack_uint8();if(u<128)return u;if((224^u)<32)return(224^u)-32;if((l=160^u)<=15)return this.unpack_raw(l);if((l=176^u)<=15)return this.unpack_string(l);if((l=144^u)<=15)return this.unpack_array(l);if((l=128^u)<=15)return this.unpack_map(l);switch(u){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:case 213:case 214:case 215:return;case 216:return l=this.unpack_uint16(),this.unpack_string(l);case 217:return l=this.unpack_uint32(),this.unpack_string(l);case 218:return l=this.unpack_uint16(),this.unpack_raw(l);case 219:return l=this.unpack_uint32(),this.unpack_raw(l);case 220:return l=this.unpack_uint16(),this.unpack_array(l);case 221:return l=this.unpack_uint32(),this.unpack_array(l);case 222:return l=this.unpack_uint16(),this.unpack_map(l);case 223:return l=this.unpack_uint32(),this.unpack_map(l)}},s.prototype.unpack_uint8=function(){var l=255&this.dataView[this.index];return this.index++,l},s.prototype.unpack_uint16=function(){var l=this.read(2),u=256*(255&l[0])+(255&l[1]);return this.index+=2,u},s.prototype.unpack_uint32=function(){var l=this.read(4),u=256*(256*(256*l[0]+l[1])+l[2])+l[3];return this.index+=4,u},s.prototype.unpack_uint64=function(){var l=this.read(8),u=256*(256*(256*(256*(256*(256*(256*l[0]+l[1])+l[2])+l[3])+l[4])+l[5])+l[6])+l[7];return this.index+=8,u},s.prototype.unpack_int8=function(){var l=this.unpack_uint8();return l<128?l:l-256},s.prototype.unpack_int16=function(){var l=this.unpack_uint16();return l<32768?l:l-65536},s.prototype.unpack_int32=function(){var l=this.unpack_uint32();return l<Math.pow(2,31)?l:l-Math.pow(2,32)},s.prototype.unpack_int64=function(){var l=this.unpack_uint64();return l<Math.pow(2,63)?l:l-Math.pow(2,64)},s.prototype.unpack_raw=function(l){if(this.length<this.index+l)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+l+" "+this.length);var u=this.dataBuffer.slice(this.index,this.index+l);return this.index+=l,u},s.prototype.unpack_string=function(l){for(var u,h,b=this.read(l),_=0,v="";_<l;)(u=b[_])<128?(v+=String.fromCharCode(u),_++):(192^u)<32?(h=(192^u)<<6|63&b[_+1],v+=String.fromCharCode(h),_+=2):(h=(15&u)<<12|(63&b[_+1])<<6|63&b[_+2],v+=String.fromCharCode(h),_+=3);return this.index+=l,v},s.prototype.unpack_array=function(l){for(var u=new Array(l),h=0;h<l;h++)u[h]=this.unpack();return u},s.prototype.unpack_map=function(l){for(var u={},h=0;h<l;h++){var b=this.unpack(),_=this.unpack();u[b]=_}return u},s.prototype.unpack_float=function(){var l=this.unpack_uint32(),u=(l>>23&255)-127;return(l>>31===0?1:-1)*(8388607&l|8388608)*Math.pow(2,u-23)},s.prototype.unpack_double=function(){var l=this.unpack_uint32(),u=this.unpack_uint32(),h=(l>>20&2047)-1023;return(l>>31===0?1:-1)*((1048575&l|1048576)*Math.pow(2,h-20)+u*Math.pow(2,h-52))},s.prototype.read=function(l){var u=this.index;if(u+l<=this.length)return this.dataView.subarray(u,u+l);throw new Error("BinaryPackFailure: read index out of range")},a.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},a.prototype.pack=function(l){var u=typeof l;if(u==="string")this.pack_string(l);else if(u==="number")Math.floor(l)===l?this.pack_integer(l):this.pack_double(l);else if(u==="boolean")l===!0?this.bufferBuilder.append(195):l===!1&&this.bufferBuilder.append(194);else if(u==="undefined")this.bufferBuilder.append(192);else{if(u!=="object")throw new Error('Type "'+u+'" not yet supported');if(l===null)this.bufferBuilder.append(192);else{var h=l.constructor;if(h==Array)this.pack_array(l);else if(h==Blob||h==File||l instanceof Blob||l instanceof File)this.pack_bin(l);else if(h==ArrayBuffer)i.useArrayBufferView?this.pack_bin(new Uint8Array(l)):this.pack_bin(l);else if("BYTES_PER_ELEMENT"in l)i.useArrayBufferView?this.pack_bin(new Uint8Array(l.buffer)):this.pack_bin(l.buffer);else if(h==Object||h.toString().startsWith("class"))this.pack_object(l);else if(h==Date)this.pack_string(l.toString());else{if(typeof l.toBinaryPack!="function")throw new Error('Type "'+h.toString()+'" not yet supported');this.bufferBuilder.append(l.toBinaryPack())}}}this.bufferBuilder.flush()},a.prototype.pack_bin=function(l){var u=l.length||l.byteLength||l.size;if(u<=15)this.pack_uint8(160+u);else if(u<=65535)this.bufferBuilder.append(218),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(219),this.pack_uint32(u)}this.bufferBuilder.append(l)},a.prototype.pack_string=function(l){var u=d(l);if(u<=15)this.pack_uint8(176+u);else if(u<=65535)this.bufferBuilder.append(216),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(217),this.pack_uint32(u)}this.bufferBuilder.append(l)},a.prototype.pack_array=function(l){var u=l.length;if(u<=15)this.pack_uint8(144+u);else if(u<=65535)this.bufferBuilder.append(220),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(221),this.pack_uint32(u)}for(var h=0;h<u;h++)this.pack(l[h])},a.prototype.pack_integer=function(l){if(l>=-32&&l<=127)this.bufferBuilder.append(255&l);else if(l>=0&&l<=255)this.bufferBuilder.append(204),this.pack_uint8(l);else if(l>=-128&&l<=127)this.bufferBuilder.append(208),this.pack_int8(l);else if(l>=0&&l<=65535)this.bufferBuilder.append(205),this.pack_uint16(l);else if(l>=-32768&&l<=32767)this.bufferBuilder.append(209),this.pack_int16(l);else if(l>=0&&l<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(l);else if(l>=-2147483648&&l<=2147483647)this.bufferBuilder.append(210),this.pack_int32(l);else if(l>=-9223372036854776e3&&l<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(l);else{if(!(l>=0&&l<=18446744073709552e3))throw new Error("Invalid integer");this.bufferBuilder.append(207),this.pack_uint64(l)}},a.prototype.pack_double=function(l){var u=0;l<0&&(u=1,l=-l);var h=Math.floor(Math.log(l)/Math.LN2),b=l/Math.pow(2,h)-1,_=Math.floor(b*Math.pow(2,52)),v=Math.pow(2,32),y=u<<31|h+1023<<20|_/v&1048575,m=_%v;this.bufferBuilder.append(203),this.pack_int32(y),this.pack_int32(m)},a.prototype.pack_object=function(l){var u=Object.keys(l).length;if(u<=15)this.pack_uint8(128+u);else if(u<=65535)this.bufferBuilder.append(222),this.pack_uint16(u);else{if(!(u<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(223),this.pack_uint32(u)}for(var h in l)l.hasOwnProperty(h)&&(this.pack(h),this.pack(l[h]))},a.prototype.pack_uint8=function(l){this.bufferBuilder.append(l)},a.prototype.pack_uint16=function(l){this.bufferBuilder.append(l>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_uint32=function(l){var u=4294967295&l;this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u)},a.prototype.pack_uint64=function(l){var u=l/Math.pow(2,32),h=l%Math.pow(2,32);this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u),this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h)},a.prototype.pack_int8=function(l){this.bufferBuilder.append(255&l)},a.prototype.pack_int16=function(l){this.bufferBuilder.append((65280&l)>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_int32=function(l){this.bufferBuilder.append(l>>>24&255),this.bufferBuilder.append((16711680&l)>>>16),this.bufferBuilder.append((65280&l)>>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_int64=function(l){var u=Math.floor(l/Math.pow(2,32)),h=l%Math.pow(2,32);this.bufferBuilder.append((4278190080&u)>>>24),this.bufferBuilder.append((16711680&u)>>>16),this.bufferBuilder.append((65280&u)>>>8),this.bufferBuilder.append(255&u),this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h)}},{"./bufferbuilder":"EgBh"}],iSxC:[function(o,e,t){"use strict";function n(f,p,g){return p in f?Object.defineProperty(f,p,{value:g,enumerable:!0,configurable:!0,writable:!0}):f[p]=g,f}function i(f){return(i=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(p){return typeof p}:function(p){return p&&typeof Symbol=="function"&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p})(f)}Object.defineProperty(t,"__esModule",{value:!0}),t.extractVersion=a,t.wrapPeerConnectionEvent=c,t.disableLog=d,t.disableWarnings=l,t.log=u,t.deprecated=h,t.detectBrowser=b,t.compactObject=v,t.walkStats=y,t.filterStats=m;var r=!0,s=!0;function a(f,p,g){var E=f.match(p);return E&&E.length>=g&&parseInt(E[g],10)}function c(f,p,g){if(f.RTCPeerConnection){var E=f.RTCPeerConnection.prototype,w=E.addEventListener;E.addEventListener=function(S,k){if(S!==p)return w.apply(this,arguments);var D=function(P){var H=g(P);H&&(k.handleEvent?k.handleEvent(H):k(H))};return this._eventMap=this._eventMap||{},this._eventMap[p]||(this._eventMap[p]=new Map),this._eventMap[p].set(k,D),w.apply(this,[S,D])};var T=E.removeEventListener;E.removeEventListener=function(S,k){if(S!==p||!this._eventMap||!this._eventMap[p])return T.apply(this,arguments);if(!this._eventMap[p].has(k))return T.apply(this,arguments);var D=this._eventMap[p].get(k);return this._eventMap[p].delete(k),this._eventMap[p].size===0&&delete this._eventMap[p],Object.keys(this._eventMap).length===0&&delete this._eventMap,T.apply(this,[S,D])},Object.defineProperty(E,"on"+p,{get:function(){return this["_on"+p]},set:function(S){this["_on"+p]&&(this.removeEventListener(p,this["_on"+p]),delete this["_on"+p]),S&&this.addEventListener(p,this["_on"+p]=S)},enumerable:!0,configurable:!0})}}function d(f){return typeof f!="boolean"?new Error("Argument type: "+i(f)+". Please use a boolean."):(r=f,f?"adapter.js logging disabled":"adapter.js logging enabled")}function l(f){return typeof f!="boolean"?new Error("Argument type: "+i(f)+". Please use a boolean."):(s=!f,"adapter.js deprecation warnings "+(f?"disabled":"enabled"))}function u(){if((typeof window>"u"?"undefined":i(window))==="object"){if(r)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function h(f,p){s&&console.warn(f+" is deprecated, please use "+p+" instead.")}function b(f){var p={browser:null,version:null};if(f===void 0||!f.navigator)return p.browser="Not a browser.",p;var{navigator:g}=f;if(g.mozGetUserMedia)p.browser="firefox",p.version=a(g.userAgent,/Firefox\/(\d+)\./,1);else if(g.webkitGetUserMedia||f.isSecureContext===!1&&f.webkitRTCPeerConnection&&!f.RTCIceGatherer)p.browser="chrome",p.version=a(g.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(g.mediaDevices&&g.userAgent.match(/Edge\/(\d+).(\d+)$/))p.browser="edge",p.version=a(g.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!f.RTCPeerConnection||!g.userAgent.match(/AppleWebKit\/(\d+)\./))return p.browser="Not a supported browser.",p;p.browser="safari",p.version=a(g.userAgent,/AppleWebKit\/(\d+)\./,1),p.supportsUnifiedPlan=f.RTCRtpTransceiver&&"currentDirection"in f.RTCRtpTransceiver.prototype}return p}function _(f){return Object.prototype.toString.call(f)==="[object Object]"}function v(f){return _(f)?Object.keys(f).reduce(function(p,g){var E=_(f[g]),w=E?v(f[g]):f[g],T=E&&!Object.keys(w).length;return w===void 0||T?p:Object.assign(p,n({},g,w))},{}):f}function y(f,p,g){p&&!g.has(p.id)&&(g.set(p.id,p),Object.keys(p).forEach(function(E){E.endsWith("Id")?y(f,f.get(p[E]),g):E.endsWith("Ids")&&p[E].forEach(function(w){y(f,f.get(w),g)})}))}function m(f,p,g){var E=g?"outbound-rtp":"inbound-rtp",w=new Map;if(p===null)return w;var T=[];return f.forEach(function(S){S.type==="track"&&S.trackIdentifier===p.id&&T.push(S)}),T.forEach(function(S){f.forEach(function(k){k.type===E&&k.trackId===S.id&&y(f,k,w)})}),w}},{}],s6SN:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=c;var n=r(o("../utils.js"));function i(){if(typeof WeakMap!="function")return null;var d=new WeakMap;return i=function(){return d},d}function r(d){if(d&&d.__esModule)return d;if(d===null||typeof d!="object"&&typeof d!="function")return{default:d};var l=i();if(l&&l.has(d))return l.get(d);var u={},h=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var b in d)if(Object.prototype.hasOwnProperty.call(d,b)){var _=h?Object.getOwnPropertyDescriptor(d,b):null;_&&(_.get||_.set)?Object.defineProperty(u,b,_):u[b]=d[b]}return u.default=d,l&&l.set(d,u),u}function s(d){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l})(d)}var a=n.log;function c(d,l){var u=d&&d.navigator;if(u.mediaDevices){var h=function(y){if(s(y)!=="object"||y.mandatory||y.optional)return y;var m={};return Object.keys(y).forEach(function(f){if(f!=="require"&&f!=="advanced"&&f!=="mediaSource"){var p=s(y[f])==="object"?y[f]:{ideal:y[f]};p.exact!==void 0&&typeof p.exact=="number"&&(p.min=p.max=p.exact);var g=function(w,T){return w?w+T.charAt(0).toUpperCase()+T.slice(1):T==="deviceId"?"sourceId":T};if(p.ideal!==void 0){m.optional=m.optional||[];var E={};typeof p.ideal=="number"?(E[g("min",f)]=p.ideal,m.optional.push(E),(E={})[g("max",f)]=p.ideal,m.optional.push(E)):(E[g("",f)]=p.ideal,m.optional.push(E))}p.exact!==void 0&&typeof p.exact!="number"?(m.mandatory=m.mandatory||{},m.mandatory[g("",f)]=p.exact):["min","max"].forEach(function(w){p[w]!==void 0&&(m.mandatory=m.mandatory||{},m.mandatory[g(w,f)]=p[w])})}}),y.advanced&&(m.optional=(m.optional||[]).concat(y.advanced)),m},b=function(y,m){if(l.version>=61)return m(y);if((y=JSON.parse(JSON.stringify(y)))&&s(y.audio)==="object"){var f=function(w,T,S){T in w&&!(S in w)&&(w[S]=w[T],delete w[T])};f((y=JSON.parse(JSON.stringify(y))).audio,"autoGainControl","googAutoGainControl"),f(y.audio,"noiseSuppression","googNoiseSuppression"),y.audio=h(y.audio)}if(y&&s(y.video)==="object"){var p=y.video.facingMode;p=p&&(s(p)==="object"?p:{ideal:p});var g,E=l.version<66;if(p&&(p.exact==="user"||p.exact==="environment"||p.ideal==="user"||p.ideal==="environment")&&(!u.mediaDevices.getSupportedConstraints||!u.mediaDevices.getSupportedConstraints().facingMode||E)&&(delete y.video.facingMode,p.exact==="environment"||p.ideal==="environment"?g=["back","rear"]:p.exact!=="user"&&p.ideal!=="user"||(g=["front"]),g))return u.mediaDevices.enumerateDevices().then(function(w){var T=(w=w.filter(function(S){return S.kind==="videoinput"})).find(function(S){return g.some(function(k){return S.label.toLowerCase().includes(k)})});return!T&&w.length&&g.includes("back")&&(T=w[w.length-1]),T&&(y.video.deviceId=p.exact?{exact:T.deviceId}:{ideal:T.deviceId}),y.video=h(y.video),a("chrome: "+JSON.stringify(y)),m(y)});y.video=h(y.video)}return a("chrome: "+JSON.stringify(y)),m(y)},_=function(y){return l.version>=64?y:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[y.name]||y.name,message:y.message,constraint:y.constraint||y.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(u.getUserMedia=function(y,m,f){b(y,function(p){u.webkitGetUserMedia(p,m,function(g){f&&f(_(g))})})}.bind(u),u.mediaDevices.getUserMedia){var v=u.mediaDevices.getUserMedia.bind(u.mediaDevices);u.mediaDevices.getUserMedia=function(y){return b(y,function(m){return v(m).then(function(f){if(m.audio&&!f.getAudioTracks().length||m.video&&!f.getVideoTracks().length)throw f.getTracks().forEach(function(p){p.stop()}),new DOMException("","NotFoundError");return f},function(f){return Promise.reject(_(f))})})}}}}},{"../utils.js":"iSxC"}],VHa8:[function(o,e,t){"use strict";function n(i,r){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(typeof r=="function"?i.navigator.mediaDevices.getDisplayMedia=function(s){return r(s).then(function(a){var c=s.video&&s.video.width,d=s.video&&s.video.height,l=s.video&&s.video.frameRate;return s.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:a,maxFrameRate:l||3}},c&&(s.video.mandatory.maxWidth=c),d&&(s.video.mandatory.maxHeight=d),i.navigator.mediaDevices.getUserMedia(s)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=n},{}],uI5X:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimMediaStream=l,t.shimOnTrack=u,t.shimGetSendersWithDtmf=h,t.shimGetStats=b,t.shimSenderReceiverGetStats=_,t.shimAddTrackRemoveTrackWithNative=v,t.shimAddTrackRemoveTrack=y,t.shimPeerConnection=m,t.fixNegotiationNeeded=f,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}});var n=a(o("../utils.js")),i=o("./getusermedia"),r=o("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var p=new WeakMap;return s=function(){return p},p}function a(p){if(p&&p.__esModule)return p;if(p===null||typeof p!="object"&&typeof p!="function")return{default:p};var g=s();if(g&&g.has(p))return g.get(p);var E={},w=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var T in p)if(Object.prototype.hasOwnProperty.call(p,T)){var S=w?Object.getOwnPropertyDescriptor(p,T):null;S&&(S.get||S.set)?Object.defineProperty(E,T,S):E[T]=p[T]}return E.default=p,g&&g.set(p,E),E}function c(p,g,E){return g in p?Object.defineProperty(p,g,{value:E,enumerable:!0,configurable:!0,writable:!0}):p[g]=E,p}function d(p){return(d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(g){return typeof g}:function(g){return g&&typeof Symbol=="function"&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g})(p)}function l(p){p.MediaStream=p.MediaStream||p.webkitMediaStream}function u(p){if(d(p)!=="object"||!p.RTCPeerConnection||"ontrack"in p.RTCPeerConnection.prototype)n.wrapPeerConnectionEvent(p,"track",function(E){return E.transceiver||Object.defineProperty(E,"transceiver",{value:{receiver:E.receiver}}),E});else{Object.defineProperty(p.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(E){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=E)},enumerable:!0,configurable:!0});var g=p.RTCPeerConnection.prototype.setRemoteDescription;p.RTCPeerConnection.prototype.setRemoteDescription=function(){var E=this;return this._ontrackpoly||(this._ontrackpoly=function(w){w.stream.addEventListener("addtrack",function(T){var S;S=p.RTCPeerConnection.prototype.getReceivers?E.getReceivers().find(function(D){return D.track&&D.track.id===T.track.id}):{track:T.track};var k=new Event("track");k.track=T.track,k.receiver=S,k.transceiver={receiver:S},k.streams=[w.stream],E.dispatchEvent(k)}),w.stream.getTracks().forEach(function(T){var S;S=p.RTCPeerConnection.prototype.getReceivers?E.getReceivers().find(function(D){return D.track&&D.track.id===T.id}):{track:T};var k=new Event("track");k.track=T,k.receiver=S,k.transceiver={receiver:S},k.streams=[w.stream],E.dispatchEvent(k)})},this.addEventListener("addstream",this._ontrackpoly)),g.apply(this,arguments)}}}function h(p){if(d(p)==="object"&&p.RTCPeerConnection&&!("getSenders"in p.RTCPeerConnection.prototype)&&"createDTMFSender"in p.RTCPeerConnection.prototype){var g=function(D,P){return{track:P,get dtmf(){return this._dtmf===void 0&&(P.kind==="audio"?this._dtmf=D.createDTMFSender(P):this._dtmf=null),this._dtmf},_pc:D}};if(!p.RTCPeerConnection.prototype.getSenders){p.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var E=p.RTCPeerConnection.prototype.addTrack;p.RTCPeerConnection.prototype.addTrack=function(D,P){var H=E.apply(this,arguments);return H||(H=g(this,D),this._senders.push(H)),H};var w=p.RTCPeerConnection.prototype.removeTrack;p.RTCPeerConnection.prototype.removeTrack=function(D){w.apply(this,arguments);var P=this._senders.indexOf(D);P!==-1&&this._senders.splice(P,1)}}var T=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(D){var P=this;this._senders=this._senders||[],T.apply(this,[D]),D.getTracks().forEach(function(H){P._senders.push(g(P,H))})};var S=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(D){var P=this;this._senders=this._senders||[],S.apply(this,[D]),D.getTracks().forEach(function(H){var F=P._senders.find(function(N){return N.track===H});F&&P._senders.splice(P._senders.indexOf(F),1)})}}else if(d(p)==="object"&&p.RTCPeerConnection&&"getSenders"in p.RTCPeerConnection.prototype&&"createDTMFSender"in p.RTCPeerConnection.prototype&&p.RTCRtpSender&&!("dtmf"in p.RTCRtpSender.prototype)){var k=p.RTCPeerConnection.prototype.getSenders;p.RTCPeerConnection.prototype.getSenders=function(){var D=this,P=k.apply(this,[]);return P.forEach(function(H){return H._pc=D}),P},Object.defineProperty(p.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function b(p){if(p.RTCPeerConnection){var g=p.RTCPeerConnection.prototype.getStats;p.RTCPeerConnection.prototype.getStats=function(){var E=this,[w,T,S]=arguments;if(arguments.length>0&&typeof w=="function")return g.apply(this,arguments);if(g.length===0&&(arguments.length===0||typeof w!="function"))return g.apply(this,[]);var k=function(P){var H={};return P.result().forEach(function(F){var N={id:F.id,timestamp:F.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[F.type]||F.type};F.names().forEach(function(G){N[G]=F.stat(G)}),H[N.id]=N}),H},D=function(P){return new Map(Object.keys(P).map(function(H){return[H,P[H]]}))};return arguments.length>=2?g.apply(this,[function(P){T(D(k(P)))},w]):new Promise(function(P,H){g.apply(E,[function(F){P(D(k(F)))},H])}).then(T,S)}}}function _(p){if(d(p)==="object"&&p.RTCPeerConnection&&p.RTCRtpSender&&p.RTCRtpReceiver){if(!("getStats"in p.RTCRtpSender.prototype)){var g=p.RTCPeerConnection.prototype.getSenders;g&&(p.RTCPeerConnection.prototype.getSenders=function(){var S=this,k=g.apply(this,[]);return k.forEach(function(D){return D._pc=S}),k});var E=p.RTCPeerConnection.prototype.addTrack;E&&(p.RTCPeerConnection.prototype.addTrack=function(){var S=E.apply(this,arguments);return S._pc=this,S}),p.RTCRtpSender.prototype.getStats=function(){var S=this;return this._pc.getStats().then(function(k){return n.filterStats(k,S.track,!0)})}}if(!("getStats"in p.RTCRtpReceiver.prototype)){var w=p.RTCPeerConnection.prototype.getReceivers;w&&(p.RTCPeerConnection.prototype.getReceivers=function(){var S=this,k=w.apply(this,[]);return k.forEach(function(D){return D._pc=S}),k}),n.wrapPeerConnectionEvent(p,"track",function(S){return S.receiver._pc=S.srcElement,S}),p.RTCRtpReceiver.prototype.getStats=function(){var S=this;return this._pc.getStats().then(function(k){return n.filterStats(k,S.track,!1)})}}if("getStats"in p.RTCRtpSender.prototype&&"getStats"in p.RTCRtpReceiver.prototype){var T=p.RTCPeerConnection.prototype.getStats;p.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof p.MediaStreamTrack){var S,k,D,P=arguments[0];return this.getSenders().forEach(function(H){H.track===P&&(S?D=!0:S=H)}),this.getReceivers().forEach(function(H){return H.track===P&&(k?D=!0:k=H),H.track===P}),D||S&&k?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):S?S.getStats():k?k.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return T.apply(this,arguments)}}}}function v(p){p.RTCPeerConnection.prototype.getLocalStreams=function(){var S=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(k){return S._shimmedLocalStreams[k][0]})};var g=p.RTCPeerConnection.prototype.addTrack;p.RTCPeerConnection.prototype.addTrack=function(S,k){if(!k)return g.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var D=g.apply(this,arguments);return this._shimmedLocalStreams[k.id]?this._shimmedLocalStreams[k.id].indexOf(D)===-1&&this._shimmedLocalStreams[k.id].push(D):this._shimmedLocalStreams[k.id]=[k,D],D};var E=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(S){var k=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},S.getTracks().forEach(function(H){if(k.getSenders().find(function(F){return F.track===H}))throw new DOMException("Track already exists.","InvalidAccessError")});var D=this.getSenders();E.apply(this,arguments);var P=this.getSenders().filter(function(H){return D.indexOf(H)===-1});this._shimmedLocalStreams[S.id]=[S].concat(P)};var w=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(S){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[S.id],w.apply(this,arguments)};var T=p.RTCPeerConnection.prototype.removeTrack;p.RTCPeerConnection.prototype.removeTrack=function(S){var k=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},S&&Object.keys(this._shimmedLocalStreams).forEach(function(D){var P=k._shimmedLocalStreams[D].indexOf(S);P!==-1&&k._shimmedLocalStreams[D].splice(P,1),k._shimmedLocalStreams[D].length===1&&delete k._shimmedLocalStreams[D]}),T.apply(this,arguments)}}function y(p,g){if(p.RTCPeerConnection){if(p.RTCPeerConnection.prototype.addTrack&&g.version>=65)return v(p);var E=p.RTCPeerConnection.prototype.getLocalStreams;p.RTCPeerConnection.prototype.getLocalStreams=function(){var P=this,H=E.apply(this);return this._reverseStreams=this._reverseStreams||{},H.map(function(F){return P._reverseStreams[F.id]})};var w=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(P){var H=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},P.getTracks().forEach(function(N){if(H.getSenders().find(function(G){return G.track===N}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[P.id]){var F=new p.MediaStream(P.getTracks());this._streams[P.id]=F,this._reverseStreams[F.id]=P,P=F}w.apply(this,[P])};var T=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(P){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},T.apply(this,[this._streams[P.id]||P]),delete this._reverseStreams[this._streams[P.id]?this._streams[P.id].id:P.id],delete this._streams[P.id]},p.RTCPeerConnection.prototype.addTrack=function(P,H){var F=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var N=[].slice.call(arguments,1);if(N.length!==1||!N[0].getTracks().find(function(ae){return ae===P}))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(function(ae){return ae.track===P}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var G=this._streams[H.id];if(G)G.addTrack(P),Promise.resolve().then(function(){F.dispatchEvent(new Event("negotiationneeded"))});else{var ee=new p.MediaStream([P]);this._streams[H.id]=ee,this._reverseStreams[ee.id]=H,this.addStream(ee)}return this.getSenders().find(function(ae){return ae.track===P})},["createOffer","createAnswer"].forEach(function(P){var H=p.RTCPeerConnection.prototype[P],F=c({},P,function(){var N=this,G=arguments;return arguments.length&&typeof arguments[0]=="function"?H.apply(this,[function(ee){var ae=D(N,ee);G[0].apply(null,[ae])},function(ee){G[1]&&G[1].apply(null,ee)},arguments[2]]):H.apply(this,arguments).then(function(ee){return D(N,ee)})});p.RTCPeerConnection.prototype[P]=F[P]});var S=p.RTCPeerConnection.prototype.setLocalDescription;p.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(P=this,H=arguments[0],F=H.sdp,Object.keys(P._reverseStreams||[]).forEach(function(N){var G=P._reverseStreams[N],ee=P._streams[G.id];F=F.replace(new RegExp(G.id,"g"),ee.id)}),new RTCSessionDescription({type:H.type,sdp:F})),S.apply(this,arguments)):S.apply(this,arguments);var P,H,F};var k=Object.getOwnPropertyDescriptor(p.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(p.RTCPeerConnection.prototype,"localDescription",{get:function(){var P=k.get.apply(this);return P.type===""?P:D(this,P)}}),p.RTCPeerConnection.prototype.removeTrack=function(P){var H,F=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!P._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(P._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(function(N){F._streams[N].getTracks().find(function(G){return P.track===G})&&(H=F._streams[N])}),H&&(H.getTracks().length===1?this.removeStream(this._reverseStreams[H.id]):H.removeTrack(P.track),this.dispatchEvent(new Event("negotiationneeded")))}}function D(P,H){var F=H.sdp;return Object.keys(P._reverseStreams||[]).forEach(function(N){var G=P._reverseStreams[N],ee=P._streams[G.id];F=F.replace(new RegExp(ee.id,"g"),G.id)}),new RTCSessionDescription({type:H.type,sdp:F})}}function m(p,g){!p.RTCPeerConnection&&p.webkitRTCPeerConnection&&(p.RTCPeerConnection=p.webkitRTCPeerConnection),p.RTCPeerConnection&&g.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(E){var w=p.RTCPeerConnection.prototype[E],T=c({},E,function(){return arguments[0]=new(E==="addIceCandidate"?p.RTCIceCandidate:p.RTCSessionDescription)(arguments[0]),w.apply(this,arguments)});p.RTCPeerConnection.prototype[E]=T[E]})}function f(p,g){n.wrapPeerConnectionEvent(p,"negotiationneeded",function(E){var w=E.target;if(!(g.version<72||w.getConfiguration&&w.getConfiguration().sdpSemantics==="plan-b")||w.signalingState==="stable")return E})}},{"../utils.js":"iSxC","./getusermedia":"s6SN","./getdisplaymedia":"VHa8"}],NZ1C:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterIceServers=s;var n=r(o("../utils"));function i(){if(typeof WeakMap!="function")return null;var a=new WeakMap;return i=function(){return a},a}function r(a){if(a&&a.__esModule)return a;if(a===null||typeof a!="object"&&typeof a!="function")return{default:a};var c=i();if(c&&c.has(a))return c.get(a);var d={},l=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in a)if(Object.prototype.hasOwnProperty.call(a,u)){var h=l?Object.getOwnPropertyDescriptor(a,u):null;h&&(h.get||h.set)?Object.defineProperty(d,u,h):d[u]=a[u]}return d.default=a,c&&c.set(a,d),d}function s(a,c){var d=!1;return(a=JSON.parse(JSON.stringify(a))).filter(function(l){if(l&&(l.urls||l.url)){var u=l.urls||l.url;l.url&&!l.urls&&n.deprecated("RTCIceServer.url","RTCIceServer.urls");var h=typeof u=="string";return h&&(u=[u]),u=u.filter(function(b){if(b.indexOf("stun:")===0)return!1;var _=b.startsWith("turn")&&!b.startsWith("turn:[")&&b.includes("transport=udp");return _&&!d?(d=!0,!0):_&&!d}),delete l.url,l.urls=h?u[0]:u,!!u.length}})}},{"../utils":"iSxC"}],YHvh:[function(o,e,t){"use strict";var n={generateIdentifier:function(){return Math.random().toString(36).substr(2,10)}};n.localCName=n.generateIdentifier(),n.splitLines=function(i){return i.trim().split(`
2
+ `).map(function(r){return r.trim()})},n.splitSections=function(i){return i.split(`
3
+ m=`).map(function(r,s){return(s>0?"m="+r:r).trim()+`\r
4
+ `})},n.getDescription=function(i){var r=n.splitSections(i);return r&&r[0]},n.getMediaSections=function(i){var r=n.splitSections(i);return r.shift(),r},n.matchPrefix=function(i,r){return n.splitLines(i).filter(function(s){return s.indexOf(r)===0})},n.parseCandidate=function(i){for(var r,s={foundation:(r=i.indexOf("a=candidate:")===0?i.substring(12).split(" "):i.substring(10).split(" "))[0],component:parseInt(r[1],10),protocol:r[2].toLowerCase(),priority:parseInt(r[3],10),ip:r[4],address:r[4],port:parseInt(r[5],10),type:r[7]},a=8;a<r.length;a+=2)switch(r[a]){case"raddr":s.relatedAddress=r[a+1];break;case"rport":s.relatedPort=parseInt(r[a+1],10);break;case"tcptype":s.tcpType=r[a+1];break;case"ufrag":s.ufrag=r[a+1],s.usernameFragment=r[a+1];break;default:s[r[a]]=r[a+1]}return s},n.writeCandidate=function(i){var r=[];r.push(i.foundation),r.push(i.component),r.push(i.protocol.toUpperCase()),r.push(i.priority),r.push(i.address||i.ip),r.push(i.port);var s=i.type;return r.push("typ"),r.push(s),s!=="host"&&i.relatedAddress&&i.relatedPort&&(r.push("raddr"),r.push(i.relatedAddress),r.push("rport"),r.push(i.relatedPort)),i.tcpType&&i.protocol.toLowerCase()==="tcp"&&(r.push("tcptype"),r.push(i.tcpType)),(i.usernameFragment||i.ufrag)&&(r.push("ufrag"),r.push(i.usernameFragment||i.ufrag)),"candidate:"+r.join(" ")},n.parseIceOptions=function(i){return i.substr(14).split(" ")},n.parseRtpMap=function(i){var r=i.substr(9).split(" "),s={payloadType:parseInt(r.shift(),10)};return r=r[0].split("/"),s.name=r[0],s.clockRate=parseInt(r[1],10),s.channels=r.length===3?parseInt(r[2],10):1,s.numChannels=s.channels,s},n.writeRtpMap=function(i){var r=i.payloadType;i.preferredPayloadType!==void 0&&(r=i.preferredPayloadType);var s=i.channels||i.numChannels||1;return"a=rtpmap:"+r+" "+i.name+"/"+i.clockRate+(s!==1?"/"+s:"")+`\r
5
+ `},n.parseExtmap=function(i){var r=i.substr(9).split(" ");return{id:parseInt(r[0],10),direction:r[0].indexOf("/")>0?r[0].split("/")[1]:"sendrecv",uri:r[1]}},n.writeExtmap=function(i){return"a=extmap:"+(i.id||i.preferredId)+(i.direction&&i.direction!=="sendrecv"?"/"+i.direction:"")+" "+i.uri+`\r
6
+ `},n.parseFmtp=function(i){for(var r,s={},a=i.substr(i.indexOf(" ")+1).split(";"),c=0;c<a.length;c++)s[(r=a[c].trim().split("="))[0].trim()]=r[1];return s},n.writeFmtp=function(i){var r="",s=i.payloadType;if(i.preferredPayloadType!==void 0&&(s=i.preferredPayloadType),i.parameters&&Object.keys(i.parameters).length){var a=[];Object.keys(i.parameters).forEach(function(c){i.parameters[c]?a.push(c+"="+i.parameters[c]):a.push(c)}),r+="a=fmtp:"+s+" "+a.join(";")+`\r
7
+ `}return r},n.parseRtcpFb=function(i){var r=i.substr(i.indexOf(" ")+1).split(" ");return{type:r.shift(),parameter:r.join(" ")}},n.writeRtcpFb=function(i){var r="",s=i.payloadType;return i.preferredPayloadType!==void 0&&(s=i.preferredPayloadType),i.rtcpFeedback&&i.rtcpFeedback.length&&i.rtcpFeedback.forEach(function(a){r+="a=rtcp-fb:"+s+" "+a.type+(a.parameter&&a.parameter.length?" "+a.parameter:"")+`\r
8
+ `}),r},n.parseSsrcMedia=function(i){var r=i.indexOf(" "),s={ssrc:parseInt(i.substr(7,r-7),10)},a=i.indexOf(":",r);return a>-1?(s.attribute=i.substr(r+1,a-r-1),s.value=i.substr(a+1)):s.attribute=i.substr(r+1),s},n.parseSsrcGroup=function(i){var r=i.substr(13).split(" ");return{semantics:r.shift(),ssrcs:r.map(function(s){return parseInt(s,10)})}},n.getMid=function(i){var r=n.matchPrefix(i,"a=mid:")[0];if(r)return r.substr(6)},n.parseFingerprint=function(i){var r=i.substr(14).split(" ");return{algorithm:r[0].toLowerCase(),value:r[1]}},n.getDtlsParameters=function(i,r){return{role:"auto",fingerprints:n.matchPrefix(i+r,"a=fingerprint:").map(n.parseFingerprint)}},n.writeDtlsParameters=function(i,r){var s="a=setup:"+r+`\r
9
+ `;return i.fingerprints.forEach(function(a){s+="a=fingerprint:"+a.algorithm+" "+a.value+`\r
10
+ `}),s},n.parseCryptoLine=function(i){var r=i.substr(9).split(" ");return{tag:parseInt(r[0],10),cryptoSuite:r[1],keyParams:r[2],sessionParams:r.slice(3)}},n.writeCryptoLine=function(i){return"a=crypto:"+i.tag+" "+i.cryptoSuite+" "+(typeof i.keyParams=="object"?n.writeCryptoKeyParams(i.keyParams):i.keyParams)+(i.sessionParams?" "+i.sessionParams.join(" "):"")+`\r
11
+ `},n.parseCryptoKeyParams=function(i){if(i.indexOf("inline:")!==0)return null;var r=i.substr(7).split("|");return{keyMethod:"inline",keySalt:r[0],lifeTime:r[1],mkiValue:r[2]?r[2].split(":")[0]:void 0,mkiLength:r[2]?r[2].split(":")[1]:void 0}},n.writeCryptoKeyParams=function(i){return i.keyMethod+":"+i.keySalt+(i.lifeTime?"|"+i.lifeTime:"")+(i.mkiValue&&i.mkiLength?"|"+i.mkiValue+":"+i.mkiLength:"")},n.getCryptoParameters=function(i,r){return n.matchPrefix(i+r,"a=crypto:").map(n.parseCryptoLine)},n.getIceParameters=function(i,r){var s=n.matchPrefix(i+r,"a=ice-ufrag:")[0],a=n.matchPrefix(i+r,"a=ice-pwd:")[0];return s&&a?{usernameFragment:s.substr(12),password:a.substr(10)}:null},n.writeIceParameters=function(i){return"a=ice-ufrag:"+i.usernameFragment+`\r
12
+ a=ice-pwd:`+i.password+`\r
13
+ `},n.parseRtpParameters=function(i){for(var r={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},s=n.splitLines(i)[0].split(" "),a=3;a<s.length;a++){var c=s[a],d=n.matchPrefix(i,"a=rtpmap:"+c+" ")[0];if(d){var l=n.parseRtpMap(d),u=n.matchPrefix(i,"a=fmtp:"+c+" ");switch(l.parameters=u.length?n.parseFmtp(u[0]):{},l.rtcpFeedback=n.matchPrefix(i,"a=rtcp-fb:"+c+" ").map(n.parseRtcpFb),r.codecs.push(l),l.name.toUpperCase()){case"RED":case"ULPFEC":r.fecMechanisms.push(l.name.toUpperCase())}}}return n.matchPrefix(i,"a=extmap:").forEach(function(h){r.headerExtensions.push(n.parseExtmap(h))}),r},n.writeRtpDescription=function(i,r){var s="";s+="m="+i+" ",s+=r.codecs.length>0?"9":"0",s+=" UDP/TLS/RTP/SAVPF ",s+=r.codecs.map(function(c){return c.preferredPayloadType!==void 0?c.preferredPayloadType:c.payloadType}).join(" ")+`\r
14
+ `,s+=`c=IN IP4 0.0.0.0\r
15
+ `,s+=`a=rtcp:9 IN IP4 0.0.0.0\r
16
+ `,r.codecs.forEach(function(c){s+=n.writeRtpMap(c),s+=n.writeFmtp(c),s+=n.writeRtcpFb(c)});var a=0;return r.codecs.forEach(function(c){c.maxptime>a&&(a=c.maxptime)}),a>0&&(s+="a=maxptime:"+a+`\r
17
+ `),s+=`a=rtcp-mux\r
18
+ `,r.headerExtensions&&r.headerExtensions.forEach(function(c){s+=n.writeExtmap(c)}),s},n.parseRtpEncodingParameters=function(i){var r,s=[],a=n.parseRtpParameters(i),c=a.fecMechanisms.indexOf("RED")!==-1,d=a.fecMechanisms.indexOf("ULPFEC")!==-1,l=n.matchPrefix(i,"a=ssrc:").map(function(_){return n.parseSsrcMedia(_)}).filter(function(_){return _.attribute==="cname"}),u=l.length>0&&l[0].ssrc,h=n.matchPrefix(i,"a=ssrc-group:FID").map(function(_){return _.substr(17).split(" ").map(function(v){return parseInt(v,10)})});h.length>0&&h[0].length>1&&h[0][0]===u&&(r=h[0][1]),a.codecs.forEach(function(_){if(_.name.toUpperCase()==="RTX"&&_.parameters.apt){var v={ssrc:u,codecPayloadType:parseInt(_.parameters.apt,10)};u&&r&&(v.rtx={ssrc:r}),s.push(v),c&&((v=JSON.parse(JSON.stringify(v))).fec={ssrc:u,mechanism:d?"red+ulpfec":"red"},s.push(v))}}),s.length===0&&u&&s.push({ssrc:u});var b=n.matchPrefix(i,"b=");return b.length&&(b=b[0].indexOf("b=TIAS:")===0?parseInt(b[0].substr(7),10):b[0].indexOf("b=AS:")===0?1e3*parseInt(b[0].substr(5),10)*.95-16e3:void 0,s.forEach(function(_){_.maxBitrate=b})),s},n.parseRtcpParameters=function(i){var r={},s=n.matchPrefix(i,"a=ssrc:").map(function(d){return n.parseSsrcMedia(d)}).filter(function(d){return d.attribute==="cname"})[0];s&&(r.cname=s.value,r.ssrc=s.ssrc);var a=n.matchPrefix(i,"a=rtcp-rsize");r.reducedSize=a.length>0,r.compound=a.length===0;var c=n.matchPrefix(i,"a=rtcp-mux");return r.mux=c.length>0,r},n.parseMsid=function(i){var r,s=n.matchPrefix(i,"a=msid:");if(s.length===1)return{stream:(r=s[0].substr(7).split(" "))[0],track:r[1]};var a=n.matchPrefix(i,"a=ssrc:").map(function(c){return n.parseSsrcMedia(c)}).filter(function(c){return c.attribute==="msid"});return a.length>0?{stream:(r=a[0].value.split(" "))[0],track:r[1]}:void 0},n.parseSctpDescription=function(i){var r,s=n.parseMLine(i),a=n.matchPrefix(i,"a=max-message-size:");a.length>0&&(r=parseInt(a[0].substr(19),10)),isNaN(r)&&(r=65536);var c=n.matchPrefix(i,"a=sctp-port:");if(c.length>0)return{port:parseInt(c[0].substr(12),10),protocol:s.fmt,maxMessageSize:r};if(n.matchPrefix(i,"a=sctpmap:").length>0){var d=n.matchPrefix(i,"a=sctpmap:")[0].substr(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:r}}},n.writeSctpDescription=function(i,r){var s=[];return s=i.protocol!=="DTLS/SCTP"?["m="+i.kind+" 9 "+i.protocol+" "+r.protocol+`\r
19
19
  `,`c=IN IP4 0.0.0.0\r
20
20
  `,"a=sctp-port:"+r.port+`\r
21
- `]:["m="+n.kind+" 9 "+n.protocol+" "+r.port+`\r
21
+ `]:["m="+i.kind+" 9 "+i.protocol+" "+r.port+`\r
22
22
  `,`c=IN IP4 0.0.0.0\r
23
23
  `,"a=sctpmap:"+r.port+" "+r.protocol+` 65535\r
24
- `],r.maxMessageSize!==void 0&&o.push("a=max-message-size:"+r.maxMessageSize+`\r
25
- `),o.join("")},i.generateSessionId=function(){return Math.random().toString().substr(2,21)},i.writeSessionBoilerplate=function(n,r,o){var s=r!==void 0?r:2;return`v=0\r
26
- o=`+(o||"thisisadapterortc")+" "+(n||i.generateSessionId())+" "+s+` IN IP4 127.0.0.1\r
24
+ `],r.maxMessageSize!==void 0&&s.push("a=max-message-size:"+r.maxMessageSize+`\r
25
+ `),s.join("")},n.generateSessionId=function(){return Math.random().toString().substr(2,21)},n.writeSessionBoilerplate=function(i,r,s){var a=r!==void 0?r:2;return`v=0\r
26
+ o=`+(s||"thisisadapterortc")+" "+(i||n.generateSessionId())+" "+a+` IN IP4 127.0.0.1\r
27
27
  s=-\r
28
28
  t=0 0\r
29
- `},i.writeMediaSection=function(n,r,o,s){var c=i.writeRtpDescription(n.kind,r);if(c+=i.writeIceParameters(n.iceGatherer.getLocalParameters()),c+=i.writeDtlsParameters(n.dtlsTransport.getLocalParameters(),o==="offer"?"actpass":"active"),c+="a=mid:"+n.mid+`\r
30
- `,n.direction?c+="a="+n.direction+`\r
31
- `:n.rtpSender&&n.rtpReceiver?c+=`a=sendrecv\r
32
- `:n.rtpSender?c+=`a=sendonly\r
33
- `:n.rtpReceiver?c+=`a=recvonly\r
29
+ `},n.writeMediaSection=function(i,r,s,a){var c=n.writeRtpDescription(i.kind,r);if(c+=n.writeIceParameters(i.iceGatherer.getLocalParameters()),c+=n.writeDtlsParameters(i.dtlsTransport.getLocalParameters(),s==="offer"?"actpass":"active"),c+="a=mid:"+i.mid+`\r
30
+ `,i.direction?c+="a="+i.direction+`\r
31
+ `:i.rtpSender&&i.rtpReceiver?c+=`a=sendrecv\r
32
+ `:i.rtpSender?c+=`a=sendonly\r
33
+ `:i.rtpReceiver?c+=`a=recvonly\r
34
34
  `:c+=`a=inactive\r
35
- `,n.rtpSender){var d="msid:"+s.id+" "+n.rtpSender.track.id+`\r
36
- `;c+="a="+d,c+="a=ssrc:"+n.sendEncodingParameters[0].ssrc+" "+d,n.sendEncodingParameters[0].rtx&&(c+="a=ssrc:"+n.sendEncodingParameters[0].rtx.ssrc+" "+d,c+="a=ssrc-group:FID "+n.sendEncodingParameters[0].ssrc+" "+n.sendEncodingParameters[0].rtx.ssrc+`\r
37
- `)}return c+="a=ssrc:"+n.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+`\r
38
- `,n.rtpSender&&n.sendEncodingParameters[0].rtx&&(c+="a=ssrc:"+n.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+`\r
39
- `),c},i.getDirection=function(n,r){for(var o=i.splitLines(n),s=0;s<o.length;s++)switch(o[s]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return o[s].substr(2)}return r?i.getDirection(r):"sendrecv"},i.getKind=function(n){return i.splitLines(n)[0].split(" ")[0].substr(2)},i.isRejected=function(n){return n.split(" ",2)[1]==="0"},i.parseMLine=function(n){var r=i.splitLines(n)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},i.parseOLine=function(n){var r=i.matchPrefix(n,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},i.isValidSDP=function(n){if(typeof n!="string"||n.length===0)return!1;for(var r=i.splitLines(n),o=0;o<r.length;o++)if(r[o].length<2||r[o].charAt(1)!=="=")return!1;return!0},typeof e=="object"&&(e.exports=i)},{}],NJ2u:[function(a,e,t){"use strict";var i=a("sdp");function n(h){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[h.type]||h.type}function r(h,u,f,x,b){var y=i.writeRtpDescription(h.kind,u);if(y+=i.writeIceParameters(h.iceGatherer.getLocalParameters()),y+=i.writeDtlsParameters(h.dtlsTransport.getLocalParameters(),f==="offer"?"actpass":b||"active"),y+="a=mid:"+h.mid+`\r
40
- `,h.rtpSender&&h.rtpReceiver?y+=`a=sendrecv\r
41
- `:h.rtpSender?y+=`a=sendonly\r
42
- `:h.rtpReceiver?y+=`a=recvonly\r
35
+ `,i.rtpSender){var d="msid:"+a.id+" "+i.rtpSender.track.id+`\r
36
+ `;c+="a="+d,c+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" "+d,i.sendEncodingParameters[0].rtx&&(c+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" "+d,c+="a=ssrc-group:FID "+i.sendEncodingParameters[0].ssrc+" "+i.sendEncodingParameters[0].rtx.ssrc+`\r
37
+ `)}return c+="a=ssrc:"+i.sendEncodingParameters[0].ssrc+" cname:"+n.localCName+`\r
38
+ `,i.rtpSender&&i.sendEncodingParameters[0].rtx&&(c+="a=ssrc:"+i.sendEncodingParameters[0].rtx.ssrc+" cname:"+n.localCName+`\r
39
+ `),c},n.getDirection=function(i,r){for(var s=n.splitLines(i),a=0;a<s.length;a++)switch(s[a]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[a].substr(2)}return r?n.getDirection(r):"sendrecv"},n.getKind=function(i){return n.splitLines(i)[0].split(" ")[0].substr(2)},n.isRejected=function(i){return i.split(" ",2)[1]==="0"},n.parseMLine=function(i){var r=n.splitLines(i)[0].substr(2).split(" ");return{kind:r[0],port:parseInt(r[1],10),protocol:r[2],fmt:r.slice(3).join(" ")}},n.parseOLine=function(i){var r=n.matchPrefix(i,"o=")[0].substr(2).split(" ");return{username:r[0],sessionId:r[1],sessionVersion:parseInt(r[2],10),netType:r[3],addressType:r[4],address:r[5]}},n.isValidSDP=function(i){if(typeof i!="string"||i.length===0)return!1;for(var r=n.splitLines(i),s=0;s<r.length;s++)if(r[s].length<2||r[s].charAt(1)!=="=")return!1;return!0},typeof e=="object"&&(e.exports=n)},{}],NJ2u:[function(o,e,t){"use strict";var n=o("sdp");function i(u){return{inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[u.type]||u.type}function r(u,h,b,_,v){var y=n.writeRtpDescription(u.kind,h);if(y+=n.writeIceParameters(u.iceGatherer.getLocalParameters()),y+=n.writeDtlsParameters(u.dtlsTransport.getLocalParameters(),b==="offer"?"actpass":v||"active"),y+="a=mid:"+u.mid+`\r
40
+ `,u.rtpSender&&u.rtpReceiver?y+=`a=sendrecv\r
41
+ `:u.rtpSender?y+=`a=sendonly\r
42
+ `:u.rtpReceiver?y+=`a=recvonly\r
43
43
  `:y+=`a=inactive\r
44
- `,h.rtpSender){var g=h.rtpSender._initialTrackId||h.rtpSender.track.id;h.rtpSender._initialTrackId=g;var p="msid:"+(x?x.id:"-")+" "+g+`\r
45
- `;y+="a="+p,y+="a=ssrc:"+h.sendEncodingParameters[0].ssrc+" "+p,h.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+h.sendEncodingParameters[0].rtx.ssrc+" "+p,y+="a=ssrc-group:FID "+h.sendEncodingParameters[0].ssrc+" "+h.sendEncodingParameters[0].rtx.ssrc+`\r
46
- `)}return y+="a=ssrc:"+h.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+`\r
47
- `,h.rtpSender&&h.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+h.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+`\r
48
- `),y}function o(h,u){var f=!1;return(h=JSON.parse(JSON.stringify(h))).filter(function(x){if(x&&(x.urls||x.url)){var b=x.urls||x.url;x.url&&!x.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var y=typeof b=="string";return y&&(b=[b]),b=b.filter(function(g){return g.indexOf("turn:")===0&&g.indexOf("transport=udp")!==-1&&g.indexOf("turn:[")===-1&&!f?(f=!0,!0):g.indexOf("stun:")===0&&u>=14393&&g.indexOf("?transport=udp")===-1}),delete x.url,x.urls=y?b[0]:b,!!b.length}})}function s(h,u){var f={codecs:[],headerExtensions:[],fecMechanisms:[]},x=function(y,g){y=parseInt(y,10);for(var p=0;p<g.length;p++)if(g[p].payloadType===y||g[p].preferredPayloadType===y)return g[p]},b=function(y,g,p,m){var v=x(y.parameters.apt,p),w=x(g.parameters.apt,m);return v&&w&&v.name.toLowerCase()===w.name.toLowerCase()};return h.codecs.forEach(function(y){for(var g=0;g<u.codecs.length;g++){var p=u.codecs[g];if(y.name.toLowerCase()===p.name.toLowerCase()&&y.clockRate===p.clockRate){if(y.name.toLowerCase()==="rtx"&&y.parameters&&p.parameters.apt&&!b(y,p,h.codecs,u.codecs))continue;(p=JSON.parse(JSON.stringify(p))).numChannels=Math.min(y.numChannels,p.numChannels),f.codecs.push(p),p.rtcpFeedback=p.rtcpFeedback.filter(function(m){for(var v=0;v<y.rtcpFeedback.length;v++)if(y.rtcpFeedback[v].type===m.type&&y.rtcpFeedback[v].parameter===m.parameter)return!0;return!1});break}}}),h.headerExtensions.forEach(function(y){for(var g=0;g<u.headerExtensions.length;g++){var p=u.headerExtensions[g];if(y.uri===p.uri){f.headerExtensions.push(p);break}}}),f}function c(h,u,f){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[u][h].indexOf(f)!==-1}function d(h,u){var f=h.getRemoteCandidates().find(function(x){return u.foundation===x.foundation&&u.ip===x.ip&&u.port===x.port&&u.priority===x.priority&&u.protocol===x.protocol&&u.type===x.type});return f||h.addRemoteCandidate(u),!f}function l(h,u){var f=new Error(u);return f.name=h,f.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[h],f}e.exports=function(h,u){function f(g,p){p.addTrack(g),p.dispatchEvent(new h.MediaStreamTrackEvent("addtrack",{track:g}))}function x(g,p,m,v){var w=new Event("track");w.track=p,w.receiver=m,w.transceiver={receiver:m},w.streams=v,h.setTimeout(function(){g._dispatchEvent("track",w)})}var b=function(g){var p=this,m=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(w){p[w]=m[w].bind(m)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",g=JSON.parse(JSON.stringify(g||{})),this.usingBundle=g.bundlePolicy==="max-bundle",g.rtcpMuxPolicy==="negotiate")throw l("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(g.rtcpMuxPolicy||(g.rtcpMuxPolicy="require"),g.iceTransportPolicy){case"all":case"relay":break;default:g.iceTransportPolicy="all"}switch(g.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:g.bundlePolicy="balanced"}if(g.iceServers=o(g.iceServers||[],u),this._iceGatherers=[],g.iceCandidatePoolSize)for(var v=g.iceCandidatePoolSize;v>0;v--)this._iceGatherers.push(new h.RTCIceGatherer({iceServers:g.iceServers,gatherPolicy:g.iceTransportPolicy}));else g.iceCandidatePoolSize=0;this._config=g,this.transceivers=[],this._sdpSessionId=i.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(b.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(b.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),b.prototype.onicecandidate=null,b.prototype.onaddstream=null,b.prototype.ontrack=null,b.prototype.onremovestream=null,b.prototype.onsignalingstatechange=null,b.prototype.oniceconnectionstatechange=null,b.prototype.onconnectionstatechange=null,b.prototype.onicegatheringstatechange=null,b.prototype.onnegotiationneeded=null,b.prototype.ondatachannel=null,b.prototype._dispatchEvent=function(g,p){this._isClosed||(this.dispatchEvent(p),typeof this["on"+g]=="function"&&this["on"+g](p))},b.prototype._emitGatheringStateChange=function(){var g=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",g)},b.prototype.getConfiguration=function(){return this._config},b.prototype.getLocalStreams=function(){return this.localStreams},b.prototype.getRemoteStreams=function(){return this.remoteStreams},b.prototype._createTransceiver=function(g,p){var m=this.transceivers.length>0,v={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:g,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&m)v.iceTransport=this.transceivers[0].iceTransport,v.dtlsTransport=this.transceivers[0].dtlsTransport;else{var w=this._createIceAndDtlsTransports();v.iceTransport=w.iceTransport,v.dtlsTransport=w.dtlsTransport}return p||this.transceivers.push(v),v},b.prototype.addTrack=function(g,p){if(this._isClosed)throw l("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var m;if(this.transceivers.find(function(w){return w.track===g}))throw l("InvalidAccessError","Track already exists.");for(var v=0;v<this.transceivers.length;v++)this.transceivers[v].track||this.transceivers[v].kind!==g.kind||(m=this.transceivers[v]);return m||(m=this._createTransceiver(g.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(p)===-1&&this.localStreams.push(p),m.track=g,m.stream=p,m.rtpSender=new h.RTCRtpSender(g,m.dtlsTransport),m.rtpSender},b.prototype.addStream=function(g){var p=this;if(u>=15025)g.getTracks().forEach(function(v){p.addTrack(v,g)});else{var m=g.clone();g.getTracks().forEach(function(v,w){var E=m.getTracks()[w];v.addEventListener("enabled",function(C){E.enabled=C.enabled})}),m.getTracks().forEach(function(v){p.addTrack(v,m)})}},b.prototype.removeTrack=function(g){if(this._isClosed)throw l("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(g instanceof h.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var p=this.transceivers.find(function(v){return v.rtpSender===g});if(!p)throw l("InvalidAccessError","Sender was not created by this connection.");var m=p.stream;p.rtpSender.stop(),p.rtpSender=null,p.track=null,p.stream=null,this.transceivers.map(function(v){return v.stream}).indexOf(m)===-1&&this.localStreams.indexOf(m)>-1&&this.localStreams.splice(this.localStreams.indexOf(m),1),this._maybeFireNegotiationNeeded()},b.prototype.removeStream=function(g){var p=this;g.getTracks().forEach(function(m){var v=p.getSenders().find(function(w){return w.track===m});v&&p.removeTrack(v)})},b.prototype.getSenders=function(){return this.transceivers.filter(function(g){return!!g.rtpSender}).map(function(g){return g.rtpSender})},b.prototype.getReceivers=function(){return this.transceivers.filter(function(g){return!!g.rtpReceiver}).map(function(g){return g.rtpReceiver})},b.prototype._createIceGatherer=function(g,p){var m=this;if(p&&g>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var v=new h.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(v,"state",{value:"new",writable:!0}),this.transceivers[g].bufferedCandidateEvents=[],this.transceivers[g].bufferCandidates=function(w){var E=!w.candidate||Object.keys(w.candidate).length===0;v.state=E?"completed":"gathering",m.transceivers[g].bufferedCandidateEvents!==null&&m.transceivers[g].bufferedCandidateEvents.push(w)},v.addEventListener("localcandidate",this.transceivers[g].bufferCandidates),v},b.prototype._gather=function(g,p){var m=this,v=this.transceivers[p].iceGatherer;if(!v.onlocalcandidate){var w=this.transceivers[p].bufferedCandidateEvents;this.transceivers[p].bufferedCandidateEvents=null,v.removeEventListener("localcandidate",this.transceivers[p].bufferCandidates),v.onlocalcandidate=function(E){if(!(m.usingBundle&&p>0)){var C=new Event("icecandidate");C.candidate={sdpMid:g,sdpMLineIndex:p};var T=E.candidate,R=!T||Object.keys(T).length===0;if(R)v.state!=="new"&&v.state!=="gathering"||(v.state="completed");else{v.state==="new"&&(v.state="gathering"),T.component=1,T.ufrag=v.getLocalParameters().usernameFragment;var I=i.writeCandidate(T);C.candidate=Object.assign(C.candidate,i.parseCandidate(I)),C.candidate.candidate=I,C.candidate.toJSON=function(){return{candidate:C.candidate.candidate,sdpMid:C.candidate.sdpMid,sdpMLineIndex:C.candidate.sdpMLineIndex,usernameFragment:C.candidate.usernameFragment}}}var O=i.getMediaSections(m._localDescription.sdp);O[C.candidate.sdpMLineIndex]+=R?`a=end-of-candidates\r
49
- `:"a="+C.candidate.candidate+`\r
50
- `,m._localDescription.sdp=i.getDescription(m._localDescription.sdp)+O.join("");var L=m.transceivers.every(function(A){return A.iceGatherer&&A.iceGatherer.state==="completed"});m.iceGatheringState!=="gathering"&&(m.iceGatheringState="gathering",m._emitGatheringStateChange()),R||m._dispatchEvent("icecandidate",C),L&&(m._dispatchEvent("icecandidate",new Event("icecandidate")),m.iceGatheringState="complete",m._emitGatheringStateChange())}},h.setTimeout(function(){w.forEach(function(E){v.onlocalcandidate(E)})},0)}},b.prototype._createIceAndDtlsTransports=function(){var g=this,p=new h.RTCIceTransport(null);p.onicestatechange=function(){g._updateIceConnectionState(),g._updateConnectionState()};var m=new h.RTCDtlsTransport(p);return m.ondtlsstatechange=function(){g._updateConnectionState()},m.onerror=function(){Object.defineProperty(m,"state",{value:"failed",writable:!0}),g._updateConnectionState()},{iceTransport:p,dtlsTransport:m}},b.prototype._disposeIceAndDtlsTransports=function(g){var p=this.transceivers[g].iceGatherer;p&&(delete p.onlocalcandidate,delete this.transceivers[g].iceGatherer);var m=this.transceivers[g].iceTransport;m&&(delete m.onicestatechange,delete this.transceivers[g].iceTransport);var v=this.transceivers[g].dtlsTransport;v&&(delete v.ondtlsstatechange,delete v.onerror,delete this.transceivers[g].dtlsTransport)},b.prototype._transceive=function(g,p,m){var v=s(g.localCapabilities,g.remoteCapabilities);p&&g.rtpSender&&(v.encodings=g.sendEncodingParameters,v.rtcp={cname:i.localCName,compound:g.rtcpParameters.compound},g.recvEncodingParameters.length&&(v.rtcp.ssrc=g.recvEncodingParameters[0].ssrc),g.rtpSender.send(v)),m&&g.rtpReceiver&&v.codecs.length>0&&(g.kind==="video"&&g.recvEncodingParameters&&u<15019&&g.recvEncodingParameters.forEach(function(w){delete w.rtx}),g.recvEncodingParameters.length?v.encodings=g.recvEncodingParameters:v.encodings=[{}],v.rtcp={compound:g.rtcpParameters.compound},g.rtcpParameters.cname&&(v.rtcp.cname=g.rtcpParameters.cname),g.sendEncodingParameters.length&&(v.rtcp.ssrc=g.sendEncodingParameters[0].ssrc),g.rtpReceiver.receive(v))},b.prototype.setLocalDescription=function(g){var p,m,v=this;if(["offer","answer"].indexOf(g.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+g.type+'"'));if(!c("setLocalDescription",g.type,v.signalingState)||v._isClosed)return Promise.reject(l("InvalidStateError","Can not set local "+g.type+" in state "+v.signalingState));if(g.type==="offer")p=i.splitSections(g.sdp),m=p.shift(),p.forEach(function(E,C){var T=i.parseRtpParameters(E);v.transceivers[C].localCapabilities=T}),v.transceivers.forEach(function(E,C){v._gather(E.mid,C)});else if(g.type==="answer"){p=i.splitSections(v._remoteDescription.sdp),m=p.shift();var w=i.matchPrefix(m,"a=ice-lite").length>0;p.forEach(function(E,C){var T=v.transceivers[C],R=T.iceGatherer,I=T.iceTransport,O=T.dtlsTransport,L=T.localCapabilities,A=T.remoteCapabilities;if(!(i.isRejected(E)&&i.matchPrefix(E,"a=bundle-only").length===0)&&!T.rejected){var F=i.getIceParameters(E,m),H=i.getDtlsParameters(E,m);w&&(H.role="server"),v.usingBundle&&C!==0||(v._gather(T.mid,C),I.state==="new"&&I.start(R,F,w?"controlling":"controlled"),O.state==="new"&&O.start(H));var z=s(L,A);v._transceive(T,z.codecs.length>0,!1)}})}return v._localDescription={type:g.type,sdp:g.sdp},g.type==="offer"?v._updateSignalingState("have-local-offer"):v._updateSignalingState("stable"),Promise.resolve()},b.prototype.setRemoteDescription=function(g){var p=this;if(["offer","answer"].indexOf(g.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+g.type+'"'));if(!c("setRemoteDescription",g.type,p.signalingState)||p._isClosed)return Promise.reject(l("InvalidStateError","Can not set remote "+g.type+" in state "+p.signalingState));var m={};p.remoteStreams.forEach(function(I){m[I.id]=I});var v=[],w=i.splitSections(g.sdp),E=w.shift(),C=i.matchPrefix(E,"a=ice-lite").length>0,T=i.matchPrefix(E,"a=group:BUNDLE ").length>0;p.usingBundle=T;var R=i.matchPrefix(E,"a=ice-options:")[0];return p.canTrickleIceCandidates=!!R&&R.substr(14).split(" ").indexOf("trickle")>=0,w.forEach(function(I,O){var L=i.splitLines(I),A=i.getKind(I),F=i.isRejected(I)&&i.matchPrefix(I,"a=bundle-only").length===0,H=L[0].substr(2).split(" ")[2],z=i.getDirection(I,E),q=i.parseMsid(I),$=i.getMid(I)||i.generateIdentifier();if(F||A==="application"&&(H==="DTLS/SCTP"||H==="UDP/DTLS/SCTP"))p.transceivers[O]={mid:$,kind:A,protocol:H,rejected:!0};else{var W,Ne,ge,Q,qe,jn,_r,rn,jt;!F&&p.transceivers[O]&&p.transceivers[O].rejected&&(p.transceivers[O]=p._createTransceiver(A,!0));var su,au,lu=i.parseRtpParameters(I);F||(su=i.getIceParameters(I,E),(au=i.getDtlsParameters(I,E)).role="client"),_r=i.parseRtpEncodingParameters(I);var cu=i.parseRtcpParameters(I),du=i.matchPrefix(I,"a=end-of-candidates",E).length>0,Co=i.matchPrefix(I,"a=candidate:").map(function(st){return i.parseCandidate(st)}).filter(function(st){return st.component===1});if((g.type==="offer"||g.type==="answer")&&!F&&T&&O>0&&p.transceivers[O]&&(p._disposeIceAndDtlsTransports(O),p.transceivers[O].iceGatherer=p.transceivers[0].iceGatherer,p.transceivers[O].iceTransport=p.transceivers[0].iceTransport,p.transceivers[O].dtlsTransport=p.transceivers[0].dtlsTransport,p.transceivers[O].rtpSender&&p.transceivers[O].rtpSender.setTransport(p.transceivers[0].dtlsTransport),p.transceivers[O].rtpReceiver&&p.transceivers[O].rtpReceiver.setTransport(p.transceivers[0].dtlsTransport)),g.type!=="offer"||F)g.type==="answer"&&!F&&(Ne=(W=p.transceivers[O]).iceGatherer,ge=W.iceTransport,Q=W.dtlsTransport,qe=W.rtpReceiver,jn=W.sendEncodingParameters,rn=W.localCapabilities,p.transceivers[O].recvEncodingParameters=_r,p.transceivers[O].remoteCapabilities=lu,p.transceivers[O].rtcpParameters=cu,Co.length&&ge.state==="new"&&(!C&&!du||T&&O!==0?Co.forEach(function(st){d(W.iceTransport,st)}):ge.setRemoteCandidates(Co)),T&&O!==0||(ge.state==="new"&&ge.start(Ne,su,"controlling"),Q.state==="new"&&Q.start(au)),!s(W.localCapabilities,W.remoteCapabilities).codecs.filter(function(st){return st.name.toLowerCase()==="rtx"}).length&&W.sendEncodingParameters[0].rtx&&delete W.sendEncodingParameters[0].rtx,p._transceive(W,z==="sendrecv"||z==="recvonly",z==="sendrecv"||z==="sendonly"),!qe||z!=="sendrecv"&&z!=="sendonly"?delete W.rtpReceiver:(jt=qe.track,q?(m[q.stream]||(m[q.stream]=new h.MediaStream),f(jt,m[q.stream]),v.push([jt,qe,m[q.stream]])):(m.default||(m.default=new h.MediaStream),f(jt,m.default),v.push([jt,qe,m.default]))));else{(W=p.transceivers[O]||p._createTransceiver(A)).mid=$,W.iceGatherer||(W.iceGatherer=p._createIceGatherer(O,T)),Co.length&&W.iceTransport.state==="new"&&(!du||T&&O!==0?Co.forEach(function(st){d(W.iceTransport,st)}):W.iceTransport.setRemoteCandidates(Co)),rn=h.RTCRtpReceiver.getCapabilities(A),u<15019&&(rn.codecs=rn.codecs.filter(function(st){return st.name!=="rtx"})),jn=W.sendEncodingParameters||[{ssrc:1001*(2*O+2)}];var To,sc=!1;z==="sendrecv"||z==="sendonly"?(sc=!W.rtpReceiver,qe=W.rtpReceiver||new h.RTCRtpReceiver(W.dtlsTransport,A),sc&&(jt=qe.track,q&&q.stream==="-"||(q?(m[q.stream]||(m[q.stream]=new h.MediaStream,Object.defineProperty(m[q.stream],"id",{get:function(){return q.stream}})),Object.defineProperty(jt,"id",{get:function(){return q.track}}),To=m[q.stream]):(m.default||(m.default=new h.MediaStream),To=m.default)),To&&(f(jt,To),W.associatedRemoteMediaStreams.push(To)),v.push([jt,qe,To]))):W.rtpReceiver&&W.rtpReceiver.track&&(W.associatedRemoteMediaStreams.forEach(function(st){var ac,hu,uu=st.getTracks().find(function(sg){return sg.id===W.rtpReceiver.track.id});uu&&(ac=uu,(hu=st).removeTrack(ac),hu.dispatchEvent(new h.MediaStreamTrackEvent("removetrack",{track:ac})))}),W.associatedRemoteMediaStreams=[]),W.localCapabilities=rn,W.remoteCapabilities=lu,W.rtpReceiver=qe,W.rtcpParameters=cu,W.sendEncodingParameters=jn,W.recvEncodingParameters=_r,p._transceive(p.transceivers[O],!1,sc)}}}),p._dtlsRole===void 0&&(p._dtlsRole=g.type==="offer"?"active":"passive"),p._remoteDescription={type:g.type,sdp:g.sdp},g.type==="offer"?p._updateSignalingState("have-remote-offer"):p._updateSignalingState("stable"),Object.keys(m).forEach(function(I){var O=m[I];if(O.getTracks().length){if(p.remoteStreams.indexOf(O)===-1){p.remoteStreams.push(O);var L=new Event("addstream");L.stream=O,h.setTimeout(function(){p._dispatchEvent("addstream",L)})}v.forEach(function(A){var F=A[0],H=A[1];O.id===A[2].id&&x(p,F,H,[O])})}}),v.forEach(function(I){I[2]||x(p,I[0],I[1],[])}),h.setTimeout(function(){p&&p.transceivers&&p.transceivers.forEach(function(I){I.iceTransport&&I.iceTransport.state==="new"&&I.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),I.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},b.prototype.close=function(){this.transceivers.forEach(function(g){g.iceTransport&&g.iceTransport.stop(),g.dtlsTransport&&g.dtlsTransport.stop(),g.rtpSender&&g.rtpSender.stop(),g.rtpReceiver&&g.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},b.prototype._updateSignalingState=function(g){this.signalingState=g;var p=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",p)},b.prototype._maybeFireNegotiationNeeded=function(){var g=this;this.signalingState==="stable"&&this.needNegotiation!==!0&&(this.needNegotiation=!0,h.setTimeout(function(){if(g.needNegotiation){g.needNegotiation=!1;var p=new Event("negotiationneeded");g._dispatchEvent("negotiationneeded",p)}},0))},b.prototype._updateIceConnectionState=function(){var g,p={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(v){v.iceTransport&&!v.rejected&&p[v.iceTransport.state]++}),g="new",p.failed>0?g="failed":p.checking>0?g="checking":p.disconnected>0?g="disconnected":p.new>0?g="new":p.connected>0?g="connected":p.completed>0&&(g="completed"),g!==this.iceConnectionState){this.iceConnectionState=g;var m=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",m)}},b.prototype._updateConnectionState=function(){var g,p={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(v){v.iceTransport&&v.dtlsTransport&&!v.rejected&&(p[v.iceTransport.state]++,p[v.dtlsTransport.state]++)}),p.connected+=p.completed,g="new",p.failed>0?g="failed":p.connecting>0?g="connecting":p.disconnected>0?g="disconnected":p.new>0?g="new":p.connected>0&&(g="connected"),g!==this.connectionState){this.connectionState=g;var m=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",m)}},b.prototype.createOffer=function(){var g=this;if(g._isClosed)return Promise.reject(l("InvalidStateError","Can not call createOffer after close"));var p=g.transceivers.filter(function(C){return C.kind==="audio"}).length,m=g.transceivers.filter(function(C){return C.kind==="video"}).length,v=arguments[0];if(v){if(v.mandatory||v.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");v.offerToReceiveAudio!==void 0&&(p=v.offerToReceiveAudio===!0?1:v.offerToReceiveAudio===!1?0:v.offerToReceiveAudio),v.offerToReceiveVideo!==void 0&&(m=v.offerToReceiveVideo===!0?1:v.offerToReceiveVideo===!1?0:v.offerToReceiveVideo)}for(g.transceivers.forEach(function(C){C.kind==="audio"?--p<0&&(C.wantReceive=!1):C.kind==="video"&&--m<0&&(C.wantReceive=!1)});p>0||m>0;)p>0&&(g._createTransceiver("audio"),p--),m>0&&(g._createTransceiver("video"),m--);var w=i.writeSessionBoilerplate(g._sdpSessionId,g._sdpSessionVersion++);g.transceivers.forEach(function(C,T){var R=C.track,I=C.kind,O=C.mid||i.generateIdentifier();C.mid=O,C.iceGatherer||(C.iceGatherer=g._createIceGatherer(T,g.usingBundle));var L=h.RTCRtpSender.getCapabilities(I);u<15019&&(L.codecs=L.codecs.filter(function(F){return F.name!=="rtx"})),L.codecs.forEach(function(F){F.name==="H264"&&F.parameters["level-asymmetry-allowed"]===void 0&&(F.parameters["level-asymmetry-allowed"]="1"),C.remoteCapabilities&&C.remoteCapabilities.codecs&&C.remoteCapabilities.codecs.forEach(function(H){F.name.toLowerCase()===H.name.toLowerCase()&&F.clockRate===H.clockRate&&(F.preferredPayloadType=H.payloadType)})}),L.headerExtensions.forEach(function(F){(C.remoteCapabilities&&C.remoteCapabilities.headerExtensions||[]).forEach(function(H){F.uri===H.uri&&(F.id=H.id)})});var A=C.sendEncodingParameters||[{ssrc:1001*(2*T+1)}];R&&u>=15019&&I==="video"&&!A[0].rtx&&(A[0].rtx={ssrc:A[0].ssrc+1}),C.wantReceive&&(C.rtpReceiver=new h.RTCRtpReceiver(C.dtlsTransport,I)),C.localCapabilities=L,C.sendEncodingParameters=A}),g._config.bundlePolicy!=="max-compat"&&(w+="a=group:BUNDLE "+g.transceivers.map(function(C){return C.mid}).join(" ")+`\r
51
- `),w+=`a=ice-options:trickle\r
52
- `,g.transceivers.forEach(function(C,T){w+=r(C,C.localCapabilities,"offer",C.stream,g._dtlsRole),w+=`a=rtcp-rsize\r
53
- `,!C.iceGatherer||g.iceGatheringState==="new"||T!==0&&g.usingBundle||(C.iceGatherer.getLocalCandidates().forEach(function(R){R.component=1,w+="a="+i.writeCandidate(R)+`\r
54
- `}),C.iceGatherer.state==="completed"&&(w+=`a=end-of-candidates\r
55
- `))});var E=new h.RTCSessionDescription({type:"offer",sdp:w});return Promise.resolve(E)},b.prototype.createAnswer=function(){var g=this;if(g._isClosed)return Promise.reject(l("InvalidStateError","Can not call createAnswer after close"));if(g.signalingState!=="have-remote-offer"&&g.signalingState!=="have-local-pranswer")return Promise.reject(l("InvalidStateError","Can not call createAnswer in signalingState "+g.signalingState));var p=i.writeSessionBoilerplate(g._sdpSessionId,g._sdpSessionVersion++);g.usingBundle&&(p+="a=group:BUNDLE "+g.transceivers.map(function(w){return w.mid}).join(" ")+`\r
56
- `),p+=`a=ice-options:trickle\r
57
- `;var m=i.getMediaSections(g._remoteDescription.sdp).length;g.transceivers.forEach(function(w,E){if(!(E+1>m)){if(w.rejected)return w.kind==="application"?w.protocol==="DTLS/SCTP"?p+=`m=application 0 DTLS/SCTP 5000\r
58
- `:p+="m=application 0 "+w.protocol+` webrtc-datachannel\r
59
- `:w.kind==="audio"?p+=`m=audio 0 UDP/TLS/RTP/SAVPF 0\r
44
+ `,u.rtpSender){var m=u.rtpSender._initialTrackId||u.rtpSender.track.id;u.rtpSender._initialTrackId=m;var f="msid:"+(_?_.id:"-")+" "+m+`\r
45
+ `;y+="a="+f,y+="a=ssrc:"+u.sendEncodingParameters[0].ssrc+" "+f,u.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+u.sendEncodingParameters[0].rtx.ssrc+" "+f,y+="a=ssrc-group:FID "+u.sendEncodingParameters[0].ssrc+" "+u.sendEncodingParameters[0].rtx.ssrc+`\r
46
+ `)}return y+="a=ssrc:"+u.sendEncodingParameters[0].ssrc+" cname:"+n.localCName+`\r
47
+ `,u.rtpSender&&u.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+u.sendEncodingParameters[0].rtx.ssrc+" cname:"+n.localCName+`\r
48
+ `),y}function s(u,h){var b=!1;return(u=JSON.parse(JSON.stringify(u))).filter(function(_){if(_&&(_.urls||_.url)){var v=_.urls||_.url;_.url&&!_.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var y=typeof v=="string";return y&&(v=[v]),v=v.filter(function(m){return m.indexOf("turn:")===0&&m.indexOf("transport=udp")!==-1&&m.indexOf("turn:[")===-1&&!b?(b=!0,!0):m.indexOf("stun:")===0&&h>=14393&&m.indexOf("?transport=udp")===-1}),delete _.url,_.urls=y?v[0]:v,!!v.length}})}function a(u,h){var b={codecs:[],headerExtensions:[],fecMechanisms:[]},_=function(y,m){y=parseInt(y,10);for(var f=0;f<m.length;f++)if(m[f].payloadType===y||m[f].preferredPayloadType===y)return m[f]},v=function(y,m,f,p){var g=_(y.parameters.apt,f),E=_(m.parameters.apt,p);return g&&E&&g.name.toLowerCase()===E.name.toLowerCase()};return u.codecs.forEach(function(y){for(var m=0;m<h.codecs.length;m++){var f=h.codecs[m];if(y.name.toLowerCase()===f.name.toLowerCase()&&y.clockRate===f.clockRate){if(y.name.toLowerCase()==="rtx"&&y.parameters&&f.parameters.apt&&!v(y,f,u.codecs,h.codecs))continue;(f=JSON.parse(JSON.stringify(f))).numChannels=Math.min(y.numChannels,f.numChannels),b.codecs.push(f),f.rtcpFeedback=f.rtcpFeedback.filter(function(p){for(var g=0;g<y.rtcpFeedback.length;g++)if(y.rtcpFeedback[g].type===p.type&&y.rtcpFeedback[g].parameter===p.parameter)return!0;return!1});break}}}),u.headerExtensions.forEach(function(y){for(var m=0;m<h.headerExtensions.length;m++){var f=h.headerExtensions[m];if(y.uri===f.uri){b.headerExtensions.push(f);break}}}),b}function c(u,h,b){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[h][u].indexOf(b)!==-1}function d(u,h){var b=u.getRemoteCandidates().find(function(_){return h.foundation===_.foundation&&h.ip===_.ip&&h.port===_.port&&h.priority===_.priority&&h.protocol===_.protocol&&h.type===_.type});return b||u.addRemoteCandidate(h),!b}function l(u,h){var b=new Error(h);return b.name=u,b.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[u],b}e.exports=function(u,h){function b(m,f){f.addTrack(m),f.dispatchEvent(new u.MediaStreamTrackEvent("addtrack",{track:m}))}function _(m,f,p,g){var E=new Event("track");E.track=f,E.receiver=p,E.transceiver={receiver:p},E.streams=g,u.setTimeout(function(){m._dispatchEvent("track",E)})}var v=function(m){var f=this,p=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(E){f[E]=p[E].bind(p)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",m=JSON.parse(JSON.stringify(m||{})),this.usingBundle=m.bundlePolicy==="max-bundle",m.rtcpMuxPolicy==="negotiate")throw l("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(m.rtcpMuxPolicy||(m.rtcpMuxPolicy="require"),m.iceTransportPolicy){case"all":case"relay":break;default:m.iceTransportPolicy="all"}switch(m.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:m.bundlePolicy="balanced"}if(m.iceServers=s(m.iceServers||[],h),this._iceGatherers=[],m.iceCandidatePoolSize)for(var g=m.iceCandidatePoolSize;g>0;g--)this._iceGatherers.push(new u.RTCIceGatherer({iceServers:m.iceServers,gatherPolicy:m.iceTransportPolicy}));else m.iceCandidatePoolSize=0;this._config=m,this.transceivers=[],this._sdpSessionId=n.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(v.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(v.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),v.prototype.onicecandidate=null,v.prototype.onaddstream=null,v.prototype.ontrack=null,v.prototype.onremovestream=null,v.prototype.onsignalingstatechange=null,v.prototype.oniceconnectionstatechange=null,v.prototype.onconnectionstatechange=null,v.prototype.onicegatheringstatechange=null,v.prototype.onnegotiationneeded=null,v.prototype.ondatachannel=null,v.prototype._dispatchEvent=function(m,f){this._isClosed||(this.dispatchEvent(f),typeof this["on"+m]=="function"&&this["on"+m](f))},v.prototype._emitGatheringStateChange=function(){var m=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",m)},v.prototype.getConfiguration=function(){return this._config},v.prototype.getLocalStreams=function(){return this.localStreams},v.prototype.getRemoteStreams=function(){return this.remoteStreams},v.prototype._createTransceiver=function(m,f){var p=this.transceivers.length>0,g={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:m,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&p)g.iceTransport=this.transceivers[0].iceTransport,g.dtlsTransport=this.transceivers[0].dtlsTransport;else{var E=this._createIceAndDtlsTransports();g.iceTransport=E.iceTransport,g.dtlsTransport=E.dtlsTransport}return f||this.transceivers.push(g),g},v.prototype.addTrack=function(m,f){if(this._isClosed)throw l("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var p;if(this.transceivers.find(function(E){return E.track===m}))throw l("InvalidAccessError","Track already exists.");for(var g=0;g<this.transceivers.length;g++)this.transceivers[g].track||this.transceivers[g].kind!==m.kind||(p=this.transceivers[g]);return p||(p=this._createTransceiver(m.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(f)===-1&&this.localStreams.push(f),p.track=m,p.stream=f,p.rtpSender=new u.RTCRtpSender(m,p.dtlsTransport),p.rtpSender},v.prototype.addStream=function(m){var f=this;if(h>=15025)m.getTracks().forEach(function(g){f.addTrack(g,m)});else{var p=m.clone();m.getTracks().forEach(function(g,E){var w=p.getTracks()[E];g.addEventListener("enabled",function(T){w.enabled=T.enabled})}),p.getTracks().forEach(function(g){f.addTrack(g,p)})}},v.prototype.removeTrack=function(m){if(this._isClosed)throw l("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(m instanceof u.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var f=this.transceivers.find(function(g){return g.rtpSender===m});if(!f)throw l("InvalidAccessError","Sender was not created by this connection.");var p=f.stream;f.rtpSender.stop(),f.rtpSender=null,f.track=null,f.stream=null,this.transceivers.map(function(g){return g.stream}).indexOf(p)===-1&&this.localStreams.indexOf(p)>-1&&this.localStreams.splice(this.localStreams.indexOf(p),1),this._maybeFireNegotiationNeeded()},v.prototype.removeStream=function(m){var f=this;m.getTracks().forEach(function(p){var g=f.getSenders().find(function(E){return E.track===p});g&&f.removeTrack(g)})},v.prototype.getSenders=function(){return this.transceivers.filter(function(m){return!!m.rtpSender}).map(function(m){return m.rtpSender})},v.prototype.getReceivers=function(){return this.transceivers.filter(function(m){return!!m.rtpReceiver}).map(function(m){return m.rtpReceiver})},v.prototype._createIceGatherer=function(m,f){var p=this;if(f&&m>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var g=new u.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(g,"state",{value:"new",writable:!0}),this.transceivers[m].bufferedCandidateEvents=[],this.transceivers[m].bufferCandidates=function(E){var w=!E.candidate||Object.keys(E.candidate).length===0;g.state=w?"completed":"gathering",p.transceivers[m].bufferedCandidateEvents!==null&&p.transceivers[m].bufferedCandidateEvents.push(E)},g.addEventListener("localcandidate",this.transceivers[m].bufferCandidates),g},v.prototype._gather=function(m,f){var p=this,g=this.transceivers[f].iceGatherer;if(!g.onlocalcandidate){var E=this.transceivers[f].bufferedCandidateEvents;this.transceivers[f].bufferedCandidateEvents=null,g.removeEventListener("localcandidate",this.transceivers[f].bufferCandidates),g.onlocalcandidate=function(w){if(!(p.usingBundle&&f>0)){var T=new Event("icecandidate");T.candidate={sdpMid:m,sdpMLineIndex:f};var S=w.candidate,k=!S||Object.keys(S).length===0;if(k)g.state!=="new"&&g.state!=="gathering"||(g.state="completed");else{g.state==="new"&&(g.state="gathering"),S.component=1,S.ufrag=g.getLocalParameters().usernameFragment;var D=n.writeCandidate(S);T.candidate=Object.assign(T.candidate,n.parseCandidate(D)),T.candidate.candidate=D,T.candidate.toJSON=function(){return{candidate:T.candidate.candidate,sdpMid:T.candidate.sdpMid,sdpMLineIndex:T.candidate.sdpMLineIndex,usernameFragment:T.candidate.usernameFragment}}}var P=n.getMediaSections(p._localDescription.sdp);P[T.candidate.sdpMLineIndex]+=k?`a=end-of-candidates\r
49
+ `:"a="+T.candidate.candidate+`\r
50
+ `,p._localDescription.sdp=n.getDescription(p._localDescription.sdp)+P.join("");var H=p.transceivers.every(function(F){return F.iceGatherer&&F.iceGatherer.state==="completed"});p.iceGatheringState!=="gathering"&&(p.iceGatheringState="gathering",p._emitGatheringStateChange()),k||p._dispatchEvent("icecandidate",T),H&&(p._dispatchEvent("icecandidate",new Event("icecandidate")),p.iceGatheringState="complete",p._emitGatheringStateChange())}},u.setTimeout(function(){E.forEach(function(w){g.onlocalcandidate(w)})},0)}},v.prototype._createIceAndDtlsTransports=function(){var m=this,f=new u.RTCIceTransport(null);f.onicestatechange=function(){m._updateIceConnectionState(),m._updateConnectionState()};var p=new u.RTCDtlsTransport(f);return p.ondtlsstatechange=function(){m._updateConnectionState()},p.onerror=function(){Object.defineProperty(p,"state",{value:"failed",writable:!0}),m._updateConnectionState()},{iceTransport:f,dtlsTransport:p}},v.prototype._disposeIceAndDtlsTransports=function(m){var f=this.transceivers[m].iceGatherer;f&&(delete f.onlocalcandidate,delete this.transceivers[m].iceGatherer);var p=this.transceivers[m].iceTransport;p&&(delete p.onicestatechange,delete this.transceivers[m].iceTransport);var g=this.transceivers[m].dtlsTransport;g&&(delete g.ondtlsstatechange,delete g.onerror,delete this.transceivers[m].dtlsTransport)},v.prototype._transceive=function(m,f,p){var g=a(m.localCapabilities,m.remoteCapabilities);f&&m.rtpSender&&(g.encodings=m.sendEncodingParameters,g.rtcp={cname:n.localCName,compound:m.rtcpParameters.compound},m.recvEncodingParameters.length&&(g.rtcp.ssrc=m.recvEncodingParameters[0].ssrc),m.rtpSender.send(g)),p&&m.rtpReceiver&&g.codecs.length>0&&(m.kind==="video"&&m.recvEncodingParameters&&h<15019&&m.recvEncodingParameters.forEach(function(E){delete E.rtx}),m.recvEncodingParameters.length?g.encodings=m.recvEncodingParameters:g.encodings=[{}],g.rtcp={compound:m.rtcpParameters.compound},m.rtcpParameters.cname&&(g.rtcp.cname=m.rtcpParameters.cname),m.sendEncodingParameters.length&&(g.rtcp.ssrc=m.sendEncodingParameters[0].ssrc),m.rtpReceiver.receive(g))},v.prototype.setLocalDescription=function(m){var f,p,g=this;if(["offer","answer"].indexOf(m.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+m.type+'"'));if(!c("setLocalDescription",m.type,g.signalingState)||g._isClosed)return Promise.reject(l("InvalidStateError","Can not set local "+m.type+" in state "+g.signalingState));if(m.type==="offer")f=n.splitSections(m.sdp),p=f.shift(),f.forEach(function(w,T){var S=n.parseRtpParameters(w);g.transceivers[T].localCapabilities=S}),g.transceivers.forEach(function(w,T){g._gather(w.mid,T)});else if(m.type==="answer"){f=n.splitSections(g._remoteDescription.sdp),p=f.shift();var E=n.matchPrefix(p,"a=ice-lite").length>0;f.forEach(function(w,T){var S=g.transceivers[T],k=S.iceGatherer,D=S.iceTransport,P=S.dtlsTransport,H=S.localCapabilities,F=S.remoteCapabilities;if(!(n.isRejected(w)&&n.matchPrefix(w,"a=bundle-only").length===0)&&!S.rejected){var N=n.getIceParameters(w,p),G=n.getDtlsParameters(w,p);E&&(G.role="server"),g.usingBundle&&T!==0||(g._gather(S.mid,T),D.state==="new"&&D.start(k,N,E?"controlling":"controlled"),P.state==="new"&&P.start(G));var ee=a(H,F);g._transceive(S,ee.codecs.length>0,!1)}})}return g._localDescription={type:m.type,sdp:m.sdp},m.type==="offer"?g._updateSignalingState("have-local-offer"):g._updateSignalingState("stable"),Promise.resolve()},v.prototype.setRemoteDescription=function(m){var f=this;if(["offer","answer"].indexOf(m.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+m.type+'"'));if(!c("setRemoteDescription",m.type,f.signalingState)||f._isClosed)return Promise.reject(l("InvalidStateError","Can not set remote "+m.type+" in state "+f.signalingState));var p={};f.remoteStreams.forEach(function(D){p[D.id]=D});var g=[],E=n.splitSections(m.sdp),w=E.shift(),T=n.matchPrefix(w,"a=ice-lite").length>0,S=n.matchPrefix(w,"a=group:BUNDLE ").length>0;f.usingBundle=S;var k=n.matchPrefix(w,"a=ice-options:")[0];return f.canTrickleIceCandidates=!!k&&k.substr(14).split(" ").indexOf("trickle")>=0,E.forEach(function(D,P){var H=n.splitLines(D),F=n.getKind(D),N=n.isRejected(D)&&n.matchPrefix(D,"a=bundle-only").length===0,G=H[0].substr(2).split(" ")[2],ee=n.getDirection(D,w),ae=n.parseMsid(D),Qd=n.getMid(D)||n.generateIdentifier();if(N||F==="application"&&(G==="DTLS/SCTP"||G==="UDP/DTLS/SCTP"))f.transceivers[P]={mid:Qd,kind:F,protocol:G,rejected:!0};else{var X,qd,jo,al,Fn,ll,cl,Ho,Bn;!N&&f.transceivers[P]&&f.transceivers[P].rejected&&(f.transceivers[P]=f._createTransceiver(F,!0));var Yd,Kd,Jd=n.parseRtpParameters(D);N||(Yd=n.getIceParameters(D,w),(Kd=n.getDtlsParameters(D,w)).role="client"),cl=n.parseRtpEncodingParameters(D);var Zd=n.parseRtcpParameters(D),$d=n.matchPrefix(D,"a=end-of-candidates",w).length>0,zr=n.matchPrefix(D,"a=candidate:").map(function(Xe){return n.parseCandidate(Xe)}).filter(function(Xe){return Xe.component===1});if((m.type==="offer"||m.type==="answer")&&!N&&S&&P>0&&f.transceivers[P]&&(f._disposeIceAndDtlsTransports(P),f.transceivers[P].iceGatherer=f.transceivers[0].iceGatherer,f.transceivers[P].iceTransport=f.transceivers[0].iceTransport,f.transceivers[P].dtlsTransport=f.transceivers[0].dtlsTransport,f.transceivers[P].rtpSender&&f.transceivers[P].rtpSender.setTransport(f.transceivers[0].dtlsTransport),f.transceivers[P].rtpReceiver&&f.transceivers[P].rtpReceiver.setTransport(f.transceivers[0].dtlsTransport)),m.type!=="offer"||N)m.type==="answer"&&!N&&(qd=(X=f.transceivers[P]).iceGatherer,jo=X.iceTransport,al=X.dtlsTransport,Fn=X.rtpReceiver,ll=X.sendEncodingParameters,Ho=X.localCapabilities,f.transceivers[P].recvEncodingParameters=cl,f.transceivers[P].remoteCapabilities=Jd,f.transceivers[P].rtcpParameters=Zd,zr.length&&jo.state==="new"&&(!T&&!$d||S&&P!==0?zr.forEach(function(Xe){d(X.iceTransport,Xe)}):jo.setRemoteCandidates(zr)),S&&P!==0||(jo.state==="new"&&jo.start(qd,Yd,"controlling"),al.state==="new"&&al.start(Kd)),!a(X.localCapabilities,X.remoteCapabilities).codecs.filter(function(Xe){return Xe.name.toLowerCase()==="rtx"}).length&&X.sendEncodingParameters[0].rtx&&delete X.sendEncodingParameters[0].rtx,f._transceive(X,ee==="sendrecv"||ee==="recvonly",ee==="sendrecv"||ee==="sendonly"),!Fn||ee!=="sendrecv"&&ee!=="sendonly"?delete X.rtpReceiver:(Bn=Fn.track,ae?(p[ae.stream]||(p[ae.stream]=new u.MediaStream),b(Bn,p[ae.stream]),g.push([Bn,Fn,p[ae.stream]])):(p.default||(p.default=new u.MediaStream),b(Bn,p.default),g.push([Bn,Fn,p.default]))));else{(X=f.transceivers[P]||f._createTransceiver(F)).mid=Qd,X.iceGatherer||(X.iceGatherer=f._createIceGatherer(P,S)),zr.length&&X.iceTransport.state==="new"&&(!$d||S&&P!==0?zr.forEach(function(Xe){d(X.iceTransport,Xe)}):X.iceTransport.setRemoteCandidates(zr)),Ho=u.RTCRtpReceiver.getCapabilities(F),h<15019&&(Ho.codecs=Ho.codecs.filter(function(Xe){return Xe.name!=="rtx"})),ll=X.sendEncodingParameters||[{ssrc:1001*(2*P+2)}];var Xr,dl=!1;ee==="sendrecv"||ee==="sendonly"?(dl=!X.rtpReceiver,Fn=X.rtpReceiver||new u.RTCRtpReceiver(X.dtlsTransport,F),dl&&(Bn=Fn.track,ae&&ae.stream==="-"||(ae?(p[ae.stream]||(p[ae.stream]=new u.MediaStream,Object.defineProperty(p[ae.stream],"id",{get:function(){return ae.stream}})),Object.defineProperty(Bn,"id",{get:function(){return ae.track}}),Xr=p[ae.stream]):(p.default||(p.default=new u.MediaStream),Xr=p.default)),Xr&&(b(Bn,Xr),X.associatedRemoteMediaStreams.push(Xr)),g.push([Bn,Fn,Xr]))):X.rtpReceiver&&X.rtpReceiver.track&&(X.associatedRemoteMediaStreams.forEach(function(Xe){var ul,eu,tu=Xe.getTracks().find(function(Yp){return Yp.id===X.rtpReceiver.track.id});tu&&(ul=tu,(eu=Xe).removeTrack(ul),eu.dispatchEvent(new u.MediaStreamTrackEvent("removetrack",{track:ul})))}),X.associatedRemoteMediaStreams=[]),X.localCapabilities=Ho,X.remoteCapabilities=Jd,X.rtpReceiver=Fn,X.rtcpParameters=Zd,X.sendEncodingParameters=ll,X.recvEncodingParameters=cl,f._transceive(f.transceivers[P],!1,dl)}}}),f._dtlsRole===void 0&&(f._dtlsRole=m.type==="offer"?"active":"passive"),f._remoteDescription={type:m.type,sdp:m.sdp},m.type==="offer"?f._updateSignalingState("have-remote-offer"):f._updateSignalingState("stable"),Object.keys(p).forEach(function(D){var P=p[D];if(P.getTracks().length){if(f.remoteStreams.indexOf(P)===-1){f.remoteStreams.push(P);var H=new Event("addstream");H.stream=P,u.setTimeout(function(){f._dispatchEvent("addstream",H)})}g.forEach(function(F){var N=F[0],G=F[1];P.id===F[2].id&&_(f,N,G,[P])})}}),g.forEach(function(D){D[2]||_(f,D[0],D[1],[])}),u.setTimeout(function(){f&&f.transceivers&&f.transceivers.forEach(function(D){D.iceTransport&&D.iceTransport.state==="new"&&D.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),D.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},v.prototype.close=function(){this.transceivers.forEach(function(m){m.iceTransport&&m.iceTransport.stop(),m.dtlsTransport&&m.dtlsTransport.stop(),m.rtpSender&&m.rtpSender.stop(),m.rtpReceiver&&m.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},v.prototype._updateSignalingState=function(m){this.signalingState=m;var f=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",f)},v.prototype._maybeFireNegotiationNeeded=function(){var m=this;this.signalingState==="stable"&&this.needNegotiation!==!0&&(this.needNegotiation=!0,u.setTimeout(function(){if(m.needNegotiation){m.needNegotiation=!1;var f=new Event("negotiationneeded");m._dispatchEvent("negotiationneeded",f)}},0))},v.prototype._updateIceConnectionState=function(){var m,f={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(g){g.iceTransport&&!g.rejected&&f[g.iceTransport.state]++}),m="new",f.failed>0?m="failed":f.checking>0?m="checking":f.disconnected>0?m="disconnected":f.new>0?m="new":f.connected>0?m="connected":f.completed>0&&(m="completed"),m!==this.iceConnectionState){this.iceConnectionState=m;var p=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",p)}},v.prototype._updateConnectionState=function(){var m,f={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(g){g.iceTransport&&g.dtlsTransport&&!g.rejected&&(f[g.iceTransport.state]++,f[g.dtlsTransport.state]++)}),f.connected+=f.completed,m="new",f.failed>0?m="failed":f.connecting>0?m="connecting":f.disconnected>0?m="disconnected":f.new>0?m="new":f.connected>0&&(m="connected"),m!==this.connectionState){this.connectionState=m;var p=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",p)}},v.prototype.createOffer=function(){var m=this;if(m._isClosed)return Promise.reject(l("InvalidStateError","Can not call createOffer after close"));var f=m.transceivers.filter(function(T){return T.kind==="audio"}).length,p=m.transceivers.filter(function(T){return T.kind==="video"}).length,g=arguments[0];if(g){if(g.mandatory||g.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");g.offerToReceiveAudio!==void 0&&(f=g.offerToReceiveAudio===!0?1:g.offerToReceiveAudio===!1?0:g.offerToReceiveAudio),g.offerToReceiveVideo!==void 0&&(p=g.offerToReceiveVideo===!0?1:g.offerToReceiveVideo===!1?0:g.offerToReceiveVideo)}for(m.transceivers.forEach(function(T){T.kind==="audio"?--f<0&&(T.wantReceive=!1):T.kind==="video"&&--p<0&&(T.wantReceive=!1)});f>0||p>0;)f>0&&(m._createTransceiver("audio"),f--),p>0&&(m._createTransceiver("video"),p--);var E=n.writeSessionBoilerplate(m._sdpSessionId,m._sdpSessionVersion++);m.transceivers.forEach(function(T,S){var k=T.track,D=T.kind,P=T.mid||n.generateIdentifier();T.mid=P,T.iceGatherer||(T.iceGatherer=m._createIceGatherer(S,m.usingBundle));var H=u.RTCRtpSender.getCapabilities(D);h<15019&&(H.codecs=H.codecs.filter(function(N){return N.name!=="rtx"})),H.codecs.forEach(function(N){N.name==="H264"&&N.parameters["level-asymmetry-allowed"]===void 0&&(N.parameters["level-asymmetry-allowed"]="1"),T.remoteCapabilities&&T.remoteCapabilities.codecs&&T.remoteCapabilities.codecs.forEach(function(G){N.name.toLowerCase()===G.name.toLowerCase()&&N.clockRate===G.clockRate&&(N.preferredPayloadType=G.payloadType)})}),H.headerExtensions.forEach(function(N){(T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[]).forEach(function(G){N.uri===G.uri&&(N.id=G.id)})});var F=T.sendEncodingParameters||[{ssrc:1001*(2*S+1)}];k&&h>=15019&&D==="video"&&!F[0].rtx&&(F[0].rtx={ssrc:F[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new u.RTCRtpReceiver(T.dtlsTransport,D)),T.localCapabilities=H,T.sendEncodingParameters=F}),m._config.bundlePolicy!=="max-compat"&&(E+="a=group:BUNDLE "+m.transceivers.map(function(T){return T.mid}).join(" ")+`\r
51
+ `),E+=`a=ice-options:trickle\r
52
+ `,m.transceivers.forEach(function(T,S){E+=r(T,T.localCapabilities,"offer",T.stream,m._dtlsRole),E+=`a=rtcp-rsize\r
53
+ `,!T.iceGatherer||m.iceGatheringState==="new"||S!==0&&m.usingBundle||(T.iceGatherer.getLocalCandidates().forEach(function(k){k.component=1,E+="a="+n.writeCandidate(k)+`\r
54
+ `}),T.iceGatherer.state==="completed"&&(E+=`a=end-of-candidates\r
55
+ `))});var w=new u.RTCSessionDescription({type:"offer",sdp:E});return Promise.resolve(w)},v.prototype.createAnswer=function(){var m=this;if(m._isClosed)return Promise.reject(l("InvalidStateError","Can not call createAnswer after close"));if(m.signalingState!=="have-remote-offer"&&m.signalingState!=="have-local-pranswer")return Promise.reject(l("InvalidStateError","Can not call createAnswer in signalingState "+m.signalingState));var f=n.writeSessionBoilerplate(m._sdpSessionId,m._sdpSessionVersion++);m.usingBundle&&(f+="a=group:BUNDLE "+m.transceivers.map(function(E){return E.mid}).join(" ")+`\r
56
+ `),f+=`a=ice-options:trickle\r
57
+ `;var p=n.getMediaSections(m._remoteDescription.sdp).length;m.transceivers.forEach(function(E,w){if(!(w+1>p)){if(E.rejected)return E.kind==="application"?E.protocol==="DTLS/SCTP"?f+=`m=application 0 DTLS/SCTP 5000\r
58
+ `:f+="m=application 0 "+E.protocol+` webrtc-datachannel\r
59
+ `:E.kind==="audio"?f+=`m=audio 0 UDP/TLS/RTP/SAVPF 0\r
60
60
  a=rtpmap:0 PCMU/8000\r
61
- `:w.kind==="video"&&(p+=`m=video 0 UDP/TLS/RTP/SAVPF 120\r
61
+ `:E.kind==="video"&&(f+=`m=video 0 UDP/TLS/RTP/SAVPF 120\r
62
62
  a=rtpmap:120 VP8/90000\r
63
- `),void(p+=`c=IN IP4 0.0.0.0\r
63
+ `),void(f+=`c=IN IP4 0.0.0.0\r
64
64
  a=inactive\r
65
- a=mid:`+w.mid+`\r
66
- `);var C;w.stream&&(w.kind==="audio"?C=w.stream.getAudioTracks()[0]:w.kind==="video"&&(C=w.stream.getVideoTracks()[0]),C&&u>=15019&&w.kind==="video"&&!w.sendEncodingParameters[0].rtx&&(w.sendEncodingParameters[0].rtx={ssrc:w.sendEncodingParameters[0].ssrc+1}));var T=s(w.localCapabilities,w.remoteCapabilities);!T.codecs.filter(function(R){return R.name.toLowerCase()==="rtx"}).length&&w.sendEncodingParameters[0].rtx&&delete w.sendEncodingParameters[0].rtx,p+=r(w,T,"answer",w.stream,g._dtlsRole),w.rtcpParameters&&w.rtcpParameters.reducedSize&&(p+=`a=rtcp-rsize\r
67
- `)}});var v=new h.RTCSessionDescription({type:"answer",sdp:p});return Promise.resolve(v)},b.prototype.addIceCandidate=function(g){var p,m=this;return g&&g.sdpMLineIndex===void 0&&!g.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(v,w){if(!m._remoteDescription)return w(l("InvalidStateError","Can not add ICE candidate without a remote description"));if(g&&g.candidate!==""){var E=g.sdpMLineIndex;if(g.sdpMid){for(var C=0;C<m.transceivers.length;C++)if(m.transceivers[C].mid===g.sdpMid){E=C;break}}var T=m.transceivers[E];if(!T)return w(l("OperationError","Can not add ICE candidate"));if(T.rejected)return v();var R=Object.keys(g.candidate).length>0?i.parseCandidate(g.candidate):{};if(R.protocol==="tcp"&&(R.port===0||R.port===9)||R.component&&R.component!==1)return v();if((E===0||E>0&&T.iceTransport!==m.transceivers[0].iceTransport)&&!d(T.iceTransport,R))return w(l("OperationError","Can not add ICE candidate"));var I=g.candidate.trim();I.indexOf("a=")===0&&(I=I.substr(2)),(p=i.getMediaSections(m._remoteDescription.sdp))[E]+="a="+(R.type?I:"end-of-candidates")+`\r
68
- `,m._remoteDescription.sdp=i.getDescription(m._remoteDescription.sdp)+p.join("")}else for(var O=0;O<m.transceivers.length&&(m.transceivers[O].rejected||(m.transceivers[O].iceTransport.addRemoteCandidate({}),(p=i.getMediaSections(m._remoteDescription.sdp))[O]+=`a=end-of-candidates\r
69
- `,m._remoteDescription.sdp=i.getDescription(m._remoteDescription.sdp)+p.join(""),!m.usingBundle));O++);v()})},b.prototype.getStats=function(g){if(g&&g instanceof h.MediaStreamTrack){var p=null;if(this.transceivers.forEach(function(v){v.rtpSender&&v.rtpSender.track===g?p=v.rtpSender:v.rtpReceiver&&v.rtpReceiver.track===g&&(p=v.rtpReceiver)}),!p)throw l("InvalidAccessError","Invalid selector.");return p.getStats()}var m=[];return this.transceivers.forEach(function(v){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(w){v[w]&&m.push(v[w].getStats())})}),Promise.all(m).then(function(v){var w=new Map;return v.forEach(function(E){E.forEach(function(C){w.set(C.id,C)})}),w})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(g){var p=h[g];if(p&&p.prototype&&p.prototype.getStats){var m=p.prototype.getStats;p.prototype.getStats=function(){return m.apply(this).then(function(v){var w=new Map;return Object.keys(v).forEach(function(E){v[E].type=n(v[E]),w.set(E,v[E])}),w})}}});var y=["createOffer","createAnswer"];return y.forEach(function(g){var p=b.prototype[g];b.prototype[g]=function(){var m=arguments;return typeof m[0]=="function"||typeof m[1]=="function"?p.apply(this,[arguments[2]]).then(function(v){typeof m[0]=="function"&&m[0].apply(null,[v])},function(v){typeof m[1]=="function"&&m[1].apply(null,[v])}):p.apply(this,arguments)}}),(y=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(g){var p=b.prototype[g];b.prototype[g]=function(){var m=arguments;return typeof m[1]=="function"||typeof m[2]=="function"?p.apply(this,arguments).then(function(){typeof m[1]=="function"&&m[1].apply(null)},function(v){typeof m[2]=="function"&&m[2].apply(null,[v])}):p.apply(this,arguments)}}),["getStats"].forEach(function(g){var p=b.prototype[g];b.prototype[g]=function(){var m=arguments;return typeof m[1]=="function"?p.apply(this,arguments).then(function(){typeof m[1]=="function"&&m[1].apply(null)}):p.apply(this,arguments)}}),b}},{sdp:"YHvh"}],YdKx:[function(a,e,t){"use strict";function i(n){var r=n&&n.navigator,o=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(s){return o(s).catch(function(c){return Promise.reject(function(d){return{name:{PermissionDeniedError:"NotAllowedError"}[d.name]||d.name,message:d.message,constraint:d.constraint,toString:function(){return this.name}}}(c))})}}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=i},{}],P3bV:[function(a,e,t){"use strict";function i(n){"getDisplayMedia"in n.navigator&&n.navigator.mediaDevices&&(n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||(n.navigator.mediaDevices.getDisplayMedia=n.navigator.getDisplayMedia.bind(n.navigator)))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],XRic:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimPeerConnection=h,t.shimReplaceTrack=u,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return o.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return s.shimGetDisplayMedia}});var i=l(a("../utils")),n=a("./filtericeservers"),r=c(a("rtcpeerconnection-shim")),o=a("./getusermedia"),s=a("./getdisplaymedia");function c(f){return f&&f.__esModule?f:{default:f}}function d(){if(typeof WeakMap!="function")return null;var f=new WeakMap;return d=function(){return f},f}function l(f){if(f&&f.__esModule)return f;if(f===null||typeof f!="object"&&typeof f!="function")return{default:f};var x=d();if(x&&x.has(f))return x.get(f);var b={},y=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in f)if(Object.prototype.hasOwnProperty.call(f,g)){var p=y?Object.getOwnPropertyDescriptor(f,g):null;p&&(p.get||p.set)?Object.defineProperty(b,g,p):b[g]=f[g]}return b.default=f,x&&x.set(f,b),b}function h(f,x){if(f.RTCIceGatherer&&(f.RTCIceCandidate||(f.RTCIceCandidate=function(g){return g}),f.RTCSessionDescription||(f.RTCSessionDescription=function(g){return g}),x.version<15025)){var b=Object.getOwnPropertyDescriptor(f.MediaStreamTrack.prototype,"enabled");Object.defineProperty(f.MediaStreamTrack.prototype,"enabled",{set:function(g){b.set.call(this,g);var p=new Event("enabled");p.enabled=g,this.dispatchEvent(p)}})}!f.RTCRtpSender||"dtmf"in f.RTCRtpSender.prototype||Object.defineProperty(f.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new f.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),f.RTCDtmfSender&&!f.RTCDTMFSender&&(f.RTCDTMFSender=f.RTCDtmfSender);var y=(0,r.default)(f,x.version);f.RTCPeerConnection=function(g){return g&&g.iceServers&&(g.iceServers=(0,n.filterIceServers)(g.iceServers,x.version),i.log("ICE servers after filtering:",g.iceServers)),new y(g)},f.RTCPeerConnection.prototype=y.prototype}function u(f){!f.RTCRtpSender||"replaceTrack"in f.RTCRtpSender.prototype||(f.RTCRtpSender.prototype.replaceTrack=f.RTCRtpSender.prototype.setTrack)}},{"../utils":"iSxC","./filtericeservers":"NZ1C","rtcpeerconnection-shim":"NJ2u","./getusermedia":"YdKx","./getdisplaymedia":"P3bV"}],GzSv:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=s;var i=r(a("../utils"));function n(){if(typeof WeakMap!="function")return null;var c=new WeakMap;return n=function(){return c},c}function r(c){if(c&&c.__esModule)return c;if(c===null||typeof c!="object"&&typeof c!="function")return{default:c};var d=n();if(d&&d.has(c))return d.get(c);var l={},h=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in c)if(Object.prototype.hasOwnProperty.call(c,u)){var f=h?Object.getOwnPropertyDescriptor(c,u):null;f&&(f.get||f.set)?Object.defineProperty(l,u,f):l[u]=c[u]}return l.default=c,d&&d.set(c,l),l}function o(c){return(o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(d){return typeof d}:function(d){return d&&typeof Symbol=="function"&&d.constructor===Symbol&&d!==Symbol.prototype?"symbol":typeof d})(c)}function s(c,d){var l=c&&c.navigator,h=c&&c.MediaStreamTrack;if(l.getUserMedia=function(y,g,p){i.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),l.mediaDevices.getUserMedia(y).then(g,p)},!(d.version>55&&"autoGainControl"in l.mediaDevices.getSupportedConstraints())){var u=function(y,g,p){g in y&&!(p in y)&&(y[p]=y[g],delete y[g])},f=l.mediaDevices.getUserMedia.bind(l.mediaDevices);if(l.mediaDevices.getUserMedia=function(y){return o(y)==="object"&&o(y.audio)==="object"&&(y=JSON.parse(JSON.stringify(y)),u(y.audio,"autoGainControl","mozAutoGainControl"),u(y.audio,"noiseSuppression","mozNoiseSuppression")),f(y)},h&&h.prototype.getSettings){var x=h.prototype.getSettings;h.prototype.getSettings=function(){var y=x.apply(this,arguments);return u(y,"mozAutoGainControl","autoGainControl"),u(y,"mozNoiseSuppression","noiseSuppression"),y}}if(h&&h.prototype.applyConstraints){var b=h.prototype.applyConstraints;h.prototype.applyConstraints=function(y){return this.kind==="audio"&&o(y)==="object"&&(y=JSON.parse(JSON.stringify(y)),u(y,"autoGainControl","mozAutoGainControl"),u(y,"noiseSuppression","mozNoiseSuppression")),b.apply(this,[y])}}}}},{"../utils":"iSxC"}],UuGU:[function(a,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(o){if(!o||!o.video){var s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return o.video===!0?o.video={mediaSource:r}:o.video.mediaSource=r,n.navigator.mediaDevices.getUserMedia(o)})}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],Fzdr:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimOnTrack=l,t.shimPeerConnection=h,t.shimSenderGetStats=u,t.shimReceiverGetStats=f,t.shimRemoveStream=x,t.shimRTCDataChannel=b,t.shimAddTransceiver=y,t.shimGetParameters=g,t.shimCreateOffer=p,t.shimCreateAnswer=m,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}});var i=s(a("../utils")),n=a("./getusermedia"),r=a("./getdisplaymedia");function o(){if(typeof WeakMap!="function")return null;var v=new WeakMap;return o=function(){return v},v}function s(v){if(v&&v.__esModule)return v;if(v===null||typeof v!="object"&&typeof v!="function")return{default:v};var w=o();if(w&&w.has(v))return w.get(v);var E={},C=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var T in v)if(Object.prototype.hasOwnProperty.call(v,T)){var R=C?Object.getOwnPropertyDescriptor(v,T):null;R&&(R.get||R.set)?Object.defineProperty(E,T,R):E[T]=v[T]}return E.default=v,w&&w.set(v,E),E}function c(v,w,E){return w in v?Object.defineProperty(v,w,{value:E,enumerable:!0,configurable:!0,writable:!0}):v[w]=E,v}function d(v){return(d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(w){return typeof w}:function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w})(v)}function l(v){d(v)==="object"&&v.RTCTrackEvent&&"receiver"in v.RTCTrackEvent.prototype&&!("transceiver"in v.RTCTrackEvent.prototype)&&Object.defineProperty(v.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function h(v,w){if(d(v)==="object"&&(v.RTCPeerConnection||v.mozRTCPeerConnection)){!v.RTCPeerConnection&&v.mozRTCPeerConnection&&(v.RTCPeerConnection=v.mozRTCPeerConnection),w.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(T){var R=v.RTCPeerConnection.prototype[T],I=c({},T,function(){return arguments[0]=new(T==="addIceCandidate"?v.RTCIceCandidate:v.RTCSessionDescription)(arguments[0]),R.apply(this,arguments)});v.RTCPeerConnection.prototype[T]=I[T]});var E={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},C=v.RTCPeerConnection.prototype.getStats;v.RTCPeerConnection.prototype.getStats=function(){var[T,R,I]=arguments;return C.apply(this,[T||null]).then(function(O){if(w.version<53&&!R)try{O.forEach(function(L){L.type=E[L.type]||L.type})}catch(L){if(L.name!=="TypeError")throw L;O.forEach(function(A,F){O.set(F,Object.assign({},A,{type:E[A.type]||A.type}))})}return O}).then(R,I)}}}function u(v){if(d(v)==="object"&&v.RTCPeerConnection&&v.RTCRtpSender&&!(v.RTCRtpSender&&"getStats"in v.RTCRtpSender.prototype)){var w=v.RTCPeerConnection.prototype.getSenders;w&&(v.RTCPeerConnection.prototype.getSenders=function(){var C=this,T=w.apply(this,[]);return T.forEach(function(R){return R._pc=C}),T});var E=v.RTCPeerConnection.prototype.addTrack;E&&(v.RTCPeerConnection.prototype.addTrack=function(){var C=E.apply(this,arguments);return C._pc=this,C}),v.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function f(v){if(d(v)==="object"&&v.RTCPeerConnection&&v.RTCRtpSender&&!(v.RTCRtpSender&&"getStats"in v.RTCRtpReceiver.prototype)){var w=v.RTCPeerConnection.prototype.getReceivers;w&&(v.RTCPeerConnection.prototype.getReceivers=function(){var E=this,C=w.apply(this,[]);return C.forEach(function(T){return T._pc=E}),C}),i.wrapPeerConnectionEvent(v,"track",function(E){return E.receiver._pc=E.srcElement,E}),v.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function x(v){!v.RTCPeerConnection||"removeStream"in v.RTCPeerConnection.prototype||(v.RTCPeerConnection.prototype.removeStream=function(w){var E=this;i.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(C){C.track&&w.getTracks().includes(C.track)&&E.removeTrack(C)})})}function b(v){v.DataChannel&&!v.RTCDataChannel&&(v.RTCDataChannel=v.DataChannel)}function y(v){if(d(v)==="object"&&v.RTCPeerConnection){var w=v.RTCPeerConnection.prototype.addTransceiver;w&&(v.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var E=arguments[1],C=E&&"sendEncodings"in E;C&&E.sendEncodings.forEach(function(O){if("rid"in O&&!/^[a-z0-9]{0,16}$/i.test(O.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in O&&!(parseFloat(O.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in O&&!(parseFloat(O.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var T=w.apply(this,arguments);if(C){var{sender:R}=T,I=R.getParameters();"encodings"in I&&(I.encodings.length!==1||Object.keys(I.encodings[0]).length!==0)||(I.encodings=E.sendEncodings,R.sendEncodings=E.sendEncodings,this.setParametersPromises.push(R.setParameters(I).then(function(){delete R.sendEncodings}).catch(function(){delete R.sendEncodings})))}return T})}}function g(v){if(d(v)==="object"&&v.RTCRtpSender){var w=v.RTCRtpSender.prototype.getParameters;w&&(v.RTCRtpSender.prototype.getParameters=function(){var E=w.apply(this,arguments);return"encodings"in E||(E.encodings=[].concat(this.sendEncodings||[{}])),E})}}function p(v){if(d(v)==="object"&&v.RTCPeerConnection){var w=v.RTCPeerConnection.prototype.createOffer;v.RTCPeerConnection.prototype.createOffer=function(){var E=arguments,C=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return w.apply(C,E)}).finally(function(){C.setParametersPromises=[]}):w.apply(this,arguments)}}}function m(v){if(d(v)==="object"&&v.RTCPeerConnection){var w=v.RTCPeerConnection.prototype.createAnswer;v.RTCPeerConnection.prototype.createAnswer=function(){var E=arguments,C=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return w.apply(C,E)}).finally(function(){C.setParametersPromises=[]}):w.apply(this,arguments)}}}},{"../utils":"iSxC","./getusermedia":"GzSv","./getdisplaymedia":"UuGU"}],t1lL:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimLocalStreamsAPI=s,t.shimRemoteStreamsAPI=c,t.shimCallbacksAPI=d,t.shimGetUserMedia=l,t.shimConstraints=h,t.shimRTCIceServerUrls=u,t.shimTrackEventTransceiver=f,t.shimCreateOfferLegacy=x,t.shimAudioContext=b;var i=r(a("../utils"));function n(){if(typeof WeakMap!="function")return null;var y=new WeakMap;return n=function(){return y},y}function r(y){if(y&&y.__esModule)return y;if(y===null||typeof y!="object"&&typeof y!="function")return{default:y};var g=n();if(g&&g.has(y))return g.get(y);var p={},m=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var v in y)if(Object.prototype.hasOwnProperty.call(y,v)){var w=m?Object.getOwnPropertyDescriptor(y,v):null;w&&(w.get||w.set)?Object.defineProperty(p,v,w):p[v]=y[v]}return p.default=y,g&&g.set(y,p),p}function o(y){return(o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(g){return typeof g}:function(g){return g&&typeof Symbol=="function"&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g})(y)}function s(y){if(o(y)==="object"&&y.RTCPeerConnection){if("getLocalStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in y.RTCPeerConnection.prototype)){var g=y.RTCPeerConnection.prototype.addTrack;y.RTCPeerConnection.prototype.addStream=function(p){var m=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(p)||this._localStreams.push(p),p.getAudioTracks().forEach(function(v){return g.call(m,v,p)}),p.getVideoTracks().forEach(function(v){return g.call(m,v,p)})},y.RTCPeerConnection.prototype.addTrack=function(p){for(var m=this,v=arguments.length,w=new Array(v>1?v-1:0),E=1;E<v;E++)w[E-1]=arguments[E];return w&&w.forEach(function(C){m._localStreams?m._localStreams.includes(C)||m._localStreams.push(C):m._localStreams=[C]}),g.apply(this,arguments)}}"removeStream"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.removeStream=function(p){var m=this;this._localStreams||(this._localStreams=[]);var v=this._localStreams.indexOf(p);if(v!==-1){this._localStreams.splice(v,1);var w=p.getTracks();this.getSenders().forEach(function(E){w.includes(E.track)&&m.removeTrack(E)})}})}}function c(y){if(o(y)==="object"&&y.RTCPeerConnection&&("getRemoteStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in y.RTCPeerConnection.prototype))){Object.defineProperty(y.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(p){var m=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=p),this.addEventListener("track",this._onaddstreampoly=function(v){v.streams.forEach(function(w){if(m._remoteStreams||(m._remoteStreams=[]),!m._remoteStreams.includes(w)){m._remoteStreams.push(w);var E=new Event("addstream");E.stream=w,m.dispatchEvent(E)}})})}});var g=y.RTCPeerConnection.prototype.setRemoteDescription;y.RTCPeerConnection.prototype.setRemoteDescription=function(){var p=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(m){m.streams.forEach(function(v){if(p._remoteStreams||(p._remoteStreams=[]),!(p._remoteStreams.indexOf(v)>=0)){p._remoteStreams.push(v);var w=new Event("addstream");w.stream=v,p.dispatchEvent(w)}})}),g.apply(p,arguments)}}}function d(y){if(o(y)==="object"&&y.RTCPeerConnection){var g=y.RTCPeerConnection.prototype,p=g.createOffer,m=g.createAnswer,v=g.setLocalDescription,w=g.setRemoteDescription,E=g.addIceCandidate;g.createOffer=function(T,R){var I=arguments.length>=2?arguments[2]:arguments[0],O=p.apply(this,[I]);return R?(O.then(T,R),Promise.resolve()):O},g.createAnswer=function(T,R){var I=arguments.length>=2?arguments[2]:arguments[0],O=m.apply(this,[I]);return R?(O.then(T,R),Promise.resolve()):O};var C=function(T,R,I){var O=v.apply(this,[T]);return I?(O.then(R,I),Promise.resolve()):O};g.setLocalDescription=C,C=function(T,R,I){var O=w.apply(this,[T]);return I?(O.then(R,I),Promise.resolve()):O},g.setRemoteDescription=C,C=function(T,R,I){var O=E.apply(this,[T]);return I?(O.then(R,I),Promise.resolve()):O},g.addIceCandidate=C}}function l(y){var g=y&&y.navigator;if(g.mediaDevices&&g.mediaDevices.getUserMedia){var p=g.mediaDevices,m=p.getUserMedia.bind(p);g.mediaDevices.getUserMedia=function(v){return m(h(v))}}!g.getUserMedia&&g.mediaDevices&&g.mediaDevices.getUserMedia&&(g.getUserMedia=function(v,w,E){g.mediaDevices.getUserMedia(v).then(w,E)}.bind(g))}function h(y){return y&&y.video!==void 0?Object.assign({},y,{video:i.compactObject(y.video)}):y}function u(y){if(y.RTCPeerConnection){var g=y.RTCPeerConnection;y.RTCPeerConnection=function(p,m){if(p&&p.iceServers){for(var v=[],w=0;w<p.iceServers.length;w++){var E=p.iceServers[w];!E.hasOwnProperty("urls")&&E.hasOwnProperty("url")?(i.deprecated("RTCIceServer.url","RTCIceServer.urls"),(E=JSON.parse(JSON.stringify(E))).urls=E.url,delete E.url,v.push(E)):v.push(p.iceServers[w])}p.iceServers=v}return new g(p,m)},y.RTCPeerConnection.prototype=g.prototype,"generateCertificate"in g&&Object.defineProperty(y.RTCPeerConnection,"generateCertificate",{get:function(){return g.generateCertificate}})}}function f(y){o(y)==="object"&&y.RTCTrackEvent&&"receiver"in y.RTCTrackEvent.prototype&&!("transceiver"in y.RTCTrackEvent.prototype)&&Object.defineProperty(y.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function x(y){var g=y.RTCPeerConnection.prototype.createOffer;y.RTCPeerConnection.prototype.createOffer=function(p){if(p){p.offerToReceiveAudio!==void 0&&(p.offerToReceiveAudio=!!p.offerToReceiveAudio);var m=this.getTransceivers().find(function(w){return w.receiver.track.kind==="audio"});p.offerToReceiveAudio===!1&&m?m.direction==="sendrecv"?m.setDirection?m.setDirection("sendonly"):m.direction="sendonly":m.direction==="recvonly"&&(m.setDirection?m.setDirection("inactive"):m.direction="inactive"):p.offerToReceiveAudio!==!0||m||this.addTransceiver("audio"),p.offerToReceiveVideo!==void 0&&(p.offerToReceiveVideo=!!p.offerToReceiveVideo);var v=this.getTransceivers().find(function(w){return w.receiver.track.kind==="video"});p.offerToReceiveVideo===!1&&v?v.direction==="sendrecv"?v.setDirection?v.setDirection("sendonly"):v.direction="sendonly":v.direction==="recvonly"&&(v.setDirection?v.setDirection("inactive"):v.direction="inactive"):p.offerToReceiveVideo!==!0||v||this.addTransceiver("video")}return g.apply(this,arguments)}}function b(y){o(y)!=="object"||y.AudioContext||(y.AudioContext=y.webkitAudioContext)}},{"../utils":"iSxC"}],GOQK:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimRTCIceCandidate=d,t.shimMaxMessageSize=l,t.shimSendThrowTypeError=h,t.shimConnectionState=u,t.removeExtmapAllowMixed=f,t.shimAddIceCandidateNullOrEmpty=x;var i=s(a("sdp")),n=o(a("./utils"));function r(){if(typeof WeakMap!="function")return null;var b=new WeakMap;return r=function(){return b},b}function o(b){if(b&&b.__esModule)return b;if(b===null||typeof b!="object"&&typeof b!="function")return{default:b};var y=r();if(y&&y.has(b))return y.get(b);var g={},p=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var m in b)if(Object.prototype.hasOwnProperty.call(b,m)){var v=p?Object.getOwnPropertyDescriptor(b,m):null;v&&(v.get||v.set)?Object.defineProperty(g,m,v):g[m]=b[m]}return g.default=b,y&&y.set(b,g),g}function s(b){return b&&b.__esModule?b:{default:b}}function c(b){return(c=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(y){return typeof y}:function(y){return y&&typeof Symbol=="function"&&y.constructor===Symbol&&y!==Symbol.prototype?"symbol":typeof y})(b)}function d(b){if(b.RTCIceCandidate&&!(b.RTCIceCandidate&&"foundation"in b.RTCIceCandidate.prototype)){var y=b.RTCIceCandidate;b.RTCIceCandidate=function(g){if(c(g)==="object"&&g.candidate&&g.candidate.indexOf("a=")===0&&((g=JSON.parse(JSON.stringify(g))).candidate=g.candidate.substr(2)),g.candidate&&g.candidate.length){var p=new y(g),m=i.default.parseCandidate(g.candidate),v=Object.assign(p,m);return v.toJSON=function(){return{candidate:v.candidate,sdpMid:v.sdpMid,sdpMLineIndex:v.sdpMLineIndex,usernameFragment:v.usernameFragment}},v}return new y(g)},b.RTCIceCandidate.prototype=y.prototype,n.wrapPeerConnectionEvent(b,"icecandidate",function(g){return g.candidate&&Object.defineProperty(g,"candidate",{value:new b.RTCIceCandidate(g.candidate),writable:"false"}),g})}}function l(b,y){if(b.RTCPeerConnection){"sctp"in b.RTCPeerConnection.prototype||Object.defineProperty(b.RTCPeerConnection.prototype,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp}});var g=b.RTCPeerConnection.prototype.setRemoteDescription;b.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,y.browser==="chrome"&&y.version>=76){var{sdpSemantics:p}=this.getConfiguration();p==="plan-b"&&Object.defineProperty(this,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(I){if(!I||!I.sdp)return!1;var O=i.default.splitSections(I.sdp);return O.shift(),O.some(function(L){var A=i.default.parseMLine(L);return A&&A.kind==="application"&&A.protocol.indexOf("SCTP")!==-1})}(arguments[0])){var m,v=function(I){var O=I.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(O===null||O.length<2)return-1;var L=parseInt(O[1],10);return L!=L?-1:L}(arguments[0]),w=(T=v,R=65536,y.browser==="firefox"&&(R=y.version<57?T===-1?16384:2147483637:y.version<60?y.version===57?65535:65536:2147483637),R),E=function(I,O){var L=65536;y.browser==="firefox"&&y.version===57&&(L=65535);var A=i.default.matchPrefix(I.sdp,"a=max-message-size:");return A.length>0?L=parseInt(A[0].substr(19),10):y.browser==="firefox"&&O!==-1&&(L=2147483637),L}(arguments[0],v);m=w===0&&E===0?Number.POSITIVE_INFINITY:w===0||E===0?Math.max(w,E):Math.min(w,E);var C={};Object.defineProperty(C,"maxMessageSize",{get:function(){return m}}),this._sctp=C}var T,R;return g.apply(this,arguments)}}}function h(b){if(b.RTCPeerConnection&&"createDataChannel"in b.RTCPeerConnection.prototype){var y=b.RTCPeerConnection.prototype.createDataChannel;b.RTCPeerConnection.prototype.createDataChannel=function(){var p=y.apply(this,arguments);return g(p,this),p},n.wrapPeerConnectionEvent(b,"datachannel",function(p){return g(p.channel,p.target),p})}function g(p,m){var v=p.send;p.send=function(){var w=arguments[0],E=w.length||w.size||w.byteLength;if(p.readyState==="open"&&m.sctp&&E>m.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+m.sctp.maxMessageSize+" bytes)");return v.apply(p,arguments)}}}function u(b){if(b.RTCPeerConnection&&!("connectionState"in b.RTCPeerConnection.prototype)){var y=b.RTCPeerConnection.prototype;Object.defineProperty(y,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(y,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(g){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),g&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=g)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(g){var p=y[g];y[g]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(m){var v=m.target;if(v._lastConnectionState!==v.connectionState){v._lastConnectionState=v.connectionState;var w=new Event("connectionstatechange",m);v.dispatchEvent(w)}return m},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),p.apply(this,arguments)}})}}function f(b,y){if(b.RTCPeerConnection&&!(y.browser==="chrome"&&y.version>=71||y.browser==="safari"&&y.version>=605)){var g=b.RTCPeerConnection.prototype.setRemoteDescription;b.RTCPeerConnection.prototype.setRemoteDescription=function(p){if(p&&p.sdp&&p.sdp.indexOf(`
70
- a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
71
- `).filter(function(v){return v.trim()!=="a=extmap-allow-mixed"}).join(`
72
- `);b.RTCSessionDescription&&p instanceof b.RTCSessionDescription?arguments[0]=new b.RTCSessionDescription({type:p.type,sdp:m}):p.sdp=m}return g.apply(this,arguments)}}}function x(b,y){if(b.RTCPeerConnection&&b.RTCPeerConnection.prototype){var g=b.RTCPeerConnection.prototype.addIceCandidate;g&&g.length!==0&&(b.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(y.browser==="chrome"&&y.version<78||y.browser==="firefox"&&y.version<68||y.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():g.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}},{sdp:"YHvh","./utils":"iSxC"}],KtlG:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.adapterFactory=h;var i=l(a("./utils")),n=l(a("./chrome/chrome_shim")),r=l(a("./edge/edge_shim")),o=l(a("./firefox/firefox_shim")),s=l(a("./safari/safari_shim")),c=l(a("./common_shim"));function d(){if(typeof WeakMap!="function")return null;var u=new WeakMap;return d=function(){return u},u}function l(u){if(u&&u.__esModule)return u;if(u===null||typeof u!="object"&&typeof u!="function")return{default:u};var f=d();if(f&&f.has(u))return f.get(u);var x={},b=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var y in u)if(Object.prototype.hasOwnProperty.call(u,y)){var g=b?Object.getOwnPropertyDescriptor(u,y):null;g&&(g.get||g.set)?Object.defineProperty(x,y,g):x[y]=u[y]}return x.default=u,f&&f.set(u,x),x}function h(){var{window:u}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},f=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},x=i.log,b=i.detectBrowser(u),y={browserDetails:b,commonShim:c,extractVersion:i.extractVersion,disableLog:i.disableLog,disableWarnings:i.disableWarnings};switch(b.browser){case"chrome":if(!n||!n.shimPeerConnection||!f.shimChrome)return x("Chrome shim is not included in this adapter release."),y;if(b.version===null)return x("Chrome shim can not determine version, not shimming."),y;x("adapter.js shimming chrome."),y.browserShim=n,c.shimAddIceCandidateNullOrEmpty(u,b),n.shimGetUserMedia(u,b),n.shimMediaStream(u,b),n.shimPeerConnection(u,b),n.shimOnTrack(u,b),n.shimAddTrackRemoveTrack(u,b),n.shimGetSendersWithDtmf(u,b),n.shimGetStats(u,b),n.shimSenderReceiverGetStats(u,b),n.fixNegotiationNeeded(u,b),c.shimRTCIceCandidate(u,b),c.shimConnectionState(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b),c.removeExtmapAllowMixed(u,b);break;case"firefox":if(!o||!o.shimPeerConnection||!f.shimFirefox)return x("Firefox shim is not included in this adapter release."),y;x("adapter.js shimming firefox."),y.browserShim=o,c.shimAddIceCandidateNullOrEmpty(u,b),o.shimGetUserMedia(u,b),o.shimPeerConnection(u,b),o.shimOnTrack(u,b),o.shimRemoveStream(u,b),o.shimSenderGetStats(u,b),o.shimReceiverGetStats(u,b),o.shimRTCDataChannel(u,b),o.shimAddTransceiver(u,b),o.shimGetParameters(u,b),o.shimCreateOffer(u,b),o.shimCreateAnswer(u,b),c.shimRTCIceCandidate(u,b),c.shimConnectionState(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b);break;case"edge":if(!r||!r.shimPeerConnection||!f.shimEdge)return x("MS edge shim is not included in this adapter release."),y;x("adapter.js shimming edge."),y.browserShim=r,r.shimGetUserMedia(u,b),r.shimGetDisplayMedia(u,b),r.shimPeerConnection(u,b),r.shimReplaceTrack(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b);break;case"safari":if(!s||!f.shimSafari)return x("Safari shim is not included in this adapter release."),y;x("adapter.js shimming safari."),y.browserShim=s,c.shimAddIceCandidateNullOrEmpty(u,b),s.shimRTCIceServerUrls(u,b),s.shimCreateOfferLegacy(u,b),s.shimCallbacksAPI(u,b),s.shimLocalStreamsAPI(u,b),s.shimRemoteStreamsAPI(u,b),s.shimTrackEventTransceiver(u,b),s.shimGetUserMedia(u,b),s.shimAudioContext(u,b),c.shimRTCIceCandidate(u,b),c.shimMaxMessageSize(u,b),c.shimSendThrowTypeError(u,b),c.removeExtmapAllowMixed(u,b);break;default:x("Unsupported browser!")}return y}},{"./utils":"iSxC","./chrome/chrome_shim":"uI5X","./edge/edge_shim":"XRic","./firefox/firefox_shim":"Fzdr","./safari/safari_shim":"t1lL","./common_shim":"GOQK"}],tI1X:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=a("./adapter_factory.js"),n=(0,i.adapterFactory)({window:typeof window>"u"?void 0:window}),r=n;t.default=r},{"./adapter_factory.js":"KtlG"}],sXtV:[function(a,e,t){"use strict";var i=this&&this.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(t,"__esModule",{value:!0}),t.webRTCAdapter=void 0;var n=i(a("webrtc-adapter"));t.webRTCAdapter=n.default},{"webrtc-adapter":"tI1X"}],I31f:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Supports=void 0;var i=a("./adapter");t.Supports=new(function(){function n(){this.isIOS=["iPad","iPhone","iPod"].includes(navigator.platform),this.supportedBrowsers=["firefox","chrome","safari"],this.minFirefoxVersion=59,this.minChromeVersion=72,this.minSafariVersion=605}return n.prototype.isWebRTCSupported=function(){return typeof RTCPeerConnection<"u"},n.prototype.isBrowserSupported=function(){var r=this.getBrowser(),o=this.getVersion();return!!this.supportedBrowsers.includes(r)&&(r==="chrome"?o>=this.minChromeVersion:r==="firefox"?o>=this.minFirefoxVersion:r==="safari"&&!this.isIOS&&o>=this.minSafariVersion)},n.prototype.getBrowser=function(){return i.webRTCAdapter.browserDetails.browser},n.prototype.getVersion=function(){return i.webRTCAdapter.browserDetails.version||0},n.prototype.isUnifiedPlanSupported=function(){var r,o=this.getBrowser(),s=i.webRTCAdapter.browserDetails.version||0;if(o==="chrome"&&s<72)return!1;if(o==="firefox"&&s>=59)return!0;if(!(window.RTCRtpTransceiver&&"currentDirection"in RTCRtpTransceiver.prototype))return!1;var c=!1;try{(r=new RTCPeerConnection).addTransceiver("audio"),c=!0}catch{}finally{r&&r.close()}return c},n.prototype.toString=function(){return`Supports:
65
+ a=mid:`+E.mid+`\r
66
+ `);var T;E.stream&&(E.kind==="audio"?T=E.stream.getAudioTracks()[0]:E.kind==="video"&&(T=E.stream.getVideoTracks()[0]),T&&h>=15019&&E.kind==="video"&&!E.sendEncodingParameters[0].rtx&&(E.sendEncodingParameters[0].rtx={ssrc:E.sendEncodingParameters[0].ssrc+1}));var S=a(E.localCapabilities,E.remoteCapabilities);!S.codecs.filter(function(k){return k.name.toLowerCase()==="rtx"}).length&&E.sendEncodingParameters[0].rtx&&delete E.sendEncodingParameters[0].rtx,f+=r(E,S,"answer",E.stream,m._dtlsRole),E.rtcpParameters&&E.rtcpParameters.reducedSize&&(f+=`a=rtcp-rsize\r
67
+ `)}});var g=new u.RTCSessionDescription({type:"answer",sdp:f});return Promise.resolve(g)},v.prototype.addIceCandidate=function(m){var f,p=this;return m&&m.sdpMLineIndex===void 0&&!m.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(g,E){if(!p._remoteDescription)return E(l("InvalidStateError","Can not add ICE candidate without a remote description"));if(m&&m.candidate!==""){var w=m.sdpMLineIndex;if(m.sdpMid){for(var T=0;T<p.transceivers.length;T++)if(p.transceivers[T].mid===m.sdpMid){w=T;break}}var S=p.transceivers[w];if(!S)return E(l("OperationError","Can not add ICE candidate"));if(S.rejected)return g();var k=Object.keys(m.candidate).length>0?n.parseCandidate(m.candidate):{};if(k.protocol==="tcp"&&(k.port===0||k.port===9)||k.component&&k.component!==1)return g();if((w===0||w>0&&S.iceTransport!==p.transceivers[0].iceTransport)&&!d(S.iceTransport,k))return E(l("OperationError","Can not add ICE candidate"));var D=m.candidate.trim();D.indexOf("a=")===0&&(D=D.substr(2)),(f=n.getMediaSections(p._remoteDescription.sdp))[w]+="a="+(k.type?D:"end-of-candidates")+`\r
68
+ `,p._remoteDescription.sdp=n.getDescription(p._remoteDescription.sdp)+f.join("")}else for(var P=0;P<p.transceivers.length&&(p.transceivers[P].rejected||(p.transceivers[P].iceTransport.addRemoteCandidate({}),(f=n.getMediaSections(p._remoteDescription.sdp))[P]+=`a=end-of-candidates\r
69
+ `,p._remoteDescription.sdp=n.getDescription(p._remoteDescription.sdp)+f.join(""),!p.usingBundle));P++);g()})},v.prototype.getStats=function(m){if(m&&m instanceof u.MediaStreamTrack){var f=null;if(this.transceivers.forEach(function(g){g.rtpSender&&g.rtpSender.track===m?f=g.rtpSender:g.rtpReceiver&&g.rtpReceiver.track===m&&(f=g.rtpReceiver)}),!f)throw l("InvalidAccessError","Invalid selector.");return f.getStats()}var p=[];return this.transceivers.forEach(function(g){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(E){g[E]&&p.push(g[E].getStats())})}),Promise.all(p).then(function(g){var E=new Map;return g.forEach(function(w){w.forEach(function(T){E.set(T.id,T)})}),E})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(m){var f=u[m];if(f&&f.prototype&&f.prototype.getStats){var p=f.prototype.getStats;f.prototype.getStats=function(){return p.apply(this).then(function(g){var E=new Map;return Object.keys(g).forEach(function(w){g[w].type=i(g[w]),E.set(w,g[w])}),E})}}});var y=["createOffer","createAnswer"];return y.forEach(function(m){var f=v.prototype[m];v.prototype[m]=function(){var p=arguments;return typeof p[0]=="function"||typeof p[1]=="function"?f.apply(this,[arguments[2]]).then(function(g){typeof p[0]=="function"&&p[0].apply(null,[g])},function(g){typeof p[1]=="function"&&p[1].apply(null,[g])}):f.apply(this,arguments)}}),(y=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(m){var f=v.prototype[m];v.prototype[m]=function(){var p=arguments;return typeof p[1]=="function"||typeof p[2]=="function"?f.apply(this,arguments).then(function(){typeof p[1]=="function"&&p[1].apply(null)},function(g){typeof p[2]=="function"&&p[2].apply(null,[g])}):f.apply(this,arguments)}}),["getStats"].forEach(function(m){var f=v.prototype[m];v.prototype[m]=function(){var p=arguments;return typeof p[1]=="function"?f.apply(this,arguments).then(function(){typeof p[1]=="function"&&p[1].apply(null)}):f.apply(this,arguments)}}),v}},{sdp:"YHvh"}],YdKx:[function(o,e,t){"use strict";function n(i){var r=i&&i.navigator,s=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(a){return s(a).catch(function(c){return Promise.reject(function(d){return{name:{PermissionDeniedError:"NotAllowedError"}[d.name]||d.name,message:d.message,constraint:d.constraint,toString:function(){return this.name}}}(c))})}}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=n},{}],P3bV:[function(o,e,t){"use strict";function n(i){"getDisplayMedia"in i.navigator&&i.navigator.mediaDevices&&(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=i.navigator.getDisplayMedia.bind(i.navigator)))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=n},{}],XRic:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimPeerConnection=u,t.shimReplaceTrack=h,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return s.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return a.shimGetDisplayMedia}});var n=l(o("../utils")),i=o("./filtericeservers"),r=c(o("rtcpeerconnection-shim")),s=o("./getusermedia"),a=o("./getdisplaymedia");function c(b){return b&&b.__esModule?b:{default:b}}function d(){if(typeof WeakMap!="function")return null;var b=new WeakMap;return d=function(){return b},b}function l(b){if(b&&b.__esModule)return b;if(b===null||typeof b!="object"&&typeof b!="function")return{default:b};var _=d();if(_&&_.has(b))return _.get(b);var v={},y=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var m in b)if(Object.prototype.hasOwnProperty.call(b,m)){var f=y?Object.getOwnPropertyDescriptor(b,m):null;f&&(f.get||f.set)?Object.defineProperty(v,m,f):v[m]=b[m]}return v.default=b,_&&_.set(b,v),v}function u(b,_){if(b.RTCIceGatherer&&(b.RTCIceCandidate||(b.RTCIceCandidate=function(m){return m}),b.RTCSessionDescription||(b.RTCSessionDescription=function(m){return m}),_.version<15025)){var v=Object.getOwnPropertyDescriptor(b.MediaStreamTrack.prototype,"enabled");Object.defineProperty(b.MediaStreamTrack.prototype,"enabled",{set:function(m){v.set.call(this,m);var f=new Event("enabled");f.enabled=m,this.dispatchEvent(f)}})}!b.RTCRtpSender||"dtmf"in b.RTCRtpSender.prototype||Object.defineProperty(b.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new b.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),b.RTCDtmfSender&&!b.RTCDTMFSender&&(b.RTCDTMFSender=b.RTCDtmfSender);var y=(0,r.default)(b,_.version);b.RTCPeerConnection=function(m){return m&&m.iceServers&&(m.iceServers=(0,i.filterIceServers)(m.iceServers,_.version),n.log("ICE servers after filtering:",m.iceServers)),new y(m)},b.RTCPeerConnection.prototype=y.prototype}function h(b){!b.RTCRtpSender||"replaceTrack"in b.RTCRtpSender.prototype||(b.RTCRtpSender.prototype.replaceTrack=b.RTCRtpSender.prototype.setTrack)}},{"../utils":"iSxC","./filtericeservers":"NZ1C","rtcpeerconnection-shim":"NJ2u","./getusermedia":"YdKx","./getdisplaymedia":"P3bV"}],GzSv:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=a;var n=r(o("../utils"));function i(){if(typeof WeakMap!="function")return null;var c=new WeakMap;return i=function(){return c},c}function r(c){if(c&&c.__esModule)return c;if(c===null||typeof c!="object"&&typeof c!="function")return{default:c};var d=i();if(d&&d.has(c))return d.get(c);var l={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in c)if(Object.prototype.hasOwnProperty.call(c,h)){var b=u?Object.getOwnPropertyDescriptor(c,h):null;b&&(b.get||b.set)?Object.defineProperty(l,h,b):l[h]=c[h]}return l.default=c,d&&d.set(c,l),l}function s(c){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(d){return typeof d}:function(d){return d&&typeof Symbol=="function"&&d.constructor===Symbol&&d!==Symbol.prototype?"symbol":typeof d})(c)}function a(c,d){var l=c&&c.navigator,u=c&&c.MediaStreamTrack;if(l.getUserMedia=function(y,m,f){n.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),l.mediaDevices.getUserMedia(y).then(m,f)},!(d.version>55&&"autoGainControl"in l.mediaDevices.getSupportedConstraints())){var h=function(y,m,f){m in y&&!(f in y)&&(y[f]=y[m],delete y[m])},b=l.mediaDevices.getUserMedia.bind(l.mediaDevices);if(l.mediaDevices.getUserMedia=function(y){return s(y)==="object"&&s(y.audio)==="object"&&(y=JSON.parse(JSON.stringify(y)),h(y.audio,"autoGainControl","mozAutoGainControl"),h(y.audio,"noiseSuppression","mozNoiseSuppression")),b(y)},u&&u.prototype.getSettings){var _=u.prototype.getSettings;u.prototype.getSettings=function(){var y=_.apply(this,arguments);return h(y,"mozAutoGainControl","autoGainControl"),h(y,"mozNoiseSuppression","noiseSuppression"),y}}if(u&&u.prototype.applyConstraints){var v=u.prototype.applyConstraints;u.prototype.applyConstraints=function(y){return this.kind==="audio"&&s(y)==="object"&&(y=JSON.parse(JSON.stringify(y)),h(y,"autoGainControl","mozAutoGainControl"),h(y,"noiseSuppression","mozNoiseSuppression")),v.apply(this,[y])}}}}},{"../utils":"iSxC"}],UuGU:[function(o,e,t){"use strict";function n(i,r){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(s){if(!s||!s.video){var a=new DOMException("getDisplayMedia without video constraints is undefined");return a.name="NotFoundError",a.code=8,Promise.reject(a)}return s.video===!0?s.video={mediaSource:r}:s.video.mediaSource=r,i.navigator.mediaDevices.getUserMedia(s)})}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=n},{}],Fzdr:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimOnTrack=l,t.shimPeerConnection=u,t.shimSenderGetStats=h,t.shimReceiverGetStats=b,t.shimRemoveStream=_,t.shimRTCDataChannel=v,t.shimAddTransceiver=y,t.shimGetParameters=m,t.shimCreateOffer=f,t.shimCreateAnswer=p,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return i.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}});var n=a(o("../utils")),i=o("./getusermedia"),r=o("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var g=new WeakMap;return s=function(){return g},g}function a(g){if(g&&g.__esModule)return g;if(g===null||typeof g!="object"&&typeof g!="function")return{default:g};var E=s();if(E&&E.has(g))return E.get(g);var w={},T=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var S in g)if(Object.prototype.hasOwnProperty.call(g,S)){var k=T?Object.getOwnPropertyDescriptor(g,S):null;k&&(k.get||k.set)?Object.defineProperty(w,S,k):w[S]=g[S]}return w.default=g,E&&E.set(g,w),w}function c(g,E,w){return E in g?Object.defineProperty(g,E,{value:w,enumerable:!0,configurable:!0,writable:!0}):g[E]=w,g}function d(g){return(d=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(E){return typeof E}:function(E){return E&&typeof Symbol=="function"&&E.constructor===Symbol&&E!==Symbol.prototype?"symbol":typeof E})(g)}function l(g){d(g)==="object"&&g.RTCTrackEvent&&"receiver"in g.RTCTrackEvent.prototype&&!("transceiver"in g.RTCTrackEvent.prototype)&&Object.defineProperty(g.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function u(g,E){if(d(g)==="object"&&(g.RTCPeerConnection||g.mozRTCPeerConnection)){!g.RTCPeerConnection&&g.mozRTCPeerConnection&&(g.RTCPeerConnection=g.mozRTCPeerConnection),E.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(S){var k=g.RTCPeerConnection.prototype[S],D=c({},S,function(){return arguments[0]=new(S==="addIceCandidate"?g.RTCIceCandidate:g.RTCSessionDescription)(arguments[0]),k.apply(this,arguments)});g.RTCPeerConnection.prototype[S]=D[S]});var w={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},T=g.RTCPeerConnection.prototype.getStats;g.RTCPeerConnection.prototype.getStats=function(){var[S,k,D]=arguments;return T.apply(this,[S||null]).then(function(P){if(E.version<53&&!k)try{P.forEach(function(H){H.type=w[H.type]||H.type})}catch(H){if(H.name!=="TypeError")throw H;P.forEach(function(F,N){P.set(N,Object.assign({},F,{type:w[F.type]||F.type}))})}return P}).then(k,D)}}}function h(g){if(d(g)==="object"&&g.RTCPeerConnection&&g.RTCRtpSender&&!(g.RTCRtpSender&&"getStats"in g.RTCRtpSender.prototype)){var E=g.RTCPeerConnection.prototype.getSenders;E&&(g.RTCPeerConnection.prototype.getSenders=function(){var T=this,S=E.apply(this,[]);return S.forEach(function(k){return k._pc=T}),S});var w=g.RTCPeerConnection.prototype.addTrack;w&&(g.RTCPeerConnection.prototype.addTrack=function(){var T=w.apply(this,arguments);return T._pc=this,T}),g.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function b(g){if(d(g)==="object"&&g.RTCPeerConnection&&g.RTCRtpSender&&!(g.RTCRtpSender&&"getStats"in g.RTCRtpReceiver.prototype)){var E=g.RTCPeerConnection.prototype.getReceivers;E&&(g.RTCPeerConnection.prototype.getReceivers=function(){var w=this,T=E.apply(this,[]);return T.forEach(function(S){return S._pc=w}),T}),n.wrapPeerConnectionEvent(g,"track",function(w){return w.receiver._pc=w.srcElement,w}),g.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function _(g){!g.RTCPeerConnection||"removeStream"in g.RTCPeerConnection.prototype||(g.RTCPeerConnection.prototype.removeStream=function(E){var w=this;n.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(T){T.track&&E.getTracks().includes(T.track)&&w.removeTrack(T)})})}function v(g){g.DataChannel&&!g.RTCDataChannel&&(g.RTCDataChannel=g.DataChannel)}function y(g){if(d(g)==="object"&&g.RTCPeerConnection){var E=g.RTCPeerConnection.prototype.addTransceiver;E&&(g.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var w=arguments[1],T=w&&"sendEncodings"in w;T&&w.sendEncodings.forEach(function(P){if("rid"in P&&!/^[a-z0-9]{0,16}$/i.test(P.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in P&&!(parseFloat(P.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in P&&!(parseFloat(P.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var S=E.apply(this,arguments);if(T){var{sender:k}=S,D=k.getParameters();"encodings"in D&&(D.encodings.length!==1||Object.keys(D.encodings[0]).length!==0)||(D.encodings=w.sendEncodings,k.sendEncodings=w.sendEncodings,this.setParametersPromises.push(k.setParameters(D).then(function(){delete k.sendEncodings}).catch(function(){delete k.sendEncodings})))}return S})}}function m(g){if(d(g)==="object"&&g.RTCRtpSender){var E=g.RTCRtpSender.prototype.getParameters;E&&(g.RTCRtpSender.prototype.getParameters=function(){var w=E.apply(this,arguments);return"encodings"in w||(w.encodings=[].concat(this.sendEncodings||[{}])),w})}}function f(g){if(d(g)==="object"&&g.RTCPeerConnection){var E=g.RTCPeerConnection.prototype.createOffer;g.RTCPeerConnection.prototype.createOffer=function(){var w=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return E.apply(T,w)}).finally(function(){T.setParametersPromises=[]}):E.apply(this,arguments)}}}function p(g){if(d(g)==="object"&&g.RTCPeerConnection){var E=g.RTCPeerConnection.prototype.createAnswer;g.RTCPeerConnection.prototype.createAnswer=function(){var w=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return E.apply(T,w)}).finally(function(){T.setParametersPromises=[]}):E.apply(this,arguments)}}}},{"../utils":"iSxC","./getusermedia":"GzSv","./getdisplaymedia":"UuGU"}],t1lL:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimLocalStreamsAPI=a,t.shimRemoteStreamsAPI=c,t.shimCallbacksAPI=d,t.shimGetUserMedia=l,t.shimConstraints=u,t.shimRTCIceServerUrls=h,t.shimTrackEventTransceiver=b,t.shimCreateOfferLegacy=_,t.shimAudioContext=v;var n=r(o("../utils"));function i(){if(typeof WeakMap!="function")return null;var y=new WeakMap;return i=function(){return y},y}function r(y){if(y&&y.__esModule)return y;if(y===null||typeof y!="object"&&typeof y!="function")return{default:y};var m=i();if(m&&m.has(y))return m.get(y);var f={},p=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in y)if(Object.prototype.hasOwnProperty.call(y,g)){var E=p?Object.getOwnPropertyDescriptor(y,g):null;E&&(E.get||E.set)?Object.defineProperty(f,g,E):f[g]=y[g]}return f.default=y,m&&m.set(y,f),f}function s(y){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(m){return typeof m}:function(m){return m&&typeof Symbol=="function"&&m.constructor===Symbol&&m!==Symbol.prototype?"symbol":typeof m})(y)}function a(y){if(s(y)==="object"&&y.RTCPeerConnection){if("getLocalStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in y.RTCPeerConnection.prototype)){var m=y.RTCPeerConnection.prototype.addTrack;y.RTCPeerConnection.prototype.addStream=function(f){var p=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(f)||this._localStreams.push(f),f.getAudioTracks().forEach(function(g){return m.call(p,g,f)}),f.getVideoTracks().forEach(function(g){return m.call(p,g,f)})},y.RTCPeerConnection.prototype.addTrack=function(f){for(var p=this,g=arguments.length,E=new Array(g>1?g-1:0),w=1;w<g;w++)E[w-1]=arguments[w];return E&&E.forEach(function(T){p._localStreams?p._localStreams.includes(T)||p._localStreams.push(T):p._localStreams=[T]}),m.apply(this,arguments)}}"removeStream"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.removeStream=function(f){var p=this;this._localStreams||(this._localStreams=[]);var g=this._localStreams.indexOf(f);if(g!==-1){this._localStreams.splice(g,1);var E=f.getTracks();this.getSenders().forEach(function(w){E.includes(w.track)&&p.removeTrack(w)})}})}}function c(y){if(s(y)==="object"&&y.RTCPeerConnection&&("getRemoteStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in y.RTCPeerConnection.prototype))){Object.defineProperty(y.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(f){var p=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=f),this.addEventListener("track",this._onaddstreampoly=function(g){g.streams.forEach(function(E){if(p._remoteStreams||(p._remoteStreams=[]),!p._remoteStreams.includes(E)){p._remoteStreams.push(E);var w=new Event("addstream");w.stream=E,p.dispatchEvent(w)}})})}});var m=y.RTCPeerConnection.prototype.setRemoteDescription;y.RTCPeerConnection.prototype.setRemoteDescription=function(){var f=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(p){p.streams.forEach(function(g){if(f._remoteStreams||(f._remoteStreams=[]),!(f._remoteStreams.indexOf(g)>=0)){f._remoteStreams.push(g);var E=new Event("addstream");E.stream=g,f.dispatchEvent(E)}})}),m.apply(f,arguments)}}}function d(y){if(s(y)==="object"&&y.RTCPeerConnection){var m=y.RTCPeerConnection.prototype,f=m.createOffer,p=m.createAnswer,g=m.setLocalDescription,E=m.setRemoteDescription,w=m.addIceCandidate;m.createOffer=function(S,k){var D=arguments.length>=2?arguments[2]:arguments[0],P=f.apply(this,[D]);return k?(P.then(S,k),Promise.resolve()):P},m.createAnswer=function(S,k){var D=arguments.length>=2?arguments[2]:arguments[0],P=p.apply(this,[D]);return k?(P.then(S,k),Promise.resolve()):P};var T=function(S,k,D){var P=g.apply(this,[S]);return D?(P.then(k,D),Promise.resolve()):P};m.setLocalDescription=T,T=function(S,k,D){var P=E.apply(this,[S]);return D?(P.then(k,D),Promise.resolve()):P},m.setRemoteDescription=T,T=function(S,k,D){var P=w.apply(this,[S]);return D?(P.then(k,D),Promise.resolve()):P},m.addIceCandidate=T}}function l(y){var m=y&&y.navigator;if(m.mediaDevices&&m.mediaDevices.getUserMedia){var f=m.mediaDevices,p=f.getUserMedia.bind(f);m.mediaDevices.getUserMedia=function(g){return p(u(g))}}!m.getUserMedia&&m.mediaDevices&&m.mediaDevices.getUserMedia&&(m.getUserMedia=function(g,E,w){m.mediaDevices.getUserMedia(g).then(E,w)}.bind(m))}function u(y){return y&&y.video!==void 0?Object.assign({},y,{video:n.compactObject(y.video)}):y}function h(y){if(y.RTCPeerConnection){var m=y.RTCPeerConnection;y.RTCPeerConnection=function(f,p){if(f&&f.iceServers){for(var g=[],E=0;E<f.iceServers.length;E++){var w=f.iceServers[E];!w.hasOwnProperty("urls")&&w.hasOwnProperty("url")?(n.deprecated("RTCIceServer.url","RTCIceServer.urls"),(w=JSON.parse(JSON.stringify(w))).urls=w.url,delete w.url,g.push(w)):g.push(f.iceServers[E])}f.iceServers=g}return new m(f,p)},y.RTCPeerConnection.prototype=m.prototype,"generateCertificate"in m&&Object.defineProperty(y.RTCPeerConnection,"generateCertificate",{get:function(){return m.generateCertificate}})}}function b(y){s(y)==="object"&&y.RTCTrackEvent&&"receiver"in y.RTCTrackEvent.prototype&&!("transceiver"in y.RTCTrackEvent.prototype)&&Object.defineProperty(y.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function _(y){var m=y.RTCPeerConnection.prototype.createOffer;y.RTCPeerConnection.prototype.createOffer=function(f){if(f){f.offerToReceiveAudio!==void 0&&(f.offerToReceiveAudio=!!f.offerToReceiveAudio);var p=this.getTransceivers().find(function(E){return E.receiver.track.kind==="audio"});f.offerToReceiveAudio===!1&&p?p.direction==="sendrecv"?p.setDirection?p.setDirection("sendonly"):p.direction="sendonly":p.direction==="recvonly"&&(p.setDirection?p.setDirection("inactive"):p.direction="inactive"):f.offerToReceiveAudio!==!0||p||this.addTransceiver("audio"),f.offerToReceiveVideo!==void 0&&(f.offerToReceiveVideo=!!f.offerToReceiveVideo);var g=this.getTransceivers().find(function(E){return E.receiver.track.kind==="video"});f.offerToReceiveVideo===!1&&g?g.direction==="sendrecv"?g.setDirection?g.setDirection("sendonly"):g.direction="sendonly":g.direction==="recvonly"&&(g.setDirection?g.setDirection("inactive"):g.direction="inactive"):f.offerToReceiveVideo!==!0||g||this.addTransceiver("video")}return m.apply(this,arguments)}}function v(y){s(y)!=="object"||y.AudioContext||(y.AudioContext=y.webkitAudioContext)}},{"../utils":"iSxC"}],GOQK:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimRTCIceCandidate=d,t.shimMaxMessageSize=l,t.shimSendThrowTypeError=u,t.shimConnectionState=h,t.removeExtmapAllowMixed=b,t.shimAddIceCandidateNullOrEmpty=_;var n=a(o("sdp")),i=s(o("./utils"));function r(){if(typeof WeakMap!="function")return null;var v=new WeakMap;return r=function(){return v},v}function s(v){if(v&&v.__esModule)return v;if(v===null||typeof v!="object"&&typeof v!="function")return{default:v};var y=r();if(y&&y.has(v))return y.get(v);var m={},f=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var p in v)if(Object.prototype.hasOwnProperty.call(v,p)){var g=f?Object.getOwnPropertyDescriptor(v,p):null;g&&(g.get||g.set)?Object.defineProperty(m,p,g):m[p]=v[p]}return m.default=v,y&&y.set(v,m),m}function a(v){return v&&v.__esModule?v:{default:v}}function c(v){return(c=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(y){return typeof y}:function(y){return y&&typeof Symbol=="function"&&y.constructor===Symbol&&y!==Symbol.prototype?"symbol":typeof y})(v)}function d(v){if(v.RTCIceCandidate&&!(v.RTCIceCandidate&&"foundation"in v.RTCIceCandidate.prototype)){var y=v.RTCIceCandidate;v.RTCIceCandidate=function(m){if(c(m)==="object"&&m.candidate&&m.candidate.indexOf("a=")===0&&((m=JSON.parse(JSON.stringify(m))).candidate=m.candidate.substr(2)),m.candidate&&m.candidate.length){var f=new y(m),p=n.default.parseCandidate(m.candidate),g=Object.assign(f,p);return g.toJSON=function(){return{candidate:g.candidate,sdpMid:g.sdpMid,sdpMLineIndex:g.sdpMLineIndex,usernameFragment:g.usernameFragment}},g}return new y(m)},v.RTCIceCandidate.prototype=y.prototype,i.wrapPeerConnectionEvent(v,"icecandidate",function(m){return m.candidate&&Object.defineProperty(m,"candidate",{value:new v.RTCIceCandidate(m.candidate),writable:"false"}),m})}}function l(v,y){if(v.RTCPeerConnection){"sctp"in v.RTCPeerConnection.prototype||Object.defineProperty(v.RTCPeerConnection.prototype,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp}});var m=v.RTCPeerConnection.prototype.setRemoteDescription;v.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,y.browser==="chrome"&&y.version>=76){var{sdpSemantics:f}=this.getConfiguration();f==="plan-b"&&Object.defineProperty(this,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(D){if(!D||!D.sdp)return!1;var P=n.default.splitSections(D.sdp);return P.shift(),P.some(function(H){var F=n.default.parseMLine(H);return F&&F.kind==="application"&&F.protocol.indexOf("SCTP")!==-1})}(arguments[0])){var p,g=function(D){var P=D.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(P===null||P.length<2)return-1;var H=parseInt(P[1],10);return H!=H?-1:H}(arguments[0]),E=(S=g,k=65536,y.browser==="firefox"&&(k=y.version<57?S===-1?16384:2147483637:y.version<60?y.version===57?65535:65536:2147483637),k),w=function(D,P){var H=65536;y.browser==="firefox"&&y.version===57&&(H=65535);var F=n.default.matchPrefix(D.sdp,"a=max-message-size:");return F.length>0?H=parseInt(F[0].substr(19),10):y.browser==="firefox"&&P!==-1&&(H=2147483637),H}(arguments[0],g);p=E===0&&w===0?Number.POSITIVE_INFINITY:E===0||w===0?Math.max(E,w):Math.min(E,w);var T={};Object.defineProperty(T,"maxMessageSize",{get:function(){return p}}),this._sctp=T}var S,k;return m.apply(this,arguments)}}}function u(v){if(v.RTCPeerConnection&&"createDataChannel"in v.RTCPeerConnection.prototype){var y=v.RTCPeerConnection.prototype.createDataChannel;v.RTCPeerConnection.prototype.createDataChannel=function(){var f=y.apply(this,arguments);return m(f,this),f},i.wrapPeerConnectionEvent(v,"datachannel",function(f){return m(f.channel,f.target),f})}function m(f,p){var g=f.send;f.send=function(){var E=arguments[0],w=E.length||E.size||E.byteLength;if(f.readyState==="open"&&p.sctp&&w>p.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+p.sctp.maxMessageSize+" bytes)");return g.apply(f,arguments)}}}function h(v){if(v.RTCPeerConnection&&!("connectionState"in v.RTCPeerConnection.prototype)){var y=v.RTCPeerConnection.prototype;Object.defineProperty(y,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(y,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(m){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),m&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=m)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(m){var f=y[m];y[m]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(p){var g=p.target;if(g._lastConnectionState!==g.connectionState){g._lastConnectionState=g.connectionState;var E=new Event("connectionstatechange",p);g.dispatchEvent(E)}return p},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),f.apply(this,arguments)}})}}function b(v,y){if(v.RTCPeerConnection&&!(y.browser==="chrome"&&y.version>=71||y.browser==="safari"&&y.version>=605)){var m=v.RTCPeerConnection.prototype.setRemoteDescription;v.RTCPeerConnection.prototype.setRemoteDescription=function(f){if(f&&f.sdp&&f.sdp.indexOf(`
70
+ a=extmap-allow-mixed`)!==-1){var p=f.sdp.split(`
71
+ `).filter(function(g){return g.trim()!=="a=extmap-allow-mixed"}).join(`
72
+ `);v.RTCSessionDescription&&f instanceof v.RTCSessionDescription?arguments[0]=new v.RTCSessionDescription({type:f.type,sdp:p}):f.sdp=p}return m.apply(this,arguments)}}}function _(v,y){if(v.RTCPeerConnection&&v.RTCPeerConnection.prototype){var m=v.RTCPeerConnection.prototype.addIceCandidate;m&&m.length!==0&&(v.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(y.browser==="chrome"&&y.version<78||y.browser==="firefox"&&y.version<68||y.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():m.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}},{sdp:"YHvh","./utils":"iSxC"}],KtlG:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.adapterFactory=u;var n=l(o("./utils")),i=l(o("./chrome/chrome_shim")),r=l(o("./edge/edge_shim")),s=l(o("./firefox/firefox_shim")),a=l(o("./safari/safari_shim")),c=l(o("./common_shim"));function d(){if(typeof WeakMap!="function")return null;var h=new WeakMap;return d=function(){return h},h}function l(h){if(h&&h.__esModule)return h;if(h===null||typeof h!="object"&&typeof h!="function")return{default:h};var b=d();if(b&&b.has(h))return b.get(h);var _={},v=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var y in h)if(Object.prototype.hasOwnProperty.call(h,y)){var m=v?Object.getOwnPropertyDescriptor(h,y):null;m&&(m.get||m.set)?Object.defineProperty(_,y,m):_[y]=h[y]}return _.default=h,b&&b.set(h,_),_}function u(){var{window:h}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},_=n.log,v=n.detectBrowser(h),y={browserDetails:v,commonShim:c,extractVersion:n.extractVersion,disableLog:n.disableLog,disableWarnings:n.disableWarnings};switch(v.browser){case"chrome":if(!i||!i.shimPeerConnection||!b.shimChrome)return _("Chrome shim is not included in this adapter release."),y;if(v.version===null)return _("Chrome shim can not determine version, not shimming."),y;_("adapter.js shimming chrome."),y.browserShim=i,c.shimAddIceCandidateNullOrEmpty(h,v),i.shimGetUserMedia(h,v),i.shimMediaStream(h,v),i.shimPeerConnection(h,v),i.shimOnTrack(h,v),i.shimAddTrackRemoveTrack(h,v),i.shimGetSendersWithDtmf(h,v),i.shimGetStats(h,v),i.shimSenderReceiverGetStats(h,v),i.fixNegotiationNeeded(h,v),c.shimRTCIceCandidate(h,v),c.shimConnectionState(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v),c.removeExtmapAllowMixed(h,v);break;case"firefox":if(!s||!s.shimPeerConnection||!b.shimFirefox)return _("Firefox shim is not included in this adapter release."),y;_("adapter.js shimming firefox."),y.browserShim=s,c.shimAddIceCandidateNullOrEmpty(h,v),s.shimGetUserMedia(h,v),s.shimPeerConnection(h,v),s.shimOnTrack(h,v),s.shimRemoveStream(h,v),s.shimSenderGetStats(h,v),s.shimReceiverGetStats(h,v),s.shimRTCDataChannel(h,v),s.shimAddTransceiver(h,v),s.shimGetParameters(h,v),s.shimCreateOffer(h,v),s.shimCreateAnswer(h,v),c.shimRTCIceCandidate(h,v),c.shimConnectionState(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v);break;case"edge":if(!r||!r.shimPeerConnection||!b.shimEdge)return _("MS edge shim is not included in this adapter release."),y;_("adapter.js shimming edge."),y.browserShim=r,r.shimGetUserMedia(h,v),r.shimGetDisplayMedia(h,v),r.shimPeerConnection(h,v),r.shimReplaceTrack(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v);break;case"safari":if(!a||!b.shimSafari)return _("Safari shim is not included in this adapter release."),y;_("adapter.js shimming safari."),y.browserShim=a,c.shimAddIceCandidateNullOrEmpty(h,v),a.shimRTCIceServerUrls(h,v),a.shimCreateOfferLegacy(h,v),a.shimCallbacksAPI(h,v),a.shimLocalStreamsAPI(h,v),a.shimRemoteStreamsAPI(h,v),a.shimTrackEventTransceiver(h,v),a.shimGetUserMedia(h,v),a.shimAudioContext(h,v),c.shimRTCIceCandidate(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v),c.removeExtmapAllowMixed(h,v);break;default:_("Unsupported browser!")}return y}},{"./utils":"iSxC","./chrome/chrome_shim":"uI5X","./edge/edge_shim":"XRic","./firefox/firefox_shim":"Fzdr","./safari/safari_shim":"t1lL","./common_shim":"GOQK"}],tI1X:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=o("./adapter_factory.js"),i=(0,n.adapterFactory)({window:typeof window>"u"?void 0:window}),r=i;t.default=r},{"./adapter_factory.js":"KtlG"}],sXtV:[function(o,e,t){"use strict";var n=this&&this.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(t,"__esModule",{value:!0}),t.webRTCAdapter=void 0;var i=n(o("webrtc-adapter"));t.webRTCAdapter=i.default},{"webrtc-adapter":"tI1X"}],I31f:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Supports=void 0;var n=o("./adapter");t.Supports=new(function(){function i(){this.isIOS=["iPad","iPhone","iPod"].includes(navigator.platform),this.supportedBrowsers=["firefox","chrome","safari"],this.minFirefoxVersion=59,this.minChromeVersion=72,this.minSafariVersion=605}return i.prototype.isWebRTCSupported=function(){return typeof RTCPeerConnection<"u"},i.prototype.isBrowserSupported=function(){var r=this.getBrowser(),s=this.getVersion();return!!this.supportedBrowsers.includes(r)&&(r==="chrome"?s>=this.minChromeVersion:r==="firefox"?s>=this.minFirefoxVersion:r==="safari"&&!this.isIOS&&s>=this.minSafariVersion)},i.prototype.getBrowser=function(){return n.webRTCAdapter.browserDetails.browser},i.prototype.getVersion=function(){return n.webRTCAdapter.browserDetails.version||0},i.prototype.isUnifiedPlanSupported=function(){var r,s=this.getBrowser(),a=n.webRTCAdapter.browserDetails.version||0;if(s==="chrome"&&a<72)return!1;if(s==="firefox"&&a>=59)return!0;if(!(window.RTCRtpTransceiver&&"currentDirection"in RTCRtpTransceiver.prototype))return!1;var c=!1;try{(r=new RTCPeerConnection).addTransceiver("audio"),c=!0}catch{}finally{r&&r.close()}return c},i.prototype.toString=function(){return`Supports:
73
73
  browser:`+this.getBrowser()+`
74
74
  version:`+this.getVersion()+`
75
75
  isIOS:`+this.isIOS+`
76
76
  isWebRTCSupported:`+this.isWebRTCSupported()+`
77
77
  isBrowserSupported:`+this.isBrowserSupported()+`
78
- isUnifiedPlanSupported:`+this.isUnifiedPlanSupported()},n}())},{"./adapter":"sXtV"}],BHXf:[function(a,e,t){"use strict";var i=this&&this.__createBinding||(Object.create?function(d,l,h,u){u===void 0&&(u=h),Object.defineProperty(d,u,{enumerable:!0,get:function(){return l[h]}})}:function(d,l,h,u){u===void 0&&(u=h),d[u]=l[h]}),n=this&&this.__setModuleDefault||(Object.create?function(d,l){Object.defineProperty(d,"default",{enumerable:!0,value:l})}:function(d,l){d.default=l}),r=this&&this.__importStar||function(d){if(d&&d.__esModule)return d;var l={};if(d!=null)for(var h in d)h!=="default"&&Object.prototype.hasOwnProperty.call(d,h)&&i(l,d,h);return n(l,d),l};Object.defineProperty(t,"__esModule",{value:!0}),t.util=void 0;var o=r(a("peerjs-js-binarypack")),s=a("./supports"),c={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"turn:0.peerjs.com:3478",username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"};t.util=new(function(){function d(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=c,this.browser=s.Supports.getBrowser(),this.browserVersion=s.Supports.getVersion(),this.supports=function(){var l,h={browser:s.Supports.isBrowserSupported(),webRTC:s.Supports.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!h.webRTC)return h;try{l=new RTCPeerConnection(c),h.audioVideo=!0;var u=void 0;try{u=l.createDataChannel("_PEERJSTEST",{ordered:!0}),h.data=!0,h.reliable=!!u.ordered;try{u.binaryType="blob",h.binaryBlob=!s.Supports.isIOS}catch{}}catch{}finally{u&&u.close()}}catch{}finally{l&&l.close()}return h}(),this.pack=o.pack,this.unpack=o.unpack,this._dataCount=1}return d.prototype.noop=function(){},d.prototype.validateId=function(l){return!l||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(l)},d.prototype.chunk=function(l){for(var h=[],u=l.size,f=Math.ceil(u/t.util.chunkedMTU),x=0,b=0;b<u;){var y=Math.min(u,b+t.util.chunkedMTU),g=l.slice(b,y),p={__peerData:this._dataCount,n:x,data:g,total:f};h.push(p),b=y,x++}return this._dataCount++,h},d.prototype.blobToArrayBuffer=function(l,h){var u=new FileReader;return u.onload=function(f){f.target&&h(f.target.result)},u.readAsArrayBuffer(l),u},d.prototype.binaryStringToArrayBuffer=function(l){for(var h=new Uint8Array(l.length),u=0;u<l.length;u++)h[u]=255&l.charCodeAt(u);return h.buffer},d.prototype.randomToken=function(){return Math.random().toString(36).substr(2)},d.prototype.isSecure=function(){return location.protocol==="https:"},d}())},{"peerjs-js-binarypack":"kdPp","./supports":"I31f"}],JJlS:[function(a,e,t){"use strict";var i=Object.prototype.hasOwnProperty,n="~";function r(){}function o(l,h,u){this.fn=l,this.context=h,this.once=u||!1}function s(l,h,u,f,x){if(typeof u!="function")throw new TypeError("The listener must be a function");var b=new o(u,f||l,x),y=n?n+h:h;return l._events[y]?l._events[y].fn?l._events[y]=[l._events[y],b]:l._events[y].push(b):(l._events[y]=b,l._eventsCount++),l}function c(l,h){--l._eventsCount==0?l._events=new r:delete l._events[h]}function d(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1)),d.prototype.eventNames=function(){var l,h,u=[];if(this._eventsCount===0)return u;for(h in l=this._events)i.call(l,h)&&u.push(n?h.slice(1):h);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},d.prototype.listeners=function(l){var h=n?n+l:l,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,x=u.length,b=new Array(x);f<x;f++)b[f]=u[f].fn;return b},d.prototype.listenerCount=function(l){var h=n?n+l:l,u=this._events[h];return u?u.fn?1:u.length:0},d.prototype.emit=function(l,h,u,f,x,b){var y=n?n+l:l;if(!this._events[y])return!1;var g,p,m=this._events[y],v=arguments.length;if(m.fn){switch(m.once&&this.removeListener(l,m.fn,void 0,!0),v){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,h),!0;case 3:return m.fn.call(m.context,h,u),!0;case 4:return m.fn.call(m.context,h,u,f),!0;case 5:return m.fn.call(m.context,h,u,f,x),!0;case 6:return m.fn.call(m.context,h,u,f,x,b),!0}for(p=1,g=new Array(v-1);p<v;p++)g[p-1]=arguments[p];m.fn.apply(m.context,g)}else{var w,E=m.length;for(p=0;p<E;p++)switch(m[p].once&&this.removeListener(l,m[p].fn,void 0,!0),v){case 1:m[p].fn.call(m[p].context);break;case 2:m[p].fn.call(m[p].context,h);break;case 3:m[p].fn.call(m[p].context,h,u);break;case 4:m[p].fn.call(m[p].context,h,u,f);break;default:if(!g)for(w=1,g=new Array(v-1);w<v;w++)g[w-1]=arguments[w];m[p].fn.apply(m[p].context,g)}}return!0},d.prototype.on=function(l,h,u){return s(this,l,h,u,!1)},d.prototype.once=function(l,h,u){return s(this,l,h,u,!0)},d.prototype.removeListener=function(l,h,u,f){var x=n?n+l:l;if(!this._events[x])return this;if(!h)return c(this,x),this;var b=this._events[x];if(b.fn)b.fn!==h||f&&!b.once||u&&b.context!==u||c(this,x);else{for(var y=0,g=[],p=b.length;y<p;y++)(b[y].fn!==h||f&&!b[y].once||u&&b[y].context!==u)&&g.push(b[y]);g.length?this._events[x]=g.length===1?g[0]:g:c(this,x)}return this},d.prototype.removeAllListeners=function(l){var h;return l?(h=n?n+l:l,this._events[h]&&c(this,h)):(this._events=new r,this._eventsCount=0),this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prefixed=n,d.EventEmitter=d,typeof e<"u"&&(e.exports=d)},{}],WOs9:[function(a,e,t){"use strict";var i=this&&this.__read||function(c,d){var l=typeof Symbol=="function"&&c[Symbol.iterator];if(!l)return c;var h,u,f=l.call(c),x=[];try{for(;(d===void 0||d-- >0)&&!(h=f.next()).done;)x.push(h.value)}catch(b){u={error:b}}finally{try{h&&!h.done&&(l=f.return)&&l.call(f)}finally{if(u)throw u.error}}return x},n=this&&this.__spreadArray||function(c,d){for(var l=0,h=d.length,u=c.length;l<h;l++,u++)c[u]=d[l];return c};Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0;var r,o="PeerJS: ";(function(c){c[c.Disabled=0]="Disabled",c[c.Errors=1]="Errors",c[c.Warnings=2]="Warnings",c[c.All=3]="All"})(r=t.LogLevel||(t.LogLevel={}));var s=function(){function c(){this._logLevel=r.Disabled}return Object.defineProperty(c.prototype,"logLevel",{get:function(){return this._logLevel},set:function(d){this._logLevel=d},enumerable:!1,configurable:!0}),c.prototype.log=function(){for(var d=[],l=0;l<arguments.length;l++)d[l]=arguments[l];this._logLevel>=r.All&&this._print.apply(this,n([r.All],i(d)))},c.prototype.warn=function(){for(var d=[],l=0;l<arguments.length;l++)d[l]=arguments[l];this._logLevel>=r.Warnings&&this._print.apply(this,n([r.Warnings],i(d)))},c.prototype.error=function(){for(var d=[],l=0;l<arguments.length;l++)d[l]=arguments[l];this._logLevel>=r.Errors&&this._print.apply(this,n([r.Errors],i(d)))},c.prototype.setLogFunction=function(d){this._print=d},c.prototype._print=function(d){for(var l=[],h=1;h<arguments.length;h++)l[h-1]=arguments[h];var u=n([o],i(l));for(var f in u)u[f]instanceof Error&&(u[f]="("+u[f].name+") "+u[f].message);d>=r.All?console.log.apply(console,n([],i(u))):d>=r.Warnings?console.warn.apply(console,n(["WARNING"],i(u))):d>=r.Errors&&console.error.apply(console,n(["ERROR"],i(u)))},c}();t.default=new s},{}],ZRYf:[function(a,e,t){"use strict";var i,n,r,o,s,c,d;Object.defineProperty(t,"__esModule",{value:!0}),t.ServerMessageType=t.SocketEventType=t.SerializationType=t.PeerErrorType=t.PeerEventType=t.ConnectionType=t.ConnectionEventType=void 0,function(l){l.Open="open",l.Stream="stream",l.Data="data",l.Close="close",l.Error="error",l.IceStateChanged="iceStateChanged"}(i=t.ConnectionEventType||(t.ConnectionEventType={})),function(l){l.Data="data",l.Media="media"}(n=t.ConnectionType||(t.ConnectionType={})),function(l){l.Open="open",l.Close="close",l.Connection="connection",l.Call="call",l.Disconnected="disconnected",l.Error="error"}(r=t.PeerEventType||(t.PeerEventType={})),function(l){l.BrowserIncompatible="browser-incompatible",l.Disconnected="disconnected",l.InvalidID="invalid-id",l.InvalidKey="invalid-key",l.Network="network",l.PeerUnavailable="peer-unavailable",l.SslUnavailable="ssl-unavailable",l.ServerError="server-error",l.SocketError="socket-error",l.SocketClosed="socket-closed",l.UnavailableID="unavailable-id",l.WebRTC="webrtc"}(o=t.PeerErrorType||(t.PeerErrorType={})),function(l){l.Binary="binary",l.BinaryUTF8="binary-utf8",l.JSON="json"}(s=t.SerializationType||(t.SerializationType={})),function(l){l.Message="message",l.Disconnected="disconnected",l.Error="error",l.Close="close"}(c=t.SocketEventType||(t.SocketEventType={})),function(l){l.Heartbeat="HEARTBEAT",l.Candidate="CANDIDATE",l.Offer="OFFER",l.Answer="ANSWER",l.Open="OPEN",l.Error="ERROR",l.IdTaken="ID-TAKEN",l.InvalidKey="INVALID-KEY",l.Leave="LEAVE",l.Expire="EXPIRE"}(d=t.ServerMessageType||(t.ServerMessageType={}))},{}],wJlv:[function(a,e,t){"use strict";var i=this&&this.__extends||function(){var u=function(f,x){return(u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,y){b.__proto__=y}||function(b,y){for(var g in y)Object.prototype.hasOwnProperty.call(y,g)&&(b[g]=y[g])})(f,x)};return function(f,x){if(typeof x!="function"&&x!==null)throw new TypeError("Class extends value "+String(x)+" is not a constructor or null");function b(){this.constructor=f}u(f,x),f.prototype=x===null?Object.create(x):(b.prototype=x.prototype,new b)}}(),n=this&&this.__read||function(u,f){var x=typeof Symbol=="function"&&u[Symbol.iterator];if(!x)return u;var b,y,g=x.call(u),p=[];try{for(;(f===void 0||f-- >0)&&!(b=g.next()).done;)p.push(b.value)}catch(m){y={error:m}}finally{try{b&&!b.done&&(x=g.return)&&x.call(g)}finally{if(y)throw y.error}}return p},r=this&&this.__spreadArray||function(u,f){for(var x=0,b=f.length,y=u.length;x<b;x++,y++)u[y]=f[x];return u},o=this&&this.__values||function(u){var f=typeof Symbol=="function"&&Symbol.iterator,x=f&&u[f],b=0;if(x)return x.call(u);if(u&&typeof u.length=="number")return{next:function(){return u&&b>=u.length&&(u=void 0),{value:u&&u[b++],done:!u}}};throw new TypeError(f?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;var c=a("eventemitter3"),d=s(a("./logger")),l=a("./enums"),h=function(u){function f(x,b,y,g,p,m){m===void 0&&(m=5e3);var v=u.call(this)||this;v.pingInterval=m,v._disconnected=!0,v._messagesQueue=[];var w=x?"wss://":"ws://";return v._baseUrl=w+b+":"+y+g+"peerjs?key="+p,v}return i(f,u),f.prototype.start=function(x,b){var y=this;this._id=x;var g=this._baseUrl+"&id="+x+"&token="+b;!this._socket&&this._disconnected&&(this._socket=new WebSocket(g),this._disconnected=!1,this._socket.onmessage=function(p){var m;try{m=JSON.parse(p.data),d.default.log("Server message received:",m)}catch{return void d.default.log("Invalid server message",p.data)}y.emit(l.SocketEventType.Message,m)},this._socket.onclose=function(p){y._disconnected||(d.default.log("Socket closed.",p),y._cleanup(),y._disconnected=!0,y.emit(l.SocketEventType.Disconnected))},this._socket.onopen=function(){y._disconnected||(y._sendQueuedMessages(),d.default.log("Socket open"),y._scheduleHeartbeat())})},f.prototype._scheduleHeartbeat=function(){var x=this;this._wsPingTimer=setTimeout(function(){x._sendHeartbeat()},this.pingInterval)},f.prototype._sendHeartbeat=function(){if(this._wsOpen()){var x=JSON.stringify({type:l.ServerMessageType.Heartbeat});this._socket.send(x),this._scheduleHeartbeat()}else d.default.log("Cannot send heartbeat, because socket closed")},f.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},f.prototype._sendQueuedMessages=function(){var x,b,y=r([],n(this._messagesQueue));this._messagesQueue=[];try{for(var g=o(y),p=g.next();!p.done;p=g.next()){var m=p.value;this.send(m)}}catch(v){x={error:v}}finally{try{p&&!p.done&&(b=g.return)&&b.call(g)}finally{if(x)throw x.error}}},f.prototype.send=function(x){if(!this._disconnected)if(this._id)if(x.type){if(this._wsOpen()){var b=JSON.stringify(x);this._socket.send(b)}}else this.emit(l.SocketEventType.Error,"Invalid message");else this._messagesQueue.push(x)},f.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},f.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},f}(c.EventEmitter);t.Socket=h},{eventemitter3:"JJlS","./logger":"WOs9","./enums":"ZRYf"}],HCdX:[function(a,e,t){"use strict";var i=this&&this.__assign||function(){return(i=Object.assign||function(h){for(var u,f=1,x=arguments.length;f<x;f++)for(var b in u=arguments[f])Object.prototype.hasOwnProperty.call(u,b)&&(h[b]=u[b]);return h}).apply(this,arguments)},n=this&&this.__awaiter||function(h,u,f,x){return new(f||(f=Promise))(function(b,y){function g(v){try{m(x.next(v))}catch(w){y(w)}}function p(v){try{m(x.throw(v))}catch(w){y(w)}}function m(v){var w;v.done?b(v.value):(w=v.value,w instanceof f?w:new f(function(E){E(w)})).then(g,p)}m((x=x.apply(h,u||[])).next())})},r=this&&this.__generator||function(h,u){var f,x,b,y,g={label:0,sent:function(){if(1&b[0])throw b[1];return b[1]},trys:[],ops:[]};return y={next:p(0),throw:p(1),return:p(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function p(m){return function(v){return function(w){if(f)throw new TypeError("Generator is already executing.");for(;g;)try{if(f=1,x&&(b=2&w[0]?x.return:w[0]?x.throw||((b=x.return)&&b.call(x),0):x.next)&&!(b=b.call(x,w[1])).done)return b;switch(x=0,b&&(w=[2&w[0],b.value]),w[0]){case 0:case 1:b=w;break;case 4:return g.label++,{value:w[1],done:!1};case 5:g.label++,x=w[1],w=[0];continue;case 7:w=g.ops.pop(),g.trys.pop();continue;default:if(!(b=(b=g.trys).length>0&&b[b.length-1])&&(w[0]===6||w[0]===2)){g=0;continue}if(w[0]===3&&(!b||w[1]>b[0]&&w[1]<b[3])){g.label=w[1];break}if(w[0]===6&&g.label<b[1]){g.label=b[1],b=w;break}if(b&&g.label<b[2]){g.label=b[2],g.ops.push(w);break}b[2]&&g.ops.pop(),g.trys.pop();continue}w=u.call(h,g)}catch(E){w=[6,E],x=0}finally{f=b=0}if(5&w[0])throw w[1];return{value:w[0]?w[1]:void 0,done:!0}}([m,v])}}},o=this&&this.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.Negotiator=void 0;var s=a("./util"),c=o(a("./logger")),d=a("./enums"),l=function(){function h(u){this.connection=u}return h.prototype.startConnection=function(u){var f=this._startPeerConnection();if(this.connection.peerConnection=f,this.connection.type===d.ConnectionType.Media&&u._stream&&this._addTracksToConnection(u._stream,f),u.originator){if(this.connection.type===d.ConnectionType.Data){var x=this.connection,b={ordered:!!u.reliable},y=f.createDataChannel(x.label,b);x.initialize(y)}this._makeOffer()}else this.handleSDP("OFFER",u.sdp)},h.prototype._startPeerConnection=function(){c.default.log("Creating RTCPeerConnection.");var u=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(u),u},h.prototype._setupListeners=function(u){var f=this,x=this.connection.peer,b=this.connection.connectionId,y=this.connection.type,g=this.connection.provider;c.default.log("Listening for ICE candidates."),u.onicecandidate=function(p){p.candidate&&p.candidate.candidate&&(c.default.log("Received ICE candidates for "+x+":",p.candidate),g.socket.send({type:d.ServerMessageType.Candidate,payload:{candidate:p.candidate,type:y,connectionId:b},dst:x}))},u.oniceconnectionstatechange=function(){switch(u.iceConnectionState){case"failed":c.default.log("iceConnectionState is failed, closing connections to "+x),f.connection.emit(d.ConnectionEventType.Error,new Error("Negotiation of connection to "+x+" failed.")),f.connection.close();break;case"closed":c.default.log("iceConnectionState is closed, closing connections to "+x),f.connection.emit(d.ConnectionEventType.Error,new Error("Connection to "+x+" closed.")),f.connection.close();break;case"disconnected":c.default.log("iceConnectionState changed to disconnected on the connection with "+x);break;case"completed":u.onicecandidate=s.util.noop}f.connection.emit(d.ConnectionEventType.IceStateChanged,u.iceConnectionState)},c.default.log("Listening for data channel"),u.ondatachannel=function(p){c.default.log("Received data channel");var m=p.channel;g.getConnection(x,b).initialize(m)},c.default.log("Listening for remote stream"),u.ontrack=function(p){c.default.log("Received remote stream");var m=p.streams[0],v=g.getConnection(x,b);if(v.type===d.ConnectionType.Media){var w=v;f._addStreamToMediaConnection(m,w)}}},h.prototype.cleanup=function(){c.default.log("Cleaning up PeerConnection to "+this.connection.peer);var u=this.connection.peerConnection;if(u){this.connection.peerConnection=null,u.onicecandidate=u.oniceconnectionstatechange=u.ondatachannel=u.ontrack=function(){};var f=u.signalingState!=="closed",x=!1;if(this.connection.type===d.ConnectionType.Data){var b=this.connection.dataChannel;b&&(x=!!b.readyState&&b.readyState!=="closed")}(f||x)&&u.close()}},h.prototype._makeOffer=function(){return n(this,void 0,Promise,function(){var u,f,x,b,y,g,p;return r(this,function(m){switch(m.label){case 0:u=this.connection.peerConnection,f=this.connection.provider,m.label=1;case 1:return m.trys.push([1,7,,8]),[4,u.createOffer(this.connection.options.constraints)];case 2:x=m.sent(),c.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(x.sdp=this.connection.options.sdpTransform(x.sdp)||x.sdp),m.label=3;case 3:return m.trys.push([3,5,,6]),[4,u.setLocalDescription(x)];case 4:return m.sent(),c.default.log("Set localDescription:",x,"for:"+this.connection.peer),b={sdp:x,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:s.util.browser},this.connection.type===d.ConnectionType.Data&&(y=this.connection,b=i(i({},b),{label:y.label,reliable:y.reliable,serialization:y.serialization})),f.socket.send({type:d.ServerMessageType.Offer,payload:b,dst:this.connection.peer}),[3,6];case 5:return(g=m.sent())!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(f.emitError(d.PeerErrorType.WebRTC,g),c.default.log("Failed to setLocalDescription, ",g)),[3,6];case 6:return[3,8];case 7:return p=m.sent(),f.emitError(d.PeerErrorType.WebRTC,p),c.default.log("Failed to createOffer, ",p),[3,8];case 8:return[2]}})})},h.prototype._makeAnswer=function(){return n(this,void 0,Promise,function(){var u,f,x,b,y;return r(this,function(g){switch(g.label){case 0:u=this.connection.peerConnection,f=this.connection.provider,g.label=1;case 1:return g.trys.push([1,7,,8]),[4,u.createAnswer()];case 2:x=g.sent(),c.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(x.sdp=this.connection.options.sdpTransform(x.sdp)||x.sdp),g.label=3;case 3:return g.trys.push([3,5,,6]),[4,u.setLocalDescription(x)];case 4:return g.sent(),c.default.log("Set localDescription:",x,"for:"+this.connection.peer),f.socket.send({type:d.ServerMessageType.Answer,payload:{sdp:x,type:this.connection.type,connectionId:this.connection.connectionId,browser:s.util.browser},dst:this.connection.peer}),[3,6];case 5:return b=g.sent(),f.emitError(d.PeerErrorType.WebRTC,b),c.default.log("Failed to setLocalDescription, ",b),[3,6];case 6:return[3,8];case 7:return y=g.sent(),f.emitError(d.PeerErrorType.WebRTC,y),c.default.log("Failed to create answer, ",y),[3,8];case 8:return[2]}})})},h.prototype.handleSDP=function(u,f){return n(this,void 0,Promise,function(){var x,b,y,g;return r(this,function(p){switch(p.label){case 0:f=new RTCSessionDescription(f),x=this.connection.peerConnection,b=this.connection.provider,c.default.log("Setting remote description",f),y=this,p.label=1;case 1:return p.trys.push([1,5,,6]),[4,x.setRemoteDescription(f)];case 2:return p.sent(),c.default.log("Set remoteDescription:"+u+" for:"+this.connection.peer),u!=="OFFER"?[3,4]:[4,y._makeAnswer()];case 3:p.sent(),p.label=4;case 4:return[3,6];case 5:return g=p.sent(),b.emitError(d.PeerErrorType.WebRTC,g),c.default.log("Failed to setRemoteDescription, ",g),[3,6];case 6:return[2]}})})},h.prototype.handleCandidate=function(u){return n(this,void 0,Promise,function(){var f,x,b,y,g,p;return r(this,function(m){switch(m.label){case 0:c.default.log("handleCandidate:",u),f=u.candidate,x=u.sdpMLineIndex,b=u.sdpMid,y=this.connection.peerConnection,g=this.connection.provider,m.label=1;case 1:return m.trys.push([1,3,,4]),[4,y.addIceCandidate(new RTCIceCandidate({sdpMid:b,sdpMLineIndex:x,candidate:f}))];case 2:return m.sent(),c.default.log("Added ICE candidate for:"+this.connection.peer),[3,4];case 3:return p=m.sent(),g.emitError(d.PeerErrorType.WebRTC,p),c.default.log("Failed to handleCandidate, ",p),[3,4];case 4:return[2]}})})},h.prototype._addTracksToConnection=function(u,f){if(c.default.log("add tracks from stream "+u.id+" to peer connection"),!f.addTrack)return c.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");u.getTracks().forEach(function(x){f.addTrack(x,u)})},h.prototype._addStreamToMediaConnection=function(u,f){c.default.log("add stream "+u.id+" to media connection "+f.connectionId),f.addStream(u)},h}();t.Negotiator=l},{"./util":"BHXf","./logger":"WOs9","./enums":"ZRYf"}],tQFK:[function(a,e,t){"use strict";var i=this&&this.__extends||function(){var o=function(s,c){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,l){d.__proto__=l}||function(d,l){for(var h in l)Object.prototype.hasOwnProperty.call(l,h)&&(d[h]=l[h])})(s,c)};return function(s,c){if(typeof c!="function"&&c!==null)throw new TypeError("Class extends value "+String(c)+" is not a constructor or null");function d(){this.constructor=s}o(s,c),s.prototype=c===null?Object.create(c):(d.prototype=c.prototype,new d)}}();Object.defineProperty(t,"__esModule",{value:!0}),t.BaseConnection=void 0;var n=a("eventemitter3"),r=function(o){function s(c,d,l){var h=o.call(this)||this;return h.peer=c,h.provider=d,h.options=l,h._open=!1,h.metadata=l.metadata,h}return i(s,o),Object.defineProperty(s.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),s}(n.EventEmitter);t.BaseConnection=r},{eventemitter3:"JJlS"}],dbHP:[function(a,e,t){"use strict";var i=this&&this.__extends||function(){var f=function(x,b){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,g){y.__proto__=g}||function(y,g){for(var p in g)Object.prototype.hasOwnProperty.call(g,p)&&(y[p]=g[p])})(x,b)};return function(x,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");function y(){this.constructor=x}f(x,b),x.prototype=b===null?Object.create(b):(y.prototype=b.prototype,new y)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(f){for(var x,b=1,y=arguments.length;b<y;b++)for(var g in x=arguments[b])Object.prototype.hasOwnProperty.call(x,g)&&(f[g]=x[g]);return f}).apply(this,arguments)},r=this&&this.__values||function(f){var x=typeof Symbol=="function"&&Symbol.iterator,b=x&&f[x],y=0;if(b)return b.call(f);if(f&&typeof f.length=="number")return{next:function(){return f&&y>=f.length&&(f=void 0),{value:f&&f[y++],done:!f}}};throw new TypeError(x?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.MediaConnection=void 0;var s=a("./util"),c=o(a("./logger")),d=a("./negotiator"),l=a("./enums"),h=a("./baseconnection"),u=function(f){function x(b,y,g){var p=f.call(this,b,y,g)||this;return p._localStream=p.options._stream,p.connectionId=p.options.connectionId||x.ID_PREFIX+s.util.randomToken(),p._negotiator=new d.Negotiator(p),p._localStream&&p._negotiator.startConnection({_stream:p._localStream,originator:!0}),p}return i(x,f),Object.defineProperty(x.prototype,"type",{get:function(){return l.ConnectionType.Media},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),x.prototype.addStream=function(b){c.default.log("Receiving stream",b),this._remoteStream=b,f.prototype.emit.call(this,l.ConnectionEventType.Stream,b)},x.prototype.handleMessage=function(b){var y=b.type,g=b.payload;switch(b.type){case l.ServerMessageType.Answer:this._negotiator.handleSDP(y,g.sdp),this._open=!0;break;case l.ServerMessageType.Candidate:this._negotiator.handleCandidate(g.candidate);break;default:c.default.warn("Unrecognized message type:"+y+" from peer:"+this.peer)}},x.prototype.answer=function(b,y){var g,p;if(y===void 0&&(y={}),this._localStream)c.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");else{this._localStream=b,y&&y.sdpTransform&&(this.options.sdpTransform=y.sdpTransform),this._negotiator.startConnection(n(n({},this.options._payload),{_stream:b}));var m=this.provider._getMessages(this.connectionId);try{for(var v=r(m),w=v.next();!w.done;w=v.next()){var E=w.value;this.handleMessage(E)}}catch(C){g={error:C}}finally{try{w&&!w.done&&(p=v.return)&&p.call(v)}finally{if(g)throw g.error}}this._open=!0}},x.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,f.prototype.emit.call(this,l.ConnectionEventType.Close))},x.ID_PREFIX="mc_",x}(h.BaseConnection);t.MediaConnection=u},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK"}],GGp6:[function(a,e,t){"use strict";var i=this&&this.__extends||function(){var c=function(d,l){return(c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(h,u){h.__proto__=u}||function(h,u){for(var f in u)Object.prototype.hasOwnProperty.call(u,f)&&(h[f]=u[f])})(d,l)};return function(d,l){if(typeof l!="function"&&l!==null)throw new TypeError("Class extends value "+String(l)+" is not a constructor or null");function h(){this.constructor=d}c(d,l),d.prototype=l===null?Object.create(l):(h.prototype=l.prototype,new h)}}(),n=this&&this.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.EncodingQueue=void 0;var r=a("eventemitter3"),o=n(a("./logger")),s=function(c){function d(){var l=c.call(this)||this;return l.fileReader=new FileReader,l._queue=[],l._processing=!1,l.fileReader.onload=function(h){l._processing=!1,h.target&&l.emit("done",h.target.result),l.doNextTask()},l.fileReader.onerror=function(h){o.default.error("EncodingQueue error:",h),l._processing=!1,l.destroy(),l.emit("error",h)},l}return i(d,c),Object.defineProperty(d.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),d.prototype.enque=function(l){this.queue.push(l),this.processing||this.doNextTask()},d.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},d.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},d}(r.EventEmitter);t.EncodingQueue=s},{eventemitter3:"JJlS","./logger":"WOs9"}],GBTQ:[function(a,e,t){"use strict";var i=this&&this.__extends||function(){var f=function(x,b){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,g){y.__proto__=g}||function(y,g){for(var p in g)Object.prototype.hasOwnProperty.call(g,p)&&(y[p]=g[p])})(x,b)};return function(x,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");function y(){this.constructor=x}f(x,b),x.prototype=b===null?Object.create(b):(y.prototype=b.prototype,new y)}}(),n=this&&this.__values||function(f){var x=typeof Symbol=="function"&&Symbol.iterator,b=x&&f[x],y=0;if(b)return b.call(f);if(f&&typeof f.length=="number")return{next:function(){return f&&y>=f.length&&(f=void 0),{value:f&&f[y++],done:!f}}};throw new TypeError(x?"Object is not iterable.":"Symbol.iterator is not defined.")},r=this&&this.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnection=void 0;var o=a("./util"),s=r(a("./logger")),c=a("./negotiator"),d=a("./enums"),l=a("./baseconnection"),h=a("./encodingQueue"),u=function(f){function x(b,y,g){var p=f.call(this,b,y,g)||this;return p.stringify=JSON.stringify,p.parse=JSON.parse,p._buffer=[],p._bufferSize=0,p._buffering=!1,p._chunkedData={},p._encodingQueue=new h.EncodingQueue,p.connectionId=p.options.connectionId||x.ID_PREFIX+o.util.randomToken(),p.label=p.options.label||p.connectionId,p.serialization=p.options.serialization||d.SerializationType.Binary,p.reliable=!!p.options.reliable,p._encodingQueue.on("done",function(m){p._bufferedSend(m)}),p._encodingQueue.on("error",function(){s.default.error("DC#"+p.connectionId+": Error occured in encoding from blob to arraybuffer, close DC"),p.close()}),p._negotiator=new c.Negotiator(p),p._negotiator.startConnection(p.options._payload||{originator:!0}),p}return i(x,f),Object.defineProperty(x.prototype,"type",{get:function(){return d.ConnectionType.Data},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),x.prototype.initialize=function(b){this._dc=b,this._configureDataChannel()},x.prototype._configureDataChannel=function(){var b=this;o.util.supports.binaryBlob&&!o.util.supports.reliable||(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){s.default.log("DC#"+b.connectionId+" dc connection success"),b._open=!0,b.emit(d.ConnectionEventType.Open)},this.dataChannel.onmessage=function(y){s.default.log("DC#"+b.connectionId+" dc onmessage:",y.data),b._handleDataMessage(y)},this.dataChannel.onclose=function(){s.default.log("DC#"+b.connectionId+" dc closed for:",b.peer),b.close()}},x.prototype._handleDataMessage=function(b){var y=this,g=b.data,p=g.constructor,m=g;if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){if(p===Blob)return void o.util.blobToArrayBuffer(g,function(w){var E=o.util.unpack(w);y.emit(d.ConnectionEventType.Data,E)});if(p===ArrayBuffer)m=o.util.unpack(g);else if(p===String){var v=o.util.binaryStringToArrayBuffer(g);m=o.util.unpack(v)}}else this.serialization===d.SerializationType.JSON&&(m=this.parse(g));m.__peerData?this._handleChunk(m):f.prototype.emit.call(this,d.ConnectionEventType.Data,m)},x.prototype._handleChunk=function(b){var y=b.__peerData,g=this._chunkedData[y]||{data:[],count:0,total:b.total};if(g.data[b.n]=b.data,g.count++,this._chunkedData[y]=g,g.total===g.count){delete this._chunkedData[y];var p=new Blob(g.data);this._handleDataMessage({data:p})}},x.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,f.prototype.emit.call(this,d.ConnectionEventType.Close))},x.prototype.send=function(b,y){if(this.open)if(this.serialization===d.SerializationType.JSON)this._bufferedSend(this.stringify(b));else if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){var g=o.util.pack(b);if(!y&&g.size>o.util.chunkedMTU)return void this._sendChunks(g);o.util.supports.binaryBlob?this._bufferedSend(g):this._encodingQueue.enque(g)}else this._bufferedSend(b);else f.prototype.emit.call(this,d.ConnectionEventType.Error,new Error("Connection is not open. You should listen for the `open` event before sending messages."))},x.prototype._bufferedSend=function(b){!this._buffering&&this._trySend(b)||(this._buffer.push(b),this._bufferSize=this._buffer.length)},x.prototype._trySend=function(b){var y=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>x.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){y._buffering=!1,y._tryBuffer()},50),!1;try{this.dataChannel.send(b)}catch(g){return s.default.error("DC#:"+this.connectionId+" Error when sending:",g),this._buffering=!0,this.close(),!1}return!0},x.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var b=this._buffer[0];this._trySend(b)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},x.prototype._sendChunks=function(b){var y,g,p=o.util.chunk(b);s.default.log("DC#"+this.connectionId+" Try to send "+p.length+" chunks...");try{for(var m=n(p),v=m.next();!v.done;v=m.next()){var w=v.value;this.send(w,!0)}}catch(E){y={error:E}}finally{try{v&&!v.done&&(g=m.return)&&g.call(m)}finally{if(y)throw y.error}}},x.prototype.handleMessage=function(b){var y=b.payload;switch(b.type){case d.ServerMessageType.Answer:this._negotiator.handleSDP(b.type,y.sdp);break;case d.ServerMessageType.Candidate:this._negotiator.handleCandidate(y.candidate);break;default:s.default.warn("Unrecognized message type:",b.type,"from peer:",this.peer)}},x.ID_PREFIX="dc_",x.MAX_BUFFERED_AMOUNT=8388608,x}(l.BaseConnection);t.DataConnection=u},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK","./encodingQueue":"GGp6"}],in7L:[function(a,e,t){"use strict";var i=this&&this.__awaiter||function(d,l,h,u){return new(h||(h=Promise))(function(f,x){function b(p){try{g(u.next(p))}catch(m){x(m)}}function y(p){try{g(u.throw(p))}catch(m){x(m)}}function g(p){var m;p.done?f(p.value):(m=p.value,m instanceof h?m:new h(function(v){v(m)})).then(b,y)}g((u=u.apply(d,l||[])).next())})},n=this&&this.__generator||function(d,l){var h,u,f,x,b={label:0,sent:function(){if(1&f[0])throw f[1];return f[1]},trys:[],ops:[]};return x={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(x[Symbol.iterator]=function(){return this}),x;function y(g){return function(p){return function(m){if(h)throw new TypeError("Generator is already executing.");for(;b;)try{if(h=1,u&&(f=2&m[0]?u.return:m[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,m[1])).done)return f;switch(u=0,f&&(m=[2&m[0],f.value]),m[0]){case 0:case 1:f=m;break;case 4:return b.label++,{value:m[1],done:!1};case 5:b.label++,u=m[1],m=[0];continue;case 7:m=b.ops.pop(),b.trys.pop();continue;default:if(!(f=(f=b.trys).length>0&&f[f.length-1])&&(m[0]===6||m[0]===2)){b=0;continue}if(m[0]===3&&(!f||m[1]>f[0]&&m[1]<f[3])){b.label=m[1];break}if(m[0]===6&&b.label<f[1]){b.label=f[1],f=m;break}if(f&&b.label<f[2]){b.label=f[2],b.ops.push(m);break}f[2]&&b.ops.pop(),b.trys.pop();continue}m=l.call(d,b)}catch(v){m=[6,v],u=0}finally{h=f=0}if(5&m[0])throw m[1];return{value:m[0]?m[1]:void 0,done:!0}}([g,p])}}},r=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(t,"__esModule",{value:!0}),t.API=void 0;var o=a("./util"),s=r(a("./logger")),c=function(){function d(l){this._options=l}return d.prototype._buildUrl=function(l){var h=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+l;return h+="?ts="+new Date().getTime()+Math.random()},d.prototype.retrieveId=function(){return i(this,void 0,Promise,function(){var l,h,u,f;return n(this,function(x){switch(x.label){case 0:l=this._buildUrl("id"),x.label=1;case 1:return x.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((h=x.sent()).status!==200)throw new Error("Error. Status:"+h.status);return[2,h.text()];case 3:throw u=x.sent(),s.default.error("Error retrieving ID",u),f="",this._options.path==="/"&&this._options.host!==o.util.CLOUD_HOST&&(f=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+f);case 4:return[2]}})})},d.prototype.listAllPeers=function(){return i(this,void 0,Promise,function(){var l,h,u,f;return n(this,function(x){switch(x.label){case 0:l=this._buildUrl("peers"),x.label=1;case 1:return x.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((h=x.sent()).status!==200)throw h.status===401?(u="",u=this._options.host===o.util.CLOUD_HOST?"It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":"You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+u)):new Error("Error. Status:"+h.status);return[2,h.json()];case 3:throw f=x.sent(),s.default.error("Error retrieving list peers",f),new Error("Could not get list peers from the server."+f);case 4:return[2]}})})},d}();t.API=c},{"./util":"BHXf","./logger":"WOs9"}],Hxpd:[function(a,e,t){"use strict";var i=this&&this.__extends||function(){var p=function(m,v){return(p=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,E){w.__proto__=E}||function(w,E){for(var C in E)Object.prototype.hasOwnProperty.call(E,C)&&(w[C]=E[C])})(m,v)};return function(m,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function w(){this.constructor=m}p(m,v),m.prototype=v===null?Object.create(v):(w.prototype=v.prototype,new w)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(p){for(var m,v=1,w=arguments.length;v<w;v++)for(var E in m=arguments[v])Object.prototype.hasOwnProperty.call(m,E)&&(p[E]=m[E]);return p}).apply(this,arguments)},r=this&&this.__values||function(p){var m=typeof Symbol=="function"&&Symbol.iterator,v=m&&p[m],w=0;if(v)return v.call(p);if(p&&typeof p.length=="number")return{next:function(){return p&&w>=p.length&&(p=void 0),{value:p&&p[w++],done:!p}}};throw new TypeError(m?"Object is not iterable.":"Symbol.iterator is not defined.")},o=this&&this.__read||function(p,m){var v=typeof Symbol=="function"&&p[Symbol.iterator];if(!v)return p;var w,E,C=v.call(p),T=[];try{for(;(m===void 0||m-- >0)&&!(w=C.next()).done;)T.push(w.value)}catch(R){E={error:R}}finally{try{w&&!w.done&&(v=C.return)&&v.call(C)}finally{if(E)throw E.error}}return T},s=this&&this.__importDefault||function(p){return p&&p.__esModule?p:{default:p}};Object.defineProperty(t,"__esModule",{value:!0}),t.Peer=void 0;var c=a("eventemitter3"),d=a("./util"),l=s(a("./logger")),h=a("./socket"),u=a("./mediaconnection"),f=a("./dataconnection"),x=a("./enums"),b=a("./api"),y=function(){return function(){}}(),g=function(p){function m(v,w){var E,C=p.call(this)||this;return C._id=null,C._lastServerId=null,C._destroyed=!1,C._disconnected=!1,C._open=!1,C._connections=new Map,C._lostMessages=new Map,v&&v.constructor==Object?w=v:v&&(E=v.toString()),w=n({debug:0,host:d.util.CLOUD_HOST,port:d.util.CLOUD_PORT,path:"/",key:m.DEFAULT_KEY,token:d.util.randomToken(),config:d.util.defaultConfig},w),C._options=w,C._options.host==="/"&&(C._options.host=window.location.hostname),C._options.path&&(C._options.path[0]!=="/"&&(C._options.path="/"+C._options.path),C._options.path[C._options.path.length-1]!=="/"&&(C._options.path+="/")),C._options.secure===void 0&&C._options.host!==d.util.CLOUD_HOST?C._options.secure=d.util.isSecure():C._options.host==d.util.CLOUD_HOST&&(C._options.secure=!0),C._options.logFunction&&l.default.setLogFunction(C._options.logFunction),l.default.logLevel=C._options.debug||0,C._api=new b.API(w),C._socket=C._createServerConnection(),d.util.supports.audioVideo||d.util.supports.data?E&&!d.util.validateId(E)?(C._delayedAbort(x.PeerErrorType.InvalidID,'ID "'+E+'" is invalid'),C):(E?C._initialize(E):C._api.retrieveId().then(function(T){return C._initialize(T)}).catch(function(T){return C._abort(x.PeerErrorType.ServerError,T)}),C):(C._delayedAbort(x.PeerErrorType.BrowserIncompatible,"The current browser does not support WebRTC"),C)}return i(m,p),Object.defineProperty(m.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"connections",{get:function(){var v,w,E=Object.create(null);try{for(var C=r(this._connections),T=C.next();!T.done;T=C.next()){var R=o(T.value,2),I=R[0],O=R[1];E[I]=O}}catch(L){v={error:L}}finally{try{T&&!T.done&&(w=C.return)&&w.call(C)}finally{if(v)throw v.error}}return E},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),m.prototype._createServerConnection=function(){var v=this,w=new h.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return w.on(x.SocketEventType.Message,function(E){v._handleMessage(E)}),w.on(x.SocketEventType.Error,function(E){v._abort(x.PeerErrorType.SocketError,E)}),w.on(x.SocketEventType.Disconnected,function(){v.disconnected||(v.emitError(x.PeerErrorType.Network,"Lost connection to server."),v.disconnect())}),w.on(x.SocketEventType.Close,function(){v.disconnected||v._abort(x.PeerErrorType.SocketClosed,"Underlying socket is already closed.")}),w},m.prototype._initialize=function(v){this._id=v,this.socket.start(v,this._options.token)},m.prototype._handleMessage=function(v){var w,E,C=v.type,T=v.payload,R=v.src;switch(C){case x.ServerMessageType.Open:this._lastServerId=this.id,this._open=!0,this.emit(x.PeerEventType.Open,this.id);break;case x.ServerMessageType.Error:this._abort(x.PeerErrorType.ServerError,T.msg);break;case x.ServerMessageType.IdTaken:this._abort(x.PeerErrorType.UnavailableID,'ID "'+this.id+'" is taken');break;case x.ServerMessageType.InvalidKey:this._abort(x.PeerErrorType.InvalidKey,'API KEY "'+this._options.key+'" is invalid');break;case x.ServerMessageType.Leave:l.default.log("Received leave message from "+R),this._cleanupPeer(R),this._connections.delete(R);break;case x.ServerMessageType.Expire:this.emitError(x.PeerErrorType.PeerUnavailable,"Could not connect to peer "+R);break;case x.ServerMessageType.Offer:var I=T.connectionId;if((H=this.getConnection(R,I))&&(H.close(),l.default.warn("Offer received for existing Connection ID:"+I)),T.type===x.ConnectionType.Media)H=new u.MediaConnection(R,this,{connectionId:I,_payload:T,metadata:T.metadata}),this._addConnection(R,H),this.emit(x.PeerEventType.Call,H);else{if(T.type!==x.ConnectionType.Data)return void l.default.warn("Received malformed connection type:"+T.type);H=new f.DataConnection(R,this,{connectionId:I,_payload:T,metadata:T.metadata,label:T.label,serialization:T.serialization,reliable:T.reliable}),this._addConnection(R,H),this.emit(x.PeerEventType.Connection,H)}var O=this._getMessages(I);try{for(var L=r(O),A=L.next();!A.done;A=L.next()){var F=A.value;H.handleMessage(F)}}catch(z){w={error:z}}finally{try{A&&!A.done&&(E=L.return)&&E.call(L)}finally{if(w)throw w.error}}break;default:if(!T)return void l.default.warn("You received a malformed message from "+R+" of type "+C);var H;I=T.connectionId,(H=this.getConnection(R,I))&&H.peerConnection?H.handleMessage(v):I?this._storeMessage(I,v):l.default.warn("You received an unrecognized message:",v)}},m.prototype._storeMessage=function(v,w){this._lostMessages.has(v)||this._lostMessages.set(v,[]),this._lostMessages.get(v).push(w)},m.prototype._getMessages=function(v){var w=this._lostMessages.get(v);return w?(this._lostMessages.delete(v),w):[]},m.prototype.connect=function(v,w){if(w===void 0&&(w={}),this.disconnected)return l.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),void this.emitError(x.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");var E=new f.DataConnection(v,this,w);return this._addConnection(v,E),E},m.prototype.call=function(v,w,E){if(E===void 0&&(E={}),this.disconnected)return l.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),void this.emitError(x.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");if(w){E._stream=w;var C=new u.MediaConnection(v,this,E);return this._addConnection(v,C),C}l.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.")},m.prototype._addConnection=function(v,w){l.default.log("add connection "+w.type+":"+w.connectionId+" to peerId:"+v),this._connections.has(v)||this._connections.set(v,[]),this._connections.get(v).push(w)},m.prototype._removeConnection=function(v){var w=this._connections.get(v.peer);if(w){var E=w.indexOf(v);E!==-1&&w.splice(E,1)}this._lostMessages.delete(v.connectionId)},m.prototype.getConnection=function(v,w){var E,C,T=this._connections.get(v);if(!T)return null;try{for(var R=r(T),I=R.next();!I.done;I=R.next()){var O=I.value;if(O.connectionId===w)return O}}catch(L){E={error:L}}finally{try{I&&!I.done&&(C=R.return)&&C.call(R)}finally{if(E)throw E.error}}return null},m.prototype._delayedAbort=function(v,w){var E=this;setTimeout(function(){E._abort(v,w)},0)},m.prototype._abort=function(v,w){l.default.error("Aborting!"),this.emitError(v,w),this._lastServerId?this.disconnect():this.destroy()},m.prototype.emitError=function(v,w){var E;l.default.error("Error:",w),(E=typeof w=="string"?new Error(w):w).type=v,this.emit(x.PeerEventType.Error,E)},m.prototype.destroy=function(){this.destroyed||(l.default.log("Destroy peer with ID:"+this.id),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit(x.PeerEventType.Close))},m.prototype._cleanup=function(){var v,w;try{for(var E=r(this._connections.keys()),C=E.next();!C.done;C=E.next()){var T=C.value;this._cleanupPeer(T),this._connections.delete(T)}}catch(R){v={error:R}}finally{try{C&&!C.done&&(w=E.return)&&w.call(E)}finally{if(v)throw v.error}}this.socket.removeAllListeners()},m.prototype._cleanupPeer=function(v){var w,E,C=this._connections.get(v);if(C)try{for(var T=r(C),R=T.next();!R.done;R=T.next())R.value.close()}catch(I){w={error:I}}finally{try{R&&!R.done&&(E=T.return)&&E.call(T)}finally{if(w)throw w.error}}},m.prototype.disconnect=function(){if(!this.disconnected){var v=this.id;l.default.log("Disconnect peer with ID:"+v),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=v,this._id=null,this.emit(x.PeerEventType.Disconnected,v)}},m.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)l.default.log("Attempting reconnection to server with ID "+this._lastServerId),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(this.disconnected||this.open)throw new Error("Peer "+this.id+" cannot reconnect because it is not disconnected from the server!");l.default.error("In a hurry? We're still trying to make the initial connection!")}},m.prototype.listAllPeers=function(v){var w=this;v===void 0&&(v=function(E){}),this._api.listAllPeers().then(function(E){return v(E)}).catch(function(E){return w._abort(x.PeerErrorType.ServerError,E)})},m.DEFAULT_KEY="peerjs",m}(c.EventEmitter);t.Peer=g},{eventemitter3:"JJlS","./util":"BHXf","./logger":"WOs9","./socket":"wJlv","./mediaconnection":"dbHP","./dataconnection":"GBTQ","./enums":"ZRYf","./api":"in7L"}],iTK6:[function(a,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.peerjs=void 0;var i=a("./util"),n=a("./peer");t.peerjs={Peer:n.Peer,util:i.util},t.default=n.Peer,window.peerjs=t.peerjs,window.Peer=n.Peer},{"./util":"BHXf","./peer":"Hxpd"}]},{},["iTK6"],null)});var pf=vs((TR,uf)=>{(function(){var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e={rotl:function(t,i){return t<<i|t>>>32-i},rotr:function(t,i){return t<<32-i|t>>>i},endian:function(t){if(t.constructor==Number)return e.rotl(t,8)&16711935|e.rotl(t,24)&4278255360;for(var i=0;i<t.length;i++)t[i]=e.endian(t[i]);return t},randomBytes:function(t){for(var i=[];t>0;t--)i.push(Math.floor(Math.random()*256));return i},bytesToWords:function(t){for(var i=[],n=0,r=0;n<t.length;n++,r+=8)i[r>>>5]|=t[n]<<24-r%32;return i},wordsToBytes:function(t){for(var i=[],n=0;n<t.length*32;n+=8)i.push(t[n>>>5]>>>24-n%32&255);return i},bytesToHex:function(t){for(var i=[],n=0;n<t.length;n++)i.push((t[n]>>>4).toString(16)),i.push((t[n]&15).toString(16));return i.join("")},hexToBytes:function(t){for(var i=[],n=0;n<t.length;n+=2)i.push(parseInt(t.substr(n,2),16));return i},bytesToBase64:function(t){for(var i=[],n=0;n<t.length;n+=3)for(var r=t[n]<<16|t[n+1]<<8|t[n+2],o=0;o<4;o++)n*8+o*6<=t.length*8?i.push(a.charAt(r>>>6*(3-o)&63)):i.push("=");return i.join("")},base64ToBytes:function(t){t=t.replace(/[^A-Z0-9+\/]/ig,"");for(var i=[],n=0,r=0;n<t.length;r=++n%4)r!=0&&i.push((a.indexOf(t.charAt(n-1))&Math.pow(2,-2*r+8)-1)<<r*2|a.indexOf(t.charAt(n))>>>6-r*2);return i}};uf.exports=e})()});var hd=vs((RR,ff)=>{var dd={utf8:{stringToBytes:function(a){return dd.bin.stringToBytes(unescape(encodeURIComponent(a)))},bytesToString:function(a){return decodeURIComponent(escape(dd.bin.bytesToString(a)))}},bin:{stringToBytes:function(a){for(var e=[],t=0;t<a.length;t++)e.push(a.charCodeAt(t)&255);return e},bytesToString:function(a){for(var e=[],t=0;t<a.length;t++)e.push(String.fromCharCode(a[t]));return e.join("")}}};ff.exports=dd});var bf=vs((SR,gf)=>{gf.exports=function(a){return a!=null&&(mf(a)||Hy(a)||!!a._isBuffer)};function mf(a){return!!a.constructor&&typeof a.constructor.isBuffer=="function"&&a.constructor.isBuffer(a)}function Hy(a){return typeof a.readFloatLE=="function"&&typeof a.slice=="function"&&mf(a.slice(0,0))}});var yf=vs((PR,vf)=>{(function(){var a=pf(),e=hd().utf8,t=bf(),i=hd().bin,n=function(r,o){r.constructor==String?o&&o.encoding==="binary"?r=i.stringToBytes(r):r=e.stringToBytes(r):t(r)?r=Array.prototype.slice.call(r,0):!Array.isArray(r)&&r.constructor!==Uint8Array&&(r=r.toString());for(var s=a.bytesToWords(r),c=r.length*8,d=1732584193,l=-271733879,h=-1732584194,u=271733878,f=0;f<s.length;f++)s[f]=(s[f]<<8|s[f]>>>24)&16711935|(s[f]<<24|s[f]>>>8)&4278255360;s[c>>>5]|=128<<c%32,s[(c+64>>>9<<4)+14]=c;for(var x=n._ff,b=n._gg,y=n._hh,g=n._ii,f=0;f<s.length;f+=16){var p=d,m=l,v=h,w=u;d=x(d,l,h,u,s[f+0],7,-680876936),u=x(u,d,l,h,s[f+1],12,-389564586),h=x(h,u,d,l,s[f+2],17,606105819),l=x(l,h,u,d,s[f+3],22,-1044525330),d=x(d,l,h,u,s[f+4],7,-176418897),u=x(u,d,l,h,s[f+5],12,1200080426),h=x(h,u,d,l,s[f+6],17,-1473231341),l=x(l,h,u,d,s[f+7],22,-45705983),d=x(d,l,h,u,s[f+8],7,1770035416),u=x(u,d,l,h,s[f+9],12,-1958414417),h=x(h,u,d,l,s[f+10],17,-42063),l=x(l,h,u,d,s[f+11],22,-1990404162),d=x(d,l,h,u,s[f+12],7,1804603682),u=x(u,d,l,h,s[f+13],12,-40341101),h=x(h,u,d,l,s[f+14],17,-1502002290),l=x(l,h,u,d,s[f+15],22,1236535329),d=b(d,l,h,u,s[f+1],5,-165796510),u=b(u,d,l,h,s[f+6],9,-1069501632),h=b(h,u,d,l,s[f+11],14,643717713),l=b(l,h,u,d,s[f+0],20,-373897302),d=b(d,l,h,u,s[f+5],5,-701558691),u=b(u,d,l,h,s[f+10],9,38016083),h=b(h,u,d,l,s[f+15],14,-660478335),l=b(l,h,u,d,s[f+4],20,-405537848),d=b(d,l,h,u,s[f+9],5,568446438),u=b(u,d,l,h,s[f+14],9,-1019803690),h=b(h,u,d,l,s[f+3],14,-187363961),l=b(l,h,u,d,s[f+8],20,1163531501),d=b(d,l,h,u,s[f+13],5,-1444681467),u=b(u,d,l,h,s[f+2],9,-51403784),h=b(h,u,d,l,s[f+7],14,1735328473),l=b(l,h,u,d,s[f+12],20,-1926607734),d=y(d,l,h,u,s[f+5],4,-378558),u=y(u,d,l,h,s[f+8],11,-2022574463),h=y(h,u,d,l,s[f+11],16,1839030562),l=y(l,h,u,d,s[f+14],23,-35309556),d=y(d,l,h,u,s[f+1],4,-1530992060),u=y(u,d,l,h,s[f+4],11,1272893353),h=y(h,u,d,l,s[f+7],16,-155497632),l=y(l,h,u,d,s[f+10],23,-1094730640),d=y(d,l,h,u,s[f+13],4,681279174),u=y(u,d,l,h,s[f+0],11,-358537222),h=y(h,u,d,l,s[f+3],16,-722521979),l=y(l,h,u,d,s[f+6],23,76029189),d=y(d,l,h,u,s[f+9],4,-640364487),u=y(u,d,l,h,s[f+12],11,-421815835),h=y(h,u,d,l,s[f+15],16,530742520),l=y(l,h,u,d,s[f+2],23,-995338651),d=g(d,l,h,u,s[f+0],6,-198630844),u=g(u,d,l,h,s[f+7],10,1126891415),h=g(h,u,d,l,s[f+14],15,-1416354905),l=g(l,h,u,d,s[f+5],21,-57434055),d=g(d,l,h,u,s[f+12],6,1700485571),u=g(u,d,l,h,s[f+3],10,-1894986606),h=g(h,u,d,l,s[f+10],15,-1051523),l=g(l,h,u,d,s[f+1],21,-2054922799),d=g(d,l,h,u,s[f+8],6,1873313359),u=g(u,d,l,h,s[f+15],10,-30611744),h=g(h,u,d,l,s[f+6],15,-1560198380),l=g(l,h,u,d,s[f+13],21,1309151649),d=g(d,l,h,u,s[f+4],6,-145523070),u=g(u,d,l,h,s[f+11],10,-1120210379),h=g(h,u,d,l,s[f+2],15,718787259),l=g(l,h,u,d,s[f+9],21,-343485551),d=d+p>>>0,l=l+m>>>0,h=h+v>>>0,u=u+w>>>0}return a.endian([d,l,h,u])};n._ff=function(r,o,s,c,d,l,h){var u=r+(o&s|~o&c)+(d>>>0)+h;return(u<<l|u>>>32-l)+o},n._gg=function(r,o,s,c,d,l,h){var u=r+(o&c|s&~c)+(d>>>0)+h;return(u<<l|u>>>32-l)+o},n._hh=function(r,o,s,c,d,l,h){var u=r+(o^s^c)+(d>>>0)+h;return(u<<l|u>>>32-l)+o},n._ii=function(r,o,s,c,d,l,h){var u=r+(s^(o|~c))+(d>>>0)+h;return(u<<l|u>>>32-l)+o},n._blocksize=16,n._digestsize=16,vf.exports=function(r,o){if(r==null)throw new Error("Illegal argument "+r);var s=a.wordsToBytes(n(r,o));return o&&o.asBytes?s:o&&o.asString?i.bytesToString(s):a.bytesToHex(s)}})()});import{DepthTexture as sx,WebGLRenderer as ax}from"three";import*as ke from"three";import*as Zt from"three";var uc=()=>a=>a;var pc=!1,dc=[];setTimeout(()=>{pc&&console.log(dc)},100);function fc(){return new URLSearchParams(window.location.search)}function D(a){pc&&!dc.includes(a)&&dc.push(a);let e=fc();if(e.has(a)){let t=e.get(a);return t||!0}return!1}pc=D("help")===!0;function Ro(a,e,t){a.has(e)?a.set(e,t.toString()):a.append(e,t.toString())}function bu(a,e){window.history.replaceState(null,a,"?"+e.toString())}function vu(a,e){return Math.floor(Math.random()*(e-a+1))+a}var mu=["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"],gu=["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 yu(){let a=mu[Math.floor(Math.random()*mu.length)],e=gu[Math.floor(Math.random()*gu.length)];return a+"_"+e}function xu(a){return a=a.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),a.trim()}function Bn(a,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===a)return e;if(e.guid==a)return e;if(i&&e.userData?.components){for(let n of e.userData.components)if(n.guid===a)return n}if(t){if(e.scenes)for(let n in e.scenes){let r=e.scenes[n],o=Bn(a,r,t,i);if(o)return o}if(e.children)for(let n in e.children){let r=e.children[n],o=Bn(a,r,t,i);if(o)return o}}}function ys(a,e){if(a!=null&&typeof a=="object"){let t;Array.isArray(a)?t=[]:(t=Object.create(a),Object.assign(t,a));for(let i of Object.keys(a)){let n=a[i];e&&!e(a,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=ys(n,e)}return t}return a}function wu(a){return new Promise((e,t)=>{setTimeout(e,a)})}var cc=D("debugsourcepath");function wi(a,e){if(a===void 0)return cc&&console.warn("getPath: source is undefined, returning uri",e),e;if(e.startsWith("http"))return cc&&console.warn("getPath: uri is absolute, returning uri",e),e;let t=a.lastIndexOf("/");if(t>=0){let i=a.substring(0,t+1),n=e.lastIndexOf("/");return n>=0?i+=e.substring(n+1):i+=e,cc&&console.log("getPath:",a,` - changed uri from
78
+ isUnifiedPlanSupported:`+this.isUnifiedPlanSupported()},i}())},{"./adapter":"sXtV"}],BHXf:[function(o,e,t){"use strict";var n=this&&this.__createBinding||(Object.create?function(d,l,u,h){h===void 0&&(h=u),Object.defineProperty(d,h,{enumerable:!0,get:function(){return l[u]}})}:function(d,l,u,h){h===void 0&&(h=u),d[h]=l[u]}),i=this&&this.__setModuleDefault||(Object.create?function(d,l){Object.defineProperty(d,"default",{enumerable:!0,value:l})}:function(d,l){d.default=l}),r=this&&this.__importStar||function(d){if(d&&d.__esModule)return d;var l={};if(d!=null)for(var u in d)u!=="default"&&Object.prototype.hasOwnProperty.call(d,u)&&n(l,d,u);return i(l,d),l};Object.defineProperty(t,"__esModule",{value:!0}),t.util=void 0;var s=r(o("peerjs-js-binarypack")),a=o("./supports"),c={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"turn:0.peerjs.com:3478",username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"};t.util=new(function(){function d(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=c,this.browser=a.Supports.getBrowser(),this.browserVersion=a.Supports.getVersion(),this.supports=function(){var l,u={browser:a.Supports.isBrowserSupported(),webRTC:a.Supports.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!u.webRTC)return u;try{l=new RTCPeerConnection(c),u.audioVideo=!0;var h=void 0;try{h=l.createDataChannel("_PEERJSTEST",{ordered:!0}),u.data=!0,u.reliable=!!h.ordered;try{h.binaryType="blob",u.binaryBlob=!a.Supports.isIOS}catch{}}catch{}finally{h&&h.close()}}catch{}finally{l&&l.close()}return u}(),this.pack=s.pack,this.unpack=s.unpack,this._dataCount=1}return d.prototype.noop=function(){},d.prototype.validateId=function(l){return!l||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(l)},d.prototype.chunk=function(l){for(var u=[],h=l.size,b=Math.ceil(h/t.util.chunkedMTU),_=0,v=0;v<h;){var y=Math.min(h,v+t.util.chunkedMTU),m=l.slice(v,y),f={__peerData:this._dataCount,n:_,data:m,total:b};u.push(f),v=y,_++}return this._dataCount++,u},d.prototype.blobToArrayBuffer=function(l,u){var h=new FileReader;return h.onload=function(b){b.target&&u(b.target.result)},h.readAsArrayBuffer(l),h},d.prototype.binaryStringToArrayBuffer=function(l){for(var u=new Uint8Array(l.length),h=0;h<l.length;h++)u[h]=255&l.charCodeAt(h);return u.buffer},d.prototype.randomToken=function(){return Math.random().toString(36).substr(2)},d.prototype.isSecure=function(){return location.protocol==="https:"},d}())},{"peerjs-js-binarypack":"kdPp","./supports":"I31f"}],JJlS:[function(o,e,t){"use strict";var n=Object.prototype.hasOwnProperty,i="~";function r(){}function s(l,u,h){this.fn=l,this.context=u,this.once=h||!1}function a(l,u,h,b,_){if(typeof h!="function")throw new TypeError("The listener must be a function");var v=new s(h,b||l,_),y=i?i+u:u;return l._events[y]?l._events[y].fn?l._events[y]=[l._events[y],v]:l._events[y].push(v):(l._events[y]=v,l._eventsCount++),l}function c(l,u){--l._eventsCount==0?l._events=new r:delete l._events[u]}function d(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(i=!1)),d.prototype.eventNames=function(){var l,u,h=[];if(this._eventsCount===0)return h;for(u in l=this._events)n.call(l,u)&&h.push(i?u.slice(1):u);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(l)):h},d.prototype.listeners=function(l){var u=i?i+l:l,h=this._events[u];if(!h)return[];if(h.fn)return[h.fn];for(var b=0,_=h.length,v=new Array(_);b<_;b++)v[b]=h[b].fn;return v},d.prototype.listenerCount=function(l){var u=i?i+l:l,h=this._events[u];return h?h.fn?1:h.length:0},d.prototype.emit=function(l,u,h,b,_,v){var y=i?i+l:l;if(!this._events[y])return!1;var m,f,p=this._events[y],g=arguments.length;if(p.fn){switch(p.once&&this.removeListener(l,p.fn,void 0,!0),g){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,u),!0;case 3:return p.fn.call(p.context,u,h),!0;case 4:return p.fn.call(p.context,u,h,b),!0;case 5:return p.fn.call(p.context,u,h,b,_),!0;case 6:return p.fn.call(p.context,u,h,b,_,v),!0}for(f=1,m=new Array(g-1);f<g;f++)m[f-1]=arguments[f];p.fn.apply(p.context,m)}else{var E,w=p.length;for(f=0;f<w;f++)switch(p[f].once&&this.removeListener(l,p[f].fn,void 0,!0),g){case 1:p[f].fn.call(p[f].context);break;case 2:p[f].fn.call(p[f].context,u);break;case 3:p[f].fn.call(p[f].context,u,h);break;case 4:p[f].fn.call(p[f].context,u,h,b);break;default:if(!m)for(E=1,m=new Array(g-1);E<g;E++)m[E-1]=arguments[E];p[f].fn.apply(p[f].context,m)}}return!0},d.prototype.on=function(l,u,h){return a(this,l,u,h,!1)},d.prototype.once=function(l,u,h){return a(this,l,u,h,!0)},d.prototype.removeListener=function(l,u,h,b){var _=i?i+l:l;if(!this._events[_])return this;if(!u)return c(this,_),this;var v=this._events[_];if(v.fn)v.fn!==u||b&&!v.once||h&&v.context!==h||c(this,_);else{for(var y=0,m=[],f=v.length;y<f;y++)(v[y].fn!==u||b&&!v[y].once||h&&v[y].context!==h)&&m.push(v[y]);m.length?this._events[_]=m.length===1?m[0]:m:c(this,_)}return this},d.prototype.removeAllListeners=function(l){var u;return l?(u=i?i+l:l,this._events[u]&&c(this,u)):(this._events=new r,this._eventsCount=0),this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prefixed=i,d.EventEmitter=d,typeof e<"u"&&(e.exports=d)},{}],WOs9:[function(o,e,t){"use strict";var n=this&&this.__read||function(c,d){var l=typeof Symbol=="function"&&c[Symbol.iterator];if(!l)return c;var u,h,b=l.call(c),_=[];try{for(;(d===void 0||d-- >0)&&!(u=b.next()).done;)_.push(u.value)}catch(v){h={error:v}}finally{try{u&&!u.done&&(l=b.return)&&l.call(b)}finally{if(h)throw h.error}}return _},i=this&&this.__spreadArray||function(c,d){for(var l=0,u=d.length,h=c.length;l<u;l++,h++)c[h]=d[l];return c};Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0;var r,s="PeerJS: ";(function(c){c[c.Disabled=0]="Disabled",c[c.Errors=1]="Errors",c[c.Warnings=2]="Warnings",c[c.All=3]="All"})(r=t.LogLevel||(t.LogLevel={}));var a=function(){function c(){this._logLevel=r.Disabled}return Object.defineProperty(c.prototype,"logLevel",{get:function(){return this._logLevel},set:function(d){this._logLevel=d},enumerable:!1,configurable:!0}),c.prototype.log=function(){for(var d=[],l=0;l<arguments.length;l++)d[l]=arguments[l];this._logLevel>=r.All&&this._print.apply(this,i([r.All],n(d)))},c.prototype.warn=function(){for(var d=[],l=0;l<arguments.length;l++)d[l]=arguments[l];this._logLevel>=r.Warnings&&this._print.apply(this,i([r.Warnings],n(d)))},c.prototype.error=function(){for(var d=[],l=0;l<arguments.length;l++)d[l]=arguments[l];this._logLevel>=r.Errors&&this._print.apply(this,i([r.Errors],n(d)))},c.prototype.setLogFunction=function(d){this._print=d},c.prototype._print=function(d){for(var l=[],u=1;u<arguments.length;u++)l[u-1]=arguments[u];var h=i([s],n(l));for(var b in h)h[b]instanceof Error&&(h[b]="("+h[b].name+") "+h[b].message);d>=r.All?console.log.apply(console,i([],n(h))):d>=r.Warnings?console.warn.apply(console,i(["WARNING"],n(h))):d>=r.Errors&&console.error.apply(console,i(["ERROR"],n(h)))},c}();t.default=new a},{}],ZRYf:[function(o,e,t){"use strict";var n,i,r,s,a,c,d;Object.defineProperty(t,"__esModule",{value:!0}),t.ServerMessageType=t.SocketEventType=t.SerializationType=t.PeerErrorType=t.PeerEventType=t.ConnectionType=t.ConnectionEventType=void 0,function(l){l.Open="open",l.Stream="stream",l.Data="data",l.Close="close",l.Error="error",l.IceStateChanged="iceStateChanged"}(n=t.ConnectionEventType||(t.ConnectionEventType={})),function(l){l.Data="data",l.Media="media"}(i=t.ConnectionType||(t.ConnectionType={})),function(l){l.Open="open",l.Close="close",l.Connection="connection",l.Call="call",l.Disconnected="disconnected",l.Error="error"}(r=t.PeerEventType||(t.PeerEventType={})),function(l){l.BrowserIncompatible="browser-incompatible",l.Disconnected="disconnected",l.InvalidID="invalid-id",l.InvalidKey="invalid-key",l.Network="network",l.PeerUnavailable="peer-unavailable",l.SslUnavailable="ssl-unavailable",l.ServerError="server-error",l.SocketError="socket-error",l.SocketClosed="socket-closed",l.UnavailableID="unavailable-id",l.WebRTC="webrtc"}(s=t.PeerErrorType||(t.PeerErrorType={})),function(l){l.Binary="binary",l.BinaryUTF8="binary-utf8",l.JSON="json"}(a=t.SerializationType||(t.SerializationType={})),function(l){l.Message="message",l.Disconnected="disconnected",l.Error="error",l.Close="close"}(c=t.SocketEventType||(t.SocketEventType={})),function(l){l.Heartbeat="HEARTBEAT",l.Candidate="CANDIDATE",l.Offer="OFFER",l.Answer="ANSWER",l.Open="OPEN",l.Error="ERROR",l.IdTaken="ID-TAKEN",l.InvalidKey="INVALID-KEY",l.Leave="LEAVE",l.Expire="EXPIRE"}(d=t.ServerMessageType||(t.ServerMessageType={}))},{}],wJlv:[function(o,e,t){"use strict";var n=this&&this.__extends||function(){var h=function(b,_){return(h=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(v,y){v.__proto__=y}||function(v,y){for(var m in y)Object.prototype.hasOwnProperty.call(y,m)&&(v[m]=y[m])})(b,_)};return function(b,_){if(typeof _!="function"&&_!==null)throw new TypeError("Class extends value "+String(_)+" is not a constructor or null");function v(){this.constructor=b}h(b,_),b.prototype=_===null?Object.create(_):(v.prototype=_.prototype,new v)}}(),i=this&&this.__read||function(h,b){var _=typeof Symbol=="function"&&h[Symbol.iterator];if(!_)return h;var v,y,m=_.call(h),f=[];try{for(;(b===void 0||b-- >0)&&!(v=m.next()).done;)f.push(v.value)}catch(p){y={error:p}}finally{try{v&&!v.done&&(_=m.return)&&_.call(m)}finally{if(y)throw y.error}}return f},r=this&&this.__spreadArray||function(h,b){for(var _=0,v=b.length,y=h.length;_<v;_++,y++)h[y]=b[_];return h},s=this&&this.__values||function(h){var b=typeof Symbol=="function"&&Symbol.iterator,_=b&&h[b],v=0;if(_)return _.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&v>=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(b?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;var c=o("eventemitter3"),d=a(o("./logger")),l=o("./enums"),u=function(h){function b(_,v,y,m,f,p){p===void 0&&(p=5e3);var g=h.call(this)||this;g.pingInterval=p,g._disconnected=!0,g._messagesQueue=[];var E=_?"wss://":"ws://";return g._baseUrl=E+v+":"+y+m+"peerjs?key="+f,g}return n(b,h),b.prototype.start=function(_,v){var y=this;this._id=_;var m=this._baseUrl+"&id="+_+"&token="+v;!this._socket&&this._disconnected&&(this._socket=new WebSocket(m),this._disconnected=!1,this._socket.onmessage=function(f){var p;try{p=JSON.parse(f.data),d.default.log("Server message received:",p)}catch{return void d.default.log("Invalid server message",f.data)}y.emit(l.SocketEventType.Message,p)},this._socket.onclose=function(f){y._disconnected||(d.default.log("Socket closed.",f),y._cleanup(),y._disconnected=!0,y.emit(l.SocketEventType.Disconnected))},this._socket.onopen=function(){y._disconnected||(y._sendQueuedMessages(),d.default.log("Socket open"),y._scheduleHeartbeat())})},b.prototype._scheduleHeartbeat=function(){var _=this;this._wsPingTimer=setTimeout(function(){_._sendHeartbeat()},this.pingInterval)},b.prototype._sendHeartbeat=function(){if(this._wsOpen()){var _=JSON.stringify({type:l.ServerMessageType.Heartbeat});this._socket.send(_),this._scheduleHeartbeat()}else d.default.log("Cannot send heartbeat, because socket closed")},b.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},b.prototype._sendQueuedMessages=function(){var _,v,y=r([],i(this._messagesQueue));this._messagesQueue=[];try{for(var m=s(y),f=m.next();!f.done;f=m.next()){var p=f.value;this.send(p)}}catch(g){_={error:g}}finally{try{f&&!f.done&&(v=m.return)&&v.call(m)}finally{if(_)throw _.error}}},b.prototype.send=function(_){if(!this._disconnected)if(this._id)if(_.type){if(this._wsOpen()){var v=JSON.stringify(_);this._socket.send(v)}}else this.emit(l.SocketEventType.Error,"Invalid message");else this._messagesQueue.push(_)},b.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},b.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},b}(c.EventEmitter);t.Socket=u},{eventemitter3:"JJlS","./logger":"WOs9","./enums":"ZRYf"}],HCdX:[function(o,e,t){"use strict";var n=this&&this.__assign||function(){return(n=Object.assign||function(u){for(var h,b=1,_=arguments.length;b<_;b++)for(var v in h=arguments[b])Object.prototype.hasOwnProperty.call(h,v)&&(u[v]=h[v]);return u}).apply(this,arguments)},i=this&&this.__awaiter||function(u,h,b,_){return new(b||(b=Promise))(function(v,y){function m(g){try{p(_.next(g))}catch(E){y(E)}}function f(g){try{p(_.throw(g))}catch(E){y(E)}}function p(g){var E;g.done?v(g.value):(E=g.value,E instanceof b?E:new b(function(w){w(E)})).then(m,f)}p((_=_.apply(u,h||[])).next())})},r=this&&this.__generator||function(u,h){var b,_,v,y,m={label:0,sent:function(){if(1&v[0])throw v[1];return v[1]},trys:[],ops:[]};return y={next:f(0),throw:f(1),return:f(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function f(p){return function(g){return function(E){if(b)throw new TypeError("Generator is already executing.");for(;m;)try{if(b=1,_&&(v=2&E[0]?_.return:E[0]?_.throw||((v=_.return)&&v.call(_),0):_.next)&&!(v=v.call(_,E[1])).done)return v;switch(_=0,v&&(E=[2&E[0],v.value]),E[0]){case 0:case 1:v=E;break;case 4:return m.label++,{value:E[1],done:!1};case 5:m.label++,_=E[1],E=[0];continue;case 7:E=m.ops.pop(),m.trys.pop();continue;default:if(!(v=(v=m.trys).length>0&&v[v.length-1])&&(E[0]===6||E[0]===2)){m=0;continue}if(E[0]===3&&(!v||E[1]>v[0]&&E[1]<v[3])){m.label=E[1];break}if(E[0]===6&&m.label<v[1]){m.label=v[1],v=E;break}if(v&&m.label<v[2]){m.label=v[2],m.ops.push(E);break}v[2]&&m.ops.pop(),m.trys.pop();continue}E=h.call(u,m)}catch(w){E=[6,w],_=0}finally{b=v=0}if(5&E[0])throw E[1];return{value:E[0]?E[1]:void 0,done:!0}}([p,g])}}},s=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.Negotiator=void 0;var a=o("./util"),c=s(o("./logger")),d=o("./enums"),l=function(){function u(h){this.connection=h}return u.prototype.startConnection=function(h){var b=this._startPeerConnection();if(this.connection.peerConnection=b,this.connection.type===d.ConnectionType.Media&&h._stream&&this._addTracksToConnection(h._stream,b),h.originator){if(this.connection.type===d.ConnectionType.Data){var _=this.connection,v={ordered:!!h.reliable},y=b.createDataChannel(_.label,v);_.initialize(y)}this._makeOffer()}else this.handleSDP("OFFER",h.sdp)},u.prototype._startPeerConnection=function(){c.default.log("Creating RTCPeerConnection.");var h=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(h),h},u.prototype._setupListeners=function(h){var b=this,_=this.connection.peer,v=this.connection.connectionId,y=this.connection.type,m=this.connection.provider;c.default.log("Listening for ICE candidates."),h.onicecandidate=function(f){f.candidate&&f.candidate.candidate&&(c.default.log("Received ICE candidates for "+_+":",f.candidate),m.socket.send({type:d.ServerMessageType.Candidate,payload:{candidate:f.candidate,type:y,connectionId:v},dst:_}))},h.oniceconnectionstatechange=function(){switch(h.iceConnectionState){case"failed":c.default.log("iceConnectionState is failed, closing connections to "+_),b.connection.emit(d.ConnectionEventType.Error,new Error("Negotiation of connection to "+_+" failed.")),b.connection.close();break;case"closed":c.default.log("iceConnectionState is closed, closing connections to "+_),b.connection.emit(d.ConnectionEventType.Error,new Error("Connection to "+_+" closed.")),b.connection.close();break;case"disconnected":c.default.log("iceConnectionState changed to disconnected on the connection with "+_);break;case"completed":h.onicecandidate=a.util.noop}b.connection.emit(d.ConnectionEventType.IceStateChanged,h.iceConnectionState)},c.default.log("Listening for data channel"),h.ondatachannel=function(f){c.default.log("Received data channel");var p=f.channel;m.getConnection(_,v).initialize(p)},c.default.log("Listening for remote stream"),h.ontrack=function(f){c.default.log("Received remote stream");var p=f.streams[0],g=m.getConnection(_,v);if(g.type===d.ConnectionType.Media){var E=g;b._addStreamToMediaConnection(p,E)}}},u.prototype.cleanup=function(){c.default.log("Cleaning up PeerConnection to "+this.connection.peer);var h=this.connection.peerConnection;if(h){this.connection.peerConnection=null,h.onicecandidate=h.oniceconnectionstatechange=h.ondatachannel=h.ontrack=function(){};var b=h.signalingState!=="closed",_=!1;if(this.connection.type===d.ConnectionType.Data){var v=this.connection.dataChannel;v&&(_=!!v.readyState&&v.readyState!=="closed")}(b||_)&&h.close()}},u.prototype._makeOffer=function(){return i(this,void 0,Promise,function(){var h,b,_,v,y,m,f;return r(this,function(p){switch(p.label){case 0:h=this.connection.peerConnection,b=this.connection.provider,p.label=1;case 1:return p.trys.push([1,7,,8]),[4,h.createOffer(this.connection.options.constraints)];case 2:_=p.sent(),c.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(_.sdp=this.connection.options.sdpTransform(_.sdp)||_.sdp),p.label=3;case 3:return p.trys.push([3,5,,6]),[4,h.setLocalDescription(_)];case 4:return p.sent(),c.default.log("Set localDescription:",_,"for:"+this.connection.peer),v={sdp:_,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:a.util.browser},this.connection.type===d.ConnectionType.Data&&(y=this.connection,v=n(n({},v),{label:y.label,reliable:y.reliable,serialization:y.serialization})),b.socket.send({type:d.ServerMessageType.Offer,payload:v,dst:this.connection.peer}),[3,6];case 5:return(m=p.sent())!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(b.emitError(d.PeerErrorType.WebRTC,m),c.default.log("Failed to setLocalDescription, ",m)),[3,6];case 6:return[3,8];case 7:return f=p.sent(),b.emitError(d.PeerErrorType.WebRTC,f),c.default.log("Failed to createOffer, ",f),[3,8];case 8:return[2]}})})},u.prototype._makeAnswer=function(){return i(this,void 0,Promise,function(){var h,b,_,v,y;return r(this,function(m){switch(m.label){case 0:h=this.connection.peerConnection,b=this.connection.provider,m.label=1;case 1:return m.trys.push([1,7,,8]),[4,h.createAnswer()];case 2:_=m.sent(),c.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(_.sdp=this.connection.options.sdpTransform(_.sdp)||_.sdp),m.label=3;case 3:return m.trys.push([3,5,,6]),[4,h.setLocalDescription(_)];case 4:return m.sent(),c.default.log("Set localDescription:",_,"for:"+this.connection.peer),b.socket.send({type:d.ServerMessageType.Answer,payload:{sdp:_,type:this.connection.type,connectionId:this.connection.connectionId,browser:a.util.browser},dst:this.connection.peer}),[3,6];case 5:return v=m.sent(),b.emitError(d.PeerErrorType.WebRTC,v),c.default.log("Failed to setLocalDescription, ",v),[3,6];case 6:return[3,8];case 7:return y=m.sent(),b.emitError(d.PeerErrorType.WebRTC,y),c.default.log("Failed to create answer, ",y),[3,8];case 8:return[2]}})})},u.prototype.handleSDP=function(h,b){return i(this,void 0,Promise,function(){var _,v,y,m;return r(this,function(f){switch(f.label){case 0:b=new RTCSessionDescription(b),_=this.connection.peerConnection,v=this.connection.provider,c.default.log("Setting remote description",b),y=this,f.label=1;case 1:return f.trys.push([1,5,,6]),[4,_.setRemoteDescription(b)];case 2:return f.sent(),c.default.log("Set remoteDescription:"+h+" for:"+this.connection.peer),h!=="OFFER"?[3,4]:[4,y._makeAnswer()];case 3:f.sent(),f.label=4;case 4:return[3,6];case 5:return m=f.sent(),v.emitError(d.PeerErrorType.WebRTC,m),c.default.log("Failed to setRemoteDescription, ",m),[3,6];case 6:return[2]}})})},u.prototype.handleCandidate=function(h){return i(this,void 0,Promise,function(){var b,_,v,y,m,f;return r(this,function(p){switch(p.label){case 0:c.default.log("handleCandidate:",h),b=h.candidate,_=h.sdpMLineIndex,v=h.sdpMid,y=this.connection.peerConnection,m=this.connection.provider,p.label=1;case 1:return p.trys.push([1,3,,4]),[4,y.addIceCandidate(new RTCIceCandidate({sdpMid:v,sdpMLineIndex:_,candidate:b}))];case 2:return p.sent(),c.default.log("Added ICE candidate for:"+this.connection.peer),[3,4];case 3:return f=p.sent(),m.emitError(d.PeerErrorType.WebRTC,f),c.default.log("Failed to handleCandidate, ",f),[3,4];case 4:return[2]}})})},u.prototype._addTracksToConnection=function(h,b){if(c.default.log("add tracks from stream "+h.id+" to peer connection"),!b.addTrack)return c.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");h.getTracks().forEach(function(_){b.addTrack(_,h)})},u.prototype._addStreamToMediaConnection=function(h,b){c.default.log("add stream "+h.id+" to media connection "+b.connectionId),b.addStream(h)},u}();t.Negotiator=l},{"./util":"BHXf","./logger":"WOs9","./enums":"ZRYf"}],tQFK:[function(o,e,t){"use strict";var n=this&&this.__extends||function(){var s=function(a,c){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,l){d.__proto__=l}||function(d,l){for(var u in l)Object.prototype.hasOwnProperty.call(l,u)&&(d[u]=l[u])})(a,c)};return function(a,c){if(typeof c!="function"&&c!==null)throw new TypeError("Class extends value "+String(c)+" is not a constructor or null");function d(){this.constructor=a}s(a,c),a.prototype=c===null?Object.create(c):(d.prototype=c.prototype,new d)}}();Object.defineProperty(t,"__esModule",{value:!0}),t.BaseConnection=void 0;var i=o("eventemitter3"),r=function(s){function a(c,d,l){var u=s.call(this)||this;return u.peer=c,u.provider=d,u.options=l,u._open=!1,u.metadata=l.metadata,u}return n(a,s),Object.defineProperty(a.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),a}(i.EventEmitter);t.BaseConnection=r},{eventemitter3:"JJlS"}],dbHP:[function(o,e,t){"use strict";var n=this&&this.__extends||function(){var b=function(_,v){return(b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,m){y.__proto__=m}||function(y,m){for(var f in m)Object.prototype.hasOwnProperty.call(m,f)&&(y[f]=m[f])})(_,v)};return function(_,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function y(){this.constructor=_}b(_,v),_.prototype=v===null?Object.create(v):(y.prototype=v.prototype,new y)}}(),i=this&&this.__assign||function(){return(i=Object.assign||function(b){for(var _,v=1,y=arguments.length;v<y;v++)for(var m in _=arguments[v])Object.prototype.hasOwnProperty.call(_,m)&&(b[m]=_[m]);return b}).apply(this,arguments)},r=this&&this.__values||function(b){var _=typeof Symbol=="function"&&Symbol.iterator,v=_&&b[_],y=0;if(v)return v.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&y>=b.length&&(b=void 0),{value:b&&b[y++],done:!b}}};throw new TypeError(_?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(t,"__esModule",{value:!0}),t.MediaConnection=void 0;var a=o("./util"),c=s(o("./logger")),d=o("./negotiator"),l=o("./enums"),u=o("./baseconnection"),h=function(b){function _(v,y,m){var f=b.call(this,v,y,m)||this;return f._localStream=f.options._stream,f.connectionId=f.options.connectionId||_.ID_PREFIX+a.util.randomToken(),f._negotiator=new d.Negotiator(f),f._localStream&&f._negotiator.startConnection({_stream:f._localStream,originator:!0}),f}return n(_,b),Object.defineProperty(_.prototype,"type",{get:function(){return l.ConnectionType.Media},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),_.prototype.addStream=function(v){c.default.log("Receiving stream",v),this._remoteStream=v,b.prototype.emit.call(this,l.ConnectionEventType.Stream,v)},_.prototype.handleMessage=function(v){var y=v.type,m=v.payload;switch(v.type){case l.ServerMessageType.Answer:this._negotiator.handleSDP(y,m.sdp),this._open=!0;break;case l.ServerMessageType.Candidate:this._negotiator.handleCandidate(m.candidate);break;default:c.default.warn("Unrecognized message type:"+y+" from peer:"+this.peer)}},_.prototype.answer=function(v,y){var m,f;if(y===void 0&&(y={}),this._localStream)c.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");else{this._localStream=v,y&&y.sdpTransform&&(this.options.sdpTransform=y.sdpTransform),this._negotiator.startConnection(i(i({},this.options._payload),{_stream:v}));var p=this.provider._getMessages(this.connectionId);try{for(var g=r(p),E=g.next();!E.done;E=g.next()){var w=E.value;this.handleMessage(w)}}catch(T){m={error:T}}finally{try{E&&!E.done&&(f=g.return)&&f.call(g)}finally{if(m)throw m.error}}this._open=!0}},_.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,b.prototype.emit.call(this,l.ConnectionEventType.Close))},_.ID_PREFIX="mc_",_}(u.BaseConnection);t.MediaConnection=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK"}],GGp6:[function(o,e,t){"use strict";var n=this&&this.__extends||function(){var c=function(d,l){return(c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,h){u.__proto__=h}||function(u,h){for(var b in h)Object.prototype.hasOwnProperty.call(h,b)&&(u[b]=h[b])})(d,l)};return function(d,l){if(typeof l!="function"&&l!==null)throw new TypeError("Class extends value "+String(l)+" is not a constructor or null");function u(){this.constructor=d}c(d,l),d.prototype=l===null?Object.create(l):(u.prototype=l.prototype,new u)}}(),i=this&&this.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(t,"__esModule",{value:!0}),t.EncodingQueue=void 0;var r=o("eventemitter3"),s=i(o("./logger")),a=function(c){function d(){var l=c.call(this)||this;return l.fileReader=new FileReader,l._queue=[],l._processing=!1,l.fileReader.onload=function(u){l._processing=!1,u.target&&l.emit("done",u.target.result),l.doNextTask()},l.fileReader.onerror=function(u){s.default.error("EncodingQueue error:",u),l._processing=!1,l.destroy(),l.emit("error",u)},l}return n(d,c),Object.defineProperty(d.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(d.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),d.prototype.enque=function(l){this.queue.push(l),this.processing||this.doNextTask()},d.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},d.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},d}(r.EventEmitter);t.EncodingQueue=a},{eventemitter3:"JJlS","./logger":"WOs9"}],GBTQ:[function(o,e,t){"use strict";var n=this&&this.__extends||function(){var b=function(_,v){return(b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,m){y.__proto__=m}||function(y,m){for(var f in m)Object.prototype.hasOwnProperty.call(m,f)&&(y[f]=m[f])})(_,v)};return function(_,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function y(){this.constructor=_}b(_,v),_.prototype=v===null?Object.create(v):(y.prototype=v.prototype,new y)}}(),i=this&&this.__values||function(b){var _=typeof Symbol=="function"&&Symbol.iterator,v=_&&b[_],y=0;if(v)return v.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&y>=b.length&&(b=void 0),{value:b&&b[y++],done:!b}}};throw new TypeError(_?"Object is not iterable.":"Symbol.iterator is not defined.")},r=this&&this.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnection=void 0;var s=o("./util"),a=r(o("./logger")),c=o("./negotiator"),d=o("./enums"),l=o("./baseconnection"),u=o("./encodingQueue"),h=function(b){function _(v,y,m){var f=b.call(this,v,y,m)||this;return f.stringify=JSON.stringify,f.parse=JSON.parse,f._buffer=[],f._bufferSize=0,f._buffering=!1,f._chunkedData={},f._encodingQueue=new u.EncodingQueue,f.connectionId=f.options.connectionId||_.ID_PREFIX+s.util.randomToken(),f.label=f.options.label||f.connectionId,f.serialization=f.options.serialization||d.SerializationType.Binary,f.reliable=!!f.options.reliable,f._encodingQueue.on("done",function(p){f._bufferedSend(p)}),f._encodingQueue.on("error",function(){a.default.error("DC#"+f.connectionId+": Error occured in encoding from blob to arraybuffer, close DC"),f.close()}),f._negotiator=new c.Negotiator(f),f._negotiator.startConnection(f.options._payload||{originator:!0}),f}return n(_,b),Object.defineProperty(_.prototype,"type",{get:function(){return d.ConnectionType.Data},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),_.prototype.initialize=function(v){this._dc=v,this._configureDataChannel()},_.prototype._configureDataChannel=function(){var v=this;s.util.supports.binaryBlob&&!s.util.supports.reliable||(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){a.default.log("DC#"+v.connectionId+" dc connection success"),v._open=!0,v.emit(d.ConnectionEventType.Open)},this.dataChannel.onmessage=function(y){a.default.log("DC#"+v.connectionId+" dc onmessage:",y.data),v._handleDataMessage(y)},this.dataChannel.onclose=function(){a.default.log("DC#"+v.connectionId+" dc closed for:",v.peer),v.close()}},_.prototype._handleDataMessage=function(v){var y=this,m=v.data,f=m.constructor,p=m;if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){if(f===Blob)return void s.util.blobToArrayBuffer(m,function(E){var w=s.util.unpack(E);y.emit(d.ConnectionEventType.Data,w)});if(f===ArrayBuffer)p=s.util.unpack(m);else if(f===String){var g=s.util.binaryStringToArrayBuffer(m);p=s.util.unpack(g)}}else this.serialization===d.SerializationType.JSON&&(p=this.parse(m));p.__peerData?this._handleChunk(p):b.prototype.emit.call(this,d.ConnectionEventType.Data,p)},_.prototype._handleChunk=function(v){var y=v.__peerData,m=this._chunkedData[y]||{data:[],count:0,total:v.total};if(m.data[v.n]=v.data,m.count++,this._chunkedData[y]=m,m.total===m.count){delete this._chunkedData[y];var f=new Blob(m.data);this._handleDataMessage({data:f})}},_.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,b.prototype.emit.call(this,d.ConnectionEventType.Close))},_.prototype.send=function(v,y){if(this.open)if(this.serialization===d.SerializationType.JSON)this._bufferedSend(this.stringify(v));else if(this.serialization===d.SerializationType.Binary||this.serialization===d.SerializationType.BinaryUTF8){var m=s.util.pack(v);if(!y&&m.size>s.util.chunkedMTU)return void this._sendChunks(m);s.util.supports.binaryBlob?this._bufferedSend(m):this._encodingQueue.enque(m)}else this._bufferedSend(v);else b.prototype.emit.call(this,d.ConnectionEventType.Error,new Error("Connection is not open. You should listen for the `open` event before sending messages."))},_.prototype._bufferedSend=function(v){!this._buffering&&this._trySend(v)||(this._buffer.push(v),this._bufferSize=this._buffer.length)},_.prototype._trySend=function(v){var y=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>_.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){y._buffering=!1,y._tryBuffer()},50),!1;try{this.dataChannel.send(v)}catch(m){return a.default.error("DC#:"+this.connectionId+" Error when sending:",m),this._buffering=!0,this.close(),!1}return!0},_.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var v=this._buffer[0];this._trySend(v)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},_.prototype._sendChunks=function(v){var y,m,f=s.util.chunk(v);a.default.log("DC#"+this.connectionId+" Try to send "+f.length+" chunks...");try{for(var p=i(f),g=p.next();!g.done;g=p.next()){var E=g.value;this.send(E,!0)}}catch(w){y={error:w}}finally{try{g&&!g.done&&(m=p.return)&&m.call(p)}finally{if(y)throw y.error}}},_.prototype.handleMessage=function(v){var y=v.payload;switch(v.type){case d.ServerMessageType.Answer:this._negotiator.handleSDP(v.type,y.sdp);break;case d.ServerMessageType.Candidate:this._negotiator.handleCandidate(y.candidate);break;default:a.default.warn("Unrecognized message type:",v.type,"from peer:",this.peer)}},_.ID_PREFIX="dc_",_.MAX_BUFFERED_AMOUNT=8388608,_}(l.BaseConnection);t.DataConnection=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK","./encodingQueue":"GGp6"}],in7L:[function(o,e,t){"use strict";var n=this&&this.__awaiter||function(d,l,u,h){return new(u||(u=Promise))(function(b,_){function v(f){try{m(h.next(f))}catch(p){_(p)}}function y(f){try{m(h.throw(f))}catch(p){_(p)}}function m(f){var p;f.done?b(f.value):(p=f.value,p instanceof u?p:new u(function(g){g(p)})).then(v,y)}m((h=h.apply(d,l||[])).next())})},i=this&&this.__generator||function(d,l){var u,h,b,_,v={label:0,sent:function(){if(1&b[0])throw b[1];return b[1]},trys:[],ops:[]};return _={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(_[Symbol.iterator]=function(){return this}),_;function y(m){return function(f){return function(p){if(u)throw new TypeError("Generator is already executing.");for(;v;)try{if(u=1,h&&(b=2&p[0]?h.return:p[0]?h.throw||((b=h.return)&&b.call(h),0):h.next)&&!(b=b.call(h,p[1])).done)return b;switch(h=0,b&&(p=[2&p[0],b.value]),p[0]){case 0:case 1:b=p;break;case 4:return v.label++,{value:p[1],done:!1};case 5:v.label++,h=p[1],p=[0];continue;case 7:p=v.ops.pop(),v.trys.pop();continue;default:if(!(b=(b=v.trys).length>0&&b[b.length-1])&&(p[0]===6||p[0]===2)){v=0;continue}if(p[0]===3&&(!b||p[1]>b[0]&&p[1]<b[3])){v.label=p[1];break}if(p[0]===6&&v.label<b[1]){v.label=b[1],b=p;break}if(b&&v.label<b[2]){v.label=b[2],v.ops.push(p);break}b[2]&&v.ops.pop(),v.trys.pop();continue}p=l.call(d,v)}catch(g){p=[6,g],h=0}finally{u=b=0}if(5&p[0])throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}([m,f])}}},r=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(t,"__esModule",{value:!0}),t.API=void 0;var s=o("./util"),a=r(o("./logger")),c=function(){function d(l){this._options=l}return d.prototype._buildUrl=function(l){var u=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+l;return u+="?ts="+new Date().getTime()+Math.random()},d.prototype.retrieveId=function(){return n(this,void 0,Promise,function(){var l,u,h,b;return i(this,function(_){switch(_.label){case 0:l=this._buildUrl("id"),_.label=1;case 1:return _.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((u=_.sent()).status!==200)throw new Error("Error. Status:"+u.status);return[2,u.text()];case 3:throw h=_.sent(),a.default.error("Error retrieving ID",h),b="",this._options.path==="/"&&this._options.host!==s.util.CLOUD_HOST&&(b=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+b);case 4:return[2]}})})},d.prototype.listAllPeers=function(){return n(this,void 0,Promise,function(){var l,u,h,b;return i(this,function(_){switch(_.label){case 0:l=this._buildUrl("peers"),_.label=1;case 1:return _.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((u=_.sent()).status!==200)throw u.status===401?(h="",h=this._options.host===s.util.CLOUD_HOST?"It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":"You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+h)):new Error("Error. Status:"+u.status);return[2,u.json()];case 3:throw b=_.sent(),a.default.error("Error retrieving list peers",b),new Error("Could not get list peers from the server."+b);case 4:return[2]}})})},d}();t.API=c},{"./util":"BHXf","./logger":"WOs9"}],Hxpd:[function(o,e,t){"use strict";var n=this&&this.__extends||function(){var f=function(p,g){return(f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(E,w){E.__proto__=w}||function(E,w){for(var T in w)Object.prototype.hasOwnProperty.call(w,T)&&(E[T]=w[T])})(p,g)};return function(p,g){if(typeof g!="function"&&g!==null)throw new TypeError("Class extends value "+String(g)+" is not a constructor or null");function E(){this.constructor=p}f(p,g),p.prototype=g===null?Object.create(g):(E.prototype=g.prototype,new E)}}(),i=this&&this.__assign||function(){return(i=Object.assign||function(f){for(var p,g=1,E=arguments.length;g<E;g++)for(var w in p=arguments[g])Object.prototype.hasOwnProperty.call(p,w)&&(f[w]=p[w]);return f}).apply(this,arguments)},r=this&&this.__values||function(f){var p=typeof Symbol=="function"&&Symbol.iterator,g=p&&f[p],E=0;if(g)return g.call(f);if(f&&typeof f.length=="number")return{next:function(){return f&&E>=f.length&&(f=void 0),{value:f&&f[E++],done:!f}}};throw new TypeError(p?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__read||function(f,p){var g=typeof Symbol=="function"&&f[Symbol.iterator];if(!g)return f;var E,w,T=g.call(f),S=[];try{for(;(p===void 0||p-- >0)&&!(E=T.next()).done;)S.push(E.value)}catch(k){w={error:k}}finally{try{E&&!E.done&&(g=T.return)&&g.call(T)}finally{if(w)throw w.error}}return S},a=this&&this.__importDefault||function(f){return f&&f.__esModule?f:{default:f}};Object.defineProperty(t,"__esModule",{value:!0}),t.Peer=void 0;var c=o("eventemitter3"),d=o("./util"),l=a(o("./logger")),u=o("./socket"),h=o("./mediaconnection"),b=o("./dataconnection"),_=o("./enums"),v=o("./api"),y=function(){return function(){}}(),m=function(f){function p(g,E){var w,T=f.call(this)||this;return T._id=null,T._lastServerId=null,T._destroyed=!1,T._disconnected=!1,T._open=!1,T._connections=new Map,T._lostMessages=new Map,g&&g.constructor==Object?E=g:g&&(w=g.toString()),E=i({debug:0,host:d.util.CLOUD_HOST,port:d.util.CLOUD_PORT,path:"/",key:p.DEFAULT_KEY,token:d.util.randomToken(),config:d.util.defaultConfig},E),T._options=E,T._options.host==="/"&&(T._options.host=window.location.hostname),T._options.path&&(T._options.path[0]!=="/"&&(T._options.path="/"+T._options.path),T._options.path[T._options.path.length-1]!=="/"&&(T._options.path+="/")),T._options.secure===void 0&&T._options.host!==d.util.CLOUD_HOST?T._options.secure=d.util.isSecure():T._options.host==d.util.CLOUD_HOST&&(T._options.secure=!0),T._options.logFunction&&l.default.setLogFunction(T._options.logFunction),l.default.logLevel=T._options.debug||0,T._api=new v.API(E),T._socket=T._createServerConnection(),d.util.supports.audioVideo||d.util.supports.data?w&&!d.util.validateId(w)?(T._delayedAbort(_.PeerErrorType.InvalidID,'ID "'+w+'" is invalid'),T):(w?T._initialize(w):T._api.retrieveId().then(function(S){return T._initialize(S)}).catch(function(S){return T._abort(_.PeerErrorType.ServerError,S)}),T):(T._delayedAbort(_.PeerErrorType.BrowserIncompatible,"The current browser does not support WebRTC"),T)}return n(p,f),Object.defineProperty(p.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"connections",{get:function(){var g,E,w=Object.create(null);try{for(var T=r(this._connections),S=T.next();!S.done;S=T.next()){var k=s(S.value,2),D=k[0],P=k[1];w[D]=P}}catch(H){g={error:H}}finally{try{S&&!S.done&&(E=T.return)&&E.call(T)}finally{if(g)throw g.error}}return w},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),p.prototype._createServerConnection=function(){var g=this,E=new u.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return E.on(_.SocketEventType.Message,function(w){g._handleMessage(w)}),E.on(_.SocketEventType.Error,function(w){g._abort(_.PeerErrorType.SocketError,w)}),E.on(_.SocketEventType.Disconnected,function(){g.disconnected||(g.emitError(_.PeerErrorType.Network,"Lost connection to server."),g.disconnect())}),E.on(_.SocketEventType.Close,function(){g.disconnected||g._abort(_.PeerErrorType.SocketClosed,"Underlying socket is already closed.")}),E},p.prototype._initialize=function(g){this._id=g,this.socket.start(g,this._options.token)},p.prototype._handleMessage=function(g){var E,w,T=g.type,S=g.payload,k=g.src;switch(T){case _.ServerMessageType.Open:this._lastServerId=this.id,this._open=!0,this.emit(_.PeerEventType.Open,this.id);break;case _.ServerMessageType.Error:this._abort(_.PeerErrorType.ServerError,S.msg);break;case _.ServerMessageType.IdTaken:this._abort(_.PeerErrorType.UnavailableID,'ID "'+this.id+'" is taken');break;case _.ServerMessageType.InvalidKey:this._abort(_.PeerErrorType.InvalidKey,'API KEY "'+this._options.key+'" is invalid');break;case _.ServerMessageType.Leave:l.default.log("Received leave message from "+k),this._cleanupPeer(k),this._connections.delete(k);break;case _.ServerMessageType.Expire:this.emitError(_.PeerErrorType.PeerUnavailable,"Could not connect to peer "+k);break;case _.ServerMessageType.Offer:var D=S.connectionId;if((G=this.getConnection(k,D))&&(G.close(),l.default.warn("Offer received for existing Connection ID:"+D)),S.type===_.ConnectionType.Media)G=new h.MediaConnection(k,this,{connectionId:D,_payload:S,metadata:S.metadata}),this._addConnection(k,G),this.emit(_.PeerEventType.Call,G);else{if(S.type!==_.ConnectionType.Data)return void l.default.warn("Received malformed connection type:"+S.type);G=new b.DataConnection(k,this,{connectionId:D,_payload:S,metadata:S.metadata,label:S.label,serialization:S.serialization,reliable:S.reliable}),this._addConnection(k,G),this.emit(_.PeerEventType.Connection,G)}var P=this._getMessages(D);try{for(var H=r(P),F=H.next();!F.done;F=H.next()){var N=F.value;G.handleMessage(N)}}catch(ee){E={error:ee}}finally{try{F&&!F.done&&(w=H.return)&&w.call(H)}finally{if(E)throw E.error}}break;default:if(!S)return void l.default.warn("You received a malformed message from "+k+" of type "+T);var G;D=S.connectionId,(G=this.getConnection(k,D))&&G.peerConnection?G.handleMessage(g):D?this._storeMessage(D,g):l.default.warn("You received an unrecognized message:",g)}},p.prototype._storeMessage=function(g,E){this._lostMessages.has(g)||this._lostMessages.set(g,[]),this._lostMessages.get(g).push(E)},p.prototype._getMessages=function(g){var E=this._lostMessages.get(g);return E?(this._lostMessages.delete(g),E):[]},p.prototype.connect=function(g,E){if(E===void 0&&(E={}),this.disconnected)return l.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect, or call reconnect on this peer if you believe its ID to still be available."),void this.emitError(_.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");var w=new b.DataConnection(g,this,E);return this._addConnection(g,w),w},p.prototype.call=function(g,E,w){if(w===void 0&&(w={}),this.disconnected)return l.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),void this.emitError(_.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");if(E){w._stream=E;var T=new h.MediaConnection(g,this,w);return this._addConnection(g,T),T}l.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.")},p.prototype._addConnection=function(g,E){l.default.log("add connection "+E.type+":"+E.connectionId+" to peerId:"+g),this._connections.has(g)||this._connections.set(g,[]),this._connections.get(g).push(E)},p.prototype._removeConnection=function(g){var E=this._connections.get(g.peer);if(E){var w=E.indexOf(g);w!==-1&&E.splice(w,1)}this._lostMessages.delete(g.connectionId)},p.prototype.getConnection=function(g,E){var w,T,S=this._connections.get(g);if(!S)return null;try{for(var k=r(S),D=k.next();!D.done;D=k.next()){var P=D.value;if(P.connectionId===E)return P}}catch(H){w={error:H}}finally{try{D&&!D.done&&(T=k.return)&&T.call(k)}finally{if(w)throw w.error}}return null},p.prototype._delayedAbort=function(g,E){var w=this;setTimeout(function(){w._abort(g,E)},0)},p.prototype._abort=function(g,E){l.default.error("Aborting!"),this.emitError(g,E),this._lastServerId?this.disconnect():this.destroy()},p.prototype.emitError=function(g,E){var w;l.default.error("Error:",E),(w=typeof E=="string"?new Error(E):E).type=g,this.emit(_.PeerEventType.Error,w)},p.prototype.destroy=function(){this.destroyed||(l.default.log("Destroy peer with ID:"+this.id),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit(_.PeerEventType.Close))},p.prototype._cleanup=function(){var g,E;try{for(var w=r(this._connections.keys()),T=w.next();!T.done;T=w.next()){var S=T.value;this._cleanupPeer(S),this._connections.delete(S)}}catch(k){g={error:k}}finally{try{T&&!T.done&&(E=w.return)&&E.call(w)}finally{if(g)throw g.error}}this.socket.removeAllListeners()},p.prototype._cleanupPeer=function(g){var E,w,T=this._connections.get(g);if(T)try{for(var S=r(T),k=S.next();!k.done;k=S.next())k.value.close()}catch(D){E={error:D}}finally{try{k&&!k.done&&(w=S.return)&&w.call(S)}finally{if(E)throw E.error}}},p.prototype.disconnect=function(){if(!this.disconnected){var g=this.id;l.default.log("Disconnect peer with ID:"+g),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=g,this._id=null,this.emit(_.PeerEventType.Disconnected,g)}},p.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)l.default.log("Attempting reconnection to server with ID "+this._lastServerId),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(this.disconnected||this.open)throw new Error("Peer "+this.id+" cannot reconnect because it is not disconnected from the server!");l.default.error("In a hurry? We're still trying to make the initial connection!")}},p.prototype.listAllPeers=function(g){var E=this;g===void 0&&(g=function(w){}),this._api.listAllPeers().then(function(w){return g(w)}).catch(function(w){return E._abort(_.PeerErrorType.ServerError,w)})},p.DEFAULT_KEY="peerjs",p}(c.EventEmitter);t.Peer=m},{eventemitter3:"JJlS","./util":"BHXf","./logger":"WOs9","./socket":"wJlv","./mediaconnection":"dbHP","./dataconnection":"GBTQ","./enums":"ZRYf","./api":"in7L"}],iTK6:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.peerjs=void 0;var n=o("./util"),i=o("./peer");t.peerjs={Peer:i.Peer,util:n.util},t.default=i.Peer,window.peerjs=t.peerjs,window.Peer=i.Peer},{"./util":"BHXf","./peer":"Hxpd"}]},{},["iTK6"],null)});var nh=Bo((zE,th)=>{(function(){var o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e={rotl:function(t,n){return t<<n|t>>>32-n},rotr:function(t,n){return t<<32-n|t>>>n},endian:function(t){if(t.constructor==Number)return e.rotl(t,8)&16711935|e.rotl(t,24)&4278255360;for(var n=0;n<t.length;n++)t[n]=e.endian(t[n]);return t},randomBytes:function(t){for(var n=[];t>0;t--)n.push(Math.floor(Math.random()*256));return n},bytesToWords:function(t){for(var n=[],i=0,r=0;i<t.length;i++,r+=8)n[r>>>5]|=t[i]<<24-r%32;return n},wordsToBytes:function(t){for(var n=[],i=0;i<t.length*32;i+=8)n.push(t[i>>>5]>>>24-i%32&255);return n},bytesToHex:function(t){for(var n=[],i=0;i<t.length;i++)n.push((t[i]>>>4).toString(16)),n.push((t[i]&15).toString(16));return n.join("")},hexToBytes:function(t){for(var n=[],i=0;i<t.length;i+=2)n.push(parseInt(t.substr(i,2),16));return n},bytesToBase64:function(t){for(var n=[],i=0;i<t.length;i+=3)for(var r=t[i]<<16|t[i+1]<<8|t[i+2],s=0;s<4;s++)i*8+s*6<=t.length*8?n.push(o.charAt(r>>>6*(3-s)&63)):n.push("=");return n.join("")},base64ToBytes:function(t){t=t.replace(/[^A-Z0-9+\/]/ig,"");for(var n=[],i=0,r=0;i<t.length;r=++i%4)r!=0&&n.push((o.indexOf(t.charAt(i-1))&Math.pow(2,-2*r+8)-1)<<r*2|o.indexOf(t.charAt(i))>>>6-r*2);return n}};th.exports=e})()});var Jl=Bo((XE,ih)=>{var Kl={utf8:{stringToBytes:function(o){return Kl.bin.stringToBytes(unescape(encodeURIComponent(o)))},bytesToString:function(o){return decodeURIComponent(escape(Kl.bin.bytesToString(o)))}},bin:{stringToBytes:function(o){for(var e=[],t=0;t<o.length;t++)e.push(o.charCodeAt(t)&255);return e},bytesToString:function(o){for(var e=[],t=0;t<o.length;t++)e.push(String.fromCharCode(o[t]));return e.join("")}}};ih.exports=Kl});var sh=Bo((QE,oh)=>{oh.exports=function(o){return o!=null&&(rh(o)||cm(o)||!!o._isBuffer)};function rh(o){return!!o.constructor&&typeof o.constructor.isBuffer=="function"&&o.constructor.isBuffer(o)}function cm(o){return typeof o.readFloatLE=="function"&&typeof o.slice=="function"&&rh(o.slice(0,0))}});var lh=Bo((qE,ah)=>{(function(){var o=nh(),e=Jl().utf8,t=sh(),n=Jl().bin,i=function(r,s){r.constructor==String?s&&s.encoding==="binary"?r=n.stringToBytes(r):r=e.stringToBytes(r):t(r)?r=Array.prototype.slice.call(r,0):!Array.isArray(r)&&r.constructor!==Uint8Array&&(r=r.toString());for(var a=o.bytesToWords(r),c=r.length*8,d=1732584193,l=-271733879,u=-1732584194,h=271733878,b=0;b<a.length;b++)a[b]=(a[b]<<8|a[b]>>>24)&16711935|(a[b]<<24|a[b]>>>8)&4278255360;a[c>>>5]|=128<<c%32,a[(c+64>>>9<<4)+14]=c;for(var _=i._ff,v=i._gg,y=i._hh,m=i._ii,b=0;b<a.length;b+=16){var f=d,p=l,g=u,E=h;d=_(d,l,u,h,a[b+0],7,-680876936),h=_(h,d,l,u,a[b+1],12,-389564586),u=_(u,h,d,l,a[b+2],17,606105819),l=_(l,u,h,d,a[b+3],22,-1044525330),d=_(d,l,u,h,a[b+4],7,-176418897),h=_(h,d,l,u,a[b+5],12,1200080426),u=_(u,h,d,l,a[b+6],17,-1473231341),l=_(l,u,h,d,a[b+7],22,-45705983),d=_(d,l,u,h,a[b+8],7,1770035416),h=_(h,d,l,u,a[b+9],12,-1958414417),u=_(u,h,d,l,a[b+10],17,-42063),l=_(l,u,h,d,a[b+11],22,-1990404162),d=_(d,l,u,h,a[b+12],7,1804603682),h=_(h,d,l,u,a[b+13],12,-40341101),u=_(u,h,d,l,a[b+14],17,-1502002290),l=_(l,u,h,d,a[b+15],22,1236535329),d=v(d,l,u,h,a[b+1],5,-165796510),h=v(h,d,l,u,a[b+6],9,-1069501632),u=v(u,h,d,l,a[b+11],14,643717713),l=v(l,u,h,d,a[b+0],20,-373897302),d=v(d,l,u,h,a[b+5],5,-701558691),h=v(h,d,l,u,a[b+10],9,38016083),u=v(u,h,d,l,a[b+15],14,-660478335),l=v(l,u,h,d,a[b+4],20,-405537848),d=v(d,l,u,h,a[b+9],5,568446438),h=v(h,d,l,u,a[b+14],9,-1019803690),u=v(u,h,d,l,a[b+3],14,-187363961),l=v(l,u,h,d,a[b+8],20,1163531501),d=v(d,l,u,h,a[b+13],5,-1444681467),h=v(h,d,l,u,a[b+2],9,-51403784),u=v(u,h,d,l,a[b+7],14,1735328473),l=v(l,u,h,d,a[b+12],20,-1926607734),d=y(d,l,u,h,a[b+5],4,-378558),h=y(h,d,l,u,a[b+8],11,-2022574463),u=y(u,h,d,l,a[b+11],16,1839030562),l=y(l,u,h,d,a[b+14],23,-35309556),d=y(d,l,u,h,a[b+1],4,-1530992060),h=y(h,d,l,u,a[b+4],11,1272893353),u=y(u,h,d,l,a[b+7],16,-155497632),l=y(l,u,h,d,a[b+10],23,-1094730640),d=y(d,l,u,h,a[b+13],4,681279174),h=y(h,d,l,u,a[b+0],11,-358537222),u=y(u,h,d,l,a[b+3],16,-722521979),l=y(l,u,h,d,a[b+6],23,76029189),d=y(d,l,u,h,a[b+9],4,-640364487),h=y(h,d,l,u,a[b+12],11,-421815835),u=y(u,h,d,l,a[b+15],16,530742520),l=y(l,u,h,d,a[b+2],23,-995338651),d=m(d,l,u,h,a[b+0],6,-198630844),h=m(h,d,l,u,a[b+7],10,1126891415),u=m(u,h,d,l,a[b+14],15,-1416354905),l=m(l,u,h,d,a[b+5],21,-57434055),d=m(d,l,u,h,a[b+12],6,1700485571),h=m(h,d,l,u,a[b+3],10,-1894986606),u=m(u,h,d,l,a[b+10],15,-1051523),l=m(l,u,h,d,a[b+1],21,-2054922799),d=m(d,l,u,h,a[b+8],6,1873313359),h=m(h,d,l,u,a[b+15],10,-30611744),u=m(u,h,d,l,a[b+6],15,-1560198380),l=m(l,u,h,d,a[b+13],21,1309151649),d=m(d,l,u,h,a[b+4],6,-145523070),h=m(h,d,l,u,a[b+11],10,-1120210379),u=m(u,h,d,l,a[b+2],15,718787259),l=m(l,u,h,d,a[b+9],21,-343485551),d=d+f>>>0,l=l+p>>>0,u=u+g>>>0,h=h+E>>>0}return o.endian([d,l,u,h])};i._ff=function(r,s,a,c,d,l,u){var h=r+(s&a|~s&c)+(d>>>0)+u;return(h<<l|h>>>32-l)+s},i._gg=function(r,s,a,c,d,l,u){var h=r+(s&c|a&~c)+(d>>>0)+u;return(h<<l|h>>>32-l)+s},i._hh=function(r,s,a,c,d,l,u){var h=r+(s^a^c)+(d>>>0)+u;return(h<<l|h>>>32-l)+s},i._ii=function(r,s,a,c,d,l,u){var h=r+(a^(s|~c))+(d>>>0)+u;return(h<<l|h>>>32-l)+s},i._blocksize=16,i._digestsize=16,ah.exports=function(r,s){if(r==null)throw new Error("Illegal argument "+r);var a=o.wordsToBytes(i(r,s));return s&&s.asBytes?a:s&&s.asString?n.bytesToString(a):o.bytesToHex(a)}})()});import{DepthTexture as Im,WebGLRenderer as Mm}from"three";import*as Ee from"three";import*as Dt from"three";var gl=()=>o=>o;var bl=!1,fl=[];setTimeout(()=>{bl&&console.log(fl)},100);function vl(){return new URLSearchParams(window.location.search)}function I(o){bl&&!fl.includes(o)&&fl.push(o);let e=vl();if(e.has(o)){let t=e.get(o);return t||!0}return!1}bl=I("help")===!0;function Qr(o,e,t){o.has(e)?o.set(e,t.toString()):o.append(e,t.toString())}function su(o,e){window.history.replaceState(null,o,"?"+e.toString())}function au(o,e){return Math.floor(Math.random()*(e-o+1))+o}var ru=["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"],ou=["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 lu(){let o=ru[Math.floor(Math.random()*ru.length)],e=ou[Math.floor(Math.random()*ou.length)];return o+"_"+e}function cu(o){return o=o.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),o.trim()}function vi(o,e,t=!0,n=!1){if(e==null)return null;if(e.userData&&e.userData.guid===o)return e;if(e.guid==o)return e;if(n&&e.userData?.components){for(let i of e.userData.components)if(i.guid===o)return i}if(t){if(e.scenes)for(let i in e.scenes){let r=e.scenes[i],s=vi(o,r,t,n);if(s)return s}if(e.children)for(let i in e.children){let r=e.children[i],s=vi(o,r,t,n);if(s)return s}}}function Uo(o,e){if(o!=null&&typeof o=="object"){let t;Array.isArray(o)?t=[]:(t=Object.create(o),Object.assign(t,o));for(let n of Object.keys(o)){let i=o[n];e&&!e(o,n,i)?t[n]=i:i?.clone!==void 0&&typeof i.clone=="function"?t[n]=i.clone():t[n]=Uo(i,e)}return t}return o}function du(o){return new Promise((e,t)=>{setTimeout(e,o)})}var pl=I("debugsourcepath");function nn(o,e){if(o===void 0)return pl&&console.warn("getPath: source is undefined, returning uri",e),e;if(e.startsWith("http"))return pl&&console.warn("getPath: uri is absolute, returning uri",e),e;let t=o.lastIndexOf("/");if(t>=0){let n=o.substring(0,t+1),i=e.lastIndexOf("/");return i>=0?n+=e.substring(i+1):n+=e,pl&&console.log("getPath:",o,` - changed uri from
79
79
  `,e,`
80
- \u2192 `,i),i}return e}var hc=class{subscribeWrite(e){this.writeCallbacks.push(e)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;let e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");let i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:o=>{e[this._wrapperProp]=o;for(let s of this.writeCallbacks)s(o)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;let e=this._object,t=this._prop;Reflect.deleteProperty(e,t);let i=e[this._wrapperProp];e[t]=i,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}},Hn=class{_watches=[];constructor(e,t){if(Array.isArray(t))for(let i of t)this._watches.push(new Hn(e,i));else this._watches.push(new hc(e,t))}subscribeWrite(e){for(let t of this._watches)t.subscribeWrite(e)}apply(){for(let e of this._watches)e.apply()}revoke(){for(let e of this._watches)e.revoke()}dispose(){for(let e of this._watches)e.dispose();this._watches.length=0}};var _i=D("gizmos"),Oe=D("debugextension");var ha=D("debugresolvedependencies"),pg=["/extensions/","extensions/"],fg=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function So(a,e){ha&&console.log(a,e);let t=[];mc(fg,a,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function mc(a,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(let n of Object.keys(t)){let r=t[n];if(typeof r=="string"){let o=_u(e,r);if(o!==null)typeof o.then=="function"?i.push(o.then(s=>t[n]=s)):t[n]=o;else for(let s of a){let c=gc(s.prefix,r);if(c>=0){ha&&console.log(s,c,s.dependencyName),i.push(e?.getDependency(s.dependencyName,c).then(d=>(t[n]=d,d)));break}}}else if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=r[o],c=_u(e,s);if(c!==null){typeof c.then=="function"?i.push(c.then(d=>r[o]=d)):r[o]=c;continue}for(let d of a){let l=gc(d.prefix,s);if(l>=0){ha&&console.log(d,l,d.dependencyName),i.push(e?.getDependency(d.dependencyName,l).then(h=>r[o]=h));break}}typeof s=="object"&&mc(a,e,s,i)}else typeof r=="object"&&mc(a,e,r,i)}else typeof t=="string"&&mg(a,e,t,i)}function _u(a,e){if(a&&a.plugins&&typeof e=="string"){for(let t of pg)if(e.startsWith(t)){let i=e.substring(t.length),n=i.indexOf("/");n>=0&&(i=i.substring(0,n));let r=a.plugins[i];if(Oe&&console.log(i,r),typeof r?.resolve=="function"){let o=e.substring(t.length+i.length+1);return r.resolve(a,o)}break}}return null}function mg(a,e,t,i){for(let n of a){let r=gc(n.prefix,t);if(r>=0)return ha&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(o=>o)),!0}return!1}function gc(a,e){if(typeof e=="string"&&e.startsWith(a)){let t=e.substring(a.length),i=Number.parseInt(t);if(i>=0)return i}return-1}var bc=class{_types={};add(e,t){let i=this._types[e];i===void 0?this._types[e]=t:i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},B=Symbol("BuiltInType"),j=new bc;var vc="NEEDLE_persistent_assets";function Eu(a){return a?.___persistentAsset===!0}var ua=class{get name(){return vc}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[vc];if(!t)return;Oe&&console.log(t);let i=new Array;for(let n of t?.assets){let r=So(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){Oe&&console.log(t);let n=e.json.extensions[vc];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let o=r.__type;if(o){let s=j.get(o)}}return r}}return null}};function Er(a=window.location.hostname){return new RegExp("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}|localhost","gm").test(a)===!0}function Cu(){return window.location.hostname.includes("glitch.me")}var on="ar",gg="quit-ar",pa=class{get ARContainer(){return this.arContainer}constructor(){this.closeARCallback=this.onRequestedEndAR.bind(this)}arContainer=null;closeARCallback;currentSession=null;registeredCloseEventElements=[];_createdAROnlyElements=[];_reparentedObjects=[];requestEndAR(){this.onRequestedEndAR()}onBegin(e,t,i){this.currentSession=i,this.arContainer=t,e.domElement.querySelectorAll(`.${on}`).forEach(o=>{!o||o!==this.arContainer&&(this._reparentedObjects.push({el:o,previousParent:o.parentElement}),this.arContainer?.appendChild(o))});let r=t.getElementsByClassName(gg);if(!r||r.length<=0)console.warn("Missing quit AR elements"),this.createFallbackCloseARButton(this.arContainer);else for(let o=0;o<r.length;o++){let s=r[o];!s||(s.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(s))}}onEnd(e){for(let t of this._createdAROnlyElements)t.remove&&t.remove();for(let t of this._reparentedObjects){let i=t.el;t.previousParent?.appendChild(i)}this._reparentedObjects.length=0}findOrCreateARContainer(e){if(e.classList.contains(on))return e;if(e.children){for(let i of e.children)if(!(!i||!i.classList)&&i.classList.contains(on))return i}let t=document.createElement("div");return t.classList.add(on),e.appendChild(t)}onRequestedEndAR(){if(!!this.currentSession){this.currentSession.end(),this.currentSession=null;for(let e of this.registeredCloseEventElements)e.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(e){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","38px"),t.setAttribute("height","38px"),t.style.position="absolute",t.style.right="20px",t.style.top="40px",t.style.zIndex="9999",t.style.pointerEvents="auto",t.addEventListener("click",this.closeARCallback),e.appendChild(t),this._createdAROnlyElements.push(t);var i=document.createElementNS("http://www.w3.org/2000/svg","path");i.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),i.setAttribute("stroke","#eee"),i.setAttribute("stroke-width","2px"),t.appendChild(i),this._createdAROnlyElements.push(i)}};var F0=D("debugdebug"),bg=D("noerrors"),yc=new Map,N0=new RegExp(" at .+/(.+?.ts)","g"),ma=(i=>(i[i.Log=0]="Log",i[i.Warn=1]="Warn",i[i.Error=2]="Error",i))(ma||{});function Tu(a,e,t,i){if(bg)return;let r=K.Current?.domElement??document.querySelector("needle-engine");if(!!r){if(Array.isArray(e)){let o="";for(let s=0;s<e.length;s++)typeof e[s]!="object"&&(s>0&&(o+=" "),o+=e[s]);e=o}vg(a,r,e)}}var xc=new Set;function vg(a,e,t){let i=xg(e);if(i.childElementCount>=20||xc.has(t))return;xc.add(t);let n=_g(a,t);i.prepend(n),setTimeout(()=>{xc.delete(t),wg(n)},1e4)}var yg=`
80
+ \u2192 `,n),n}return e}var ml=class{subscribeWrite(e){this.writeCallbacks.push(e)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;let e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");let n=e[t];e[this._wrapperProp]=n,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:s=>{e[this._wrapperProp]=s;for(let a of this.writeCallbacks)a(s,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;let e=this._object,t=this._prop;Reflect.deleteProperty(e,t);let n=e[this._wrapperProp];e[t]=n,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}},Un=class{_watches=[];constructor(e,t){if(Array.isArray(t))for(let n of t)this._watches.push(new Un(e,n));else this._watches.push(new ml(e,t))}subscribeWrite(e){for(let t of this._watches)t.subscribeWrite(e)}apply(){for(let e of this._watches)e.apply()}revoke(){for(let e of this._watches)e.revoke()}dispose(){for(let e of this._watches)e.dispose();this._watches.length=0}};var rn=I("gizmos"),_e=I("debugextension");var Rs=I("debugresolvedependencies"),nf=["/extensions/","extensions/"],rf=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function qr(o,e){Rs&&console.log(o,e);let t=[];yl(rf,o,e,t);let n=await Promise.all(t);return typeof e=="string"&&n.length===1?n[0]:n}function yl(o,e,t,n){if(typeof t=="object"&&t!==void 0&&t!==null)for(let i of Object.keys(t)){let r=t[i];if(typeof r=="string"){let s=uu(e,r);if(s!==null)typeof s.then=="function"?n.push(s.then(a=>t[i]=a)):t[i]=s;else for(let a of o){let c=_l(a.prefix,r);if(c>=0){Rs&&console.log(a,c,a.dependencyName),n.push(e?.getDependency(a.dependencyName,c).then(d=>(t[i]=d,d)));break}}}else if(Array.isArray(r))for(let s=0;s<r.length;s++){let a=r[s],c=uu(e,a);if(c!==null){typeof c.then=="function"?n.push(c.then(d=>r[s]=d)):r[s]=c;continue}for(let d of o){let l=_l(d.prefix,a);if(l>=0){Rs&&console.log(d,l,d.dependencyName),n.push(e?.getDependency(d.dependencyName,l).then(u=>r[s]=u));break}}typeof a=="object"&&yl(o,e,a,n)}else typeof r=="object"&&yl(o,e,r,n)}else typeof t=="string"&&of(o,e,t,n)}function uu(o,e){if(o&&o.plugins&&typeof e=="string"){for(let t of nf)if(e.startsWith(t)){let n=e.substring(t.length),i=n.indexOf("/");i>=0&&(n=n.substring(0,i));let r=o.plugins[n];if(_e&&console.log(n,r),typeof r?.resolve=="function"){let s=e.substring(t.length+n.length+1);return r.resolve(o,s)}break}}return null}function of(o,e,t,n){for(let i of o){let r=_l(i.prefix,t);if(r>=0)return Rs&&console.log(i,r,i.dependencyName),n.push(e?.getDependency(i.dependencyName,r).then(s=>s)),!0}return!1}function _l(o,e){if(typeof e=="string"&&e.startsWith(o)){let t=e.substring(o.length),n=Number.parseInt(t);if(n>=0)return n}return-1}var El=class{_types={};add(e,t){let n=this._types[e];n===void 0?this._types[e]=t:n!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e)}get(e){return this._types[e]}},A=Symbol("BuiltInType"),M=new El;var wl="NEEDLE_persistent_assets";function hu(o){return o?.___persistentAsset===!0}var Ss=class{get name(){return wl}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[wl];if(!t)return;_e&&console.log(t);let n=new Array;for(let i of t?.assets){let r=qr(this.parser,i);r&&n.push(r)}await Promise.all(n)}resolve(e,t){let n=Number.parseInt(t);if(n>=0){_e&&console.log(t);let i=e.json.extensions[wl];if(i){let r=i?.assets[n];if(r&&typeof r=="object"){r.___persistentAsset=!0;let s=r.__type;if(s){let a=M.get(s)}}return r}}return null}};function tr(o=window.location.hostname){return new RegExp("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}|localhost","gm").test(o)===!0}function pu(){return window.location.hostname.includes("glitch.me")}var Gn="ar",sf="quit-ar",Ps=class{get ARContainer(){return this.arContainer}constructor(){this.closeARCallback=this.onRequestedEndAR.bind(this)}arContainer=null;closeARCallback;currentSession=null;registeredCloseEventElements=[];_createdAROnlyElements=[];_reparentedObjects=[];requestEndAR(){this.onRequestedEndAR()}onBegin(e,t,n){this.currentSession=n,this.arContainer=t,e.domElement.querySelectorAll(`.${Gn}`).forEach(s=>{!s||s!==this.arContainer&&(this._reparentedObjects.push({el:s,previousParent:s.parentElement}),this.arContainer?.appendChild(s))});let r=t.getElementsByClassName(sf);if(!r||r.length<=0)console.warn("Missing quit AR elements"),this.createFallbackCloseARButton(this.arContainer);else for(let s=0;s<r.length;s++){let a=r[s];!a||(a.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(a))}}onEnd(e){for(let t of this._createdAROnlyElements)t.remove&&t.remove();for(let t of this._reparentedObjects){let n=t.el;t.previousParent?.appendChild(n)}this._reparentedObjects.length=0}findOrCreateARContainer(e){if(e.classList.contains(Gn))return e;if(e.children){for(let n of e.children)if(!(!n||!n.classList)&&n.classList.contains(Gn))return n}let t=document.createElement("div");return t.classList.add(Gn),e.appendChild(t)}onRequestedEndAR(){if(!!this.currentSession){this.currentSession.end(),this.currentSession=null;for(let e of this.registeredCloseEventElements)e.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(e){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","38px"),t.setAttribute("height","38px"),t.style.position="absolute",t.style.right="20px",t.style.top="40px",t.style.zIndex="9999",t.style.pointerEvents="auto",t.addEventListener("click",this.closeARCallback),e.appendChild(t),this._createdAROnlyElements.push(t);var n=document.createElementNS("http://www.w3.org/2000/svg","path");n.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),n.setAttribute("stroke","#eee"),n.setAttribute("stroke-width","2px"),t.appendChild(n),this._createdAROnlyElements.push(n)}};var hy=I("debugdebug"),af=I("noerrors"),xl=new Map,py=new RegExp(" at .+/(.+?.ts)","g"),Go=(n=>(n[n.Log=0]="Log",n[n.Warn=1]="Warn",n[n.Error=2]="Error",n))(Go||{});function fu(o,e,t,n){if(af)return;let r=V.Current?.domElement??document.querySelector("needle-engine");if(!!r){if(Array.isArray(e)){let s="";for(let a=0;a<e.length;a++)typeof e[a]!="object"&&(a>0&&(s+=" "),s+=e[a]);e=s}lf(o,r,e)}}var Cl=new Set;function lf(o,e,t){let n=df(e);if(n.childElementCount>=20||Cl.has(t))return;Cl.add(t);let i=hf(o,t);n.prepend(i),setTimeout(()=>{Cl.delete(t),uf(i)},1e4)}var cf=`
81
81
 
82
82
  @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
83
83
 
@@ -114,21 +114,21 @@ a:hover {
114
114
  color: rgba(255,100,120, 1);
115
115
  }
116
116
 
117
- `;function xg(a){if(yc.has(a))return yc.get(a);{let e=document.createElement("div");e.classList.add(on),e.classList.add("desktop"),e.classList.add("debug-container"),e.style.position="absolute",e.style.top="0",e.style.right="5px",e.style.paddingTop="0px",e.style.maxWidth="70%",e.style.maxHeight="calc(100% - 5px)",e.style.zIndex="1000",e.style.pointerEvents="scroll",e.style.display="flex",e.style.alignItems="end",e.style.flexDirection="column",e.style.color="white",e.style.overflow="auto",a.appendChild(e),yc.set(a,e);let t=document.createElement("style");return t.innerHTML=yg,e.appendChild(t),e}}var Ru=Symbol("logtype"),fa=new Map;function wg(a){a.remove();let e=a[Ru],t=fa.get(e)??[];t.push(a),fa.set(e,t)}function _g(a,e){if(fa.has(a)){let i=fa.get(a);if(i.length>0)return i.pop()}let t=document.createElement("div");switch(t.style.marginRight="5px",t.style.padding=".5em",t.style.backgroundColor="rgba(0,0,0,.9)",t.style.marginTop="5px",t.style.marginBottom="3px",t.style.borderRadius="8px",t.style.pointerEvents="all",t.style.userSelect="text",t.style.maxWidth="250px",t.style.whiteSpace="pre-wrap",t.style["backdrop-filter"]="blur(10px)",t.style.backgroundColor="rgba(20,20,20,.8)",t.style.boxShadow="inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)",t.style.border="1px solid rgba(160,160,160,.2)",t[Ru]=a,a){case 0:t.classList.add("log"),t.style.color="rgba(200,200,200,.7)",t.style.backgroundColor="rgba(40,40,40,.7)";break;case 1:t.classList.add("warn"),t.style.color="rgb(255, 255, 150)",t.style.backgroundColor="rgba(50,50,20,.8)";break;case 2:t.classList.add("error"),t.style.color="rgb(255, 50, 50",t.style.backgroundColor="rgba(50,20,20,.8)";break}return t.title="Open the browser console (F12) for more information",t.innerHTML=e,t}function xs(a,e=0){Tu(e,a)}var Cr=D("debugserializer"),wc=class{register(e,t){if(this.typeMap[e]!==void 0){if(this.typeMap[e]===t)return;console.warn("Type "+e+" is already registered",t,this.typeMap[e])}Cr&&console.log("Register type serializer for "+e,t),this.typeMap[e]=t}typeMap={};getSerializer(e){if(!!e)return this.typeMap[e]}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){Cr&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){Cr&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return Cr&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){Cr&&console.warn("No prototype for "+i,e,e.name,e.prototype,e.constructor.name);return}let s=r.prototype??r.constructor;if(s!==e){let c=this.getSerializerForConstructor(s,++t);if(c){Cr&&console.log("FOUND "+s.constructor.name,s.name,s,c);let d=s.name??s.constructor.name;d==="Function"?console.error("Registering Function is not allowed, something went wrong",e,s,c):this.register(d,c)}return c}}},ba=new wc,sn=class{constructor(e){if(Array.isArray(e))for(let t of e)ba.register(t.name,this);else ba.register(e.name,this)}},Po=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function Ec(a,e){let t=a.$serializedTypes;if(t===void 0)return null;let i={};for(let n in t){let r=a[n];if(r!=null&&typeof r=="object"){let o=ba.getSerializerForConstructor(r);if(o){i[n]=o.onSerialize(r,e);continue}}i[n]=r}return i.name=a.constructor.name,typeof a.guid=="string"&&(i.guid=a.guid),i}var ga=[];function Su(a,e){if(!a)return e;typeof a.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,a.$serializedTypes));let t=Object.getPrototypeOf(a);return Su(t,e)}function ws(a,e,t){if(!a)return!1;if(t.target=a,a.onBeforeDeserialize!==void 0){let r=a.onBeforeDeserialize(e,t);if(typeof r=="boolean")return r}let i=Su(a);if(e){if(typeof e.guid=="string"&&(a.guid=e.guid),i)for(let r in i){let o=i[r],s=e[r];if(!(a[r]!==void 0&&s===void 0))if(t.path=r,o===null)a[r]=s;else{let c=function(d){let h=d.type;return h?_c(s,h,t,void 0,a[r]):_c(s,d,t,void 0,a[r])};var n=c;if(a.onBeforeDeserializeMember!==void 0&&a.onBeforeDeserializeMember(r,s,t)===!0)continue;if(Array.isArray(o))for(let d=0;d<o.length;d++){let l=o[d],h=c(l);if(h!==void 0||d===o.length-1){a[r]=h;break}}else a[r]=c(o);ga.length=0,a.onAfterDeserializeMember!==void 0&&a.onAfterDeserializeMember(r,s,t)}}Tg(a,e)}return Cg(a,e),a.onAfterDeserialize!==void 0&&a.onAfterDeserialize(e,t),t.path=void 0,!0}var Eg=D("noerrors");function Cg(a,e){if(Eg||Er()===!1||!a||a.constructor&&a.constructor[B]===!0)return;let t=a.constructor?.name,i=Object.getOwnPropertyNames(a);for(let n of i){if(n==="sourceId")continue;let r=a[n];r!=null&&(typeof r=="object"?r.isObject3D||(typeof r.node=="number"||typeof r.guid=="string")&&(Object.keys(r).length>1||(xs(`<strong>Missing serialization for object reference!</strong>
117
+ `;function df(o){if(xl.has(o))return xl.get(o);{let e=document.createElement("div");e.classList.add(Gn),e.classList.add("desktop"),e.classList.add("debug-container"),e.style.position="absolute",e.style.top="0",e.style.right="5px",e.style.paddingTop="0px",e.style.maxWidth="70%",e.style.maxHeight="calc(100% - 5px)",e.style.zIndex="1000",e.style.pointerEvents="scroll",e.style.display="flex",e.style.alignItems="end",e.style.flexDirection="column",e.style.color="white",e.style.overflow="auto",o.appendChild(e),xl.set(o,e);let t=document.createElement("style");return t.innerHTML=cf,e.appendChild(t),e}}var mu=Symbol("logtype"),Os=new Map;function uf(o){o.remove();let e=o[mu],t=Os.get(e)??[];t.push(o),Os.set(e,t)}function hf(o,e){if(Os.has(o)){let n=Os.get(o);if(n.length>0)return n.pop()}let t=document.createElement("div");switch(t.style.marginRight="5px",t.style.padding=".5em",t.style.backgroundColor="rgba(0,0,0,.9)",t.style.marginTop="5px",t.style.marginBottom="3px",t.style.borderRadius="8px",t.style.pointerEvents="all",t.style.userSelect="text",t.style.maxWidth="250px",t.style.whiteSpace="pre-wrap",t.style["backdrop-filter"]="blur(10px)",t.style.backgroundColor="rgba(20,20,20,.8)",t.style.boxShadow="inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)",t.style.border="1px solid rgba(160,160,160,.2)",t[mu]=o,o){case 0:t.classList.add("log"),t.style.color="rgba(200,200,200,.7)",t.style.backgroundColor="rgba(40,40,40,.7)";break;case 1:t.classList.add("warn"),t.style.color="rgb(255, 255, 150)",t.style.backgroundColor="rgba(50,50,20,.8)";break;case 2:t.classList.add("error"),t.style.color="rgb(255, 50, 50",t.style.backgroundColor="rgba(50,20,20,.8)";break}return t.title="Open the browser console (F12) for more information",t.innerHTML=e,t}function yi(o,e=0){fu(e,o)}function gy(o){yi(o,1)}var nr=I("debugserializer"),Tl=class{register(e,t){if(this.typeMap[e]!==void 0){if(this.typeMap[e]===t)return;console.warn("Type "+e+" is already registered",t,this.typeMap[e])}nr&&console.log("Register type serializer for "+e,t),this.typeMap[e]=t}typeMap={};getSerializer(e){if(!!e)return this.typeMap[e]}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){nr&&console.log("invalid type");return}let n=e.name??e.constructor?.name;if(!n){nr&&console.log("invalid name",n);return}let i=this.getSerializer(n);if(i!==void 0)return nr&&console.log("FOUND "+n,e.name,e.constructor.name,i,this.typeMap),i;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){nr&&console.warn("No prototype for "+n,e,e.name,e.prototype,e.constructor.name);return}let a=r.prototype??r.constructor;if(a!==e){let c=this.getSerializerForConstructor(a,++t);if(c){nr&&console.log("FOUND "+a.constructor.name,a.name,a,c);let d=a.name??a.constructor.name;d==="Function"?console.error("Registering Function is not allowed, something went wrong",e,a,c):this.register(d,c)}return c}}},Is=new Tl,Vn=class{constructor(e){if(Array.isArray(e))for(let t of e)Is.register(t.name,this);else Is.register(e.name,this)}},Yr=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function Sl(o,e){let t=o.$serializedTypes;if(t===void 0)return null;let n={};for(let i in t){let r=o[i];if(r!=null&&typeof r=="object"){let s=Is.getSerializerForConstructor(r);if(s){n[i]=s.onSerialize(r,e);continue}}n[i]=r}return n.name=o.constructor.name,typeof o.guid=="string"&&(n.guid=o.guid),n}var ks=[];function gu(o,e){if(!o)return e;typeof o.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,o.$serializedTypes));let t=Object.getPrototypeOf(o);return gu(t,e)}function Vo(o,e,t){if(!o)return!1;if(t.target=o,o.onBeforeDeserialize!==void 0){let r=o.onBeforeDeserialize(e,t);if(typeof r=="boolean")return r}let n=gu(o);if(e){if(typeof e.guid=="string"&&(o.guid=e.guid),n)for(let r in n){let s=n[r],a=e[r];if(!(o[r]!==void 0&&a===void 0))if(t.path=r,s===null)o[r]=a;else{let c=function(d){let u=d.type;return u?Rl(a,u,t,void 0,o[r]):Rl(a,d,t,void 0,o[r])};var i=c;if(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(r,a,t)===!0)continue;if(Array.isArray(s))for(let d=0;d<s.length;d++){let l=s[d],u=c(l);if(u!==void 0||d===s.length-1){o[r]=u;break}}else o[r]=c(s);ks.length=0,o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(r,a,t)}}mf(o,e)}return ff(o,e),o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(e,t),t.path=void 0,!0}var pf=I("noerrors");function ff(o,e){if(pf||tr()===!1||!o||o.constructor&&o.constructor[A]===!0)return;let t=o.constructor?.name,n=Object.getOwnPropertyNames(o);for(let i of n){if(i==="sourceId")continue;let r=o[i];r!=null&&(typeof r=="object"?r.isObject3D||(typeof r.node=="number"||typeof r.guid=="string")&&(Object.keys(r).length>1||(yi(`<strong>Missing serialization for object reference!</strong>
118
118
 
119
119
  Please change to:
120
120
  @serializable(Object3D)
121
- ${n}? : Object3D;
121
+ ${i}? : Object3D;
122
122
 
123
123
  in script ${t}.ts
124
- <a href="https://docs.needle.tools/serializeable" target="_blank">documentation</a>`,1),console.warn(t,n,a[n],a))):typeof r=="string"&&(r.endsWith(".gltf")||r.endsWith(".glb"))&&(xs(`<strong>Missing serialization for object reference!</strong>
124
+ <a href="https://docs.needle.tools/serializeable" target="_blank">documentation</a>`,1),console.warn(t,i,o[i],o))):typeof r=="string"&&(r.endsWith(".gltf")||r.endsWith(".glb"))&&(yi(`<strong>Missing serialization for object reference!</strong>
125
125
 
126
126
  Please change to:
127
127
  @serializable(AssetReference)
128
- ${n}? : AssetReference;
128
+ ${i}? : AssetReference;
129
129
 
130
130
  in script ${t}.ts
131
- <a href="https://docs.needle.tools/serializeable" target="_blank">documentation</a>`,1),console.warn(t,n,a[n],a)))}}function Tg(a,e){for(let i of Object.keys(e)){let n=e[i];if(typeof n=="object"&&n!==null&&n!==void 0){let r=a[i];if(!r){Cr&&console.log(i,"is undefined on",a);continue}for(let o of Object.keys(n))r[o]===void 0&&t(n[o])&&!t(r)&&(r[o]=n[o])}}function t(i){switch(typeof i){case"number":case"string":case"boolean":return!0}return!1}}function _c(a,e,t,i,n){let r=typeof e=="function"&&e.prototype===void 0,o=e;if(r)try{if(o=e?.call(e,n),r=!1,o==null)return}catch(l){console.error("Error in callback",l,a)}if(!r&&n instanceof o)return n;if(n&&typeof n=="object"&&Eu(n)){if(n.__concreteInstance)return n.__concreteInstance;let l=n;if(!l.$serializedTypes&&o.prototype.$serializedTypes&&(l.$serializedTypes=o.prototype.$serializedTypes),l.$serializedTypes&&ws(l,a,t),n&&o!==void 0)try{let h=new o;Oe&&console.log("Create concrete instance for persistent asset",n,"instance:",h),Tr(h,n),n.__concreteInstance=h,n=h}catch(h){console.error("Error creating instance or creating values on instance",h,n,o)}return n}if(i||(i={serializer:ba.getSerializerForConstructor(o)}),Array.isArray(a)){let l=[];for(let h=0;h<a.length;h++){let u=a[h],f=_c(u,e,t,i,u);l.push(f)}return l}let s=i.serializer;if(s)return s.onDeserialize(a,t);let c;a&&(a.isMaterial||a.isTexture||a.isObject3D)?c=a:c=new o(...Rg(a));let d=c;return d.$serializedTypes&&ws(d,a,t),c}function Rg(a){if(ga.length=0,typeof a=="object"&&a!==null&&a!==void 0)for(let e of Object.keys(a))ga.push(a[e]);return ga}function Tr(a,e){if(e==null||a==null)return;let t=!1;for(let i of Object.keys(e)){let n=Sg(a,i);t&&n===void 0||(!n||n.writable===!0||n?.set!==void 0)&&(a[i]=e[i])}}function Sg(a,e){let t;do t=Object.getOwnPropertyDescriptor(a,e);while(!t&&(a=Object.getPrototypeOf(a)));return t}var _s=class{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}};var va=class extends EventTarget{_doubleClickTimeThreshold=.2;_longPressTimeThreshold=1;get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}_specialCursorTrigger=0;setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new Zt.Vector2];_pointerPositionsLastFrame=[new Zt.Vector2];_pointerPositionsDelta=[new Zt.Vector2];_pointerPositionsRC=[new Zt.Vector2];_pointerPositionDown=[new Zt.Vector2];_pointerDownTime=[];_pointerUpTime=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_pointerEvent=[];getKeyDown(){for(let e in this.keysPressed){let t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(let e in this.keysPressed){let t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){return typeof e=="number"&&(console.warn("Use of keycode as number is not recommended, please use KeyCode or string instead"),e=String.fromCharCode(e)),this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.startFrame===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){return typeof e=="number"&&(console.warn("Use of keycode as number is not recommended, please use KeyCode or string instead"),e=String.fromCharCode(e)),this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.frame===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){return typeof e=="number"&&(e=String.fromCharCode(e)),this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.pressed}createPointerDown(e){this.onDown(e)}createPointerMove(e){this.onMove(e)}createPointerUp(e){this.onUp(e)}constructor(e){super(),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame.bind(this));let t=this.context.renderer.domElement;t.addEventListener("touchmove",this.onTouchMove.bind(this),{passive:!0}),t.addEventListener("touchend",this.onTouchUp.bind(this),!1),t.addEventListener("pointerdown",this.onPointerDown.bind(this),!1),t.addEventListener("pointermove",this.onPointerMove.bind(this),!1),t.addEventListener("pointerup",this.onPointerUp.bind(this),!1),t.addEventListener("wheel",this.onMouseWheel.bind(this),{passive:!0}),window.addEventListener("keydown",this.onKeyDown.bind(this),!1),window.addEventListener("keypress",this.onKeyPressed.bind(this),!1),window.addEventListener("keyup",this.onKeyUp.bind(this),!1),window.addEventListener("blur",this.onLostFocus.bind(this))}onLostFocus(){for(let e in this.keysPressed)this.keysPressed[e].pressed=!1}onEndOfFrame(){for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(let e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1}keysPressed={};onKeyDown(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.key];t&&t.pressed||(this.keysPressed[e.key]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key},this.onDispatchEvent("keydown",new _s(e)))}onKeyPressed(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.key];!t||(t.pressed=!0,t.frame=this.context.time.frameCount+1,this.onDispatchEvent("keypress",new _s(e)))}onKeyUp(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.key];!t||(t.pressed=!1,t.frame=this.context.time.frameCount+1,this.onDispatchEvent("keyup",new _s(e)))}onMouseWheel(e){this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0}onTouchMove(e){}onTouchUp(e){}onPointerDown(e){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),this.onDown({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e})}onPointerMove(e){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),t<0&&(t=0);let i={button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e};this.onMove(i),this.onDispatchEvent("pointermove",e)}onPointerUp(e){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),this._pointerIds[t]=-1,this.onUp({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e}),this.onDispatchEvent("pointerup",e)}isInRect(e){return!0}onDown(e){if(!!this.isInRect(e)){for(this.setPointerState(e.button,this._pointerPressed,!0),this.setPointerState(e.button,this._pointerDown,!0),this.setPointerStateT(e.button,this._pointerEvent,e.source);e.button>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[e.button]=e.pointerType===void 0?"mouse":e.pointerType;e.button>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new Zt.Vector2);this._pointerPositionDown[e.button].set(e.clientX,e.clientY),e.button>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e.button]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent("pointerdown",e)}}onMove(e){!this.isInRect(e)||(this.updatePointerPosition(e),this.setPointerStateT(e.button,this._pointerEvent,e.source))}onUp(e){if(this.setPointerState(e.button,this._pointerPressed,!1),this.setPointerStateT(e.button,this._pointerEvent,e.source),!this.isInRect(e))return;if(this.setPointerState(e.button,this._pointerUp,!0),this.updatePointerPosition(e),!this._pointerPositionDown[e.button]){console.warn("Received pointer up event without matching down event for button: "+e.button);return}let t=e.clientX-this._pointerPositionDown[e.button].x,i=e.clientY-this._pointerPositionDown[e.button].y;if(e.button>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(t)<5&&Math.abs(i)<5){this.setPointerState(e.button,this._pointerClick,!0);let n=this._pointerUpTime[e.button],r=this.context.time.time-n;r<this._doubleClickTimeThreshold&&r>0&&this.setPointerState(e.button,this._pointerDoubleClick,!0)}this._pointerUpTime[e.button]=this.context.time.time}updatePointerPosition(e){for(;e.button>=this._pointerPositions.length;)this._pointerPositions.push(new Zt.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Zt.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Zt.Vector2);let t=this._pointerPositionsLastFrame[e.button];t.copy(this._pointerPositions[e.button]),this._pointerPositionsDelta[e.button].set(e.clientX-t.x,e.clientY-t.y),this._pointerPositions[e.button].x=e.clientX,this._pointerPositions[e.button].y=e.clientY;let i=e.clientX+window.scrollX,n=e.clientY+window.scrollY;for(;e.button>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new Zt.Vector2);this._pointerPositionsRC[e.button].x=(i-this.context.domX)/this.context.domWidth*2-1,this._pointerPositionsRC[e.button].y=-((n-this.context.domY)/this.context.domHeight)*2+1}getPointerIndex(e){for(let t=0;t<this._pointerIds.length;t++)if(this._pointerIds[t]===e)return t;for(let t=0;t<this._pointerIds.length;t++)if(this._pointerIds[t]===-1&&(this._pointerIds[t]=e),this._pointerIds[t]===e)return t;return this._pointerIds.push(e),this._pointerIds.length-1}setPointerState(e,t,i){for(;t.length<=e;)t.push(!1);t[e]=i}setPointerStateT(e,t,i){for(;t.length<=e;)t.push(null);t[e]=i}onDispatchEvent(e,t){let i=K.Current;try{K.Current=this.context;let n=new Event(e);Tr(n,t),this.dispatchEvent(n)}finally{K.Current=i}}};var Bt=class{constructor(e=[0,0,0,0,0,0,0,0,0]){this.elements=void 0,this.elements=e}identity(){let e=this.elements;e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1}setZero(){let e=this.elements;e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=0,e[6]=0,e[7]=0,e[8]=0}setTrace(e){let t=this.elements;t[0]=e.x,t[4]=e.y,t[8]=e.z}getTrace(e=new _){let t=this.elements;return e.x=t[0],e.y=t[4],e.z=t[8],e}vmult(e,t=new _){let i=this.elements,n=e.x,r=e.y,o=e.z;return t.x=i[0]*n+i[1]*r+i[2]*o,t.y=i[3]*n+i[4]*r+i[5]*o,t.z=i[6]*n+i[7]*r+i[8]*o,t}smult(e){for(let t=0;t<this.elements.length;t++)this.elements[t]*=e}mmult(e,t=new Bt){let i=this.elements,n=e.elements,r=t.elements,o=i[0],s=i[1],c=i[2],d=i[3],l=i[4],h=i[5],u=i[6],f=i[7],x=i[8],b=n[0],y=n[1],g=n[2],p=n[3],m=n[4],v=n[5],w=n[6],E=n[7],C=n[8];return r[0]=o*b+s*p+c*w,r[1]=o*y+s*m+c*E,r[2]=o*g+s*v+c*C,r[3]=d*b+l*p+h*w,r[4]=d*y+l*m+h*E,r[5]=d*g+l*v+h*C,r[6]=u*b+f*p+x*w,r[7]=u*y+f*m+x*E,r[8]=u*g+f*v+x*C,t}scale(e,t=new Bt){let i=this.elements,n=t.elements;for(let r=0;r!==3;r++)n[3*r+0]=e.x*i[3*r+0],n[3*r+1]=e.y*i[3*r+1],n[3*r+2]=e.z*i[3*r+2];return t}solve(e,t=new _){let r=[],o,s;for(o=0;o<3*4;o++)r.push(0);for(o=0;o<3;o++)for(s=0;s<3;s++)r[o+4*s]=this.elements[o+3*s];r[3+4*0]=e.x,r[3+4*1]=e.y,r[3+4*2]=e.z;let c=3,d=c,l,h=4,u;do{if(o=d-c,r[o+4*o]===0){for(s=o+1;s<d;s++)if(r[o+4*s]!==0){l=h;do u=h-l,r[u+4*o]+=r[u+4*s];while(--l);break}}if(r[o+4*o]!==0)for(s=o+1;s<d;s++){let f=r[o+4*s]/r[o+4*o];l=h;do u=h-l,r[u+4*s]=u<=o?0:r[u+4*s]-r[u+4*o]*f;while(--l)}}while(--c);if(t.z=r[2*4+3]/r[2*4+2],t.y=(r[1*4+3]-r[1*4+2]*t.z)/r[1*4+1],t.x=(r[0*4+3]-r[0*4+2]*t.z-r[0*4+1]*t.y)/r[0*4+0],isNaN(t.x)||isNaN(t.y)||isNaN(t.z)||t.x===1/0||t.y===1/0||t.z===1/0)throw"Could not solve equation! Got x=["+t.toString()+"], b=["+e.toString()+"], A=["+this.toString()+"]";return t}e(e,t,i){if(i===void 0)return this.elements[t+3*e];this.elements[t+3*e]=i}copy(e){for(let t=0;t<e.elements.length;t++)this.elements[t]=e.elements[t];return this}toString(){let e="",t=",";for(let i=0;i<9;i++)e+=this.elements[i]+t;return e}reverse(e=new Bt){let n=Pg,r,o;for(r=0;r<3;r++)for(o=0;o<3;o++)n[r+6*o]=this.elements[r+3*o];n[3+6*0]=1,n[3+6*1]=0,n[3+6*2]=0,n[4+6*0]=0,n[4+6*1]=1,n[4+6*2]=0,n[5+6*0]=0,n[5+6*1]=0,n[5+6*2]=1;let s=3,c=s,d,l=6,h;do{if(r=c-s,n[r+6*r]===0){for(o=r+1;o<c;o++)if(n[r+6*o]!==0){d=l;do h=l-d,n[h+6*r]+=n[h+6*o];while(--d);break}}if(n[r+6*r]!==0)for(o=r+1;o<c;o++){let u=n[r+6*o]/n[r+6*r];d=l;do h=l-d,n[h+6*o]=h<=r?0:n[h+6*o]-n[h+6*r]*u;while(--d)}}while(--s);r=2;do{o=r-1;do{let u=n[r+6*o]/n[r+6*r];d=6;do h=6-d,n[h+6*o]=n[h+6*o]-n[h+6*r]*u;while(--d)}while(o--)}while(--r);r=2;do{let u=1/n[r+6*r];d=6;do h=6-d,n[h+6*r]=n[h+6*r]*u;while(--d)}while(r--);r=2;do{o=2;do{if(h=n[3+o+6*r],isNaN(h)||h===1/0)throw"Could not reverse! A=["+this.toString()+"]";e.e(r,o,h)}while(o--)}while(r--);return e}setRotationFromQuaternion(e){let t=e.x,i=e.y,n=e.z,r=e.w,o=t+t,s=i+i,c=n+n,d=t*o,l=t*s,h=t*c,u=i*s,f=i*c,x=n*c,b=r*o,y=r*s,g=r*c,p=this.elements;return p[3*0+0]=1-(u+x),p[3*0+1]=l-g,p[3*0+2]=h+y,p[3*1+0]=l+g,p[3*1+1]=1-(d+x),p[3*1+2]=f-b,p[3*2+0]=h-y,p[3*2+1]=f+b,p[3*2+2]=1-(d+u),this}transpose(e=new Bt){let t=this.elements,i=e.elements,n;return i[0]=t[0],i[4]=t[4],i[8]=t[8],n=t[1],i[1]=t[3],i[3]=n,n=t[2],i[2]=t[6],i[6]=n,n=t[5],i[5]=t[7],i[7]=n,e}},Pg=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],_=class{constructor(e=0,t=0,i=0){this.x=void 0,this.y=void 0,this.z=void 0,this.x=e,this.y=t,this.z=i}cross(e,t=new _){let i=e.x,n=e.y,r=e.z,o=this.x,s=this.y,c=this.z;return t.x=s*r-c*n,t.y=c*i-o*r,t.z=o*n-s*i,t}set(e,t,i){return this.x=e,this.y=t,this.z=i,this}setZero(){this.x=this.y=this.z=0}vadd(e,t){if(t)t.x=e.x+this.x,t.y=e.y+this.y,t.z=e.z+this.z;else return new _(this.x+e.x,this.y+e.y,this.z+e.z)}vsub(e,t){if(t)t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z;else return new _(this.x-e.x,this.y-e.y,this.z-e.z)}crossmat(){return new Bt([0,-this.z,this.y,this.z,0,-this.x,-this.y,this.x,0])}normalize(){let e=this.x,t=this.y,i=this.z,n=Math.sqrt(e*e+t*t+i*i);if(n>0){let r=1/n;this.x*=r,this.y*=r,this.z*=r}else this.x=0,this.y=0,this.z=0;return n}unit(e=new _){let t=this.x,i=this.y,n=this.z,r=Math.sqrt(t*t+i*i+n*n);return r>0?(r=1/r,e.x=t*r,e.y=i*r,e.z=n*r):(e.x=1,e.y=0,e.z=0),e}length(){let e=this.x,t=this.y,i=this.z;return Math.sqrt(e*e+t*t+i*i)}lengthSquared(){return this.dot(this)}distanceTo(e){let t=this.x,i=this.y,n=this.z,r=e.x,o=e.y,s=e.z;return Math.sqrt((r-t)*(r-t)+(o-i)*(o-i)+(s-n)*(s-n))}distanceSquared(e){let t=this.x,i=this.y,n=this.z,r=e.x,o=e.y,s=e.z;return(r-t)*(r-t)+(o-i)*(o-i)+(s-n)*(s-n)}scale(e,t=new _){let i=this.x,n=this.y,r=this.z;return t.x=e*i,t.y=e*n,t.z=e*r,t}vmul(e,t=new _){return t.x=e.x*this.x,t.y=e.y*this.y,t.z=e.z*this.z,t}addScaledVector(e,t,i=new _){return i.x=this.x+e*t.x,i.y=this.y+e*t.y,i.z=this.z+e*t.z,i}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}isZero(){return this.x===0&&this.y===0&&this.z===0}negate(e=new _){return e.x=-this.x,e.y=-this.y,e.z=-this.z,e}tangents(e,t){let i=this.length();if(i>0){let n=Og,r=1/i;n.set(this.x*r,this.y*r,this.z*r);let o=Ig;Math.abs(n.x)<.9?(o.set(1,0,0),n.cross(o,e)):(o.set(0,1,0),n.cross(o,e)),n.cross(e,t)}else e.set(1,0,0),t.set(0,1,0)}toString(){return this.x+","+this.y+","+this.z}toArray(){return[this.x,this.y,this.z]}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}lerp(e,t,i){let n=this.x,r=this.y,o=this.z;i.x=n+(e.x-n)*t,i.y=r+(e.y-r)*t,i.z=o+(e.z-o)*t}almostEquals(e,t=1e-6){return!(Math.abs(this.x-e.x)>t||Math.abs(this.y-e.y)>t||Math.abs(this.z-e.z)>t)}almostZero(e=1e-6){return!(Math.abs(this.x)>e||Math.abs(this.y)>e||Math.abs(this.z)>e)}isAntiparallelTo(e,t){return this.negate(Pu),Pu.almostEquals(e,t)}clone(){return new _(this.x,this.y,this.z)}};_.ZERO=void 0;_.UNIT_X=void 0;_.UNIT_Y=void 0;_.UNIT_Z=void 0;_.ZERO=new _(0,0,0);_.UNIT_X=new _(1,0,0);_.UNIT_Y=new _(0,1,0);_.UNIT_Z=new _(0,0,1);var Og=new _,Ig=new _,Pu=new _,Ze=class{constructor(e={}){this.lowerBound=void 0,this.upperBound=void 0,this.lowerBound=new _,this.upperBound=new _,e.lowerBound&&this.lowerBound.copy(e.lowerBound),e.upperBound&&this.upperBound.copy(e.upperBound)}setFromPoints(e,t,i,n){let r=this.lowerBound,o=this.upperBound,s=i;r.copy(e[0]),s&&s.vmult(r,r),o.copy(r);for(let c=1;c<e.length;c++){let d=e[c];s&&(s.vmult(d,Ou),d=Ou),d.x>o.x&&(o.x=d.x),d.x<r.x&&(r.x=d.x),d.y>o.y&&(o.y=d.y),d.y<r.y&&(r.y=d.y),d.z>o.z&&(o.z=d.z),d.z<r.z&&(r.z=d.z)}return t&&(t.vadd(r,r),t.vadd(o,o)),n&&(r.x-=n,r.y-=n,r.z-=n,o.x+=n,o.y+=n,o.z+=n),this}copy(e){return this.lowerBound.copy(e.lowerBound),this.upperBound.copy(e.upperBound),this}clone(){return new Ze().copy(this)}extend(e){this.lowerBound.x=Math.min(this.lowerBound.x,e.lowerBound.x),this.upperBound.x=Math.max(this.upperBound.x,e.upperBound.x),this.lowerBound.y=Math.min(this.lowerBound.y,e.lowerBound.y),this.upperBound.y=Math.max(this.upperBound.y,e.upperBound.y),this.lowerBound.z=Math.min(this.lowerBound.z,e.lowerBound.z),this.upperBound.z=Math.max(this.upperBound.z,e.upperBound.z)}overlaps(e){let t=this.lowerBound,i=this.upperBound,n=e.lowerBound,r=e.upperBound,o=n.x<=i.x&&i.x<=r.x||t.x<=r.x&&r.x<=i.x,s=n.y<=i.y&&i.y<=r.y||t.y<=r.y&&r.y<=i.y,c=n.z<=i.z&&i.z<=r.z||t.z<=r.z&&r.z<=i.z;return o&&s&&c}volume(){let e=this.lowerBound,t=this.upperBound;return(t.x-e.x)*(t.y-e.y)*(t.z-e.z)}contains(e){let t=this.lowerBound,i=this.upperBound,n=e.lowerBound,r=e.upperBound;return t.x<=n.x&&i.x>=r.x&&t.y<=n.y&&i.y>=r.y&&t.z<=n.z&&i.z>=r.z}getCorners(e,t,i,n,r,o,s,c){let d=this.lowerBound,l=this.upperBound;e.copy(d),t.set(l.x,d.y,d.z),i.set(l.x,l.y,d.z),n.set(d.x,l.y,l.z),r.set(l.x,d.y,l.z),o.set(d.x,l.y,d.z),s.set(d.x,d.y,l.z),c.copy(l)}toLocalFrame(e,t){let i=Iu,n=i[0],r=i[1],o=i[2],s=i[3],c=i[4],d=i[5],l=i[6],h=i[7];this.getCorners(n,r,o,s,c,d,l,h);for(let u=0;u!==8;u++){let f=i[u];e.pointToLocal(f,f)}return t.setFromPoints(i)}toWorldFrame(e,t){let i=Iu,n=i[0],r=i[1],o=i[2],s=i[3],c=i[4],d=i[5],l=i[6],h=i[7];this.getCorners(n,r,o,s,c,d,l,h);for(let u=0;u!==8;u++){let f=i[u];e.pointToWorld(f,f)}return t.setFromPoints(i)}overlapsRay(e){let{direction:t,from:i}=e,n=1/t.x,r=1/t.y,o=1/t.z,s=(this.lowerBound.x-i.x)*n,c=(this.upperBound.x-i.x)*n,d=(this.lowerBound.y-i.y)*r,l=(this.upperBound.y-i.y)*r,h=(this.lowerBound.z-i.z)*o,u=(this.upperBound.z-i.z)*o,f=Math.max(Math.max(Math.min(s,c),Math.min(d,l)),Math.min(h,u)),x=Math.min(Math.min(Math.max(s,c),Math.max(d,l)),Math.max(h,u));return!(x<0||f>x)}},Ou=new _,Iu=[new _,new _,new _,new _,new _,new _,new _,new _],Ca=class{constructor(){this.matrix=void 0,this.matrix=[]}get(e,t){let{index:i}=e,{index:n}=t;if(n>i){let r=n;n=i,i=r}return this.matrix[(i*(i+1)>>1)+n-1]}set(e,t,i){let{index:n}=e,{index:r}=t;if(r>n){let o=r;r=n,n=o}this.matrix[(n*(n+1)>>1)+r-1]=i?1:0}reset(){for(let e=0,t=this.matrix.length;e!==t;e++)this.matrix[e]=0}setNumObjects(e){this.matrix.length=e*(e-1)>>1}},Ta=class{constructor(){this._listeners=void 0}addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let i=this._listeners;return i[e]===void 0&&(i[e]=[]),i[e].includes(t)||i[e].push(t),this}hasEventListener(e,t){if(this._listeners===void 0)return!1;let i=this._listeners;return!!(i[e]!==void 0&&i[e].includes(t))}hasAnyEventListener(e){return this._listeners===void 0?!1:this._listeners[e]!==void 0}removeEventListener(e,t){if(this._listeners===void 0)return this;let i=this._listeners;if(i[e]===void 0)return this;let n=i[e].indexOf(t);return n!==-1&&i[e].splice(n,1),this}dispatchEvent(e){if(this._listeners===void 0)return this;let i=this._listeners[e.type];if(i!==void 0){e.target=this;for(let n=0,r=i.length;n<r;n++)i[n].call(this,e)}return this}},ce=class{constructor(e=0,t=0,i=0,n=1){this.x=void 0,this.y=void 0,this.z=void 0,this.w=void 0,this.x=e,this.y=t,this.z=i,this.w=n}set(e,t,i,n){return this.x=e,this.y=t,this.z=i,this.w=n,this}toString(){return this.x+","+this.y+","+this.z+","+this.w}toArray(){return[this.x,this.y,this.z,this.w]}setFromAxisAngle(e,t){let i=Math.sin(t*.5);return this.x=e.x*i,this.y=e.y*i,this.z=e.z*i,this.w=Math.cos(t*.5),this}toAxisAngle(e=new _){this.normalize();let t=2*Math.acos(this.w),i=Math.sqrt(1-this.w*this.w);return i<.001?(e.x=this.x,e.y=this.y,e.z=this.z):(e.x=this.x/i,e.y=this.y/i,e.z=this.z/i),[e,t]}setFromVectors(e,t){if(e.isAntiparallelTo(t)){let i=kg,n=Ag;e.tangents(i,n),this.setFromAxisAngle(i,Math.PI)}else{let i=e.cross(t);this.x=i.x,this.y=i.y,this.z=i.z,this.w=Math.sqrt(e.length()**2*t.length()**2)+e.dot(t),this.normalize()}return this}mult(e,t=new ce){let i=this.x,n=this.y,r=this.z,o=this.w,s=e.x,c=e.y,d=e.z,l=e.w;return t.x=i*l+o*s+n*d-r*c,t.y=n*l+o*c+r*s-i*d,t.z=r*l+o*d+i*c-n*s,t.w=o*l-i*s-n*c-r*d,t}inverse(e=new ce){let t=this.x,i=this.y,n=this.z,r=this.w;this.conjugate(e);let o=1/(t*t+i*i+n*n+r*r);return e.x*=o,e.y*=o,e.z*=o,e.w*=o,e}conjugate(e=new ce){return e.x=-this.x,e.y=-this.y,e.z=-this.z,e.w=this.w,e}normalize(){let e=Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);return e===0?(this.x=0,this.y=0,this.z=0,this.w=0):(e=1/e,this.x*=e,this.y*=e,this.z*=e,this.w*=e),this}normalizeFast(){let e=(3-(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w))/2;return e===0?(this.x=0,this.y=0,this.z=0,this.w=0):(this.x*=e,this.y*=e,this.z*=e,this.w*=e),this}vmult(e,t=new _){let i=e.x,n=e.y,r=e.z,o=this.x,s=this.y,c=this.z,d=this.w,l=d*i+s*r-c*n,h=d*n+c*i-o*r,u=d*r+o*n-s*i,f=-o*i-s*n-c*r;return t.x=l*d+f*-o+h*-c-u*-s,t.y=h*d+f*-s+u*-o-l*-c,t.z=u*d+f*-c+l*-s-h*-o,t}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}toEuler(e,t="YZX"){let i,n,r,o=this.x,s=this.y,c=this.z,d=this.w;switch(t){case"YZX":let l=o*s+c*d;if(l>.499&&(i=2*Math.atan2(o,d),n=Math.PI/2,r=0),l<-.499&&(i=-2*Math.atan2(o,d),n=-Math.PI/2,r=0),i===void 0){let h=o*o,u=s*s,f=c*c;i=Math.atan2(2*s*d-2*o*c,1-2*u-2*f),n=Math.asin(2*l),r=Math.atan2(2*o*d-2*s*c,1-2*h-2*f)}break;default:throw new Error("Euler order "+t+" not supported yet.")}e.y=i,e.z=n,e.x=r}setFromEuler(e,t,i,n="XYZ"){let r=Math.cos(e/2),o=Math.cos(t/2),s=Math.cos(i/2),c=Math.sin(e/2),d=Math.sin(t/2),l=Math.sin(i/2);return n==="XYZ"?(this.x=c*o*s+r*d*l,this.y=r*d*s-c*o*l,this.z=r*o*l+c*d*s,this.w=r*o*s-c*d*l):n==="YXZ"?(this.x=c*o*s+r*d*l,this.y=r*d*s-c*o*l,this.z=r*o*l-c*d*s,this.w=r*o*s+c*d*l):n==="ZXY"?(this.x=c*o*s-r*d*l,this.y=r*d*s+c*o*l,this.z=r*o*l+c*d*s,this.w=r*o*s-c*d*l):n==="ZYX"?(this.x=c*o*s-r*d*l,this.y=r*d*s+c*o*l,this.z=r*o*l-c*d*s,this.w=r*o*s+c*d*l):n==="YZX"?(this.x=c*o*s+r*d*l,this.y=r*d*s+c*o*l,this.z=r*o*l-c*d*s,this.w=r*o*s-c*d*l):n==="XZY"&&(this.x=c*o*s-r*d*l,this.y=r*d*s-c*o*l,this.z=r*o*l+c*d*s,this.w=r*o*s+c*d*l),this}clone(){return new ce(this.x,this.y,this.z,this.w)}slerp(e,t,i=new ce){let n=this.x,r=this.y,o=this.z,s=this.w,c=e.x,d=e.y,l=e.z,h=e.w,u,f,x,b,y;return f=n*c+r*d+o*l+s*h,f<0&&(f=-f,c=-c,d=-d,l=-l,h=-h),1-f>1e-6?(u=Math.acos(f),x=Math.sin(u),b=Math.sin((1-t)*u)/x,y=Math.sin(t*u)/x):(b=1-t,y=t),i.x=b*n+y*c,i.y=b*r+y*d,i.z=b*o+y*l,i.w=b*s+y*h,i}integrate(e,t,i,n=new ce){let r=e.x*i.x,o=e.y*i.y,s=e.z*i.z,c=this.x,d=this.y,l=this.z,h=this.w,u=t*.5;return n.x+=u*(r*h+o*l-s*d),n.y+=u*(o*h+s*c-r*l),n.z+=u*(s*h+r*d-o*c),n.w+=u*(-r*c-o*d-s*l),n}},kg=new _,Ag=new _,Mg={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},V=class{constructor(e={}){this.id=void 0,this.type=void 0,this.boundingSphereRadius=void 0,this.collisionResponse=void 0,this.collisionFilterGroup=void 0,this.collisionFilterMask=void 0,this.material=void 0,this.body=void 0,this.id=V.idCounter++,this.type=e.type||0,this.boundingSphereRadius=0,this.collisionResponse=e.collisionResponse?e.collisionResponse:!0,this.collisionFilterGroup=e.collisionFilterGroup!==void 0?e.collisionFilterGroup:1,this.collisionFilterMask=e.collisionFilterMask!==void 0?e.collisionFilterMask:-1,this.material=e.material?e.material:null,this.body=null}updateBoundingSphereRadius(){throw"computeBoundingSphereRadius() not implemented for shape type "+this.type}volume(){throw"volume() not implemented for shape type "+this.type}calculateLocalInertia(e,t){throw"calculateLocalInertia() not implemented for shape type "+this.type}calculateWorldAABB(e,t,i,n){throw"calculateWorldAABB() not implemented for shape type "+this.type}};V.idCounter=0;V.types=Mg;var te=class{constructor(e={}){this.position=void 0,this.quaternion=void 0,this.position=new _,this.quaternion=new ce,e.position&&this.position.copy(e.position),e.quaternion&&this.quaternion.copy(e.quaternion)}pointToLocal(e,t){return te.pointToLocalFrame(this.position,this.quaternion,e,t)}pointToWorld(e,t){return te.pointToWorldFrame(this.position,this.quaternion,e,t)}vectorToWorldFrame(e,t=new _){return this.quaternion.vmult(e,t),t}static pointToLocalFrame(e,t,i,n=new _){return i.vsub(e,n),t.conjugate(ku),ku.vmult(n,n),n}static pointToWorldFrame(e,t,i,n=new _){return t.vmult(i,n),n.vadd(e,n),n}static vectorToWorldFrame(e,t,i=new _){return e.vmult(t,i),i}static vectorToLocalFrame(e,t,i,n=new _){return t.w*=-1,t.vmult(i,n),t.w*=-1,n}},ku=new ce,Pr=class extends V{constructor(e={}){let{vertices:t=[],faces:i=[],normals:n=[],axes:r,boundingSphereRadius:o}=e;super({type:V.types.CONVEXPOLYHEDRON}),this.vertices=void 0,this.faces=void 0,this.faceNormals=void 0,this.worldVertices=void 0,this.worldVerticesNeedsUpdate=void 0,this.worldFaceNormals=void 0,this.worldFaceNormalsNeedsUpdate=void 0,this.uniqueAxes=void 0,this.uniqueEdges=void 0,this.vertices=t,this.faces=i,this.faceNormals=n,this.faceNormals.length===0&&this.computeNormals(),o?this.boundingSphereRadius=o:this.updateBoundingSphereRadius(),this.worldVertices=[],this.worldVerticesNeedsUpdate=!0,this.worldFaceNormals=[],this.worldFaceNormalsNeedsUpdate=!0,this.uniqueAxes=r?r.slice():null,this.uniqueEdges=[],this.computeEdges()}computeEdges(){let e=this.faces,t=this.vertices,i=this.uniqueEdges;i.length=0;let n=new _;for(let r=0;r!==e.length;r++){let o=e[r],s=o.length;for(let c=0;c!==s;c++){let d=(c+1)%s;t[o[c]].vsub(t[o[d]],n),n.normalize();let l=!1;for(let h=0;h!==i.length;h++)if(i[h].almostEquals(n)||i[h].almostEquals(n)){l=!0;break}l||i.push(n.clone())}}}computeNormals(){this.faceNormals.length=this.faces.length;for(let e=0;e<this.faces.length;e++){for(let n=0;n<this.faces[e].length;n++)if(!this.vertices[this.faces[e][n]])throw new Error("Vertex "+this.faces[e][n]+" not found!");let t=this.faceNormals[e]||new _;this.getFaceNormal(e,t),t.negate(t),this.faceNormals[e]=t;let i=this.vertices[this.faces[e][0]];if(t.dot(i)<0){console.error(".faceNormals["+e+"] = Vec3("+t.toString()+") looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.");for(let n=0;n<this.faces[e].length;n++)console.warn(".vertices["+this.faces[e][n]+"] = Vec3("+this.vertices[this.faces[e][n]].toString()+")")}}}getFaceNormal(e,t){let i=this.faces[e],n=this.vertices[i[0]],r=this.vertices[i[1]],o=this.vertices[i[2]];Pr.computeNormal(n,r,o,t)}static computeNormal(e,t,i,n){let r=new _,o=new _;t.vsub(e,o),i.vsub(t,r),r.cross(o,n),n.isZero()||n.normalize()}clipAgainstHull(e,t,i,n,r,o,s,c,d){let l=new _,h=-1,u=-Number.MAX_VALUE;for(let x=0;x<i.faces.length;x++){l.copy(i.faceNormals[x]),r.vmult(l,l);let b=l.dot(o);b>u&&(u=b,h=x)}let f=[];for(let x=0;x<i.faces[h].length;x++){let b=i.vertices[i.faces[h][x]],y=new _;y.copy(b),r.vmult(y,y),n.vadd(y,y),f.push(y)}h>=0&&this.clipFaceAgainstHull(o,e,t,f,s,c,d)}findSeparatingAxis(e,t,i,n,r,o,s,c){let d=new _,l=new _,h=new _,u=new _,f=new _,x=new _,b=Number.MAX_VALUE,y=this;if(y.uniqueAxes)for(let g=0;g!==y.uniqueAxes.length;g++){i.vmult(y.uniqueAxes[g],d);let p=y.testSepAxis(d,e,t,i,n,r);if(p===!1)return!1;p<b&&(b=p,o.copy(d))}else{let g=s?s.length:y.faces.length;for(let p=0;p<g;p++){let m=s?s[p]:p;d.copy(y.faceNormals[m]),i.vmult(d,d);let v=y.testSepAxis(d,e,t,i,n,r);if(v===!1)return!1;v<b&&(b=v,o.copy(d))}}if(e.uniqueAxes)for(let g=0;g!==e.uniqueAxes.length;g++){r.vmult(e.uniqueAxes[g],l);let p=y.testSepAxis(l,e,t,i,n,r);if(p===!1)return!1;p<b&&(b=p,o.copy(l))}else{let g=c?c.length:e.faces.length;for(let p=0;p<g;p++){let m=c?c[p]:p;l.copy(e.faceNormals[m]),r.vmult(l,l);let v=y.testSepAxis(l,e,t,i,n,r);if(v===!1)return!1;v<b&&(b=v,o.copy(l))}}for(let g=0;g!==y.uniqueEdges.length;g++){i.vmult(y.uniqueEdges[g],u);for(let p=0;p!==e.uniqueEdges.length;p++)if(r.vmult(e.uniqueEdges[p],f),u.cross(f,x),!x.almostZero()){x.normalize();let m=y.testSepAxis(x,e,t,i,n,r);if(m===!1)return!1;m<b&&(b=m,o.copy(x))}}return n.vsub(t,h),h.dot(o)>0&&o.negate(o),!0}testSepAxis(e,t,i,n,r,o){let s=this;Pr.project(s,e,i,n,Cc),Pr.project(t,e,r,o,Tc);let c=Cc[0],d=Cc[1],l=Tc[0],h=Tc[1];if(c<h||l<d)return!1;let u=c-h,f=l-d;return u<f?u:f}calculateLocalInertia(e,t){let i=new _,n=new _;this.computeLocalAABB(n,i);let r=i.x-n.x,o=i.y-n.y,s=i.z-n.z;t.x=1/12*e*(2*o*2*o+2*s*2*s),t.y=1/12*e*(2*r*2*r+2*s*2*s),t.z=1/12*e*(2*o*2*o+2*r*2*r)}getPlaneConstantOfFace(e){let t=this.faces[e],i=this.faceNormals[e],n=this.vertices[t[0]];return-i.dot(n)}clipFaceAgainstHull(e,t,i,n,r,o,s){let c=new _,d=new _,l=new _,h=new _,u=new _,f=new _,x=new _,b=new _,y=this,g=[],p=n,m=g,v=-1,w=Number.MAX_VALUE;for(let I=0;I<y.faces.length;I++){c.copy(y.faceNormals[I]),i.vmult(c,c);let O=c.dot(e);O<w&&(w=O,v=I)}if(v<0)return;let E=y.faces[v];E.connectedFaces=[];for(let I=0;I<y.faces.length;I++)for(let O=0;O<y.faces[I].length;O++)E.indexOf(y.faces[I][O])!==-1&&I!==v&&E.connectedFaces.indexOf(I)===-1&&E.connectedFaces.push(I);let C=E.length;for(let I=0;I<C;I++){let O=y.vertices[E[I]],L=y.vertices[E[(I+1)%C]];O.vsub(L,d),l.copy(d),i.vmult(l,l),t.vadd(l,l),h.copy(this.faceNormals[v]),i.vmult(h,h),t.vadd(h,h),l.cross(h,u),u.negate(u),f.copy(O),i.vmult(f,f),t.vadd(f,f);let A=E.connectedFaces[I];x.copy(this.faceNormals[A]);let F=this.getPlaneConstantOfFace(A);b.copy(x),i.vmult(b,b);let H=F-b.dot(t);for(this.clipFaceAgainstPlane(p,m,b,H);p.length;)p.shift();for(;m.length;)p.push(m.shift())}x.copy(this.faceNormals[v]);let T=this.getPlaneConstantOfFace(v);b.copy(x),i.vmult(b,b);let R=T-b.dot(t);for(let I=0;I<p.length;I++){let O=b.dot(p[I])+R;if(O<=r&&(console.log("clamped: depth="+O+" to minDist="+r),O=r),O<=o){let L=p[I];if(O<=1e-6){let A={point:L,normal:b,depth:O};s.push(A)}}}}clipFaceAgainstPlane(e,t,i,n){let r,o,s=e.length;if(s<2)return t;let c=e[e.length-1],d=e[0];r=i.dot(c)+n;for(let l=0;l<s;l++){if(d=e[l],o=i.dot(d)+n,r<0)if(o<0){let h=new _;h.copy(d),t.push(h)}else{let h=new _;c.lerp(d,r/(r-o),h),t.push(h)}else if(o<0){let h=new _;c.lerp(d,r/(r-o),h),t.push(h),t.push(d)}c=d,r=o}return t}computeWorldVertices(e,t){for(;this.worldVertices.length<this.vertices.length;)this.worldVertices.push(new _);let i=this.vertices,n=this.worldVertices;for(let r=0;r!==this.vertices.length;r++)t.vmult(i[r],n[r]),e.vadd(n[r],n[r]);this.worldVerticesNeedsUpdate=!1}computeLocalAABB(e,t){let i=this.vertices;e.set(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),t.set(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let n=0;n<this.vertices.length;n++){let r=i[n];r.x<e.x?e.x=r.x:r.x>t.x&&(t.x=r.x),r.y<e.y?e.y=r.y:r.y>t.y&&(t.y=r.y),r.z<e.z?e.z=r.z:r.z>t.z&&(t.z=r.z)}}computeWorldFaceNormals(e){let t=this.faceNormals.length;for(;this.worldFaceNormals.length<t;)this.worldFaceNormals.push(new _);let i=this.faceNormals,n=this.worldFaceNormals;for(let r=0;r!==t;r++)e.vmult(i[r],n[r]);this.worldFaceNormalsNeedsUpdate=!1}updateBoundingSphereRadius(){let e=0,t=this.vertices;for(let i=0;i!==t.length;i++){let n=t[i].lengthSquared();n>e&&(e=n)}this.boundingSphereRadius=Math.sqrt(e)}calculateWorldAABB(e,t,i,n){let r=this.vertices,o,s,c,d,l,h,u=new _;for(let f=0;f<r.length;f++){u.copy(r[f]),t.vmult(u,u),e.vadd(u,u);let x=u;(o===void 0||x.x<o)&&(o=x.x),(d===void 0||x.x>d)&&(d=x.x),(s===void 0||x.y<s)&&(s=x.y),(l===void 0||x.y>l)&&(l=x.y),(c===void 0||x.z<c)&&(c=x.z),(h===void 0||x.z>h)&&(h=x.z)}i.set(o,s,c),n.set(d,l,h)}volume(){return 4*Math.PI*this.boundingSphereRadius/3}getAveragePointLocal(e=new _){let t=this.vertices;for(let i=0;i<t.length;i++)e.vadd(t[i],e);return e.scale(1/t.length,e),e}transformAllPoints(e,t){let i=this.vertices.length,n=this.vertices;if(t){for(let r=0;r<i;r++){let o=n[r];t.vmult(o,o)}for(let r=0;r<this.faceNormals.length;r++){let o=this.faceNormals[r];t.vmult(o,o)}}if(e)for(let r=0;r<i;r++){let o=n[r];o.vadd(e,o)}}pointIsInside(e){let t=this.vertices,i=this.faces,n=this.faceNormals,r=new _;this.getAveragePointLocal(r);for(let o=0;o<this.faces.length;o++){let s=n[o],c=t[i[o][0]],d=new _;e.vsub(c,d);let l=s.dot(d),h=new _;r.vsub(c,h);let u=s.dot(h);if(l<0&&u>0||l>0&&u<0)return!1}return-1}static project(e,t,i,n,r){let o=e.vertices.length,s=Lg,c=0,d=0,l=Dg,h=e.vertices;l.setZero(),te.vectorToLocalFrame(i,n,t,s),te.pointToLocalFrame(i,n,l,l);let u=l.dot(s);d=c=h[0].dot(s);for(let f=1;f<o;f++){let x=h[f].dot(s);x>c&&(c=x),x<d&&(d=x)}if(d-=u,c-=u,d>c){let f=d;d=c,c=f}r[0]=c,r[1]=d}},Cc=[],Tc=[],Lg=new _,Dg=new _,Or=class extends V{constructor(e){super({type:V.types.BOX}),this.halfExtents=void 0,this.convexPolyhedronRepresentation=void 0,this.halfExtents=e,this.convexPolyhedronRepresentation=null,this.updateConvexPolyhedronRepresentation(),this.updateBoundingSphereRadius()}updateConvexPolyhedronRepresentation(){let e=this.halfExtents.x,t=this.halfExtents.y,i=this.halfExtents.z,n=_,r=[new n(-e,-t,-i),new n(e,-t,-i),new n(e,t,-i),new n(-e,t,-i),new n(-e,-t,i),new n(e,-t,i),new n(e,t,i),new n(-e,t,i)],o=[[3,2,1,0],[4,5,6,7],[5,4,0,1],[2,3,7,6],[0,4,7,3],[1,2,6,5]],s=[new n(0,0,1),new n(0,1,0),new n(1,0,0)],c=new Pr({vertices:r,faces:o,axes:s});this.convexPolyhedronRepresentation=c,c.material=this.material}calculateLocalInertia(e,t=new _){return Or.calculateInertia(this.halfExtents,e,t),t}static calculateInertia(e,t,i){let n=e;i.x=1/12*t*(2*n.y*2*n.y+2*n.z*2*n.z),i.y=1/12*t*(2*n.x*2*n.x+2*n.z*2*n.z),i.z=1/12*t*(2*n.y*2*n.y+2*n.x*2*n.x)}getSideNormals(e,t){let i=e,n=this.halfExtents;if(i[0].set(n.x,0,0),i[1].set(0,n.y,0),i[2].set(0,0,n.z),i[3].set(-n.x,0,0),i[4].set(0,-n.y,0),i[5].set(0,0,-n.z),t!==void 0)for(let r=0;r!==i.length;r++)t.vmult(i[r],i[r]);return i}volume(){return 8*this.halfExtents.x*this.halfExtents.y*this.halfExtents.z}updateBoundingSphereRadius(){this.boundingSphereRadius=this.halfExtents.length()}forEachWorldCorner(e,t,i){let n=this.halfExtents,r=[[n.x,n.y,n.z],[-n.x,n.y,n.z],[-n.x,-n.y,n.z],[-n.x,-n.y,-n.z],[n.x,-n.y,-n.z],[n.x,n.y,-n.z],[-n.x,n.y,-n.z],[n.x,-n.y,n.z]];for(let o=0;o<r.length;o++)Fn.set(r[o][0],r[o][1],r[o][2]),t.vmult(Fn,Fn),e.vadd(Fn,Fn),i(Fn.x,Fn.y,Fn.z)}calculateWorldAABB(e,t,i,n){let r=this.halfExtents;Ei[0].set(r.x,r.y,r.z),Ei[1].set(-r.x,r.y,r.z),Ei[2].set(-r.x,-r.y,r.z),Ei[3].set(-r.x,-r.y,-r.z),Ei[4].set(r.x,-r.y,-r.z),Ei[5].set(r.x,r.y,-r.z),Ei[6].set(-r.x,r.y,-r.z),Ei[7].set(r.x,-r.y,r.z);let o=Ei[0];t.vmult(o,o),e.vadd(o,o),n.copy(o),i.copy(o);for(let s=1;s<8;s++){let c=Ei[s];t.vmult(c,c),e.vadd(c,c);let d=c.x,l=c.y,h=c.z;d>n.x&&(n.x=d),l>n.y&&(n.y=l),h>n.z&&(n.z=h),d<i.x&&(i.x=d),l<i.y&&(i.y=l),h<i.z&&(i.z=h)}}},Fn=new _,Ei=[new _,new _,new _,new _,new _,new _,new _,new _],Hc={DYNAMIC:1,STATIC:2,KINEMATIC:4},Fc={AWAKE:0,SLEEPY:1,SLEEPING:2},G=class extends Ta{constructor(e={}){super(),this.id=void 0,this.index=void 0,this.world=void 0,this.preStep=void 0,this.postStep=void 0,this.vlambda=void 0,this.collisionFilterGroup=void 0,this.collisionFilterMask=void 0,this.collisionResponse=void 0,this.position=void 0,this.previousPosition=void 0,this.interpolatedPosition=void 0,this.initPosition=void 0,this.velocity=void 0,this.initVelocity=void 0,this.force=void 0,this.mass=void 0,this.invMass=void 0,this.material=void 0,this.linearDamping=void 0,this.type=void 0,this.allowSleep=void 0,this.sleepState=void 0,this.sleepSpeedLimit=void 0,this.sleepTimeLimit=void 0,this.timeLastSleepy=void 0,this.wakeUpAfterNarrowphase=void 0,this.torque=void 0,this.quaternion=void 0,this.initQuaternion=void 0,this.previousQuaternion=void 0,this.interpolatedQuaternion=void 0,this.angularVelocity=void 0,this.initAngularVelocity=void 0,this.shapes=void 0,this.shapeOffsets=void 0,this.shapeOrientations=void 0,this.inertia=void 0,this.invInertia=void 0,this.invInertiaWorld=void 0,this.invMassSolve=void 0,this.invInertiaSolve=void 0,this.invInertiaWorldSolve=void 0,this.fixedRotation=void 0,this.angularDamping=void 0,this.linearFactor=void 0,this.angularFactor=void 0,this.aabb=void 0,this.aabbNeedsUpdate=void 0,this.boundingRadius=void 0,this.wlambda=void 0,this.isTrigger=void 0,this.id=G.idCounter++,this.index=-1,this.world=null,this.preStep=null,this.postStep=null,this.vlambda=new _,this.collisionFilterGroup=typeof e.collisionFilterGroup=="number"?e.collisionFilterGroup:1,this.collisionFilterMask=typeof e.collisionFilterMask=="number"?e.collisionFilterMask:-1,this.collisionResponse=typeof e.collisionResponse=="boolean"?e.collisionResponse:!0,this.position=new _,this.previousPosition=new _,this.interpolatedPosition=new _,this.initPosition=new _,e.position&&(this.position.copy(e.position),this.previousPosition.copy(e.position),this.interpolatedPosition.copy(e.position),this.initPosition.copy(e.position)),this.velocity=new _,e.velocity&&this.velocity.copy(e.velocity),this.initVelocity=new _,this.force=new _;let t=typeof e.mass=="number"?e.mass:0;this.mass=t,this.invMass=t>0?1/t:0,this.material=e.material||null,this.linearDamping=typeof e.linearDamping=="number"?e.linearDamping:.01,this.type=t<=0?G.STATIC:G.DYNAMIC,typeof e.type==typeof G.STATIC&&(this.type=e.type),this.allowSleep=typeof e.allowSleep<"u"?e.allowSleep:!0,this.sleepState=G.AWAKE,this.sleepSpeedLimit=typeof e.sleepSpeedLimit<"u"?e.sleepSpeedLimit:.1,this.sleepTimeLimit=typeof e.sleepTimeLimit<"u"?e.sleepTimeLimit:1,this.timeLastSleepy=0,this.wakeUpAfterNarrowphase=!1,this.torque=new _,this.quaternion=new ce,this.initQuaternion=new ce,this.previousQuaternion=new ce,this.interpolatedQuaternion=new ce,e.quaternion&&(this.quaternion.copy(e.quaternion),this.initQuaternion.copy(e.quaternion),this.previousQuaternion.copy(e.quaternion),this.interpolatedQuaternion.copy(e.quaternion)),this.angularVelocity=new _,e.angularVelocity&&this.angularVelocity.copy(e.angularVelocity),this.initAngularVelocity=new _,this.shapes=[],this.shapeOffsets=[],this.shapeOrientations=[],this.inertia=new _,this.invInertia=new _,this.invInertiaWorld=new Bt,this.invMassSolve=0,this.invInertiaSolve=new _,this.invInertiaWorldSolve=new Bt,this.fixedRotation=typeof e.fixedRotation<"u"?e.fixedRotation:!1,this.angularDamping=typeof e.angularDamping<"u"?e.angularDamping:.01,this.linearFactor=new _(1,1,1),e.linearFactor&&this.linearFactor.copy(e.linearFactor),this.angularFactor=new _(1,1,1),e.angularFactor&&this.angularFactor.copy(e.angularFactor),this.aabb=new Ze,this.aabbNeedsUpdate=!0,this.boundingRadius=0,this.wlambda=new _,this.isTrigger=Boolean(e.isTrigger),e.shape&&this.addShape(e.shape),this.updateMassProperties()}wakeUp(){let e=this.sleepState;this.sleepState=G.AWAKE,this.wakeUpAfterNarrowphase=!1,e===G.SLEEPING&&this.dispatchEvent(G.wakeupEvent)}sleep(){this.sleepState=G.SLEEPING,this.velocity.set(0,0,0),this.angularVelocity.set(0,0,0),this.wakeUpAfterNarrowphase=!1}sleepTick(e){if(this.allowSleep){let t=this.sleepState,i=this.velocity.lengthSquared()+this.angularVelocity.lengthSquared(),n=this.sleepSpeedLimit**2;t===G.AWAKE&&i<n?(this.sleepState=G.SLEEPY,this.timeLastSleepy=e,this.dispatchEvent(G.sleepyEvent)):t===G.SLEEPY&&i>n?this.wakeUp():t===G.SLEEPY&&e-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(G.sleepEvent))}}updateSolveMassProperties(){this.sleepState===G.SLEEPING||this.type===G.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve.setZero(),this.invInertiaWorldSolve.setZero()):(this.invMassSolve=this.invMass,this.invInertiaSolve.copy(this.invInertia),this.invInertiaWorldSolve.copy(this.invInertiaWorld))}pointToLocalFrame(e,t=new _){return e.vsub(this.position,t),this.quaternion.conjugate().vmult(t,t),t}vectorToLocalFrame(e,t=new _){return this.quaternion.conjugate().vmult(e,t),t}pointToWorldFrame(e,t=new _){return this.quaternion.vmult(e,t),t.vadd(this.position,t),t}vectorToWorldFrame(e,t=new _){return this.quaternion.vmult(e,t),t}addShape(e,t,i){let n=new _,r=new ce;return t&&n.copy(t),i&&r.copy(i),this.shapes.push(e),this.shapeOffsets.push(n),this.shapeOrientations.push(r),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,e.body=this,this}removeShape(e){let t=this.shapes.indexOf(e);return t===-1?(console.warn("Shape does not belong to the body"),this):(this.shapes.splice(t,1),this.shapeOffsets.splice(t,1),this.shapeOrientations.splice(t,1),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0,e.body=null,this)}updateBoundingRadius(){let e=this.shapes,t=this.shapeOffsets,i=e.length,n=0;for(let r=0;r!==i;r++){let o=e[r];o.updateBoundingSphereRadius();let s=t[r].length(),c=o.boundingSphereRadius;s+c>n&&(n=s+c)}this.boundingRadius=n}updateAABB(){let e=this.shapes,t=this.shapeOffsets,i=this.shapeOrientations,n=e.length,r=jg,o=Bg,s=this.quaternion,c=this.aabb,d=Hg;for(let l=0;l!==n;l++){let h=e[l];s.vmult(t[l],r),r.vadd(this.position,r),s.mult(i[l],o),h.calculateWorldAABB(r,o,d.lowerBound,d.upperBound),l===0?c.copy(d):c.extend(d)}this.aabbNeedsUpdate=!1}updateInertiaWorld(e){let t=this.invInertia;if(!(t.x===t.y&&t.y===t.z&&!e)){let i=Fg,n=Ng;i.setRotationFromQuaternion(this.quaternion),i.transpose(n),i.scale(t,i),i.mmult(n,this.invInertiaWorld)}}applyForce(e,t=new _){if(this.type!==G.DYNAMIC)return;this.sleepState===G.SLEEPING&&this.wakeUp();let i=zg;t.cross(e,i),this.force.vadd(e,this.force),this.torque.vadd(i,this.torque)}applyLocalForce(e,t=new _){if(this.type!==G.DYNAMIC)return;let i=Ug,n=Gg;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyForce(i,n)}applyTorque(e){this.type===G.DYNAMIC&&(this.sleepState===G.SLEEPING&&this.wakeUp(),this.torque.vadd(e,this.torque))}applyImpulse(e,t=new _){if(this.type!==G.DYNAMIC)return;this.sleepState===G.SLEEPING&&this.wakeUp();let i=t,n=Vg;n.copy(e),n.scale(this.invMass,n),this.velocity.vadd(n,this.velocity);let r=Wg;i.cross(e,r),this.invInertiaWorld.vmult(r,r),this.angularVelocity.vadd(r,this.angularVelocity)}applyLocalImpulse(e,t=new _){if(this.type!==G.DYNAMIC)return;let i=qg,n=Xg;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyImpulse(i,n)}updateMassProperties(){let e=Qg;this.invMass=this.mass>0?1/this.mass:0;let t=this.inertia,i=this.fixedRotation;this.updateAABB(),e.set((this.aabb.upperBound.x-this.aabb.lowerBound.x)/2,(this.aabb.upperBound.y-this.aabb.lowerBound.y)/2,(this.aabb.upperBound.z-this.aabb.lowerBound.z)/2),Or.calculateInertia(e,this.mass,t),this.invInertia.set(t.x>0&&!i?1/t.x:0,t.y>0&&!i?1/t.y:0,t.z>0&&!i?1/t.z:0),this.updateInertiaWorld(!0)}getVelocityAtWorldPoint(e,t){let i=new _;return e.vsub(this.position,i),this.angularVelocity.cross(i,t),this.velocity.vadd(t,t),t}integrate(e,t,i){if(this.previousPosition.copy(this.position),this.previousQuaternion.copy(this.quaternion),!(this.type===G.DYNAMIC||this.type===G.KINEMATIC)||this.sleepState===G.SLEEPING)return;let n=this.velocity,r=this.angularVelocity,o=this.position,s=this.force,c=this.torque,d=this.quaternion,l=this.invMass,h=this.invInertiaWorld,u=this.linearFactor,f=l*e;n.x+=s.x*f*u.x,n.y+=s.y*f*u.y,n.z+=s.z*f*u.z;let x=h.elements,b=this.angularFactor,y=c.x*b.x,g=c.y*b.y,p=c.z*b.z;r.x+=e*(x[0]*y+x[1]*g+x[2]*p),r.y+=e*(x[3]*y+x[4]*g+x[5]*p),r.z+=e*(x[6]*y+x[7]*g+x[8]*p),o.x+=n.x*e,o.y+=n.y*e,o.z+=n.z*e,d.integrate(this.angularVelocity,e,this.angularFactor,d),t&&(i?d.normalizeFast():d.normalize()),this.aabbNeedsUpdate=!0,this.updateInertiaWorld()}};G.idCounter=0;G.COLLIDE_EVENT_NAME="collide";G.DYNAMIC=Hc.DYNAMIC;G.STATIC=Hc.STATIC;G.KINEMATIC=Hc.KINEMATIC;G.AWAKE=Fc.AWAKE;G.SLEEPY=Fc.SLEEPY;G.SLEEPING=Fc.SLEEPING;G.wakeupEvent={type:"wakeup"};G.sleepyEvent={type:"sleepy"};G.sleepEvent={type:"sleep"};var jg=new _,Bg=new ce,Hg=new Ze,Fg=new Bt,Ng=new Bt,zg=new _,Ug=new _,Gg=new _,Vg=new _,Wg=new _,qg=new _,Xg=new _,Qg=new _,Oc=class{constructor(){this.world=void 0,this.useBoundingBoxes=void 0,this.dirty=void 0,this.world=null,this.useBoundingBoxes=!1,this.dirty=!0}collisionPairs(e,t,i){throw new Error("collisionPairs not implemented for this BroadPhase class!")}needBroadphaseCollision(e,t){return!((e.collisionFilterGroup&t.collisionFilterMask)===0||(t.collisionFilterGroup&e.collisionFilterMask)===0||((e.type&G.STATIC)!==0||e.sleepState===G.SLEEPING)&&((t.type&G.STATIC)!==0||t.sleepState===G.SLEEPING))}intersectionTest(e,t,i,n){this.useBoundingBoxes?this.doBoundingBoxBroadphase(e,t,i,n):this.doBoundingSphereBroadphase(e,t,i,n)}doBoundingSphereBroadphase(e,t,i,n){let r=Yg;t.position.vsub(e.position,r);let o=(e.boundingRadius+t.boundingRadius)**2;r.lengthSquared()<o&&(i.push(e),n.push(t))}doBoundingBoxBroadphase(e,t,i,n){e.aabbNeedsUpdate&&e.updateAABB(),t.aabbNeedsUpdate&&t.updateAABB(),e.aabb.overlaps(t.aabb)&&(i.push(e),n.push(t))}makePairsUnique(e,t){let i=Kg,n=Jg,r=Zg,o=e.length;for(let s=0;s!==o;s++)n[s]=e[s],r[s]=t[s];e.length=0,t.length=0;for(let s=0;s!==o;s++){let c=n[s].id,d=r[s].id,l=c<d?c+","+d:d+","+c;i[l]=s,i.keys.push(l)}for(let s=0;s!==i.keys.length;s++){let c=i.keys.pop(),d=i[c];e.push(n[d]),t.push(r[d]),delete i[c]}}setWorld(e){}static boundingSphereCheck(e,t){let i=new _;e.position.vsub(t.position,i);let n=e.shapes[0],r=t.shapes[0];return Math.pow(n.boundingSphereRadius+r.boundingSphereRadius,2)>i.lengthSquared()}aabbQuery(e,t,i){return console.warn(".aabbQuery is not implemented in this Broadphase subclass."),[]}},Yg=new _,Kg={keys:[]},Jg=[],Zg=[];var eE=new _,Ic=class extends Oc{constructor(){super()}collisionPairs(e,t,i){let n=e.bodies,r=n.length,o,s;for(let c=0;c!==r;c++)for(let d=0;d!==c;d++)o=n[c],s=n[d],this.needBroadphaseCollision(o,s)&&this.intersectionTest(o,s,t,i)}aabbQuery(e,t,i=[]){for(let n=0;n<e.bodies.length;n++){let r=e.bodies[n];r.aabbNeedsUpdate&&r.updateAABB(),r.aabb.overlaps(t)&&i.push(r)}return i}},Ss=class{constructor(){this.rayFromWorld=void 0,this.rayToWorld=void 0,this.hitNormalWorld=void 0,this.hitPointWorld=void 0,this.hasHit=void 0,this.shape=void 0,this.body=void 0,this.hitFaceIndex=void 0,this.distance=void 0,this.shouldStop=void 0,this.rayFromWorld=new _,this.rayToWorld=new _,this.hitNormalWorld=new _,this.hitPointWorld=new _,this.hasHit=!1,this.shape=null,this.body=null,this.hitFaceIndex=-1,this.distance=-1,this.shouldStop=!1}reset(){this.rayFromWorld.setZero(),this.rayToWorld.setZero(),this.hitNormalWorld.setZero(),this.hitPointWorld.setZero(),this.hasHit=!1,this.shape=null,this.body=null,this.hitFaceIndex=-1,this.distance=-1,this.shouldStop=!1}abort(){this.shouldStop=!0}set(e,t,i,n,r,o,s){this.rayFromWorld.copy(e),this.rayToWorld.copy(t),this.hitNormalWorld.copy(i),this.hitPointWorld.copy(n),this.shape=r,this.body=o,this.distance=s}},Gu,Vu,Wu,qu,Xu,Qu,Yu,Nc={CLOSEST:1,ANY:2,ALL:4};Gu=V.types.SPHERE;Vu=V.types.PLANE;Wu=V.types.BOX;qu=V.types.CYLINDER;Xu=V.types.CONVEXPOLYHEDRON;Qu=V.types.HEIGHTFIELD;Yu=V.types.TRIMESH;var be=class{get[Gu](){return this._intersectSphere}get[Vu](){return this._intersectPlane}get[Wu](){return this._intersectBox}get[qu](){return this._intersectConvex}get[Xu](){return this._intersectConvex}get[Qu](){return this._intersectHeightfield}get[Yu](){return this._intersectTrimesh}constructor(e=new _,t=new _){this.from=void 0,this.to=void 0,this.direction=void 0,this.precision=void 0,this.checkCollisionResponse=void 0,this.skipBackfaces=void 0,this.collisionFilterMask=void 0,this.collisionFilterGroup=void 0,this.mode=void 0,this.result=void 0,this.hasHit=void 0,this.callback=void 0,this.from=e.clone(),this.to=t.clone(),this.direction=new _,this.precision=1e-4,this.checkCollisionResponse=!0,this.skipBackfaces=!1,this.collisionFilterMask=-1,this.collisionFilterGroup=-1,this.mode=be.ANY,this.result=new Ss,this.hasHit=!1,this.callback=i=>{}}intersectWorld(e,t){return this.mode=t.mode||be.ANY,this.result=t.result||new Ss,this.skipBackfaces=!!t.skipBackfaces,this.collisionFilterMask=typeof t.collisionFilterMask<"u"?t.collisionFilterMask:-1,this.collisionFilterGroup=typeof t.collisionFilterGroup<"u"?t.collisionFilterGroup:-1,this.checkCollisionResponse=typeof t.checkCollisionResponse<"u"?t.checkCollisionResponse:!0,t.from&&this.from.copy(t.from),t.to&&this.to.copy(t.to),this.callback=t.callback||(()=>{}),this.hasHit=!1,this.result.reset(),this.updateDirection(),this.getAABB(Au),Rc.length=0,e.broadphase.aabbQuery(e,Au,Rc),this.intersectBodies(Rc),this.hasHit}intersectBody(e,t){t&&(this.result=t,this.updateDirection());let i=this.checkCollisionResponse;if(i&&!e.collisionResponse||(this.collisionFilterGroup&e.collisionFilterMask)===0||(e.collisionFilterGroup&this.collisionFilterMask)===0)return;let n=$g,r=eb;for(let o=0,s=e.shapes.length;o<s;o++){let c=e.shapes[o];if(!(i&&!c.collisionResponse)&&(e.quaternion.mult(e.shapeOrientations[o],r),e.quaternion.vmult(e.shapeOffsets[o],n),n.vadd(e.position,n),this.intersectShape(c,r,n,e),this.result.shouldStop))break}}intersectBodies(e,t){t&&(this.result=t,this.updateDirection());for(let i=0,n=e.length;!this.result.shouldStop&&i<n;i++)this.intersectBody(e[i])}updateDirection(){this.to.vsub(this.from,this.direction),this.direction.normalize()}intersectShape(e,t,i,n){let r=this.from;if(fb(r,this.direction,i)>e.boundingSphereRadius)return;let s=this[e.type];s&&s.call(this,e,t,i,n,e)}_intersectBox(e,t,i,n,r){return this._intersectConvex(e.convexPolyhedronRepresentation,t,i,n,r)}_intersectPlane(e,t,i,n,r){let o=this.from,s=this.to,c=this.direction,d=new _(0,0,1);t.vmult(d,d);let l=new _;o.vsub(i,l);let h=l.dot(d);s.vsub(i,l);let u=l.dot(d);if(h*u>0||o.distanceTo(s)<h)return;let f=d.dot(c);if(Math.abs(f)<this.precision)return;let x=new _,b=new _,y=new _;o.vsub(i,x);let g=-d.dot(x)/f;c.scale(g,b),o.vadd(b,y),this.reportIntersection(d,y,r,n,-1)}getAABB(e){let{lowerBound:t,upperBound:i}=e,n=this.to,r=this.from;t.x=Math.min(n.x,r.x),t.y=Math.min(n.y,r.y),t.z=Math.min(n.z,r.z),i.x=Math.max(n.x,r.x),i.y=Math.max(n.y,r.y),i.z=Math.max(n.z,r.z)}_intersectHeightfield(e,t,i,n,r){e.data,e.elementSize;let o=tb;o.from.copy(this.from),o.to.copy(this.to),te.pointToLocalFrame(i,t,o.from,o.from),te.pointToLocalFrame(i,t,o.to,o.to),o.updateDirection();let s=ib,c,d,l,h;c=d=0,l=h=e.data.length-1;let u=new Ze;o.getAABB(u),e.getIndexOfPosition(u.lowerBound.x,u.lowerBound.y,s,!0),c=Math.max(c,s[0]),d=Math.max(d,s[1]),e.getIndexOfPosition(u.upperBound.x,u.upperBound.y,s,!0),l=Math.min(l,s[0]+1),h=Math.min(h,s[1]+1);for(let f=c;f<l;f++)for(let x=d;x<h;x++){if(this.result.shouldStop)return;if(e.getAabbAtIndex(f,x,u),!!u.overlapsRay(o)){if(e.getConvexTrianglePillar(f,x,!1),te.pointToWorldFrame(i,t,e.pillarOffset,ya),this._intersectConvex(e.pillarConvex,t,ya,n,r,Mu),this.result.shouldStop)return;e.getConvexTrianglePillar(f,x,!0),te.pointToWorldFrame(i,t,e.pillarOffset,ya),this._intersectConvex(e.pillarConvex,t,ya,n,r,Mu)}}}_intersectSphere(e,t,i,n,r){let o=this.from,s=this.to,c=e.radius,d=(s.x-o.x)**2+(s.y-o.y)**2+(s.z-o.z)**2,l=2*((s.x-o.x)*(o.x-i.x)+(s.y-o.y)*(o.y-i.y)+(s.z-o.z)*(o.z-i.z)),h=(o.x-i.x)**2+(o.y-i.y)**2+(o.z-i.z)**2-c**2,u=l**2-4*d*h,f=nb,x=rb;if(!(u<0))if(u===0)o.lerp(s,u,f),f.vsub(i,x),x.normalize(),this.reportIntersection(x,f,r,n,-1);else{let b=(-l-Math.sqrt(u))/(2*d),y=(-l+Math.sqrt(u))/(2*d);if(b>=0&&b<=1&&(o.lerp(s,b,f),f.vsub(i,x),x.normalize(),this.reportIntersection(x,f,r,n,-1)),this.result.shouldStop)return;y>=0&&y<=1&&(o.lerp(s,y,f),f.vsub(i,x),x.normalize(),this.reportIntersection(x,f,r,n,-1))}}_intersectConvex(e,t,i,n,r,o){let s=ob,c=Lu,d=o&&o.faceList||null,l=e.faces,h=e.vertices,u=e.faceNormals,f=this.direction,x=this.from,b=this.to,y=x.distanceTo(b),g=d?d.length:l.length,p=this.result;for(let m=0;!p.shouldStop&&m<g;m++){let v=d?d[m]:m,w=l[v],E=u[v],C=t,T=i;c.copy(h[w[0]]),C.vmult(c,c),c.vadd(T,c),c.vsub(x,c),C.vmult(E,s);let R=f.dot(s);if(Math.abs(R)<this.precision)continue;let I=s.dot(c)/R;if(!(I<0)){f.scale(I,at),at.vadd(x,at),$t.copy(h[w[0]]),C.vmult($t,$t),T.vadd($t,$t);for(let O=1;!p.shouldStop&&O<w.length-1;O++){Ci.copy(h[w[O]]),Ti.copy(h[w[O+1]]),C.vmult(Ci,Ci),C.vmult(Ti,Ti),T.vadd(Ci,Ci),T.vadd(Ti,Ti);let L=at.distanceTo(x);!(be.pointInTriangle(at,$t,Ci,Ti)||be.pointInTriangle(at,Ci,$t,Ti))||L>y||this.reportIntersection(s,at,r,n,v)}}}}_intersectTrimesh(e,t,i,n,r,o){let s=sb,c=ub,d=pb,l=Lu,h=ab,u=lb,f=cb,x=hb,b=db,y=e.indices;e.vertices;let g=this.from,p=this.to,m=this.direction;d.position.copy(i),d.quaternion.copy(t),te.vectorToLocalFrame(i,t,m,h),te.pointToLocalFrame(i,t,g,u),te.pointToLocalFrame(i,t,p,f),f.x*=e.scale.x,f.y*=e.scale.y,f.z*=e.scale.z,u.x*=e.scale.x,u.y*=e.scale.y,u.z*=e.scale.z,f.vsub(u,h),h.normalize();let v=u.distanceSquared(f);e.tree.rayQuery(this,d,c);for(let w=0,E=c.length;!this.result.shouldStop&&w!==E;w++){let C=c[w];e.getNormal(C,s),e.getVertex(y[C*3],$t),$t.vsub(u,l);let T=h.dot(s),R=s.dot(l)/T;if(R<0)continue;h.scale(R,at),at.vadd(u,at),e.getVertex(y[C*3+1],Ci),e.getVertex(y[C*3+2],Ti);let I=at.distanceSquared(u);!(be.pointInTriangle(at,Ci,$t,Ti)||be.pointInTriangle(at,$t,Ci,Ti))||I>v||(te.vectorToWorldFrame(t,s,b),te.pointToWorldFrame(i,t,at,x),this.reportIntersection(b,x,r,n,C))}c.length=0}reportIntersection(e,t,i,n,r){let o=this.from,s=this.to,c=o.distanceTo(t),d=this.result;if(!(this.skipBackfaces&&e.dot(this.direction)>0))switch(d.hitFaceIndex=typeof r<"u"?r:-1,this.mode){case be.ALL:this.hasHit=!0,d.set(o,s,e,t,i,n,c),d.hasHit=!0,this.callback(d);break;case be.CLOSEST:(c<d.distance||!d.hasHit)&&(this.hasHit=!0,d.hasHit=!0,d.set(o,s,e,t,i,n,c));break;case be.ANY:this.hasHit=!0,d.hasHit=!0,d.set(o,s,e,t,i,n,c),d.shouldStop=!0;break}}static pointInTriangle(e,t,i,n){n.vsub(t,Sr),i.vsub(t,Es),e.vsub(t,Sc);let r=Sr.dot(Sr),o=Sr.dot(Es),s=Sr.dot(Sc),c=Es.dot(Es),d=Es.dot(Sc),l,h;return(l=c*s-o*d)>=0&&(h=r*d-o*s)>=0&&l+h<r*c-o*o}};be.CLOSEST=Nc.CLOSEST;be.ANY=Nc.ANY;be.ALL=Nc.ALL;var Au=new Ze,Rc=[],Es=new _,Sc=new _,$g=new _,eb=new ce,at=new _,$t=new _,Ci=new _,Ti=new _,Mu={faceList:[0]},ya=new _,tb=new be,ib=[],nb=new _,rb=new _,ob=new _,Lu=new _,sb=new _,ab=new _,lb=new _,cb=new _,db=new _,hb=new _;new Ze;var ub=[],pb=new te,Sr=new _,xa=new _;function fb(a,e,t){t.vsub(a,Sr);let i=Sr.dot(e);return e.scale(i,xa),xa.vadd(a,xa),t.distanceTo(xa)}var Ra=class{static defaults(e={},t){for(let i in t)i in e||(e[i]=t[i]);return e}},Ps=class{constructor(e,t,i={}){this.equations=void 0,this.bodyA=void 0,this.bodyB=void 0,this.id=void 0,this.collideConnected=void 0,i=Ra.defaults(i,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=e,this.bodyB=t,this.id=Ps.idCounter++,this.collideConnected=i.collideConnected,i.wakeUpBodies&&(e&&e.wakeUp(),t&&t.wakeUp())}update(){throw new Error("method update() not implmemented in this Constraint subclass!")}enable(){let e=this.equations;for(let t=0;t<e.length;t++)e[t].enabled=!0}disable(){let e=this.equations;for(let t=0;t<e.length;t++)e[t].enabled=!1}};Ps.idCounter=0;var Sa=class{constructor(){this.spatial=void 0,this.rotational=void 0,this.spatial=new _,this.rotational=new _}multiplyElement(e){return e.spatial.dot(this.spatial)+e.rotational.dot(this.rotational)}multiplyVectors(e,t){return e.dot(this.spatial)+t.dot(this.rotational)}},Ir=class{constructor(e,t,i=-1e6,n=1e6){this.id=void 0,this.minForce=void 0,this.maxForce=void 0,this.bi=void 0,this.bj=void 0,this.si=void 0,this.sj=void 0,this.a=void 0,this.b=void 0,this.eps=void 0,this.jacobianElementA=void 0,this.jacobianElementB=void 0,this.enabled=void 0,this.multiplier=void 0,this.id=Ir.idCounter++,this.minForce=i,this.maxForce=n,this.bi=e,this.bj=t,this.a=0,this.b=0,this.eps=0,this.jacobianElementA=new Sa,this.jacobianElementB=new Sa,this.enabled=!0,this.multiplier=0,this.setSpookParams(1e7,4,1/60)}setSpookParams(e,t,i){let n=t,r=e,o=i;this.a=4/(o*(1+4*n)),this.b=4*n/(1+4*n),this.eps=4/(o*o*r*(1+4*n))}computeB(e,t,i){let n=this.computeGW(),r=this.computeGq(),o=this.computeGiMf();return-r*e-n*t-o*i}computeGq(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.position,o=n.position;return e.spatial.dot(r)+t.spatial.dot(o)}computeGW(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.velocity,o=n.velocity,s=i.angularVelocity,c=n.angularVelocity;return e.multiplyVectors(r,s)+t.multiplyVectors(o,c)}computeGWlambda(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.vlambda,o=n.vlambda,s=i.wlambda,c=n.wlambda;return e.multiplyVectors(r,s)+t.multiplyVectors(o,c)}computeGiMf(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.force,o=i.torque,s=n.force,c=n.torque,d=i.invMassSolve,l=n.invMassSolve;return r.scale(d,Du),s.scale(l,ju),i.invInertiaWorldSolve.vmult(o,Bu),n.invInertiaWorldSolve.vmult(c,Hu),e.multiplyVectors(Du,Bu)+t.multiplyVectors(ju,Hu)}computeGiMGt(){let e=this.jacobianElementA,t=this.jacobianElementB,i=this.bi,n=this.bj,r=i.invMassSolve,o=n.invMassSolve,s=i.invInertiaWorldSolve,c=n.invInertiaWorldSolve,d=r+o;return s.vmult(e.rotational,wa),d+=wa.dot(e.rotational),c.vmult(t.rotational,wa),d+=wa.dot(t.rotational),d}addToWlambda(e){let t=this.jacobianElementA,i=this.jacobianElementB,n=this.bi,r=this.bj,o=mb;n.vlambda.addScaledVector(n.invMassSolve*e,t.spatial,n.vlambda),r.vlambda.addScaledVector(r.invMassSolve*e,i.spatial,r.vlambda),n.invInertiaWorldSolve.vmult(t.rotational,o),n.wlambda.addScaledVector(e,o,n.wlambda),r.invInertiaWorldSolve.vmult(i.rotational,o),r.wlambda.addScaledVector(e,o,r.wlambda)}computeC(){return this.computeGiMGt()+this.eps}};Ir.idCounter=0;var Du=new _,ju=new _,Bu=new _,Hu=new _,wa=new _,mb=new _,kc=class extends Ir{constructor(e,t,i=1e6){super(e,t,0,i),this.restitution=void 0,this.ri=void 0,this.rj=void 0,this.ni=void 0,this.restitution=0,this.ri=new _,this.rj=new _,this.ni=new _}computeB(e){let t=this.a,i=this.b,n=this.bi,r=this.bj,o=this.ri,s=this.rj,c=gb,d=bb,l=n.velocity,h=n.angularVelocity;n.force,n.torque;let u=r.velocity,f=r.angularVelocity;r.force,r.torque;let x=vb,b=this.jacobianElementA,y=this.jacobianElementB,g=this.ni;o.cross(g,c),s.cross(g,d),g.negate(b.spatial),c.negate(b.rotational),y.spatial.copy(g),y.rotational.copy(d),x.copy(r.position),x.vadd(s,x),x.vsub(n.position,x),x.vsub(o,x);let p=g.dot(x),m=this.restitution+1,v=m*u.dot(g)-m*l.dot(g)+f.dot(d)-h.dot(c),w=this.computeGiMf();return-p*t-v*i-e*w}getImpactVelocityAlongNormal(){let e=yb,t=xb,i=wb,n=_b,r=Eb;return this.bi.position.vadd(this.ri,i),this.bj.position.vadd(this.rj,n),this.bi.getVelocityAtWorldPoint(i,e),this.bj.getVelocityAtWorldPoint(n,t),e.vsub(t,r),this.ni.dot(r)}},gb=new _,bb=new _,vb=new _,yb=new _,xb=new _,wb=new _,_b=new _,Eb=new _;var tE=new _,iE=new _;var nE=new _,rE=new _;var oE=new _,sE=new _,Pa=class extends Ir{constructor(e,t,i){super(e,t,-i,i),this.ri=void 0,this.rj=void 0,this.t=void 0,this.ri=new _,this.rj=new _,this.t=new _}computeB(e){this.a;let t=this.b;this.bi,this.bj;let i=this.ri,n=this.rj,r=Cb,o=Tb,s=this.t;i.cross(s,r),n.cross(s,o);let c=this.jacobianElementA,d=this.jacobianElementB;s.negate(c.spatial),r.negate(c.rotational),d.spatial.copy(s),d.rotational.copy(o);let l=this.computeGW(),h=this.computeGiMf();return-l*t-e*h}},Cb=new _,Tb=new _,ko=class{constructor(e,t,i){this.id=void 0,this.materials=void 0,this.friction=void 0,this.restitution=void 0,this.contactEquationStiffness=void 0,this.contactEquationRelaxation=void 0,this.frictionEquationStiffness=void 0,this.frictionEquationRelaxation=void 0,i=Ra.defaults(i,{friction:.3,restitution:.3,contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}),this.id=ko.idCounter++,this.materials=[e,t],this.friction=i.friction,this.restitution=i.restitution,this.contactEquationStiffness=i.contactEquationStiffness,this.contactEquationRelaxation=i.contactEquationRelaxation,this.frictionEquationStiffness=i.frictionEquationStiffness,this.frictionEquationRelaxation=i.frictionEquationRelaxation}};ko.idCounter=0;var Ao=class{constructor(e={}){this.name=void 0,this.id=void 0,this.friction=void 0,this.restitution=void 0;let t="";typeof e=="string"&&(t=e,e={}),this.name=t,this.id=Ao.idCounter++,this.friction=typeof e.friction<"u"?e.friction:-1,this.restitution=typeof e.restitution<"u"?e.restitution:-1}};Ao.idCounter=0;var Oa=class{constructor(e,t,i={}){this.restLength=void 0,this.stiffness=void 0,this.damping=void 0,this.bodyA=void 0,this.bodyB=void 0,this.localAnchorA=void 0,this.localAnchorB=void 0,this.restLength=typeof i.restLength=="number"?i.restLength:1,this.stiffness=i.stiffness||100,this.damping=i.damping||1,this.bodyA=e,this.bodyB=t,this.localAnchorA=new _,this.localAnchorB=new _,i.localAnchorA&&this.localAnchorA.copy(i.localAnchorA),i.localAnchorB&&this.localAnchorB.copy(i.localAnchorB),i.worldAnchorA&&this.setWorldAnchorA(i.worldAnchorA),i.worldAnchorB&&this.setWorldAnchorB(i.worldAnchorB)}setWorldAnchorA(e){this.bodyA.pointToLocalFrame(e,this.localAnchorA)}setWorldAnchorB(e){this.bodyB.pointToLocalFrame(e,this.localAnchorB)}getWorldAnchorA(e){this.bodyA.pointToWorldFrame(this.localAnchorA,e)}getWorldAnchorB(e){this.bodyB.pointToWorldFrame(this.localAnchorB,e)}applyForce(){let e=this.stiffness,t=this.damping,i=this.restLength,n=this.bodyA,r=this.bodyB,o=Rb,s=Sb,c=Pb,d=Ob,l=jb,h=Ib,u=kb,f=Ab,x=Mb,b=Lb,y=Db;this.getWorldAnchorA(h),this.getWorldAnchorB(u),h.vsub(n.position,f),u.vsub(r.position,x),u.vsub(h,o);let g=o.length();s.copy(o),s.normalize(),r.velocity.vsub(n.velocity,c),r.angularVelocity.cross(x,l),c.vadd(l,c),n.angularVelocity.cross(f,l),c.vsub(l,c),s.scale(-e*(g-i)-t*c.dot(s),d),n.force.vsub(d,n.force),r.force.vadd(d,r.force),f.cross(d,b),x.cross(d,y),n.torque.vsub(b,n.torque),r.torque.vadd(y,r.torque)}},Rb=new _,Sb=new _,Pb=new _,Ob=new _,Ib=new _,kb=new _,Ab=new _,Mb=new _,Lb=new _,Db=new _,jb=new _;var aE=new _,lE=new _;var cE=new _,dE=new _,hE=new _;new be;var uE=new _,pE=new _,fE=[new _(1,0,0),new _(0,1,0),new _(0,0,1)],mE=new _;var gE=new _,bE=new _,vE=new _;var yE=new _,xE=new _,wE=new _,_E=new _;var EE=new _,CE=new _,TE=new _;var Ia=class extends V{constructor(e){if(super({type:V.types.SPHERE}),this.radius=void 0,this.radius=e!==void 0?e:1,this.radius<0)throw new Error("The sphere radius cannot be negative.");this.updateBoundingSphereRadius()}calculateLocalInertia(e,t=new _){let i=2*e*this.radius*this.radius/5;return t.x=i,t.y=i,t.z=i,t}volume(){return 4*Math.PI*Math.pow(this.radius,3)/3}updateBoundingSphereRadius(){this.boundingSphereRadius=this.radius}calculateWorldAABB(e,t,i,n){let r=this.radius,o=["x","y","z"];for(let s=0;s<o.length;s++){let c=o[s];i[c]=e[c]-r,n[c]=e[c]+r}}};var RE=new _,SE=new _;var PE=new _,OE=new _,IE=new _,kE=new _,AE=new _,ME=new _,LE=new _;var DE=new _;var jE=new _,BE=new _,HE=new _,FE=new _,NE=new _,zE=new _,UE=new _,GE=new _,VE=new _;var WE=new _,qE=new Ze;var XE=new _,QE=new Ze,YE=new _,KE=new _,JE=new _,ZE=new _,$E=new _,eC=new _,tC=new _,iC=new Ze,nC=new _,rC=new te,oC=new Ze,Ac=class{constructor(){this.equations=void 0,this.equations=[]}solve(e,t){return 0}addEquation(e){e.enabled&&!e.bi.isTrigger&&!e.bj.isTrigger&&this.equations.push(e)}removeEquation(e){let t=this.equations,i=t.indexOf(e);i!==-1&&t.splice(i,1)}removeAllEquations(){this.equations.length=0}},Mc=class extends Ac{constructor(){super(),this.iterations=void 0,this.tolerance=void 0,this.iterations=10,this.tolerance=1e-7}solve(e,t){let i=0,n=this.iterations,r=this.tolerance*this.tolerance,o=this.equations,s=o.length,c=t.bodies,d=c.length,l=e,h,u,f,x,b,y;if(s!==0)for(let v=0;v!==d;v++)c[v].updateSolveMassProperties();let g=Hb,p=Fb,m=Bb;g.length=s,p.length=s,m.length=s;for(let v=0;v!==s;v++){let w=o[v];m[v]=0,p[v]=w.computeB(l),g[v]=1/w.computeC()}if(s!==0){for(let E=0;E!==d;E++){let C=c[E],T=C.vlambda,R=C.wlambda;T.set(0,0,0),R.set(0,0,0)}for(i=0;i!==n;i++){x=0;for(let E=0;E!==s;E++){let C=o[E];h=p[E],u=g[E],y=m[E],b=C.computeGWlambda(),f=u*(h-b-C.eps*y),y+f<C.minForce?f=C.minForce-y:y+f>C.maxForce&&(f=C.maxForce-y),m[E]+=f,x+=f>0?f:-f,C.addToWlambda(f)}if(x*x<r)break}for(let E=0;E!==d;E++){let C=c[E],T=C.velocity,R=C.angularVelocity;C.vlambda.vmul(C.linearFactor,C.vlambda),T.vadd(C.vlambda,T),C.wlambda.vmul(C.angularFactor,C.wlambda),R.vadd(C.wlambda,R)}let v=o.length,w=1/l;for(;v--;)o[v].multiplier=m[v]*w}return i}},Bb=[],Hb=[],Fb=[];var sC=G.STATIC;var Lc=class{constructor(){this.objects=[],this.type=Object}release(...e){let t=e.length;for(let i=0;i!==t;i++)this.objects.push(e[i]);return this}get(){return this.objects.length===0?this.constructObject():this.objects.pop()}constructObject(){throw new Error("constructObject() not implemented in this Pool subclass yet!")}resize(e){let t=this.objects;for(;t.length>e;)t.pop();for(;t.length<e;)t.push(this.constructObject());return this}},Dc=class extends Lc{constructor(...e){super(...e),this.type=_}constructObject(){return new _}},Ku,Ju,Zu,$u,ep,tp,ip,np,rp,op,sp,ap,lp,cp,dp,hp,up,pp,fp,mp,gp,bp,vp,yp,xp,pe={sphereSphere:V.types.SPHERE,spherePlane:V.types.SPHERE|V.types.PLANE,boxBox:V.types.BOX|V.types.BOX,sphereBox:V.types.SPHERE|V.types.BOX,planeBox:V.types.PLANE|V.types.BOX,convexConvex:V.types.CONVEXPOLYHEDRON,sphereConvex:V.types.SPHERE|V.types.CONVEXPOLYHEDRON,planeConvex:V.types.PLANE|V.types.CONVEXPOLYHEDRON,boxConvex:V.types.BOX|V.types.CONVEXPOLYHEDRON,sphereHeightfield:V.types.SPHERE|V.types.HEIGHTFIELD,boxHeightfield:V.types.BOX|V.types.HEIGHTFIELD,convexHeightfield:V.types.CONVEXPOLYHEDRON|V.types.HEIGHTFIELD,sphereParticle:V.types.PARTICLE|V.types.SPHERE,planeParticle:V.types.PLANE|V.types.PARTICLE,boxParticle:V.types.BOX|V.types.PARTICLE,convexParticle:V.types.PARTICLE|V.types.CONVEXPOLYHEDRON,cylinderCylinder:V.types.CYLINDER,sphereCylinder:V.types.SPHERE|V.types.CYLINDER,planeCylinder:V.types.PLANE|V.types.CYLINDER,boxCylinder:V.types.BOX|V.types.CYLINDER,convexCylinder:V.types.CONVEXPOLYHEDRON|V.types.CYLINDER,heightfieldCylinder:V.types.HEIGHTFIELD|V.types.CYLINDER,particleCylinder:V.types.PARTICLE|V.types.CYLINDER,sphereTrimesh:V.types.SPHERE|V.types.TRIMESH,planeTrimesh:V.types.PLANE|V.types.TRIMESH};Ku=pe.sphereSphere;Ju=pe.spherePlane;Zu=pe.boxBox;$u=pe.sphereBox;ep=pe.planeBox;tp=pe.convexConvex;ip=pe.sphereConvex;np=pe.planeConvex;rp=pe.boxConvex;op=pe.sphereHeightfield;sp=pe.boxHeightfield;ap=pe.convexHeightfield;lp=pe.sphereParticle;cp=pe.planeParticle;dp=pe.boxParticle;hp=pe.convexParticle;up=pe.cylinderCylinder;pp=pe.sphereCylinder;fp=pe.planeCylinder;mp=pe.boxCylinder;gp=pe.convexCylinder;bp=pe.heightfieldCylinder;vp=pe.particleCylinder;yp=pe.sphereTrimesh;xp=pe.planeTrimesh;var jc=class{get[Ku](){return this.sphereSphere}get[Ju](){return this.spherePlane}get[Zu](){return this.boxBox}get[$u](){return this.sphereBox}get[ep](){return this.planeBox}get[tp](){return this.convexConvex}get[ip](){return this.sphereConvex}get[np](){return this.planeConvex}get[rp](){return this.boxConvex}get[op](){return this.sphereHeightfield}get[sp](){return this.boxHeightfield}get[ap](){return this.convexHeightfield}get[lp](){return this.sphereParticle}get[cp](){return this.planeParticle}get[dp](){return this.boxParticle}get[hp](){return this.convexParticle}get[up](){return this.convexConvex}get[pp](){return this.sphereConvex}get[fp](){return this.planeConvex}get[mp](){return this.boxConvex}get[gp](){return this.convexConvex}get[bp](){return this.heightfieldCylinder}get[vp](){return this.particleCylinder}get[yp](){return this.sphereTrimesh}get[xp](){return this.planeTrimesh}constructor(e){this.contactPointPool=void 0,this.frictionEquationPool=void 0,this.result=void 0,this.frictionResult=void 0,this.v3pool=void 0,this.world=void 0,this.currentContactMaterial=void 0,this.enableFrictionReduction=void 0,this.contactPointPool=[],this.frictionEquationPool=[],this.result=[],this.frictionResult=[],this.v3pool=new Dc,this.world=e,this.currentContactMaterial=e.defaultContactMaterial,this.enableFrictionReduction=!1}createContactEquation(e,t,i,n,r,o){let s;this.contactPointPool.length?(s=this.contactPointPool.pop(),s.bi=e,s.bj=t):s=new kc(e,t),s.enabled=e.collisionResponse&&t.collisionResponse&&i.collisionResponse&&n.collisionResponse;let c=this.currentContactMaterial;s.restitution=c.restitution,s.setSpookParams(c.contactEquationStiffness,c.contactEquationRelaxation,this.world.dt);let d=i.material||e.material,l=n.material||t.material;return d&&l&&d.restitution>=0&&l.restitution>=0&&(s.restitution=d.restitution*l.restitution),s.si=r||i,s.sj=o||n,s}createFrictionEquationsFromContact(e,t){let i=e.bi,n=e.bj,r=e.si,o=e.sj,s=this.world,c=this.currentContactMaterial,d=c.friction,l=r.material||i.material,h=o.material||n.material;if(l&&h&&l.friction>=0&&h.friction>=0&&(d=l.friction*h.friction),d>0){let u=d*s.gravity.length(),f=i.invMass+n.invMass;f>0&&(f=1/f);let x=this.frictionEquationPool,b=x.length?x.pop():new Pa(i,n,u*f),y=x.length?x.pop():new Pa(i,n,u*f);return b.bi=y.bi=i,b.bj=y.bj=n,b.minForce=y.minForce=-u*f,b.maxForce=y.maxForce=u*f,b.ri.copy(e.ri),b.rj.copy(e.rj),y.ri.copy(e.ri),y.rj.copy(e.rj),e.ni.tangents(b.t,y.t),b.setSpookParams(c.frictionEquationStiffness,c.frictionEquationRelaxation,s.dt),y.setSpookParams(c.frictionEquationStiffness,c.frictionEquationRelaxation,s.dt),b.enabled=y.enabled=e.enabled,t.push(b,y),!0}return!1}createFrictionFromAverage(e){let t=this.result[this.result.length-1];if(!this.createFrictionEquationsFromContact(t,this.frictionResult)||e===1)return;let i=this.frictionResult[this.frictionResult.length-2],n=this.frictionResult[this.frictionResult.length-1];Rr.setZero(),Oo.setZero(),Io.setZero();let r=t.bi;t.bj;for(let s=0;s!==e;s++)t=this.result[this.result.length-1-s],t.bi!==r?(Rr.vadd(t.ni,Rr),Oo.vadd(t.ri,Oo),Io.vadd(t.rj,Io)):(Rr.vsub(t.ni,Rr),Oo.vadd(t.rj,Oo),Io.vadd(t.ri,Io));let o=1/e;Oo.scale(o,i.ri),Io.scale(o,i.rj),n.ri.copy(i.ri),n.rj.copy(i.rj),Rr.normalize(),Rr.tangents(i.t,n.t)}getContacts(e,t,i,n,r,o,s){this.contactPointPool=r,this.frictionEquationPool=s,this.result=n,this.frictionResult=o;let c=Ub,d=Gb,l=Nb,h=zb;for(let u=0,f=e.length;u!==f;u++){let x=e[u],b=t[u],y=null;x.material&&b.material&&(y=i.getContactMaterial(x.material,b.material)||null);let g=x.type&G.KINEMATIC&&b.type&G.STATIC||x.type&G.STATIC&&b.type&G.KINEMATIC||x.type&G.KINEMATIC&&b.type&G.KINEMATIC;for(let p=0;p<x.shapes.length;p++){x.quaternion.mult(x.shapeOrientations[p],c),x.quaternion.vmult(x.shapeOffsets[p],l),l.vadd(x.position,l);let m=x.shapes[p];for(let v=0;v<b.shapes.length;v++){b.quaternion.mult(b.shapeOrientations[v],d),b.quaternion.vmult(b.shapeOffsets[v],h),h.vadd(b.position,h);let w=b.shapes[v];if(!(m.collisionFilterMask&w.collisionFilterGroup&&w.collisionFilterMask&m.collisionFilterGroup)||l.distanceTo(h)>m.boundingSphereRadius+w.boundingSphereRadius)continue;let E=null;m.material&&w.material&&(E=i.getContactMaterial(m.material,w.material)||null),this.currentContactMaterial=E||y||i.defaultContactMaterial;let C=m.type|w.type,T=this[C];if(T){let R=!1;m.type<w.type?R=T.call(this,m,w,l,h,c,d,x,b,m,w,g):R=T.call(this,w,m,h,l,d,c,b,x,m,w,g),R&&g&&(i.shapeOverlapKeeper.set(m.id,w.id),i.bodyOverlapKeeper.set(x.id,b.id))}}}}}sphereSphere(e,t,i,n,r,o,s,c,d,l,h){if(h)return i.distanceSquared(n)<(e.radius+t.radius)**2;let u=this.createContactEquation(s,c,e,t,d,l);n.vsub(i,u.ni),u.ni.normalize(),u.ri.copy(u.ni),u.rj.copy(u.ni),u.ri.scale(e.radius,u.ri),u.rj.scale(-t.radius,u.rj),u.ri.vadd(i,u.ri),u.ri.vsub(s.position,u.ri),u.rj.vadd(n,u.rj),u.rj.vsub(c.position,u.rj),this.result.push(u),this.createFrictionEquationsFromContact(u,this.frictionResult)}spherePlane(e,t,i,n,r,o,s,c,d,l,h){let u=this.createContactEquation(s,c,e,t,d,l);if(u.ni.set(0,0,1),o.vmult(u.ni,u.ni),u.ni.negate(u.ni),u.ni.normalize(),u.ni.scale(e.radius,u.ri),i.vsub(n,_a),u.ni.scale(u.ni.dot(_a),Fu),_a.vsub(Fu,u.rj),-_a.dot(u.ni)<=e.radius){if(h)return!0;let f=u.ri,x=u.rj;f.vadd(i,f),f.vsub(s.position,f),x.vadd(n,x),x.vsub(c.position,x),this.result.push(u),this.createFrictionEquationsFromContact(u,this.frictionResult)}}boxBox(e,t,i,n,r,o,s,c,d,l,h){return e.convexPolyhedronRepresentation.material=e.material,t.convexPolyhedronRepresentation.material=t.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,t.convexPolyhedronRepresentation.collisionResponse=t.collisionResponse,this.convexConvex(e.convexPolyhedronRepresentation,t.convexPolyhedronRepresentation,i,n,r,o,s,c,e,t,h)}sphereBox(e,t,i,n,r,o,s,c,d,l,h){let u=this.v3pool,f=mv;i.vsub(n,Ea),t.getSideNormals(f,o);let x=e.radius,b=!1,y=bv,g=vv,p=yv,m=null,v=0,w=0,E=0,C=null;for(let z=0,q=f.length;z!==q&&b===!1;z++){let $=uv;$.copy(f[z]);let W=$.length();$.normalize();let Ne=Ea.dot($);if(Ne<W+x&&Ne>0){let ge=pv,Q=fv;ge.copy(f[(z+1)%3]),Q.copy(f[(z+2)%3]);let qe=ge.length(),jn=Q.length();ge.normalize(),Q.normalize();let _r=Ea.dot(ge),rn=Ea.dot(Q);if(_r<qe&&_r>-qe&&rn<jn&&rn>-jn){let jt=Math.abs(Ne-W-x);if((C===null||jt<C)&&(C=jt,w=_r,E=rn,m=W,y.copy($),g.copy(ge),p.copy(Q),v++,h))return!0}}}if(v){b=!0;let z=this.createContactEquation(s,c,e,t,d,l);y.scale(-x,z.ri),z.ni.copy(y),z.ni.negate(z.ni),y.scale(m,y),g.scale(w,g),y.vadd(g,y),p.scale(E,p),y.vadd(p,z.rj),z.ri.vadd(i,z.ri),z.ri.vsub(s.position,z.ri),z.rj.vadd(n,z.rj),z.rj.vsub(c.position,z.rj),this.result.push(z),this.createFrictionEquationsFromContact(z,this.frictionResult)}let T=u.get(),R=gv;for(let z=0;z!==2&&!b;z++)for(let q=0;q!==2&&!b;q++)for(let $=0;$!==2&&!b;$++)if(T.set(0,0,0),z?T.vadd(f[0],T):T.vsub(f[0],T),q?T.vadd(f[1],T):T.vsub(f[1],T),$?T.vadd(f[2],T):T.vsub(f[2],T),n.vadd(T,R),R.vsub(i,R),R.lengthSquared()<x*x){if(h)return!0;b=!0;let W=this.createContactEquation(s,c,e,t,d,l);W.ri.copy(R),W.ri.normalize(),W.ni.copy(W.ri),W.ri.scale(x,W.ri),W.rj.copy(T),W.ri.vadd(i,W.ri),W.ri.vsub(s.position,W.ri),W.rj.vadd(n,W.rj),W.rj.vsub(c.position,W.rj),this.result.push(W),this.createFrictionEquationsFromContact(W,this.frictionResult)}u.release(T),T=null;let I=u.get(),O=u.get(),L=u.get(),A=u.get(),F=u.get(),H=f.length;for(let z=0;z!==H&&!b;z++)for(let q=0;q!==H&&!b;q++)if(z%3!==q%3){f[q].cross(f[z],I),I.normalize(),f[z].vadd(f[q],O),L.copy(i),L.vsub(O,L),L.vsub(n,L);let $=L.dot(I);I.scale($,A);let W=0;for(;W===z%3||W===q%3;)W++;F.copy(i),F.vsub(A,F),F.vsub(O,F),F.vsub(n,F);let Ne=Math.abs($),ge=F.length();if(Ne<f[W].length()&&ge<x){if(h)return!0;b=!0;let Q=this.createContactEquation(s,c,e,t,d,l);O.vadd(A,Q.rj),Q.rj.copy(Q.rj),F.negate(Q.ni),Q.ni.normalize(),Q.ri.copy(Q.rj),Q.ri.vadd(n,Q.ri),Q.ri.vsub(i,Q.ri),Q.ri.normalize(),Q.ri.scale(x,Q.ri),Q.ri.vadd(i,Q.ri),Q.ri.vsub(s.position,Q.ri),Q.rj.vadd(n,Q.rj),Q.rj.vsub(c.position,Q.rj),this.result.push(Q),this.createFrictionEquationsFromContact(Q,this.frictionResult)}}u.release(I,O,L,A,F)}planeBox(e,t,i,n,r,o,s,c,d,l,h){return t.convexPolyhedronRepresentation.material=t.material,t.convexPolyhedronRepresentation.collisionResponse=t.collisionResponse,t.convexPolyhedronRepresentation.id=t.id,this.planeConvex(e,t.convexPolyhedronRepresentation,i,n,r,o,s,c,e,t,h)}convexConvex(e,t,i,n,r,o,s,c,d,l,h,u,f){let x=Lv;if(!(i.distanceTo(n)>e.boundingSphereRadius+t.boundingSphereRadius)&&e.findSeparatingAxis(t,i,r,n,o,x,u,f)){let b=[],y=Dv;e.clipAgainstHull(i,r,t,n,o,x,-100,100,b);let g=0;for(let p=0;p!==b.length;p++){if(h)return!0;let m=this.createContactEquation(s,c,e,t,d,l),v=m.ri,w=m.rj;x.negate(m.ni),b[p].normal.negate(y),y.scale(b[p].depth,y),b[p].point.vadd(y,v),w.copy(b[p].point),v.vsub(i,v),w.vsub(n,w),v.vadd(i,v),v.vsub(s.position,v),w.vadd(n,w),w.vsub(c.position,w),this.result.push(m),g++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(m,this.frictionResult)}this.enableFrictionReduction&&g&&this.createFrictionFromAverage(g)}}sphereConvex(e,t,i,n,r,o,s,c,d,l,h){let u=this.v3pool;i.vsub(n,xv);let f=t.faceNormals,x=t.faces,b=t.vertices,y=e.radius,g=!1;for(let p=0;p!==b.length;p++){let m=b[p],v=Cv;o.vmult(m,v),n.vadd(v,v);let w=Ev;if(v.vsub(i,w),w.lengthSquared()<y*y){if(h)return!0;g=!0;let E=this.createContactEquation(s,c,e,t,d,l);E.ri.copy(w),E.ri.normalize(),E.ni.copy(E.ri),E.ri.scale(y,E.ri),v.vsub(n,E.rj),E.ri.vadd(i,E.ri),E.ri.vsub(s.position,E.ri),E.rj.vadd(n,E.rj),E.rj.vsub(c.position,E.rj),this.result.push(E),this.createFrictionEquationsFromContact(E,this.frictionResult);return}}for(let p=0,m=x.length;p!==m&&g===!1;p++){let v=f[p],w=x[p],E=Tv;o.vmult(v,E);let C=Rv;o.vmult(b[w[0]],C),C.vadd(n,C);let T=Sv;E.scale(-y,T),i.vadd(T,T);let R=Pv;T.vsub(C,R);let I=R.dot(E),O=Ov;if(i.vsub(C,O),I<0&&O.dot(E)>0){let L=[];for(let A=0,F=w.length;A!==F;A++){let H=u.get();o.vmult(b[w[A]],H),n.vadd(H,H),L.push(H)}if(hv(L,E,i)){if(h)return!0;g=!0;let A=this.createContactEquation(s,c,e,t,d,l);E.scale(-y,A.ri),E.negate(A.ni);let F=u.get();E.scale(-I,F);let H=u.get();E.scale(-y,H),i.vsub(n,A.rj),A.rj.vadd(H,A.rj),A.rj.vadd(F,A.rj),A.rj.vadd(n,A.rj),A.rj.vsub(c.position,A.rj),A.ri.vadd(i,A.ri),A.ri.vsub(s.position,A.ri),u.release(F),u.release(H),this.result.push(A),this.createFrictionEquationsFromContact(A,this.frictionResult);for(let z=0,q=L.length;z!==q;z++)u.release(L[z]);return}else for(let A=0;A!==w.length;A++){let F=u.get(),H=u.get();o.vmult(b[w[(A+1)%w.length]],F),o.vmult(b[w[(A+2)%w.length]],H),n.vadd(F,F),n.vadd(H,H);let z=wv;H.vsub(F,z);let q=_v;z.unit(q);let $=u.get(),W=u.get();i.vsub(F,W);let Ne=W.dot(q);q.scale(Ne,$),$.vadd(F,$);let ge=u.get();if($.vsub(i,ge),Ne>0&&Ne*Ne<z.lengthSquared()&&ge.lengthSquared()<y*y){if(h)return!0;let Q=this.createContactEquation(s,c,e,t,d,l);$.vsub(n,Q.rj),$.vsub(i,Q.ni),Q.ni.normalize(),Q.ni.scale(y,Q.ri),Q.rj.vadd(n,Q.rj),Q.rj.vsub(c.position,Q.rj),Q.ri.vadd(i,Q.ri),Q.ri.vsub(s.position,Q.ri),this.result.push(Q),this.createFrictionEquationsFromContact(Q,this.frictionResult);for(let qe=0,jn=L.length;qe!==jn;qe++)u.release(L[qe]);u.release(F),u.release(H),u.release($),u.release(ge),u.release(W);return}u.release(F),u.release(H),u.release($),u.release(ge),u.release(W)}for(let A=0,F=L.length;A!==F;A++)u.release(L[A])}}}planeConvex(e,t,i,n,r,o,s,c,d,l,h){let u=Iv,f=kv;f.set(0,0,1),r.vmult(f,f);let x=0,b=Av;for(let y=0;y!==t.vertices.length;y++)if(u.copy(t.vertices[y]),o.vmult(u,u),n.vadd(u,u),u.vsub(i,b),f.dot(b)<=0){if(h)return!0;let p=this.createContactEquation(s,c,e,t,d,l),m=Mv;f.scale(f.dot(b),m),u.vsub(m,m),m.vsub(i,p.ri),p.ni.copy(f),u.vsub(n,p.rj),p.ri.vadd(i,p.ri),p.ri.vsub(s.position,p.ri),p.rj.vadd(n,p.rj),p.rj.vsub(c.position,p.rj),this.result.push(p),x++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(p,this.frictionResult)}this.enableFrictionReduction&&x&&this.createFrictionFromAverage(x)}boxConvex(e,t,i,n,r,o,s,c,d,l,h){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexConvex(e.convexPolyhedronRepresentation,t,i,n,r,o,s,c,e,t,h)}sphereHeightfield(e,t,i,n,r,o,s,c,d,l,h){let u=t.data,f=e.radius,x=t.elementSize,b=Xv,y=qv;te.pointToLocalFrame(n,o,i,y);let g=Math.floor((y.x-f)/x)-1,p=Math.ceil((y.x+f)/x)+1,m=Math.floor((y.y-f)/x)-1,v=Math.ceil((y.y+f)/x)+1;if(p<0||v<0||g>u.length||m>u[0].length)return;g<0&&(g=0),p<0&&(p=0),m<0&&(m=0),v<0&&(v=0),g>=u.length&&(g=u.length-1),p>=u.length&&(p=u.length-1),v>=u[0].length&&(v=u[0].length-1),m>=u[0].length&&(m=u[0].length-1);let w=[];t.getRectMinMax(g,m,p,v,w);let E=w[0],C=w[1];if(y.z-f>C||y.z+f<E)return;let T=this.result;for(let R=g;R<p;R++)for(let I=m;I<v;I++){let O=T.length,L=!1;if(t.getConvexTrianglePillar(R,I,!1),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(L=this.sphereConvex(e,t.pillarConvex,i,b,r,o,s,c,e,t,h)),h&&L||(t.getConvexTrianglePillar(R,I,!0),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(L=this.sphereConvex(e,t.pillarConvex,i,b,r,o,s,c,e,t,h)),h&&L))return!0;if(T.length-O>2)return}}boxHeightfield(e,t,i,n,r,o,s,c,d,l,h){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexHeightfield(e.convexPolyhedronRepresentation,t,i,n,r,o,s,c,e,t,h)}convexHeightfield(e,t,i,n,r,o,s,c,d,l,h){let u=t.data,f=t.elementSize,x=e.boundingSphereRadius,b=Vv,y=Wv,g=Gv;te.pointToLocalFrame(n,o,i,g);let p=Math.floor((g.x-x)/f)-1,m=Math.ceil((g.x+x)/f)+1,v=Math.floor((g.y-x)/f)-1,w=Math.ceil((g.y+x)/f)+1;if(m<0||w<0||p>u.length||v>u[0].length)return;p<0&&(p=0),m<0&&(m=0),v<0&&(v=0),w<0&&(w=0),p>=u.length&&(p=u.length-1),m>=u.length&&(m=u.length-1),w>=u[0].length&&(w=u[0].length-1),v>=u[0].length&&(v=u[0].length-1);let E=[];t.getRectMinMax(p,v,m,w,E);let C=E[0],T=E[1];if(!(g.z-x>T||g.z+x<C))for(let R=p;R<m;R++)for(let I=v;I<w;I++){let O=!1;if(t.getConvexTrianglePillar(R,I,!1),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(O=this.convexConvex(e,t.pillarConvex,i,b,r,o,s,c,null,null,h,y,null)),h&&O||(t.getConvexTrianglePillar(R,I,!0),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(O=this.convexConvex(e,t.pillarConvex,i,b,r,o,s,c,null,null,h,y,null)),h&&O))return!0}}sphereParticle(e,t,i,n,r,o,s,c,d,l,h){let u=Fv;if(u.set(0,0,1),n.vsub(i,u),u.lengthSquared()<=e.radius*e.radius){if(h)return!0;let x=this.createContactEquation(c,s,t,e,d,l);u.normalize(),x.rj.copy(u),x.rj.scale(e.radius,x.rj),x.ni.copy(u),x.ni.negate(x.ni),x.ri.set(0,0,0),this.result.push(x),this.createFrictionEquationsFromContact(x,this.frictionResult)}}planeParticle(e,t,i,n,r,o,s,c,d,l,h){let u=jv;u.set(0,0,1),s.quaternion.vmult(u,u);let f=Bv;if(n.vsub(s.position,f),u.dot(f)<=0){if(h)return!0;let b=this.createContactEquation(c,s,t,e,d,l);b.ni.copy(u),b.ni.negate(b.ni),b.ri.set(0,0,0);let y=Hv;u.scale(u.dot(n),y),n.vsub(y,y),b.rj.copy(y),this.result.push(b),this.createFrictionEquationsFromContact(b,this.frictionResult)}}boxParticle(e,t,i,n,r,o,s,c,d,l,h){return e.convexPolyhedronRepresentation.material=e.material,e.convexPolyhedronRepresentation.collisionResponse=e.collisionResponse,this.convexParticle(e.convexPolyhedronRepresentation,t,i,n,r,o,s,c,e,t,h)}convexParticle(e,t,i,n,r,o,s,c,d,l,h){let u=-1,f=zv,x=Uv,b=null,y=Nv;if(y.copy(n),y.vsub(i,y),r.conjugate(Nu),Nu.vmult(y,y),e.pointIsInside(y)){e.worldVerticesNeedsUpdate&&e.computeWorldVertices(i,r),e.worldFaceNormalsNeedsUpdate&&e.computeWorldFaceNormals(r);for(let g=0,p=e.faces.length;g!==p;g++){let m=[e.worldVertices[e.faces[g][0]]],v=e.worldFaceNormals[g];n.vsub(m[0],zu);let w=-v.dot(zu);if(b===null||Math.abs(w)<Math.abs(b)){if(h)return!0;b=w,u=g,f.copy(v)}}if(u!==-1){let g=this.createContactEquation(c,s,t,e,d,l);f.scale(b,x),x.vadd(n,x),x.vsub(i,x),g.rj.copy(x),f.negate(g.ni),g.ri.set(0,0,0);let p=g.ri,m=g.rj;p.vadd(n,p),p.vsub(c.position,p),m.vadd(i,m),m.vsub(s.position,m),this.result.push(g),this.createFrictionEquationsFromContact(g,this.frictionResult)}else console.warn("Point found inside convex, but did not find penetrating face!")}}heightfieldCylinder(e,t,i,n,r,o,s,c,d,l,h){return this.convexHeightfield(t,e,n,i,o,r,c,s,d,l,h)}particleCylinder(e,t,i,n,r,o,s,c,d,l,h){return this.convexParticle(t,e,n,i,o,r,c,s,d,l,h)}sphereTrimesh(e,t,i,n,r,o,s,c,d,l,h){let u=Jb,f=Zb,x=$b,b=ev,y=tv,g=iv,p=sv,m=Kb,v=Qb,w=av;te.pointToLocalFrame(n,o,i,y);let E=e.radius;p.lowerBound.set(y.x-E,y.y-E,y.z-E),p.upperBound.set(y.x+E,y.y+E,y.z+E),t.getTrianglesInAABB(p,w);let C=Yb,T=e.radius*e.radius;for(let A=0;A<w.length;A++)for(let F=0;F<3;F++)if(t.getVertex(t.indices[w[A]*3+F],C),C.vsub(y,v),v.lengthSquared()<=T){if(m.copy(C),te.pointToWorldFrame(n,o,m,C),C.vsub(i,v),h)return!0;let H=this.createContactEquation(s,c,e,t,d,l);H.ni.copy(v),H.ni.normalize(),H.ri.copy(H.ni),H.ri.scale(e.radius,H.ri),H.ri.vadd(i,H.ri),H.ri.vsub(s.position,H.ri),H.rj.copy(C),H.rj.vsub(c.position,H.rj),this.result.push(H),this.createFrictionEquationsFromContact(H,this.frictionResult)}for(let A=0;A<w.length;A++)for(let F=0;F<3;F++){t.getVertex(t.indices[w[A]*3+F],u),t.getVertex(t.indices[w[A]*3+(F+1)%3],f),f.vsub(u,x),y.vsub(f,g);let H=g.dot(x);y.vsub(u,g);let z=g.dot(x);if(z>0&&H<0&&(y.vsub(u,g),b.copy(x),b.normalize(),z=g.dot(b),b.scale(z,g),g.vadd(u,g),g.distanceTo(y)<e.radius)){if(h)return!0;let $=this.createContactEquation(s,c,e,t,d,l);g.vsub(y,$.ni),$.ni.normalize(),$.ni.scale(e.radius,$.ri),$.ri.vadd(i,$.ri),$.ri.vsub(s.position,$.ri),te.pointToWorldFrame(n,o,g,g),g.vsub(c.position,$.rj),te.vectorToWorldFrame(o,$.ni,$.ni),te.vectorToWorldFrame(o,$.ri,$.ri),this.result.push($),this.createFrictionEquationsFromContact($,this.frictionResult)}}let R=nv,I=rv,O=ov,L=Xb;for(let A=0,F=w.length;A!==F;A++){t.getTriangleVertices(w[A],R,I,O),t.getNormal(w[A],L),y.vsub(R,g);let H=g.dot(L);if(L.scale(H,g),y.vsub(g,g),H=g.distanceTo(y),be.pointInTriangle(g,R,I,O)&&H<e.radius){if(h)return!0;let z=this.createContactEquation(s,c,e,t,d,l);g.vsub(y,z.ni),z.ni.normalize(),z.ni.scale(e.radius,z.ri),z.ri.vadd(i,z.ri),z.ri.vsub(s.position,z.ri),te.pointToWorldFrame(n,o,g,g),g.vsub(c.position,z.rj),te.vectorToWorldFrame(o,z.ni,z.ni),te.vectorToWorldFrame(o,z.ri,z.ri),this.result.push(z),this.createFrictionEquationsFromContact(z,this.frictionResult)}}w.length=0}planeTrimesh(e,t,i,n,r,o,s,c,d,l,h){let u=new _,f=Vb;f.set(0,0,1),r.vmult(f,f);for(let x=0;x<t.vertices.length/3;x++){t.getVertex(x,u);let b=new _;b.copy(u),te.pointToWorldFrame(n,o,b,u);let y=Wb;if(u.vsub(i,y),f.dot(y)<=0){if(h)return!0;let p=this.createContactEquation(s,c,e,t,d,l);p.ni.copy(f);let m=qb;f.scale(y.dot(f),m),u.vsub(m,m),p.ri.copy(m),p.ri.vsub(s.position,p.ri),p.rj.copy(u),p.rj.vsub(c.position,p.rj),this.result.push(p),this.createFrictionEquationsFromContact(p,this.frictionResult)}}}},Rr=new _,Oo=new _,Io=new _,Nb=new _,zb=new _,Ub=new ce,Gb=new ce,Vb=new _,Wb=new _,qb=new _,Xb=new _,Qb=new _,Yb=new _,Kb=new _,Jb=new _,Zb=new _,$b=new _,ev=new _,tv=new _,iv=new _,nv=new _,rv=new _,ov=new _,sv=new Ze,av=[],_a=new _,Fu=new _,lv=new _,cv=new _,dv=new _;function hv(a,e,t){let i=null,n=a.length;for(let r=0;r!==n;r++){let o=a[r],s=lv;a[(r+1)%n].vsub(o,s);let c=cv;s.cross(e,c);let d=dv;t.vsub(o,d);let l=c.dot(d);if(i===null||l>0&&i===!0||l<=0&&i===!1){i===null&&(i=l>0);continue}else return!1}return!0}var Ea=new _,uv=new _,pv=new _,fv=new _,mv=[new _,new _,new _,new _,new _,new _],gv=new _,bv=new _,vv=new _,yv=new _,xv=new _,wv=new _,_v=new _,Ev=new _,Cv=new _,Tv=new _,Rv=new _,Sv=new _,Pv=new _,Ov=new _,Iv=new _,kv=new _,Av=new _,Mv=new _,Lv=new _,Dv=new _,jv=new _,Bv=new _,Hv=new _,Fv=new _,Nu=new ce,Nv=new _,zv=new _,zu=new _,Uv=new _,Gv=new _,Vv=new _,Wv=[0],qv=new _,Xv=new _,ka=class{constructor(){this.current=void 0,this.previous=void 0,this.current=[],this.previous=[]}getKey(e,t){if(t<e){let i=t;t=e,e=i}return e<<16|t}set(e,t){let i=this.getKey(e,t),n=this.current,r=0;for(;i>n[r];)r++;if(i!==n[r]){for(let o=n.length-1;o>=r;o--)n[o+1]=n[o];n[r]=i}}tick(){let e=this.current;this.current=this.previous,this.previous=e,this.current.length=0}getDiff(e,t){let i=this.current,n=this.previous,r=i.length,o=n.length,s=0;for(let c=0;c<r;c++){let d=!1,l=i[c];for(;l>n[s];)s++;d=l===n[s],d||Uu(e,l)}s=0;for(let c=0;c<o;c++){let d=!1,l=n[c];for(;l>i[s];)s++;d=i[s]===l,d||Uu(t,l)}}};function Uu(a,e){a.push((e&4294901760)>>16,e&65535)}var Bc=class{constructor(){this.data={keys:[]}}get(e,t){if(e>t){let i=t;t=e,e=i}return this.data[e+"-"+t]}set(e,t,i){if(e>t){let r=t;t=e,e=r}let n=e+"-"+t;this.get(e,t)||this.data.keys.push(n),this.data[n]=i}reset(){let e=this.data,t=e.keys;for(;t.length>0;){let i=t.pop();delete e[i]}}},Aa=class extends Ta{constructor(e={}){super(),this.dt=void 0,this.allowSleep=void 0,this.contacts=void 0,this.frictionEquations=void 0,this.quatNormalizeSkip=void 0,this.quatNormalizeFast=void 0,this.time=void 0,this.stepnumber=void 0,this.default_dt=void 0,this.nextId=void 0,this.gravity=void 0,this.broadphase=void 0,this.bodies=void 0,this.hasActiveBodies=void 0,this.solver=void 0,this.constraints=void 0,this.narrowphase=void 0,this.collisionMatrix=void 0,this.collisionMatrixPrevious=void 0,this.bodyOverlapKeeper=void 0,this.shapeOverlapKeeper=void 0,this.materials=void 0,this.contactmaterials=void 0,this.contactMaterialTable=void 0,this.defaultMaterial=void 0,this.defaultContactMaterial=void 0,this.doProfiling=void 0,this.profile=void 0,this.accumulator=void 0,this.subsystems=void 0,this.addBodyEvent=void 0,this.removeBodyEvent=void 0,this.idToBodyMap=void 0,this.dt=-1,this.allowSleep=!!e.allowSleep,this.contacts=[],this.frictionEquations=[],this.quatNormalizeSkip=e.quatNormalizeSkip!==void 0?e.quatNormalizeSkip:0,this.quatNormalizeFast=e.quatNormalizeFast!==void 0?e.quatNormalizeFast:!1,this.time=0,this.stepnumber=0,this.default_dt=1/60,this.nextId=0,this.gravity=new _,e.gravity&&this.gravity.copy(e.gravity),this.broadphase=e.broadphase!==void 0?e.broadphase:new Ic,this.bodies=[],this.hasActiveBodies=!1,this.solver=e.solver!==void 0?e.solver:new Mc,this.constraints=[],this.narrowphase=new jc(this),this.collisionMatrix=new Ca,this.collisionMatrixPrevious=new Ca,this.bodyOverlapKeeper=new ka,this.shapeOverlapKeeper=new ka,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new Bc,this.defaultMaterial=new Ao("default"),this.defaultContactMaterial=new ko(this.defaultMaterial,this.defaultMaterial,{friction:.3,restitution:0}),this.doProfiling=!1,this.profile={solve:0,makeContactConstraints:0,broadphase:0,integrate:0,narrowphase:0},this.accumulator=0,this.subsystems=[],this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null},this.idToBodyMap={},this.broadphase.setWorld(this)}getContactMaterial(e,t){return this.contactMaterialTable.get(e.id,t.id)}numObjects(){return this.bodies.length}collisionMatrixTick(){let e=this.collisionMatrixPrevious;this.collisionMatrixPrevious=this.collisionMatrix,this.collisionMatrix=e,this.collisionMatrix.reset(),this.bodyOverlapKeeper.tick(),this.shapeOverlapKeeper.tick()}addConstraint(e){this.constraints.push(e)}removeConstraint(e){let t=this.constraints.indexOf(e);t!==-1&&this.constraints.splice(t,1)}rayTest(e,t,i){i instanceof Ss?this.raycastClosest(e,t,{skipBackfaces:!0},i):this.raycastAll(e,t,{skipBackfaces:!0},i)}raycastAll(e,t,i={},n){return i.mode=be.ALL,i.from=e,i.to=t,i.callback=n,Pc.intersectWorld(this,i)}raycastAny(e,t,i={},n){return i.mode=be.ANY,i.from=e,i.to=t,i.result=n,Pc.intersectWorld(this,i)}raycastClosest(e,t,i={},n){return i.mode=be.CLOSEST,i.from=e,i.to=t,i.result=n,Pc.intersectWorld(this,i)}addBody(e){this.bodies.includes(e)||(e.index=this.bodies.length,this.bodies.push(e),e.world=this,e.initPosition.copy(e.position),e.initVelocity.copy(e.velocity),e.timeLastSleepy=this.time,e instanceof G&&(e.initAngularVelocity.copy(e.angularVelocity),e.initQuaternion.copy(e.quaternion)),this.collisionMatrix.setNumObjects(this.bodies.length),this.addBodyEvent.body=e,this.idToBodyMap[e.id]=e,this.dispatchEvent(this.addBodyEvent))}removeBody(e){e.world=null;let t=this.bodies.length-1,i=this.bodies,n=i.indexOf(e);if(n!==-1){i.splice(n,1);for(let r=0;r!==i.length;r++)i[r].index=r;this.collisionMatrix.setNumObjects(t),this.removeBodyEvent.body=e,delete this.idToBodyMap[e.id],this.dispatchEvent(this.removeBodyEvent)}}getBodyById(e){return this.idToBodyMap[e]}getShapeById(e){let t=this.bodies;for(let i=0;i<t.length;i++){let n=t[i].shapes;for(let r=0;r<n.length;r++){let o=n[r];if(o.id===e)return o}}return null}addMaterial(e){this.materials.push(e)}addContactMaterial(e){this.contactmaterials.push(e),this.contactMaterialTable.set(e.materials[0].id,e.materials[1].id,e)}step(e,t,i=10){if(t===void 0)this.internalStep(e),this.time+=e;else{this.accumulator+=t;let n=Me.now(),r=0;for(;this.accumulator>=e&&r<i&&(this.internalStep(e),this.accumulator-=e,r++,!(Me.now()-n>e*1e3)););this.accumulator=this.accumulator%e;let o=this.accumulator/e;for(let s=0;s!==this.bodies.length;s++){let c=this.bodies[s];c.previousPosition.lerp(c.position,o,c.interpolatedPosition),c.previousQuaternion.slerp(c.quaternion,o,c.interpolatedQuaternion),c.previousQuaternion.normalize()}this.time+=t}}internalStep(e){this.dt=e;let t=this.contacts,i=Zv,n=$v,r=this.numObjects(),o=this.bodies,s=this.solver,c=this.gravity,d=this.doProfiling,l=this.profile,h=G.DYNAMIC,u=-1/0,f=this.constraints,x=Jv;c.length();let b=c.x,y=c.y,g=c.z,p=0;for(d&&(u=Me.now()),p=0;p!==r;p++){let A=o[p];if(A.type===h){let F=A.force,H=A.mass;F.x+=H*b,F.y+=H*y,F.z+=H*g}}for(let A=0,F=this.subsystems.length;A!==F;A++)this.subsystems[A].update();d&&(u=Me.now()),i.length=0,n.length=0,this.broadphase.collisionPairs(this,i,n),d&&(l.broadphase=Me.now()-u);let m=f.length;for(p=0;p!==m;p++){let A=f[p];if(!A.collideConnected)for(let F=i.length-1;F>=0;F-=1)(A.bodyA===i[F]&&A.bodyB===n[F]||A.bodyB===i[F]&&A.bodyA===n[F])&&(i.splice(F,1),n.splice(F,1))}this.collisionMatrixTick(),d&&(u=Me.now());let v=Kv,w=t.length;for(p=0;p!==w;p++)v.push(t[p]);t.length=0;let E=this.frictionEquations.length;for(p=0;p!==E;p++)x.push(this.frictionEquations[p]);for(this.frictionEquations.length=0,this.narrowphase.getContacts(i,n,this,t,v,this.frictionEquations,x),d&&(l.narrowphase=Me.now()-u),d&&(u=Me.now()),p=0;p<this.frictionEquations.length;p++)s.addEquation(this.frictionEquations[p]);let C=t.length;for(let A=0;A!==C;A++){let F=t[A],H=F.bi,z=F.bj,q=F.si,$=F.sj,W;if(H.material&&z.material?W=this.getContactMaterial(H.material,z.material)||this.defaultContactMaterial:W=this.defaultContactMaterial,W.friction,H.material&&z.material&&(H.material.friction>=0&&z.material.friction>=0&&H.material.friction*z.material.friction,H.material.restitution>=0&&z.material.restitution>=0&&(F.restitution=H.material.restitution*z.material.restitution)),s.addEquation(F),H.allowSleep&&H.type===G.DYNAMIC&&H.sleepState===G.SLEEPING&&z.sleepState===G.AWAKE&&z.type!==G.STATIC){let Ne=z.velocity.lengthSquared()+z.angularVelocity.lengthSquared(),ge=z.sleepSpeedLimit**2;Ne>=ge*2&&(H.wakeUpAfterNarrowphase=!0)}if(z.allowSleep&&z.type===G.DYNAMIC&&z.sleepState===G.SLEEPING&&H.sleepState===G.AWAKE&&H.type!==G.STATIC){let Ne=H.velocity.lengthSquared()+H.angularVelocity.lengthSquared(),ge=H.sleepSpeedLimit**2;Ne>=ge*2&&(z.wakeUpAfterNarrowphase=!0)}this.collisionMatrix.set(H,z,!0),this.collisionMatrixPrevious.get(H,z)||(Cs.body=z,Cs.contact=F,H.dispatchEvent(Cs),Cs.body=H,z.dispatchEvent(Cs)),this.bodyOverlapKeeper.set(H.id,z.id),this.shapeOverlapKeeper.set(q.id,$.id)}for(this.emitContactEvents(),d&&(l.makeContactConstraints=Me.now()-u,u=Me.now()),p=0;p!==r;p++){let A=o[p];A.wakeUpAfterNarrowphase&&(A.wakeUp(),A.wakeUpAfterNarrowphase=!1)}for(m=f.length,p=0;p!==m;p++){let A=f[p];A.update();for(let F=0,H=A.equations.length;F!==H;F++){let z=A.equations[F];s.addEquation(z)}}s.solve(e,this),d&&(l.solve=Me.now()-u),s.removeAllEquations();let T=Math.pow;for(p=0;p!==r;p++){let A=o[p];if(A.type&h){let F=T(1-A.linearDamping,e),H=A.velocity;H.scale(F,H);let z=A.angularVelocity;if(z){let q=T(1-A.angularDamping,e);z.scale(q,z)}}}for(this.dispatchEvent(Yv),p=0;p!==r;p++){let A=o[p];A.preStep&&A.preStep.call(A)}d&&(u=Me.now());let I=this.stepnumber%(this.quatNormalizeSkip+1)===0,O=this.quatNormalizeFast;for(p=0;p!==r;p++)o[p].integrate(e,I,O);for(this.clearForces(),this.broadphase.dirty=!0,d&&(l.integrate=Me.now()-u),this.stepnumber+=1,this.dispatchEvent(Qv),p=0;p!==r;p++){let A=o[p],F=A.postStep;F&&F.call(A)}let L=!0;if(this.allowSleep)for(L=!1,p=0;p!==r;p++){let A=o[p];A.sleepTick(this.time),A.sleepState!==G.SLEEPING&&(L=!0)}this.hasActiveBodies=L}emitContactEvents(){let e=this.hasAnyEventListener("beginContact"),t=this.hasAnyEventListener("endContact");if((e||t)&&this.bodyOverlapKeeper.getDiff(an,ln),e){for(let r=0,o=an.length;r<o;r+=2)Ts.bodyA=this.getBodyById(an[r]),Ts.bodyB=this.getBodyById(an[r+1]),this.dispatchEvent(Ts);Ts.bodyA=Ts.bodyB=null}if(t){for(let r=0,o=ln.length;r<o;r+=2)Rs.bodyA=this.getBodyById(ln[r]),Rs.bodyB=this.getBodyById(ln[r+1]),this.dispatchEvent(Rs);Rs.bodyA=Rs.bodyB=null}an.length=ln.length=0;let i=this.hasAnyEventListener("beginShapeContact"),n=this.hasAnyEventListener("endShapeContact");if((i||n)&&this.shapeOverlapKeeper.getDiff(an,ln),i){for(let r=0,o=an.length;r<o;r+=2){let s=this.getShapeById(an[r]),c=this.getShapeById(an[r+1]);cn.shapeA=s,cn.shapeB=c,s&&(cn.bodyA=s.body),c&&(cn.bodyB=c.body),this.dispatchEvent(cn)}cn.bodyA=cn.bodyB=cn.shapeA=cn.shapeB=null}if(n){for(let r=0,o=ln.length;r<o;r+=2){let s=this.getShapeById(ln[r]),c=this.getShapeById(ln[r+1]);dn.shapeA=s,dn.shapeB=c,s&&(dn.bodyA=s.body),c&&(dn.bodyB=c.body),this.dispatchEvent(dn)}dn.bodyA=dn.bodyB=dn.shapeA=dn.shapeB=null}}clearForces(){let e=this.bodies,t=e.length;for(let i=0;i!==t;i++){let n=e[i];n.force,n.torque,n.force.set(0,0,0),n.torque.set(0,0,0)}}};new Ze;var Pc=new be,Me=globalThis.performance||{};if(!Me.now){let a=Date.now();Me.timing&&Me.timing.navigationStart&&(a=Me.timing.navigationStart),Me.now=()=>Date.now()-a}var Qv={type:"postStep"},Yv={type:"preStep"},Cs={type:G.COLLIDE_EVENT_NAME,body:null,contact:null},Kv=[],Jv=[],Zv=[],$v=[],an=[],ln=[],Ts={type:"beginContact",bodyA:null,bodyB:null},Rs={type:"endContact",bodyA:null,bodyB:null},cn={type:"beginShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null},dn={type:"endShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null};import{Box3 as Iy,Layers as nd,Matrix4 as rf,Quaternion as id,Raycaster as ky,Sphere as Ay,Vector2 as My,Vector3 as of}from"three";import{MeshBasicMaterial as ey,SphereGeometry as _p,BoxGeometry as Ep,PlaneGeometry as Cp,Mesh as Nn,CylinderGeometry as ty,BufferGeometry as zc,Float32BufferAttribute as Uc}from"three";function iy(a,e,{color:t=65280,scale:i=1,onInit:n,onUpdate:r,autoUpdate:o}={}){let s=[],c=new ey({color:t??65280,wireframe:!0}),d=new _,l=new _,h=new _,u=new ce,f=new _p(1),x=new Ep(1,1,1),b=new Cp(10,10,10,10);function y(T){let R=new zc,I=[];for(let L=0;L<T.vertices.length;L++){let A=T.vertices[L];I.push(A.x,A.y,A.z)}R.setAttribute("position",new Uc(I,3));let O=[];for(let L=0;L<T.faces.length;L++){let A=T.faces[L],F=A[0];for(let H=1;H<A.length-1;H++){let z=A[H],q=A[H+1];O.push(F,z,q)}}return R.setIndex(O),R.computeBoundingSphere(),R.computeVertexNormals(),R}function g(T){let R=new zc,I=[],O=d,L=l,A=h;for(let F=0;F<T.indices.length/3;F++)T.getTriangleVertices(F,O,L,A),I.push(O.x,O.y,O.z),I.push(L.x,L.y,L.z),I.push(A.x,A.y,A.z);return R.setAttribute("position",new Uc(I,3)),R.computeBoundingSphere(),R.computeVertexNormals(),R}function p(T){let R=new zc,I=T.elementSize||1,O=T.data.flatMap((A,F)=>A.flatMap((H,z)=>[F*I,z*I,H])),L=[];for(let A=0;A<T.data.length-1;A++)for(let F=0;F<T.data[A].length-1;F++){let H=T.data[A].length,z=A*H+F;L.push(z+1,z+H,z+H+1),L.push(z+H,z+1,z)}return R.setIndex(L),R.setAttribute("position",new Uc(O,3)),R.computeBoundingSphere(),R.computeVertexNormals(),R}function m(T){let R=new Nn,{SPHERE:I,BOX:O,PLANE:L,CYLINDER:A,CONVEXPOLYHEDRON:F,TRIMESH:H,HEIGHTFIELD:z}=V.types;switch(T.type){case I:{R=new Nn(f,c);break}case O:{R=new Nn(x,c);break}case L:{R=new Nn(b,c);break}case A:{let q=new ty(T.radiusTop,T.radiusBottom,T.height,T.numSegments);R=new Nn(q,c),T.geometryId=q.id;break}case F:{let q=y(T);R=new Nn(q,c),T.geometryId=q.id;break}case H:{let q=g(T);R=new Nn(q,c),T.geometryId=q.id;break}case z:{let q=p(T);R=new Nn(q,c),T.geometryId=q.id;break}}return a.add(R),R}function v(T,R){let{SPHERE:I,BOX:O,PLANE:L,CYLINDER:A,CONVEXPOLYHEDRON:F,TRIMESH:H,HEIGHTFIELD:z}=V.types;switch(R.type){case I:{let{radius:q}=R;T.scale.set(q*i,q*i,q*i);break}case O:{T.scale.copy(R.halfExtents),T.scale.multiplyScalar(2*i);break}case L:break;case A:{T.scale.set(1*i,1*i,1*i);break}case F:{T.scale.set(1*i,1*i,1*i);break}case H:{T.scale.copy(R.scale).multiplyScalar(i);break}case z:{T.scale.set(1*i,1*i,1*i);break}}}function w(T,R){if(!T)return!1;let{geometry:I}=T;return I instanceof _p&&R.type===V.types.SPHERE||I instanceof Ep&&R.type===V.types.BOX||I instanceof Cp&&R.type===V.types.PLANE||I.id===R.geometryId&&R.type===V.types.CYLINDER||I.id===R.geometryId&&R.type===V.types.CONVEXPOLYHEDRON||I.id===R.geometryId&&R.type===V.types.TRIMESH||I.id===R.geometryId&&R.type===V.types.HEIGHTFIELD}function E(T,R){let I=s[T],O=!1;return w(I,R)||(I&&a.remove(I),s[T]=I=m(R),O=!0),v(I,R),O}function C(){let T=s,R=d,I=u,O=0;for(let L of e)for(let A=0;A!==L.shapes.length;A++){let F=L.shapes[A],H=E(O,F),z=T[O];z&&(L.quaternion.vmult(L.shapeOffsets[A],R),L.position.vadd(R,R),L.quaternion.mult(L.shapeOrientations[A],I),z.position.copy(R),z.quaternion.copy(I),H&&n instanceof Function&&n(L,z,F),!H&&r instanceof Function&&r(L,z,F)),O++}for(let L=O;L<T.length;L++){let A=T[L];A&&a.remove(A)}T.length=O,o!==!1&&requestAnimationFrame(C)}return o!==!1&&requestAnimationFrame(C),{update:C}}var Tp=iy;import*as de from"three";var Gc=class{random(){return Math.random()}clamp(e,t,i){return e<t?t:e>i?i:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,i){return i=i<0?0:i,i=i>1?1:i,e+(t-e)*i}moveTowards(e,t,i){return e+=i,(i<0&&e<t||i>0&&e>t)&&(e=t),e}toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}},J=new Gc;import{Vector3 as ny,Quaternion as ry,Uniform as oy}from"three";var Wc=class{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){let e=this._index++;return e>=this._cache.length&&(e>=this._maxSize?e=this._index=0:this._cache.push(this._factory())),this._cache[e]}},pC=new ry().setFromAxisAngle(new ny(0,1,0),Math.PI);var qc=new Wc(()=>new de.Vector3,100);function X(a,e=null,t=!0){let i=e??qc.get();return a?a.parent?(t&&a.updateWorldMatrix(!0,!1),a.matrixWorldNeedsUpdate&&a.updateMatrixWorld(),i.setFromMatrixPosition(a.matrixWorld),i):i.copy(a.position):i.set(0,0,0)}function se(a,e){if(!a)return;let t=qc.get();e!==t&&t.copy(e),(a?.parent??a).worldToLocal(t),a.position.set(t.x,t.y,t.z)}function Mo(a,e,t,i){let n=qc.get();n.set(e,t,i),se(a,n)}var kr=new de.Quaternion,Os=new de.Quaternion,Vc=new de.Quaternion;function Ie(a,e=null){if(!a)return Os.set(0,0,0,1);let t=e??Os;return a.parent?(a.getWorldQuaternion(t),t):t.copy(a.quaternion)}function $e(a,e){if(!a)return;e!==kr&&kr.copy(e);let t=kr;a?.parent?.getWorldQuaternion(Vc),Vc.invert();let n=Vc.multiply(t);a.quaternion.set(n.x,n.y,n.z,n.w)}function Pp(a,e,t,i,n){kr.set(e,t,i,n),$e(a,kr)}var Ma=new de.Vector3,fC=new de.Vector3;function Is(a,e=null){return a?a.parent?(a.getWorldScale(e??Ma),e??Ma):Ma.copy(a.position):Ma.set(0,0,0)}var mC=new de.Vector3,gC=new de.Quaternion;var Rp=new de.Euler,Sp=new de.Euler,sy=new de.Vector3;function ay(a){return a.getWorldQuaternion(Os),Sp.setFromQuaternion(Os),Sp}function Op(a,e){$e(a,Os.setFromEuler(e))}function La(a){let e=ay(a),t=sy;return t.set(e.x,e.y,e.z),t.x=J.toDegrees(t.x),t.y=J.toDegrees(t.y),t.z=J.toDegrees(t.z),t}function Da(a,e,t,i,n=!0){n&&(e=J.toRadians(e),t=J.toRadians(t),i=J.toRadians(i)),Rp.set(e,t,i),kr.setFromEuler(Rp),$e(a,kr)}function ks(a,e=!0){!a||(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(a):a.traverse(function(t){for(var i="|___",n=t;n.parent!==null;)i=" "+i,n=n.parent;console.log(i+t.name+" <"+t.type+">")}))}var bC=new de.PlaneGeometry(2,2,1,1),vC=new de.WebGLRenderer({antialias:!1}),yC=new de.PerspectiveCamera,xC=new de.Scene,wC=new de.ShaderMaterial({uniforms:{blitTexture:new oy(null)},vertexShader:`
131
+ <a href="https://docs.needle.tools/serializeable" target="_blank">documentation</a>`,1),console.warn(t,i,o[i],o)))}}function mf(o,e){for(let n of Object.keys(e)){let i=e[n];if(typeof i=="object"&&i!==null&&i!==void 0){let r=o[n];if(!r){nr&&console.log(n,"is undefined on",o);continue}for(let s of Object.keys(i))r[s]===void 0&&t(i[s])&&!t(r)&&(r[s]=i[s])}}function t(n){switch(typeof n){case"number":case"string":case"boolean":return!0}return!1}}function Rl(o,e,t,n,i){let r=typeof e=="function"&&e.prototype===void 0,s=e;if(r)try{if(s=e?.call(e,i),r=!1,s==null)return}catch(l){console.error("Error in callback",l,o)}if(!r&&i instanceof s)return i;if(i&&typeof i=="object"&&hu(i)){if(i.__concreteInstance)return i.__concreteInstance;let l=i;if(!l.$serializedTypes&&s.prototype.$serializedTypes&&(l.$serializedTypes=s.prototype.$serializedTypes),l.$serializedTypes&&Vo(l,o,t),i&&s!==void 0)try{let u=new s;_e&&console.log("Create concrete instance for persistent asset",i,"instance:",u),Nn(u,i),i.__concreteInstance=u,i=u}catch(u){console.error("Error creating instance or creating values on instance",u,i,s)}return i}if(n||(n={serializer:Is.getSerializerForConstructor(s)}),Array.isArray(o)){let l=[];for(let u=0;u<o.length;u++){let h=o[u],b=Rl(h,e,t,n,h);l.push(b)}return l}let a=n.serializer;if(a)return a.onDeserialize(o,t);let c;o&&(o.isMaterial||o.isTexture||o.isObject3D)?c=o:c=new s(...gf(o));let d=c;return d.$serializedTypes&&Vo(d,o,t),c}function gf(o){if(ks.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(let e of Object.keys(o))ks.push(o[e]);return ks}var Ms=Symbol("assigned component properties");function Nn(o,e){if(e==null||o==null)return;let t=!1;o[Ms]=!0;for(let n of Object.keys(e)){let i=bf(o,n);t&&i===void 0||(!i||i.writable===!0||i?.set!==void 0)&&(o[n]=e[n])}delete o[Ms]}function bf(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}var No=class{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}};var Ds=class extends EventTarget{_doubleClickTimeThreshold=.2;_longPressTimeThreshold=1;get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}_specialCursorTrigger=0;setCursorPointer(){this._specialCursorTrigger+=1,this.context.domElement.style.cursor="pointer"}setCursorNormal(){this._specialCursorTrigger-=1,this._specialCursorTrigger=Math.max(0,this._specialCursorTrigger),this._specialCursorTrigger===0&&(this.context.domElement.style.cursor="default")}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new Dt.Vector2];_pointerPositionsLastFrame=[new Dt.Vector2];_pointerPositionsDelta=[new Dt.Vector2];_pointerPositionsRC=[new Dt.Vector2];_pointerPositionDown=[new Dt.Vector2];_pointerDownTime=[];_pointerUpTime=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_pointerEvent=[];getKeyDown(){for(let e in this.keysPressed){let t=this.keysPressed[e];if(t.startFrame===this.context.time.frameCount)return t.key}return null}getKeyPressed(){for(let e in this.keysPressed){let t=this.keysPressed[e];if(t.pressed)return t.key}return null}isKeyDown(e){return typeof e=="number"&&(console.warn("Use of keycode as number is not recommended, please use KeyCode or string instead"),e=String.fromCharCode(e)),this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.startFrame===this.context.time.frameCount&&this.keysPressed[e].pressed}isKeyUp(e){return typeof e=="number"&&(console.warn("Use of keycode as number is not recommended, please use KeyCode or string instead"),e=String.fromCharCode(e)),this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.frame===this.context.time.frameCount&&!this.keysPressed[e].pressed}isKeyPressed(e){return typeof e=="number"&&(e=String.fromCharCode(e)),this.context.application.isVisible&&this.context.application.hasFocus&&this.keysPressed[e]?.pressed}createPointerDown(e){this.onDown(e)}createPointerMove(e){this.onMove(e)}createPointerUp(e){this.onUp(e)}constructor(e){super(),this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame.bind(this));let t=this.context.renderer.domElement;t.addEventListener("touchmove",this.onTouchMove.bind(this),{passive:!0}),t.addEventListener("touchend",this.onTouchUp.bind(this),!1),t.addEventListener("pointerdown",this.onPointerDown.bind(this),!1),t.addEventListener("pointermove",this.onPointerMove.bind(this),!1),t.addEventListener("pointerup",this.onPointerUp.bind(this),!1),t.addEventListener("wheel",this.onMouseWheel.bind(this),{passive:!0}),window.addEventListener("keydown",this.onKeyDown.bind(this),!1),window.addEventListener("keypress",this.onKeyPressed.bind(this),!1),window.addEventListener("keyup",this.onKeyUp.bind(this),!1),window.addEventListener("blur",this.onLostFocus.bind(this))}onLostFocus(){for(let e in this.keysPressed)this.keysPressed[e].pressed=!1}onEndOfFrame(){for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(let e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1}keysPressed={};onKeyDown(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.key];t&&t.pressed||(this.keysPressed[e.key]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key},this.onDispatchEvent("keydown",new No(e)))}onKeyPressed(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.key];!t||(t.pressed=!0,t.frame=this.context.time.frameCount+1,this.onDispatchEvent("keypress",new No(e)))}onKeyUp(e){if(!this.context.application.hasFocus)return;let t=this.keysPressed[e.key];!t||(t.pressed=!1,t.frame=this.context.time.frameCount+1,this.onDispatchEvent("keyup",new No(e)))}onMouseWheel(e){this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0}onTouchMove(e){}onTouchUp(e){}onPointerDown(e){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),this.onDown({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e})}onPointerMove(e){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),t<0&&(t=0);let n={button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e};this.onMove(n),this.onDispatchEvent("pointermove",e)}onPointerUp(e){if(e.defaultPrevented||e.pointerType===void 0&&e.pointerId===void 0)return;let t=e.pointerType==="mouse"?e.button:this.getPointerIndex(e.pointerId);e.pointerId===void 0&&e.button!==void 0&&(t=e.button),this._pointerIds[t]=-1,this.onUp({button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,source:e}),this.onDispatchEvent("pointerup",e)}isInRect(e){return!0}onDown(e){if(!!this.isInRect(e)){for(this.setPointerState(e.button,this._pointerPressed,!0),this.setPointerState(e.button,this._pointerDown,!0),this.setPointerStateT(e.button,this._pointerEvent,e.source);e.button>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[e.button]=e.pointerType===void 0?"mouse":e.pointerType;e.button>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new Dt.Vector2);this._pointerPositionDown[e.button].set(e.clientX,e.clientY),e.button>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[e.button]=this.context.time.time,this.updatePointerPosition(e),this.onDispatchEvent("pointerdown",e)}}onMove(e){!this.isInRect(e)||(this.updatePointerPosition(e),this.setPointerStateT(e.button,this._pointerEvent,e.source))}onUp(e){if(this.setPointerState(e.button,this._pointerPressed,!1),this.setPointerStateT(e.button,this._pointerEvent,e.source),!this.isInRect(e))return;if(this.setPointerState(e.button,this._pointerUp,!0),this.updatePointerPosition(e),!this._pointerPositionDown[e.button]){console.warn("Received pointer up event without matching down event for button: "+e.button);return}let t=e.clientX-this._pointerPositionDown[e.button].x,n=e.clientY-this._pointerPositionDown[e.button].y;if(e.button>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),Math.abs(t)<5&&Math.abs(n)<5){this.setPointerState(e.button,this._pointerClick,!0);let i=this._pointerUpTime[e.button],r=this.context.time.time-i;r<this._doubleClickTimeThreshold&&r>0&&this.setPointerState(e.button,this._pointerDoubleClick,!0)}this._pointerUpTime[e.button]=this.context.time.time}updatePointerPosition(e){for(;e.button>=this._pointerPositions.length;)this._pointerPositions.push(new Dt.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Dt.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Dt.Vector2);let t=this._pointerPositionsLastFrame[e.button];t.copy(this._pointerPositions[e.button]),this._pointerPositionsDelta[e.button].set(e.clientX-t.x,e.clientY-t.y),this._pointerPositions[e.button].x=e.clientX,this._pointerPositions[e.button].y=e.clientY;let n=e.clientX+window.scrollX,i=e.clientY+window.scrollY;for(;e.button>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new Dt.Vector2);this._pointerPositionsRC[e.button].x=(n-this.context.domX)/this.context.domWidth*2-1,this._pointerPositionsRC[e.button].y=-((i-this.context.domY)/this.context.domHeight)*2+1}getPointerIndex(e){for(let t=0;t<this._pointerIds.length;t++)if(this._pointerIds[t]===e)return t;for(let t=0;t<this._pointerIds.length;t++)if(this._pointerIds[t]===-1&&(this._pointerIds[t]=e),this._pointerIds[t]===e)return t;return this._pointerIds.push(e),this._pointerIds.length-1}setPointerState(e,t,n){for(;t.length<=e;)t.push(!1);t[e]=n}setPointerStateT(e,t,n){for(;t.length<=e;)t.push(null);t[e]=n}onDispatchEvent(e,t){let n=V.Current;try{V.Current=this.context;let i=new Event(e);Nn(i,t),this.dispatchEvent(i)}finally{V.Current=n}}};import{Box3 as zf,BufferAttribute as qu,BufferGeometry as Xf,Layers as Nl,LineBasicMaterial as Qf,LineSegments as qf,Matrix4 as Yf,Quaternion as Kf,Raycaster as Jf,Sphere as Zf,Vector2 as $f,Vector3 as Yu}from"three";import*as te from"three";var Pl=class{random(){return Math.random()}clamp(e,t,n){return e<t?t:e>n?n:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,n){return n=n<0?0:n,n=n>1?1:n,e+(t-e)*n}moveTowards(e,t,n){return e+=n,(n<0&&e<t||n>0&&e>t)&&(e=t),e}toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}},W=new Pl;import{Vector3 as vf,Quaternion as yf,Uniform as _f}from"three";var kl=class{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){let e=this._index++;return e>=this._cache.length&&(e>=this._maxSize?e=this._index=0:this._cache.push(this._factory())),this._cache[e]}},Iy=new yf().setFromAxisAngle(new vf(0,1,0),Math.PI);var Il=new kl(()=>new te.Vector3,100);function B(o,e=null,t=!0){let n=e??Il.get();return o?o.parent?(t&&o.updateWorldMatrix(!0,!1),o.matrixWorldNeedsUpdate&&o.updateMatrixWorld(),n.setFromMatrixPosition(o.matrixWorld),n):n.copy(o.position):n.set(0,0,0)}function J(o,e){if(!o)return;let t=Il.get();e!==t&&t.copy(e),(o?.parent??o).worldToLocal(t),o.position.set(t.x,t.y,t.z)}function Kr(o,e,t,n){let i=Il.get();i.set(e,t,n),J(o,i)}var ir=new te.Quaternion,Wo=new te.Quaternion,Ol=new te.Quaternion;function me(o,e=null){if(!o)return Wo.set(0,0,0,1);let t=e??Wo;return o.parent?(o.getWorldQuaternion(t),t):t.copy(o.quaternion)}function Be(o,e){if(!o)return;e!==ir&&ir.copy(e);let t=ir;o?.parent?.getWorldQuaternion(Ol),Ol.invert();let i=Ol.multiply(t);o.quaternion.set(i.x,i.y,i.z,i.w)}function yu(o,e,t,n,i){ir.set(e,t,n,i),Be(o,ir)}var As=new te.Vector3,My=new te.Vector3;function on(o,e=null){return o?o.parent?(o.getWorldScale(e??As),e??As):As.copy(o.position):As.set(0,0,0)}var Dy=new te.Vector3,Ay=new te.Quaternion;var bu=new te.Euler,vu=new te.Euler,Ef=new te.Vector3;function wf(o){return o.getWorldQuaternion(Wo),vu.setFromQuaternion(Wo),vu}function _u(o,e){Be(o,Wo.setFromEuler(e))}function Ls(o){let e=wf(o),t=Ef;return t.set(e.x,e.y,e.z),t.x=W.toDegrees(t.x),t.y=W.toDegrees(t.y),t.z=W.toDegrees(t.z),t}function js(o,e,t,n,i=!0){i&&(e=W.toRadians(e),t=W.toRadians(t),n=W.toRadians(n)),bu.set(e,t,n),ir.setFromEuler(bu),Be(o,ir)}function zo(o,e=!0){!o||(e?function t(n){console.groupCollapsed((n.name?n.name:"(no name : "+n.type+")")+" %o",n),n.children.forEach(t),console.groupEnd()}(o):o.traverse(function(t){for(var n="|___",i=t;i.parent!==null;)n=" "+n,i=i.parent;console.log(n+t.name+" <"+t.type+">")}))}var Ly=new te.PlaneGeometry(2,2,1,1),jy=new te.WebGLRenderer({antialias:!1}),Hy=new te.PerspectiveCamera,Fy=new te.Scene,By=new te.ShaderMaterial({uniforms:{blitTexture:new _f(null)},vertexShader:`
132
132
  varying vec2 vUv;
133
133
  void main(){
134
134
  vUv = uv;
@@ -141,13 +141,13 @@ in script ${t}.ts
141
141
  uv.y = 1.0 - uv.y;
142
142
  gl_FragColor = vec4(uv.xy, 0, 1);
143
143
  gl_FragColor = texture2D( blitTexture, uv);
144
- }`});import{Vector3 as ly}from"three";var As=Symbol("object"),Lo=class{get __internalCollision(){return this.collision}get __internalInvertedSourceReceiver(){return this.invert}invert;collision;targetBody;context;me;_normal;get normal(){if(!this._normal){let e=this.collision.contact.ni;this._normal=new ly(e.x,e.y,e.z)}return this._normal}_collider;get collider(){return this._collider||(this._collider=this.context.getCollider(this.gameObject)),this._collider}get gameObject(){return this.targetBody[As]}constructor(e,t,i,n=!1){this.me=e,this.collision=t,this.context=i,this.targetBody=n?t.target:t.body,this.invert=n}};var ja=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),re=class{static isUsingInstancing(e){return e.__isUsingInstancing===!0}static markDirty(e,t=!0){if(!!e&&(this.isUsingInstancing(e)&&(e[ja]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)re.markDirty(i,!0)}};function Ar(a,e){try{e?a(e):a()}catch(t){return console.error(t),!1}return!0}var Ri="__isActiveInHierarchy",Mr="builtin_components";var hy=D("debugnewscripts"),ve=[];function un(a){if(!(a.new_scripts.length<=0)){if(hy&&console.log("Register new components",a.new_scripts.length,a.alias?"element: "+a.alias:""),a.new_scripts_pre_setup_callbacks.length>0){for(let e of a.new_scripts_pre_setup_callbacks)!e||e();a.new_scripts_pre_setup_callbacks.length=0}ve.length=0,a.new_scripts.length>0&&ve.push(...a.new_scripts),a.new_scripts.length=0;for(let e=0;e<ve.length;e++)try{let t=ve[e];if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),ve.splice(e,1),e--;continue}t.context=a,Ms(t.gameObject),Qc(t,a)}catch(t){console.error(t),hn(ve[e],a),ve.splice(e,1),e--}for(let e=0;e<ve.length;e++)try{let t=ve[e];if(t.destroyed){hn(ve[e],a),ve.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),Ms(t.gameObject),t.activeAndEnabled&&Ar(t.__internalAwake.bind(t)))}catch(t){console.error(t),hn(ve[e],a),ve.splice(e,1),e--}for(let e=0;e<ve.length;e++)try{let t=ve[e];if(t.destroyed||t.enabled===!1||(Ms(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Ar(t.__internalEnable.bind(t)))}catch(t){console.error(t),hn(ve[e],a),ve.splice(e,1),e--}for(let e=0;e<ve.length;e++)try{let t=ve[e];if(t.destroyed||!t.gameObject)continue;a.new_script_start.push(t)}catch(t){console.error(t),hn(ve[e],a),ve.splice(e,1),e--}ve.length=0;for(let e of a.new_scripts_post_setup_callbacks)e&&e();a.new_scripts_post_setup_callbacks.length=0}}function Ip(a){!a||(a.__internalDisable(),hn(a,a.context))}function Ba(a,e){for(let t=0;t<a.new_script_start.length;t++)try{let i=a.new_script_start[t];if(e!==void 0&&i.gameObject!==e||i.destroyed||i.activeAndEnabled===!1)continue;Ar(i.__internalAwake.bind(i)),Ar(i.__internalEnable.bind(i)),Ar(i.__internalStart.bind(i)),a.new_script_start.splice(t,1),t--}catch(i){console.error(i),hn(a.new_script_start[t],a),a.new_script_start.splice(t,1),t--}}function Qc(a,e){e.scripts.indexOf(a)===-1&&(e.scripts.push(a),a.earlyUpdate&&e.scripts_earlyUpdate.push(a),a.update&&e.scripts_update.push(a),a.lateUpdate&&e.scripts_lateUpdate.push(a),a.onBeforeRender&&e.scripts_onBeforeRender.push(a),a.onAfterRender&&e.scripts_onAfterRender.push(a))}function hn(a,e){Un(a,e.new_scripts),Un(a,e.new_script_start),Un(a,e.scripts),Un(a,e.scripts_earlyUpdate),Un(a,e.scripts_update),Un(a,e.scripts_lateUpdate),Un(a,e.scripts_onBeforeRender),Un(a,e.scripts_onAfterRender),e.stopAllCoroutinesFrom(a)}function Un(a,e){let t=e.indexOf(a);t>=0&&e.splice(t,1)}var uy={},Xc={};function Do(a){if(a||(a=K.Current.scene),!a){console.trace("Invalid call - no current context.");return}kp(a,Lr(a),!0)}function kp(a,e,t){let i=!1,n=Lr(a);if(uy[a.uuid]=n,e&&(e=Lr(a)),a[Ri]=e,!i){let r=Xc[a.uuid];r!==void 0&&r!==e&&t&&py(a,o=>{e?(Ar(o.__internalAwake.bind(o)),o.enabled=!0):o.enabled=!1})}if(Xc[a.uuid]=e,a.children)for(let r of a.children)kp(r,e,t)}function Ms(a){let e=!0,t=a,i=!1;for(;t&&t;){if(t.type==="Scene"&&(i=!0),!Lr(t)){e=!1;break}t=t.parent}if(!a){console.error("GO is null");return}Xc[a.uuid]=e,a[Ri]=e&&i}function py(a,e){if(a.userData?.components)for(let t of a.userData.components)e(t)}import*as Ls from"three";var Mp=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function fy(a){return typeof a=="string"&&Mp.test(a)}var Lp=fy;var ze=[];for(let a=0;a<256;++a)ze.push((a+256).toString(16).slice(1));function Dp(a,e=0){return(ze[a[e+0]]+ze[a[e+1]]+ze[a[e+2]]+ze[a[e+3]]+"-"+ze[a[e+4]]+ze[a[e+5]]+"-"+ze[a[e+6]]+ze[a[e+7]]+"-"+ze[a[e+8]]+ze[a[e+9]]+"-"+ze[a[e+10]]+ze[a[e+11]]+ze[a[e+12]]+ze[a[e+13]]+ze[a[e+14]]+ze[a[e+15]]).toLowerCase()}function my(a){if(!Lp(a))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(a.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(a.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(a.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(a.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(a.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var jp=my;function gy(a){a=unescape(encodeURIComponent(a));let e=[];for(let t=0;t<a.length;++t)e.push(a.charCodeAt(t));return e}var by="6ba7b810-9dad-11d1-80b4-00c04fd430c8",vy="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Yc(a,e,t){function i(n,r,o,s){var c;if(typeof n=="string"&&(n=gy(n)),typeof r=="string"&&(r=jp(r)),((c=r)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let d=new Uint8Array(16+n.length);if(d.set(r),d.set(n,r.length),d=t(d),d[6]=d[6]&15|e,d[8]=d[8]&63|128,o){s=s||0;for(let l=0;l<16;++l)o[s+l]=d[l];return o}return Dp(d)}try{i.name=a}catch{}return i.DNS=by,i.URL=vy,i}function yy(a,e,t,i){switch(a){case 0:return e&t^~e&i;case 1:return e^t^i;case 2:return e&t^e&i^t&i;case 3:return e^t^i}}function Kc(a,e){return a<<e|a>>>32-e}function xy(a){let e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof a=="string"){let o=unescape(encodeURIComponent(a));a=[];for(let s=0;s<o.length;++s)a.push(o.charCodeAt(s))}else Array.isArray(a)||(a=Array.prototype.slice.call(a));a.push(128);let i=a.length/4+2,n=Math.ceil(i/16),r=new Array(n);for(let o=0;o<n;++o){let s=new Uint32Array(16);for(let c=0;c<16;++c)s[c]=a[o*64+c*4]<<24|a[o*64+c*4+1]<<16|a[o*64+c*4+2]<<8|a[o*64+c*4+3];r[o]=s}r[n-1][14]=(a.length-1)*8/Math.pow(2,32),r[n-1][14]=Math.floor(r[n-1][14]),r[n-1][15]=(a.length-1)*8&4294967295;for(let o=0;o<n;++o){let s=new Uint32Array(80);for(let f=0;f<16;++f)s[f]=r[o][f];for(let f=16;f<80;++f)s[f]=Kc(s[f-3]^s[f-8]^s[f-14]^s[f-16],1);let c=t[0],d=t[1],l=t[2],h=t[3],u=t[4];for(let f=0;f<80;++f){let x=Math.floor(f/20),b=Kc(c,5)+yy(x,d,l,h)+u+e[x]+s[f]>>>0;u=h,h=l,l=Kc(d,30)>>>0,d=c,c=b}t[0]=t[0]+c>>>0,t[1]=t[1]+d>>>0,t[2]=t[2]+l>>>0,t[3]=t[3]+h>>>0,t[4]=t[4]+u>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}var Bp=xy;var wy=Yc("v5",80,Bp),Jc=wy;var Ha=D("debugcomponents"),_y="eff8ba80-635d-11ec-90d6-0242ac120003",Ue=class{get seed(){return this._seed}_originalSeed;_seed;constructor(e){this._originalSeed=e,this._seed=e}generateUUID(){let e=this._seed;return this._seed-=1,Jc(e.toString(),_y)}static createFromString(e){return new Ue(this.hash(e))}static hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}};var Fa=class{guid;constructor(e){this.guid=e}};function jo(a,e,t=!0){if(!a)return;let i=a;if(ei(a,t),!e){console.warn("Can not send destroy: No networking connection provided",a.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",a.guid);return}let n=a.guid;if(!n&&i.uuid&&(n=i.uuid),!n){console.warn("Can not send destroy: failed to find guid",a);return}let r=new Fa(n);e.send("instance-destroyed",r,2)}function Hp(a,e){let t=new Fa(a);e.send("instance-destroyed",t,2)}function Fp(a){a.connection.beginListen("instance-destroyed",e=>{Ha&&console.log("[Remote] Destroyed",a.scene,e);let t=Dr(e.guid,a.scene);t&&ei(t)})}var Zc=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function Na(a,e,t,i){let n=a;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(e.context||(e.context=K.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;let r=e?{...e}:null,{instance:o,seed:s}=Ey(n,e);if(o){let c=o;if(c.guid){Ha&&console.log("[Local] new instance","gameobject:",o?.guid);let d=new Zc(n.guid,c.guid);d.seed=s,r&&(r.position&&(d.position={x:r.position.x,y:r.position.y,z:r.position.z}),r.rotation&&(d.rotation={x:r.rotation.x,y:r.rotation.y,z:r.rotation.z,w:r.rotation.w}),r.scale&&(d.scale={x:r.scale.x,y:r.scale.y,z:r.scale.z})),d.position||(d.position={x:c.position.x,y:c.position.y,z:c.position.z}),d.rotation||(d.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),d.scale||(d.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),d.visible=n.visible,r?.parent&&(typeof r.parent=="string"?d.parent=r.parent:d.parent=r.parent.guid),d.hostData=t,i===!1&&(d.dontSave=!0),e?.context?.connection.send("new-instance-created",d)}else console.warn("Missing guid, can not send new instance event",c)}return o}function za(){return Math.random()*9999999}function Np(a){a.connection.beginListen("new-instance-created",async e=>{let t=await Cy(e.originalGuid,a.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let i=new Ge;e.position&&(i.position=new Ls.Vector3(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new Ls.Quaternion(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new Ls.Vector3(e.scale.x,e.scale.y,e.scale.z)),i.parent=e.parent,e.seed&&(i.idProvider=new Ue(e.seed)),i.visible=e.visible,i.context=a,Ha&&a.alias&&console.log("[Remote] instantiate in: "+a.alias);let n=jr(t,i);n&&(e.parent==="scene"&&a.scene.add(n),Ha&&console.log("[Remote] new instance","gameobject:",n?.guid,t))})}function Ey(a,e){let t=za(),i=e??new Ge;i.idProvider=new Ue(t);let n=jr(a,i);return{seed:t,instance:n}}var zp={};function Up(a,e){zp[a]=e}async function Cy(a,e){let t=zp[a];if(t!=null){let i=await t(a);if(i)return i}return Gp(a,e)}function Gp(a,e){if(e===null||!a)return null;if(e.guid===a)return e;if(e.children)for(let t of e.children){let i=Gp(a,t);if(i)return i}return null}var Vp=new Map;function Wp(a,e){if(!a)return;if(!e){console.warn("No prototype found",a,a.prototype,a.constructor);return}let t=Vp.get(e);t&&t.apply(a)}function qp(a){let e=Ty(a.prototype);Vp.set(a,e)}function Ty(a){return new ed(a)}var ed=class{$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++){let 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++){let i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}};import{Object3D as lt}from"three";var td=D("debuggetcomponent");function Ry(a){return a==null||a.isObject3D?a:a.object&&a.object.isObject3D?a.object:a}function Ua(a,e){if(!a||!a.userData.components)return;let t=a.userData.components.indexOf(e);t<0||(e.gameObject=null,a.userData.components.splice(t,1))}function Ga(a,e){let t=Br(a,e);if(t)return t;let i=new e;return Gn(a,i)}function Gn(a,e,t=!0){a||new Error("Can not add componet to null object"),a.userData||(a.userData={}),a.userData.components||(a.userData.components=[]),a.userData.components.push(e),e.gameObject=a,No(a),Va(e);try{e.__internalAwake&&t&&(Ms(a),e.__internalAwake())}catch(i){console.error(i)}return e}function Qp(a,e){if(e.gameObject!==a){if(e.gameObject&&e.gameObject.userData.components){let t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}if(!a.userData.components)a.userData.components=[];else if(a.userData.components.includes(e))return;a.userData.components.push(e),e.gameObject=a}}function Yp(a){if(a.gameObject&&a.gameObject.userData.components){let e=a.gameObject.userData.components.indexOf(a);a.gameObject.userData.components.splice(e,1)}a.__internalDisable&&a.__internalDisable(),a.onDestroy&&a.onDestroy(),hn(a,a.context??K.Current),a.__internalDestroy(),a.gameObject=null}var Xp=!1;function Kp(a,e,t){if(a!=null){if(!a.isObject3D){console.error("Object is not object3D");return}if(!a?.userData?.components)return null;if(typeof e=="string"&&(Xp||(Xp=!0,console.warn(`Accessing components by name is not supported.
144
+ }`});var Uy=Symbol("object"),Hs=class{localPoint;distance;normal;constructor(e,t,n){this.localPoint=e,this.distance=t,this.normal=n}},Xo=class{contacts;constructor(e,t,n){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=n}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}};function rr(o,e){try{e?o(e):o()}catch(t){return console.error(t),!1}return!0}var sn="__isActiveInHierarchy",or="builtin_components";var Tf=I("debugnewscripts"),le=[];function zn(o){if(!(o.new_scripts.length<=0)){if(Tf&&console.log("Register new components",o.new_scripts.length,o.alias?"element: "+o.alias:""),o.new_scripts_pre_setup_callbacks.length>0){for(let e of o.new_scripts_pre_setup_callbacks)!e||e();o.new_scripts_pre_setup_callbacks.length=0}le.length=0,o.new_scripts.length>0&&le.push(...o.new_scripts),o.new_scripts.length=0;for(let e=0;e<le.length;e++)try{let t=le[e];if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),le.splice(e,1),e--;continue}t.context=o,Qo(t.gameObject),Dl(t,o)}catch(t){console.error(t),Wn(le[e],o),le.splice(e,1),e--}for(let e=0;e<le.length;e++)try{let t=le[e];if(t.destroyed){Wn(le[e],o),le.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),Qo(t.gameObject),t.activeAndEnabled&&rr(t.__internalAwake.bind(t)))}catch(t){console.error(t),Wn(le[e],o),le.splice(e,1),e--}for(let e=0;e<le.length;e++)try{let t=le[e];if(t.destroyed||t.enabled===!1||(Qo(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,rr(t.__internalEnable.bind(t)))}catch(t){console.error(t),Wn(le[e],o),le.splice(e,1),e--}for(let e=0;e<le.length;e++)try{let t=le[e];if(t.destroyed||!t.gameObject)continue;o.new_script_start.push(t)}catch(t){console.error(t),Wn(le[e],o),le.splice(e,1),e--}le.length=0;for(let e of o.new_scripts_post_setup_callbacks)e&&e();o.new_scripts_post_setup_callbacks.length=0}}function Eu(o){!o||(o.__internalDisable(),Wn(o,o.context))}function Fs(o,e){for(let t=0;t<o.new_script_start.length;t++)try{let n=o.new_script_start[t];if(e!==void 0&&n.gameObject!==e||n.destroyed||n.activeAndEnabled===!1)continue;rr(n.__internalAwake.bind(n)),rr(n.__internalEnable.bind(n)),rr(n.__internalStart.bind(n)),o.new_script_start.splice(t,1),t--}catch(n){console.error(n),Wn(o.new_script_start[t],o),o.new_script_start.splice(t,1),t--}}function Dl(o,e){e.scripts.indexOf(o)===-1&&(e.scripts.push(o),o.earlyUpdate&&e.scripts_earlyUpdate.push(o),o.update&&e.scripts_update.push(o),o.lateUpdate&&e.scripts_lateUpdate.push(o),o.onBeforeRender&&e.scripts_onBeforeRender.push(o),o.onAfterRender&&e.scripts_onAfterRender.push(o))}function Wn(o,e){Ei(o,e.new_scripts),Ei(o,e.new_script_start),Ei(o,e.scripts),Ei(o,e.scripts_earlyUpdate),Ei(o,e.scripts_update),Ei(o,e.scripts_lateUpdate),Ei(o,e.scripts_onBeforeRender),Ei(o,e.scripts_onAfterRender),e.stopAllCoroutinesFrom(o)}function Ei(o,e){let t=e.indexOf(o);t>=0&&e.splice(t,1)}var Rf={},Ml={};function Jr(o){if(o||(o=V.Current.scene),!o){console.trace("Invalid call - no current context.");return}wu(o,sr(o),!0)}function wu(o,e,t){let n=!1,i=sr(o);if(Rf[o.uuid]=i,e&&(e=sr(o)),o[sn]=e,!n){let r=Ml[o.uuid];r!==void 0&&r!==e&&t&&Sf(o,s=>{e?(rr(s.__internalAwake.bind(s)),s.enabled=!0):s.enabled=!1})}if(Ml[o.uuid]=e,o.children)for(let r of o.children)wu(r,e,t)}function Qo(o){let e=!0,t=o,n=!1;for(;t&&t;){if(t.type==="Scene"&&(n=!0),!sr(t)){e=!1;break}t=t.parent}if(!o){console.error("GO is null");return}Ml[o.uuid]=e,o[sn]=e&&n}function Sf(o,e){if(o.userData?.components)for(let t of o.userData.components)e(t)}import*as qo from"three";var Cu=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Pf(o){return typeof o=="string"&&Cu.test(o)}var Tu=Pf;var Oe=[];for(let o=0;o<256;++o)Oe.push((o+256).toString(16).slice(1));function Ru(o,e=0){return(Oe[o[e+0]]+Oe[o[e+1]]+Oe[o[e+2]]+Oe[o[e+3]]+"-"+Oe[o[e+4]]+Oe[o[e+5]]+"-"+Oe[o[e+6]]+Oe[o[e+7]]+"-"+Oe[o[e+8]]+Oe[o[e+9]]+"-"+Oe[o[e+10]]+Oe[o[e+11]]+Oe[o[e+12]]+Oe[o[e+13]]+Oe[o[e+14]]+Oe[o[e+15]]).toLowerCase()}function Of(o){if(!Tu(o))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(o.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(o.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(o.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(o.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(o.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var Su=Of;function kf(o){o=unescape(encodeURIComponent(o));let e=[];for(let t=0;t<o.length;++t)e.push(o.charCodeAt(t));return e}var If="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Mf="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Al(o,e,t){function n(i,r,s,a){var c;if(typeof i=="string"&&(i=kf(i)),typeof r=="string"&&(r=Su(r)),((c=r)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let d=new Uint8Array(16+i.length);if(d.set(r),d.set(i,r.length),d=t(d),d[6]=d[6]&15|e,d[8]=d[8]&63|128,s){a=a||0;for(let l=0;l<16;++l)s[a+l]=d[l];return s}return Ru(d)}try{n.name=o}catch{}return n.DNS=If,n.URL=Mf,n}function Df(o,e,t,n){switch(o){case 0:return e&t^~e&n;case 1:return e^t^n;case 2:return e&t^e&n^t&n;case 3:return e^t^n}}function Ll(o,e){return o<<e|o>>>32-e}function Af(o){let e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof o=="string"){let s=unescape(encodeURIComponent(o));o=[];for(let a=0;a<s.length;++a)o.push(s.charCodeAt(a))}else Array.isArray(o)||(o=Array.prototype.slice.call(o));o.push(128);let n=o.length/4+2,i=Math.ceil(n/16),r=new Array(i);for(let s=0;s<i;++s){let a=new Uint32Array(16);for(let c=0;c<16;++c)a[c]=o[s*64+c*4]<<24|o[s*64+c*4+1]<<16|o[s*64+c*4+2]<<8|o[s*64+c*4+3];r[s]=a}r[i-1][14]=(o.length-1)*8/Math.pow(2,32),r[i-1][14]=Math.floor(r[i-1][14]),r[i-1][15]=(o.length-1)*8&4294967295;for(let s=0;s<i;++s){let a=new Uint32Array(80);for(let b=0;b<16;++b)a[b]=r[s][b];for(let b=16;b<80;++b)a[b]=Ll(a[b-3]^a[b-8]^a[b-14]^a[b-16],1);let c=t[0],d=t[1],l=t[2],u=t[3],h=t[4];for(let b=0;b<80;++b){let _=Math.floor(b/20),v=Ll(c,5)+Df(_,d,l,u)+h+e[_]+a[b]>>>0;h=u,u=l,l=Ll(d,30)>>>0,d=c,c=v}t[0]=t[0]+c>>>0,t[1]=t[1]+d>>>0,t[2]=t[2]+l>>>0,t[3]=t[3]+u>>>0,t[4]=t[4]+h>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}var Pu=Af;var Lf=Al("v5",80,Pu),jl=Lf;var Bs=I("debugcomponents"),jf="eff8ba80-635d-11ec-90d6-0242ac120003",ke=class{get seed(){return this._seed}_originalSeed;_seed;constructor(e){this._originalSeed=e,this._seed=e}generateUUID(){let e=this._seed;return this._seed-=1,jl(e.toString(),jf)}static createFromString(e){return new ke(this.hash(e))}static hash(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return t}};var Us=class{guid;constructor(e){this.guid=e}};function Zr(o,e,t=!0){if(!o)return;let n=o;if(At(o,t),!e){console.warn("Can not send destroy: No networking connection provided",o.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",o.guid);return}let i=o.guid;if(!i&&n.uuid&&(i=n.uuid),!i){console.warn("Can not send destroy: failed to find guid",o);return}let r=new Us(i);e.send("instance-destroyed",r,2)}function Ou(o,e){let t=new Us(o);e.send("instance-destroyed",t,2)}function ku(o){o.connection.beginListen("instance-destroyed",e=>{Bs&&console.log("[Remote] Destroyed",o.scene,e);let t=ar(e.guid,o.scene);t&&At(t)})}var Hl=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function Gs(o,e,t,n){let i=o;if(!i.guid)return console.warn("Can not instantiate: No guid",i),null;if(e.context||(e.context=V.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;let r=e?{...e}:null,{instance:s,seed:a}=Hf(i,e);if(s){let c=s;if(c.guid){Bs&&console.log("[Local] new instance","gameobject:",s?.guid);let d=new Hl(i.guid,c.guid);d.seed=a,r&&(r.position&&(d.position={x:r.position.x,y:r.position.y,z:r.position.z}),r.rotation&&(d.rotation={x:r.rotation.x,y:r.rotation.y,z:r.rotation.z,w:r.rotation.w}),r.scale&&(d.scale={x:r.scale.x,y:r.scale.y,z:r.scale.z})),d.position||(d.position={x:c.position.x,y:c.position.y,z:c.position.z}),d.rotation||(d.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),d.scale||(d.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),d.visible=i.visible,r?.parent&&(typeof r.parent=="string"?d.parent=r.parent:d.parent=r.parent.guid),d.hostData=t,n===!1&&(d.dontSave=!0),e?.context?.connection.send("new-instance-created",d)}else console.warn("Missing guid, can not send new instance event",c)}return s}function Vs(){return Math.random()*9999999}function Iu(o){o.connection.beginListen("new-instance-created",async e=>{let t=await Ff(e.originalGuid,o.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let n=new Ie;e.position&&(n.position=new qo.Vector3(e.position.x,e.position.y,e.position.z)),e.rotation&&(n.rotation=new qo.Quaternion(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(n.scale=new qo.Vector3(e.scale.x,e.scale.y,e.scale.z)),n.parent=e.parent,e.seed&&(n.idProvider=new ke(e.seed)),n.visible=e.visible,n.context=o,Bs&&o.alias&&console.log("[Remote] instantiate in: "+o.alias);let i=lr(t,n);i&&(e.parent==="scene"&&o.scene.add(i),Bs&&console.log("[Remote] new instance","gameobject:",i?.guid,t))})}function Hf(o,e){let t=Vs(),n=e??new Ie;n.idProvider=new ke(t);let i=lr(o,n);return{seed:t,instance:i}}var Mu={};function Du(o,e){Mu[o]=e}async function Ff(o,e){let t=Mu[o];if(t!=null){let n=await t(o);if(n)return n}return Au(o,e)}function Au(o,e){if(e===null||!o)return null;if(e.guid===o)return e;if(e.children)for(let t of e.children){let n=Au(o,t);if(n)return n}return null}var Lu=new Map;function ju(o,e){if(!o)return;if(!e){console.warn("No prototype found",o,o.prototype,o.constructor);return}let t=Lu.get(e);t&&t.apply(o)}function Hu(o){let e=Bf(o.prototype);Lu.set(o,e)}function Bf(o){return new Bl(o)}var Bl=class{$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++){let n=this.extensions[t],i=Object.getOwnPropertyDescriptor(e,n);i&&this.descriptors.push(i)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){let n=this.extensions[t],i=this.descriptors[t];i&&Object.defineProperty(e,n,i)}}}};import{Object3D as Qe}from"three";var Ul=I("debuggetcomponent");function Uf(o){return o==null||o.isObject3D?o:o.object&&o.object.isObject3D?o.object:o}function Ns(o,e){if(!o||!o.userData.components)return;let t=o.userData.components.indexOf(e);t<0||(e.gameObject=null,o.userData.components.splice(t,1))}function Ws(o,e){let t=cr(o,e);if(t)return t;let n=new e;return wi(o,n)}function wi(o,e,t=!0){o||new Error("Can not add componet to null object"),o.userData||(o.userData={}),o.userData.components||(o.userData.components=[]),o.userData.components.push(e),e.gameObject=o,no(o),zs(e);try{e.__internalAwake&&t&&(Qo(o),e.__internalAwake())}catch(n){console.error(n)}return e}function Bu(o,e){if(e.gameObject!==o){if(e.gameObject&&e.gameObject.userData.components){let t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}if(!o.userData.components)o.userData.components=[];else if(o.userData.components.includes(e))return;o.userData.components.push(e),e.gameObject=o}}function Uu(o){if(o.gameObject&&o.gameObject.userData.components){let e=o.gameObject.userData.components.indexOf(o);o.gameObject.userData.components.splice(e,1)}o.__internalDisable&&o.__internalDisable(),o.onDestroy&&o.onDestroy(),Wn(o,o.context??V.Current),o.__internalDestroy(),o.gameObject=null}var Fu=!1;function Gu(o,e,t){if(o!=null){if(!o.isObject3D){console.error("Object is not object3D");return}if(!o?.userData?.components)return null;if(typeof e=="string"&&(Fu||(Fu=!0,console.warn(`Accessing components by name is not supported.
145
145
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
146
146
 
147
147
  You can import other modules your main module to get access to types
148
148
  or if you use npmdefs you can make types available globally using globalThis:
149
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`))),td&&console.log("FIND",e),e!=null){for(let i=0;i<a.userData.components.length;i++){let n=a.userData.components[i];if(e===null||n.constructor.name===e.name||n.constructor.name===e)if(td&&console.log("MATCH BY NAME",n),t)t.push(n);else return n}for(let i=0;i<a.userData.components.length;i++){let n=a.userData.components[i],r=Object.getPrototypeOf(n.constructor);do{if(r===e)if(td&&console.log("MATCH BY PROTOYPE",r),t)t.push(n);else return n;r=Object.getPrototypeOf(r)}while(r)}return t}}}function Br(a,e){return Kp(a,e)}function Ho(a,e,t){return t||(t=[]),Kp(a,e,t)}function pn(a,e,t){let i=Br(a,e);if(t===!1&&i.enabled===!1)return null;if(i)return i;for(let n=0;n<a?.children?.length;n++){let r=pn(a.children[n],e);if(r)return r}return null}function Fo(a,e,t){t||(t=[]),Ho(a,e,t);for(let i=0;i<a?.children?.length;i++)Fo(a.children[i],e,t);return t}function Bo(a,e){if(!a)return null;if(Array.isArray(a)){for(let i=0;i<a.length;i++){let n=Ry(a[i]),r=Bo(n,e);if(r)return r}return null}let t=Br(a,e);return t||(a.parent?Bo(a.parent,e):null)}function Ds(a,e,t){return t||(t=[]),a?(Ho(a,e,t),a.parent?Ds(a.parent,e,t):t):t}function Jp(a,e,t){if(!a)return null;if(!e&&(e=K.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e;if(i.isScene||(i=e?.scene),!i)return null;for(let n in i.children){let r=i.children[n];if(t===!1&&r[Ri]===!1)continue;if(r.constructor==a)return r;let o=pn(r,a);if(o)return o}return null}function Zp(a,e,t){if(!a)return e;if(!t&&(t=K.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;let i=t.isScene===!0||t.isObject3D===!0?t:t?.scene;if(!i)return e;for(let n in i.children){let r=i.children[n];if(r.constructor==a)return r;Fo(r,a,e)}return e}function No(a){a&&a.isObject3D===!0&&Wp(a,lt)}lt.prototype.SetActive=function(a){this.visible=a};lt.prototype.addNewComponent=function(a){return Gn(this,new a)};lt.prototype.removeComponent=function(a){return Ua(this,a)};lt.prototype.getOrAddComponent=function(a){return Ga(this,a)};lt.prototype.getComponent=function(a){return Br(this,a)};lt.prototype.getComponents=function(a,e){return Ho(this,a,e)};lt.prototype.getComponentInChildren=function(a){return pn(this,a)};lt.prototype.getComponentsInChildren=function(a,e){return Fo(this,a,e)};lt.prototype.getComponentInParent=function(a){return Bo(this,a)};lt.prototype.getComponentsInParent=function(a,e){return Ds(this,a,e)};Object.getOwnPropertyDescriptor(lt.prototype,"activeSelf")||Object.defineProperty(lt.prototype,"activeSelf",{get:function(){return this.visible},set:function(a){let e=typeof a=="number"?a>.5:a;this.visible=e}});qp(lt);var Hr=D("debuggetcomponent"),Sy=(d=>(d[d.None=0]="None",d[d.HideInHierarchy=1]="HideInHierarchy",d[d.HideInInspector=2]="HideInInspector",d[d.DontSaveInEditor=4]="DontSaveInEditor",d[d.NotEditable=8]="NotEditable",d[d.DontSaveInBuild=16]="DontSaveInBuild",d[d.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",d[d.DontSave=52]="DontSave",d[d.HideAndDontSave=61]="HideAndDontSave",d))(Sy||{}),Ge=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context},Wa=Symbol("isActive");function Lr(a){let e=a.visible||Xa(a);return a[Wa]===void 0&&(a[Wa]=e),a[Wa]&&e}function qa(a,e,t=!0){a[Wa]=e,t&&(a.visible=e)}function ef(a){return a[Ri]||Xa(a)}function tf(a,e){a.__isUsingInstancing=e}function Xa(a){return re.isUsingInstancing(a)}function Dr(a,e){return Bn(a,e,!0,!0)}function ei(a,e=!0,t=!0){let i=a;if(i.isComponent){i.__internalDisable(),i.__internalDestroy();return}let n=a;if(Hr&&console.log(n),e&&n.children)for(let o of n.children)ei(o,e,!1);let r=n.userData.components;if(r){let o=r.length;for(let s=0;s<r.length;s++){let c=r[s];c.__internalDisable(),c.__internalDestroy(),r.length<o&&(o=r.length,s--)}}t&&n.removeFromParent()}function Ht(a,e,t=!0){if(!!a){if(a.isObject3D||new Error("Expected Object3D but got "+a),a.userData?.components)for(let i=0;i<a.userData.components.length;i++){let n=a.userData.components[i];if(n?.isComponent===!0){let r=e(n);if(r!==void 0)return r}}if(t&&a.children)for(let i=0;i<a.children.length;i++){let n=a.children[i];if(!n)continue;let r=Ht(n,e,t);if(r!==void 0)return r}}}function jr(a,e=null){if(a===null)return null;let t=null;e!==null&&(e.x!==void 0?(t=new Ge,t.position=e):t=e);let i=K.Current;t?.context&&(i=t.context),Hr&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new Ue(Date.now()));let n=[],r={},o={},s=nf(i,a,t,n,r,o);s&&(Oy(r),Py(o,r)),Hr&&(ks(a,!0),ks(s,!0));let c={};for(let d in n){let l=n[d],h=l.guid;t&&t.idProvider&&(l.guid=t.idProvider.generateUUID(),c[h]=l.guid,Hr&&console.log(l.name,l.guid)),Va(l,i),l.__internalNewInstanceCreated&&l.__internalNewInstanceCreated()}for(let d in n){let l=n[d];l.resolveGuids&&l.resolveGuids(c),l.enabled!==!1&&(l.enabled=!0)}return un(i),s}function nf(a,e,t,i,n,r){if(!e)return null;let o=e.userData;e.userData={};let s=e.children;e.children=[];let c;if(c=e.clone(!1),No(c),e.userData=o,e.children=s,n[e.uuid]={original:e,clone:c},e.type==="SkinnedMesh"&&(r[e.uuid]={original:e,clone:c}),t?.visible!==void 0&&(c.visible=t.visible),t?.idProvider){c.uuid=t.idProvider.generateUUID();let l=c;l&&(l.guid=c.uuid)}e.animations&&e.animations.length>0&&(c.animations=[...e.animations]);let d=e.parent;if(d&&d.add(c),t?.position?se(c,t.position):c.position.copy(e.position),t?.rotation?$e(c,t.rotation):c.quaternion.copy(e.quaternion),t?.scale?c.scale.copy(t.scale):c.scale.copy(e.scale),t?.parent&&t.parent!=="scene"){let l=null;if(typeof t.parent=="string"?l=Bn(t.parent,a.scene,!0):l=t.parent,l){let h=t.keepWorldPosition===!0?l.attach:l.add;h?h.call(l,c):console.error("Invalid parent object",l,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(let[l,h]of Object.entries(e.userData))l!=="components"&&(c.userData[l]=h);if(e.userData?.components){let l=e.userData.components,h=[];c.userData.components=h;for(let u=0;u<l.length;u++){let f=l[u],x=Object.create(f);Object.assign(x,f),h.push(x),x.gameObject=c,i.push(x)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(let l in e.children){let h=e.children[l],u=nf(a,h,t,i,n,r);u&&c.add(u)}return c}function Py(a,e){for(let t in a){let i=a[t],n=i.original,r=n.skeleton,o=i.clone;if(!r){console.warn("Skinned mesh has no skeleton?",i);continue}let s=r.bones,c=o.skeleton.clone();o.skeleton=c,o.bindMatrix.clone().copy(n.bindMatrix),o.bindMatrixInverse.copy(n.bindMatrixInverse);let d=[];c.bones=d;for(let l=0;l<s.length;l++){let h=s[l],f=e[h.uuid].clone;d.push(f)}}for(let t in a){let i=a[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function Oy(a){for(let e in a){let i=a[e].clone;if(i.userData?.components)for(let n=0;n<i.userData.components.length;n++){let r=i.userData.components[n],o=Object.entries(r);for(let[s,c]of o)if(Array.isArray(c)){let d=[];r[s]=d;for(let l=0;l<c.length;l++){let h=c[l];if(typeof h!="object"){d.push(h);continue}let u=$p(r,s,h,a);u!==void 0?d.push(u):d.push(h)}}else if(typeof c=="object"){let d=$p(r,s,c,a);d!==void 0&&(r[s]=d)}}}}function $p(a,e,t,i){if(t!=null){if(t.isComponent===!0){let n=t.gameObject;if(n){let r=n.uuid,o=i[r]?.clone;if(!o){Hr&&console.log("reference did not change",e,a,t);return}let s=n.userData.components.indexOf(t);if(s>=0)return Hr&&console.log(e,r),o.userData.components[s];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;let n=t;if(n){let r=n.uuid,o=i[r]?.clone;if(o)return Hr&&console.log(e,"old",t,"new",o),o}}}}var js=D("debugphysics"),Ly=D("debugcollisions"),Qa=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},Bs=class{obj;parent;body;shapes=[];collisonCallback=null;_hasRigidbody=!1;_didSleepLastStep=!1;constructor(e,t){this.obj=e,this.parent=e.parent,this.body=t,this.body&&(this.body[As]=e)}},Te=class{ray=void 0;cam=void 0;screenPoint=void 0;raycaster=void 0;results=void 0;targets=void 0;recursive=!0;minDistance=void 0;maxDistance=void 0;lineThreshold=void 0;layerMask=void 0;ignore=void 0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new My),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new nd);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};U(Te,"AllLayers",4294967295);var rd=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},Ya=class{raycaster=new ky;defaultRaycastOptions=new Te;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new nd;sphereOverlap(e,t,i=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let n=new Ay(e,t),r=this.sphereMask;r.enableAll(),r.disable(2);for(let o of this.context.scene.children)this.onSphereOverlap(o,n,r,this.sphereResults,i);return this.sphereResults.sort((o,s)=>o.distance-s.distance)}tempBoundingBox=new Iy;onSphereOverlap(e,t,i,n,r){if(e.type==="Mesh"&&e.layers.test(i)){let o=e,s=o.geometry;if(s.boundingBox||s.computeBoundingBox(),s.boundingBox){o.matrixWorldNeedsUpdate&&o.updateMatrixWorld();let c=this.tempBoundingBox.copy(s.boundingBox).applyMatrix4(o.matrixWorld);if(t.intersectsBox(c)){let l=X(e).distanceTo(t.center),h=new rd(e,l,t.center.clone());if(n.push(h),!r)return}}}if(e.children)for(let o of e.children){let s=n.length;if(this.onSphereOverlap(o,t,i,n,r),s!=n.length&&!r)return}}raycastFromRay(e,t=null){let i=t??this.defaultRaycastOptions;return i.ray=e,this.raycast(i)}raycast(e=null){e||(e=this.defaultRaycastOptions);let 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?i.params.Line={threshold:e.lineThreshold}:i.params.Line={threshold:0},e.ray)i.ray.copy(e.ray);else{let s=e.cam??this.context.mainCamera;if(!s)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];i.setFromCamera(t,s)}let n=e.targets;n||(n=this.targetBuffer,n[0]=this.context.scene);let r=e.results;r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof nd?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),r.length=0,i.intersectObjects(n,e.recursive,r);let o=e.ignore;return o!==void 0&&o.length>0&&(r=r.filter(s=>!o.includes(s.object))),r}get isUpdating(){return this._isUpdatingPhysicsWorld}_isUpdatingPhysicsWorld=!1;context;world=new Aa;objects=[];tempPosition=new of;tempQuaternion=new id;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),js){let t={};t.onInit=(i,n,r)=>{n.layers.set(-1)},Tp(e.scene,this.world.bodies,t)}this.world.addEventListener("beginContact",this.onBeginContact.bind(this)),this.world.addEventListener("endContact",this.onEndContact.bind(this))}addPreStepListener(e){this.world.addEventListener("preStep",e)}addPostStepListener(e){this.world.addEventListener("postStep",e)}addConstraint(e){this.world.addConstraint(e)}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}multiplyGravity(e){this.world.gravity.x*=e.x,this.world.gravity.y*=e.y,this.world.gravity.z*=e.z}addBody(e,t){for(let i=0;i<this.objects.length;i++){let n=this.objects[i];if(n.obj===e){n._hasRigidbody=!0;break}}t.shapes.length>0&&this.world.addBody(t)}removeBody(e,t,i=!0){this.world.removeBody(t);for(let n=0;n<this.objects.length;n++){let r=this.objects[n];if(r.obj===e){r._hasRigidbody=!1,i&&this.objects.splice(n,1);break}}}removeShape(e,t){for(let i of this.objects)if(i.obj===e){i.body&&(i.body.removeShape(t),i.body.updateMassProperties());return}}createBody(e,t){let i=this.internalCreateBody(e,null);t.mass&&(i.mass=t.mass),t.kinematic?i.type=G.KINEMATIC:i.type=G.DYNAMIC,t.drag&&(i.linearDamping=t.drag),t.angularDrag&&(i.angularDamping=t.angularDrag),t.sleepThreshold&&(i.sleepSpeedLimit=t.sleepThreshold),i.shapes.length>0&&this.world.addBody(i);let n=new Bs(e,i);return n._hasRigidbody=!0,this.objects.push(n),js&&console.log("created new body",e.name,i,i.sleepState,this.world.gravity),t.physicsEvents&&this.registerCollisionEvents(n),i}addBoxCollider(e,t,i,n,r){let o=this.tempPosition;e.getWorldScale(o);let s=new _(.5*o.x*n.x,.5*o.y*n.y,.5*o.z*n.z),c=new Or(s);c.collisionResponse=!t,i=i.clone(),i.multiply(o);let d=this.addShape(e,c,i,r);if(d!==null){if(this.world.addBody(d),this.isAlreadyRegistered(d))return c;let l=new Bs(e,d);this.objects.push(l)}return c}addSphereCollider(e,t,i,n){let r=this.tempPosition;e.getWorldScale(r);let o=Math.max(r.x,r.y,r.z),s=new Ia(i*o);t=t.clone(),t.multiply(r);let c=this.addShape(e,s,t,n);if(c!==null){if(this.world.addBody(c),this.isAlreadyRegistered(c))return s;let d=new Bs(e,c);this.objects.push(d)}return s}addMeshCollider(e){js&&console.warn("TODO mesh collider not yet supported")}isAlreadyRegistered(e){for(let t of this.objects)if(t.body===e)return!0;return!1}tempMat1=new rf;tempMat2=new rf;addShape(e,t,i,n){let r=null;if(n?(n.initialize(),console.assert(!!n.body,"rigidbody didn't initialize / produce a physics body",n),r=n.body):(r=this.internalCreateBody(e,null),r.type=G.KINEMATIC),r){i.x*=-1;let o=e.position,s=e.quaternion;if(n&&n.gameObject!==e)this.tempMat1.copy(e.matrixWorld),this.tempMat2.copy(n.gameObject.matrixWorld).invert(),this.tempMat1.premultiply(this.tempMat2),this.tempMat1.decompose(o,s,this.tempPosition);else{o=X(e);let l=r.position;o.x-=l.x,o.y-=l.y,o.z-=l.z,s=Ie(e);let h=new id(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w);s.multiply(h.invert())}o.add(i);let c=new _(o.x,o.y,o.z),d=new ce(s.x,s.y,s.z,s.w);r.addShape(t,c,d),r.updateMassProperties(),this.world.addBody(r)}return r}step(e){this._isUpdatingPhysicsWorld=!0,e=Math.min(e,1/30),this.world.step(e),this._isUpdatingPhysicsWorld=!1,js&&this.context.time.frameCount%60}temp=new of;tempQuat=new id;postStep(){this._isUpdatingPhysicsWorld=!0;for(let e=0;e<this.objects.length;e++){let t=this.objects[e],i=t.body;if(!i||!i.world)continue;let n=t.obj;if(i.sleepTick(this.context.time.time),js&&(!t._didSleepLastStep&&i.sleepState===G.SLEEPING?console.log("BODY SLEEPING",i):t._didSleepLastStep&&i.sleepState!==G.SLEEPING&&console.log("BODY WOKE UP",i)),t._didSleepLastStep=i.sleepState===G.SLEEPING,i.type===G.KINEMATIC){let r=X(n,this.temp);i.position.set(r.x,r.y,r.z);let o=Ie(n,this.tempQuat);i.quaternion.set(o.x,o.y,o.z,o.w);continue}if(isNaN(i.position.x)||isNaN(i.position.y)||isNaN(i.position.z)){console.error("body position is NaN on",n.name,"this usually means some colliders are overlapping",i.previousPosition,n.position),this.world.removeBody(i);continue}if(t.parent&&n.parent===t.parent){Pp(n,i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w);let r=i.position;Mo(n,r.x,r.y,r.z),i.velocity.length()>i.sleepSpeedLimit&&re.markDirty(n)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let i=new G;i._owner=e,i._name=e.name,e.getWorldPosition(this.tempPosition);let n=this.tempPosition;i.position=new _(n.x,n.y,n.z);let r=this.tempQuaternion;return e.getWorldQuaternion(r),i.quaternion=new ce(r.x,r.y,r.z,r.w),i.type=G.KINEMATIC,t&&(i.addShape(t),i.updateMassProperties()),i}registerCollisionEvents(e){if(e.collisonCallback&&this.unregisterCollisionEvents(e),!e.body)return;let t=i=>this.raiseCollisionEvents(e.obj,i);e.collisonCallback=t.bind(this),e.body.addEventListener("collide",e.collisonCallback)}unregisterCollisionEvents(e){!e.collisonCallback||!e.body||e.body.removeEventListener("collide",e.collisonCallback)}onBeginContact(e){}collisionContext=new od;raiseCollisionEvents(e,t){let i=new Lo(e,t,this.collisionContext);if(Ly&&console.log("collision between",t.contact.bi,t.contact.bj,e,t),Ht(e,n=>{n.__internalHandleCollision(i,!1)}),i.collider&&!i.collider.attachedRigidbody&&i.collider.isTrigger){let n=new Lo(i.gameObject,t,this.collisionContext,!0);Ht(i.gameObject,r=>{r.__internalHandleCollision(n,!0)})}}onEndContact(e){let t=e.bodyA[As],i=e.bodyB[As];Ht(i,n=>{n.__internalHandleExitCollisionEvent(t,!1)}),Ht(t,n=>{let r=n;r.isCollider&&!r.attachedRigidbody&&r.isTrigger&&Ht(r.gameObject,o=>{o.__internalHandleExitCollisionEvent(i,!0)})})}},sf=null;function af(a){sf=a}var od=class{getCollider(e){return sf.getCollider(e)}};import{Clock as Dy}from"three";var Ka=class{deltaTime=0;time=0;frame=0;get realtimeSinceStartup(){return this.clock.elapsedTime}get frameCount(){return this.frame}get smoothedFps(){return this._smoothedFps}clock=new Dy;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<30?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%30]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedFps=1/(e/this._fpsSamples.length)}};import{WebsocketBuilder as By}from"websocket-ts";var Si=new Int32Array(2),Ja=new Float32Array(Si.buffer),Za=new Float64Array(Si.buffer),zo=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Xe=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?Xe.ZERO:new Xe(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Xe.ZERO=new Xe(0,0);var Hs;(function(a){a[a.UTF8_BYTES=1]="UTF8_BYTES",a[a.UTF16_STRING=2]="UTF16_STRING"})(Hs||(Hs={}));var Pi=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new Pi(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new Xe(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Xe(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return Si[0]=this.readInt32(e),Ja[0]}readFloat64(e){return Si[zo?0:1]=this.readInt32(e),Si[zo?1:0]=this.readInt32(e+4),Za[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)}writeUint64(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)}writeFloat32(e,t){Ja[0]=t,this.writeInt32(e,Si[0])}writeFloat64(e,t){Za[0]=t,this.writeInt32(e,Si[zo?0:1]),this.writeInt32(e+4,Si[zo?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let i=e-this.readInt32(e);return t<this.readInt16(i)?this.readInt16(i+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let i=this.readInt32(e),n="",r=0;if(e+=4,t===Hs.UTF8_BYTES)return this.bytes_.subarray(e,e+i);for(;r<i;){let o,s=this.readUint8(e+r++);if(s<192)o=s;else{let c=this.readUint8(e+r++);if(s<224)o=(s&31)<<6|c&63;else{let d=this.readUint8(e+r++);if(s<240)o=(s&15)<<12|(c&63)<<6|d&63;else{let l=this.readUint8(e+r++);o=(s&7)<<18|(c&63)<<12|(d&63)<<6|l&63}}}o<65536?n+=String.fromCharCode(o):(o-=65536,n+=String.fromCharCode((o>>10)+55296,(o&(1<<10)-1)+56320))}return n}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return Xe.create(e,t)}createScalarList(e,t){let i=[];for(let n=0;n<t;++n)e(n)!==null&&i.push(e(n));return i}createObjList(e,t){let i=[];for(let n=0;n<t;++n){let r=e(n);r!==null&&i.push(r.unpack())}return i}};var yt=class{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=Pi.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);let i=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<i+e+t;){let n=this.bb.capacity();this.bb=yt.growByteBuffer(this.bb),this.space+=this.bb.capacity()-n}this.pad(i)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,i){(this.force_defaults||t!=i)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,i){(this.force_defaults||t!=i)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,i){(this.force_defaults||t!=i)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,i){(this.force_defaults||!t.equals(i))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,i){(this.force_defaults||t!=i)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,i){(this.force_defaults||t!=i)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,i){t!=i&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let i=t<<1,n=Pi.allocate(i);return n.setPosition(i-t),n.bytes().set(e.bytes(),i-t),n}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let i=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let n=2;this.addInt16(e-this.object_start);let r=(i+n)*2;this.addInt16(r);let o=0,s=this.space;e:for(t=0;t<this.vtables.length;t++){let c=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(c)){for(let d=2;d<r;d+=2)if(this.bb.readInt16(s+d)!=this.bb.readInt16(c+d))continue e;o=this.vtables[t];break}}return o?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,o-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,i){let n=i?4:0;if(t){let r=t;if(this.prep(this.minalign,4+4+n),r.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let o=4-1;o>=0;o--)this.writeInt8(r.charCodeAt(o))}this.prep(this.minalign,4+n),this.addOffset(e),n&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let i=this.bb.capacity()-e,n=i-this.bb.readInt32(i);if(!(this.bb.readInt16(n+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,i){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(i,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let i=0;for(;i<e.length;){let n,r=e.charCodeAt(i++);if(r<55296||r>=56320)n=r;else{let o=e.charCodeAt(i++);n=(r<<10)+o+(65536-(55296<<10)-56320)}n<128?t.push(n):(n<2048?t.push(n>>6&31|192):(n<65536?t.push(n>>12&15|224):t.push(n>>18&7|240,n>>12&63|128),t.push(n>>6&63|128)),t.push(n&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let i=0,n=this.space,r=this.bb.bytes();i<t.length;i++)r[n++]=t[i];return this.endVector()}createLong(e,t){return Xe.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let i=0;i<e.length;++i){let n=e[i];if(n!==null)t.push(this.createObjectOffset(n));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}};var lf={};function Go(a,e){lf[a]=e}function cf(a){let e=a.getBufferIdentifier(),t=lf[e];return t(a)}function df(a){return typeof a.guid=="function"?a.guid():null}var ad=ca(el(),1);var tl=class{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){let e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}trySetupHost(e){let t=new ad.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new cd(t)})}trySetupClient(e){this._client=new ad.default,this._client.on("error",t=>{console.error("Client error",t)}),this._client.on("open",t=>{console.log("client connected",t),this._clientData=this._client.connect(e,{metadata:{id:t}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",i=>{console.log("<<",i)})})}},ld=class{_peer;constructor(e){this._peer=e}};var cd=class extends ld{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){let t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let i=this._peer.connections[t];if(!!i)if(Array.isArray(i))for(let n of i)!n||n.send(e);else console.warn(i)}}}};var il="wss://needle-tiny-starter.glitch.me/socket",xt=!!D("debugnet"),nl=!!(xt||D("debugowner"));var Wn=class{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(nl&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0,n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return nl&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListening("gained-ownership",this._gainSubscription),this.connection.stopListening("lost-ownership",this._lostSubscription),this.connection.stopListening("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(nl&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(nl&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}},rl=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new tl),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return xt}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(let t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){this.connect(),xt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},0)}leaveRoom(e=null){if(e||(e=this.currentRoomName),!e){console.error("Can not leave unknown room");return}this.send("leave-room",{room:e})}send(e,t=null,i=2){if(t===null&&(t={}),i===2){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]}sendBinary(e){xt&&console.log("<< bin",e.length),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;let e=Object.keys(this._defaultMessagesBuffer).length;for(let i in this._defaultMessagesBuffer){let n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,3);break}let r=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(r)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&xt&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}connect(){if(this.connected)return;xt&&console.log("connecting");let e=this.netWebSocketUrlProvider?.getWebsocketUrl();e?il=e:Cu()&&(il="wss://"+window.location.host+"/socket"),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+il);let e=new By(il).onOpen(()=>{this._ws=e,this._isConnectingToWebsocket=!1,this.connected=!0,console.log("Connected to websocket"),this.onSendQueued(0)}).onClose(t=>{this.connected=!1,this._isInRoom=!1}).onError((t,i)=>{console.error(t,i)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}let n=JSON.parse(i);if(Array.isArray(n))for(let r of n)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(n);return}catch{xt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new Pi(i),r=n.getBufferIdentifier(),o=this._listenersBinary[r],s=cf(n),c=df(s);if(c&&typeof c=="string"&&(this._state[c]=s),!o)return;let d=s??n;for(let l of o)l(d)}handleIncomingStringMessage(e){if(xt&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let o=e.data;o&&(console.assert(o.id!==void 0&&o.id!==null&&o.id.length>0,"server did not send connection id",o.id),console.log("Your id is: "+o.id,this.context.alias??""),this._connectionId=o.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(xt&&console.log(e),e){this._isInRoom=!0;let o=e;this._currentRoomName=o.room,this._currentRoomViewId=o.viewId,this._currentRoomAllowEditing=o.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...o.inRoom),xt&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let o=e.data;this._currentInRoom.push(o.userId),xt&&console.log(o.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let o=e.data,s=this._currentInRoom.indexOf(o.userId);s>=0&&(console.log(o.userId+" left",this.context.alias??""),this._currentInRoom.splice(s,1)),o.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),xt&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+this._currentInRoom?.length);break}let t=this._listeners[e.key];if(t)for(let n of t)n(e.data);let i=e.data;i&&(this._state[i.guid]=i)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=1){if(!this._ws){let r=this._waitingForSocket[i]||[];r.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=r;return}let n=JSON.stringify(this.toMessage(e,t));xt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let i of t)i();t.length=0}}};import{EffectComposer as lx}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as cx}from"three/examples/jsm/postprocessing/RenderPass";import*as qn from"three";var xf=ca(yf(),1),ol=class{success;filename;hash;size;url;constructor(e,t,i,n){this.success=e,this.filename=t,this.hash=i,this.size=n}};async function wf(a,e){let t=await a.arrayBuffer(),i=_f(t),n=a.name.split(".").pop(),r=i+"."+n,o=a.name.split(".").shift();console.assert(o!==void 0);let s={alias:o,filename:r},d=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(s)})).json();if(d.success||console.warn("exists check did fail"),d.exists)return console.log("file already exists",i),new ol(!0,r,i,a.size);console.log("begin uploading file",o,a.size);let l=new FormData;l.append("file",a);let h={};h.filesize=a.size,o&&(h.alias=o);let f=await(await fetch(e+"/upload/file",{method:"POST",body:l,headers:h})).json();if(f?.success===!1)return f.message!==void 0?console.error("Upload failed:",f.message):console.error("Upload failed"),null;console.assert(f.hash_sum===i,"hash sum did not match","received:",f.hash_sum,"expected:",i),f.success&&console.log("successfully uploaded",i,f.id);let x=new ol(f.success,r,i,a.size);return x.url=e,x}function _f(a){return(0,xf.default)(new Uint8Array(a))}async function sl(a,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:a});if(r.status!==200)return console.error("download failed",r),null;let o=await r.blob(),s=await o.arrayBuffer();n||console.assert(o.size===t,"size mismatch","expected:",t,"got:",o.size);let c=_f(s);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function Ef(a,e){let t=await fetch(a),i=t.body?.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let o=0,s=[];for(;;){let{done:l,value:h}=await i.read();if(h&&(s.push(h),o+=h.length,e.call(null,new ProgressEvent("progress",{loaded:o,total:r}))),l)break}let c=new Uint8Array(o),d=0;for(let l of s)c.set(l,d),d+=l.length;return c}function al(a,e,t){console.warn("Adding components on object has been temporarily disabled")}var Tf,Cf=null;function Qe(){return Tf}function ll(a){Cf!==a&&(Cf=a,Tf=new a)}var ud=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,i,n,r,o,s,c){this.seed=t,this.guid=i,this.file_name=n,this.file_hash=r,this.file_size=o,this.position=s,this.sender=e,this.serverUrl=c}};async function Rf(a,e,t){let i=a.name;return i.endsWith(".gltf")||i.endsWith(".glb")?new Promise((n,r)=>{let o=new FileReader;o.readAsDataURL(a),o.onloadend=async s=>{let c=o.result,d=za(),l=new Ue(d),h=await Qe().loadSync(e,c,l,!0);if(h&&h.scene){let u=h.scene;if(!u.guid){let f=new Ue(d);u.guid=f.generateUUID()}t&&zy(e.connection,a,d,u,t),al(u,l,h),n(h)}}}):(console.warn("Unsupported file type: "+i),console.log(a),null)}async function Sf(a,e){return new Promise(async(t,i)=>{let n=za(),r=new Ue(n),o=await Qe().loadSync(e,a.toString(),r,!0);if(o&&o.scene){let s=o.scene;al(s,r,o),t(o)}else console.warn("Unsupported file type: "+a.toString())})}function Pf(a){a.connection.beginListen("file-spawned",async e=>{if(e.sender!==a.connection.connectionId){console.log("received file event",e),Uy(e,a);let t=null;try{t=await sl(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{Gy(e,a)}if(t){let i=new Ue(e.seed),n=await Qe().parseSync(a,t,null,i);if(n&&n.scene){let r=n.scene;if(al(r,i,n),e.parentGuid){let o=Dr(e.parentGuid,a.scene);"add"in o&&o.add(r)}r.parent||a.scene.add(r),e.position!==null&&r.position.copy(e.position)}}else console.error("download didnt return file")}})}async function zy(a,e,t,i,n){if(!a.connectionId){console.error("Can not upload file - no connection id");return}if(!i.guid){console.error("Can not upload file - no guid",i,i.guid);return}let r=await wf(e,n);if(!r)return;if(!r.filename){console.error("Can not send upload event - no filename",e.name);return}if(!r.hash){console.error("Can not send upload event - no hash",e.name);return}let o=new ud(a.connectionId,t,i.guid,r.filename,r.hash,e.size,i.position,r.url??n);i.parent&&(o.parentGuid=i.parent.guid),a.send("file-spawned",o)}var pd={};function Uy(a,e){let t=new qn.BoxGeometry,i=new qn.Mesh(t,new qn.MeshBasicMaterial({color:65280})),n=new qn.BoxHelper(i,5592405);if(pd[a.guid]=n,e.scene.add(n),a.parentGuid){let r=Dr(a.parentGuid,e.scene);r&&r.add(n)}a.position&&n.position.copy(a.position)}function Gy(a,e){let t=a.guid,i=pd[t];i&&(delete pd[t],i.removeFromParent())}import*as Of from"three";var MR=D("debugassets");var cl=class{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;let t=e?.reason?.path;if(t){let i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
150
- `+i.src),e.preventDefault())}})}texturesLoader=new Of.TextureLoader;textures={};texturesLoading={};async loadTexture(e){if(this.textures[e])return this.textures[e];if(this.texturesLoading[e])return await this.texturesLoading[e];let t=this.texturesLoader.loadAsync(e);this.texturesLoading[e]=t;let i=await t;return delete this.texturesLoading[e],this.textures[e]=i,i}getTexture(e){return this._textures.get(e)||null}findTexture(e){for(let t of this._textures.values())if(t.name===e)return t;return null}findMesh(e){for(let t of this._meshes.values())if(t.name===e)return t;return null}findMaterial(e){for(let t of this._materials.values())if(t.name===e)return t;return null}async registerGltf(e){}registerAsset(e){}_materials=new Map;_meshes=new Map;_textures=new Map};import*as Ff from"three/examples/jsm/libs/stats.module";import{Vector4 as Jy,EquirectangularReflectionMapping as dl,sRGBEncoding as hl,WebGLCubeRenderTarget as Zy}from"three";import{LightProbeGenerator as $y}from"three/examples/jsm/lights/LightProbeGenerator.js";import*as If from"three";var Wy=new If.FileLoader;async function fd(a){return new Promise((e,t)=>{Wy.load(a,e,void 0,t)})}import{Vector4 as Xn,FileLoader as Xy,DataTexture as yd,RGBAFormat as Qy,Color as Yy}from"three";var Fs=new Uint8Array(4);Fs[0]=255;Fs[1]=255;Fs[2]=255;Fs[3]=255;var Mf=new yd(Fs,1,1,Qy);function Lf(a,e=1){let t="alpha"in a,i=e*e,n=new Uint8Array(4*i),r=Math.floor(a.r*255),o=Math.floor(a.g*255),s=Math.floor(a.b*255);for(let d=0;d<i;d++){let l=d*4;n[l+0]=r,n[l+1]=o,n[l+2]=s,t?n[l+3]=Math.floor(a.alpha*255):n[l+3]=255}let c=new yd(n,e,e);return c.needsUpdate=!0,c}function Df(a,e,t,i=1,n=3){let s=i*n,c=[a,e,t],d=c.length,l=new Uint8Array(4*d*s),h=new Yy;for(let f=0;f<n;f++){let x=Math.floor(f/n*d),b=J.clamp(x+1,0,d-1),y=c[x],g=c[b],p=f/n*d%1;h.lerpColors(y,g,p);let m=Math.floor(h.r*255),v=Math.floor(h.g*255),w=Math.floor(h.b*255);for(let E=0;E<i;E++){let C=(f*i+E)*4;l[C+0]=m,l[C+1]=v,l[C+2]=w,l[C+3]=255}}let u=new yd(l,i,n);return u.needsUpdate=!0,u}var gd=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},bd=class{loaded=new Map;async loadShader(e){let t=await fd(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((r,o)=>{let s=this.loaded.get(t);s?r(s):o("Shader not found")});let i=await fd(t),n=new gd(e,i);return this.loaded.set(t,n),n}},HR=new bd;function Ns(a,e){let t=a.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){let n=t[i],r=t[i+1],o=t[i+2],s=t[i+3],c=new Xn(n,r,o,s);e.push(c)}return e}var md=[],kf=[];function xd(a,e){if(md.length===0)for(let t=0;t<27;t++)md.push(0);e||(e=md);for(let t=0;t<27;t++)kf[t]=e[t];e=kf,a.unity_SHAr={value:new Xn(e[9],e[3],e[6],e[0])},a.unity_SHBr={value:new Xn(e[12],e[15],e[18],e[21])},a.unity_SHAg={value:new Xn(e[10],e[4],e[7],e[1])},a.unity_SHBg={value:new Xn(e[13],e[16],e[19],e[22])},a.unity_SHAb={value:new Xn(e[11],e[5],e[8],e[2])},a.unity_SHBb={value:new Xn(e[14],e[17],e[20],e[23])},a.unity_SHC={value:new Xn(e[24],e[25],e[26],1)}}var vd=class{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}};async function jf(a,e){if(!a)return console.error("Can not find technique: no shader data"),null;let t=a.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){let r=a.shaders[i],o=a.shaders[n];if(r.uri&&o.uri||r.code&&o.code){if(!r.code&&r.uri&&await Af(r),!o.code&&o.uri&&await Af(o),!r.code||!o.code)return null;let s=a.techniques[e];return new vd(r.code,o.code,s)}}return console.error("Shader technique not found",e),null}async function Af(a){let e=a.uri;if(!!e)if(e.endsWith(".glsl")){let i=await new Xy().loadAsync(e);a.code=i.toString()}else a.code=Ky(a.uri)}function Ky(a){return decodeURIComponent(Array.prototype.map.call(atob(a),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}var wd=D("debugenvlight"),Ed=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Ed||{});var ul=class{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}sceneLightSettings;preUpdate(){let 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 Jy;get timeVec4(){return this._timevec4}get environmentIntensity(){return this.sceneLightSettings?this.sceneLightSettings.ambientIntensity:1}registerSceneLightSettings(e){this.sceneLightSettings=e}registerReflection(e,t){let i=new _d(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(wd&&console.log(this.sceneLightSettings?Ed[this.sceneLightSettings.ambientMode]:"Unknown ambient mode"),this.sceneLightSettings?.ambientMode){case 0:case 4:let t=this.getReflection(e);if(t&&t.Source){let i=this.context.scene,n=t.Source;n.encoding=hl,n.mapping=dl,i.environment=n;return}break}if(this.sceneLightSettings?.environmentReflectionSource===1)switch(this.sceneLightSettings?.ambientMode){case 1:if(this.sceneLightSettings.ambientTrilight){let t=this.sceneLightSettings.ambientTrilight,i=Df(t[0],t[1],t[2],64,64);i.encoding=hl,i.mapping=dl,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=Lf(this.sceneLightSettings.ambientLight,64);t.encoding=hl,t.mapping=dl,this.context.scene.environment=t}else console.error("Missing ambientlight",this.sceneLightSettings.sourceId);return;default:return}}disableReflection(){let e=this.context.scene;e.environment=null}async getSceneLightingData(e){return wd&&console.log("GET SCENE LIGHT DATA"),this._waitPromise?this._waitPromise:(this._waitPromise=new Promise((t,i)=>{let n=setInterval(async()=>{let r=this.getReflection(e);r&&(clearInterval(n),t(r.getSphericalHarmonicsArray(this.sceneLightSettings?.ambientIntensity??1)))},10)}),this._waitPromise)}_waitPromise;_lighting={}},_d=class{get Source(){return this._source}get Array(){return this._sphericalHarmonicsArray}_context;_source;_sphericalHarmonics=null;_sphericalHarmonicsArray;_ambientScale=1;_lightProbe;constructor(e,t,i=1){this._context=e,this._source=t,this._ambientScale=i,t.mapping=dl,t.encoding=hl}getSphericalHarmonicsArray(e=1){if(this._sphericalHarmonicsArray?.length&&this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:this._lightProbe};try{let t=this._source,i=null;if(t){wd&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new Zy(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=$y.fromCubeRenderTarget(this._context.renderer,i);this._lightProbe=n;let r=this._ambientScale*(e*e*Math.PI*.5)-1;this._sphericalHarmonics=n.sh,this._sphericalHarmonicsArray=this._sphericalHarmonics.toArray();let o=e/(Math.PI*.5);for(let s=0;s<this._sphericalHarmonicsArray.length;s++)this._sphericalHarmonicsArray[s]*=o;if(n.sh.scale(r),this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:n}}}catch(t){console.error(t)}return null}};import{Object3D as ex}from"three";var Fr=D("debugaddressables"),pl=class{_context;constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}_assetReferences={};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}},Ye=class{static getOrCreate(e,t,i){let n=wi(e,t);Fr&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,o=r.findAssetReference(n);if(o)return o;let s=new Ye(n);return r.registerAssetReference(s),s}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(e){this._uri=e,Up(this._uri,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(Fr&&console.log("Unload",this.asset),this.asset.scene?ei(this.asset.scene):ei(this.asset)),this.asset=null}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,Fr&&console.log("Preload",this.uri);let e=await Ef(this.uri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=K.Current;this._rawBinary?(this._loading=Qe().parseSync(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(Fr&&console.log("Load async",this.uri),this._loading=Qe().loadSync(t,this.uri,null,!0,n=>{this.raiseProgressEvent(n)}));let i=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),this._loading=void 0,i)return un(t),i.scene!==void 0&&(this.asset=i),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){let t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(let t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,i){let n=K.Current;if(e||(e=n.scene),this.mustLoad&&await this.loadAssetAsync(),Fr&&console.log("Instantiate",this.uri,"parent:",e),this.asset){Fr&&console.log("Add to scene",this.asset);let r=e instanceof Ge?e:null;if(r||(r=new Ge),typeof e=="object"&&(e instanceof ex?r.parent=e:Object.assign(r,e)),t){r.context=n;let o=this.asset;o.guid=this.uri;let s=Na(o,r,void 0,i);if(s)return s}else{let o=jr(this.asset,r);if(o)return o}}else Fr&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){let t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}},Cd=class extends sn{constructor(){super([Ye])}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){return typeof e=="string"?t.context?t.gltfId?Ye.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new Cd;var fl=class extends EventTarget{context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};import{FloatType as tx,HalfFloatType as ix,sRGBEncoding as nx}from"three";var Bf="NEEDLE_lightmaps",rx=D("debuglightmapsextension"),zs=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(zs||{}),ml=class{get name(){return Bf}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Bf];if(i){let n=i.textures;return n.length?(rx&&console.log(i),new Promise(async(r,o)=>{let s=[];for(let c of n)if(c.pointer){let d=So(this.parser,c.pointer).then(l=>{let h=l;h?.isTexture&&(this.registry?(c.type!==0&&(h.encoding=nx),(h.type==tx||h.type==ix)&&(h.flipY=!0),this.registry.registerTexture(this.source,c.type,h,c.index)):console.log(zs[c.type],c.pointer,h))});s.push(d)}await Promise.all(s),r()})):null}}return null}};import*as Oi from"three";var Hf=!!D("debuglightmaps"),gl=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){Hf&&console.log("Registering lightmap",e,zs[t],i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);let r=this._lightmaps.get(e),o=r?.get(t)??[];o.length<n&&(o.length=n+1),o[n]=i,r?.set(t,o)}tryGetLightmap(e,t=0){return this.tryGet(e,0,t)}tryGetSkybox(e){return this.tryGet(e,1,0)}tryGetReflection(e){return this.tryGet(e,2,0)}tryGet(e,t,i){if(!e)return Hf&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};Oi.ShaderChunk.lights_fragment_maps=Oi.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
149
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`))),Ul&&console.log("FIND",e),e!=null){for(let n=0;n<o.userData.components.length;n++){let i=o.userData.components[n];if(e===null||i.constructor.name===e.name||i.constructor.name===e)if(Ul&&console.log("MATCH BY NAME",i),t)t.push(i);else return i}for(let n=0;n<o.userData.components.length;n++){let i=o.userData.components[n],r=Object.getPrototypeOf(i.constructor);do{if(r===e)if(Ul&&console.log("MATCH BY PROTOYPE",r),t)t.push(i);else return i;r=Object.getPrototypeOf(r)}while(r)}return t}}}function cr(o,e){return Gu(o,e)}function eo(o,e,t){return t||(t=[]),Gu(o,e,t)}function Xn(o,e,t){let n=cr(o,e);if(t===!1&&n.enabled===!1)return null;if(n)return n;for(let i=0;i<o?.children?.length;i++){let r=Xn(o.children[i],e);if(r)return r}return null}function to(o,e,t){t||(t=[]),eo(o,e,t);for(let n=0;n<o?.children?.length;n++)to(o.children[n],e,t);return t}function $r(o,e){if(!o)return null;if(Array.isArray(o)){for(let n=0;n<o.length;n++){let i=Uf(o[n]),r=$r(i,e);if(r)return r}return null}let t=cr(o,e);return t||(o.parent?$r(o.parent,e):null)}function Yo(o,e,t){return t||(t=[]),o?(eo(o,e,t),o.parent?Yo(o.parent,e,t):t):t}function Vu(o,e,t){if(!o)return null;if(!e&&(e=V.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let n=e;if(n.isScene||(n=e?.scene),!n)return null;for(let i in n.children){let r=n.children[i];if(t===!1&&r[sn]===!1)continue;if(r.constructor==o)return r;let s=Xn(r,o);if(s)return s}return null}function Nu(o,e,t){if(!o)return e;if(!t&&(t=V.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;let n=t.isScene===!0||t.isObject3D===!0?t:t?.scene;if(!n)return e;for(let i in n.children){let r=n.children[i];if(r.constructor==o)return r;to(r,o,e)}return e}function no(o){o&&o.isObject3D===!0&&ju(o,Qe)}Qe.prototype.SetActive=function(o){this.visible=o};Qe.prototype.addNewComponent=function(o){return wi(this,new o)};Qe.prototype.removeComponent=function(o){return Ns(this,o)};Qe.prototype.getOrAddComponent=function(o){return Ws(this,o)};Qe.prototype.getComponent=function(o){return cr(this,o)};Qe.prototype.getComponents=function(o,e){return eo(this,o,e)};Qe.prototype.getComponentInChildren=function(o){return Xn(this,o)};Qe.prototype.getComponentsInChildren=function(o,e){return to(this,o,e)};Qe.prototype.getComponentInParent=function(o){return $r(this,o)};Qe.prototype.getComponentsInParent=function(o,e){return Yo(this,o,e)};Object.getOwnPropertyDescriptor(Qe.prototype,"activeSelf")||Object.defineProperty(Qe.prototype,"activeSelf",{get:function(){return this.visible},set:function(o){let e=typeof o=="number"?o>.5:o;this.visible=e}});Hu(Qe);var Xs=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),ne=class{static isUsingInstancing(e){return e.__isUsingInstancing===!0}static markDirty(e,t=!0){if(!!e&&(this.isUsingInstancing(e)&&(e[Xs]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let n of e.children)ne.markDirty(n,!0)}};var dr=I("debuggetcomponent"),Gf=(d=>(d[d.None=0]="None",d[d.HideInHierarchy=1]="HideInHierarchy",d[d.HideInInspector=2]="HideInInspector",d[d.DontSaveInEditor=4]="DontSaveInEditor",d[d.NotEditable=8]="NotEditable",d[d.DontSaveInBuild=16]="DontSaveInBuild",d[d.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",d[d.DontSave=52]="DontSave",d[d.HideAndDontSave=61]="HideAndDontSave",d))(Gf||{}),Ie=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context},Qs=Symbol("isActive");function sr(o){let e=o.visible||Ys(o);return o[Qs]===void 0&&(o[Qs]=e),o[Qs]&&e}function qs(o,e,t=!0){o[Qs]=e,t&&(o.visible=e)}function zu(o){return o[sn]||Ys(o)}function Xu(o,e){o.__isUsingInstancing=e}function Ys(o){return ne.isUsingInstancing(o)}function ar(o,e){return vi(o,e,!0,!0)}function At(o,e=!0,t=!0){let n=o;if(n.isComponent){n.__internalDisable(),n.__internalDestroy();return}let i=o;if(dr&&console.log(i),e&&i.children)for(let s of i.children)At(s,e,!1);let r=i.userData.components;if(r){let s=r.length;for(let a=0;a<r.length;a++){let c=r[a];c.__internalDisable(),c.__internalDestroy(),r.length<s&&(s=r.length,a--)}}t&&i.removeFromParent()}function Qn(o,e,t=!0){if(!!o){if(o.isObject3D||new Error("Expected Object3D but got "+o),o.userData?.components)for(let n=0;n<o.userData.components.length;n++){let i=o.userData.components[n];if(i?.isComponent===!0){let r=e(i);if(r!==void 0)return r}}if(t&&o.children)for(let n=0;n<o.children.length;n++){let i=o.children[n];if(!i)continue;let r=Qn(i,e,t);if(r!==void 0)return r}}}function lr(o,e=null){if(o===null)return null;let t=null;e!==null&&(e.x!==void 0?(t=new Ie,t.position=e):t=e);let n=V.Current;t?.context&&(n=t.context),dr&&n.alias&&console.log("context",n.alias),t&&!t.idProvider&&(t.idProvider=new ke(Date.now()));let i=[],r={},s={},a=Qu(n,o,t,i,r,s);a&&(Nf(r),Vf(s,r)),dr&&(zo(o,!0),zo(a,!0));let c={};for(let d in i){let l=i[d],u=l.guid;t&&t.idProvider&&(l.guid=t.idProvider.generateUUID(),c[u]=l.guid,dr&&console.log(l.name,l.guid)),zs(l,n),l.__internalNewInstanceCreated&&l.__internalNewInstanceCreated()}for(let d in i){let l=i[d];l.resolveGuids&&l.resolveGuids(c),l.enabled!==!1&&(l.enabled=!0)}return zn(n),a}function Qu(o,e,t,n,i,r){if(!e)return null;let s=e.userData;e.userData={};let a=e.children;e.children=[];let c;if(c=e.clone(!1),no(c),e.userData=s,e.children=a,i[e.uuid]={original:e,clone:c},e.type==="SkinnedMesh"&&(r[e.uuid]={original:e,clone:c}),t?.visible!==void 0&&(c.visible=t.visible),t?.idProvider){c.uuid=t.idProvider.generateUUID();let l=c;l&&(l.guid=c.uuid)}e.animations&&e.animations.length>0&&(c.animations=[...e.animations]);let d=e.parent;if(d&&d.add(c),t?.position?J(c,t.position):c.position.copy(e.position),t?.rotation?Be(c,t.rotation):c.quaternion.copy(e.quaternion),t?.scale?c.scale.copy(t.scale):c.scale.copy(e.scale),t?.parent&&t.parent!=="scene"){let l=null;if(typeof t.parent=="string"?l=vi(t.parent,o.scene,!0):l=t.parent,l){let u=t.keepWorldPosition===!0?l.attach:l.add;u?u.call(l,c):console.error("Invalid parent object",l,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(let[l,u]of Object.entries(e.userData))l!=="components"&&(c.userData[l]=u);if(e.userData?.components){let l=e.userData.components,u=[];c.userData.components=u;for(let h=0;h<l.length;h++){let b=l[h],_=Object.create(b);Nn(_,b),u.push(_),_.gameObject=c,n.push(_)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(let l in e.children){let u=e.children[l],h=Qu(o,u,t,n,i,r);h&&c.add(h)}return c}function Vf(o,e){for(let t in o){let n=o[t],i=n.original,r=i.skeleton,s=n.clone;if(!r){console.warn("Skinned mesh has no skeleton?",n);continue}let a=r.bones,c=s.skeleton.clone();s.skeleton=c,s.bindMatrix.clone().copy(i.bindMatrix),s.bindMatrixInverse.copy(i.bindMatrixInverse);let d=[];c.bones=d;for(let l=0;l<a.length;l++){let u=a[l],b=e[u.uuid].clone;d.push(b)}}for(let t in o){let n=o[t].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}function Nf(o){for(let e in o){let n=o[e].clone;if(n.userData?.components)for(let i=0;i<n.userData.components.length;i++){let r=n.userData.components[i],s=Object.entries(r);for(let[a,c]of s)if(Array.isArray(c)){let d=[];r[a]=d;for(let l=0;l<c.length;l++){let u=c[l];if(typeof u!="object"){d.push(u);continue}let h=Wu(r,a,u,o);h!==void 0?d.push(h):d.push(u)}}else if(typeof c=="object"){let d=Wu(r,a,c,o);d!==void 0&&(r[a]=d)}}}}function Wu(o,e,t,n){if(t!=null){if(t.isComponent===!0){let i=t.gameObject;if(i){let r=i.uuid,s=n[r]?.clone;if(!s){dr&&console.log("reference did not change",e,o,t);return}let a=i.userData.components.indexOf(t);if(a>=0)return dr&&console.log(e,r),s.userData.components[a];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;let i=t;if(i){let r=i.uuid,s=n[r]?.clone;if(s)return dr&&console.log(e,"old",t,"new",s),s}}}}import ur,{ActiveEvents as em,Collider as tm,ColliderDesc as Ks,EventQueue as nm,RigidBody as im,World as rm}from"@dimforge/rapier3d-compat";var Gl=I("debugphysics"),Vl=I("debugphysicscolliders"),sE=I("debugcollisions"),Ko=Symbol("needle component"),qn=Symbol("physics body"),ge=class{ray=void 0;cam=void 0;screenPoint=void 0;raycaster=void 0;results=void 0;targets=void 0;recursive=!0;minDistance=void 0;maxDistance=void 0;lineThreshold=void 0;layerMask=void 0;ignore=void 0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new $f),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new Nl);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};j(ge,"AllLayers",4294967295);var Wl=class{distance;point;object;constructor(e,t,n){this.object=e,this.distance=t,this.point=n}},Jo=class{raycaster=new Jf;defaultRaycastOptions=new ge;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new Nl;sphereOverlap(e,t,n=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let i=new Zf(e,t),r=this.sphereMask;r.enableAll(),r.disable(2);for(let s of this.context.scene.children)this.onSphereOverlap(s,i,r,this.sphereResults,n);return this.sphereResults.sort((s,a)=>s.distance-a.distance)}tempBoundingBox=new zf;onSphereOverlap(e,t,n,i,r){if(e.type==="Mesh"&&e.layers.test(n)){let s=e,a=s.geometry;if(a.boundingBox||a.computeBoundingBox(),a.boundingBox){s.matrixWorldNeedsUpdate&&s.updateMatrixWorld();let c=this.tempBoundingBox.copy(a.boundingBox).applyMatrix4(s.matrixWorld);if(t.intersectsBox(c)){let l=B(e).distanceTo(t.center),u=new Wl(e,l,t.center.clone());if(i.push(u),!r)return}}}if(e.children)for(let s of e.children){let a=i.length;if(this.onSphereOverlap(s,t,n,i,r),a!=i.length&&!r)return}}raycastFromRay(e,t=null){let n=t??this.defaultRaycastOptions;return n.ray=e,this.raycast(n)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,n=e.raycaster??this.raycaster;if(n.near=e.minDistance??0,n.far=e.maxDistance??1/0,n.params=this.defaultThresholds,e.lineThreshold?n.params.Line={threshold:e.lineThreshold}:n.params.Line={threshold:0},e.ray)n.ray.copy(e.ray);else{let a=e.cam??this.context.mainCamera;if(!a)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];n.setFromCamera(t,a)}let i=e.targets;i||(i=this.targetBuffer,i[0]=this.context.scene);let r=e.results;r||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),r=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof Nl?n.layers.mask=e.layerMask.mask:n.layers.mask=e.layerMask:(n.layers.enableAll(),n.layers.disable(2)),r.length=0,n.intersectObjects(i,e.recursive,r);let s=e.ignore;return s!==void 0&&s.length>0&&(r=r.filter(a=>!s.includes(a.object))),r}_tempPosition=new Yu;_tempQuaternion=new Kf;_tempMatrix=new Yf;_isUpdatingPhysicsWorld=!1;get isUpdating(){return this._isUpdatingPhysicsWorld}context;world;_hasCreatedWorld=!1;eventQueue;collisionHandler;objects=[];bodies=[];constructor(e){this.context=e}async createWorld(){if(this._hasCreatedWorld){console.error("Invalid call to create physics world: world is already created");return}this._hasCreatedWorld=!0,Jo._didLoadPhysicsEngine||(await ur.init().then(()=>ur),Jo._didLoadPhysicsEngine=!0);let e={x:0,y:-9.81,z:0};this.world=new rm(e)}addBoxCollider(e,t,n){let i=e.gameObject,r=on(i,this._tempPosition).multiply(n);r.multiplyScalar(.5);let s=Ks.cuboid(r.x,r.y,r.z);this.createCollider(e,s,t)}addSphereCollider(e,t,n){let i=e.gameObject,r=on(i,this._tempPosition).multiplyScalar(n),s=Ks.ball(r.x);this.createCollider(e,s,t)}addMeshCollider(e,t,n){let i=t.geometry;if(!i){Gl&&console.warn("Missing mesh geometry",t.name);return}let r=i.getAttribute("position").array,s=i.index?.array,a=on(t,this._tempPosition);if(Math.abs(a.x-1)>1e-4||Math.abs(a.y-1)>1e-4||Math.abs(a.z-1)>1e-4){console.warn("Your model is using scaled mesh colliders which is not optimal for performance",t.name,Object.assign({},a),t);let d=new Float32Array(r.length);for(let l=0;l<r.length;l+=3)d[l]=r[l]*a.x,d[l+1]=r[l+1]*a.y,d[l+2]=r[l+2]*a.z;r=d}let c=n?Ks.convexMesh(r):Ks.trimesh(r,s);c&&this.createCollider(e,c)}createCollider(e,t,n){if(!this.world)throw new Error("Physics world not initialized");let i=this._tempMatrix,{rigidBody:r,useExplicitMassProperties:s}=this.getRigidbody(e,this._tempMatrix);i.decompose(this._tempPosition,this._tempQuaternion,new Yu),n&&this._tempPosition.add(n),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);let a=this.world.createCollider(t,r);return a[Ko]=e,e[qn]=a,a.setActiveEvents(em.COLLISION_EVENTS),this.objects.push(e),this.bodies.push(a),a}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let n=null,i=!1;if(e.attachedRigidbody){let r=e.attachedRigidbody;if(n=r[qn],i=!0,!n){let s=r.isKinematic&&!Vl;Gl&&console.log("Create rigidbody",s);let a=s?ur.RigidBodyDesc.kinematicPositionBased():ur.RigidBodyDesc.dynamic(),c=B(e.attachedRigidbody.gameObject);a.setTranslation(c.x,c.y,c.z),a.setRotation(me(e.attachedRigidbody.gameObject)),n=this.world.createRigidBody(a),this.bodies.push(n),this.objects.push(r)}n[Ko]=r,r[qn]=n,this.internalUpdateProperties(r,n),this.getRigidbodyRelativeMatrix(e.gameObject,r.gameObject,t)}else{let r=ur.RigidBodyDesc.kinematicPositionBased(),s=B(e.gameObject);r.setTranslation(s.x,s.y,s.z),r.setRotation(me(e.gameObject)),n=this.world.createRigidBody(r),t.identity(),n[Ko]=null}return{rigidBody:n,useExplicitMassProperties:i}}removeBody(e){let t=e[qn];if(e[qn]=null,t){let n=this.objects.findIndex(i=>i===e);if(n>=0){let i=this.bodies[n];this.bodies.splice(n,1),this.objects.splice(n,1),i instanceof tm?this.world?.removeCollider(i,!0):i instanceof im&&this.world?.removeRigidBody(i);let r=e;if(r.isCollider&&r.attachedRigidbody){let s=r.attachedRigidbody[qn];s&&s.numColliders()<=0&&s.world()===this.world&&this.world?.removeRigidBody(s)}}}}updateBody(e,t,n){if(!(e.destroyed||!e.gameObject)&&!(!t&&!n))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{let i=e,r=i[qn];r&&this.syncPhysicsBody(i.gameObject,r,t,n)}}updateProperties(e){let t=e[qn];t&&this.internalUpdateProperties(e,t)}internal_getRigidbody(e){return e[qn]}internalUpdateProperties(e,t){t.enableCcd(e.collisionDetectionMode!==0),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?1:0,!0),t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!0),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!0),e.isKinematic?t.setBodyType(ur.RigidBodyType.KinematicPositionBased):t.setBodyType(ur.RigidBodyType.Dynamic)}lines;step(e){!this.world||(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new nm(!1)),this.world.step(this.eventQueue),this._isUpdatingPhysicsWorld=!1,this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Gl||Vl){if(!this.lines){let n=new Qf({color:16777215}),i=new Xf;this.lines=new qf(i,n),this.context.scene.add(this.lines)}let t=e.debugRender();this.lines.geometry.setAttribute("position",new qu(t.vertices,3)),this.lines.geometry.setAttribute("color",new qu(t.colors,4))}}postStep(){!this.world||(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new zl(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()))}syncObjects(){if(!Vl)for(let e=0;e<this.bodies.length;e++){let t=this.objects[e],n=this.bodies[e],i=t;if(i?.isCollider===!0&&!i.attachedRigidbody){let a=n.parent();a&&this.syncPhysicsBody(t.gameObject,a,!0,!0);continue}let r=n.translation();Kr(t.gameObject,r.x,r.y,r.z);let s=n.rotation();yu(t.gameObject,s.x,s.y,s.z,s.w)}}syncPhysicsBody(e,t,n,i){let r=B(e,this._tempPosition),s=me(e,this._tempQuaternion);n&&t.setTranslation(r,!1),i&&t.setRotation(s,!1),t.wakeUp()}getRigidbodyRelativeMatrix(e,t,n,i){if(i===void 0&&(i=Jo._matricesBuffer,i.length=0),e===t){let r=on(e,this._tempPosition);n.makeScale(r.x,r.y,r.z);for(let s=i.length-1;s>=0;s--)n.multiply(i[s]);return n}return i.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,n,i),n}},io=Jo;j(io,"_didLoadPhysicsEngine",!1),j(io,"_matricesBuffer",[]);var om=null;function Ku(o){om=o}var zl=class{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeTriggers=[];handleCollisionEvents(){!this.eventQueue||!this.world||this.eventQueue.drainCollisionEvents((e,t,n)=>{let i=this.world.getCollider(e),r=this.world.getCollider(t),s=i[Ko],a=r[Ko];s&&a&&(n?(this.onCollisionStarted(s,i,a,r),this.onCollisionStarted(a,r,s,i)):(this.onCollisionEnded(s,a),this.onCollisionEnded(a,s)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,n,i){let r=null;if(e.isTrigger||n.isTrigger)Qn(e.gameObject,s=>{s.onTriggerEnter&&s.onTriggerEnter(n),this.activeTriggers.push({collider:e,component:s,otherCollider:n})});else{let s=e.gameObject;this.world.contactPair(t,i,(a,c)=>{Qn(s,d=>{if(d.onCollisionEnter){if(!r){let l=[],u=a.normal();for(let h=0;h<a.numContacts();h++){let b=a.localContactPoint1(h),_=a.contactDist(h);if(b){let v=new Hs(b,_,u);l.push(v)}}r=new Xo(s,n,l)}d.onCollisionEnter.call(d,r),this.activeCollisions.push({collider:e,component:d,collision:r})}})})}}onHandleCollisionStay(){for(let e of this.activeCollisions){let t=e.component;if(t.activeAndEnabled&&t.onCollisionStay){let n=e.collision;t.onCollisionStay(n)}}for(let e of this.activeTriggers){let t=e.component;if(t.activeAndEnabled&&t.onTriggerStay){let n=e.collider;t.onTriggerStay(n)}}}onCollisionEnded(e,t){for(let n=0;n<this.activeCollisions.length;n++){let i=this.activeCollisions[n];if(i.collider===e&&i.collision.collider===t){let s=i.component;if(this.activeCollisions.splice(n,1),n--,s.activeAndEnabled&&s.onCollisionExit){let a=i.collision;s.onCollisionExit(a)}}}for(let n=0;n<this.activeTriggers.length;n++){let i=this.activeTriggers[n];if(i.collider===e&&i.otherCollider===t){let s=i.component;if(this.activeTriggers.splice(n,1),n--,s.activeAndEnabled&&s.onTriggerExit){let a=i.otherCollider;s.onTriggerExit(a)}}}}};import{Clock as sm}from"three";var Js=class{deltaTime=0;time=0;frame=0;get realtimeSinceStartup(){return this.clock.elapsedTime}get frameCount(){return this.frame}get smoothedFps(){return this._smoothedFps}clock=new sm;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<30?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%30]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedFps=1/(e/this._fpsSamples.length)}};import{WebsocketBuilder as lm}from"websocket-ts";var an=new Int32Array(2),Zs=new Float32Array(an.buffer),$s=new Float64Array(an.buffer),ro=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1;var Ae=class{constructor(e,t){this.low=e|0,this.high=t|0}static create(e,t){return e==0&&t==0?Ae.ZERO:new Ae(e,t)}toFloat64(){return(this.low>>>0)+this.high*4294967296}equals(e){return this.low==e.low&&this.high==e.high}};Ae.ZERO=new Ae(0,0);var Zo;(function(o){o[o.UTF8_BYTES=1]="UTF8_BYTES",o[o.UTF16_STRING=2]="UTF16_STRING"})(Zo||(Zo={}));var ln=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new ln(new Uint8Array(e))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(e){this.position_=e}capacity(){return this.bytes_.length}readInt8(e){return this.readUint8(e)<<24>>24}readUint8(e){return this.bytes_[e]}readInt16(e){return this.readUint16(e)<<16>>16}readUint16(e){return this.bytes_[e]|this.bytes_[e+1]<<8}readInt32(e){return this.bytes_[e]|this.bytes_[e+1]<<8|this.bytes_[e+2]<<16|this.bytes_[e+3]<<24}readUint32(e){return this.readInt32(e)>>>0}readInt64(e){return new Ae(this.readInt32(e),this.readInt32(e+4))}readUint64(e){return new Ae(this.readUint32(e),this.readUint32(e+4))}readFloat32(e){return an[0]=this.readInt32(e),Zs[0]}readFloat64(e){return an[ro?0:1]=this.readInt32(e),an[ro?1:0]=this.readInt32(e+4),$s[0]}writeInt8(e,t){this.bytes_[e]=t}writeUint8(e,t){this.bytes_[e]=t}writeInt16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeUint16(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8}writeInt32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeUint32(e,t){this.bytes_[e]=t,this.bytes_[e+1]=t>>8,this.bytes_[e+2]=t>>16,this.bytes_[e+3]=t>>24}writeInt64(e,t){this.writeInt32(e,t.low),this.writeInt32(e+4,t.high)}writeUint64(e,t){this.writeUint32(e,t.low),this.writeUint32(e+4,t.high)}writeFloat32(e,t){Zs[0]=t,this.writeInt32(e,an[0])}writeFloat64(e,t){$s[0]=t,this.writeInt32(e,an[ro?0:1]),this.writeInt32(e+4,an[ro?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+4+4)throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let e="";for(let t=0;t<4;t++)e+=String.fromCharCode(this.readInt8(this.position_+4+t));return e}__offset(e,t){let n=e-this.readInt32(e);return t<this.readInt16(n)?this.readInt16(n+t):0}__union(e,t){return e.bb_pos=t+this.readInt32(t),e.bb=this,e}__string(e,t){e+=this.readInt32(e);let n=this.readInt32(e),i="",r=0;if(e+=4,t===Zo.UTF8_BYTES)return this.bytes_.subarray(e,e+n);for(;r<n;){let s,a=this.readUint8(e+r++);if(a<192)s=a;else{let c=this.readUint8(e+r++);if(a<224)s=(a&31)<<6|c&63;else{let d=this.readUint8(e+r++);if(a<240)s=(a&15)<<12|(c&63)<<6|d&63;else{let l=this.readUint8(e+r++);s=(a&7)<<18|(c&63)<<12|(d&63)<<6|l&63}}}s<65536?i+=String.fromCharCode(s):(s-=65536,i+=String.fromCharCode((s>>10)+55296,(s&(1<<10)-1)+56320))}return i}__union_with_string(e,t){return typeof e=="string"?this.__string(t):this.__union(e,t)}__indirect(e){return e+this.readInt32(e)}__vector(e){return e+this.readInt32(e)+4}__vector_len(e){return this.readInt32(e+this.readInt32(e))}__has_identifier(e){if(e.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let t=0;t<4;t++)if(e.charCodeAt(t)!=this.readInt8(this.position()+4+t))return!1;return!0}createLong(e,t){return Ae.create(e,t)}createScalarList(e,t){let n=[];for(let i=0;i<t;++i)e(i)!==null&&n.push(e(i));return n}createObjList(e,t){let n=[];for(let i=0;i<t;++i){let r=e(i);r!==null&&n.push(r.unpack())}return n}};var rt=class{constructor(e){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null;let t;e?t=e:t=1024,this.bb=ln.allocate(t),this.space=t}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(e){this.force_defaults=e}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(e,t){e>this.minalign&&(this.minalign=e);let n=~(this.bb.capacity()-this.space+t)+1&e-1;for(;this.space<n+e+t;){let i=this.bb.capacity();this.bb=rt.growByteBuffer(this.bb),this.space+=this.bb.capacity()-i}this.pad(n)}pad(e){for(let t=0;t<e;t++)this.bb.writeInt8(--this.space,0)}writeInt8(e){this.bb.writeInt8(this.space-=1,e)}writeInt16(e){this.bb.writeInt16(this.space-=2,e)}writeInt32(e){this.bb.writeInt32(this.space-=4,e)}writeInt64(e){this.bb.writeInt64(this.space-=8,e)}writeFloat32(e){this.bb.writeFloat32(this.space-=4,e)}writeFloat64(e){this.bb.writeFloat64(this.space-=8,e)}addInt8(e){this.prep(1,0),this.writeInt8(e)}addInt16(e){this.prep(2,0),this.writeInt16(e)}addInt32(e){this.prep(4,0),this.writeInt32(e)}addInt64(e){this.prep(8,0),this.writeInt64(e)}addFloat32(e){this.prep(4,0),this.writeFloat32(e)}addFloat64(e){this.prep(8,0),this.writeFloat64(e)}addFieldInt8(e,t,n){(this.force_defaults||t!=n)&&(this.addInt8(t),this.slot(e))}addFieldInt16(e,t,n){(this.force_defaults||t!=n)&&(this.addInt16(t),this.slot(e))}addFieldInt32(e,t,n){(this.force_defaults||t!=n)&&(this.addInt32(t),this.slot(e))}addFieldInt64(e,t,n){(this.force_defaults||!t.equals(n))&&(this.addInt64(t),this.slot(e))}addFieldFloat32(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat32(t),this.slot(e))}addFieldFloat64(e,t,n){(this.force_defaults||t!=n)&&(this.addFloat64(t),this.slot(e))}addFieldOffset(e,t,n){(this.force_defaults||t!=n)&&(this.addOffset(t),this.slot(e))}addFieldStruct(e,t,n){t!=n&&(this.nested(t),this.slot(e))}nested(e){if(e!=this.offset())throw new Error("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw new Error("FlatBuffers: object serialization must not be nested.")}slot(e){this.vtable!==null&&(this.vtable[e]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(e){let t=e.capacity();if(t&3221225472)throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let n=t<<1,i=ln.allocate(n);return i.setPosition(n-t),i.bytes().set(e.bytes(),n-t),i}addOffset(e){this.prep(4,0),this.writeInt32(this.offset()-e+4)}startObject(e){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=e;for(let t=0;t<e;t++)this.vtable[t]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw new Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let e=this.offset(),t=this.vtable_in_use-1;for(;t>=0&&this.vtable[t]==0;t--);let n=t+1;for(;t>=0;t--)this.addInt16(this.vtable[t]!=0?e-this.vtable[t]:0);let i=2;this.addInt16(e-this.object_start);let r=(n+i)*2;this.addInt16(r);let s=0,a=this.space;e:for(t=0;t<this.vtables.length;t++){let c=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(c)){for(let d=2;d<r;d+=2)if(this.bb.readInt16(a+d)!=this.bb.readInt16(c+d))continue e;s=this.vtables[t];break}}return s?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,s-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,n){let i=n?4:0;if(t){let r=t;if(this.prep(this.minalign,4+4+i),r.length!=4)throw new Error("FlatBuffers: file identifier must be length "+4);for(let s=4-1;s>=0;s--)this.writeInt8(r.charCodeAt(s))}this.prep(this.minalign,4+i),this.addOffset(e),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(e,t){this.finish(e,t,!0)}requiredField(e,t){let n=this.bb.capacity()-e,i=n-this.bb.readInt32(n);if(!(this.bb.readInt16(i+t)!=0))throw new Error("FlatBuffers: field "+t+" must be set")}startVector(e,t,n){this.notNested(),this.vector_num_elems=t,this.prep(4,e*t),this.prep(n,e*t)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(e){if(!e)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(e))return this.string_maps.get(e);let t=this.createString(e);return this.string_maps.set(e,t),t}createString(e){if(!e)return 0;let t;if(e instanceof Uint8Array)t=e;else{t=[];let n=0;for(;n<e.length;){let i,r=e.charCodeAt(n++);if(r<55296||r>=56320)i=r;else{let s=e.charCodeAt(n++);i=(r<<10)+s+(65536-(55296<<10)-56320)}i<128?t.push(i):(i<2048?t.push(i>>6&31|192):(i<65536?t.push(i>>12&15|224):t.push(i>>18&7|240,i>>12&63|128),t.push(i>>6&63|128)),t.push(i&63|128))}}this.addInt8(0),this.startVector(1,t.length,1),this.bb.setPosition(this.space-=t.length);for(let n=0,i=this.space,r=this.bb.bytes();n<t.length;n++)r[i++]=t[n];return this.endVector()}createLong(e,t){return Ae.create(e,t)}createObjectOffset(e){return e===null?0:typeof e=="string"?this.createString(e):e.pack(this)}createObjectOffsetList(e){let t=[];for(let n=0;n<e.length;++n){let i=e[n];if(i!==null)t.push(this.createObjectOffset(i));else throw new Error("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return t}createStructOffsetList(e,t){return t(this,e.length),this.createObjectOffsetList(e),this.endVector()}};var Ju={};function so(o,e){Ju[o]=e}function Zu(o){let e=o.getBufferIdentifier(),t=Ju[e];return t(o)}function $u(o){return typeof o.guid=="function"?o.guid():null}var Ql=Cs(ta(),1);var na=class{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){let e="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(e)}trySetupHost(e){let t=new Ql.default(e);t.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),t.on("open",n=>{this._host=new Yl(t)})}trySetupClient(e){this._client=new Ql.default,this._client.on("error",t=>{console.error("Client error",t)}),this._client.on("open",t=>{console.log("client connected",t),this._clientData=this._client.connect(e,{metadata:{id:t}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}},ql=class{_peer;constructor(e){this._peer=e}};var Yl=class extends ql{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){let t=this._connections.map(n=>n.metadata?.id).filter(n=>n!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(let t in this._peer.connections){let n=this._peer.connections[t];if(!!n)if(Array.isArray(n))for(let i of n)!i||i.send(e);else console.warn(n)}}}};var ia="wss://needle-tiny-starter.glitch.me/socket",ot=!!I("debugnet"),ra=!!(ot||I("debugowner"));var Ci=class{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(ra&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let n=0,i=()=>{if(n++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):i()},100)};i()})}requestOwnership(){return ra&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListening("gained-ownership",this._gainSubscription),this.connection.stopListening("lost-ownership",this._lostSubscription),this.connection.stopListening("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListening("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(ra&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(ra&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}},oa=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new na),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return ot}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(let t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){this.connect(),ot&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},0)}leaveRoom(e=null){if(e||(e=this.currentRoomName),!e){console.error("Can not leave unknown room");return}this.send("leave-room",{room:e})}send(e,t=null,n=2){if(t===null&&(t={}),n===2){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,n)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendBinary(e){ot&&console.log("<< bin",e.length),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;let e=Object.keys(this._defaultMessagesBuffer).length;for(let n in this._defaultMessagesBuffer){let i=this._defaultMessagesBuffer[n];if(e<=1){this.sendWithWebsocket(i.key,i.value,3);break}let r=this.toMessage(i.key,i.value);this._defaultMessagesBufferArray.push(r)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&ot&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let n=this._listeners[e].indexOf(t);n>=0&&this._listeners[e].splice(n,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let n=this._listenersBinary[e].indexOf(t);n>=0&&this._listenersBinary[e].splice(n,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}connect(){if(this.connected)return;ot&&console.log("connecting");let e=this.netWebSocketUrlProvider?.getWebsocketUrl();e?ia=e:pu()&&(ia="wss://"+window.location.host+"/socket"),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+ia);let e=new lm(ia).onOpen(()=>{this._ws=e,this._isConnectingToWebsocket=!1,this.connected=!0,console.log("Connected to websocket"),this.onSendQueued(0)}).onClose(t=>{this.connected=!1,this._isInRoom=!1}).onError((t,n)=>{console.error(t,n)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("websocket connection retry")}).build()}onMessage(e,t){let n=t.data;try{if(typeof n!="string"){n.size&&this.handleIncomingBinaryMessage(n);return}let i=JSON.parse(n);if(Array.isArray(i))for(let r of i)this.handleIncomingStringMessage(r);else this.handleIncomingStringMessage(i);return}catch{ot&&n==="pong"&&console.log("<<",n)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var n=new Uint8Array(t);let i=new ln(n),r=i.getBufferIdentifier(),s=this._listenersBinary[r],a=Zu(i),c=$u(a);if(c&&typeof c=="string"&&(this._state[c]=a),!s)return;let d=a??i;for(let l of s)l(d)}handleIncomingStringMessage(e){if(ot&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let s=e.data;s&&(console.assert(s.id!==void 0&&s.id!==null&&s.id.length>0,"server did not send connection id",s.id),console.log("Your id is: "+s.id,this.context.alias??""),this._connectionId=s.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(ot&&console.log(e),e){this._isInRoom=!0;let s=e;this._currentRoomName=s.room,this._currentRoomViewId=s.viewId,this._currentRoomAllowEditing=s.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...s.inRoom),ot&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let s=e.data;this._currentInRoom.push(s.userId),ot&&console.log(s.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let s=e.data,a=this._currentInRoom.indexOf(s.userId);a>=0&&(console.log(s.userId+" left",this.context.alias??""),this._currentInRoom.splice(a,1)),s.userId===this.connectionId&&console.log("you left the room")}break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),ot&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+this._currentInRoom?.length);break}let t=this._listeners[e.key];if(t)for(let i of t)i(e.data);let n=e.data;n&&(this._state[n.guid]=n)}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,n=1){if(!this._ws){let r=this._waitingForSocket[n]||[];r.push(()=>this.sendWithWebsocket(e,t,n)),this._waitingForSocket[n]=r;return}let i=JSON.stringify(this.toMessage(e,t));ot&&console.log(">>",e),this._ws.send(i)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let n of t)n();t.length=0}}};import{EffectComposer as Dm}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as Am}from"three/examples/jsm/postprocessing/RenderPass";import*as Ti from"three";var ch=Cs(lh(),1),sa=class{success;filename;hash;size;url;constructor(e,t,n,i){this.success=e,this.filename=t,this.hash=n,this.size=i}};async function dh(o,e){let t=await o.arrayBuffer(),n=uh(t),i=o.name.split(".").pop(),r=n+"."+i,s=o.name.split(".").shift();console.assert(s!==void 0);let a={alias:s,filename:r},d=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(d.success||console.warn("exists check did fail"),d.exists)return console.log("file already exists",n),new sa(!0,r,n,o.size);console.log("begin uploading file",s,o.size);let l=new FormData;l.append("file",o);let u={};u.filesize=o.size,s&&(u.alias=s);let b=await(await fetch(e+"/upload/file",{method:"POST",body:l,headers:u})).json();if(b?.success===!1)return b.message!==void 0?console.error("Upload failed:",b.message):console.error("Upload failed"),null;console.assert(b.hash_sum===n,"hash sum did not match","received:",b.hash_sum,"expected:",n),b.success&&console.log("successfully uploaded",n,b.id);let _=new sa(b.success,r,n,o.size);return _.url=e,_}function uh(o){return(0,ch.default)(new Uint8Array(o))}async function aa(o,e,t,n,i=!1){try{let r=await fetch(n+"/download/file",{method:"POST",body:o});if(r.status!==200)return console.error("download failed",r),null;let s=await r.blob(),a=await s.arrayBuffer();i||console.assert(s.size===t,"size mismatch","expected:",t,"got:",s.size);let c=uh(a);return i||console.assert(c===e,"hash mismatch, downloaded file is invalid"),s.arrayBuffer()}catch(r){console.error(r)}return null}async function hh(o,e){let t=await fetch(o),n=t.body?.getReader(),i=t.headers.get("Content-Length"),r=i?parseInt(i):0;if(!n)return null;let s=0,a=[];for(;;){let{done:l,value:u}=await n.read();if(u&&(a.push(u),s+=u.length,e.call(null,new ProgressEvent("progress",{loaded:s,total:r}))),l)break}let c=new Uint8Array(s),d=0;for(let l of a)c.set(l,d),d+=l.length;return c}function la(o,e,t){console.warn("Adding components on object has been temporarily disabled")}var fh,ph=null;function Le(){return fh}function ca(o){ph!==o&&(ph=o,fh=new o)}var Zl=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,n,i,r,s,a,c){this.seed=t,this.guid=n,this.file_name=i,this.file_hash=r,this.file_size=s,this.position=a,this.sender=e,this.serverUrl=c}};async function mh(o,e,t){let n=o.name;return n.endsWith(".gltf")||n.endsWith(".glb")?new Promise((i,r)=>{let s=new FileReader;s.readAsDataURL(o),s.onloadend=async a=>{let c=s.result,d=Vs(),l=new ke(d),u=await Le().loadSync(e,c,l,!0);if(u&&u.scene){let h=u.scene;if(!h.guid){let b=new ke(d);h.guid=b.generateUUID()}t&&hm(e.connection,o,d,h,t),la(h,l,u),i(u)}}}):(console.warn("Unsupported file type: "+n),console.log(o),null)}async function gh(o,e){return new Promise(async(t,n)=>{let i=Vs(),r=new ke(i),s=await Le().loadSync(e,o.toString(),r,!0);if(s&&s.scene){let a=s.scene;la(a,r,s),t(s)}else console.warn("Unsupported file type: "+o.toString())})}function bh(o){o.connection.beginListen("file-spawned",async e=>{if(e.sender!==o.connection.connectionId){console.log("received file event",e),pm(e,o);let t=null;try{t=await aa(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{fm(e,o)}if(t){let n=new ke(e.seed),i=await Le().parseSync(o,t,null,n);if(i&&i.scene){let r=i.scene;if(la(r,n,i),e.parentGuid){let s=ar(e.parentGuid,o.scene);"add"in s&&s.add(r)}r.parent||o.scene.add(r),e.position!==null&&r.position.copy(e.position)}}else console.error("download didnt return file")}})}async function hm(o,e,t,n,i){if(!o.connectionId){console.error("Can not upload file - no connection id");return}if(!n.guid){console.error("Can not upload file - no guid",n,n.guid);return}let r=await dh(e,i);if(!r)return;if(!r.filename){console.error("Can not send upload event - no filename",e.name);return}if(!r.hash){console.error("Can not send upload event - no hash",e.name);return}let s=new Zl(o.connectionId,t,n.guid,r.filename,r.hash,e.size,n.position,r.url??i);n.parent&&(s.parentGuid=n.parent.guid),o.send("file-spawned",s)}var $l={};function pm(o,e){let t=new Ti.BoxGeometry,n=new Ti.Mesh(t,new Ti.MeshBasicMaterial({color:65280})),i=new Ti.BoxHelper(n,5592405);if($l[o.guid]=i,e.scene.add(i),o.parentGuid){let r=ar(o.parentGuid,e.scene);r&&r.add(i)}o.position&&i.position.copy(o.position)}function fm(o,e){let t=o.guid,n=$l[t];n&&(delete $l[t],n.removeFromParent())}import*as vh from"three";var $E=I("debugassets");var da=class{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;let t=e?.reason?.path;if(t){let n=t[0];n&&n.tagName==="IMG"&&(console.warn(`Could not load image:
150
+ `+n.src),e.preventDefault())}})}texturesLoader=new vh.TextureLoader;textures={};texturesLoading={};async loadTexture(e){if(this.textures[e])return this.textures[e];if(this.texturesLoading[e])return await this.texturesLoading[e];let t=this.texturesLoader.loadAsync(e);this.texturesLoading[e]=t;let n=await t;return delete this.texturesLoading[e],this.textures[e]=n,n}getTexture(e){return this._textures.get(e)||null}findTexture(e){for(let t of this._textures.values())if(t.name===e)return t;return null}findMesh(e){for(let t of this._meshes.values())if(t.name===e)return t;return null}findMaterial(e){for(let t of this._materials.values())if(t.name===e)return t;return null}async registerGltf(e){}registerAsset(e){}_materials=new Map;_meshes=new Map;_textures=new Map};import*as Ph from"three/examples/jsm/libs/stats.module";import{Vector4 as wm,EquirectangularReflectionMapping as ua,sRGBEncoding as ha,WebGLCubeRenderTarget as xm}from"three";import{LightProbeGenerator as Cm}from"three/examples/jsm/lights/LightProbeGenerator.js";import*as yh from"three";var gm=new yh.FileLoader;async function ec(o){return new Promise((e,t)=>{gm.load(o,e,void 0,t)})}import{Vector4 as Ri,FileLoader as vm,DataTexture as oc,RGBAFormat as ym,Color as _m}from"three";var $o=new Uint8Array(4);$o[0]=255;$o[1]=255;$o[2]=255;$o[3]=255;var wh=new oc($o,1,1,ym);function xh(o,e=1){let t="alpha"in o,n=e*e,i=new Uint8Array(4*n),r=Math.floor(o.r*255),s=Math.floor(o.g*255),a=Math.floor(o.b*255);for(let d=0;d<n;d++){let l=d*4;i[l+0]=r,i[l+1]=s,i[l+2]=a,t?i[l+3]=Math.floor(o.alpha*255):i[l+3]=255}let c=new oc(i,e,e);return c.needsUpdate=!0,c}function Ch(o,e,t,n=1,i=3){let a=n*i,c=[o,e,t],d=c.length,l=new Uint8Array(4*d*a),u=new _m;for(let b=0;b<i;b++){let _=Math.floor(b/i*d),v=W.clamp(_+1,0,d-1),y=c[_],m=c[v],f=b/i*d%1;u.lerpColors(y,m,f);let p=Math.floor(u.r*255),g=Math.floor(u.g*255),E=Math.floor(u.b*255);for(let w=0;w<n;w++){let T=(b*n+w)*4;l[T+0]=p,l[T+1]=g,l[T+2]=E,l[T+3]=255}}let h=new oc(l,n,i);return h.needsUpdate=!0,h}var nc=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},ic=class{loaded=new Map;async loadShader(e){let t=await ec(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((r,s)=>{let a=this.loaded.get(t);a?r(a):s("Shader not found")});let n=await ec(t),i=new nc(e,n);return this.loaded.set(t,i),i}},rw=new ic;function es(o,e){let t=o.elements;e||(e=[]),e.length=0;for(let n=0;n<16;n+=4){let i=t[n],r=t[n+1],s=t[n+2],a=t[n+3],c=new Ri(i,r,s,a);e.push(c)}return e}var tc=[],_h=[];function sc(o,e){if(tc.length===0)for(let t=0;t<27;t++)tc.push(0);e||(e=tc);for(let t=0;t<27;t++)_h[t]=e[t];e=_h,o.unity_SHAr={value:new Ri(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new Ri(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new Ri(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new Ri(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new Ri(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new Ri(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new Ri(e[24],e[25],e[26],1)}}var rc=class{vertexShader;fragmentShader;technique;constructor(e,t,n){this.vertexShader=e,this.fragmentShader=t,this.technique=n}};async function Th(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;let t=o.programs[e],n=t.vertexShader,i=t.fragmentShader;if(n!==void 0&&i!==void 0){let r=o.shaders[n],s=o.shaders[i];if(r.uri&&s.uri||r.code&&s.code){if(!r.code&&r.uri&&await Eh(r),!s.code&&s.uri&&await Eh(s),!r.code||!s.code)return null;let a=o.techniques[e];return new rc(r.code,s.code,a)}}return console.error("Shader technique not found",e),null}async function Eh(o){let e=o.uri;if(!!e)if(e.endsWith(".glsl")){let n=await new vm().loadAsync(e);o.code=n.toString()}else o.code=Em(o.uri)}function Em(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}var ac=I("debugenvlight"),cc=(i=>(i[i.Skybox=0]="Skybox",i[i.Trilight=1]="Trilight",i[i.Flat=3]="Flat",i[i.Custom=4]="Custom",i))(cc||{});var pa=class{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}sceneLightSettings;preUpdate(){let 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 wm;get timeVec4(){return this._timevec4}get environmentIntensity(){return this.sceneLightSettings?this.sceneLightSettings.ambientIntensity:1}registerSceneLightSettings(e){this.sceneLightSettings=e}registerReflection(e,t){let n=new lc(this.context,t,1);this._lighting[e]=n}getReflection(e){return this._lighting[e]}enableReflection(e){switch(ac&&console.log(this.sceneLightSettings?cc[this.sceneLightSettings.ambientMode]:"Unknown ambient mode"),this.sceneLightSettings?.ambientMode){case 0:case 4:let t=this.getReflection(e);if(t&&t.Source){let n=this.context.scene,i=t.Source;i.encoding=ha,i.mapping=ua,n.environment=i;return}break}if(this.sceneLightSettings?.environmentReflectionSource===1)switch(this.sceneLightSettings?.ambientMode){case 1:if(this.sceneLightSettings.ambientTrilight){let t=this.sceneLightSettings.ambientTrilight,n=Ch(t[0],t[1],t[2],64,64);n.encoding=ha,n.mapping=ua,this.context.scene.environment=n}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=xh(this.sceneLightSettings.ambientLight,64);t.encoding=ha,t.mapping=ua,this.context.scene.environment=t}else console.error("Missing ambientlight",this.sceneLightSettings.sourceId);return;default:return}}disableReflection(){let e=this.context.scene;e.environment=null}async getSceneLightingData(e){return ac&&console.log("GET SCENE LIGHT DATA"),this._waitPromise?this._waitPromise:(this._waitPromise=new Promise((t,n)=>{let i=setInterval(async()=>{let r=this.getReflection(e);r&&(clearInterval(i),t(r.getSphericalHarmonicsArray(this.sceneLightSettings?.ambientIntensity??1)))},10)}),this._waitPromise)}_waitPromise;_lighting={}},lc=class{get Source(){return this._source}get Array(){return this._sphericalHarmonicsArray}_context;_source;_sphericalHarmonics=null;_sphericalHarmonicsArray;_ambientScale=1;_lightProbe;constructor(e,t,n=1){this._context=e,this._source=t,this._ambientScale=n,t.mapping=ua,t.encoding=ha}getSphericalHarmonicsArray(e=1){if(this._sphericalHarmonicsArray?.length&&this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:this._lightProbe};try{let t=this._source,n=null;if(t){ac&&console.log("GENERATING LIGHT PROBE",t);let i=Math.min(t.image.width,512);n=new xm(i).fromEquirectangularTexture(this._context.renderer,t),this._source=n.texture}if(this._sphericalHarmonicsArray=[],n){let i=Cm.fromCubeRenderTarget(this._context.renderer,n);this._lightProbe=i;let r=this._ambientScale*(e*e*Math.PI*.5)-1;this._sphericalHarmonics=i.sh,this._sphericalHarmonicsArray=this._sphericalHarmonics.toArray();let s=e/(Math.PI*.5);for(let a=0;a<this._sphericalHarmonicsArray.length;a++)this._sphericalHarmonicsArray[a]*=s;if(i.sh.scale(r),this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:i}}}catch(t){console.error(t)}return null}};import{Object3D as Tm}from"three";var hr=I("debugaddressables"),fa=class{_context;constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate.bind(this))}preUpdate(){}_assetReferences={};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.uri&&(this._assetReferences[e.uri]?console.warn("Asset reference already registered",e):this._assetReferences[e.uri]=e),e}},je=class{static getOrCreate(e,t,n){let i=nn(e,t);hr&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",i);let r=n.addressables,s=r.findAssetReference(i);if(s)return s;let a=new je(i);return r.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(e){this._uri=e,Du(this._uri,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.uri&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0}isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(hr&&console.log("Unload",this.asset),this.asset.scene?At(this.asset.scene):At(this.asset)),this.asset=null}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,hr&&console.log("Preload",this.uri);let e=await hh(this.uri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=V.Current;this._rawBinary?(this._loading=Le().parseSync(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(hr&&console.log("Load async",this.uri),this._loading=Le().loadSync(t,this.uri,null,!0,i=>{this.raiseProgressEvent(i)}));let n=await this._loading;if(this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(n),this._loading=void 0,n)return zn(t),n.scene!==void 0&&(this.asset=n),this.asset}async instantiate(e){return this.onInstantiate(e,!1)}async instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){let t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(let t of this._progressListeners)t(this,e)}async onInstantiate(e,t=!1,n){let i=V.Current;if(e||(e=i.scene),this.mustLoad&&await this.loadAssetAsync(),hr&&console.log("Instantiate",this.uri,"parent:",e),this.asset){hr&&console.log("Add to scene",this.asset);let r=e instanceof Ie?e:null;if(r||(r=new Ie),typeof e=="object"&&(e instanceof Tm?r.parent=e:Object.assign(r,e)),t){r.context=i;let s=this.asset;s.guid=this.uri;let a=Gs(s,r,void 0,n);if(a)return a}else{let s=lr(this.asset,r);if(s)return s}}else hr&&console.warn("Failed to load asset",this.uri);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){let t=e.scene;return t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name?t.children[0]:t}return null}},dc=class extends Vn{constructor(){super([je])}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){return typeof e=="string"?t.context?t.gltfId?je.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new dc;var ma=class extends EventTarget{context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}};import{FloatType as Rm,HalfFloatType as Sm,sRGBEncoding as Pm}from"three";var Rh="NEEDLE_lightmaps",Om=I("debuglightmapsextension"),ts=(n=>(n[n.Lightmap=0]="Lightmap",n[n.Skybox=1]="Skybox",n[n.Reflection=2]="Reflection",n))(ts||{}),ga=class{get name(){return Rh}parser;registry;source;constructor(e,t,n){this.parser=e,this.registry=t,this.source=n}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[Rh];if(n){let i=n.textures;return i.length?(Om&&console.log(n),new Promise(async(r,s)=>{let a=[];for(let c of i)if(c.pointer){let d=qr(this.parser,c.pointer).then(l=>{let u=l;u?.isTexture&&(this.registry?(c.type!==0&&(u.encoding=Pm),(u.type==Rm||u.type==Sm)&&(u.flipY=!0),this.registry.registerTexture(this.source,c.type,u,c.index)):console.log(ts[c.type],c.pointer,u))});a.push(d)}await Promise.all(a),r()})):null}}return null}};import*as cn from"three";var Sh=!!I("debuglightmaps"),ba=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,n,i){Sh&&console.log("Registering lightmap",e,ts[t],n),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);let r=this._lightmaps.get(e),s=r?.get(t)??[];s.length<i&&(s.length=i+1),s[i]=n,r?.set(t,s)}tryGetLightmap(e,t=0){return this.tryGet(e,0,t)}tryGetSkybox(e){return this.tryGet(e,1,0)}tryGetReflection(e){return this.tryGet(e,2,0)}tryGet(e,t,n){if(!e)return Sh&&console.warn("Missing source id"),null;let i=this._lightmaps.get(e)?.get(t)??null;return!i?.length||i.length<=n?null:i[n]}};cn.ShaderChunk.lights_fragment_maps=cn.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
151
151
 
152
152
  vec2 lUv = vUv2.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
153
153
  vec4 lightMapTexel = texture2D( lightMap, lUv);
@@ -155,7 +155,7 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
155
155
  lightMapTexel.rgb *= lightMapTexel.a * 8.; // no idea where that "8" comes from... heuristically derived
156
156
  lightMapTexel.a = 1.;
157
157
  lightMapTexel = conv_sRGBToLinear(lightMapTexel);
158
- `);Oi.ShaderChunk.lightmap_pars_fragment=`
158
+ `);cn.ShaderChunk.lightmap_pars_fragment=`
159
159
  #ifdef USE_LIGHTMAP
160
160
  uniform sampler2D lightMap;
161
161
  uniform float lightMapIntensity;
@@ -166,14 +166,14 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
166
166
  return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
167
167
  }
168
168
  #endif
169
- `;Oi.ShaderChunk.lights_fragment_begin=Oi.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
169
+ `;cn.ShaderChunk.lights_fragment_begin=cn.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
170
170
  #if defined(USE_LIGHTMAP)
171
171
  irradiance += 0.;
172
172
  #else
173
173
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
174
- #endif`);Oi.UniformsLib.lightmap.lightmapScaleOffset={value:new Oi.Vector4(1,1,0,0)};var ox=D("debugplayerview");var Td=class{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}},bl=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new Td(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!e)return;if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}removePlayerView(e,t){let i=this.playerViews.get(e);i?.viewDevice===t&&(ox&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}};var dx=D("debugSetup"),hx=D("stats"),vl={};var ii=(o=>(o[o.EarlyUpdate=0]="EarlyUpdate",o[o.Update=1]="Update",o[o.LateUpdate=2]="LateUpdate",o[o.OnBeforeRender=3]="OnBeforeRender",o[o.OnAfterRender=4]="OnAfterRender",o[o.PhysicsStep=10]="PhysicsStep",o))(ii||{});function Va(a,e){if(!a)return;let t=e?.new_scripts??K.Current.new_scripts;t.includes(a)||t.push(a)}var Nt=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;domElement;get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;get domWidth(){return this.domElement.clientWidth}get domHeight(){return this.domElement.clientHeight}get domX(){return this.domElement.offsetLeft}get domY(){return this.domElement.offsetTop}get isInXR(){return this.renderer.xr?.isPresenting||!1}xrSessionMode=void 0;get xrSession(){return this.renderer.xr?.getSession()}get arOverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}scene;renderer;composer=null;scripts=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];coroutines={};get mainCamera(){if(this.mainCameraComponent){let e=this.mainCameraComponent;return e.cam||e.buildCamera(),e.cam}return null}mainCameraComponent;post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];application;time;input;physics;connection;assets;mainLight=null;rendererData;addressables;lightmaps;players;_sizeChanged=!1;_isCreated=!1;_stats=hx?Ff.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let i=D("postfx");this.renderer=new ax({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=ke.NoToneMapping,this.renderer.setClearColor(new ke.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=ke.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=ke.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=i?new lx(this.renderer):null}this.scene=new ke.Scene,this.application=new fl(this),this.time=new Ka,this.input=new va(this),this.physics=new Ya(this),this.connection=new rl(this),this.assets=new cl,this.rendererData=new ul(this),this.addressables=new pl(this),this.lightmaps=new gl(this),this.players=new bl(this),window.addEventListener("resize",()=>this._sizeChanged=!0),new ResizeObserver(i=>this._sizeChanged=!0).observe(this.domElement)}updateSize(){if(!this.isManagedExternally&&!this.renderer.xr.isPresenting){this._sizeChanged=!1;let e=this.resolutionScaleFactor,t=this.domWidth*e,i=this.domHeight*e,n=this.mainCamera;this.updateAspect(n),this.renderer.setSize(t,i),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&(this.composer.setSize(t,i),this.composer.setPixelRatio(window.devicePixelRatio))}}updateAspect(e){if(!e)return;let t=this.domWidth,i=this.domHeight,n=e.aspect;e.aspect=t/i,n!==e.aspect&&e.updateProjectionMatrix()}onCreate(e,t){return this._isCreated?(console.warn("Context already created"),null):(this._isCreated=!0,this.internalOnCreate(e,t))}onDestroy(){!this._isCreated||(this._isCreated=!1,ei(this.scene,!0),this.renderer?.setAnimationLoop(null),this.isManagedExternally||this.renderer?.dispose())}registerCoroutineUpdate(e,t,i){return this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;let i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(let t in this.coroutines){let i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.cam||e.buildCamera(),!e.cam){console.warn("Camera component is missing camera",e);return}let t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;let i=e.cam;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;let t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){let i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners={};addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners[e.uuid]){this._onBeforeRenderListeners[e.uuid]=[];let i=(n,r,o,s,c,d)=>{let l=this._onBeforeRenderListeners[e.uuid];if(!!l)for(let h=0;h<l.length;h++){let u=l[h];u(n,r,o,s,c,d)}};e.onBeforeRender=i}this._onBeforeRenderListeners[e.uuid].push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners[e.uuid]){let i=this._onBeforeRenderListeners[e.uuid],n=i.indexOf(t);n>=0&&i.splice(n,1)}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}async internalOnCreate(e,t){let i=!0;try{Nt.Current=this,e&&await e(this,t)}catch(n){console.error(n),i=!1}if(!!i){this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),Np(this),Fp(this),Pf(this),Nt._current=this;for(let n=0;n<this.new_scripts.length;n++){let r=this.new_scripts[n];if(r.gameObject!==void 0&&r.gameObject!==null){r.gameObject.userData===void 0&&(r.gameObject.userData={}),r.gameObject.userData.components===void 0&&(r.gameObject.userData.components=[]);let o=r.gameObject.userData.components;o.includes(r)||o.push(r)}}if(this.post_setup_callbacks)for(let n=0;n<this.post_setup_callbacks.length;n++)Nt._current=this,await this.post_setup_callbacks[n](this);if(this.mainCamera,Nt._current=this,un(this),!this.isManagedExternally&&this.composer&&this.mainCamera){let n=new cx(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(n),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),this.renderer.setAnimationLoop(this.render.bind(this)),dx&&ks(this.scene,!0)}}render(e,t){for(this._stats?.begin(),Nt._current=this,this.time.update(),un(this),Do(),Ba(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}if(this.pre_update_callbacks)for(let i in this.pre_update_callbacks)this.pre_update_callbacks[i]();for(let i=0;i<this.scripts_earlyUpdate.length;i++){let n=this.scripts_earlyUpdate[i];!n.activeAndEnabled||n.earlyUpdate!==void 0&&(Nt._current=this,n.earlyUpdate())}this.executeCoroutines(0);for(let i=0;i<this.scripts_update.length;i++){let n=this.scripts_update[i];!n.activeAndEnabled||n.update!==void 0&&(Nt._current=this,n.update())}this.executeCoroutines(1);for(let i=0;i<this.scripts_lateUpdate.length;i++){let n=this.scripts_lateUpdate[i];!n.activeAndEnabled||n.lateUpdate!==void 0&&(Nt._current=this,n.lateUpdate())}this.executeCoroutines(2);try{let n=this.time.deltaTime/2;for(let r=0;r<2;r++)this.physics.step(n),this.executeCoroutines(10)}catch(i){console.error(i)}this.physics.postStep();for(let i=0;i<this.scripts_onBeforeRender.length;i++){let n=this.scripts_onBeforeRender[i];!n.activeAndEnabled||n.onBeforeRender!==void 0&&(Nt._current=this,n.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(let i in this.pre_render_callbacks)this.pre_render_callbacks[i]();this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer&&!this.isInXR?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1;for(let i=0;i<this.scripts_onAfterRender.length;i++){let n=this.scripts_onAfterRender[i];!n.activeAndEnabled||n.onAfterRender!==void 0&&(Nt._current=this,n.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(let i in this.post_render_callbacks)this.post_render_callbacks[i]();this.connection.sendBufferedMessagesNow(),this._stats?.end()}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new ke.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new sx(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new ke.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=ke.NearestFilter,this._renderTarget.texture.magFilter=ke.NearestFilter,this._renderTarget.texture.format=ke.RGBAFormat)}let e=this._renderTarget;e.texture&&(e.texture.encoding=this.renderer.outputEncoding);let 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]){let i=this.coroutines[e];for(let n=0;n<i.length;n++){let r=i[n];if(!r.comp||r.comp.destroyed||!r.main||r.comp.enabled===!1){i.splice(n,1),--n;continue}let s=r.chained;if(s&&s.length>0){let h=s[s.length-1].next();if(h.done&&s.pop(),t(h)&&(r.chained||(r.chained=[]),r.chained.push(h.value)),!h.done)continue}let c=r.main.next();if(c.done===!0){i.splice(n,1),--n;continue}let d=c.value;if(t(d)){if(d.next().done)continue;r.chained||(r.chained=[]),r.chained.push(d)}}}function t(i){return!!(i&&i.next&&i.return)}}},K=Nt;U(K,"_current");var Rd={};fu(Rd,{Behaviour:()=>M,Component:()=>wt,GameObject:()=>k});import*as et from"three";var k=class extends et.Object3D{guid;static setActive(e,t,i=!0,n=!0){!e||(qa(e,t,n),Do(e),t&&i&&Ba(K.Current,e))}static isActiveSelf(e){return Lr(e)}static isActiveInHierarchy(e){return ef(e)}static markAsInstancedRendered(e,t){tf(e,t)}static isUsingInstancing(e){return Xa(e)}static foreachComponent(e,t,i=!0){return Ht(e,t,i)}static instantiateSynced(e,t){return e?Na(e,t):null}static instantiate(e,t=null){return jr(e,t)}static destroySynced(e,t,i=!0){if(!e)return;let n=e;t=t??K.Current,jo(n,t.connection,i)}static destroy(e,t=!0,i=!0){return ei(e,t,i)}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=K.Current),t.add(e),qa(e,!0),Do(e),i?k.foreachComponent(e,n=>{Qc(n,i),!n.__internalDidAwakeAndStart&&i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){!e||(e.parent?.remove(e),qa(e,!1),Do(e),k.foreachComponent(e,t=>{Ip(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){!e||this.foreachComponent(e,r=>{let o=r[t];o&&typeof o=="function"&&o.bind(r)(...n)},i)}static addNewComponent(e,t,i=!0){let n=new t;return Gn(e,n,i),n}static addComponent(e,t){if(t.gameObject==null)throw new Error("Did you mean to create a new component? Use addNewComponent");Qp(e,t)}static removeComponent(e){return Ua(e.gameObject,e),e}static getOrAddComponent(e,t){return Ga(e,t)}static getComponent(e,t){return e===null?null:Br(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:Ho(e,t,i)}static findByGuid(e,t){return Dr(e,t)}static findObjectOfType(e,t,i=!0){return Jp(e,t??K.Current,i)}static findObjectsOfType(e,t){let i=[];return Zp(e,i,t),i}static getComponentInChildren(e,t){return pn(e,t)}static getComponentsInChildren(e,t,i=null){return Fo(e,t,i??void 0)}static getComponentInParent(e,t){return Bo(e,t)}static getComponentsInParent(e,t,i=null){return Ds(e,t,i)}static getAllComponents(e){return[...e.userData?.components]}static*iterateComponents(e){let t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}},ni=class{get isComponent(){return!0}__context;get context(){return this.__context??K.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}get hideFlags(){return this.gameObject?.userData.hideFlags}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;let e=this.gameObject[Ri];return e===void 0?!0:e}set __isActiveInHierarchy(e){!this.gameObject||(this.gameObject[Ri]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=1){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=1){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__internalNewInstanceCreated(){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this.__internalResetsCachedPhysicsData()}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(){return this.__didEnable?!1:(this.__didEnable=!0,this.onEnable(),this.__isEnabled=!0,!0)}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this._collisionExitRoutine=void 0,this.onDisable(),this._collisions?.clear(),this.__isEnabled=!1)}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.destroy?.call(this),Yp(this))}get enabled(){return this.__isEnabled??!0}set enabled(e){if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}constructor(){this.__internalNewInstanceCreated()}_collisionExitRoutine;_collisions=null;_triggerExitRoutine;_triggerCollisions=null;get collisionsCount(){return this._collisions?.size??0}__internalResetsCachedPhysicsData(){this._collisionExitRoutine=null,this._collisions=null,this._triggerExitRoutine=null,this._triggerCollisions=null}__internalHandleCollision(e,t){if(t){if(!this.onTriggerEnter&&!this.onTriggerStay&&!this.onTriggerExit)return}else if(!this.onCollisionEnter&&!this.onCollisionStay&&!this.onCollisionExit)return;let i=e.gameObject;t&&!this._triggerCollisions?this._triggerCollisions=new Map:this._collisions||(this._collisions=new Map);let n=t?this._triggerCollisions:this._collisions;if(n.has(i)){let r=n.get(i);r.frame=this.context.time.frameCount,r.col=e,t?this.onTriggerStay?.(e):this.onCollisionStay?.call(this,e)}else{let r={col:e,frame:this.context.time.frameCount};n.set(i,r),t?this.onTriggerEnter?.(e):this.onCollisionEnter?.call(this,e)}}__internalHandleExitCollisionEvent(e,t){if(t){if(!this._triggerCollisions)return}else if(!this._collisions)return;let n=(t?this._triggerCollisions:this._collisions).get(e);!n||(n.exitFrame=this.context.time.frameCount,this.__waitForCollisionExit(t),t||this.onCollisionExitRaw?.call(this,n.col))}__waitForCollisionExit(e){if(e?this._triggerExitRoutine:this._collisionExitRoutine)return;let i=e?this._triggerCollisions:this._collisions,n=this,r=10;function*o(){for(;i&&i.size>0;){for(let c of i.keys()){let d=i.get(c);d.frame!==void 0&&n.context.time.frameCount-d.frame>=r&&(i.delete(c),e?n.onTriggerExit?.(d.col):n.onCollisionExit?.call(n,d.col))}for(let c=0;c<r;c++)yield}e?n._triggerExitRoutine=void 0:n._collisionExitRoutine=null}let s=this.startCoroutine(o(),4);e?this._triggerExitRoutine=s:this._collisionExitRoutine=s}_worldPosition=void 0;_worldQuaternion=void 0;_worldEuler=void 0;_worldRotation=void 0;get worldPosition(){return this._worldPosition||(this._worldPosition=new et.Vector3),X(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){se(this.gameObject,e)}setWorldPosition(e,t,i){ni._worldPositionBuffer.set(e,t,i),this.worldPosition=ni._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new et.Quaternion),Ie(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){$e(this.gameObject,e)}setWorldQuaternion(e,t,i,n){ni._worldQuaternionBuffer.set(e,t,i,n),this.worldQuaternion=ni._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new et.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new et.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new et.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=J.toDegrees(t.x),t.y=J.toDegrees(t.y),t.z=J.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){n&&(e=J.toRadians(e),t=J.toRadians(t),i=J.toRadians(i)),ni._worldEulerBuffer.set(e,t,i),ni._worldQuaternionBuffer.setFromEuler(ni._worldEulerBuffer),this.worldQuaternion=ni._worldQuaternionBuffer}get forward(){return ni._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}_eventListeners=new Map;addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;let i=this._eventListeners[e].indexOf(t);i>=0&&this._eventListeners[e].splice(i,1)}dispatchEvent(e){if(!this._eventListeners[e.type])return!1;let t=this._eventListeners[e.type];for(let i=0;i<t.length;i++)t[i](e);return!1}},wt=ni;U(wt,"_worldPositionBuffer",new et.Vector3),U(wt,"_worldQuaternionBuffer",new et.Quaternion),U(wt,"_worldEulerBuffer",new et.Euler),U(wt,"_tempQuaternionBuffer2",new et.Quaternion),U(wt,"_forward",new et.Vector3);var M=class extends wt{};var ux=D("debugloadingbar");function Sd(a){return a.index/a.count+a.progress.loaded/a.progress.total/a.count}var yl=class{loadingProgress=0;container;_progress=0;_allowCustomLoadingElement=!1;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this.container=e,this._loadingElementOptions=t}onLoadingBegin(e){if(!this._loadingElement){for(let t=0;t<this.container.children.length;t++){let i=this.container.children[t];if(i.classList.contains("loading")){if(!this._allowCustomLoadingElement){console.warn("Custom loading container is not allowed"),this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement(i);return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let i=0;typeof e=="number"?i=e:("index"in e&&(i=Sd(e)),!t&&"name"in e&&this.setMessage(e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(e){this.loadingProgress=1,this.setMessage(e??"")}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;ux&&(e=.001);let t=1-.05;this._progressLoop=setInterval(()=>{if(this.loadingProgress>=1&&this._progress>=t){this._loadingElement&&(this._loadingElement.style.display="none",this._loadingElement.remove()),clearInterval(this._progressLoop),this._progressLoop=null;return}this._progress=J.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}updateDisplay(){let e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){this._loadingElement=e||document.createElement("div"),e||(this._loadingElement.style.position="fixed",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",this._loadingElement.style.backgroundColor="#000000",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex="1000",this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let s of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(s);let i=document.createElement("div"),n=30;i.style.display="flex",i.style.width=n+"%",i.style.height="2px",i.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(i),this._loadingBar=document.createElement("div"),i.appendChild(this._loadingBar);let r=function(s){return J.lerp(n*.5,100-n*.5,s)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${r(0)}, #0BA398 ${r(.4)}, #99CC33 ${r(.5)}, #D7DB0A ${r(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let o=document.createElement("div");return this._messageContainer=o,o.style.display="flex",o.style.fontSize=".8em",o.style.paddingTop=".5em",o.style.color="rgba(255,255,255,.5)",o.style.justifyContent="center",this._loadingElement.appendChild(o),this._loadingElement}};import{DRACOLoader as Pd}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Nf}from"three/examples/jsm/loaders/KTX2Loader.js";var Us=D("debugdecoders"),ri,Qn;function Od(a){a!==void 0&&typeof a=="string"&&(ri||(ri=new Pd),Us&&console.log("Setting draco decoder path to",a),ri.setDecoderPath(a))}function Id(a){a!==void 0&&typeof a=="string"&&(ri||(ri=new Pd),Us&&console.log("Setting draco decoder type to",a),ri.setDecoderConfig({type:a}))}function kd(a){a!==void 0&&typeof a=="string"&&(Qn||(Qn=new Nf),Us&&console.log("Setting ktx2 transcoder path to",a),Qn.setTranscoderPath(a))}function Nr(a,e){ri||(ri=new Pd,ri.setDecoderPath("./include/draco/"),ri.setDecoderConfig({type:"js"}),Us&&console.log("Setting draco decoder path to","./include/draco/")),Qn||(Qn=new Nf,Qn.setTranscoderPath("./include/ktx2/"),Us&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&Qn.detectSupport(e.renderer)),a.setDRACOLoader(ri),a.setKTX2Loader(Qn)}import{AnimationClip as px,MathUtils as fx}from"three";var Vo=class{_name;get name(){return this._name}_nameHash;get nameHash(){return this._nameHash}_normalizedTime;get normalizedTime(){return this._normalizedTime}_length;get length(){return this._length}_speed;get speed(){return this._speed}constructor(e,t,i,n){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=i,this._speed=n}};function Uf(a,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??fx.generateUUID(),index:-1,clip:new px(a,1,[])}}import{AnimationClip as mx,AnimationMixer as gx,AxesHelper as bx,Euler as Gf,LoopOnce as vx,Quaternion as oi,Vector3 as Gs}from"three";import*as wl from"three";var Yn=D("debuganimatorcontroller"),Ad=D("debugrootmotion"),zt=class{Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let o=this.model.layers[t].stateMachine;for(let s of o.states)if(s.name===e||s.hash===e){Yn&&console.log("transition to ",s),this.transitionTo(s,n,i);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??!1}SetFloat(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetInteger(e,t){let i=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[i]===e).forEach(n=>n.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(i=>i[t]===e)?.value??0}SetTrigger(e){Yn&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[t]===e).forEach(i=>i.value=!1)}IsInTransition(){return this._activeStates.length>1}SetSpeed(e){this._speed=e}FindState(e){if(!e)return null;for(let t of this.model.layers)for(let i of t.stateMachine.states)if(i.name===e)return i;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new gx(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=ys(this.model,(i,n,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||r?.constructor?.name==="AnimationAction"||r.tracks!==void 0));return console.assert(e!==this.model),new zt(e)}update(){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates();let e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(),this._mixer.update(e),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate()}_mixer;_activeState;constructor(e){this.model=e,Yn&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],i=t.motion;if(!i.action)this._activeStates.splice(e,1),e--;else{let n=i.action;n.getEffectiveWeight()<=0&&!n.isRunning()&&(Yn&&console.debug("REMOVE",t.name,n.getEffectiveWeight(),n.isRunning(),n.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}let i=this._activeState,n=i.motion.action,r=0;for(let s of i.transitions){if(++r,!s.hasExitTime&&s.conditions.length<=0)continue;let c=!0;for(let d of s.conditions)if(!this.evaluateCondition(d)){c=!1;break}if(!!c){Yn&&c&&console.log("All conditions are met",s);for(let d of s.conditions){let l=this.model.parameters.find(h=>h.name===d.parameter);l?.type===9&&(l.value=!1)}if(n){let d=i.motion.clip.duration,l=d<=0?1:n.time/d;if(!s.hasExitTime||l>=s.exitTime&&n.time>=n.getClip().duration){n.clampWhenFinished=!0,Yn&&(console.log("transition to "+s.destinationState,s),console.log(n.time,s.exitTime)),this.transitionTo(s.destinationState,s.duration,s.offset);return}}else{this.transitionTo(s.destinationState,s.duration,s.offset);return}break}}let o=!1;if(i.motion.isLooping&&n&&n.time>=n.getClip().duration&&(o=!0,n.reset(),n.time=0,n.play()),!o&&i&&!t&&n&&this.animator&&i.behaviours){let s=n?.getClip().duration,c=n.time/s,d=new Vo(this._activeState,c,s,this._speed);for(let l of i.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,d,0)}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(e=this.getState(e,n),!e?.motion||!e.motion.clip)return;let r=this._activeState===e;if(r){let d=e.motion;!d.action_loopback&&d.clip&&(this._mixer.uncacheAction(d.clip,this.animator.gameObject),d.action_loopback=this.createAction(d.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let d=this._activeState?.motion.clip.duration,l=this._activeState.motion.action.time/d,h=new Vo(this._activeState,l,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateExit?.call(u.instance,this.animator,h,n)}let o=this._activeState?.motion.action;o&&o.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=o);let s=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){i=Math.max(0,Math.min(1,i)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let d=e.motion.clip.duration;if(c.time=i*d,c.clampWhenFinished=!0,c.setLoop(vx,0),t>0?c.fadeIn(t):c.setEffectiveWeight(1),c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let l=new Vo(e,i,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateEnter?.call(h.instance,this.animator,l,n)}}else console.warn("No action",e.motion,this);Yn&&console.log("TRANSITION FROM "+s?.name+" TO "+e.name,t,o,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new Md(this));let t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case 1:return t.value===!0;case 2:return t.value===!1;case 3:return t.value>e.threshold;case 4:return t.value<e.threshold;case 6:return t.value===e.threshold;case 7:return t.value!==e.threshold}return!1}createActions(e){for(let t of this.model.layers){let i=t.stateMachine;for(let n=0;n<i.states.length;n++){let r=i.states[n];if(r.motion||(r.motion=Uf(r.name)),this.animator&&r.motion.clips){let o=r.motion.clips?.find(s=>s.node.name===this.animator?.gameObject?.name);r.motion.clip=o?.clip}if(!r.motion.clip){let o=new mx;r.motion.clip=o}if(r.motion?.clip){let o=r.motion.clip,s=this.createAction(o);r.motion.action=s}if(r.behaviours&&Array.isArray(r.behaviours))for(let o of r.behaviours){if(!o?.typeName)continue;let s=j.get(o.typeName),c=new s;c.isStateMachineBehaviour&&(c._context=this.context??void 0,Tr(c,o.properties),o.instance=c),Yn&&console.log("Created animator controller behaviour",r.name,o.typeName,o.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let i=0;i<t.states.length;i++){let n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler},xl=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let o=this.originalEvaluate(r);return t(r,o)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},Re=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new Gs;rotationChange=new oi;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,Re.firstKeyframeRotation[i.uuid]||(Re.firstKeyframeRotation[i.uuid]=new wl.Quaternion),r){let o=r.values;Re.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}Re.spaceRotation[i.uuid]||(Re.spaceRotation[i.uuid]=new oi),Re.effectiveSpaceRotation[i.uuid]||(Re.effectiveSpaceRotation[i.uuid]=new oi),Re.clipOffsetRotation[i.uuid]=new oi,r&&Re.clipOffsetRotation[i.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,r)}onStart(e){if(e.getClip()!==this.clip)return;let t=Re.lastObjRotation[this.root.uuid];Re.spaceRotation[this.clip.uuid].copy(t);{let i=new wl.Euler().setFromQuaternion(t);console.log("START",this.clip.name,J.toDegrees(i.y))}}getClipRotationOffset(){return Re.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Ad&&i.add(new bx),Re.lastObjPosition[i.uuid]||(Re.lastObjPosition[i.uuid]=new Gs);let n=new Gs,r=new Gs,o=0;this.positionWrapper=new xl(t,(s,c)=>{let d=this.action.getEffectiveWeight();if(Ad&&i.position.length()>8&&i.position.set(0,i.position.y,0),s>o){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(d),n.applyQuaternion(this.getClipRotationOffset());let l=this.clip.uuid;n.applyQuaternion(Re.spaceRotation[l]),this.positionChange.copy(n)}return r.fromArray(c),o=s,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(Ad){let s=t.values,c=new Gf().setFromQuaternion(new oi(s[0],s[1],s[2],s[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",J.toDegrees(c.y));let d=t.values.length-4,l=new oi().set(s[d],s[d+1],s[d+2],s[d+3]),h=new Gf().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",J.toDegrees(h.y))}let i=this.root;Re.lastObjRotation[i.uuid]||(Re.lastObjRotation[i.uuid]=new oi);let n=0,r=new oi,o=new oi;this.rotationWrapper=new xl(t,(s,c)=>(s>n&&(o.set(c[0],c[1],c[2],c[3]),r.invert(),o.multiply(r),this.rotationChange.copy(o)),r.fromArray(c),n=s,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(Re.identityQuaternion,1-e)}},si=Re;U(si,"lastObjPosition",{}),U(si,"lastObjRotation",{}),U(si,"firstKeyframeRotation",{}),U(si,"spaceRotation",{}),U(si,"effectiveSpaceRotation",{}),U(si,"clipOffsetRotation",{}),U(si,"identityQuaternion",new oi);var Md=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,i){this.root=t;let n="";t&&"name"in t&&(n=t.name);let r=this.findRootTrack(i,".position"),o=this.findRootTrack(i,".quaternion"),s=new si(this.controller.context,t,i,r,o);this.handler.push(s);let c=e.clipAction(i);return s.action=c,c}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new Gs;summedRotation=new oi;onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(let e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),si.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let i=e.tracks;for(let n of i)if(n.name.endsWith(t))return n;return null}};var S=function(a){if(a===void 0&&(a=null),!Array.isArray(a))a=Vf(a);else for(let e=0;e<a.length;e++){let t=a[e];a[e]=Vf(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=a}};function Vf(a){switch(a?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return a}var yx=D("debuganimator"),ct=class extends M{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof zt?this._animatorController=e:this._animatorController=new zt(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.Play(e,t,i,n)}Reset(){this._animatorController?.Reset()}SetBool(e,t){this.runtimeAnimatorController?.SetBool(e,t)}GetBool(e){return this.runtimeAnimatorController?.GetBool(e)??!1}SetFloat(e,t){this.runtimeAnimatorController?.SetFloat(e,t)}GetFloat(e){return this.runtimeAnimatorController?.GetFloat(e)??-1}SetInteger(e,t){this.runtimeAnimatorController?.SetInteger(e,t)}GetInteger(e){return this.runtimeAnimatorController?.GetInteger(e)??-1}SetTrigger(e){this.runtimeAnimatorController?.SetTrigger(e)}ResetTrigger(e){this.runtimeAnimatorController?.ResetTrigger(e)}IsInTransition(){return this.runtimeAnimatorController?.IsInTransition()??!1}SetSpeed(e){e!==this.speed&&(this.speed=e,this._animatorController?.SetSpeed(e))}set minMaxSpeed(e){this.speed=J.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=J.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(!!this.gameObject){if(this.runtimeAnimatorController){let e=this.runtimeAnimatorController.clone();console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.SetSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset}yx&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};P([S()],ct.prototype,"applyRootMotion",2),P([S()],ct.prototype,"hasRootMotion",2),P([S()],ct.prototype,"keepAnimatorControllerStateOnDisable",2),P([S()],ct.prototype,"runtimeAnimatorController",1);import*as Wo from"three";import{Vector2 as Wf}from"three";var Ut=class extends M{playAutomatically=!0;randomStartTime=!0;minMaxSpeed;minMaxOffsetNormalized;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.gameObject){this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(this.gameObject.animations||(this.gameObject.animations=[]),this.gameObject.animations.push(e))}set animations(e){this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions=[];_currentActions=[];_handles=[];awake(){this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.actions.length>0&&this.currentActions.length<=0){let e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){if(!!this.mixer){this.mixer.update(this.context.time.deltaTime);for(let e of this._handles)e._update();this._handles?.length>0&&re.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let i=e;if(typeof e=="number"){if(e>=this.animations.length)return;i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(r=>r.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={}),t.minMaxOffsetNormalized||(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed||(t.minMaxSpeed=this.minMaxSpeed);for(let r of this.actions)if(r.getClip()===i)return this.internalOnPlay(r,t);let n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.currentAction;if(i===e&&i.isRunning()&&i.time<i.getClip().duration){let s=this.tryFindHandle(e);if(s)return s.getPromise()}let n=t?.exclusive??!0;t?.fadeDuration?(n&&i?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):n&&i?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1;let r=e.getClip();t?.minMaxOffsetNormalized&&(e.time=J.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration),t?.minMaxSpeed&&(e.timeScale=J.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random())),t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?Wo.LoopRepeat:Wo.LoopOnce),e.play();let o=new Ld(e,this.mixer,t,s=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){if(!this._didInit&&(this._didInit=!0,!!this.gameObject)){this.actions=[],this.mixer=new Wo.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};P([S()],Ut.prototype,"playAutomatically",2),P([S()],Ut.prototype,"randomStartTime",2),P([S(Wf)],Ut.prototype,"minMaxSpeed",2),P([S(Wf)],Ut.prototype,"minMaxOffsetNormalized",2);var Ld=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as ng}from"three/examples/jsm/loaders/GLTFLoader.js";import*as me from"three";import{RawShaderMaterial as wx}from"three";var fn=D("debugshaders"),qo="NEEDLE_techniques_webgl";var Dd=class{objectToWorldMatrix=new me.Matrix4;worldToObjectMatrix=new me.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Ns(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Ns(this.worldToObjectMatrix,this.worldToObject)}};var fe=class extends wx{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){let e=super.clone();return qf(e),e}constructor(e,...t){super(...t),this.identifier=e,fn&&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.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&K.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=K.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&K.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=K.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}fn&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},xd(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new me.Vector4(r,r,r,r)},fn&&console.log("Set environment lighting",this.uniforms)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";_rendererData=new Dd;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&K.Current.setRequireColor(!0),this.depthTextureUniform&&K.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,r,o){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=K.Current;e&&(fe.viewProjection&&this.uniforms[this._viewProjectionName]&&(fe.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Ns(fe.viewProjection,fe._viewProjectionValues)),fe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(fe.viewMatrix.copy(e.matrixWorldInverse),Ns(fe.viewMatrix,fe._viewMatrixValues)),this.uniforms[fe._worldSpaceCameraPosName]&&fe._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters?this.uniforms._TimeParameters.value=i.rendererData.timeVec4:this.uniforms._Time&&(this.uniforms._Time.value=i.rendererData.timeVec4);let n=i.mainLight;if(n){let s=X(n.gameObject,fe._mainLightPosition);this.uniforms._MainLightPosition={value:s.normalize()},fe._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:fe._mainLightColor};let c=n.intensity;fe._lightData.z=c,this.uniforms.unity_LightData={value:fe._lightData}}if(e&&(fe.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=fe._viewProjectionValues),fe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=fe._viewMatrixValues),this.uniforms[fe._worldSpaceCameraPosName]&&(this.uniforms[fe._worldSpaceCameraPosName]={value:fe._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){let s=this.uniforms._ProjectionParams.value;s.x=1,s.y=i.mainCameraComponent.nearClipPlane,s.z=i.mainCameraComponent.farClipPlane,s.w=1/s.z,this.uniforms._ProjectionParams.value=s}if(this.uniforms._ZBufferParams){let s=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;s.x=1-c.farClipPlane/c.nearClipPlane,s.y=c.farClipPlane/c.nearClipPlane,s.z=s.x/c.farClipPlane,s.w=s.y/c.farClipPlane,this.uniforms._ZBufferParams.value=s}if(this.uniforms._ScreenParams){let s=this.uniforms._ScreenParams.value;s.x=i.domWidth,s.y=i.domHeight,s.z=1+1/s.x,s.w=1+1/s.y,this.uniforms._ScreenParams.value=s}}let r=this.depthTextureUniform;r&&(r.value=i.depthTexture);let o=this.opaqueTextureUniform;if(o&&(o.value=i.opaqueColorTexture),t){let s=this._rendererData;s.updateFrom(t),this.uniforms[this._worldToObjectName].value=s.worldToObject,this.uniforms[this._objToWorldName].value=s.objectToWorld}this.uniformsNeedUpdate=!0}},Gt=fe;U(Gt,"viewProjection",new me.Matrix4),U(Gt,"_viewProjectionValues",[]),U(Gt,"viewMatrix",new me.Matrix4),U(Gt,"_viewMatrixValues",[]),U(Gt,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),U(Gt,"_worldSpaceCameraPos",new me.Vector3),U(Gt,"_mainLightColor",new me.Vector4),U(Gt,"_mainLightPosition",new me.Vector3),U(Gt,"_lightData",new me.Vector4);var _l=class{get name(){return qo}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return fn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[qo])return fn&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[qo].technique;if(i<0)return null;let n=this.parser.json.extensions[qo];if(!n)return null;fn&&console.log(n);let r=n.techniques[i];return r?new Promise(async(o,s)=>{let c=await jf(n,r.program),d=c?.fragmentShader,l=c?.vertexShader;if(!d||!l)return s();fn&&console.log("loadMaterial",t,c);let h={},u=r.uniforms;l.includes("_Time")&&(h._Time={value:new me.Vector4(0,0,0,0)});for(let y in u){let g=y;switch(g){case"_TimeParameters":let p=new me.Vector4;h[g]={value:p};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":h[g]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":h[g]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":h[g]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":h[g]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":h[g]={value:null};break}}let f=!1;if(t.extensions&&t.extensions[qo]){let y=t.extensions[qo];if(y.technique===i){fn&&console.log(t.name,"Material Properties",y);for(let g in y.values){let p=y.values[g];if(typeof p=="string"){if(p.startsWith("/textures/")){let m=p.substring(10),v=Number.parseInt(m);if(v>=0){let w=await this.parser.getDependency("texture",v);w&&(w.encoding=me.LinearEncoding,w.needsUpdate=!0),h[g]={value:w};continue}}switch(g){case"alphaMode":p==="BLEND"&&(f=!0);continue}}if(Array.isArray(p)&&p.length===4){h[g]={value:new me.Vector4(p[0],p[1],p[2],p[3])};continue}h[g]={value:p}}}}let x=new Gt(this.identifier,{name:t.name??"",uniforms:h,vertexShader:l,fragmentShader:d,lights:!1});switch(h._Cull?.value){case 0:x.side=me.DoubleSide;break;case 1:x.side=me.BackSide;break;case 2:x.side=me.FrontSide;break;default:x.side=me.FrontSide;break}x.transparent=f,f&&(x.depthWrite=!1),xd(h),x.onUpdateUniforms();for(let y in u){let g=y,p=u[y].type;if(h[g]?.value===void 0)switch(p){case 35678:h[g]={value:Mf},console.warn("Missing/unassigned texture, fallback to white: "+g);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+g,u[y]);break}}fn&&console.log(x.uuid,h),qf(x),o(x)}):null}};function qf(a){if(a.uniforms)for(let e in a.uniforms)Object.getOwnPropertyDescriptor(a,e)||Object.defineProperty(a,e,{get:()=>a.uniforms[e].value,set:t=>{a.uniforms[e].value=t,a.needsUpdate=!0}})}var Kn=Oe,El="$___Export_Components",_x="NEEDLE_components",jd=class{[Mr]},Bd=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},Xo=class{get name(){return _x}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let i=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(n,r)=>{try{this.serializeUserData(n,r),i(n,r)}finally{this.afterSerializeUserData(n,r)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let i=e.userData?.components;!i||i.length<=0||(delete e.userData.components,e[El]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Kn&&console.log("DONE",JSON.stringify(t)),e[El]===void 0)return;let i=e[El];delete e[El],i!==null&&(e.userData.components=i)}writeNode(e,t){let i=this.writer.json.nodes.length;console.log(e.name,i,e.uuid);let n=new Bd(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Kn&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,o=i.nodeIndex,s=n.userData?.components;if(!s||s.length<=0)continue;let c=new jd;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=o,this.context.objectToNode=this.objectToNodeMap;let d=[];for(let l of s){this.context.target=l;let h=Qe().writeBuiltinComponentData(l,this.context);h!==null&&d.push(h)}d.length>0&&(c[Mr]=d,Kn&&console.log("DID WRITE",n,"nodeIndex",o,d))}}beforeRoot(){return Kn&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,i=t?.extensions;if(!i)return;let n=i[this.name];Kn&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let o=t.json.nodes;for(let s=0;s<o.length;s++){let c=await t.getDependency("node",s);this.nodeToObjectMap[s]=c}for(let s=0;s<o.length;s++){let c=o[s],d=s,l=c.extensions;if(!l)continue;let h=l[this.name];if(!h)continue;Kn&&console.log("NODE",c);let u=this.nodeToObjectMap[d];if(!u){console.error("Could not find object for node index: "+d,c,t);continue}No(u),r.push(this.createComponents(u,h))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Mr];if(i){Kn&&console.log(e.name,i);for(let n in i){let r=i[n];Kn&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await So(this.parser,r),e.userData=e.userData||{},e.userData[Mr]=e.userData[Mr]||[],e.userData[Mr].push(r)}}}};import{EXRLoader as Ex}from"three/examples/jsm/loaders/EXRLoader";var Hd=D("debugexr"),Cl=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",Hd&&console.log(e)}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(Hd&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let o=r.extensions[t],s=new Ex(i.options.manager);return Hd&&console.log("EXT_texture_exr.loadTexture",o,s),i.loadTextureImage(e,o.source,s)}};var Xf="NEEDLE_gameobject_data",Tl=class{get name(){return Xf}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let i=0;i<this.parser.json.nodes.length;i++){let n=this.parser.json.nodes[i];if(n&&n.extensions){let r=n.extensions[Xf];if(r){let o=this.findAndApplyExtensionData(i,r);t.push(o)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){e.userData.layer=t.layers,e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};import{AmbientLight as Cx,Color as Qf,HemisphereLight as Tx}from"three";var Yf="NEEDLE_lighting_settings",Qo=D("debugenvlight"),Rl=class{get name(){return Yf}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Yf];if(i){Qo&&console.log(i);let n=k.addNewComponent(e.scene,Fd,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new Qf().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new Qf().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},Fd=class extends M{ambientMode=0;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=0;_hasReflection=!1;_ambientLightObj;_lightProbeObj;awake(){if(this.sourceId){let e=this.environmentReflectionSource===0?1:2,t=this.context.lightmaps.tryGet(this.sourceId,e,0);this._hasReflection=t!=null,t&&this.context.rendererData.registerReflection(this.sourceId,t)}Qo&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(Qo&&console.log("Enable scene lighting",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),e||Qo&&console.warn("This is no active?!",this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&!this._ambientLightObj&&(this._ambientLightObj=new Cx(this.ambientLight,Math.PI*this.ambientIntensity)),this._ambientLightObj&&this.gameObject.add(this._ambientLightObj),this._lightProbeObj&&this._lightProbeObj.removeFromParent();else if(this.ambientMode===1){if(this.ambientTrilight){let t=this.ambientTrilight[0],i=this.ambientTrilight[this.ambientTrilight.length-1],n=new Tx(i,t,this.ambientIntensity);this.gameObject.add(n)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._lightProbeObj?this.enabled&&this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj):this.sourceId&&this.context.rendererData.getSceneLightingData(this.sourceId).then(t=>{Qo&&console.log(t),t&&(this._lightProbeObj=t.lightProbe,this.enabled&&!this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj))});this.sourceId&&this.context.rendererData.enableReflection(this.sourceId)}onDisable(){Qo&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};import{NeverStencilFunc as Rx,LessStencilFunc as Sx,EqualStencilFunc as Px,LessEqualStencilFunc as Ox,GreaterStencilFunc as Ix,NotEqualStencilFunc as kx,GreaterEqualStencilFunc as Ax,AlwaysStencilFunc as Mx,ZeroStencilOp as Lx,KeepStencilOp as Dx,ReplaceStencilOp as jx,IncrementStencilOp as Bx,DecrementStencilOp as Hx,IncrementWrapStencilOp as Fx,DecrementWrapStencilOp as Nx,InvertStencilOp as zx}from"three";var Nd=D("debugstencil");function Ux(a,e){return(a&1<<e.layer)!=0}var zr=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(Nd&&console.log(t,zr.stencils),!t)return;let i=zr.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(Ux(r.layer,e)){Nd&&console.log(r);let o=e.sharedMaterial?.clone();o&&(e.sharedMaterial=o,e.gameObject.renderOrder=r.event*1e3+r.index*50,o.stencilWrite=!0,o.stencilWriteMask=255,o.stencilFuncMask=255,o.stencilRef=r.value,o.stencilFunc=r.compareFunc,o.stencilZPass=r.passOp,o.stencilFail=r.failOp,o.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Vx];if(i){Nd&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let o={...r};o.compareFunc=Gx(o.compareFunc),o.passOp=zd(o.passOp),o.failOp=zd(o.failOp),o.zFailOp=zd(o.zFailOp),zr.stencils[this.source]||(zr.stencils[this.source]=[]),zr.stencils[this.source].push(o)}}}return null}},Ur=zr;U(Ur,"stencils",{});function zd(a){switch(a){case 0:return Dx;case 1:return Lx;case 2:return jx;case 3:return Bx;case 4:return Hx;case 6:return Fx;case 7:return Nx;case 5:return zx}return 0}function Gx(a){switch(a){case 1:return Rx;case 2:return Sx;case 3:return Px;case 4:return Ox;case 5:return Ix;case 6:return kx;case 7:return Ax;case 8:return Mx}return 0}var Vx="NEEDLE_render_objects";import{TextureLoader as Wx}from"three";import{GLTFLoader as qx}from"three/examples/jsm/loaders/GLTFLoader";var Ud="NEEDLE_deferred_texture",dt=D("debugprogressive"),Vd=new Map,Gd=!1;dt&&window.addEventListener("keyup",a=>{a.key==="p"&&(Vd.forEach((e,t)=>{Object.entries(e).forEach(([i,n])=>{Gd?t[i]=n.lod0:t[i]=n.original,t.needsUpdate=!0})}),Gd=!Gd)});var Vs=class{static assignTextureLOD(e,t,i,n=0){if(!!i)for(let r of Object.keys(i)){let o=i[r];o?.isTexture===!0&&(dt&&console.log(`-----------
175
- `,"FIND",i.name,r,o?.name,o?.userData,o),Vs.getOrLoadTexture(e,t,i,r,o,n).then(s=>{if(s?.isTexture===!0&&(s.needsUpdate=!0,dt&&console.log("Assign LOD",i.name,r,s.name,s.guid,i,"Prev:",o,"Now:",s,`
176
- --------------`),i[r]=s,i.needsUpdate=!0,dt)){let c=Vd.get(i);c||(c={},Vd.set(i,c));let d=c[r];d||(d=c[r]={original:o,lod0:s}),d.lod0=s}}))}}get name(){return Ud}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return dt&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[Ud];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(o=>{dt&&console.log("register texture",o.name,o.uuid,n),o.userData.deferred=n,Vs.cache.set(o.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r,o){let s=r.uuid,c=Vs.cache.get(s);if(c){dt&&console.log(s,c.uri,c.guid);let d=wi(t,c.uri);if(d.endsWith(".glb")||d.endsWith(".gltf")){if(!c.guid)return console.warn("missing pointer for glb/gltf texture",c),null;let l=d+"_"+c.guid;if(this.resolved[l])return dt&&console.log("Texture has already been loaded: "+l,i.name,n,r.name),this.resolved[l];let h=new qx;Nr(h,e),dt&&console.log("Load "+d,i.name,n,c.guid);let u=await h.loadAsync(d),f=u.parser;dt&&console.log("Loading finished "+d,i.name,n,c.guid);let x=-1,b=!1;for(let g of u.parser.json.textures)if(x++,g?.extensions){let p=g?.extensions[Ud];if(p?.guid&&p.guid===c.guid){b=!0;break}}if(!b)return null;let y=await f.getDependency("texture",x);return y&&(y.guid=c.guid),this.resolved[l]=y,dt&&console.log(i.name,n,'change "'+r.name+'" \u2192 "'+y.name+'"',d,x,y,i,l),y}else{dt&&console.log("Load texture from uri: "+d);let h=await new Wx().loadAsync(d);return h&&dt?console.log(c,h):console.warn("failed loading",d),h}}else dt&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},mn=Vs;U(mn,"cache",new Map),U(mn,"resolved",{});function qd(a){let e=new Xo;return a.register(t=>(e.parser=t,e)),e}var Wd=class{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}};function Xd(a,e,t){a.register(n=>new Tl(n)),a.register(n=>new ua(n)),a.register(n=>new ml(n,e.lightmaps,t)),a.register(n=>new Rl(n,t,e)),a.register(n=>new _l(n,t)),a.register(n=>new Ur(n,t)),a.register(n=>new mn(n,t,e)),a.register(n=>new Cl(n));let i=a.setAnimationPointerResolver;typeof i=="function"&&i.bind(a)(new Wd)}import{Vector3 as Xx}from"three";var gn=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new Xx}update(){if(!this.from||!this.to)return;let e=X(this.from).clone(),t=X(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),se(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(X(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};P([S(k)],gn.prototype,"from",2),P([S(k)],gn.prototype,"to",2);var Ii=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};P([S()],Ii.prototype,"time",2),P([S()],Ii.prototype,"value",2),P([S()],Ii.prototype,"inTangent",2),P([S()],Ii.prototype,"inWeight",2),P([S()],Ii.prototype,"outTangent",2),P([S()],Ii.prototype,"outWeight",2),P([S()],Ii.prototype,"weightedMode",2);var Jn=class{keys;get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;let t=null;for(let i of this.keys){if(t&&i.time>e&&e>t.time)return J.lerp(t.value,i.value,(e-t.time)/(i.time-t.time));t=i}return this.keys[this.keys.length-1].value}};P([S(Ii)],Jn.prototype,"keys",2);import*as Jf from"three";import*as Ws from"three";import{PositionalAudioHelper as Qx}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var ht=D("debugaudio");var Le=class extends M{static get userInteractionRegistered(){return Le._didCallBeginWaitForUserInteraction||(Le._didCallBeginWaitForUserInteraction=!0,Le._beginWaitForUserInteraction()),Le._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Le._didCallBeginWaitForUserInteraction||(Le._didCallBeginWaitForUserInteraction=!0,Le._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Le._userInteractionRegistered){Le._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i);for(let n of this.callbacks)n();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(ht&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&Le._userInteractionRegistered){let e=k.getComponent(this.context.mainCamera,Vt)??k.findObjectOfType(Vt,this.context);e?.listener&&(this.sound=new Ws.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new Ws.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&Le._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Le._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Le._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,i)=>e*(1-i)+t*i;onLoaded(e){ht&&console.log("audio buffer loaded"),Le.registerWaitForAllowAudio(()=>{ht&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this.loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),ht&&console.log(this.name,this.shouldPlay,Le.userInteractionRegistered,this),this.shouldPlay&&Le._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(ht&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:break}this.spatialBlend>0?ht&&!this.helper&&(this.helper=new Qx(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(ht&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new Ws.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){ht&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,ht&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,ht&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){ht&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){ht&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,ht&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,ht&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},ae=Le;U(ae,"_didCallBeginWaitForUserInteraction",!1),U(ae,"callbacks",[]),U(ae,"_userInteractionRegistered",!1),P([S()],ae.prototype,"clip",2),P([S()],ae.prototype,"playOnAwake",2),P([S()],ae.prototype,"loop",1),P([S()],ae.prototype,"spatialBlend",1),P([S()],ae.prototype,"minDistance",1),P([S()],ae.prototype,"maxDistance",1),P([S()],ae.prototype,"volume",1),P([S()],ae.prototype,"rollOffMode",2);import*as bn from"three";import{Color as Yx}from"three";var ye=class extends Yx{alpha=1;get isRGBAColor(){return!0}constructor(e,t,i,n){super(e,t,i),this.alpha=n}clone(){let e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){let i=e;return i.alpha&&(this.alpha=J.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as Jx}from"three";var Kf=D("debugcam"),he=class extends M{get aspect(){return this._cam instanceof Jx?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._fov}set fieldOfView(e){let t=this._fov!=e;this._fov=e,t&&this._cam&&this._cam instanceof bn.PerspectiveCamera&&(this._cam.fov=this._fov,this._cam.updateProjectionMatrix())}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){let t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){let t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;_nearClipPlane=.1;_farClipPlane=1e3;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(!!e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}this.applyClearFlagsIfIsActiveCamera()}}_backgroundColor;_fov=60;_cam=null;_clearFlags=2;_skybox;get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name)}onEnable(){Kf&&console.log(this),this.buildCamera(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?t=this.gameObject:t=this.gameObject.children[0],t&&t.isCamera)t.type==="PerspectiveCamera"&&(t.fov=this._fov,t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new bn.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new bn.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(this._cam&&this.context.mainCameraComponent===this)switch(this._clearFlags){case 1:if(this.environmentIsTransparent()&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox();break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;this.environmentIsTransparent()&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}environmentIsTransparent(){let e=this.context.renderer.xr?.getSession();if(!e)return!1;let t=e.environmentBlendMode,i=t==="additive"||t==="alpha-blend";return t==="opaque"&&navigator.userAgent?.includes("OculusBrowser")&&this.context.xrSessionMode==="immersive-ar"?!0:i}enableSkybox(){this._skybox||(this._skybox=new Qd(this)),this._skybox.enable()}};P([S()],he.prototype,"fieldOfView",1),P([S()],he.prototype,"nearClipPlane",1),P([S()],he.prototype,"farClipPlane",1),P([S()],he.prototype,"clearFlags",1),P([S()],he.prototype,"orthographic",2),P([S()],he.prototype,"orthographicSize",2),P([S()],he.prototype,"ARBackgroundAlpha",2),P([S(ye)],he.prototype,"backgroundColor",1);var Qd=class{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?(Kf&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=bn.sRGBEncoding,this._skybox.mapping=bn.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};var Vt=class extends M{get listener(){return this._listener==null&&(this._listener=new Jf.AudioListener),this._listener}_listener=null;awake(){ae.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=k.getComponentInParent(this.gameObject,he);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as Zx}from"three/examples/jsm/loaders/GLTFLoader";import*as Sl from"three";var qs=D("debugavatar"),Zn=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(r=>r.layers.set(2))}},vn=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new Ge;i=k.instantiate(Bn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(qs&&console.log("[Custom Avatar] valid config",t,qs?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,qs?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(qs&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let n=await fetch("./"+t),r=null;if(n.ok){let s=await n.blob();s&&(r=await s.arrayBuffer())}return!r&&(r=await sl(t,t,0,"no url here go away",!0),!r)?null:(await Qe().parseSync(e,r,null,0))?.scene??null}let i=new Zx;return Nr(i,e),new Promise((n,r)=>{let o=this.avatarRegistryUrl+"/"+t;i.load(o,async s=>{await Qe().createBuiltinComponents(e,o,s,null,void 0),n(s.scene)},s=>{qs&&console.log("[Custom Avatar] "+s.loaded/s.total*100+"% loaded of "+s.total/1024+"kB")},s=>{console.error("[Custom Avatar] Error when loading: "+s),n(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]),r=this.findAvatarPart(i,["left","hand"]),o=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;let c=new Sl.Vector3;new Sl.Box3().setFromObject(n).getSize(c);let d=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+d+" meters! Should be < 0.3m"),d>.3&&n.scale.multiplyScalar(1/d*.3)}return new Zn(t,n,r,o)}findAvatarPart(e,t){let i=e.name.toLowerCase(),n=!0;for(let r of t){if(!n)break;i.indexOf(r)===-1&&(n=!1)}if(n)return e;if(e.children)for(let r of e.children){let o=this.findAvatarPart(r,t);if(o)return o}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as $x}from"three";var ki=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!_i)return;this._axes||(this._axes=new $x(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};P([S()],ki.prototype,"length",2),P([S()],ki.prototype,"depthTest",2),P([S()],ki.prototype,"isGizmo",2);import*as Zf from"three";var Gr=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=X(this.to).clone(),t=X(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let o=X(this.hint).clone();o.sub(r);let s=new Zf.Vector3;s.crossVectors(o,n),s.crossVectors(n,s),s.normalize();let c=i*.5,d=Math.max(this.desiredDistance,c),l=Math.sqrt(d*d-c*c),h=s.clone();h.multiplyScalar(l),h.add(r),se(this.gameObject,h);let u=r.clone();u.sub(s),this.gameObject.lookAt(u)}};import*as Vr from"three";import*as Ai from"three";var ew=new Ai.BoxGeometry(1,1,1);function Pl(a=null){let e=new Ai.Color(a??14540253),t=new Ai.EdgesGeometry(ew);return new Ai.LineSegments(t,new Ai.LineBasicMaterial({color:e}))}var iw=D("gizmos"),_t=class extends M{box=null;_lastMatrixUpdateFrame=-1;isInBox(e,t){if(!!e){if(this.box||(this.box=new Vr.Box3),e.type==="Mesh")_t.testBox.setFromObject(e);else if(e.type==="Group"){if(e.children.length>0){_t.testBox.setFromCenterAndSize(_t._position.set(0,0,0),_t._size.set(0,0,0));for(let i=0;i<e.children.length;i++)e.children[i].type==="Mesh"&&_t.testBox.expandByObject(e)}}else{let i=X(e,_t._position),n=Is(e,_t._size);t!==void 0&&n.multiplyScalar(t),_t.testBox.setFromCenterAndSize(i,n)}return this.box?.intersectsBox(_t.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new Vr.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){let t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;let i=t,n=X(this.gameObject,_t._position,i),r=Is(this.gameObject,_t._size);this.box.setFromCenterAndSize(n,r)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!iw&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Pl(e),this.gameObject.add(this._helper)}}},De=_t;U(De,"testBox",new Vr.Box3),U(De,"_position",new Vr.Vector3),U(De,"_size",new Vr.Vector3(.01,.01,.01));import*as Wr from"three";import{Vector3 as $f}from"three";var $n=class extends M{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?G.KINEMATIC:G.DYNAMIC)}get isKinematic(){return this._isKinematic}_isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;get body(){return this._body===null&&this.initialize(),this._body}_body=null;currentVelocity;_smoothedVelocity;lastWorldPosition;_ignoreChange=!1;_dirty=!1;_positionWatch;_matrixWatch;_setMatrix;constructor(){super(),this._setMatrix=new Wr.Matrix4}awake(){this._body=null,this.currentVelocity=new Wr.Vector3,this._smoothedVelocity=new Wr.Vector3,this.lastWorldPosition=X(this.gameObject).clone(),this._matrixWatch=void 0,this._positionWatch=void 0}onEnable(){this._body?this.context.physics.addBody(this.gameObject,this._body):this.initialize(),this.body&&(this.body.wakeUp(),this.gameObject.updateWorldMatrix(!0,!1),this.setBodyFromGameObject()),this._positionWatch||(this._positionWatch=new Hn(this.gameObject.position,["x","y","z"])),this._positionWatch.subscribeWrite(e=>{!this.context.physics.isUpdating&&!this._ignoreChange&&(this._dirty=!0,this._setMatrix.copy(this.gameObject.matrix),this._setMatrix.setPosition(this.gameObject.position))})}onDisable(){this._body&&this.context.physics.removeBody(this.gameObject,this._body,!1)}onDestroy(){this._body&&this.context.physics.removeBody(this.gameObject,this._body)}onBeforeRender(){this._ignoreChange=!0,this.updateVelocity(),this._dirty&&(this._dirty=!1,this._setMatrix.decompose(this.gameObject.position,this.gameObject.quaternion,this.gameObject.scale),this.setBodyFromGameObject()),this._ignoreChange=!1}initialize(){if(this._body)return;let e=new Qa;e.drag=this.drag,e.angularDrag=this.angularDrag,e.mass=this.mass,e.kinematic=this.isKinematic,e.physicsEvents=this.detectCollisions,e.sleepThreshold=this.sleepThreshold,this._body=this.context.physics.createBody(this.gameObject,e)}wakeUp(){this.body?.wakeUp()}applyForce(e,t){let i=new _(e.x,e.y,e.z);i.scale(1/this.context.time.deltaTime,i),this.body?.applyForce(i,t?new _(t.x,t.y,t.z):void 0)}setForce(e,t,i){this.body?.force.set(e,t,i)}getVelocity(){return this.body?$n.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):$n.tempPosition.set(0,0,0)}setVelocity(e,t,i){if(!!this.body){if(e instanceof $f){let n=e;e=n.x,t=n.y,i=n.z}this.body.velocity.x=e/this.context.time.deltaTime,this.body.velocity.y=t/this.context.time.deltaTime,this.body.velocity.z=i/this.context.time.deltaTime}}getTorque(){return this.body?$n.tempPosition.set(this.body?.torque.x,this.body?.torque.y,this.body?.torque.z):$n.tempPosition.set(0,0,0)}setTorque(e,t,i){if(!!this.body){if(e instanceof $f){let n=e;e=n.x,t=n.y,i=n.z}this.body.torque.x=e/this.context.time.deltaTime,this.body.torque.y=t/this.context.time.deltaTime,this.body.torque.z=i/this.context.time.deltaTime}}get smoothedVelocity(){return this._smoothedVelocity}setAngularVelocity(e,t,i){!this.body||(this.body.angularVelocity.x=e/this.context.time.deltaTime,this.body.angularVelocity.y=t/this.context.time.deltaTime,this.body.angularVelocity.z=i/this.context.time.deltaTime)}setBodyFromGameObject(e=null){if(this.body&&this.gameObject&&!this.destroyed){this._ignoreChange=!0;let t=this.worldPosition;this.body.position.set(t.x,t.y,t.z);let i=this.worldQuaternion;if(this.body.quaternion.set(i.x,i.y,i.z,i.w),e){$n.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp($n.copyVector3,this.context.time.deltaTime/.1);let n=this._smoothedVelocity;this.body.velocity.x=n.x,this.body.velocity.y=n.y,this.body.velocity.z=n.z}this._ignoreChange=!1}}updateVelocity(){if(!!this.currentVelocity&&this.body&&this.gameObject){let e=X(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},oe=$n;U(oe,"tempPosition",new Wr.Vector3),U(oe,"copyVector3",new Wr.Vector3),P([S()],oe.prototype,"mass",2),P([S()],oe.prototype,"isKinematic",1),P([S()],oe.prototype,"drag",2),P([S()],oe.prototype,"angularDrag",2),P([S()],oe.prototype,"detectCollisions",2),P([S()],oe.prototype,"sleepThreshold",2);import{Vector3 as Yo}from"three";var Yd=class{getCollider(e){return pn(e,Wt)}};af(new Yd);var Wt=class extends M{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(oe))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(oe))}onDisable(){this._shape}};P([S(oe)],Wt.prototype,"attachedRigidbody",2),P([S()],Wt.prototype,"isTrigger",2);var yn=class extends Wt{radius=.5;center=new Yo(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};P([S()],yn.prototype,"radius",2),P([S(Yo)],yn.prototype,"center",2);var xn=class extends Wt{size=new Yo(1,1,1);center=new Yo(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};P([S(Yo)],xn.prototype,"size",2),P([S(Yo)],xn.prototype,"center",2);var Et=class extends M{canGrab=!0;onPointerClick(e){}},Ct=class extends M{isUsed=!0;usedBy=null};var er=class extends De{},qr=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=k.findObjectsOfType(er,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(k.getComponentInParent(this.gameObject,Ct)||jo(this.gameObject,this.context.connection))}}};var tr=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||k.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:nw()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};P([S()],tr.prototype,"visibleOn",2);var Ol;function nw(){if(Ol===!0||Ol===!1)return Ol;let a=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(a=!0)}(navigator.userAgent||navigator.vendor||window.opera),Ol=a,a}import*as wn from"three";var Se=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Ko=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Se).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Se).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Se).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,o,s,c,d,l){return e.prep(4,36),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(s),e.writeFloat32(o),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var qt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new qt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new qt).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){let t=this.bb.__offset(this.bb_pos,8);return t?(e||new Ko).__init(this.bb_pos+t,this.bb):null}dontSave(){let e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}};var ir=D("debugsync"),Jo="STRS";Go(Jo,qt.getRootAsSyncedTransformModel);var Mi=new yt;function Kd(a,e,t=!0){Mi.clear();let i=Mi.createString(a);qt.startSyncedTransformModel(Mi),qt.addGuid(Mi,i),qt.addFast(Mi,t);let n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;qt.addTransform(Mi,Ko.createTransform(Mi,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));let s=qt.endSyncedTransformModel(Mi);return Mi.finish(s,Jo),Mi.asUint8Array()}var ut=class extends M{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){ir&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){ir&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new wn.Vector3,this._targetRotation=new wn.Quaternion,this.lastWorldPos=new wn.Vector3,this.lastWorldRotation=new wn.Quaternion,this.rb=k.getComponentInChildren(this.gameObject,oe),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Wn(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(Jo,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Hp(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(Jo,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new wn.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){ir&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){re.markDirty(this.gameObject,!0);let i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));let n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Op(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastWorldPos;lastWorldRotation;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){ir&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),o=t.angleTo(this.lastWorldRotation),s=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>s||o>s)&&(this._model.hasOwnership?this._needsUpdate=!0:(ir&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),re.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let o=this._receivedFastUpdate||this.fastMode?.5:.3,s=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,o),this.worldPosition=c,s=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,o),this.worldQuaternion=c,s=!0}s&&re.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject());return}this.rb&&(this._wasKinematic!==void 0&&(ir&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new wn.Vector3(0,0,0))>1e3&&(ir&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let i=10,n=this.rb||this.fastMode;if(this._needsUpdate&&(i<=0||i>0&&this.context.time.frameCount%i===0||n)){ir&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb&&this.rb.setBodyFromGameObject(),this._needsUpdate=!1;let r=Kd(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as ee from"three";import{Euler as Pw,EventDispatcher as Ow,Group as Iw,Matrix4 as cm,Mesh as kw,MeshBasicMaterial as Aw,Object3D as Mw,Quaternion as sh,RingGeometry as Lw,Vector3 as dm}from"three";var Il=class{static createButton(e,t={}){let i=document.createElement("button");function n(){if(t.domOverlay===void 0){var c=document.createElement("div");c.style.display="none",document.body.appendChild(c);var d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("width",38),d.setAttribute("height",38),d.style.position="absolute",d.style.right="20px",d.style.top="20px",d.addEventListener("click",function(){h.end()}),c.appendChild(d);var l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),l.setAttribute("stroke","#fff"),l.setAttribute("stroke-width",2),d.appendChild(l),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:c}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let h=null;async function u(x){x.addEventListener("end",f),await e.xr.setSession(x),i.textContent="STOP AR",t.domOverlay.root.style.display="",h=x}function f(){h.removeEventListener("end",f),i.textContent="START AR",t.domOverlay.root.style.display="none",h=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="START AR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){h===null?navigator.xr.requestSession("immersive-ar",t).then(u):h.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="AR NOT SUPPORTED"}function s(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?n():o()}).catch(o),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",s(c),c}}};var kl=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let i=document.createElement("button");function n(){let c=null;async function d(h){h.addEventListener("end",l),await e.xr.setSession(h),i.textContent="EXIT VR",c=h}function l(){c.removeEventListener("end",l),i.textContent="ENTER VR",c=null}i.style.display="",i.style.cursor="pointer",i.style.left="calc(50% - 50px)",i.style.width="100px",i.textContent="ENTER VR",i.onmouseenter=function(){i.style.opacity="1.0"},i.onmouseleave=function(){i.style.opacity="0.5"},i.onclick=function(){if(c===null){let h={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",h).then(d)}else c.end()}}function r(){i.disabled=!0,i.style.display="",i.style.cursor="auto",i.style.left="calc(50% - 75px)",i.style.width="150px",i.onmouseenter=null,i.onmouseleave=null,i.onclick=null}function o(){r(),i.textContent="VR NOT SUPPORTED"}function s(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",s(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():o(),kl.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),i.click())}),i;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",s(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),kl.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},$o=kl;U($o,"xrSessionIsGranted",!1);$o.registerSessionGrantedListener();import*as Al from"three";var em=ca(el(),1);import{AudioAnalyser as rw}from"three";var es="noVoip",pt=D("debugvoip"),ow=D("voip");var Jd=class{id;constructor(e){this.id=e}};var Zd=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,i,n){this.voip=e,this.peer=t,this.userId=i,this.peerId=n}close(){pt&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let i of t)i.enabled=!e}async startVoipCall(){if(!await Ke.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}pt&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),pt&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{pt&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(i){i.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){pt&&console.log("call closed",e)}},$d=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,i){this.voip=e,this.obj=t,this.call=i}openAudioStream(e){let t=e.getAudioTracks();for(let i of t)if(i.kind==="audio"&&i.readyState==="live"){this.open(i);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,ae.userInteractionRegistered||pt&&console.log("Incoming call, waiting for user interaction before opening audio"),ae.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){pt&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Al.AudioListener;this.audio=new Al.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(n=>{if(!!i){console.log(n);for(let r of n)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),pt&&console.log("call is setup, you should hear something now"),this.analyzer=new rw(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},Ke=class extends M{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let i in this.currentIncomingCalls)this.currentIncomingCalls[i]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let i in this.currentIncomingCalls){let n=this.currentIncomingCalls[i];if(n&&n.currentAnalyzer)return n.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(D(es)){console.log("VOIP is disabled by url parameter: "+es);return}if(this.requireParam&&!ow){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new em.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let i=new Zd(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=i,i.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,i=this.connections[t];this.connections[t]=null,i&&i.close();let n=this.currentIncomingCalls[t];pt&&console.log("UserLeftRoom",e,t,n),n&&(n.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){pt&&console.log("Peer connection established and received id"),this.model=new Jd(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){pt&&console.log("CONNECTION",t),t.on("data",function(i){pt&&console.log("Received",i)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:i}=t,{peer:n}=e,r=this.currentIncomingCalls[i];if(r&&r.close(),pt&&console.log("received call"),await Ke.HasMicrophonePermissions()){let o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(o)}else e.answer(null);this.currentIncomingCalls[i]=new $d(this,this.gameObject,e),e.on("stream",o=>{pt&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(o)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};import{Matrix4 as Xs}from"three";var Tt=class extends M{webAR=null;get rig(){return this.webAR?.webxr.Rig}invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_initalMatrix=new Xs;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=k.findObjectOfType(Y);e&&(e.Rig.updateMatrix(),this._initalMatrix.copy(e.Rig.matrix))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;_rigStartPose=null;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=this.rig?.matrix.clone(),e.addEventListener("selectstart",this._selectStartFn),e.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale))}onUpdate(e,t,i){return i&&!this._placementPose&&this._isTouching?(this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(e,new Xs().fromArray(i.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new Xs),this._placementPose.copy(t),e){if(this.invertForward){let i=new Xs().makeRotationY(Math.PI);this._placementPose.premultiply(i)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),e&&(e.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(e.position,e.quaternion,e.scale)),re.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(this._rigStartPose||(this._rigStartPose=t.matrix.clone()),t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new Xs().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};P([S()],Tt.prototype,"invertForward",2),P([S()],Tt.prototype,"arScale",1);import{BoxHelper as pw,BufferGeometry as fw,Color as sm,Euler as mw,Layers as gw,Line as bw,Mesh as vw,MeshBasicMaterial as yw,Quaternion as Dl,Ray as xw,SphereGeometry as ww,Vector2 as _w,Vector3 as ci}from"three";import{OculusHandModel as Ew}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Cw}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import{XRControllerModelFactory as Tw}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import*as nm from"three";import{Quaternion as sw,Vector3 as Ml}from"three";var ts=D("debugflags");var eh=class{Mask=17;Has(e){let t=this.Mask&e;return ts&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,we.Apply()}Enable(e){this.Mask|=e,we.Apply()}Disable(e){this.Mask&=~e,we.Apply()}Toggle(e){this.Mask^=e,we.Apply()}EnableAll(){this.Mask=-1,we.Apply()}DisableAll(){this.Mask=0,we.Apply()}},ft=eh;U(ft,"Global",new eh);var Li=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(ft.Global)}awake(){Li.registry.push(this)}onEnable(){Li.firstApply||(Li.firstApply=!0,Li.Apply())}onDestroy(){let e=Li.registry.indexOf(this);e>=0&&Li.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,i=e;i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),ts&&console.log(i),Li.buffer.Mask=i,e=Li.buffer);let n=e;if(n?(ts&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(ts&&console.log("use global mask"),ft.Global.Has(this.visibleIn)),t!==void 0)if(t)ts&&console.trace("is visible",this.name,this.gameObject.uuid),k.setActive(this.gameObject,!0);else{if(ts&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},we=Li;U(we,"registry",[]),U(we,"firstApply"),U(we,"buffer",new ft);import{Object3D as th}from"three";var nr=D("debugavatar"),ai=class extends M{static getAvatar(e){return e>=0&&e<ai.instances.length?ai.instances[e]:null}static onAvatarMarkerCreated(e){return ai._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return ai._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){ai.instances.push(this),nr&&console.log(this);for(let e of ai._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){ai.instances.splice(ai.instances.indexOf(this),1);for(let e of ai._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):k.setActive(this.avatar,e))}},ue=ai;U(ue,"instances",[]),U(ue,"_onNewAvatarMarkerAdded",[]),U(ue,"_onAvatarMarkerDestroyed",[]);var Qs=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}get isWebXRAvatar(){return!0}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new Ml(1,1,1);handLeftScale=new Ml(1,1,1);handRightScale=new Ml(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,i){this.context=e,this.guid=t,this.webxr=i,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new th;_handLeftTarget=new th;_handRightTarget=new th;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){let i=this.webxr.IsInAR?"handheld":"headset",n=this.head;this.context.players.setPlayerView(e.guid,n,i),re.markDirty(this.head),this._canInterpolate=!0;let r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){let o=this.isLocalAvatar?this.handLeft:this._handLeftTarget;o.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),o.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),o.quaternion.multiply(Qs.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handLeftScale),re.markDirty(this.handLeft)}if(this.handRight){let o=this.isLocalAvatar?this.handRight:this._handRightTarget;o.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),o.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),o.quaternion.multiply(Qs.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handRightScale),re.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){nr&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&xe.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&k.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(nr&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&xe.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;k.setActive(n,!1),e=k.instantiate(n),k.setActive(e,!0)}nr&&console.log(e);let i=await Qs.loader.getOrCreateNewAvatarInstance(this.context,e);if(nr&&console.log(i,i?.isValid,this.lastAvatarId,e),i?.isValid){if(this.root=i.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=k.addNewComponent(this.root,ue),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==i.head&&this.head?.removeFromParent(),this.head=i.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&xe.Add(this.context,this.head,this.avatarMarker),i.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=i.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),i.rigthHand&&this.handRight?.removeFromParent(),this.handRight=i.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...k.getComponentsInChildren(this.root,we)),this.flags.length<=0&&this.head){let n=k.addNewComponent(this.head,we);n.visibleIn=20,this.flags.push(n),nr&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return nr&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return nr&&console.warn("build avatar failed"),!1}},Rt=Qs;U(Rt,"loader",new vn),U(Rt,"invertRotation",new sw().setFromAxisAngle(new Ml(0,1,0),Math.PI));var xe=class{static Add(e,t,i=null){if(!!t){for(let n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??K.Current?.time.time;return}}}};U(xe,"Pois",[]),U(xe,"LastChangeTime",0);var ih=class{guid;position=new nm.Vector3},Di=class extends M{set controlledTarget(e){this.target=e;let t=j.get("MoveRandom");if(t&&this.target){let i=k.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new ih;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=k.getComponentInParent(this.gameObject,ue),this.avatar){let e=k.getComponentInParent(this.gameObject,ue);this._model=new Wn(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&se(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(xe.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=xe.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=X(this._currentTargetObject);se(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let t=xe.Pois;if(t.length>0){let i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}};import*as Ll from"three-mesh-ui";import{OrbitControls as lw}from"three/examples/jsm/controls/OrbitControls";import{Object3D as aw}from"three";var ji=class extends M{constraintActive=!0;locked=!1;sources=[]};P([S(aw)],ji.prototype,"sources",2);import*as Ys from"three";var rm=D("nocamlimits"),Je=class extends M{get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoRotate=!1;autoRotateSpeed=1;enableKeys=!0;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;middleClickToFocus=!0;doubleClickToFocus=!0;useSlerp=!1;debugLog=!1;targetLerpSpeed=5;_lookTargetPosition;_controls=null;_cameraObject=null;_lerpToTargetPosition=!1;_lerpCameraToTarget=!1;_cameraTargetPosition=null;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;awake(){this._lookTargetPosition=new Ys.Vector3,this._startedListeningToKeyEvents=!1}onEnable(){this._enableTime=this.context.time.time;let t=k.getComponent(this.gameObject,he)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new lw(t,this.context.renderer.domElement)),this._controls&&(this._controls.enableDamping=this.enableDamping,this._controls.enableKeys=this.enableKeys,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,t?.type==="PerspectiveCamera"?rm||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):rm||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body)))}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}onDestroy(){this._controls?.dispose()}start(){if(this._controls){let e=k.getComponent(this.gameObject,he);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");let t=new Ys.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new Te;e.screenPoint=new Ys.Vector2(0,0),e.lineThreshold=.1;let t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){if(!this._controls)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3,e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){let t=this.context.time.deltaTime*this.targetLerpSpeed;this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject&&(this.useSlerp&&typeof this._cameraObject?.position.slerp=="function"?(this._cameraObject?.position).slerp(this._cameraTargetPosition,t):this._cameraObject?.position.lerp(this._cameraTargetPosition,t),this._cameraObject.position.distanceTo(this._cameraTargetPosition)<.01&&(this._lerpCameraToTarget=!1)),this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<.005&&(this._lerpToTargetPosition=!1))}this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!0,this._controls.update())}setCameraTarget(e,t=!1){e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&this.controllerObject?.position.copy(this._cameraTargetPosition)):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){if(!this._controls)return!1;let i=this.lookAtConstraint?.sources;if(i&&i.length>0){let n=i[e];if(n)return n.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,t),!0}return!1}setTarget(e=null,t=!1){!this._controls||(e!==null&&this._lookTargetPosition.copy(e),t?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(e,t){!this._controls||this._controls.target.lerp(e,t)}distanceToTarget(e){return this._controls?this._controls.target.distanceTo(e):-1}setTargetFromRaycast(){if(!this.controls)return;let e=this.context.physics.raycast();for(let t of e)if(t.distance>0&&k.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=X(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};P([S(ji)],Je.prototype,"lookAtConstraint",2);var Xt=class{used=!1;Use(){this.used=!0}StopPropagation(){this.event?.stopImmediatePropagation()}inputSource;object;isDown;isUp;isPressed;isClicked;event;constructor(e){this.event=e}};import{Object3D as dw}from"three";var hw=D("debugeventsystem"),Bi=class extends M{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Bi.systems.length<=0&&Bi.systems.push(...k.findObjectsOfType(Bi,e)));for(let i of Bi.systems)if(i.context===e)return;let t=new dw;k.addNewComponent(t,Bi),e.scene.add(t)}static ensureUpdateMeshUI(e,t){li.update(e,t)}static markUIDirty(e){li.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Bi.systems.push(this)}onDestroy(){Bi.systems.splice(Bi.systems.indexOf(this),1)}start(){}register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){let t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}_selectStartFn;_selectEndFn;_selectUpdateFn;onEnable(){let e=new Map;this._selectStartFn??=(i,n)=>{if(!n.grab)return;li.resetLastSelected();let r=new Xt;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=!1,e.set(i,n.grab),n.grab&&!this.handleEvents(n.grab,r)&&(n.grab=null)},this._selectEndFn??=(i,n)=>{if(!n.grab)return;let r=new Xt;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=i.selectionClick,this.handleEvents(n.grab,r);let o=e.get(i);if(e.set(i,null),o)for(let s=0;s<this.raisedPointerDownEvents.length;s++){let c=this.raisedPointerDownEvents[s];this.raisedPointerDownObjects[s]===o&&c&&(c.onPointerUp?.call(c,r),this.raisedPointerDownEvents.splice(s,1),this.raisedPointerDownObjects.splice(s,1),s--)}};let t=new Te;this._selectUpdateFn??=i=>{t.ray=i.getRay();let n=this.performRaycast(t);if(!n)return;let r=new Xt;r.inputSource=i,this.handleIntersections(n,r)},ie.addEventListener("select-start",this._selectStartFn),ie.addEventListener("select-end",this._selectEndFn),ie.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){ie.removeEventListener("select-start",this._selectStartFn),ie.removeEventListener("select-end",this._selectEndFn),ie.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];raisedPointerDownObjects=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),Y.IsInWebXR||this.context.input.isKeyPressed("Alt"))return;if(!this._didMove){let r=this.context.input.getPointerPositionRC(0);if(r&&r.x===0&&r.y===0)return;this._didMove=!0}let e=this.performRaycast(null),t=new Xt(this.context.input.getPointerEvent(0));if(t.inputSource=this.context.input,t.isClicked=this.context.input.mouseClick,t.isDown=this.context.input.mouseDown,t.isUp=this.context.input.mouseUp,t.isPressed=this.context.input.mousePressed,this.lastPointerEvent=t,!e)return;let i=null,n=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(i=k.getComponent(this.context.mainCameraComponent.gameObject,Je)??null,i&&(n=i.enabled,i.enabled=!1)),this.handleIntersections(e,t),i&&(this.orbitControl=i,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=k.getComponentsInParent(t,M,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let n=0;n<i.length;n++){let r=i[n];if(!r.gameObject||r.destroyed)continue;let o=r;o.onPointerExit&&o.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let i=t.performRaycast(e);i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let i of e){let{object:n}=i;if(this.handleEvents(n,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&hw&&console.log("not allowed",e),!1;let i=e;t.object=e,this.lastPointerEvent=t;let n=e.parent,r=!1,o=t.isClicked??!1,s=null;if(n&&n.isUI){let c=(t.isPressed||t.isClicked)??!1;if(n[St]){let d=n[St].gameObject;if(d){if(!Qt.isInteractable(d,this.out))return this.out.canvasGroup?.interactable??!1;s=this.out.canvasGroup??null;let h=this.handleMeshUIIntersection(e,c);e=d,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(n,c))return!0}if(this.objectsHoveredThisFrame.push(e),s===null||s.interactable){let c=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let d=k.getComponentsInParent(e,M,this.handleEventsArray);for(let l=0;l<d.length;l++){if(t.used)return!0;if(d[l].destroyed)continue;let h=d[l];h.interactable!==!1&&(h.onPointerEnter&&(c||h.onPointerEnter(t)),t.isDown&&h.onPointerDown&&!this.raisedPointerDownEvents.includes(h)&&(h.onPointerDown(t),this.raisedPointerDownEvents.push(h),this.raisedPointerDownObjects.push(i)),t.isUp&&h.onPointerUp&&h.onPointerUp(t),t.isClicked&&h.onPointerClick&&h.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=li.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&li.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];li.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?k.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},Ve=Bi;U(Ve,"didSearchEventSystem",!1),U(Ve,"systems",[]);var li=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let i of this.lastUpdateFrame)if(i.context===t){if(t.time.frameCount===i.frame)return;i.frame=t.time.frameCount,(this.needsUpdate||t.time.frameCount<30)&&(this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:t.time.frameCount}],e.update()}static updateState(e,t){let i=null;if(e&&(i=this.findBlockInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;t?(this.lastSelected=i,i.states.pressed&&i.setState("pressed")):i.states.hovered&&i.setState("hovered"),this.needsUpdate=!0}return i}static resetLastSelected(){let e=this.lastSelected;!e||(this.lastSelected=null,this.resetState(e))}static resetState(e){if(!e)return;e.interactable===!1?e.states.disabled&&e.setState("disabled"):e===this.lastSelected&&e.states.selected?e.setState("selected"):e.setState("normal"),this.needsUpdate=!0}static findBlockInParent(e){return e?e.isBlock&&Object.keys(e.states).length>0?e:this.findBlockInParent(e.parent):null}};U(li,"lastSelected",null),U(li,"lastUpdateFrame",[]),U(li,"needsUpdate",!1);import{AxesHelper as uw}from"three";var is="./include";Ll.Block.prototype.interactable={get(){return this.interactive},set(a){this.interactable=a}};var St=Symbol("shadowDomOwner"),je=class extends M{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Ve.markUIDirty(this.context)}shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=k.getComponentInParent(this.gameObject,Hi)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=k.getComponentInParent(i,je),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[St]=this,e.traverse(r=>{r[St]===void 0&&(r[St]=this)});let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&(r?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),_i&&e.add(new uw(.5)),this.onAfterAddedToScene(),n&&Ll.update()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e[St]===t){i(e);for(let n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},Hi=class extends je{awake(){super.awake()}};var Qt=class{static getObject(e){let t=e[St];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;let i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;let n=Ht(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),n?.raycastTarget!==!1}static tryFindCanvasGroup(e){if(!e)return null;let t=Ht(e,i=>{let n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}};var Ks=D("debugwebxrcontroller");var rr=class extends M{},Be=class extends M{static CreateRaycastLine(){let e=new bw(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new ww(.5,22,22),t=new yw({color:this.raycastColor}),i=new vw(e,t);return i.visible=!1,i.layers.set(2),i}static Create(e,t,i,n){let r=i?k.addNewComponent(i,Be,!1):new Be;r.webXR=e,r.index=t,r.type=n;let o=e.context;r.controller=o.renderer.xr.getController(t),r.controllerGrip=o.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=o.renderer.xr.getHand(t);let s=new Ew(r.hand);return r.webXR.handModelPath&&r.webXR.handModelPath!==""&&(s.path="/"+wi(e.sourceId,r.webXR.handModelPath)),r.hand.add(s),r.hand.traverse(c=>c.layers.set(2)),r.handPointerModel=new Cw(r.hand,r.controller),r.controller.addEventListener("connected",c=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",c=>{if(c.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(h=>h.layers.set(2)),r.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let l=r.hand.joints;if(l)for(let h of Object.keys(l)){let u=l[h];u.parent||r.hand.add(u)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}static removeEventListener(e,t){if(!t)return;let i=this.eventSubs[e]??[],n=i.indexOf(t);n>=0&&i.splice(n,1),this.eventSubs[e]=i}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new Dl),Ie(e).multiply(this._wristQuaternion.setFromEuler(new mw(-Math.PI/4,0,0)))):null}movementVector=new ci;worldRot=new Dl;joystick=new _w;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=null;get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=Be.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Be.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),Ks&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new Dl;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Be.eventSubs["update"];if(e&&e.length>0)for(let n of e)n(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(Ie(this.controller),this.useSmoothing?t:1);let i=X(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,se(this.raycastLine,i);let n=this.hand.joints;if(n&&n.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let o=this.getWristQuaternion();o&&this.rayRotation.copy(o)}$e(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,$e(this.raycastLine,this.rayRotation),se(this.raycastLine,i);this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let i=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let n=3*Be.MovementSpeedFactor,r=2,o=J.clamp01(this.joystick.length()*2),s=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=s,c*=o;let d=this.joystick.y>0?1:-1,l=Math.pow(this.joystick.y,r);l*=d,c*=o,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,l),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(n*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let h=this.joystick.x,u=Math.abs(h);if(u<.4)this.didRotate=!1;else if(u>.5&&!this.didRotate){let f=h>0?-1:1;t.rotateY(J.toRadians(30*f)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let s=this.handPointerModel.isPinched();s&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),s&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),s||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let n=i>.5&&this.webXR.IsInVR,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,o=null;if(t&&this.input&&!this.input.hand)for(let s=0;s<t.length;s++){let c=t[s];if(s===4)if(c.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),o=1,Be.MovementSpeedFactor=1;let l=this.context.mainCamera;Be.PreviousCameraFarDistance&&(l.far=Be.PreviousCameraFarDistance)}else{r=!0,n=!0,o=.1,Be.MovementSpeedFactor=o*2;let l=this.context.mainCamera;Be.PreviousCameraFarDistance=l.far,l.far/=o}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let s=this.raycast();if(this.didTeleport=!0,s&&s.length>0){let c=s[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;se(e,d)}}}}else i<.1&&(this.didTeleport=!1);o!==null&&(e.scale.set(o,o,o),e.updateMatrixWorld())}isValidTeleportTarget(e){return k.getComponentInParent(e,rr)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let i=1;if(this.webXR.Rig&&(i/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=i*(this.lastHit?.distance??9999);let n=this.raycastLine.material;t!=null?n.color=Be.raycastColor:n.color=Be.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=J.clamp(this.lastHit.distance*.01*i,.015,.1);this._raycastHitPoint.scale.set(n,n,n)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),Ks&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(let i of e){let n=i.object;this.lastSelectStartObject=n;let r={selected:n,grab:n},o=Be.eventSubs["select-start"];if(o&&o.length>0)for(let s of o)s(this,r);r.grab!==n&&Ks&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=it.TryTake(this,r.grab,i,t));break}else{let i=Be.eventSubs["select-start"],n={selected:null,grab:null};if(i&&i.length>0)for(let r of i)r(this,n)}}_didNotEndSelection=!1;onSelectEnd(){if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=Be.eventSubs["select-end"];if(t&&t.length>0)for(let i of t)i(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return!(!e||k.isActiveInHierarchy(e)===!1||Qt.isInteractable(e)===!1)}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let i of e.children)this.grabbed?.selected===i||this.grabbed?.selectedMesh===i||this.setControllerLayers(i,t)}getRay(){let e=new xw;return e.origin.copy(X(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}closeGrabBoundingBoxHelper;overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Ks&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new pw(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;let t=X(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new Te;e.layerMask=new gw,e.layerMask.set(0),e.layerMask.disable(2),e.ray=this.getRay();let t=this.context.physics.raycast(e);for(let i=0;i<t.length;i++){let n=t[i],r=n.object;if(!this.testIsVisible(r)){t.splice(i,1),i--;continue}n.object=Qt.getObject(r);break}return t}},ie=Be;U(ie,"Factory",new Tw),U(ie,"raycastColor",new sm(.9,.3,.3)),U(ie,"raycastNoHitColor",new sm(.6,.6,.6)),U(ie,"geometry",new fw().setFromPoints([new ci(0,0,0),new ci(0,0,-1)])),U(ie,"handModels",{}),U(ie,"eventSubs",{}),U(ie,"PreviousCameraFarDistance"),U(ie,"MovementSpeedFactor",1);var tt=class{static AddEventListener(e,t){return tt.Events[e]||(tt.Events[e]=[]),tt.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!tt.Events[e])return;let i=tt.Events[e].indexOf(t);i>=0&&tt.Events[e].splice(i,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,i,n){let r=k.getComponentInParent(t,Et);if(r)t=r.gameObject;else return Ks&&console.warn("Prevented taking object that is not interactable",t),null;let o=t,s=k.getComponentInParent(t,ut);s&&(s.requestOwnership(),o=s.gameObject);for(let d of this.Current)if(d.selected===o)return d.controller===e||(d.free(),d.Take(e,o,t,s,r,i,n)),d;let c=new tt;return c.Take(e,o,t,s,r,i,n),c}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,i,n,r,o,s){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=s?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};tt.Events.WillTake?.forEach(f=>f(this,c));let d=i;d?.material&&(this.originalMaterial=d.material,Array.isArray(d.material)||(d.material=d.material.clone(),d.material&&d.material.emissive&&(d.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=d,this.controller=e,this.interactable=r,this.isCloseGrab=s,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=k.addNewComponent(this.selected,Ct),this.rigidbodies=k.getComponentsInChildren(this.selected,oe),X(this.positionSource,this.lastControllerWorldPos);let l=()=>s?this.lastControllerWorldPos.clone():o.point.clone();this.grabDistance=l().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(l());let h=e.isUsingHands&&s?this.controller.getWristQuaternion().clone():e.rayRotation.clone();Ie(this.selected,this.localQuaternionToGrab).premultiply(h.invert());let u=this.controller.webXR.Rig;return u&&this.rigPositionLastFrame.copy(X(u)),xe.Add(e.context,this.selected),tt.Register(this),this.sync&&(this.sync.fastMode=!0),tt.Events.DidTake?.forEach(f=>f(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};tt.Events.WillFree?.forEach(n=>n(this,e)),xe.Remove(this.controller.context,this.selected),tt.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let i=this.selected;if(this.didReparent&&i.parent){let n=this.selectedParent;n?n.attach(i):this.controller?.context.scene.attach(i)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let n of this.rigidbodies)n.wakeUp(),n.smoothedVelocity&&n.setVelocity(n.smoothedVelocity.x,n.smoothedVelocity.y,n.smoothedVelocity.z);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,tt.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new ci;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new ci;localQuaternionToGrab=new Dl(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new ci;controllerWorldPos=new ci;lastControllerWorldPos=new ci;controllerPosDelta=new ci;totalChangeAlongDirection=0;rigPositionLastFrame=new ci;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),X(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let i=X(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new ci),this.targetDir.set(0,0,-this.grabDistance*t);let i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),n=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=n.clone()),this.quaternionLerp.slerp(n,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),$e(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(X(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),se(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});re.markDirty(this.selected,!0)}}},it=tt;U(it,"Events",{}),U(it,"Current",[]);var _n=class extends M{awake(){}};import{Quaternion as Js,Vector3 as jl,Vector4 as Rw}from"three";var Fi=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,i,n,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Ae=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new Ae).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Ae).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Se).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Fi).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new Se).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Se).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new Fi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new Fi).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}};var am=D("debugxr"),Zs=D("debugavatar");var oh="VRUS";Go(oh,Ae.getRootAsVrUserStateBuffer);function rh(){return new Date().getTime()}function Sw(a){let e=a&4294967295,t=a/Math.pow(2,32)&1048575;return Xe.create(e,t)}var $s=class{guid;time;avatarId;position=new jl;rotation=new Rw;scale=1;posLeftHand=new jl;posRightHand=new jl;rotLeftHand=new Js;rotRightHand=new Js;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=rh(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=$s.quat0,s=$s.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,$s.invertRotation),e&&(e.getWorldQuaternion(s),o.multiplyQuaternions(s,o)),this.rotation.set(o.x,o.y,o.z,o.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=n.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),n.LeftController?.hand?.visible){let l=n.LeftController.wrist;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand))}if(n.RightController?.hand?.visible){let l=n.RightController.wrist;l&&(l.getWorldPosition(this.posRightHand),l.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let i=e.createString(this.guid),n=e.createString(this.avatarId);Ae.startVrUserStateBuffer(e),Ae.addGuid(e,i),Ae.addTime(e,Sw(this.time)),Ae.addAvatarId(e,n),Ae.addPosition(e,Se.createVec3(e,this.position.x,this.position.y,this.position.z)),Ae.addRotation(e,Fi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Ae.addScale(e,this.scale),Ae.addPosLeftHand(e,Se.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Ae.addPosRightHand(e,Se.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Ae.addRotLeftHand(e,Fi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Ae.addRotRightHand(e,Fi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Ae.endVrUserStateBuffer(e);e.finish(r,oh);let o=e.asUint8Array();t.sendBinary(o)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let i=t.avatarId();i&&(this.avatarId=i);let n=t.position();n&&this.position.set(n.x(),n.y(),n.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let o=t.posLeftHand();o&&this.posLeftHand.set(o.x(),o.y(),o.z());let s=t.posRightHand();s&&this.posRightHand.set(s.x(),s.y(),s.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let d=t.rotRightHand();d&&this.rotRightHand.set(d.x(),d.y(),d.z(),d.w()),this.scale=t.scale()}},Pt=$s;U(Pt,"invertRotation",new Js().setFromAxisAngle(new jl(0,1,0),Math.PI)),U(Pt,"quat0",new Js),U(Pt,"quat1",new Js);var Ni=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=k.getComponent(this.gameObject,Y)),this.webXR||(this.webXR=k.findObjectOfType(Y,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=k.findObjectOfType(Y,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=k.findObjectOfType(Ke,this.context)),Zs){let e="debug-avatar-"+Zs,t=new Rt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof Zs=="string"&&Zs.length>0)if(await t.setAvatarOverride(Zs)){let i=new Pt(e);i.position.y+=1;let n=.5;i.posLeftHand.y+=n,i.posLeftHand.x+=n,i.posRightHand.y+=n,i.posRightHand.x-=n,t.tryUpdate(i,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=k.getComponent(this.gameObject,Y),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),Y.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),Y.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Y.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(oh,e=>{let t=e.guid();if(!t)return;let i=e.time().toFloat64(),n=this.tempState;n.setFromBuffer(t,e),this.onTryGetAvatar(t,i)?.tryUpdate(n,i)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,i=e.time;this.onTryGetAvatar(t,i)?.tryUpdate(e,i)})}tempState=new Pt("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return am&&console.log("old data",i,e),null;let n=this.avatars[e];if(n===void 0)try{console.log("create new avatar");let r=new Rt(this.context,e,this.webXR);n=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return n}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),Y.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),Y.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),Y.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=rh();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let i=this.avatars[t];!i||i.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=rh();for(let t in this.avatars){let i=this.avatars[t];if(!i){this._removeAvatarsList.push(t);continue}e-i.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),i.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new Rt(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){am&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"})}ownership=null;xrState=null;builder=new yt(1024);onXRSessionUpdate(e){this.xrState??=new Pt(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new Wn(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:i,rig:n}=e,r=t.getViewerPose(i.getReferenceSpace());if(!r)return;let o=r?.transform,s=o.position,c=o.orientation;this.xrState.update(n,s,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return D("avatar")??null}};async function Dw(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function jw(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var ah=!1,lh=!1;Dw().then(a=>ah=a);jw().then(a=>lh=a);var He=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;handModelPath="";createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(ah||lh)}static get IsARSupported(){return ah}static get IsVRSupported(){return lh}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){He.XRSupported||console.warn("WebXR is not supported on this device");let i=$o.createButton(e.context.renderer);return i.classList.add("webxr-ar-button"),i.classList.add("webxr-button"),this.resetButtonStyles(i),(t?.registerClick??!0)&&i.addEventListener("click",e.onClickedVRButton.bind(e)),i}static createARButton(e,t){let i=e.webAR?.getAROverlayContainer(),n={};i&&(n.domOverlay={root:i},n.optionalFeatures=["hit-test","dom-overlay"]);let r=Il.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),He.resetButtonStyles(r),(t?.registerClick??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=Ye.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!k.findObjectOfType(Ni,this.context)){let e=k.addNewComponent(this.gameObject,Ni,!1);e.webXR=this}}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,this.webAR=new En(this);let e=He.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=He.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(i=He.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{He.resetButtonStyles(i),He.resetButtonStyles(t)},1e3)}_transformOrientation=new sh;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let i=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=i,!i)return;let n=i?.transform;n&&this._transformOrientation.set(n.orientation.x,n.orientation.y,n.orientation.z,n.orientation.w);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}He._isInXr===!1&&t&&this.onEnterXR(t,e),He.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureCameraState())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureCameraState(),this.ensureRig();for(let e=0;e<2;e++)ie.Create(this,e,this.gameObject,0);He.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(X(this.context.mainCamera)),this._originalCameraRotation.copy(Ie(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=k.findObjectOfType(_n,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new Iw,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new dm;_originalCameraRotation=new sh;onEnterXR(e,t){console.log("[XR] session begin",e),He._isInXr=!0,this.ensureRig();let i=this.context.renderer.xr.getReferenceSpace();if(i&&this.rig){let s=t.getViewerPose(i)?.transform.orientation;if(s){let c=new sh(s.x,s.y,s.z,s.w),d=new Pw().setFromQuaternion(c);this.rig.rotateY(d.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let o=n.getCamera(this.context.mainCamera);for(let s of o.cameras)s.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch(ft.Global.Set(r),r){case 2:this.context.xrSessionMode="immersive-ar",this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this.context.xrSessionMode="immersive-vr",this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),He._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),He.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.context.xrSessionMode=void 0,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),se(this.context.mainCamera,this._originalCameraPosition),$e(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),ft.Global.Set(17),He.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!D("mirror")||setTimeout(()=>{if(!He.IsInWebXR)return;let t=new URL(window.location.href);Ro(t.searchParams,es,1),Ro(t.searchParams,"isMirror",1);let i=t.toString();this.xrMirrorWindow=window.open(i,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{He.IsInWebXR&&e.end()})})},1e3)}},Y=He;U(Y,"_isInXr",!1),U(Y,"events",new Ow),P([S()],Y.prototype,"enableVR",2),P([S()],Y.prototype,"enableAR",2),P([S(Ye)],Y.prototype,"defaultAvatar",2),P([S()],Y.prototype,"handModelPath",2),P([S()],Y.prototype,"createVRButton",2),P([S()],Y.prototype,"createARButton",2);var ns=class{get webxr(){return this._webxr}_webxr;reticle=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this._webxr=e}arDomOverlay=null;arOverlayElement=null;noHitTestAvailable=!1;didPlaceARSessionRoot=!1;getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;let e=this.arDomOverlay;return e.getAROverlayContainer?this.arOverlayElement=e.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(e){this.reticleActive=e}async onBegin(e){let t=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1;let i=navigator.userAgent?.includes("OculusBrowser")?0:1,n=i===1?4:2;for(let r=0;r<n;r++)ie.Create(this.webxr,r,this.webxr.gameObject,i);if((!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=k.findObjectOfType(Tt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(r=>{e.requestHitTestSource({space:r}).then(o=>{this.hitTestSource=o}).catch(o=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported")})}),!this.reticle&&this.sessionRoot&&(this.reticle=new kw(new Lw(.07,.09,32).rotateX(-Math.PI/2),new Aw),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.webxr.scene?(this.webxr.scene.add(this.reticle),this.webxr.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,ns.tempWebXRObject||(ns.tempWebXRObject=new Mw),this.context.scene.add(ns.tempWebXRObject),k.addComponent(ns.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene"),this.arDomOverlay&&this.arOverlayElement){let r=this.arOverlayElement;r.onEnterAR?.call(r,e,this.arOverlayElement)}this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),k.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;if(t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay){let i=this.arOverlayElement;i.onExitAR?.call(i,e)}this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;let n=this.webxr.Rig,r=Bw.clone();if(n){let o=new dm(0,0,0).add(n.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new cm().makeTranslation(o.x,o.y,o.z))}this.sessionRoot?.placeAt(n,r)}return}if(!this.hitTestSource)return;let i=t.getHitTestResults(this.hitTestSource);if(i.length){let n=i[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let o=n.getPose(r);if(this.sessionRoot){let s=this.sessionRoot.onUpdate(this.webxr.Rig,e,o);this.didPlaceARSessionRoot=s}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&o)){let s=o.transform.matrix;this.reticle.matrix.fromArray(s),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},En=ns;U(En,"tempWebXRObject");var Bw=new cm().identity().makeTranslation(0,-.5,0);var ch=!1;var rs=class extends Et{static get HasAnySelected(){return this._active!==null}transformSelf=!0;orbit=null;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new ee.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){this.orbit=k.findObjectOfType(Je,this.context)}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||Y.IsInWebXR)return;let t=k.getComponentInParent(e.object,rs);!t||t!==this||(rs.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||Y.IsInWebXR||rs.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||Y.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(Y.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!Y.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&this._dragHelper?.hasSelected===!1&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new Bl(this.context.mainCamera);else return;if(!e||!e.object)return;let t=k.getComponentInParent(e.object,rs);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let c of this.selectStartEventListener)c(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context),this.orbit&&(this.orbit.enabled=!1);let r=k.getComponentInChildren(i,ut);ch&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=k.addNewComponent(i,Ct),this._draggingRigidbodies.length=0;let o=k.getComponentsInChildren(i,oe);o&&this._draggingRigidbodies.push(...o);let s=uc();k.invokeOnChildren(this._dragHelper.selected,s("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.setBodyFromGameObject()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(ch&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e?.object){let n=k.getComponentInChildren(e.object,ut);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=uc();k.invokeOnChildren(t,i("onDragEnd"))}},di=rs;U(di,"_active",null),U(di,"lastHovered");var dh=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new ee.Plane;_hasGroundPlane=!1;_groundPlane=new ee.Plane;_groundOffset=new ee.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new ee.Vector3;_raycaster=new ee.Raycaster;_cameraPlaneOffset=new ee.Vector3;_intersection=new ee.Vector3;_worldPosition=new ee.Vector3;_inverseMatrix=new ee.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new ee.Line(dh.geometry),i=t.material;i.color=new ee.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new ee.SphereGeometry(.5,22,22),r=new ee.MeshBasicMaterial({color:i.color}),o=new ee.Mesh(n,r);o.visible=!1,o.layers.set(2),this._groundMarker=o}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.smoothedVelocity&&i.setVelocity(i.smoothedVelocity.x,i.smoothedVelocity.y,i.smoothedVelocity.z);if(this._selected&&xe.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}xe.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=k.getComponentsInChildren(this._selected,oe),this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new ee.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=" ",i="d",n="s",r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),o=this._context.input.getTouchesPressedCount()>=2||r;if(o){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let s=this._context.input.getPointerPositionRC(0);if(!!s&&(this._raycaster.setFromCamera(s,this._camera),this._selected)){ch&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=X(this._camera).clone().sub(X(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),l=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),h=!o&&d>.2&&!l&&this._context.input.getPointerPressedCount()<=1,u=this._didDragOnGroundPlaneLastFrame!==h;if(this._didDragOnGroundPlaneLastFrame=h,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!h||u)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let f=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=f,h){this._groundOffsetVector.set(0,1,0);let x=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(x,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);u&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,i){if(!!this._selected){if(i){let n=X(this._selected);n.y=e.y,e=n}if(se(this._selected,e),se(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=X(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),se(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;let e=X(this._selected),t=new ee.Ray(new ee.Vector3(0,.1,0).add(e),new ee.Vector3(0,-1,0)),i=new Te;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let o=n[r];if(!o.face||this.contains(this._selected,o.object))continue;let s=new ee.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(s,o.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){re.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0}),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let i of e.children)if(this.contains(i,t))return!0}return!1}},Bl=dh;U(Bl,"geometry",new ee.BufferGeometry().setFromPoints([new ee.Vector3(0,0,0),new ee.Vector3(0,-1,0)]));var Yt=class extends M{url=null;urlParameterName=null;localhost=null;awake(){this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Yt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=D(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e,n=Yt.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return Er(e)}};var Cn=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?Yt.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let i in t){let n=t[i];if(n.kind==="file"){let r=n.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let o=await Rf(r,this.context,this.filesBackendUrl);o&&this.addObject(e,o)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let o=new URL(r);if(!o)return;let s=await Sf(o,this.context);s&&this.addObject(e,s)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=new Te;i.setMask(16777215),i.screenPointFromOffset(e.offsetX,e.offsetY);let n=this.context.physics.raycast(i),r=t.scene;if(n&&n.length>0)for(let o of n){r.position.copy(o.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};P([S()],Cn.prototype,"filesBackendUrl",2),P([S()],Cn.prototype,"localhost",2);import{Vector3 as Hw,Quaternion as Fw,Object3D as hm}from"three";var hi=class extends Et{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new Hw(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Fw(0,0,0,1)}let e=k.getComponentInParent(this.gameObject,di);e?e.addDragEventListener("selectstart",(t,i)=>{if(this._currentCount>=this.limitCount){i.attached=null;return}let n=this.handleDuplication(i.selected);n&&(console.assert(n!==i.selected,"Duplicated object is original"),i.attached=n)}):console.warn("Could no find drag controls in parent",this.name),ie.addEventListener("select-start",(t,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}let n=this.handleDuplication(i.selected);n&&(i.grab=n)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new Ge;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let i=k.instantiateSynced(this.object,t);return console.assert(i!==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),i}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let i of e.children)if(this.isInChildren(i,t))return!0}return!1}};P([S(hm)],hi.prototype,"parent",2),P([S(hm)],hi.prototype,"object",2),P([S()],hi.prototype,"limitCount",2),P([S()],hi.prototype,"limitInterval",2);var ui=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},Nw=a=>/^[A-Z]*$/.test(a),or=class extends Event{args},_e=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(let r of this.key)n&&Nw(r)&&(i+="-"),n=!0,i+=r.toLowerCase();this.key=i}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let i=new or(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new ui(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};var Xr=class extends M{};import{FlyControls as zw}from"three/examples/jsm/controls/FlyControls";var Qr=class extends M{_controls=null;onEnable(){let e=k.getComponent(this.gameObject,he)?.cam;this._controls=new zw(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){this._controls?.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}};import*as um from"three";import{Color as Uw}from"three";var zi=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!_i||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new um.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Pl(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),3)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}};P([S()],zi.prototype,"objectBounds",2),P([S(Uw)],zi.prototype,"color",2),P([S()],zi.prototype,"isGizmo",2);import{GLTFExporter as r_}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as hh,Matrix4 as Gw,Vector3 as pm,Quaternion as Vw}from"three";var ea=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let i=this.writer,n=i.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let o=new Gw,s=new Array,c=new Array,d=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,o);let x=new pm,b=new Vw,y=new pm;o.decompose(x,b,y),s.push(x.x,x.y,x.z),c.push(b.x,b.y,b.z,b.w),d.push(y.x,y.y,y.z)}let l=new Float32Array(s),h=new Float32Array(c),u=new Float32Array(d);r.attributes={TRANSLATION:i.processAccessor(new hh(l,3)),ROTATION:i.processAccessor(new hh(h,4)),SCALE:i.processAccessor(new hh(u,3))},n[this.name]=!0}};import*as Vi from"three";import*as ta from"three";var Ui=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new ta.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new ta.Vector4(1,1,0,0)};lightmapUniform={value:null};beforeRenderCallback;constructor(e,t){this.gameObject=e,this.context=t}init(e,t,i,n=!1){if(console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,this.lightmapIndex<0)return;this.lightmapScaleOffset=t,this.lightmapTexture=i,n&&this.setLightmapDebugMaterial(),this.setupLightmap()}bindOnBeforeRender(){this.beforeRenderCallback=this.onBeforeRenderThreeComplete.bind(this),this.context.addBeforeRenderListener(this.gameObject,this.beforeRenderCallback)}onBeforeRenderThreeComplete(e,t,i,n,r,o){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(i,n)=>{i.uniforms.lightmap=this.lightmapUniform,i.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform},this.lightmapIndex>=0){let i=this.lightmapTexture,n=this.gameObject.material;n&&i&&(n.uniforms||(n.uniforms={}),n.lightMap=i,n.uniforms.lightmap={value:i})}}onBeforeRenderThree(e){let t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,t.lightmap=this.lightmapUniform,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}setLightmapDebugMaterial(){this.gameObject.material=new ta.ShaderMaterial({vertexShader:`
174
+ #endif`);cn.UniformsLib.lightmap.lightmapScaleOffset={value:new cn.Vector4(1,1,0,0)};var km=I("debugplayerview");var uc=class{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}},va=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,n){let i=this.playerViews.get(e);i||(i=new uc(e,this.context),this.playerViews.set(e,i)),i.viewDevice=n,i.currentObject=t,i.removed=!1}getPlayerView(e){if(!e)return;if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}removePlayerView(e,t){let n=this.playerViews.get(e);n?.viewDevice===t&&(km&&console.log("REMOVE",e),n.removed=!0,this.playerViews.delete(e))}};var Lm=I("debugSetup"),jm=I("stats"),ya={};var jt=(s=>(s[s.EarlyUpdate=0]="EarlyUpdate",s[s.Update=1]="Update",s[s.LateUpdate=2]="LateUpdate",s[s.OnBeforeRender=3]="OnBeforeRender",s[s.OnAfterRender=4]="OnAfterRender",s[s.PhysicsStep=10]="PhysicsStep",s))(jt||{});function zs(o,e){if(!o)return;let t=e?.new_scripts??V.Current.new_scripts;t.includes(o)||t.push(o)}var xt=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;domElement;get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;get domWidth(){return this.domElement.clientWidth}get domHeight(){return this.domElement.clientHeight}get domX(){return this.domElement.offsetLeft}get domY(){return this.domElement.offsetTop}get isInXR(){return this.renderer.xr?.isPresenting||!1}xrSessionMode=void 0;get xrSession(){return this.renderer.xr?.getSession()}get arOverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}scene;renderer;composer=null;scripts=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];coroutines={};get mainCamera(){if(this.mainCameraComponent){let e=this.mainCameraComponent;return e.cam||e.buildCamera(),e.cam}return null}mainCameraComponent;post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];application;time;input;physics;connection;assets;mainLight=null;rendererData;addressables;lightmaps;players;_sizeChanged=!1;_isCreated=!1;_stats=jm?Ph.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let n=I("postfx");this.renderer=new Mm({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Ee.NoToneMapping,this.renderer.setClearColor(new Ee.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Ee.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=Ee.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=n?new Dm(this.renderer):null}this.scene=new Ee.Scene,this.application=new ma(this),this.time=new Js,this.input=new Ds(this),this.physics=new io(this),this.connection=new oa(this),this.assets=new da,this.rendererData=new pa(this),this.addressables=new fa(this),this.lightmaps=new ba(this),this.players=new va(this),window.addEventListener("resize",()=>this._sizeChanged=!0),new ResizeObserver(n=>this._sizeChanged=!0).observe(this.domElement)}updateSize(){if(!this.isManagedExternally&&!this.renderer.xr.isPresenting){this._sizeChanged=!1;let e=this.resolutionScaleFactor,t=this.domWidth*e,n=this.domHeight*e,i=this.mainCamera;this.updateAspect(i),this.renderer.setSize(t,n),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&(this.composer.setSize(t,n),this.composer.setPixelRatio(window.devicePixelRatio))}}updateAspect(e){if(!e)return;let t=this.domWidth,n=this.domHeight,i=e.aspect;e.aspect=t/n,i!==e.aspect&&e.updateProjectionMatrix()}onCreate(e,t){return this._isCreated?(console.warn("Context already created"),null):(this._isCreated=!0,this.internalOnCreate(e,t))}onDestroy(){!this._isCreated||(this._isCreated=!1,At(this.scene,!0),this.renderer?.setAnimationLoop(null),this.isManagedExternally||this.renderer?.dispose())}registerCoroutineUpdate(e,t,n){return this.coroutines[n]||(this.coroutines[n]=[]),this.coroutines[n].push({comp:e,main:t}),t}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;let n=this.coroutines[t].findIndex(i=>i.main===e);n>=0&&this.coroutines[t].splice(n,1)}stopAllCoroutinesFrom(e){for(let t in this.coroutines){let n=this.coroutines[t];for(let i=n.length-1;i>=0;i--)n[i].comp===e&&n.splice(i,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.cam||e.buildCamera(),!e.cam){console.warn("Camera component is missing camera",e);return}let t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;let n=e.cam;n.isPerspectiveCamera&&this.updateAspect(n),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;let t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){let n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}}_onBeforeRenderListeners={};addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners[e.uuid]){this._onBeforeRenderListeners[e.uuid]=[];let n=(i,r,s,a,c,d)=>{let l=this._onBeforeRenderListeners[e.uuid];if(!!l)for(let u=0;u<l.length;u++){let h=l[u];h(i,r,s,a,c,d)}};e.onBeforeRender=n}this._onBeforeRenderListeners[e.uuid].push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners[e.uuid]){let n=this._onBeforeRenderListeners[e.uuid],i=n.indexOf(t);i>=0&&n.splice(i,1)}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}async internalOnCreate(e,t){await this.physics.createWorld();let n=!0;try{xt.Current=this,e&&await e(this,t)}catch(i){console.error(i),n=!1}if(!!n){this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),Iu(this),ku(this),bh(this),xt._current=this;for(let i=0;i<this.new_scripts.length;i++){let r=this.new_scripts[i];if(r.gameObject!==void 0&&r.gameObject!==null){r.gameObject.userData===void 0&&(r.gameObject.userData={}),r.gameObject.userData.components===void 0&&(r.gameObject.userData.components=[]);let s=r.gameObject.userData.components;s.includes(r)||s.push(r)}}if(this.post_setup_callbacks)for(let i=0;i<this.post_setup_callbacks.length;i++)xt._current=this,await this.post_setup_callbacks[i](this);if(this.mainCamera,xt._current=this,zn(this),!this.isManagedExternally&&this.composer&&this.mainCamera){let i=new Am(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(i),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),this.renderer.setAnimationLoop(this.render.bind(this)),Lm&&zo(this.scene,!0)}}render(e,t){for(this._stats?.begin(),xt._current=this,this.time.update(),zn(this),Jr(),Fs(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);let n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_callbacks)for(let n in this.pre_update_callbacks)this.pre_update_callbacks[n]();for(let n=0;n<this.scripts_earlyUpdate.length;n++){let i=this.scripts_earlyUpdate[n];!i.activeAndEnabled||i.earlyUpdate!==void 0&&(xt._current=this,i.earlyUpdate())}this.executeCoroutines(0);for(let n=0;n<this.scripts_update.length;n++){let i=this.scripts_update[n];!i.activeAndEnabled||i.update!==void 0&&(xt._current=this,i.update())}this.executeCoroutines(1);for(let n=0;n<this.scripts_lateUpdate.length;n++){let i=this.scripts_lateUpdate[n];!i.activeAndEnabled||i.lateUpdate!==void 0&&(xt._current=this,i.lateUpdate())}this.executeCoroutines(2);try{let i=this.time.deltaTime/1;for(let r=0;r<1;r++)this.physics.step(i),this.executeCoroutines(10)}catch(n){console.error(n)}this.physics.postStep();for(let n=0;n<this.scripts_onBeforeRender.length;n++){let i=this.scripts_onBeforeRender[n];!i.activeAndEnabled||i.onBeforeRender!==void 0&&(xt._current=this,i.onBeforeRender(t))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(let n in this.pre_render_callbacks)this.pre_render_callbacks[n]();this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer&&!this.isInXR?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1;for(let n=0;n<this.scripts_onAfterRender.length;n++){let i=this.scripts_onAfterRender[n];!i.activeAndEnabled||i.onAfterRender!==void 0&&(xt._current=this,i.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(let n in this.post_render_callbacks)this.post_render_callbacks[n]();this.connection.sendBufferedMessagesNow(),this._stats?.end()}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new Ee.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let n=new Im(this.domWidth,this.domHeight);this._renderTarget.depthTexture=n}this._requireColorTexture&&(this._renderTarget.texture=new Ee.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Ee.NearestFilter,this._renderTarget.texture.magFilter=Ee.NearestFilter,this._renderTarget.texture.format=Ee.RGBAFormat)}let e=this._renderTarget;e.texture&&(e.texture.encoding=this.renderer.outputEncoding);let 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]){let n=this.coroutines[e];for(let i=0;i<n.length;i++){let r=n[i];if(!r.comp||r.comp.destroyed||!r.main||r.comp.enabled===!1){n.splice(i,1),--i;continue}let a=r.chained;if(a&&a.length>0){let u=a[a.length-1].next();if(u.done&&a.pop(),t(u)&&(r.chained||(r.chained=[]),r.chained.push(u.value)),!u.done)continue}let c=r.main.next();if(c.done===!0){n.splice(i,1),--i;continue}let d=c.value;if(t(d)){if(d.next().done)continue;r.chained||(r.chained=[]),r.chained.push(d)}}}function t(n){return!!(n&&n.next&&n.return)}}},V=xt;j(V,"_current");var hc={};iu(hc,{Behaviour:()=>O,Component:()=>st,GameObject:()=>R});import*as Ue from"three";var R=class extends Ue.Object3D{guid;static setActive(e,t,n=!0,i=!0){!e||(qs(e,t,i),Jr(e),t&&n&&Fs(V.Current,e))}static isActiveSelf(e){return sr(e)}static isActiveInHierarchy(e){return zu(e)}static markAsInstancedRendered(e,t){Xu(e,t)}static isUsingInstancing(e){return Ys(e)}static foreachComponent(e,t,n=!0){return Qn(e,t,n)}static instantiateSynced(e,t){return e?Gs(e,t):null}static instantiate(e,t=null){return lr(e,t)}static destroySynced(e,t,n=!0){if(!e)return;let i=e;t=t??V.Current,Zr(i,t.connection,n)}static destroy(e,t=!0,n=!0){return At(e,t,n)}static add(e,t,n){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}n||(n=V.Current),t.add(e),qs(e,!0),Jr(e),n?R.foreachComponent(e,i=>{Dl(i,n),!i.__internalDidAwakeAndStart&&n.new_script_start.includes(i)===!1&&n.new_script_start.push(i)},!0):console.warn("Missing context")}}static remove(e){!e||(e.parent?.remove(e),qs(e,!1),Jr(e),R.foreachComponent(e,t=>{Eu(t)},!0))}static invokeOnChildren(e,t,...n){this.invoke(e,t,!0,n)}static invoke(e,t,n=!1,...i){!e||this.foreachComponent(e,r=>{let s=r[t];s&&typeof s=="function"&&s.bind(r)(...i)},n)}static addNewComponent(e,t,n=!0){let i=new t;return wi(e,i,n),i}static addComponent(e,t){if(t.gameObject==null)throw new Error("Did you mean to create a new component? Use addNewComponent");Bu(e,t)}static removeComponent(e){return Ns(e.gameObject,e),e}static getOrAddComponent(e,t){return Ws(e,t)}static getComponent(e,t){return e===null?null:cr(e,t)}static getComponents(e,t,n=null){return e===null?n??[]:eo(e,t,n)}static findByGuid(e,t){return ar(e,t)}static findObjectOfType(e,t,n=!0){return Vu(e,t??V.Current,n)}static findObjectsOfType(e,t){let n=[];return Nu(e,n,t),n}static getComponentInChildren(e,t){return Xn(e,t)}static getComponentsInChildren(e,t,n=null){return to(e,t,n??void 0)}static getComponentInParent(e,t){return $r(e,t)}static getComponentsInParent(e,t,n=null){return Yo(e,t,n)}static getAllComponents(e){return[...e.userData?.components]}static*iterateComponents(e){let t=e?.userData?.components;if(t&&Array.isArray(t))for(let n=0;n<t.length;n++)yield t[n]}},Ht=class{get isComponent(){return!0}__context;get context(){return this.__context??V.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}get hideFlags(){return this.gameObject?.userData.hideFlags}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;let e=this.gameObject[sn];return e===void 0?!0:e}set __isActiveInHierarchy(e){!this.gameObject||(this.gameObject[sn]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=1){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=1){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(){this.__internalNewInstanceCreated()}__internalNewInstanceCreated(){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(){return this.__didEnable?!1:(this.__didEnable=!0,this.onEnable(),this.__isEnabled=!0,!0)}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this.onDisable(),this.__isEnabled=!1)}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.destroy?.call(this),Uu(this))}get enabled(){return this.__isEnabled??!0}set enabled(e){if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}_worldPosition=void 0;_worldQuaternion=void 0;_worldEuler=void 0;_worldRotation=void 0;get worldPosition(){return this._worldPosition||(this._worldPosition=new Ue.Vector3),B(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){J(this.gameObject,e)}setWorldPosition(e,t,n){Ht._worldPositionBuffer.set(e,t,n),this.worldPosition=Ht._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new Ue.Quaternion),me(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){Be(this.gameObject,e)}setWorldQuaternion(e,t,n,i){Ht._worldQuaternionBuffer.set(e,t,n,i),this.worldQuaternion=Ht._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new Ue.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new Ue.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new Ue.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=W.toDegrees(t.x),t.y=W.toDegrees(t.y),t.z=W.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,n,i=!0){i&&(e=W.toRadians(e),t=W.toRadians(t),n=W.toRadians(n)),Ht._worldEulerBuffer.set(e,t,n),Ht._worldQuaternionBuffer.setFromEuler(Ht._worldEulerBuffer),this.worldQuaternion=Ht._worldQuaternionBuffer}get forward(){return Ht._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}_eventListeners=new Map;addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;let n=this._eventListeners[e].indexOf(t);n>=0&&this._eventListeners[e].splice(n,1)}dispatchEvent(e){if(!this._eventListeners[e.type])return!1;let t=this._eventListeners[e.type];for(let n=0;n<t.length;n++)t[n](e);return!1}},st=Ht;j(st,"_worldPositionBuffer",new Ue.Vector3),j(st,"_worldQuaternionBuffer",new Ue.Quaternion),j(st,"_worldEulerBuffer",new Ue.Euler),j(st,"_tempQuaternionBuffer2",new Ue.Quaternion),j(st,"_forward",new Ue.Vector3);var O=class extends st{};var Hm=I("debugloadingbar");function pc(o){return o.index/o.count+o.progress.loaded/o.progress.total/o.count}var _a=class{loadingProgress=0;container;_progress=0;_allowCustomLoadingElement=!1;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this.container=e,this._loadingElementOptions=t}onLoadingBegin(e){if(!this._loadingElement){for(let t=0;t<this.container.children.length;t++){let n=this.container.children[t];if(n.classList.contains("loading")){if(!this._allowCustomLoadingElement){console.warn("Custom loading container is not allowed"),this.container.removeChild(n);continue}this._loadingElement=this.createLoadingElement(n);return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let n=0;typeof e=="number"?n=e:("index"in e&&(n=pc(e)),!t&&"name"in e&&this.setMessage(e.name)),this.loadingProgress=n,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(e){this.loadingProgress=1,this.setMessage(e??"")}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;Hm&&(e=.001);let t=1-.05;this._progressLoop=setInterval(()=>{if(this.loadingProgress>=1&&this._progress>=t){this._loadingElement&&(this._loadingElement.style.display="none",this._loadingElement.remove()),clearInterval(this._progressLoop),this._progressLoop=null;return}this._progress=W.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}updateDisplay(){let e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){this._loadingElement=e||document.createElement("div"),e||(this._loadingElement.style.position="fixed",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",this._loadingElement.style.backgroundColor="#000000",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex="1000",this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let a of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(a);let n=document.createElement("div"),i=30;n.style.display="flex",n.style.width=i+"%",n.style.height="2px",n.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(n),this._loadingBar=document.createElement("div"),n.appendChild(this._loadingBar);let r=function(a){return W.lerp(i*.5,100-i*.5,a)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${r(0)}, #0BA398 ${r(.4)}, #99CC33 ${r(.5)}, #D7DB0A ${r(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let s=document.createElement("div");return this._messageContainer=s,s.style.display="flex",s.style.fontSize=".8em",s.style.paddingTop=".5em",s.style.color="rgba(255,255,255,.5)",s.style.justifyContent="center",this._loadingElement.appendChild(s),this._loadingElement}};import{DRACOLoader as fc}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Oh}from"three/examples/jsm/loaders/KTX2Loader.js";var ns=I("debugdecoders"),Ft,Si;function mc(o){o!==void 0&&typeof o=="string"&&(Ft||(Ft=new fc),ns&&console.log("Setting draco decoder path to",o),Ft.setDecoderPath(o))}function gc(o){o!==void 0&&typeof o=="string"&&(Ft||(Ft=new fc),ns&&console.log("Setting draco decoder type to",o),Ft.setDecoderConfig({type:o}))}function bc(o){o!==void 0&&typeof o=="string"&&(Si||(Si=new Oh),ns&&console.log("Setting ktx2 transcoder path to",o),Si.setTranscoderPath(o))}function Yn(o,e){Ft||(Ft=new fc,Ft.setDecoderPath("./include/draco/"),Ft.setDecoderConfig({type:"js"}),ns&&console.log("Setting draco decoder path to","./include/draco/")),Si||(Si=new Oh,Si.setTranscoderPath("./include/ktx2/"),ns&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&Si.detectSupport(e.renderer)),o.setDRACOLoader(Ft),o.setKTX2Loader(Si)}import{AnimationClip as Fm,MathUtils as Bm}from"three";var ao=class{_name;get name(){return this._name}_nameHash;get nameHash(){return this._nameHash}_normalizedTime;get normalizedTime(){return this._normalizedTime}_length;get length(){return this._length}_speed;get speed(){return this._speed}constructor(e,t,n,i){this._name=e.name,this._nameHash=e.hash,this._normalizedTime=t,this._length=n,this._speed=i}};function Ih(o,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??Bm.generateUUID(),index:-1,clip:new Fm(o,1,[])}}import{AnimationClip as Um,AnimationMixer as Gm,AxesHelper as Vm,Euler as Mh,LoopOnce as Nm,Quaternion as Bt,Vector3 as is}from"three";import*as wa from"three";var Pi=I("debuganimatorcontroller"),vc=I("debugrootmotion"),Ct=class{Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}let s=this.model.layers[t].stateMachine;for(let a of s.states)if(a.name===e||a.hash===e){Pi&&console.log("transition to ",a),this.transitionTo(a,i,n);return}console.warn("Could not find "+e+" to play")}Reset(){this.setStartTransition()}SetBool(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetBool(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??!1}SetFloat(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetFloat(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??0}SetInteger(e,t){let n=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(i=>i[n]===e).forEach(i=>i.value=t)}GetInteger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.find(n=>n[t]===e)?.value??0}SetTrigger(e){Pi&&console.log("SET TRIGGER",e);let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!0)}ResetTrigger(e){let t=typeof e=="string"?"name":"hash";return this.model?.parameters.filter(n=>n[t]===e).forEach(n=>n.value=!1)}IsInTransition(){return this._activeStates.length>1}SetSpeed(e){this._speed=e}FindState(e){if(!e)return null;for(let t of this.model.layers)for(let n of t.stateMachine.states)if(n.name===e)return n;return null}normalizedStartOffset=0;_speed=1;animator;model;get context(){return this.animator?.context}bind(e){this.animator=e,this._mixer=new Gm(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=Uo(this.model,(n,i,r)=>r==null?!0:!(r.type==="Object3D"||r.isObject3D===!0||r?.constructor?.name==="AnimationAction"||r.tracks!==void 0));return console.assert(e!==this.model),new Ct(e)}update(){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates();let e=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(),this._mixer.update(e),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate()}_mixer;_activeState;constructor(e){this.model=e,Pi&&console.log(this)}_activeStates=[];updateActiveStates(){for(let e=0;e<this._activeStates.length;e++){let t=this._activeStates[e],n=t.motion;if(!n.action)this._activeStates.splice(e,1),e--;else{let i=n.action;i.getEffectiveWeight()<=0&&!i.isRunning()&&(Pi&&console.debug("REMOVE",t.name,i.getEffectiveWeight(),i.isRunning(),i.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,n=t.states[t.defaultState];this.transitionTo(n,0,this.normalizedStartOffset)}}evaluateTransitions(){let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}let n=this._activeState,i=n.motion.action,r=0;for(let a of n.transitions){if(++r,!a.hasExitTime&&a.conditions.length<=0)continue;let c=!0;for(let d of a.conditions)if(!this.evaluateCondition(d)){c=!1;break}if(!!c){Pi&&c&&console.log("All conditions are met",a);for(let d of a.conditions){let l=this.model.parameters.find(u=>u.name===d.parameter);l?.type===9&&(l.value=!1)}if(i){let d=n.motion.clip.duration,l=d<=0?1:i.time/d;if(!a.hasExitTime||l>=a.exitTime&&i.time>=i.getClip().duration){i.clampWhenFinished=!0,Pi&&(console.log("transition to "+a.destinationState,a),console.log(i.time,a.exitTime)),this.transitionTo(a.destinationState,a.duration,a.offset);return}}else{this.transitionTo(a.destinationState,a.duration,a.offset);return}break}}let s=!1;if(n.motion.isLooping&&i&&i.time>=i.getClip().duration&&(s=!0,i.reset(),i.time=0,i.play()),!s&&n&&!t&&i&&this.animator&&n.behaviours){let a=i?.getClip().duration,c=i.time/a,d=new ao(this._activeState,c,a,this._speed);for(let l of n.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,d,0)}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,n){if(!this.animator)return;let i=0;if(e=this.getState(e,i),!e?.motion||!e.motion.clip)return;let r=this._activeState===e;if(r){let d=e.motion;!d.action_loopback&&d.clip&&(this._mixer.uncacheAction(d.clip,this.animator.gameObject),d.action_loopback=this.createAction(d.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let d=this._activeState?.motion.clip.duration,l=this._activeState.motion.action.time/d,u=new ao(this._activeState,l,d,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateExit?.call(h.instance,this.animator,u,i)}let s=this._activeState?.motion.action;s&&s.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=s);let a=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){n=Math.max(0,Math.min(1,n)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let d=e.motion.clip.duration;if(c.time=n*d,c.clampWhenFinished=!0,c.setLoop(Nm,0),t>0?c.fadeIn(t):c.setEffectiveWeight(1),c.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(c),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){let l=new ao(e,n,d,this._speed);for(let u of this._activeState.behaviours)u.instance?.onStateEnter?.call(u.instance,this.animator,l,i)}}else console.warn("No action",e.motion,this);Pi&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,s,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.uncacheClip(e),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new yc(this));let t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){let t=this.model.parameters.find(n=>n.name===e.parameter);if(!t)return!1;switch(e.mode){case 1:return t.value===!0;case 2:return t.value===!1;case 3:return t.value>e.threshold;case 4:return t.value<e.threshold;case 6:return t.value===e.threshold;case 7:return t.value!==e.threshold}return!1}createActions(e){for(let t of this.model.layers){let n=t.stateMachine;for(let i=0;i<n.states.length;i++){let r=n.states[i];if(r.motion||(r.motion=Ih(r.name)),this.animator&&r.motion.clips){let s=r.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r.motion.clip=s?.clip}if(!r.motion.clip){let s=new Um;r.motion.clip=s}if(r.motion?.clip){let s=r.motion.clip,a=this.createAction(s);r.motion.action=a}if(r.behaviours&&Array.isArray(r.behaviours))for(let s of r.behaviours){if(!s?.typeName)continue;let a=M.get(s.typeName),c=new a;c.isStateMachineBehaviour&&(c._context=this.context??void 0,Nn(c,s.properties),s.instance=c),Pi&&console.log("Created animator controller behaviour",r.name,s.typeName,s.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let n=0;n<t.states.length;n++){let i=t.states[n];i?.motion&&(i.motion.action&&(yield i.motion.action),i.motion.action_loopback&&(yield i.motion.action_loopback))}}}rootMotionHandler},Ea=class{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;let n=e,i=n.createInterpolant.bind(e);n.createInterpolant=()=>(n.createInterpolant=i,this.createdInterpolant=i(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=r=>{if(!this.originalEvaluate)return;let s=this.originalEvaluate(r);return t(r,s)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},be=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new is;rotationChange=new Bt;constructor(e,t,n,i,r){if(this.context=e,this.root=t,this.clip=n,be.firstKeyframeRotation[n.uuid]||(be.firstKeyframeRotation[n.uuid]=new wa.Quaternion),r){let s=r.values;be.firstKeyframeRotation[n.uuid].set(s[0],s[1],s[2],s[3])}be.spaceRotation[n.uuid]||(be.spaceRotation[n.uuid]=new Bt),be.effectiveSpaceRotation[n.uuid]||(be.effectiveSpaceRotation[n.uuid]=new Bt),be.clipOffsetRotation[n.uuid]=new Bt,r&&be.clipOffsetRotation[n.uuid].set(r.values[0],r.values[1],r.values[2],r.values[3]).invert(),this.handlePosition(n,i),this.handleRotation(n,r)}onStart(e){if(e.getClip()!==this.clip)return;let t=be.lastObjRotation[this.root.uuid];be.spaceRotation[this.clip.uuid].copy(t);{let n=new wa.Euler().setFromQuaternion(t);console.log("START",this.clip.name,W.toDegrees(n.y))}}getClipRotationOffset(){return be.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let n=this.root;vc&&n.add(new Vm),be.lastObjPosition[n.uuid]||(be.lastObjPosition[n.uuid]=new is);let i=new is,r=new is,s=0;this.positionWrapper=new Ea(t,(a,c)=>{let d=this.action.getEffectiveWeight();if(vc&&n.position.length()>8&&n.position.set(0,n.position.y,0),a>s){i.set(c[0],c[1],c[2]),i.sub(r),i.multiplyScalar(d),i.applyQuaternion(this.getClipRotationOffset());let l=this.clip.uuid;i.applyQuaternion(be.spaceRotation[l]),this.positionChange.copy(i)}return r.fromArray(c),s=a,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(vc){let a=t.values,c=new Mh().setFromQuaternion(new Bt(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",W.toDegrees(c.y));let d=t.values.length-4,l=new Bt().set(a[d],a[d+1],a[d+2],a[d+3]),u=new Mh().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",W.toDegrees(u.y))}let n=this.root;be.lastObjRotation[n.uuid]||(be.lastObjRotation[n.uuid]=new Bt);let i=0,r=new Bt,s=new Bt;this.rotationWrapper=new Ea(t,(a,c)=>(a>i&&(s.set(c[0],c[1],c[2],c[3]),r.invert(),s.multiply(r),this.rotationChange.copy(s)),r.fromArray(c),i=a,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(be.identityQuaternion,1-e)}},Ut=be;j(Ut,"lastObjPosition",{}),j(Ut,"lastObjRotation",{}),j(Ut,"firstKeyframeRotation",{}),j(Ut,"spaceRotation",{}),j(Ut,"effectiveSpaceRotation",{}),j(Ut,"clipOffsetRotation",{}),j(Ut,"identityQuaternion",new Bt);var yc=class{controller;handler=[];root;constructor(e){this.controller=e}createClip(e,t,n){this.root=t;let i="";t&&"name"in t&&(i=t.name);let r=this.findRootTrack(n,".position"),s=this.findRootTrack(n,".quaternion"),a=new Ut(this.controller.context,t,n,r,s);this.handler.push(a);let c=e.clipAction(n);return a.action=c,c}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new is;summedRotation=new Bt;onAfterUpdate(){this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(let e of this.handler)e.onAfterUpdate(),this.summedPosition.add(e.positionChange),this.summedRotation.multiply(e.rotationChange);this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation),Ut.lastObjRotation[this.root.uuid].copy(this.root.quaternion)}findRootTrack(e,t){let n=e.tracks;for(let i of n)if(i.name.endsWith(t))return i;return null}};var x=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=Dh(o);else for(let e=0;e<o.length;e++){let t=o[e];o[e]=Dh(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let n=e.$serializedTypes=e.$serializedTypes||{};n[t]=o}};function Dh(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}var Wm=I("debuganimator"),qe=class extends O{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Ct?this._animatorController=e:this._animatorController=new Ct(e):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}Play(e,t=-1,n=Number.NEGATIVE_INFINITY,i=0){this.runtimeAnimatorController?.Play(e,t,n,i)}Reset(){this._animatorController?.Reset()}SetBool(e,t){this.runtimeAnimatorController?.SetBool(e,t)}GetBool(e){return this.runtimeAnimatorController?.GetBool(e)??!1}SetFloat(e,t){this.runtimeAnimatorController?.SetFloat(e,t)}GetFloat(e){return this.runtimeAnimatorController?.GetFloat(e)??-1}SetInteger(e,t){this.runtimeAnimatorController?.SetInteger(e,t)}GetInteger(e){return this.runtimeAnimatorController?.GetInteger(e)??-1}SetTrigger(e){this.runtimeAnimatorController?.SetTrigger(e)}ResetTrigger(e){this.runtimeAnimatorController?.ResetTrigger(e)}IsInTransition(){return this.runtimeAnimatorController?.IsInTransition()??!1}SetSpeed(e){e!==this.speed&&(this.speed=e,this._animatorController?.SetSpeed(e))}set minMaxSpeed(e){this.speed=W.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=W.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController&&(this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset)}speed=1;normalizedStartOffset=0;_animatorController=null;awake(){if(!!this.gameObject){if(this.runtimeAnimatorController){let e=this.runtimeAnimatorController.clone();console.assert(this.runtimeAnimatorController!==e),this.runtimeAnimatorController=e,console.assert(this.runtimeAnimatorController===e),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.SetSpeed(this.speed),this.runtimeAnimatorController.normalizedStartOffset=this.normalizedStartOffset}Wm&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};C([x()],qe.prototype,"applyRootMotion",2),C([x()],qe.prototype,"hasRootMotion",2),C([x()],qe.prototype,"keepAnimatorControllerStateOnDisable",2),C([x()],qe.prototype,"runtimeAnimatorController",1);import*as lo from"three";var dn=class extends O{playAutomatically=!0;randomStartTime=!0;minMaxSpeed;minMaxOffsetNormalized;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.gameObject){this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(this.gameObject.animations||(this.gameObject.animations=[]),this.gameObject.animations.push(e))}set animations(e){this.gameObject.animations=e}get animations(){return this.gameObject.animations}get currentAction(){return this._currentActions[0]}get currentActions(){return this._currentActions}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions=[];_currentActions=[];_handles=[];awake(){this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.playAutomatically&&this.init()}onEnable(){if(this.playAutomatically&&this.actions.length>0&&this.currentActions.length<=0){let e=Math.floor(Math.random()*this.actions.length);this.play(e)}}start(){this.randomStartTime&&this.currentAction&&(this.currentAction.time=Math.random()*this.currentAction.getClip().duration)}update(){if(!!this.mixer){this.mixer.update(this.context.time.deltaTime);for(let e of this._handles)e._update();this._handles?.length>0&&ne.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}play(e,t){if(this.init(),!this.mixer)return;let n=e;if(typeof e=="number"){if(e>=this.animations.length)return;n=this.animations[e]}else typeof e=="string"&&(n=this.animations.find(r=>r.name===e));if(!n){console.error("Could not find clip",e);return}t||(t={}),t.minMaxOffsetNormalized||(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed||(t.minMaxSpeed=this.minMaxSpeed);for(let r of this.actions)if(r.getClip()===n)return this.internalOnPlay(r,t);let i=this.mixer.clipAction(n);return this.actions.push(i),this.internalOnPlay(i,t)}internalOnPlay(e,t){var n=this.currentAction;if(n===e&&n.isRunning()&&n.time<n.getClip().duration){let a=this.tryFindHandle(e);if(a)return a.getPromise()}let i=t?.exclusive??!0;t?.fadeDuration?(i&&n?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):i&&n?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1;let r=e.getClip();t?.minMaxOffsetNormalized&&(e.time=W.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration),t?.minMaxSpeed&&(e.timeScale=W.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random())),t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?lo.LoopRepeat:lo.LoopOnce),e.play();let s=new _c(e,this.mixer,t,a=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){if(!this._didInit&&(this._didInit=!0,!!this.gameObject)){this.actions=[],this.mixer=new lo.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};C([x()],dn.prototype,"playAutomatically",2),C([x()],dn.prototype,"randomStartTime",2);var _c=class{mixer;action;promise=null;resolve=null;reject=null;_options;_resolveCallback=null;_rejectCallback=null;_loopCallback;_finishedCallback;_resolvedOrRejectedCallback;constructor(e,t,n,i){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=i,this._options=n}getPromise(){return this.promise?this.promise:(this.promise=new Promise((e,t)=>{this._resolveCallback=e,this._rejectCallback=t,this.resolve=this.onResolve.bind(this),this.reject=this.onReject.bind(this)}),this._loopCallback=this.onLoop.bind(this),this._finishedCallback=this.onFinished.bind(this),this.mixer.addEventListener("loop",this._loopCallback),this.mixer.addEventListener("finished",this._finishedCallback),this.promise)}_update(){!this._options||this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onReject(e){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._rejectCallback?.call(this,e)}onLoop(e){}onFinished(e){e.action===this.action&&this.onResolve()}dispose(){this._loopCallback&&this.mixer.removeEventListener("loop",this._loopCallback),this._finishedCallback&&this.mixer.removeEventListener("finished",this._finishedCallback),this._loopCallback=void 0,this._finishedCallback=void 0}};import{GLTFLoader as Xp}from"three/examples/jsm/loaders/GLTFLoader.js";import*as se from"three";import{RawShaderMaterial as Xm}from"three";var Kn=I("debugshaders"),co="NEEDLE_techniques_webgl";var Ec=class{objectToWorldMatrix=new se.Matrix4;worldToObjectMatrix=new se.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),es(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),es(this.worldToObjectMatrix,this.worldToObject)}};var oe=class extends Xm{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){let e=super.clone();return Ah(e),e}constructor(e,...t){super(...t),this.identifier=e,Kn&&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.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&V.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=V.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&V.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=V.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}Kn&&console.log(t);let n=t.array,i=t.texture;this.uniforms.unity_SpecCube0={value:i},sc(this.uniforms,n);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new se.Vector4(r,r,r,r)},Kn&&console.log("Set environment lighting",this.uniforms)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";_rendererData=new Ec;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&V.Current.setRequireColor(!0),this.depthTextureUniform&&V.Current.setRequireDepth(!0)}onBeforeRender(e,t,n,i,r,s){i.attributes.tangent||i.computeTangents(),this.onUpdateUniforms(n,r)}onUpdateUniforms(e,t){let n=V.Current;e&&(oe.viewProjection&&this.uniforms[this._viewProjectionName]&&(oe.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),es(oe.viewProjection,oe._viewProjectionValues)),oe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(oe.viewMatrix.copy(e.matrixWorldInverse),es(oe.viewMatrix,oe._viewMatrixValues)),this.uniforms[oe._worldSpaceCameraPosName]&&oe._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters?this.uniforms._TimeParameters.value=n.rendererData.timeVec4:this.uniforms._Time&&(this.uniforms._Time.value=n.rendererData.timeVec4);let i=n.mainLight;if(i){let a=B(i.gameObject,oe._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},oe._mainLightColor.set(i.color.r,i.color.g,i.color.b,0),this.uniforms._MainLightColor={value:oe._mainLightColor};let c=i.intensity;oe._lightData.z=c,this.uniforms.unity_LightData={value:oe._lightData}}if(e&&(oe.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=oe._viewProjectionValues),oe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=oe._viewMatrixValues),this.uniforms[oe._worldSpaceCameraPosName]&&(this.uniforms[oe._worldSpaceCameraPosName]={value:oe._worldSpaceCameraPos}),n.mainCameraComponent)){if(this.uniforms._ProjectionParams){let a=this.uniforms._ProjectionParams.value;a.x=1,a.y=n.mainCameraComponent.nearClipPlane,a.z=n.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){let a=this.uniforms._ZBufferParams.value,c=n.mainCameraComponent;a.x=1-c.farClipPlane/c.nearClipPlane,a.y=c.farClipPlane/c.nearClipPlane,a.z=a.x/c.farClipPlane,a.w=a.y/c.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){let a=this.uniforms._ScreenParams.value;a.x=n.domWidth,a.y=n.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}}let r=this.depthTextureUniform;r&&(r.value=n.depthTexture);let s=this.opaqueTextureUniform;if(s&&(s.value=n.opaqueColorTexture),t){let a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}},Tt=oe;j(Tt,"viewProjection",new se.Matrix4),j(Tt,"_viewProjectionValues",[]),j(Tt,"viewMatrix",new se.Matrix4),j(Tt,"_viewMatrixValues",[]),j(Tt,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),j(Tt,"_worldSpaceCameraPos",new se.Vector3),j(Tt,"_mainLightColor",new se.Vector4),j(Tt,"_mainLightPosition",new se.Vector3),j(Tt,"_lightData",new se.Vector4);var xa=class{get name(){return co}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return Kn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[co])return Kn&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let n=t.extensions[co].technique;if(n<0)return null;let i=this.parser.json.extensions[co];if(!i)return null;Kn&&console.log(i);let r=i.techniques[n];return r?new Promise(async(s,a)=>{let c=await Th(i,r.program),d=c?.fragmentShader,l=c?.vertexShader;if(!d||!l)return a();Kn&&console.log("loadMaterial",t,c);let u={},h=r.uniforms;l.includes("_Time")&&(u._Time={value:new se.Vector4(0,0,0,0)});for(let y in h){let m=y;switch(m){case"_TimeParameters":let f=new se.Vector4;u[m]={value:f};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[m]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[m]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[m]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[m]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[m]={value:null};break}}let b=!1;if(t.extensions&&t.extensions[co]){let y=t.extensions[co];if(y.technique===n){Kn&&console.log(t.name,"Material Properties",y);for(let m in y.values){let f=y.values[m];if(typeof f=="string"){if(f.startsWith("/textures/")){let p=f.substring(10),g=Number.parseInt(p);if(g>=0){let E=await this.parser.getDependency("texture",g);E&&(E.encoding=se.LinearEncoding,E.needsUpdate=!0),u[m]={value:E};continue}}switch(m){case"alphaMode":f==="BLEND"&&(b=!0);continue}}if(Array.isArray(f)&&f.length===4){u[m]={value:new se.Vector4(f[0],f[1],f[2],f[3])};continue}u[m]={value:f}}}}let _=new Tt(this.identifier,{name:t.name??"",uniforms:u,vertexShader:l,fragmentShader:d,lights:!1});switch(u._Cull?.value){case 0:_.side=se.DoubleSide;break;case 1:_.side=se.BackSide;break;case 2:_.side=se.FrontSide;break;default:_.side=se.FrontSide;break}_.transparent=b,b&&(_.depthWrite=!1),sc(u),_.onUpdateUniforms();for(let y in h){let m=y,f=h[y].type;if(u[m]?.value===void 0)switch(f){case 35678:u[m]={value:wh},console.warn("Missing/unassigned texture, fallback to white: "+m);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+m,h[y]);break}}Kn&&console.log(_.uuid,u),Ah(_),s(_)}):null}};function Ah(o){if(o.uniforms)for(let e in o.uniforms)Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{get:()=>o.uniforms[e].value,set:t=>{o.uniforms[e].value=t,o.needsUpdate=!0}})}var Oi=_e,Ca="$___Export_Components",Qm="NEEDLE_components",wc=class{[or]},xc=class{node;nodeIndex;nodeDef;constructor(e,t,n){this.node=e,this.nodeIndex=t,this.nodeDef=n}},uo=class{get name(){return Qm}parser;nodeToObjectMap={};exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{let n=t.serializeUserData.bind(t);return this.writer=t,t.serializeUserData=(i,r)=>{try{this.serializeUserData(i,r),n(i,r)}finally{this.afterSerializeUserData(i,r)}},this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){let n=e.userData?.components;!n||n.length<=0||(delete e.userData.components,e[Ca]=n)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Oi&&console.log("DONE",JSON.stringify(t)),e[Ca]===void 0)return;let n=e[Ca];delete e[Ca],n!==null&&(e.userData.components=n)}writeNode(e,t){let n=this.writer.json.nodes.length;console.log(e.name,n,e.uuid);let i=new xc(e,n,t);this.exportContext[n]=i,this.objectToNodeMap[e.uuid]=n}afterParse(e){Oi&&console.log("AFTER",e);for(let t in this.exportContext){let n=this.exportContext[t],i=n.node,r=n.nodeDef,s=n.nodeIndex,a=i.userData?.components;if(!a||a.length<=0)continue;let c=new wc;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=i,this.context.nodeId=s,this.context.objectToNode=this.objectToNodeMap;let d=[];for(let l of a){this.context.target=l;let u=Le().writeBuiltinComponentData(l,this.context);u!==null&&d.push(u)}d.length>0&&(c[or]=d,Oi&&console.log("DID WRITE",i,"nodeIndex",s,d))}}beforeRoot(){return Oi&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){let t=e.parser,n=t?.extensions;if(!n)return;let i=n[this.name];Oi&&console.log("After root",e,this.parser,n);let r=[];if(i===!0){let s=t.json.nodes;for(let a=0;a<s.length;a++){let c=await t.getDependency("node",a);this.nodeToObjectMap[a]=c}for(let a=0;a<s.length;a++){let c=s[a],d=a,l=c.extensions;if(!l)continue;let u=l[this.name];if(!u)continue;Oi&&console.log("NODE",c);let h=this.nodeToObjectMap[d];if(!h){console.error("Could not find object for node index: "+d,c,t);continue}no(h),r.push(this.createComponents(h,u))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let n=t[or];if(n){Oi&&console.log(e.name,n);for(let i in n){let r=n[i];Oi&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await qr(this.parser,r),e.userData=e.userData||{},e.userData[or]=e.userData[or]||[],e.userData[or].push(r)}}}};import{EXRLoader as qm}from"three/examples/jsm/loaders/EXRLoader";var Cc=I("debugexr"),Ta=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",Cc&&console.log(e)}loadTexture(e){let t=this.name,n=this.parser,r=n.json.textures[e];if(Cc&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],a=new qm(n.options.manager);return Cc&&console.log("EXT_texture_exr.loadTexture",s,a),n.loadTextureImage(e,s.source,a)}};var Lh="NEEDLE_gameobject_data",Ra=class{get name(){return Lh}parser;constructor(e){this.parser=e}afterRoot(e){let t=[];for(let n=0;n<this.parser.json.nodes.length;n++){let i=this.parser.json.nodes[n];if(i&&i.extensions){let r=i.extensions[Lh];if(r){let s=this.findAndApplyExtensionData(n,r);t.push(s)}}}return Promise.all(t).then(()=>{})}async findAndApplyExtensionData(e,t){let n=await this.parser.getDependency("node",e);n&&this.applyExtensionData(n,t)}applyExtensionData(e,t){e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};import{AmbientLight as Ym,Color as jh,HemisphereLight as Km}from"three";var Hh="NEEDLE_lighting_settings",ho=I("debugenvlight"),Sa=class{get name(){return Hh}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[Hh];if(n){ho&&console.log(n);let i=R.addNewComponent(e.scene,Tc,!1);i.sourceId=this.sourceId,i.ambientIntensity=n.ambientIntensity,i.ambientLight=new jh().fromArray(n.ambientLight),Array.isArray(n.ambientTrilight)&&(i.ambientTrilight=n.ambientTrilight.map(r=>new jh().fromArray(r))),i.ambientMode=n.ambientMode,i.environmentReflectionSource=n.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(i)}}return null}},Tc=class extends O{ambientMode=0;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=0;_hasReflection=!1;_ambientLightObj;_lightProbeObj;awake(){if(this.sourceId){let e=this.environmentReflectionSource===0?1:2,t=this.context.lightmaps.tryGet(this.sourceId,e,0);this._hasReflection=t!=null,t&&this.context.rendererData.registerReflection(this.sourceId,t)}ho&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(ho&&console.log("Enable scene lighting",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),e||ho&&console.warn("This is no active?!",this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&!this._ambientLightObj&&(this._ambientLightObj=new Ym(this.ambientLight,Math.PI*this.ambientIntensity)),this._ambientLightObj&&this.gameObject.add(this._ambientLightObj),this._lightProbeObj&&this._lightProbeObj.removeFromParent();else if(this.ambientMode===1){if(this.ambientTrilight){let t=this.ambientTrilight[0],n=this.ambientTrilight[this.ambientTrilight.length-1],i=new Km(n,t,this.ambientIntensity);this.gameObject.add(i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._lightProbeObj?this.enabled&&this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj):this.sourceId&&this.context.rendererData.getSceneLightingData(this.sourceId).then(t=>{ho&&console.log(t),t&&(this._lightProbeObj=t.lightProbe,this.enabled&&!this.destroyed&&this._lightProbeObj&&this.scene.add(this._lightProbeObj))});this.sourceId&&this.context.rendererData.enableReflection(this.sourceId)}onDisable(){ho&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};import{NeverStencilFunc as Jm,LessStencilFunc as Zm,EqualStencilFunc as $m,LessEqualStencilFunc as eg,GreaterStencilFunc as tg,NotEqualStencilFunc as ng,GreaterEqualStencilFunc as ig,AlwaysStencilFunc as rg,ZeroStencilOp as og,KeepStencilOp as sg,ReplaceStencilOp as ag,IncrementStencilOp as lg,DecrementStencilOp as cg,IncrementWrapStencilOp as dg,DecrementWrapStencilOp as ug,InvertStencilOp as hg}from"three";var Rc=I("debugstencil");function pg(o,e){return(o&1<<e.layer)!=0}var pr=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(Rc&&console.log(t,pr.stencils),!t)return;let n=pr.stencils[t];if(!!n)for(let i=n.length-1;i>=0;i--){let r=n[i];if(pg(r.layer,e)){Rc&&console.log(r);let s=e.sharedMaterial?.clone();s&&(e.sharedMaterial=s,e.gameObject.renderOrder=r.event*1e3+r.index*50,s.stencilWrite=!0,s.stencilWriteMask=255,s.stencilFuncMask=255,s.stencilRef=r.value,s.stencilFunc=r.compareFunc,s.stencilZPass=r.passOp,s.stencilFail=r.failOp,s.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let n=t[mg];if(n){Rc&&console.log(n);let i=n.stencil;if(i&&Array.isArray(i))for(let r of i){let s={...r};s.compareFunc=fg(s.compareFunc),s.passOp=Sc(s.passOp),s.failOp=Sc(s.failOp),s.zFailOp=Sc(s.zFailOp),pr.stencils[this.source]||(pr.stencils[this.source]=[]),pr.stencils[this.source].push(s)}}}return null}},fr=pr;j(fr,"stencils",{});function Sc(o){switch(o){case 0:return sg;case 1:return og;case 2:return ag;case 3:return lg;case 4:return cg;case 6:return dg;case 7:return ug;case 5:return hg}return 0}function fg(o){switch(o){case 1:return Jm;case 2:return Zm;case 3:return $m;case 4:return eg;case 5:return tg;case 6:return ng;case 7:return ig;case 8:return rg}return 0}var mg="NEEDLE_render_objects";import{TextureLoader as gg}from"three";import{GLTFLoader as bg}from"three/examples/jsm/loaders/GLTFLoader";var Pc="NEEDLE_deferred_texture",Ye=I("debugprogressive"),kc=new Map,Oc=!1;Ye&&window.addEventListener("keyup",o=>{o.key==="p"&&(kc.forEach((e,t)=>{Object.entries(e).forEach(([n,i])=>{Oc?t[n]=i.lod0:t[n]=i.original,t.needsUpdate=!0})}),Oc=!Oc)});var rs=class{static assignTextureLOD(e,t,n,i=0){if(!!n)for(let r of Object.keys(n)){let s=n[r];s?.isTexture===!0&&(Ye&&console.log(`-----------
175
+ `,"FIND",n.name,r,s?.name,s?.userData,s),rs.getOrLoadTexture(e,t,n,r,s,i).then(a=>{if(a?.isTexture===!0&&(a.needsUpdate=!0,Ye&&console.log("Assign LOD",n.name,r,a.name,a.guid,n,"Prev:",s,"Now:",a,`
176
+ --------------`),n[r]=a,n.needsUpdate=!0,Ye)){let c=kc.get(n);c||(c={},kc.set(n,c));let d=c[r];d||(d=c[r]={original:s,lod0:a}),d.lod0=a}}))}}get name(){return Pc}parser;sourceId;context;constructor(e,t,n){this.parser=e,this.sourceId=t,this.context=n}_loading=[];afterRoot(e){return Ye&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,n)=>{if(t?.extensions){let i=t?.extensions[Pc];if(i){let r=this.parser.getDependency("texture",n);this._loading.splice(this._loading.indexOf(n),1),r.then(s=>{Ye&&console.log("register texture",s.name,s.uuid,i),s.userData.deferred=i,rs.cache.set(s.uuid,i)})}}}),null}static async getOrLoadTexture(e,t,n,i,r,s){let a=r.uuid,c=rs.cache.get(a);if(c){Ye&&console.log(a,c.uri,c.guid);let d=nn(t,c.uri);if(d.endsWith(".glb")||d.endsWith(".gltf")){if(!c.guid)return console.warn("missing pointer for glb/gltf texture",c),null;let l=d+"_"+c.guid;if(this.resolved[l])return Ye&&console.log("Texture has already been loaded: "+l,n.name,i,r.name),this.resolved[l];let u=new bg;Yn(u,e),Ye&&console.log("Load "+d,n.name,i,c.guid);let h=await u.loadAsync(d),b=h.parser;Ye&&console.log("Loading finished "+d,n.name,i,c.guid);let _=-1,v=!1;for(let m of h.parser.json.textures)if(_++,m?.extensions){let f=m?.extensions[Pc];if(f?.guid&&f.guid===c.guid){v=!0;break}}if(!v)return null;let y=await b.getDependency("texture",_);return y&&(y.guid=c.guid),this.resolved[l]=y,Ye&&console.log(n.name,i,'change "'+r.name+'" \u2192 "'+y.name+'"',d,_,y,n,l),y}else{Ye&&console.log("Load texture from uri: "+d);let u=await new gg().loadAsync(d);return u&&Ye?console.log(c,u):console.warn("failed loading",d),u}}else Ye&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},Jn=rs;j(Jn,"cache",new Map),j(Jn,"resolved",{});function Mc(o){let e=new uo;return o.register(t=>(e.parser=t,e)),e}var Ic=class{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}};function Dc(o,e,t){o.register(i=>new Ra(i)),o.register(i=>new Ss(i)),o.register(i=>new ga(i,e.lightmaps,t)),o.register(i=>new Sa(i,t,e)),o.register(i=>new xa(i,t)),o.register(i=>new fr(i,t)),o.register(i=>new Jn(i,t,e)),o.register(i=>new Ta(i));let n=o.setAnimationPointerResolver;typeof n=="function"&&n.bind(o)(new Ic)}import{Vector3 as vg}from"three";var Zn=class extends O{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new vg}update(){if(!this.from||!this.to)return;let e=B(this.from).clone(),t=B(this.to).clone(),n=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),J(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(B(this.to).clone()),this.gameObject.scale.set(this.width,this.width,n)}};C([x(R)],Zn.prototype,"from",2),C([x(R)],Zn.prototype,"to",2);var un=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};C([x()],un.prototype,"time",2),C([x()],un.prototype,"value",2),C([x()],un.prototype,"inTangent",2),C([x()],un.prototype,"inWeight",2),C([x()],un.prototype,"outTangent",2),C([x()],un.prototype,"outWeight",2),C([x()],un.prototype,"weightedMode",2);var ki=class{keys;get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;let t=null;for(let n of this.keys){if(t&&n.time>e&&e>t.time)return W.lerp(t.value,n.value,(e-t.time)/(n.time-t.time));t=n}return this.keys[this.keys.length-1].value}};C([x(un)],ki.prototype,"keys",2);import*as Bh from"three";import*as os from"three";import{PositionalAudioHelper as yg}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var Ke=I("debugaudio");var xe=class extends O{static get userInteractionRegistered(){return xe._didCallBeginWaitForUserInteraction||(xe._didCallBeginWaitForUserInteraction=!0,xe._beginWaitForUserInteraction()),xe._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),xe._didCallBeginWaitForUserInteraction||(xe._didCallBeginWaitForUserInteraction=!0,xe._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let n=(()=>{if(n!=null&&!xe._userInteractionRegistered){xe._userInteractionRegistered=!0,console.log("registered interaction, can play audio now"),document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n);for(let i of this.callbacks)i();this.callbacks.length=0}}).bind(this);document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)}clip="";playOnAwake=!1;get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&(Ke&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;get Sound(){if(!this.sound&&xe._userInteractionRegistered){let e=R.getComponent(this.context.mainCamera,Rt)??R.findObjectOfType(Rt,this.context);e?.listener&&(this.sound=new os.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new os.AudioLoader,this.playOnAwake&&(this.shouldPlay=!0),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this.isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}}),this._focusCallback=()=>{this.enabled&&this.playOnAwake&&!this.isPlaying&&xe._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){xe._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():xe._beginWaitForUserInteraction(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.loadAndPlay(this.clip)})}onDisable(){this.stop()}lerp=(e,t,n)=>e*(1-n)+t*n;onLoaded(e){Ke&&console.log("audio buffer loaded"),xe.registerWaitForAllowAudio(()=>{Ke&&console.log("finished loading",e);let t=this.Sound;if(!t){console.warn("Failed getting sound",this.name);return}t.isPlaying&&t.stop(),t.setBuffer(e),t.loop=this.loop,t.setVolume(this.volume),t.autoplay=this.shouldPlay,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),Ke&&console.log(this.name,this.shouldPlay,xe.userInteractionRegistered,this),this.shouldPlay&&xe._userInteractionRegistered&&this.play()})}applySpatialDistanceSettings(){let e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;let t=this.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Ke&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:break}this.spatialBlend>0?Ke&&!this.helper&&(this.helper=new yg(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(Ke&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new os.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){Ke&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,Ke&&console.log("load audio",this.clip),this.audioLoader.load(this.clip,this.onLoaded.bind(this),()=>{},console.error)}}play(e=void 0){if(!this.audioLoader||!this.sound||e&&e!==this.clip){this.loadAndPlay(e);return}this.shouldPlay=!0,this._hasEnded=!1,Ke&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){Ke&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){Ke&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,Ke&&console.log(this._lastContextTime),this.sound.stop())}_lastContextTime=0;get isPlaying(){return this.sound?.isPlaying??!1}set isPlaying(e){}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;let t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,Ke&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},Z=xe;j(Z,"_didCallBeginWaitForUserInteraction",!1),j(Z,"callbacks",[]),j(Z,"_userInteractionRegistered",!1),C([x()],Z.prototype,"clip",2),C([x()],Z.prototype,"playOnAwake",2),C([x()],Z.prototype,"loop",1),C([x()],Z.prototype,"spatialBlend",1),C([x()],Z.prototype,"minDistance",1),C([x()],Z.prototype,"maxDistance",1),C([x()],Z.prototype,"volume",1),C([x()],Z.prototype,"rollOffMode",2);import*as $n from"three";import{Color as _g}from"three";var ce=class extends _g{alpha=1;get isRGBAColor(){return!0}constructor(e,t,n,i){super(e,t,n),this.alpha=i}clone(){let e=super.clone();return e.alpha=this.alpha,e}copy(e){return super.copy(e),"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){let n=e;return n.alpha&&(this.alpha=W.lerp(this.alpha,n.alpha,t)),super.lerp(e,t)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as wg}from"three";var Fh=I("debugcam"),ie=class extends O{get aspect(){return this._cam instanceof wg?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._fov}set fieldOfView(e){let t=this._fov!=e;this._fov=e,t&&this._cam&&this._cam instanceof $n.PerspectiveCamera&&(this._cam.fov=this._fov,this._cam.updateProjectionMatrix())}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){let t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&t&&(this._cam.near=e,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(e){let t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&t&&(this._cam.far=e,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;_nearClipPlane=.1;_farClipPlane=1e3;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){if(!!e){if(this._backgroundColor)this._backgroundColor.copy(e);else{if(!e.clone)return;this._backgroundColor=e.clone()}this.applyClearFlagsIfIsActiveCamera()}}_backgroundColor;_fov=60;_cam=null;_clearFlags=2;_skybox;get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name)}onEnable(){Fh&&console.log(this),this.buildCamera(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?t=this.gameObject:t=this.gameObject.children[0],t&&t.isCamera)t.type==="PerspectiveCamera"&&(t.fov=this._fov,t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new $n.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let n=this.orthographicSize*100;t=new $n.OrthographicCamera(window.innerWidth/-n,window.innerWidth/n,window.innerHeight/n,window.innerHeight/-n,this._nearClipPlane,this._farClipPlane)}this._cam=t,this.layer===0&&this._cam.layers.enableAll(),this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(this._cam&&this.context.mainCameraComponent===this)switch(this._clearFlags){case 1:if(this.environmentIsTransparent()&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox();break;case 2:if(this._backgroundColor){let e=this._backgroundColor.alpha;this.environmentIsTransparent()&&(e=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,e)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}environmentIsTransparent(){let e=this.context.renderer.xr?.getSession();if(!e)return!1;let t=e.environmentBlendMode,n=t==="additive"||t==="alpha-blend";return t==="opaque"&&navigator.userAgent?.includes("OculusBrowser")&&this.context.xrSessionMode==="immersive-ar"?!0:n}enableSkybox(){this._skybox||(this._skybox=new Ac(this)),this._skybox.enable()}};C([x()],ie.prototype,"fieldOfView",1),C([x()],ie.prototype,"nearClipPlane",1),C([x()],ie.prototype,"farClipPlane",1),C([x()],ie.prototype,"clearFlags",1),C([x()],ie.prototype,"orthographic",2),C([x()],ie.prototype,"orthographicSize",2),C([x()],ie.prototype,"ARBackgroundAlpha",2),C([x(ce)],ie.prototype,"backgroundColor",1);var Ac=class{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?(Fh&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=$n.sRGBEncoding,this._skybox.mapping=$n.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};var Rt=class extends O{get listener(){return this._listener==null&&(this._listener=new Bh.AudioListener),this._listener}_listener=null;awake(){Z.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=R.getComponentInParent(this.gameObject,ie);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as xg}from"three/examples/jsm/loaders/GLTFLoader";import*as Pa from"three";var ss=I("debugavatar"),Ii=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,n,i){this.root=e,this.head=t,this.leftHand=n,this.rigthHand=i,this.root?.traverse(r=>r.layers.set(2))}},ei=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let n=null;if(typeof t=="string"){if(n=await this.loadAvatar(e,t),!n){let r=new Ie;n=R.instantiate(vi(t,e.scene),r)}}else n=t;if(!n)return null;let i=this.findAvatar(n);return i.isValid?(ss&&console.log("[Custom Avatar] valid config",t,ss?i:""),i):(console.warn("[Custom Avatar] config isn't valid",t,ss?i:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(ss&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){let i=await fetch("./"+t),r=null;if(i.ok){let a=await i.blob();a&&(r=await a.arrayBuffer())}return!r&&(r=await aa(t,t,0,"no url here go away",!0),!r)?null:(await Le().parseSync(e,r,null,0))?.scene??null}let n=new xg;return Yn(n,e),new Promise((i,r)=>{let s=this.avatarRegistryUrl+"/"+t;n.load(s,async a=>{await Le().createBuiltinComponents(e,s,a,null,void 0),i(a.scene)},a=>{ss&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),i(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,n=t;n.children.length==1&&(n=e.children[0]);let i=this.findAvatarPart(n,["head"]),r=this.findAvatarPart(n,["left","hand"]),s=this.findAvatarPart(n,["right","hand"]);if(!i){i=t;let c=new Pa.Vector3;new Pa.Box3().setFromObject(i).getSize(c);let d=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+d+" meters! Should be < 0.3m"),d>.3&&i.scale.multiplyScalar(1/d*.3)}return new Ii(t,i,r,s)}findAvatarPart(e,t){let n=e.name.toLowerCase(),i=!0;for(let r of t){if(!i)break;n.indexOf(r)===-1&&(i=!1)}if(i)return e;if(e.children)for(let r of e.children){let s=this.findAvatarPart(r,t);if(s)return s}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as Cg}from"three";var hn=class extends O{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!rn)return;this._axes||(this._axes=new Cg(this.length)),this.gameObject.add(this._axes);let e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){!this._axes||this.gameObject.remove(this._axes)}};C([x()],hn.prototype,"length",2),C([x()],hn.prototype,"depthTest",2),C([x()],hn.prototype,"isGizmo",2);import*as Uh from"three";var mr=class extends O{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=B(this.to).clone(),t=B(this.from).clone(),n=e.distanceTo(t),i=e.clone();i.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let s=B(this.hint).clone();s.sub(r);let a=new Uh.Vector3;a.crossVectors(s,i),a.crossVectors(i,a),a.normalize();let c=n*.5,d=Math.max(this.desiredDistance,c),l=Math.sqrt(d*d-c*c),u=a.clone();u.multiplyScalar(l),u.add(r),J(this.gameObject,u);let h=r.clone();h.sub(a),this.gameObject.lookAt(h)}};import*as gr from"three";import*as pn from"three";var Tg=new pn.BoxGeometry(1,1,1);function Oa(o=null){let e=new pn.Color(o??14540253),t=new pn.EdgesGeometry(Tg);return new pn.LineSegments(t,new pn.LineBasicMaterial({color:e}))}var Sg=I("gizmos"),at=class extends O{box=null;_lastMatrixUpdateFrame=-1;isInBox(e,t){if(!!e){if(this.box||(this.box=new gr.Box3),e.type==="Mesh")at.testBox.setFromObject(e);else if(e.type==="Group"){if(e.children.length>0){at.testBox.setFromCenterAndSize(at._position.set(0,0,0),at._size.set(0,0,0));for(let n=0;n<e.children.length;n++)e.children[n].type==="Mesh"&&at.testBox.expandByObject(e)}}else{let n=B(e,at._position),i=on(e,at._size);t!==void 0&&i.multiplyScalar(t),at.testBox.setFromCenterAndSize(n,i)}return this.updateBox(),this.box?.intersectsBox(at.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new gr.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){let t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;let n=t,i=B(this.gameObject,at._position,n),r=on(this.gameObject,at._size);this.box.setFromCenterAndSize(i,r)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!Sg&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Oa(e),this.gameObject.add(this._helper)}}},Ce=at;j(Ce,"testBox",new gr.Box3),j(Ce,"_position",new gr.Vector3),j(Ce,"_size",new gr.Vector3(.01,.01,.01));import*as po from"three";import{Vector3 as Gh}from"three";var Gt=function(o,e){return function(t,n,i){Pg(t,n,i,o,e)}};function Pg(o,e,t,n,i){if(!(!i&&!n&&!o.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),yi("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,2);return}if(o.__internalAwake){let r=Symbol(e),s=o.__internalAwake;o.__internalAwake=function(){this[r]===void 0&&(this[r]=this[e],Object.defineProperty(this,e,{set:function(a){if(this[Ms]===!0)this[r]=a;else{n?.call(this,a);let c=this[r];this[r]=a,this.onValidate?.call(this,e,c)}},get:function(){return i?.call(this),this[r]}})),s.call(this)}}}}var Lc=class{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;reset(){this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1}mute=!1;applyValues(){this.positionChanged&&this.obj.position.copy(this.position),this.rotationChanged&&this.obj.quaternion.copy(this.quaternion)}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new Un(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position=this.obj.position.clone(),this._positionWatch.subscribeWrite((n,i)=>{this.context.physics.isUpdating||this.mute||(this.position[i]=n,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new Un(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion=this.obj.quaternion.clone(),this._rotationWatch.subscribeWrite((n,i)=>{this.context.physics.isUpdating||this.mute||(this.quaternion[i]=n,this.rotationChanged=!0)}))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}},ka=class extends O{mass=1;useGravity=!0;constraints=0;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=0;get lockPositionX(){return(this.constraints&2)!==0}get lockPositionY(){return(this.constraints&4)!==0}get lockPositionZ(){return(this.constraints&8)!==0}get lockRotationX(){return(this.constraints&16)!==0}get lockRotationY(){return(this.constraints&32)!==0}get lockRotationZ(){return(this.constraints&64)!==0}set lockPositionX(e){e?this.constraints|=2:this.constraints&=-3}set lockPositionY(e){e?this.constraints|=4:this.constraints&=-5}set lockPositionZ(e){e?this.constraints|=8:this.constraints&=-9}set lockRotationX(e){e?this.constraints|=16:this.constraints&=-17}set lockRotationY(e){e?this.constraints|=32:this.constraints&=-33}set lockRotationZ(e){e?this.constraints|=64:this.constraints&=-65}_propertiesChanged=!1;_currentVelocity;_smoothedVelocity;_smoothedVelocityGetter;_lastPosition;_watch;awake(){this._watch=void 0,this._currentVelocity=new po.Vector3,this._smoothedVelocity=new po.Vector3,this._smoothedVelocityGetter=new po.Vector3,this._lastPosition=new po.Vector3}onEnable(){this._watch||(this._watch=new Lc(this.gameObject,this.context)),this._watch.start(!0,!0)}onDisable(){this._watch?.stop(),this.context.physics.removeBody(this)}onDestroy(){this.context.physics.removeBody(this)}onValidate(){this._propertiesChanged=!0}earlyUpdate(){this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.updateProperties(this)),this._watch?.isDirty&&(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()),this.captureVelocity()}get body(){return this.context.physics.internal_getRigidbody(this)}resetForces(){this.body?.resetForces(!0)}resetTorques(){this.body?.resetTorques(!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.addForce(e,!0)}applyImpulse(e){this.body?.applyImpulse(e,!0)}setForce(e,t,n){this.body?.resetForces(!0),this.body?.addForce({x:e,y:t,z:n},!0)}getVelocity(){let e=this.body?.linvel();return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,n){if(e instanceof Gh){let i=e;this.body?.setLinvel(i,!0);return}t===void 0||n===void 0||this.body?.setLinvel({x:e,y:t,z:n},!0)}setAngularVelocity(e,t,n){if(e instanceof Gh){let i=e;this.body?.setAngvel(i,!0);return}t===void 0||n===void 0||this.body?.setAngvel({x:e,y:t,z:n},!0)}setTorque(e,t,n){this.setAngularVelocity(e,t,n)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){this.gameObject&&this.destroyed}captureVelocity(){if(this.body){let e=B(this.gameObject);ka.tempPosition.copy(e);let t=e.sub(this._lastPosition);this._lastPosition.copy(ka.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}}},K=ka;j(K,"tempPosition",new po.Vector3),C([Gt(),x()],K.prototype,"mass",2),C([Gt(),x()],K.prototype,"useGravity",2),C([Gt(),x()],K.prototype,"constraints",2),C([Gt(),x()],K.prototype,"isKinematic",2),C([Gt(),x()],K.prototype,"drag",2),C([Gt(),x()],K.prototype,"angularDrag",2),C([Gt(),x()],K.prototype,"detectCollisions",2),C([Gt(),x()],K.prototype,"sleepThreshold",2),C([Gt(),x()],K.prototype,"collisionDetectionMode",2);import{Mesh as Og,Vector3 as fo}from"three";var jc=class{getCollider(e){return Xn(e,lt)}};Ku(new jc);var lt=class extends O{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(K))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(K))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(K))}onDisable(){this.context.physics.removeBody(this)}};C([x(K)],lt.prototype,"attachedRigidbody",2),C([x()],lt.prototype,"isTrigger",2);var ti=class extends lt{radius=.5;center=new fo(0,0,0);onEnable(){super.onEnable(),this.context.physics.addSphereCollider(this,this.center,this.radius)}};C([x()],ti.prototype,"radius",2),C([x(fo)],ti.prototype,"center",2);var ni=class extends lt{size=new fo(1,1,1);center=new fo(0,0,0);onEnable(){super.onEnable(),this.context.physics.addBoxCollider(this,this.center,this.size)}};C([x(fo)],ni.prototype,"size",2),C([x(fo)],ni.prototype,"center",2);var Mi=class extends lt{sharedMesh;convex=!1;awake(){console.log(this)}onEnable(){super.onEnable(),this.sharedMesh?.isMesh||this.gameObject instanceof Og&&(this.sharedMesh=this.gameObject),this.sharedMesh?.isMesh&&this.context.physics.addMeshCollider(this,this.sharedMesh,this.convex)}};C([x()],Mi.prototype,"convex",2);var ct=class extends O{canGrab=!0;onPointerClick(e){}},dt=class extends O{isUsed=!0;usedBy=null};var Di=class extends Ce{},br=class extends O{deleteBoxes=[];awake(){this.deleteBoxes=R.findObjectsOfType(Di,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(R.getComponentInParent(this.gameObject,dt)||Zr(this.gameObject,this.context.connection))}}};var Ai=class extends O{visibleOn;onEnable(){this.apply()}apply(){this.test()||R.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:kg()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};C([x()],Ai.prototype,"visibleOn",2);var Ia;function kg(){if(Ia===!0||Ia===!1)return Ia;let o=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),Ia=o,o}import*as ii from"three";var ve=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,n,i){return e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var mo=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new ve).__init(this.bb_pos,this.bb)}rotation(e){return(e||new ve).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new ve).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,n,i,r,s,a,c,d,l){return e.prep(4,36),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(d),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(s),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var St=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new St).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new St).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){let e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){let t=this.bb.__offset(this.bb_pos,8);return t?(e||new mo).__init(this.bb_pos+t,this.bb):null}dontSave(){let e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}};var Li=I("debugsync"),go="STRS";so(go,St.getRootAsSyncedTransformModel);var fn=new rt;function Hc(o,e,t=!0){fn.clear();let n=fn.createString(o);St.startSyncedTransformModel(fn),St.addGuid(fn,n),St.addFast(fn,t);let i=e.worldPosition,r=e.worldEuler,s=e.gameObject.scale;St.addTransform(fn,mo.createTransform(fn,i.x,i.y,i.z,r.x,r.y,r.z,s.x,s.y,s.z));let a=St.endSyncedTransformModel(fn);return fn.finish(a,go),fn.asUint8Array()}var Je=class extends O{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){Li&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){Li&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new ii.Vector3,this._targetRotation=new ii.Quaternion,this.lastWorldPos=new ii.Vector3,this.lastWorldRotation=new ii.Quaternion,this.rb=R.getComponentInChildren(this.gameObject,K),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Ci(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen("joined-room",this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinrary(go,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Ou(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(go,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new ii.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Li&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();let t=e.transform();if(t){ne.markDirty(this.gameObject,!0);let n=t.position();n&&(this.interpolatePosition&&this._targetPosition?.set(n.x(),n.y(),n.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(n.x(),n.y(),n.z()));let i=t.rotation();i&&(this.tempEuler.set(i.x(),i.y(),i.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&_u(this.gameObject,this.tempEuler))}this._receivedDataBefore=!0}}onEnable(){this.lastWorldPos.copy(this.worldPosition),this.lastWorldRotation.copy(this.worldQuaternion),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastWorldPos;lastWorldRotation;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){Li&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>a||s>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(Li&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastWorldPos),this.worldPosition=this.lastWorldPos,e.copy(this.lastWorldPos),this.worldQuaternion=this.lastWorldRotation,t.copy(this.lastWorldRotation),ne.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let s=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,s),this.worldPosition=c,a=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,s),this.worldQuaternion=c,a=!0}a&&ne.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastWorldPos.copy(e),this.lastWorldRotation.copy(t),!this._model)return;if(!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership){this.rb&&(this.rb.isKinematic=this._model.isOwned??!1,this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject());return}this.rb&&(this._wasKinematic!==void 0&&(Li&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new ii.Vector3(0,0,0))>1e3&&(Li&&console.log("RESET",this.name),this.gameObject.position.set(0,1,0),this.rb.setVelocity(0,0,0),this.rb.setBodyFromGameObject()));let n=10,i=this.rb||this.fastMode;if(this._needsUpdate&&(n<=0||n>0&&this.context.time.frameCount%n===0||i)){Li&&console.log("send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this.overridePhysics&&this.rb&&this.rb.setBodyFromGameObject(),this._needsUpdate=!1;let r=Hc(this.guid,this,!!i);this.context.connection.sendBinary(r)}}};import*as Q from"three";import{Euler as nb,EventDispatcher as ib,Group as rb,Matrix4 as Zh,Mesh as ob,MeshBasicMaterial as sb,Object3D as Jh,Quaternion as Qc,RingGeometry as ab,Vector3 as $h}from"three";var Ma=class{static createButton(e,t={}){let n=document.createElement("button");function i(){if(t.domOverlay===void 0){var c=document.createElement("div");c.style.display="none",document.body.appendChild(c);var d=document.createElementNS("http://www.w3.org/2000/svg","svg");d.setAttribute("width",38),d.setAttribute("height",38),d.style.position="absolute",d.style.right="20px",d.style.top="20px",d.addEventListener("click",function(){u.end()}),c.appendChild(d);var l=document.createElementNS("http://www.w3.org/2000/svg","path");l.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),l.setAttribute("stroke","#fff"),l.setAttribute("stroke-width",2),d.appendChild(l),t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("dom-overlay"),t.domOverlay={root:c}}t.optionalFeatures===void 0&&(t.optionalFeatures=[]),t.optionalFeatures.push("local-floor"),t.optionalFeatures.push("hand-tracking"),t.optionalFeatures.push("layers");let u=null;async function h(_){_.addEventListener("end",b),await e.xr.setSession(_),n.textContent="STOP AR",t.domOverlay.root.style.display="",u=_}function b(){u.removeEventListener("end",b),n.textContent="START AR",t.domOverlay.root.style.display="none",u=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="START AR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){u===null?navigator.xr.requestSession("immersive-ar",t).then(h):u.end()}}function r(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function s(){r(),n.textContent="AR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return n.id="ARButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?i():s()}).catch(s),n;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",a(c),c}}};var Da=class{static createButton(e,t){t&&console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');let n=document.createElement("button");function i(){let c=null;async function d(u){u.addEventListener("end",l),await e.xr.setSession(u),n.textContent="EXIT VR",c=u}function l(){c.removeEventListener("end",l),n.textContent="ENTER VR",c=null}n.style.display="",n.style.cursor="pointer",n.style.left="calc(50% - 50px)",n.style.width="100px",n.textContent="ENTER VR",n.onmouseenter=function(){n.style.opacity="1.0"},n.onmouseleave=function(){n.style.opacity="0.5"},n.onclick=function(){if(c===null){let u={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",u).then(d)}else c.end()}}function r(){n.disabled=!0,n.style.display="",n.style.cursor="auto",n.style.left="calc(50% - 75px)",n.style.width="150px",n.onmouseenter=null,n.onmouseleave=null,n.onclick=null}function s(){r(),n.textContent="VR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return n.id="VRButton",n.style.display="none",a(n),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?i():s(),Da.xrSessionIsGranted&&(console.log("XR session is granted - will enter immersive web now"),n.click())}),n;{let c=document.createElement("a");return window.isSecureContext===!1?(c.href=document.location.href.replace(/^http:/,"https:"),c.innerHTML="WEBXR NEEDS HTTPS"):(c.href="https://immersiveweb.dev/",c.innerHTML="WEBXR NOT AVAILABLE"),c.style.left="calc(50% - 90px)",c.style.width="180px",c.style.textDecoration="none",a(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),Da.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},vo=Da;j(vo,"xrSessionIsGranted",!1);vo.registerSessionGrantedListener();import*as Aa from"three";var Vh=Cs(ta(),1);import{AudioAnalyser as Ig}from"three";var yo="noVoip",Ze=I("debugvoip"),Mg=I("voip");var Fc=class{id;constructor(e){this.id=e}};var Bc=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,n,i){this.voip=e,this.peer=t,this.userId=n,this.peerId=i}close(){Ze&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let n of t)n.enabled=!e}async startVoipCall(){if(!await He.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}Ze&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),Ze&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{Ze&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(n){n.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){Ze&&console.log("call closed",e)}},Uc=class{get currentStream(){return this.stream}get currentAudio(){return this.audio}get currentAnalyzer(){return this.analyzer}voip;call;audio=null;stream=null;obj;analyzer=null;waitingForStart=!1;closed=!1;audioElement=null;constructor(e,t,n){this.voip=e,this.obj=t,this.call=n}openAudioStream(e){let t=e.getAudioTracks();for(let n of t)if(n.kind==="audio"&&n.readyState==="live"){this.open(n);return}console.warn("failed finding valid audio stream to begin call")}open(e){console.assert(e.kind==="audio","invalid track kind, expected audio but received "+e.kind),!this.waitingForStart&&(this.waitingForStart=!0,Z.userInteractionRegistered||Ze&&console.log("Incoming call, waiting for user interaction before opening audio"),Z.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){Ze&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Aa.AudioListener;this.audio=new Aa.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let n=document.createElement("audio");this.audioElement=n,n.style.display="none",document.body.appendChild(n),n.srcObject=this.stream,n.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(i=>{if(!!n){console.log(i);for(let r of i)if(r.label==="Speakerphone"){n.sinkId=r.deviceId;break}}}),Ze&&console.log("call is setup, you should hear something now"),this.analyzer=new Ig(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},He=class extends O{requireParam=!1;set muteInput(e){if(e===this._inputMuted||(this._inputMuted=e,!this.currentIncomingCalls))return;let t=this._inputMuted?0:1;for(let n in this.currentIncomingCalls)this.currentIncomingCalls[n]?.currentAudio?.setVolume(t)}get muteInput(){return this._inputMuted}set muteOutput(e){if(e!==this._outputMuted&&(this._outputMuted=e,!!this.connections))for(let t in this.connections)this.connections[t]?.updateMute(e)}get muteOutput(){return this._outputMuted}getFrequency(e){if(e===null){for(let n in this.currentIncomingCalls){let i=this.currentIncomingCalls[n];if(i&&i.currentAnalyzer)return i.currentAnalyzer.getAverageFrequency()}return null}let t=this.currentIncomingCalls[e];return t&&t.currentAnalyzer?t.currentAnalyzer.getAverageFrequency():null}peer=null;model=null;connections={};currentIncomingCalls={};_inputMuted=!1;_outputMuted=!1;awake(){if(I(yo)){console.log("VOIP is disabled by url parameter: "+yo);return}if(this.requireParam&&!Mg){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Vh.default,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,this.context.connection.beginListen("joined-room",e=>{navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}),this.context.connection.beginListen("peer-update-id",e=>{if(e.id!==this.context.connection.connectionId){let t=this.connections[e.id];if(t&&t.close(),this.peer&&this.context.connection.connectionId){let n=new Bc(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=n,n.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,n=this.connections[t];this.connections[t]=null,n&&n.close();let i=this.currentIncomingCalls[t];Ze&&console.log("UserLeftRoom",e,t,i),i&&(i.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){Ze&&console.log("Peer connection established and received id"),this.model=new Fc(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){Ze&&console.log("CONNECTION",t),t.on("data",function(n){Ze&&console.log("Received",n)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:n}=t,{peer:i}=e,r=this.currentIncomingCalls[n];if(r&&r.close(),Ze&&console.log("received call"),await He.HasMicrophonePermissions()){let s=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(s)}else e.answer(null);this.currentIncomingCalls[n]=new Uc(this,this.gameObject,e),e.on("stream",s=>{Ze&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[n]?.openAudioStream(s)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};import{Matrix4 as as}from"three";var ut=class extends O{webAR=null;get rig(){return this.webAR?.webxr.Rig}invertForward=!1;get arScale(){return this._arScale}set arScale(e){e!==this._arScale&&(this._arScale=e,this.setScale(e))}_initalMatrix=new as;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=R.findObjectOfType(U);e&&(e.Rig.updateMatrix(),this._initalMatrix.copy(e.Rig.matrix))}_arScale=5;_rig=null;_startPose=null;_placementPose=null;_isTouching=!1;_rigStartPose=null;onBegin(e){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose=this.gameObject.matrix.clone(),this._rigStartPose=this.rig?.matrix.clone(),e.addEventListener("selectstart",this._selectStartFn),e.addEventListener("selectend",this._selectEndFn),this.gameObject.visible=!1,this.rig&&(this.rig.matrixAutoUpdate=!0,this._initalMatrix.decompose(this.rig.position,this.rig.quaternion,this.rig.scale))}onUpdate(e,t,n){return n&&!this._placementPose&&this._isTouching?(this.webAR&&this.webAR.setReticleActive(!1),this.placeAt(e,new as().fromArray(n.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new as),this._placementPose.copy(t),e){if(this.invertForward){let n=new as().makeRotationY(Math.PI);this._placementPose.premultiply(n)}this._rig=e,this.setScale(this.arScale)}else this._rig=null;this.gameObject.visible=!0}onEnd(e,t){this._placementPose=null,this.gameObject.visible=!1,this.gameObject.matrixAutoUpdate=!1,this._startPose&&this.gameObject.matrix.copy(this._startPose),e&&(e.matrixAutoUpdate=!0,this._rigStartPose&&this._rigStartPose.decompose(e.position,e.quaternion,e.scale)),ne.markDirty(this.gameObject,!0),setTimeout(()=>{this.gameObject.matrixAutoUpdate=!0,this.gameObject.visible=!0},100)}onSelectStart(){this._isTouching=!0}onSelectEnd(){this._isTouching=!1}setScale(e){let t=this._rig;!t||!this._placementPose||(this._rigStartPose||(this._rigStartPose=t.matrix.clone()),t.matrixAutoUpdate=!1,t.matrix.multiplyMatrices(new as().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};C([x()],ut.prototype,"invertForward",2),C([x()],ut.prototype,"arScale",1);import{BoxHelper as Ug,BufferGeometry as Gg,Color as qh,Euler as Vg,Layers as Ng,Line as Wg,Mesh as zg,MeshBasicMaterial as Xg,Quaternion as Ha,Ray as Qg,SphereGeometry as qg,Vector2 as Yg,Vector3 as Wt}from"three";import{OculusHandModel as Kg}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Jg}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import{XRControllerModelFactory as Zg}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{GLTFLoader as $g}from"three/examples/jsm/loaders/GLTFLoader.js";import*as zh from"three";import{Quaternion as Dg,Vector3 as La}from"three";var _o=I("debugflags");var Gc=class{Mask=17;Has(e){let t=this.Mask&e;return _o&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,ue.Apply()}Enable(e){this.Mask|=e,ue.Apply()}Disable(e){this.Mask&=~e,ue.Apply()}Toggle(e){this.Mask^=e,ue.Apply()}EnableAll(){this.Mask=-1,ue.Apply()}DisableAll(){this.Mask=0,ue.Apply()}},$e=Gc;j($e,"Global",new Gc);var mn=class extends O{static Apply(){for(let e of this.registry)e.UpdateVisible($e.Global)}awake(){mn.registry.push(this)}onEnable(){mn.firstApply||(mn.firstApply=!0,mn.Apply())}onDestroy(){let e=mn.registry.indexOf(this);e>=0&&mn.registry.splice(e,1)}visibleIn;get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(!this.enabled)return;let t,n=e;n&&typeof n=="number"&&(console.assert(typeof n=="number","XRFlag.UpdateVisible: state must be a number",n),_o&&console.log(n),mn.buffer.Mask=n,e=mn.buffer);let i=e;if(i?(_o&&console.log("use passed in mask"),t=i.Has(this.visibleIn)):(_o&&console.log("use global mask"),$e.Global.Has(this.visibleIn)),t!==void 0)if(t)_o&&console.trace("is visible",this.name,this.gameObject.uuid),R.setActive(this.gameObject,!0);else{if(_o&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},ue=mn;j(ue,"registry",[]),j(ue,"firstApply"),j(ue,"buffer",new $e);import{Object3D as Vc}from"three";var ji=I("debugavatar"),Vt=class extends O{static getAvatar(e){return e>=0&&e<Vt.instances.length?Vt.instances[e]:null}static onAvatarMarkerCreated(e){return Vt._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Vt._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){Vt.instances.push(this),ji&&console.log(this);for(let e of Vt._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Vt.instances.splice(Vt.instances.indexOf(this),1);for(let e of Vt._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):R.setActive(this.avatar,e))}},re=Vt;j(re,"instances",[]),j(re,"_onNewAvatarMarkerAdded",[]),j(re,"_onAvatarMarkerDestroyed",[]);var ls=class{_isVisible=!0;setVisible(e){this._isVisible=e,this.updateVisibility()}get isWebXRAvatar(){return!0}guid;root=null;head=null;handLeft=null;handRight=null;lastUpdate=-1;isLocalAvatar=!1;flags=null;headScale=new La(1,1,1);handLeftScale=new La(1,1,1);handRightScale=new La(1,1,1);webxr;lastAvatarId=null;hasAvatarOverride=!1;context;avatarMarker=null;constructor(e,t,n){this.context=e,this.guid=t,this.webxr=n,this.setupCustomAvatar(this.webxr.defaultAvatar)}updateFlags(){if(!this.flags)return;let e=this.isLocalAvatar?8:16;for(let t of this.flags)t.gameObject.visible=!0,t.UpdateVisible(e)}async setAvatarOverride(e){return this.hasAvatarOverride=e!==null,this.hasAvatarOverride&&this.lastAvatarId!==e&&(this.lastAvatarId=e,e!=null&&e.length>0)?await this.setupCustomAvatar(e):null}_headTarget=new Vc;_handLeftTarget=new Vc;_handRightTarget=new Vc;_canInterpolate=!1;tryUpdate(e,t){if(e.guid===this.guid&&(this.lastAvatarId!==e.avatarId&&e.avatarId&&e.avatarId.length>0&&(this.lastAvatarId=e.avatarId,this.setupCustomAvatar(e.avatarId)),this.lastUpdate=e.time,this.head)){let n=this.webxr.IsInAR?"handheld":"headset",i=this.head;this.context.players.setPlayerView(e.guid,i,n),ne.markDirty(this.head),this._canInterpolate=!0;let r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){let s=this.isLocalAvatar?this.handLeft:this._handLeftTarget;s.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),s.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),s.quaternion.multiply(ls.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handLeftScale),ne.markDirty(this.handLeft)}if(this.handRight){let s=this.isLocalAvatar?this.handRight:this._handRightTarget;s.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),s.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),s.quaternion.multiply(ls.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handRightScale),ne.markDirty(this.handRight)}}}update(){if(this.isLocalAvatar||!this._canInterpolate)return;let e=this.context.time.deltaTime/.1;this.head&&(this.head.position.lerp(this._headTarget.position,e),this.head.quaternion.slerp(this._headTarget.quaternion,e),this.head.scale.lerp(this._headTarget.scale,e)),this.handLeft&&this._handLeftTarget&&(this.handLeft.position.lerp(this._handLeftTarget.position,e),this.handLeft.quaternion.slerp(this._handLeftTarget.quaternion,e),this.handLeft.scale.lerp(this._handLeftTarget.scale,e)),this.handRight&&this._handRightTarget&&(this.handRight.position.lerp(this._handRightTarget.position,e),this.handRight.quaternion.slerp(this._handRightTarget.quaternion,e),this.handRight.scale.lerp(this._handRightTarget.scale,e))}destroy(){ji&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&de.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&R.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(ji&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&de.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let i=t.asset;R.setActive(i,!1),e=R.instantiate(i),R.setActive(e,!0)}ji&&console.log(e);let n=await ls.loader.getOrCreateNewAvatarInstance(this.context,e);if(ji&&console.log(n,n?.isValid,this.lastAvatarId,e),n?.isValid){if(this.root=n.root,this.root.position.set(0,0,0),this.root.quaternion.set(0,0,0,1),this.root.scale.set(1,1,1),this.avatarMarker=R.addNewComponent(this.root,re),this.avatarMarker.connectionId=this.guid,this.avatarMarker.avatar=this,this.head&&this.head!==n.head&&this.head?.removeFromParent(),this.head=n.head,this.headScale.copy(this.head.scale),this.head&&!this.isLocalAvatar&&de.Add(this.context,this.head,this.avatarMarker),n.leftHand&&this.handLeft?.removeFromParent(),this.handLeft=n.leftHand??this.handLeft,this.handLeft?this.handLeftScale.copy(this.handLeft.scale):this.handLeftScale.set(1,1,1),n.rigthHand&&this.handRight?.removeFromParent(),this.handRight=n.rigthHand??this.handRight,this.handRight?this.handRightScale.copy(this.handRight.scale):this.handRightScale.set(1,1,1),this.context.scene.add(this.root),this.flags==null&&(this.flags=[]),this.flags.length=0,this.flags.push(...R.getComponentsInChildren(this.root,ue)),this.flags.length<=0&&this.head){let i=R.addNewComponent(this.head,ue);i.visibleIn=20,this.flags.push(i),ji&&console.log("Added flag to head: "+i.visibleIn,this.head.name)}return ji&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return ji&&console.warn("build avatar failed"),!1}},ht=ls;j(ht,"loader",new ei),j(ht,"invertRotation",new Dg().setFromAxisAngle(new La(0,1,0),Math.PI));var de=class{static Add(e,t,n=null){if(!!t){for(let i of this.Pois)if(i.obj===t)return;this.Pois.push({obj:t,avatar:n}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(!!t){for(let n of this.Pois)if(n.obj===t){this.Pois.splice(this.Pois.indexOf(n),1),this.LastChangeTime=e?.time.time??V.Current?.time.time;return}}}};j(de,"Pois",[]),j(de,"LastChangeTime",0);var Nc=class{guid;position=new zh.Vector3},gn=class extends O{set controlledTarget(e){this.target=e;let t=M.get("MoveRandom");if(t&&this.target){let n=R.getComponent(this.target,t);n&&n.destroy()}}target=null;avatar=null;_model=null;_targetModel=new Nc;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=R.getComponentInParent(this.gameObject,re),this.avatar){let e=R.getComponentInParent(this.gameObject,re);this._model=new Ci(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&J(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(de.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=de.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=B(this._currentTargetObject);J(this.target,t),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;let t=de.Pois;if(t.length>0){let n=t[Math.floor(Math.random()*t.length)];if(n&&n.obj){if(n.avatar&&n.avatar===this.avatar)return;this._currentTargetObject=n.obj}}}}};import*as ja from"three-mesh-ui";import{OrbitControls as Lg}from"three/examples/jsm/controls/OrbitControls";import{Object3D as Ag}from"three";var bn=class extends O{constraintActive=!0;locked=!1;sources=[]};C([x(Ag)],bn.prototype,"sources",2);import*as cs from"three";var Xh=I("nocamlimits"),Fe=class extends O{get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoRotate=!1;autoRotateSpeed=1;enableKeys=!0;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;middleClickToFocus=!0;doubleClickToFocus=!0;useSlerp=!1;debugLog=!1;targetLerpSpeed=5;_lookTargetPosition;_controls=null;_cameraObject=null;_lerpToTargetPosition=!1;_lerpCameraToTarget=!1;_cameraTargetPosition=null;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;awake(){this._lookTargetPosition=new cs.Vector3,this._startedListeningToKeyEvents=!1}onEnable(){this._enableTime=this.context.time.time;let t=R.getComponent(this.gameObject,ie)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new Lg(t,this.context.renderer.domElement)),this._controls&&(this._controls.enableDamping=this.enableDamping,this._controls.enableKeys=this.enableKeys,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,t?.type==="PerspectiveCamera"?Xh||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):Xh||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body)))}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}onDestroy(){this._controls?.dispose()}start(){if(this._controls){let e=R.getComponent(this.gameObject,ie);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");let t=new cs.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new ge;e.screenPoint=new cs.Vector2(0,0),e.lineThreshold=.1;let t=this.context.physics.raycast(e);t.length>0&&this.setTarget(t[0].point,!0)}}onBeforeRender(){if(!this._controls)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let e=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(e||=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3,e?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){let t=this.context.time.deltaTime*this.targetLerpSpeed;this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject&&(this.useSlerp&&typeof this._cameraObject?.position.slerp=="function"?(this._cameraObject?.position).slerp(this._cameraTargetPosition,t):this._cameraObject?.position.lerp(this._cameraTargetPosition,t),this._cameraObject.position.distanceTo(this._cameraTargetPosition)<.01&&(this._lerpCameraToTarget=!1)),this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,t),this._lookTargetPosition.distanceTo(this._controls.target)<.005&&(this._lerpToTargetPosition=!1))}this.lookAtConstraint?.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!0,this._controls.update())}setCameraTarget(e,t=!1){e?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=e.clone(),t&&this._cameraTargetPosition&&this.controllerObject?.position.copy(this._cameraTargetPosition)):this._lerpCameraToTarget=!1}setFromTargetPosition(e=0,t=1){if(!this._controls)return!1;let n=this.lookAtConstraint?.sources;if(n&&n.length>0){let i=n[e];if(i)return i.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,t),!0}return!1}setTarget(e=null,t=!1){!this._controls||(e!==null&&this._lookTargetPosition.copy(e),t?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(e,t){!this._controls||this._controls.target.lerp(e,t)}distanceToTarget(e){return this._controls?this._controls.target.distanceTo(e):-1}setTargetFromRaycast(){if(!this.controls)return;let e=this.context.physics.raycast();for(let t of e)if(t.distance>0&&R.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let n=B(this.context.mainCamera);this._cameraTargetPosition=n.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};C([x(bn)],Fe.prototype,"lookAtConstraint",2);var Pt=class{used=!1;Use(){this.used=!0}StopPropagation(){this.event?.stopImmediatePropagation()}inputSource;object;isDown;isUp;isPressed;isClicked;event;constructor(e){this.event=e}};import{Object3D as Hg}from"three";var Fg=I("debugeventsystem"),vn=class extends O{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,vn.systems.length<=0&&vn.systems.push(...R.findObjectsOfType(vn,e)));for(let n of vn.systems)if(n.context===e)return;let t=new Hg;R.addNewComponent(t,vn),e.scene.add(t)}static ensureUpdateMeshUI(e,t){Nt.update(e,t)}static markUIDirty(e){Nt.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),vn.systems.push(this)}onDestroy(){vn.systems.splice(vn.systems.indexOf(this),1)}start(){}register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){let t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}_selectStartFn;_selectEndFn;_selectUpdateFn;onEnable(){let e=new Map;this._selectStartFn??=(n,i)=>{if(!i.grab)return;Nt.resetLastSelected();let r=new Pt;r.inputSource=n,r.isDown=n.selectionDown,r.isUp=n.selectionUp,r.isPressed=n.selectionPressed,r.isClicked=!1,e.set(n,i.grab),i.grab&&!this.handleEvents(i.grab,r)&&(i.grab=null)},this._selectEndFn??=(n,i)=>{if(!i.grab)return;let r=new Pt;r.inputSource=n,r.isDown=n.selectionDown,r.isUp=n.selectionUp,r.isPressed=n.selectionPressed,r.isClicked=n.selectionClick,this.handleEvents(i.grab,r);let s=e.get(n);if(e.set(n,null),s)for(let a=0;a<this.raisedPointerDownEvents.length;a++){let c=this.raisedPointerDownEvents[a];this.raisedPointerDownObjects[a]===s&&c&&(c.onPointerUp?.call(c,r),this.raisedPointerDownEvents.splice(a,1),this.raisedPointerDownObjects.splice(a,1),a--)}};let t=new ge;this._selectUpdateFn??=n=>{t.ray=n.getRay();let i=this.performRaycast(t);if(!i)return;let r=new Pt;r.inputSource=n,this.handleIntersections(i,r)},q.addEventListener("select-start",this._selectStartFn),q.addEventListener("select-end",this._selectEndFn),q.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){q.removeEventListener("select-start",this._selectStartFn),q.removeEventListener("select-end",this._selectEndFn),q.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];raisedPointerDownObjects=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),U.IsInWebXR||this.context.input.isKeyPressed("Alt"))return;if(!this._didMove){let r=this.context.input.getPointerPositionRC(0);if(r&&r.x===0&&r.y===0)return;this._didMove=!0}let e=this.performRaycast(null),t=new Pt(this.context.input.getPointerEvent(0));if(t.inputSource=this.context.input,t.isClicked=this.context.input.mouseClick,t.isDown=this.context.input.mouseDown,t.isUp=this.context.input.mouseUp,t.isPressed=this.context.input.mousePressed,this.lastPointerEvent=t,!e)return;let n=null,i=null;this.context.input.mouseDown&&this.currentActiveMeshUIComponents.length>0&&this.context.mainCameraComponent&&(n=R.getComponent(this.context.mainCameraComponent.gameObject,Fe)??null,n&&(i=n.enabled,n.enabled=!1)),this.handleIntersections(e,t),n&&(this.orbitControl=n,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let n=R.getComponentsInParent(t,O,this._tempComponentsArray);this.lastPointerEvent.object=t;for(let i=0;i<n.length;i++){let r=n[i];if(!r.gameObject||r.destroyed)continue;let s=r;s.onPointerExit&&s.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let n=t.performRaycast(e);n&&n.length>0&&this._sortedHits.push(...n)}return this._sortedHits.sort((t,n)=>t.distance-n.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let n of e){let{object:i}=n;if(this.handleEvents(i,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let n=e[t],i=n.object;if(i.material&&i.material.depthTest===!1){this._noDepthTestingResults.push(n);continue}this._sortingBuffer.push(n)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&Fg&&console.log("not allowed",e),!1;let n=e;t.object=e,this.lastPointerEvent=t;let i=e.parent,r=!1,s=t.isClicked??!1,a=null;if(i&&i.isUI){let c=(t.isPressed||t.isClicked)??!1;if(i[pt]){let d=i[pt].gameObject;if(d){if(!Ot.isInteractable(d,this.out))return this.out.canvasGroup?.interactable??!1;a=this.out.canvasGroup??null;let u=this.handleMeshUIIntersection(e,c);e=d,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(i,c))return!0}if(this.objectsHoveredThisFrame.push(e),a===null||a.interactable){let c=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let d=R.getComponentsInParent(e,O,this.handleEventsArray);for(let l=0;l<d.length;l++){if(t.used)return!0;if(d[l].destroyed)continue;let u=d[l];u.interactable!==!1&&(u.onPointerEnter&&(c||u.onPointerEnter(t)),t.isDown&&u.onPointerDown&&!this.raisedPointerDownEvents.includes(u)&&(u.onPointerDown(t),this.raisedPointerDownEvents.push(u),this.raisedPointerDownObjects.push(n)),t.isUp&&u.onPointerUp&&u.onPointerUp(t),t.isClicked&&u.onPointerClick&&u.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let n=Nt.updateState(e,t);return n&&this.currentActiveMeshUIComponents.push(n),n!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Nt.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];Nt.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?R.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},Me=vn;j(Me,"didSearchEventSystem",!1),j(Me,"systems",[]);var Nt=class{static markDirty(){this.needsUpdate=!0}static update(e,t){for(let n of this.lastUpdateFrame)if(n.context===t){if(t.time.frameCount===n.frame)return;n.frame=t.time.frameCount,(this.needsUpdate||t.time.frameCount<30)&&(this.needsUpdate=!1,e.update());return}this.lastUpdateFrame=[{context:t,frame:t.time.frameCount}],e.update()}static updateState(e,t){let n=null;if(e&&(n=this.findBlockInParent(e),n&&n!==this.lastSelected)){if(n.interactable===!1)return null;t?(this.lastSelected=n,n.states.pressed&&n.setState("pressed")):n.states.hovered&&n.setState("hovered"),this.needsUpdate=!0}return n}static resetLastSelected(){let e=this.lastSelected;!e||(this.lastSelected=null,this.resetState(e))}static resetState(e){if(!e)return;e.interactable===!1?e.states.disabled&&e.setState("disabled"):e===this.lastSelected&&e.states.selected?e.setState("selected"):e.setState("normal"),this.needsUpdate=!0}static findBlockInParent(e){return e?e.isBlock&&Object.keys(e.states).length>0?e:this.findBlockInParent(e.parent):null}};j(Nt,"lastSelected",null),j(Nt,"lastUpdateFrame",[]),j(Nt,"needsUpdate",!1);import{AxesHelper as Bg}from"three";var Eo="./include";ja.Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};var pt=Symbol("shadowDomOwner"),Te=class extends O{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Me.markUIDirty(this.context)}shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=R.getComponentInParent(this.gameObject,yn)),this._root}_parentComponent=void 0;onEnable(){super.onEnable()}addShadowComponent(e,t){this.removeShadowComponent();let n=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=R.getComponentInParent(n,Te),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[pt]=this,e.traverse(r=>{r[pt]===void 0&&(r[pt]=this)});let i=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&(r?.add(e),i=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),rn&&e.add(new Bg(.5)),this.onAfterAddedToScene(),i&&ja.update()}set(e){}traverseOwnedShadowComponents(e,t,n){if(!!e&&e[pt]===t){n(e);for(let i of e.children)this.traverseOwnedShadowComponents(i,t,n)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}},yn=class extends Te{awake(){super.awake()}};var Ot=class{static getObject(e){let t=e[pt];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;let n=this.tryFindCanvasGroup(e);if(n?.isCanvasGroup===!0&&(t&&(t.canvasGroup=n),n.blocksRaycasts===!1||n.interactable===!1))return!1;let i=Qn(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&i?.isGraphic===!0&&(t.graphic=i),i?.raycastTarget!==!1}static tryFindCanvasGroup(e){if(!e)return null;let t=Qn(e,n=>{let i=n;if(i.blocksRaycasts!==void 0&&i.interactable!==void 0)return i},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}};var ds=I("debugwebxrcontroller");var Hi=class extends O{},Re=class extends O{static CreateRaycastLine(){let e=new Wg(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new qg(.5,22,22),t=new Xg({color:this.raycastColor}),n=new zg(e,t);return n.visible=!1,n.layers.set(2),n}static Create(e,t,n,i){let r=n?R.addNewComponent(n,Re,!1):new Re;r.webXR=e,r.index=t,r.type=i;let s=e.context;r.controller=s.renderer.xr.getController(t),r.controllerGrip=s.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=s.renderer.xr.getHand(t);let a=new $g;Yn(a,s),r.webXR.handModelPath&&r.webXR.handModelPath!==""&&a.setPath("/"+nn(e.sourceId,r.webXR.handModelPath));let c=new Kg(r.hand,a);return r.hand.add(c),r.hand.traverse(d=>d.layers.set(2)),r.handPointerModel=new Jg(r.hand,r.controller),r.controller.addEventListener("connected",d=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",d=>{if(d.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(h=>h.layers.set(2)),r.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let u=r.hand.joints;if(u)for(let h of Object.keys(u)){let b=u[h];b.parent||r.hand.add(b)}}}),r}static addEventListener(e,t){let n=this.eventSubs[e]??[];n.push(t),this.eventSubs[e]=n}static removeEventListener(e,t){if(!t)return;let n=this.eventSubs[e]??[],i=n.indexOf(t);i>=0&&n.splice(i,1),this.eventSubs[e]=n}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;get isUsingHands(){let e=this.input?.hand;return e!=null}get wrist(){if(!this.hand)return null;let e=this.hand.joints;return e?e.wrist:null}_wristQuaternion=null;getWristQuaternion(){let e=this.wrist;return e?(this._wristQuaternion||(this._wristQuaternion=new Ha),me(e).multiply(this._wristQuaternion.setFromEuler(new Vg(-Math.PI/4,0,0)))):null}movementVector=new Wt;worldRot=new Ha;joystick=new Yg;didRotate=!1;didTeleport=!1;didChangeScale=!1;lastHit=null;raycastLine=null;_raycastHitPoint=null;_connnectedCallback=null;_disconnectedCallback=null;_selectStartEvt=null;_selectEndEvt=null;get selectionDown(){return this._selectionPressed&&!this._selectionPressedLastFrame}get selectionUp(){return!this._selectionPressed&&this._selectionPressedLastFrame}get selectionPressed(){return this._selectionPressed}get selectionClick(){return this._selectionEndTime-this._selectionStartTime<.3}get raycastHitPoint(){return this._raycastHitPoint}_selectionPressed=!1;_selectionPressedLastFrame=!1;_selectionStartTime=0;_selectionEndTime=0;get useSmoothing(){return this._useSmoothing}_useSmoothing=!0;awake(){if(!this.controller){console.warn("Missing Controller!!!",this);return}this._connnectedCallback=this.onSourceConnected.bind(this),this._disconnectedCallback=this.onSourceDisconnected.bind(this),this._selectStartEvt=this.onSelectStart.bind(this),this._selectEndEvt=this.onSelectEnd.bind(this),this.type===1&&(this.controllerGrip.addEventListener("connected",this._connnectedCallback),this.controllerGrip.addEventListener("disconnected",this._disconnectedCallback),this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.addEventListener("selectstart",this._selectStartEvt),this.controller.addEventListener("selectend",this._selectEndEvt))}onDestroy(){this.type===1&&(this.controllerGrip.removeEventListener("connected",this._connnectedCallback),this.controllerGrip.removeEventListener("disconnected",this._disconnectedCallback),this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.type===0&&(this.controller.removeEventListener("selectstart",this._selectStartEvt),this.controller.removeEventListener("selectend",this._selectEndEvt)),this.hand?.clear(),this.controllerGrip?.clear(),this.controller?.clear()}onEnable(){this.hand&&(this.hand.name="Hand"),this.controllerGrip&&(this.controllerGrip.name="ControllerGrip"),this.controller&&(this.controller.name="Controller"),this.raycastLine&&(this.raycastLine.name="RaycastLine;"),this.webXR.Controllers.indexOf(this)<0&&this.webXR.Controllers.push(this),this.raycastLine||(this.raycastLine=Re.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Re.CreateRaycastHitPoint()),this.webXR.Rig?.add(this.hand),this.webXR.Rig?.add(this.controllerGrip),this.webXR.Rig?.add(this.controller),this.webXR.Rig?.add(this.raycastLine),this.raycastLine?.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),ds&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){this.hand?.removeFromParent(),this.controllerGrip?.removeFromParent(),this.controller?.removeFromParent(),this.raycastLine?.removeFromParent(),this._raycastHitPoint?.removeFromParent();let e=this.webXR.Controllers.indexOf(this);e>=0&&this.webXR.Controllers.splice(e,1)}_isConnected=!1;onSourceConnected(e){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,e);return}this._isConnected=!0,this.input=e.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(e){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",e);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(e){switch(e){case"down":this.context.input.createPointerDown({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({pointerId:this.index,clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}rayRotation=new Ha;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Re.eventSubs["update"];if(e&&e.length>0)for(let i of e)i(this);let t=1;this.type===0?t=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(t=this.context.time.deltaTime/.3),this.rayRotation.slerp(me(this.controller),this.useSmoothing?t:1);let n=B(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,J(this.raycastLine,n);let i=this.hand.joints;if(i&&i.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let s=this.getWristQuaternion();s&&this.rayRotation.copy(s)}Be(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,Be(this.raycastLine,this.rayRotation),J(this.raycastLine,n);this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}_pinchStartTime=void 0;onUpdate(e){if(this.lastHit=null,!e||e.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=e.inputSources[this.index]),!this.input)return;let t=this.webXR.Rig;if(!t)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);let n=this.input?.gamepad?.buttons;switch(this.input.handedness){case"left":let i=3*Re.MovementSpeedFactor,r=2,s=W.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=a,c*=s;let d=this.joystick.y>0?1:-1,l=Math.pow(this.joystick.y,r);l*=d,c*=s,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,l),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(i*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,n);break;case"right":let u=this.joystick.x,h=Math.abs(u);if(h<.4)this.didRotate=!1;else if(h>.5&&!this.didRotate){let b=u>0?-1:1;t.rotateY(W.toRadians(30*b)),this.didRotate=!0}this.runTeleport(t,n);break}}runTeleport(e,t){let n=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(n=this.handPointerModel.isPinched()?1:0),a||(this._pinchStartTime=void 0)}else this._pinchStartTime=void 0;let i=n>.5&&this.webXR.IsInVR,r=this.webXR.Rig?this.webXR.Rig?.scale?.x<.999:!1,s=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let c=t[a];if(a===4)if(c.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;let d=this.webXR.Rig;if(d)if(r){r=!1,d.scale.set(1,1,1),s=1,Re.MovementSpeedFactor=1;let l=this.context.mainCamera;Re.PreviousCameraFarDistance&&(l.far=Re.PreviousCameraFarDistance)}else{r=!0,i=!0,s=.1,Re.MovementSpeedFactor=s*2;let l=this.context.mainCamera;Re.PreviousCameraFarDistance=l.far,l.far/=s}}else c.pressed||(this.didChangeScale=!1)}if(i){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let c=a[0];if(r||this.isValidTeleportTarget(c.object)){let d=c.point;J(e,d)}}}}else n<.1&&(this.didTeleport=!1);s!==null&&(e.scale.set(s,s,s),e.updateMatrixWorld())}isValidTeleportTarget(e){return R.getComponentInParent(e,Hi)!=null}updateStick(e){!e||!e.gamepad||e.gamepad.axes?.length<4||(this.joystick.x=e.gamepad.axes[2],this.joystick.y=e.gamepad.axes[3])}updateLastHit(){let e=this.raycast(),t=e?e[0]:null;this.lastHit=t;let n=1;if(this.webXR.Rig&&(n/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=n*(this.lastHit?.distance??9999);let i=this.raycastLine.material;t!=null?i.color=Re.raycastColor:i.color=Re.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let i=W.clamp(this.lastHit.distance*.01*n,.015,.1);this._raycastHitPoint.scale.set(i,i,i)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return t}onSelectStart(){!this.context.connection.allowEditing||(this.selectStartCallback=()=>this.onHandleSelectStart())}selectStartCallback=null;lastSelectStartObject=null;onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let e=null,t=!1;if(this.isUsingHands?(e=this.overlap(),e.length<=0?(e=this.raycast(),t=!1):t=!0):e=this.raycast(),ds&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(let n of e){let i=n.object;this.lastSelectStartObject=i;let r={selected:i,grab:i},s=Re.eventSubs["select-start"];if(s&&s.length>0)for(let a of s)a(this,r);r.grab!==i&&ds&&console.log("Grabbed object changed","original",i,"new",r.grab),r.grab&&(this.grabbed=Ve.TryTake(this,r.grab,n,t));break}else{let n=Re.eventSubs["select-start"],i={selected:null,grab:null};if(n&&n.length>0)for(let r of n)r(this,i)}}_didNotEndSelection=!1;onSelectEnd(){if(this.isUsingHands&&this.handPointerModel.pinched){this._didNotEndSelection=!0;return}if(!this._selectionPressed)return;this.selectStartCallback=null,this._selectionPressed=!1,this._selectionEndTime=this.context.time.time;let e={grab:this.grabbed?.selected??this.lastSelectStartObject},t=Re.eventSubs["select-end"];if(t&&t.length>0)for(let n of t)n(this,e);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(e){return!(!e||R.isActiveInHierarchy(e)===!1||Ot.isInteractable(e)===!1)}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let n of e.children)this.grabbed?.selected===n||this.grabbed?.selectedMesh===n||this.setControllerLayers(n,t)}getRay(){let e=new Qg;return e.origin.copy(B(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}closeGrabBoundingBoxHelper;overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(ds&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new Ug(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;let t=B(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new ge;e.layerMask=new Ng,e.layerMask.set(0),e.layerMask.disable(2),e.ray=this.getRay();let t=this.context.physics.raycast(e);for(let n=0;n<t.length;n++){let i=t[n],r=i.object;if(!this.testIsVisible(r)){t.splice(n,1),n--;continue}i.object=Ot.getObject(r);break}return t}},q=Re;j(q,"Factory",new Zg),j(q,"raycastColor",new qh(.9,.3,.3)),j(q,"raycastNoHitColor",new qh(.6,.6,.6)),j(q,"geometry",new Gg().setFromPoints([new Wt(0,0,0),new Wt(0,0,-1)])),j(q,"handModels",{}),j(q,"eventSubs",{}),j(q,"PreviousCameraFarDistance"),j(q,"MovementSpeedFactor",1);var Ge=class{static AddEventListener(e,t){return Ge.Events[e]||(Ge.Events[e]=[]),Ge.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!Ge.Events[e])return;let n=Ge.Events[e].indexOf(t);n>=0&&Ge.Events[e].splice(n,1)}static Register(e){this.Current.find(t=>t===e)||this.Current.push(e)}static Remove(e){let t=this.Current.indexOf(e);t>=0&&this.Current.splice(t,1)}static TryTake(e,t,n,i){let r=R.getComponentInParent(t,ct);if(r)t=r.gameObject;else return ds&&console.warn("Prevented taking object that is not interactable",t),null;let s=t,a=R.getComponentInParent(t,Je);a&&(a.requestOwnership(),s=a.gameObject);for(let d of this.Current)if(d.selected===s)return d.controller===e||(d.free(),d.Take(e,s,t,a,r,n,i)),d;let c=new Ge;return c.Take(e,s,t,a,r,n,i),c}sync=null;selected=null;selectedParent=null;selectedMesh=null;controller=null;grabTime=0;grabUUID="";isCloseGrab=!1;originalMaterial=null;usageMarker=null;rigidbodies=null;didReparent=!1;grabDistance=0;interactable=null;positionSource=null;Take(e,t,n,i,r,s,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:n,sync:i,interactable:r};Ge.Events.WillTake?.forEach(b=>b(this,c));let d=n;d?.material&&(this.originalMaterial=d.material,Array.isArray(d.material)||(d.material=d.material.clone(),d.material&&d.material.emissive&&(d.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=d,this.controller=e,this.interactable=r,this.isCloseGrab=a,this.didReparent=!1,this.sync=i,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=R.addNewComponent(this.selected,dt),this.rigidbodies=R.getComponentsInChildren(this.selected,K),B(this.positionSource,this.lastControllerWorldPos);let l=()=>a?this.lastControllerWorldPos.clone():s.point.clone();this.grabDistance=l().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(l());let u=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();me(this.selected,this.localQuaternionToGrab).premultiply(u.invert());let h=this.controller.webXR.Rig;return h&&this.rigPositionLastFrame.copy(B(h)),de.Add(e.context,this.selected),Ge.Register(this),this.sync&&(this.sync.fastMode=!0),Ge.Events.DidTake?.forEach(b=>b(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};Ge.Events.WillFree?.forEach(i=>i(this,e)),de.Remove(this.controller.context,this.selected),Ge.Remove(this),this.sync&&(this.sync.fastMode=!1);let t=this.selectedMesh;t&&this.originalMaterial&&t.material&&(t.material=this.originalMaterial);let n=this.selected;if(this.didReparent&&n.parent){let i=this.selectedParent;i?i.attach(n):this.controller?.context.scene.attach(n)}if(this.usageMarker?.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(let i of this.rigidbodies)i.wakeUp(),i.setVelocity(i.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,Ge.Events.DidFree?.forEach(i=>i(this,e))}grabPoint=new Wt;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new Wt;localQuaternionToGrab=new Ha(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new Wt;controllerWorldPos=new Wt;lastControllerWorldPos=new Wt;controllerPosDelta=new Wt;totalChangeAlongDirection=0;rigPositionLastFrame=new Wt;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),B(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);let e=this.controller.webXR.Rig;if(e){let n=B(e),i=this.rigPositionLastFrame.sub(n);this.controllerPosDelta.add(i),this.rigPositionLastFrame.copy(n)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.rigidbodies)for(let e of this.rigidbodies)e.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new Wt),this.targetDir.set(0,0,-this.grabDistance*t);let n=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),i=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=i.clone()),this.quaternionLerp.slerp(i,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),Be(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(n),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(B(this.selected)),n.sub(this.localPositionOffsetToGrab_worldSpace)),J(this.selected,n)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});ne.markDirty(this.selected,!0)}}},Ve=Ge;j(Ve,"Events",{}),j(Ve,"Current",[]);var ri=class extends O{awake(){}};import{Quaternion as us,Vector3 as Fa,Vector4 as eb}from"three";var _n=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}w(){return this.bb.readFloat32(this.bb_pos+12)}static sizeOf(){return 16}static createVec4(e,t,n,i,r){return e.prep(4,16),e.writeFloat32(r),e.writeFloat32(i),e.writeFloat32(n),e.writeFloat32(t),e.offset()}};var we=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsVrUserStateBuffer(e,t){return(t||new we).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new we).__init(e.readInt32(e.position())+e.position(),e)}guid(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}time(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readInt64(this.bb_pos+e):this.bb.createLong(0,0)}avatarId(e){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__string(this.bb_pos+t,e):null}position(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new ve).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new _n).__init(this.bb_pos+t,this.bb):null}scale(){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.readFloat32(this.bb_pos+e):0}posLeftHand(e){let t=this.bb.__offset(this.bb_pos,16);return t?(e||new ve).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new ve).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new _n).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new _n).__init(this.bb_pos+t,this.bb):null}static startVrUserStateBuffer(e){e.startObject(10)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addTime(e,t){e.addFieldInt64(1,t,e.createLong(0,0))}static addAvatarId(e,t){e.addFieldOffset(2,t,0)}static addPosition(e,t){e.addFieldStruct(3,t,0)}static addRotation(e,t){e.addFieldStruct(4,t,0)}static addScale(e,t){e.addFieldFloat32(5,t,0)}static addPosLeftHand(e,t){e.addFieldStruct(6,t,0)}static addPosRightHand(e,t){e.addFieldStruct(7,t,0)}static addRotLeftHand(e,t){e.addFieldStruct(8,t,0)}static addRotRightHand(e,t){e.addFieldStruct(9,t,0)}static endVrUserStateBuffer(e){return e.endObject()}static finishVrUserStateBufferBuffer(e,t){e.finish(t)}static finishSizePrefixedVrUserStateBufferBuffer(e,t){e.finish(t,void 0,!0)}};var Yh=I("debugxr"),hs=I("debugavatar");var Xc="VRUS";so(Xc,we.getRootAsVrUserStateBuffer);function zc(){return new Date().getTime()}function tb(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return Ae.create(e,t)}var ps=class{guid;time;avatarId;position=new Fa;rotation=new eb;scale=1;posLeftHand=new Fa;posRightHand=new Fa;rotLeftHand=new us;rotRightHand=new us;constructor(e){this.guid=e}update(e,t,n,i,r){this.time=zc(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let s=ps.quat0,a=ps.quat1;s.set(n.x,n.y,n.z,n.w),s=s.multiplyQuaternions(s,ps.invertRotation),e&&(e.getWorldQuaternion(a),s.multiplyQuaternions(a,s)),this.rotation.set(s.x,s.y,s.z,s.w),this.scale=e.scale.x;let c=i.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let d=i.RightController?.controllerGrip;if(d&&(d.getWorldPosition(this.posRightHand),d.getWorldQuaternion(this.rotRightHand)),i.LeftController?.hand?.visible){let l=i.LeftController.wrist;l&&(l.getWorldPosition(this.posLeftHand),l.getWorldQuaternion(this.rotLeftHand))}if(i.RightController?.hand?.visible){let l=i.RightController.wrist;l&&(l.getWorldPosition(this.posRightHand),l.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(e,t){e.clear();let n=e.createString(this.guid),i=e.createString(this.avatarId);we.startVrUserStateBuffer(e),we.addGuid(e,n),we.addTime(e,tb(this.time)),we.addAvatarId(e,i),we.addPosition(e,ve.createVec3(e,this.position.x,this.position.y,this.position.z)),we.addRotation(e,_n.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),we.addScale(e,this.scale),we.addPosLeftHand(e,ve.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),we.addPosRightHand(e,ve.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),we.addRotLeftHand(e,_n.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),we.addRotRightHand(e,_n.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=we.endVrUserStateBuffer(e);e.finish(r,Xc);let s=e.asUint8Array();t.sendBinary(s)}setFromBuffer(e,t){if(!e)return;this.guid=e,this.time=t.time().toFloat64();let n=t.avatarId();n&&(this.avatarId=n);let i=t.position();i&&this.position.set(i.x(),i.y(),i.z());let r=t.rotation();r&&this.rotation.set(r.x(),r.y(),r.z(),r.w());let s=t.posLeftHand();s&&this.posLeftHand.set(s.x(),s.y(),s.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let d=t.rotRightHand();d&&this.rotRightHand.set(d.x(),d.y(),d.z(),d.w()),this.scale=t.scale()}},ft=ps;j(ft,"invertRotation",new us().setFromAxisAngle(new Fa(0,1,0),Math.PI)),j(ft,"quat0",new us),j(ft,"quat1",new us);var En=class extends O{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=R.getComponent(this.gameObject,U)),this.webXR||(this.webXR=R.findObjectOfType(U,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=R.findObjectOfType(U,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=R.findObjectOfType(He,this.context)),hs){let e="debug-avatar-"+hs,t=new ht(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof hs=="string"&&hs.length>0)if(await t.setAvatarOverride(hs)){let n=new ft(e);n.position.y+=1;let i=.5;n.posLeftHand.y+=i,n.posLeftHand.x+=i,n.posRightHand.y+=i,n.posRightHand.x-=i,t.tryUpdate(n,0)}else t.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=R.getComponent(this.gameObject,U),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),U.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),U.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),U.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen("joined-room",this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",e=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",e=>{let t=e.id!==null&&e.id!==void 0;!t||(console.log("webxr user left evt"),t&&(this.avatars[e.id]?.destroy(),this.avatars[e.id]=void 0))}),this.context.connection.beginListenBinrary(Xc,e=>{let t=e.guid();if(!t)return;let n=e.time().toFloat64(),i=this.tempState;i.setFromBuffer(t,e),this.onTryGetAvatar(t,n)?.tryUpdate(i,n)}),this.context.connection.beginListen("vr-session-update",e=>{let t=e.guid,n=e.time;this.onTryGetAvatar(t,n)?.tryUpdate(e,n)})}tempState=new ft("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let n=new Date().getTime()-t;if(n>5e3)return Yh&&console.log("old data",n,e),null;let i=this.avatars[e];if(i===void 0)try{console.log("create new avatar");let r=new ht(this.context,e,this.webXR);i=r,this.avatars[e]=r}catch(r){this.avatars[e]=null,console.error(r)}return i}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListening("joined-room",this.eventSub_ConnectionEvent),U.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),U.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),U.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=zc();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=e),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(let t in this.avatars){let n=this.avatars[t];!n||n.update()}}_removeAvatarsList=[];detectPotentiallyDisconnectedAvatarsAndRemove(){let e=zc();for(let t in this.avatars){let n=this.avatars[t];if(!n){this._removeAvatarsList.push(t);continue}e-n.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),n.destroy(),this.avatars[t]=void 0)}for(let t of this._removeAvatarsList)delete this.avatars[t];this._removeAvatarsList.length=0}buildLocalAvatar(){if(this.localAvatar)return;let e=this.context.connection?.connectionId??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new ht(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}eventSub_ConnectionEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;eventSub_WebXRUpdateEvent=null;avatars={};localAvatar=null;k_LocalAvatarNoNetworkingGuid="local";onConnected(){Yh&&console.log("Hey you are connected as "+this.context.connection.connectionId),this.localAvatar?.guid===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null)}onXRSessionStart(e){if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&(this.localAvatar?.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,this.ownership?.freeOwnership(),this.ownership=null,this.avatars)for(let t in this.avatars)this.avatars[t]?.updateFlags()}onXRSessionEnded(e){console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"})}ownership=null;xrState=null;builder=new rt(1024);onXRSessionUpdate(e){this.xrState??=new ft(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new Ci(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();let{frame:t,xr:n,rig:i}=e,r=t.getViewerPose(n.getReferenceSpace());if(!r)return;let s=r?.transform,a=s.position,c=s.orientation;this.xrState.update(i,a,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return I("avatar")??null}};async function lb(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function cb(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var qc=!1,Yc=!1;lb().then(o=>qc=o);cb().then(o=>Yc=o);var Se=class extends O{enableVR=!0;enableAR=!0;defaultAvatar;handModelPath="";createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(qc||Yc)}static get IsARSupported(){return qc}static get IsVRSupported(){return Yc}static addEventListener(e,t){return this.events.addEventListener(e,t),t}static removeEventListener(e,t){return this.events.removeEventListener(e,t),t}static createVRButton(e,t){Se.XRSupported||console.warn("WebXR is not supported on this device");let n=vo.createButton(e.context.renderer);return n.classList.add("webxr-ar-button"),n.classList.add("webxr-button"),this.resetButtonStyles(n),(t?.registerClick??!0)&&n.addEventListener("click",e.onClickedVRButton.bind(e)),n}static createARButton(e,t){let n=e.webAR?.getAROverlayContainer(),i={};n&&(i.domOverlay={root:n},i.optionalFeatures=["hit-test","dom-overlay"]);let r=Ma.createButton(e.context.renderer,i);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Se.resetButtonStyles(r),(t?.registerClick??!0)&&r.addEventListener("click",e.onClickedARButton.bind(e)),r}static resetButtonStyles(e){!e||(e.style.position="",e.style.bottom="",e.style.left="")}endSession(){let e=this.context.renderer.xr.getSession();e&&e.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}controllers=[];get Controllers(){return this.controllers}get LeftController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="left"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="left"?this.controllers[1]:null}get RightController(){return this.controllers.length>0&&this.controllers[0].input?.handedness==="right"?this.controllers[0]:this.controllers.length>1&&this.controllers[1].input?.handedness==="right"?this.controllers[1]:null}get ARButton(){return this._arButton}get VRButton(){return this._vrButton}get IsInVR(){return this._isInVR}get IsInAR(){return this._isInAR}rig;isInit=!1;_requestedAR=!1;_requestedVR=!1;_isInAR=!1;_isInVR=!1;_arButton;_vrButton;webAR=null;awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=je.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!R.findObjectOfType(En,this.context)){let e=R.addNewComponent(this.gameObject,En,!1);e.webXR=this}}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,this.webAR=new oi(this);let e=Se.XRSupported,t,n,i=document.createElement("div");i.classList.add("webxr-buttons"),this.context.domElement.append(i),this.enableAR&&this.createARButton&&(t=Se.createARButton(this),this._arButton=t,i.appendChild(t)),this.createVRButton&&this.enableVR&&(n=Se.createVRButton(this),this._vrButton=n,i.appendChild(n)),setTimeout(()=>{Se.resetButtonStyles(n),Se.resetButtonStyles(t)},1e3)}_transformOrientation=new Qc;get TransformOrientation(){return this._transformOrientation}_currentHeadPose=null;get HeadPose(){return this._currentHeadPose}onBeforeRender(e){if(!e)return;let t=this.context.renderer.xr.getSession();if(t){let n=e.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(this._currentHeadPose=n,!n)return;let i=n?.transform;i&&this._transformOrientation.set(i.orientation.x,i.orientation.y,i.orientation.z,i.orientation.w);for(let r of this.controllers)r.onUpdate(t);this._isInAR&&this.webAR?.onUpdate(t,e)}Se._isInXr===!1&&t&&this.onEnterXR(t,e),Se.events.dispatchEvent({type:"xrUpdate",frame:e,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureCameraState())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureCameraState(),this.ensureRig();for(let e=0;e<2;e++)q.Create(this,e,this.gameObject,0);Se.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(B(this.context.mainCamera)),this._originalCameraRotation.copy(me(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=R.findObjectOfType(ri,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new rb,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new $h;_originalCameraRotation=new Qc;onEnterXR(e,t){console.log("[XR] session begin",e),Se._isInXr=!0,this.ensureRig();let n=this.context.renderer.xr.getReferenceSpace();if(n&&this.rig){let a=t.getViewerPose(n)?.transform.orientation;if(a){let c=new Qc(a.x,a.y,a.z,a.w),d=new nb().setFromQuaternion(c);this.rig.rotateY(d.y)}}let i=this.context.renderer.xr;if(this.context.mainCamera){let s=i.getCamera(this.context.mainCamera);for(let a of s.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch($e.Global.Set(r),r){case 2:this.context.xrSessionMode="immersive-ar",this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this.context.xrSessionMode="immersive-vr",this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),Se._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Se.events.dispatchEvent({type:"xrStarted",session:e})}onExitXR(e){this._isInAR&&e&&this.webAR?.onEnd(e),this._isInAR=!1,this._isInVR=!1,this._requestedAR=!1,this._requestedVR=!1,this.context.xrSessionMode=void 0,this.xrMirrorWindow&&(this.xrMirrorWindow.close(),this.xrMirrorWindow=null),this.destroyControllers(),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),J(this.context.mainCamera,this._originalCameraPosition),Be(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),$e.Global.Set(17),Se.events.dispatchEvent({type:"xrStopped",session:e})}onEnterVR(e){}destroyControllers(){for(let e=this.controllers.length-1;e>=0;e-=1)this.controllers[e]?.destroy();this.controllers.length=0}xrMirrorWindow=null;onEnterXR_HandleMirrorWindow(e){!I("mirror")||setTimeout(()=>{if(!Se.IsInWebXR)return;let t=new URL(window.location.href);Qr(t.searchParams,yo,1),Qr(t.searchParams,"isMirror",1);let n=t.toString();this.xrMirrorWindow=window.open(n,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{Se.IsInWebXR&&e.end()})})},1e3)}},U=Se;j(U,"_isInXr",!1),j(U,"events",new ib),C([x()],U.prototype,"enableVR",2),C([x()],U.prototype,"enableAR",2),C([x(je)],U.prototype,"defaultAvatar",2),C([x()],U.prototype,"handModelPath",2),C([x()],U.prototype,"createVRButton",2),C([x()],U.prototype,"createARButton",2);var wo=class{get webxr(){return this._webxr}_webxr;reticle=null;reticleParent=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this._webxr=e}arDomOverlay=null;arOverlayElement=null;noHitTestAvailable=!1;didPlaceARSessionRoot=!1;getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;let e=this.arDomOverlay;return e.getAROverlayContainer?this.arOverlayElement=e.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(e){this.reticleActive=e}async onBegin(e){let t=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1;let n=navigator.userAgent?.includes("OculusBrowser")?0:1,i=n===1?4:2;for(let r=0;r<i;r++)q.Create(this.webxr,r,this.webxr.gameObject,n);if((!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=R.findObjectOfType(ut,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(r=>{e.requestHitTestSource({space:r}).then(s=>{this.hitTestSource=s}).catch(s=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported")})}),!this.reticle&&this.sessionRoot&&(this.reticle=new ob(new ab(.07,.09,32).rotateX(-Math.PI/2),new sb),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new Jh,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),this.reticleParent.matrix.copy(this.sessionRoot.gameObject.matrixWorld),this.webxr.scene?(this.context.scene.add(this.reticleParent),this.context.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,wo.tempWebXRObject||(wo.tempWebXRObject=new Jh),this.context.scene.add(wo.tempWebXRObject),R.addComponent(wo.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene"),this.arDomOverlay&&this.arOverlayElement){let r=this.arOverlayElement;r.onEnterAR?.call(r,e,this.arOverlayElement)}this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),R.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;if(t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay){let n=this.arOverlayElement;n.onExitAR?.call(n,e)}this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;let i=this.webxr.Rig,r=db.clone();if(i){let s=new $h(0,0,0).add(i.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new Zh().makeTranslation(s.x,s.y,s.z))}this.sessionRoot?.placeAt(i,r)}return}if(!this.hitTestSource)return;let n=t.getHitTestResults(this.hitTestSource);if(n.length){let i=n[0],r=this.webxr.context.renderer.xr.getReferenceSpace();if(r){let s=i.getPose(r);if(this.sessionRoot){let a=this.sessionRoot.onUpdate(this.webxr.Rig,e,s);this.didPlaceARSessionRoot=a}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){let a=s.transform.matrix;this.reticle.matrix.fromArray(a),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},oi=wo;j(oi,"tempWebXRObject");var db=new Zh().identity().makeTranslation(0,-.5,0);var Kc=!1;var xo=class extends ct{static get HasAnySelected(){return this._active!==null}transformSelf=!0;orbit=null;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new Q.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){this.orbit=R.findObjectOfType(Fe,this.context)}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||U.IsInWebXR)return;let t=R.getComponentInParent(e.object,xo);!t||t!==this||(xo.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||U.IsInWebXR||xo.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||U.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(U.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!U.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&this._dragHelper?.hasSelected===!1&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new Ba(this.context.mainCamera);else return;if(!e||!e.object)return;let t=R.getComponentInParent(e.object,xo);if(!t||t!==this)return;let n=e.object;this.transformSelf&&(n=this.gameObject);let i={selected:n,attached:n};for(let c of this.selectStartEventListener)c(this,i);if(!i.attached)return;i.attached,n=i.attached,this._isDragging=!0,this._dragHelper.setSelected(n,this.context),this.orbit&&(this.orbit.enabled=!1);let r=R.getComponentInChildren(n,Je);Kc&&console.log("DRAG START",r,n),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=R.addNewComponent(n,dt),this._draggingRigidbodies.length=0;let s=R.getComponentsInChildren(n,K);s&&this._draggingRigidbodies.push(...s);let a=gl();R.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(let i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity);this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(Kc&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e?.object){let i=R.getComponentInChildren(e.object,Je);i&&(i.fastMode=!1),this._marker&&this._marker.destroy()}for(let i of this.selectEndEventListener)i(this);let n=gl();R.invokeOnChildren(t,n("onDragEnd"))}},zt=xo;j(zt,"_active",null),j(zt,"lastHovered");var Jc=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new Q.Plane;_hasGroundPlane=!1;_groundPlane=new Q.Plane;_groundOffset=new Q.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new Q.Vector3;_raycaster=new Q.Raycaster;_cameraPlaneOffset=new Q.Vector3;_intersection=new Q.Vector3;_worldPosition=new Q.Vector3;_inverseMatrix=new Q.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new Q.Line(Jc.geometry),n=t.material;n.color=new Q.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let i=new Q.SphereGeometry(.5,22,22),r=new Q.MeshBasicMaterial({color:n.color}),s=new Q.Mesh(i,r);s.visible=!1,s.layers.set(2),this._groundMarker=s}setSelected(e,t){if(this._selected&&t)for(let n of this._rbs)n.wakeUp(),n.setVelocity(0,0,0);if(this._selected&&de.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}de.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new Q.Vector3(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){if(!this._context)return;let t=" ",n="d",i="s",r=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),s=this._context.input.getTouchesPressedCount()>=2||r;if(s){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){Kc&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=B(this._camera).clone().sub(B(this._selected)).normalize(),d=Math.abs(c.dot(this._groundOffsetVector)),l=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(n),u=!s&&d>.2&&!l&&this._context.input.getPointerPressedCount()<=1,h=this._didDragOnGroundPlaneLastFrame!==u;if(this._didDragOnGroundPlaneLastFrame=u,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!u||h)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let b=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=b,u){this._groundOffsetVector.set(0,1,0);let _=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(_,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);h&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,n){if(!!this._selected){if(n){let i=B(this._selected);i.y=e.y,e=i}if(J(this._selected,e),J(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let i=B(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(i,i,i),J(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;let e=this._context.input.getPointerPositionRC(0);!e||(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;let e=B(this._selected),t=new Q.Ray(new Q.Vector3(0,.1,0).add(e),new Q.Vector3(0,-1,0)),n=new ge;n.ignore=[this._selected];let i=this._context.physics.raycastFromRay(t,n);for(let r=0;r<i.length;r++){let s=i[r];if(!s.face||this.contains(this._selected,s.object))continue;let a=new Q.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,s.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){ne.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.resetForcesAndTorques(),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let n of e.children)if(this.contains(n,t))return!0}return!1}},Ba=Jc;j(Ba,"geometry",new Q.BufferGeometry().setFromPoints([new Q.Vector3(0,0,0),new Q.Vector3(0,-1,0)]));var kt=class extends O{url=null;urlParameterName=null;localhost=null;awake(){this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?kt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=I(this.urlParameterName);r&&typeof r=="string"&&(e=r)}if(!e)return null;let n=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return n?.groups?n?.groups.socket_prefix?e:"wss://"+n?.groups.url:null}static GetUrl(e,t){let n=e,i=kt.IsLocalNetwork()&&t;return i&&(n=t),e?.startsWith("/")&&(n=(i?n:window.location.origin)+e),n}static IsLocalNetwork(e=window.location.hostname){return tr(e)}};var si=class extends O{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?kt.GetUrl(this.filesBackendUrl,this.localhost):void 0,this._dragOver=this.onDrag.bind(this),this._drop=this.onDrop.bind(this),this.context.domElement.addEventListener("dragover",this._dragOver),this.context.domElement.addEventListener("drop",this._drop)}onDisable(){this.context.domElement.removeEventListener("dragover",this._dragOver),this.context.domElement.removeEventListener("drop",this._drop)}onDrag(e){e.preventDefault()}async onDrop(e){if(console.log(e),!e.dataTransfer)return;e.preventDefault();let t=e.dataTransfer.items;if(!!t)for(let n in t){let i=t[n];if(i.kind==="file"){let r=i.getAsFile();if(!r)continue;console.log("Register file "+r.name+" to",this.filesBackendUrl,r);let s=await mh(r,this.context,this.filesBackendUrl);s&&this.addObject(e,s)}else i.kind==="string"&&i.type=="text/plain"&&i.getAsString(async r=>{console.log("dropped url",r);try{let s=new URL(r);if(!s)return;let a=await gh(s,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let n=new ge;n.setMask(16777215),n.screenPointFromOffset(e.offsetX,e.offsetY);let i=this.context.physics.raycast(n),r=t.scene;if(i&&i.length>0)for(let s of i){r.position.copy(s.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};C([x()],si.prototype,"filesBackendUrl",2),C([x()],si.prototype,"localhost",2);import{Vector3 as ub,Quaternion as hb,Object3D as ep}from"three";var Xt=class extends ct{parent=null;object=null;limitCount=10;limitInterval=60;_currentCount=0;_startPosition=null;_startQuaternion=null;awake(){if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=this.object.position?.clone()??new ub(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new hb(0,0,0,1)}let e=R.getComponentInParent(this.gameObject,zt);e?e.addDragEventListener("selectstart",(t,n)=>{if(this._currentCount>=this.limitCount){n.attached=null;return}let i=this.handleDuplication(n.selected);i&&(console.assert(i!==n.selected,"Duplicated object is original"),n.attached=i)}):console.warn("Could no find drag controls in parent",this.name),q.addEventListener("select-start",(t,n)=>{if(this._currentCount>=this.limitCount){n.grab=null;return}let i=this.handleDuplication(n.selected);i&&(n.grab=i)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new Ie;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let n=R.instantiateSynced(this.object,t);return console.assert(n!==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),n}return null}handleMultiObject(e){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,e):!1}isInChildren(e,t){if(!e)return!1;if(e===t)return!0;if(e.children){for(let n of e.children)if(this.isInChildren(n,t))return!0}return!1}};C([x(ep)],Xt.prototype,"parent",2),C([x(ep)],Xt.prototype,"object",2),C([x()],Xt.prototype,"limitCount",2),C([x()],Xt.prototype,"limitInterval",2);var Qt=class{method;enabled;constructor(e,t){this.method=e,this.enabled=t!==void 0?t:!0}invoke(...e){if(this.enabled!==!1){if(!this.method){console.warn("No function. Please check you assigned a method to invoke on export",this);return}this.method(...e)}}},pb=o=>/^[A-Z]*$/.test(o),Fi=class extends Event{args},he=class{target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let n="",i=!1;for(let r of this.key)i&&pb(r)&&(n+="-"),i=!0,n+=r.toLowerCase();this.key=n}}_isInvoking=!1;methods=[];constructor(e){this.methods=e??[]}invoke(...e){if(this._isInvoking){console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this);return}this._isInvoking=!0;try{for(let t of this.methods)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){let t=this.target.dispatchEvent;if(typeof t=="function"){let n=new Fi(this.key);n.args=e,t.call(this.target,n)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new Qt(e,!0)),e}removeEventListener(e){if(!!e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].method===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}};var vr=class extends O{};import{FlyControls as fb}from"three/examples/jsm/controls/FlyControls";var yr=class extends O{_controls=null;onEnable(){let e=R.getComponent(this.gameObject,ie)?.cam;this._controls=new fb(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){this._controls?.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}};import*as tp from"three";import{Color as mb}from"three";var wn=class extends O{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!rn||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new tp.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Oa(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),3)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}};C([x()],wn.prototype,"objectBounds",2),C([x(mb)],wn.prototype,"color",2),C([x()],wn.prototype,"isGizmo",2);import{GLTFExporter as Ib}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as Zc,Matrix4 as gb,Vector3 as np,Quaternion as bb}from"three";var fs=class{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;let n=this.writer,i=n.extensionsUsed,r={};t.extensions=t.extensions||{},t.extensions[this.name]=r;let s=new gb,a=new Array,c=new Array,d=new Array;for(let b=0;b<e.count;b++){e.getMatrixAt(b,s);let _=new np,v=new bb,y=new np;s.decompose(_,v,y),a.push(_.x,_.y,_.z),c.push(v.x,v.y,v.z,v.w),d.push(y.x,y.y,y.z)}let l=new Float32Array(a),u=new Float32Array(c),h=new Float32Array(d);r.attributes={TRANSLATION:n.processAccessor(new Zc(l,3)),ROTATION:n.processAccessor(new Zc(u,4)),SCALE:n.processAccessor(new Zc(h,3))},i[this.name]=!0}};import*as Tn from"three";import*as ms from"three";var xn=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new ms.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new ms.Vector4(1,1,0,0)};lightmapUniform={value:null};beforeRenderCallback;constructor(e,t){this.gameObject=e,this.context=t}init(e,t,n,i=!1){if(console.assert(this.gameObject!==void 0&&this.gameObject!==null,"Missing gameobject",this),this.lightmapIndex=e,this.lightmapIndex<0)return;this.lightmapScaleOffset=t,this.lightmapTexture=n,i&&this.setLightmapDebugMaterial(),this.setupLightmap()}bindOnBeforeRender(){this.beforeRenderCallback=this.onBeforeRenderThreeComplete.bind(this),this.context.addBeforeRenderListener(this.gameObject,this.beforeRenderCallback)}onBeforeRenderThreeComplete(e,t,n,i,r,s){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(n,i)=>{n.uniforms.lightmap=this.lightmapUniform,n.uniforms.lightmapScaleOffset=this.lightmapScaleOffsetUniform},this.lightmapIndex>=0){let n=this.lightmapTexture,i=this.gameObject.material;i&&n&&(i.uniforms||(i.uniforms={}),i.lightMap=n,i.uniforms.lightmap={value:n})}}onBeforeRenderThree(e){let t=e.uniforms;t&&t.lightmap&&(this.lightmapScaleOffsetUniform.value=this.lightmapScaleOffset,this.lightmapUniform.value=this.lightmapTexture,t.lightmap=this.lightmapUniform,t.lightmapScaleOffset=this.lightmapScaleOffsetUniform)}setLightmapDebugMaterial(){this.gameObject.material=new ms.ShaderMaterial({vertexShader:`
177
177
  attribute vec2 uv2;
178
178
  varying vec2 vUv2;
179
179
  void main()
@@ -205,7 +205,7 @@ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
205
205
  // gl_FragColor = vec4(vUv2.xy, 0, 1);
206
206
  gl_FragColor = lightMapTexel;
207
207
  }
208
- `,defines:{USE_LIGHTMAP:""}})}};import{AxesHelper as Jw,Object3D as Zw,Vector4 as $w}from"three";import{EquirectangularReflectionMapping as Yw,sRGBEncoding as Kw,Vector3 as mm}from"three";import*as fm from"three";import{Color as Ww,Object3D as qw}from"three";var ph=class extends sn{constructor(){super([Ww,ye])}onDeserialize(e){if(e!=null)return e.a!==void 0?new ye(e.r,e.g,e.b,e.a):e.alpha!==void 0?new ye(e.r,e.g,e.b,e.alpha):new fm.Color(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}},UL=new ph,fh=class extends sn{constructor(){super(qw)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return Oe&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let i=t.nodeToObject[e.node];return Oe&&console.log("Deserialized object reference?",e,i,t?.nodeToObject),i||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),i}else if(e.guid){if(!t.context){console.error("Missing context");return}let i,n=t.gltf?.scene;return n&&(i=k.findByGuid(e.guid,n)),i||(i=k.findByGuid(e.guid,t.context.scene)),i?Oe&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},Xw=new fh,mh=class extends sn{constructor(){super([wt,M])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Oe&&console.log(e.guid,t.root,t.object,t.target);let i=this.findObjectForGuid(e.guid,t.root);if(i)return i;if(t.context)return this.findObjectForGuid(e.guid,t.context?.scene)}}findObjectForGuid(e,t){if(t.guid===e)return t;let i=k.foreachComponent(t,n=>{if(n.guid===e)return n},!1);if(i!==void 0)return i;for(let n=0;n<t.children.length;n++){let r=t.children[n],o=this.findObjectForGuid(e,r);if(o)return o}}},uh=new mh,gh=class extends sn{constructor(){super([_e])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){Oe&&console.log("DESERIALIZE EVENT",e);let i=new Array;for(let o of e.calls){Oe&&console.log(o);let s=uh.findObjectForGuid(o.target,t.root);!s&&t.context?.scene&&(s=uh.findObjectForGuid(o.target,t.context?.scene));let c=o.method?.length>0;if(s&&c){let u=()=>console.warn(`Could not find method ${o.method} on object ${s.name}`,s,typeof s[o.method]);if(typeof s[o.method]!="function"){let f=!1;o.method.startsWith("set_")&&o.method.length>4&&(o.method=o.method.substring(4),s[o.method]!==void 0&&(f=!0)),f||u()}}let d,l=o.argument;o.argument!==void 0?(typeof l=="object"&&(l=Xw.onDeserialize(o.argument,t),l||(l=uh.onDeserialize(o.argument,t))),d=new ui(c?(...u)=>h(...u):void 0,o.enabled)):d=new ui(c?(...u)=>h(...u):void 0,o.enabled);let h=(...u)=>{let f=s[o.method];typeof f=="function"?l!==void 0?f?.call(s,l):f?.call(s,...u):s[o.method]=l};if(d.method||(d.__debuginfo=t.object?.name),!s||!d.method){let u=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;s?console.warn('EventList method not found: "'+o.method+'" on',s):console.warn("EventList is missing target - will be ignored",o.target,u,e)}else i.push(d)}let n=new _e(i);Oe&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},GL=new gh;var os=D("debugreflectionprobe"),gm=D("noreflectionprobe"),Gi=class extends M{static get(e,t,i){if(!e||e.isObject3D!==!0||gm)return null;let n=Gi._probes.get(t);if(n){for(let r of n)if(r.__didAwake||r.__internalAwake(),r.enabled&&r.isInBox(e,i?1e-8:void 0))return os&&console.log("Found reflection probe",e.name,r.name),r}return os&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;set texture(e){this._texture=e}get texture(){return this._texture}center;size;_boxHelper;isInBox(e,t){return this._boxHelper?.isInBox(e,t)}constructor(){super(),Gi._probes.has(this.context)||Gi._probes.set(this.context,[]),Gi._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addNewComponent(De),this._boxHelper.updateBox(!0),os&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=Yw,this.texture.encoding=Kw,this.texture.needsUpdate=!0)}onDestroy(){let e=Gi._probes.get(this.context);if(e){let t=e.indexOf(this);t>=0&&e.splice(t,1)}}onSet(e){if(gm||e.sharedMaterials?.length<=0||!this.texture)return;let t=Gi._rendererMaterialsCache.get(e);t||(t=[],Gi._rendererMaterialsCache.set(e,t));for(let i=0;i<e.sharedMaterials.length;i++){let n=e.sharedMaterials[i];if(!n||n.envMap===void 0)continue;let r=t[i],o=r?.copy;r||(o=n.clone(),t.push({orig:n,copy:o}),o.__reflection_probe=this,o.envMap=this.texture,os&&console.log("Set reflection",e.name,e.guid)),e.sharedMaterials[i]=o}}onUnset(e){let t=Gi._rendererMaterialsCache.get(e);if(t)for(let i=0;i<t.length;i++){let n=t[i];e.sharedMaterials[i]=n.orig}}},Ot=Gi;U(Ot,"_probes",new Map),U(Ot,"_rendererMaterialsCache",new Map),P([S(mm)],Ot.prototype,"center",2),P([S(mm)],Ot.prototype,"size",2);var bm=D("noInstancing"),vm=!!D("debuglightmaps"),e_=D("debuginstancing"),t_=D("debugprogressive"),i_=D("noprogressive");var Yr=class{path=null;asset=null;default};var bh=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),i=this.getMaterial.bind(this),n=e.gameObject;if(this._targets=[],n)switch(n.type){case"Group":this._targets=[...n.children];break;case"Mesh":this._targets.push(n);break}return new Proxy(this,{get(r,o){if(typeof o=="string"){let s=parseInt(o);if(!isNaN(s))return i(s)}return r[o]},set(r,o,s){return typeof o=="string"&&t(s,Number.parseInt(o)),Reflect.set(r,o,s)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let i=this._targets[t];!i||i.material===void 0||(i.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let i=t[e];return i?i.material:null}},Fl=class extends M{receiveShadows=!1;shadowCastingMode=vh.Off;lightmapIndex=-1;lightmapScaleOffset=new Vi.Vector4(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==="Group")return this.gameObject.children[0]}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(e){this.sharedMaterials[0]=e}get material(){return this.sharedMaterials[0]}set material(e){this.sharedMaterials[0]=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new bh(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return bm}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(let t of this._lightmaps)t.lightmap=e}get hasLightmap(){let e=this.lightmap;return e!=null}awake(){this.clearInstancingState(),this.probeAnchor&&os&&this.probeAnchor.add(new Jw(.2)),this._reflectionProbe=null;let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let i=0;i<this.gameObject.children.length;i++){let n=this.gameObject.children[i];if(!(n.type!=="Mesh"||k.getComponent(n,Fl))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}n.renderOrder=this.renderOrder[t],t+=1}}}}else(e==="Mesh"||e==="SkinnedMesh")&&(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree.bind(this)),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0]));if(this.lightmapIndex>=0){let t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps=[],e==="Mesh"){if(!this.gameObject.material?.isMeshBasicMaterial){let i=new Ui(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,vm)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new Ui(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,vm),n.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;clearInstancingState(){this._isInstancingEnabled=!1,this.handles=void 0,this.prevLayers=void 0}setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=e,e){if(this.handles===void 0){if(this.handles=n_.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return k.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return k.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(let t of this.handles)t.remove();return!0}return!1}start(){if(this.enableInstancing&&!bm&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.gameObject.type==="Group")for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&(this.gameObject.visible=!0,this.applyStencil()),this.updateReflectionProbe()}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){Ur.applyStencil(this)}onBeforeRender(){if(!this.gameObject)return;Fl.envmap=this.scene.environment;let e=this.gameObject[ja]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.gameObject.type==="Group"&&this.gameObject.children?.length>0)for(let t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(e&&(delete this.gameObject[ja],this.handles)){for(let i=this.handles.length-1;i>=0;i--)this.handles[i].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&k.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let i=this.handles[t];this.prevLayers||(this.prevLayers=[]);let n=i.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(n):this.prevLayers[t]=n,i.object.layers.disableAll()}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onSet(this)}onBeforeRenderThree(e,t,i,n,r,o){if(!i_&&r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,t_?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{mn.assignTextureLOD(this.context,this.sourceId,r)},2e3)):mn.assignTextureLOD(this.context,this.sourceId,r)),r.envMapIntensity!==void 0){let s=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/s)}if(this._lightmaps)for(let s of this._lightmaps)s.onBeforeRenderThree(r)}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==vh.On?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){if(this._reflectionProbe=null,this.reflectionProbeUsage!==0){let e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=Ot.get(e,this.context,t)}}},le=Fl;U(le,"envmap",null),P([S()],le.prototype,"receiveShadows",2),P([S()],le.prototype,"shadowCastingMode",2),P([S()],le.prototype,"lightmapIndex",2),P([S($w)],le.prototype,"lightmapScaleOffset",2),P([S()],le.prototype,"enableInstancing",2),P([S()],le.prototype,"renderOrder",2),P([S()],le.prototype,"allowOcclusionWhenDynamic",2),P([S(Zw)],le.prototype,"probeAnchor",2),P([S()],le.prototype,"reflectionProbeUsage",2);var sr=class extends le{},Kr=class extends sr{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},vh=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(vh||{}),yh=class{objs=[];setup(e,t,i,n,r=0){let o=this.tryCreateOrAddInstance(e,t,n);if(o)return i===null&&(i=[]),i.push(o),i;if(r<=0&&e.type!=="Mesh"){let s=r+1;for(let c of e.children)i=this.setup(c,t,i,n,s)}return i}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){let n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing||n>=i.rend.enableInstancing.length||!i.rend.enableInstancing[n])return null;let r=e,o=r.geometry,s=r.material;for(let d of this.objs)if(!d.isFull()&&d.geo===o&&d.material===s)return d.addInstance(r);let c=new Hl(e.name,o,s,200,t);return this.objs.push(c),c.addInstance(r)}return null}},n_=new yh,xh=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,k.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},wh=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,i,n,r){this.name=e,this.geo=t,this.material=i,this.context=r,this.maxCount=n,e_&&(i=new Vi.MeshBasicMaterial({color:this.randomColor()})),this.inst=new Vi.InstancedMesh(t,i,n),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new Vi.Color(Math.random(),Math.random(),Math.random())}addInstance(e){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;let t=new xh(-1,e,this);return this.add(t),t}add(e){e.instanceIndex<0&&(e.instanceIndex=this.currentCount,e.instanceIndex>=this.handles.length?this.handles.push(e):this.handles[e.instanceIndex]=e),e.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(e.instanceIndex,e.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this.inst.count>0&&(this.inst.visible=!0)}remove(e){if(!e||e.instanceIndex<0||e.instanceIndex>=this.handles.length||this.inst.count<=0)return;if(this.handles[e.instanceIndex]!==e){console.error("instance handle is not part of renderer, was it removed before?",e.instanceIndex,this.name);let i=this.handles.indexOf(e);if(i<0)return;e.instanceIndex=i}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,wh.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let i=this.handles[this.currentCount-1];i&&(i.instanceIndex=e.instanceIndex,i.updateInstanceMatrix(),this.handles[e.instanceIndex]=i,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),e.instanceIndex=-1,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0}updateInstance(e,t){this.inst.setMatrixAt(t,e),this.inst.instanceMatrix.needsUpdate=!0}},Hl=wh;U(Hl,"nullMatrix",new Vi.Matrix4);import{Object3D as o_,Vector3 as s_}from"three";var Jr=class extends De{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},It=class extends M{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:It.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?It.saveArrayBuffer(i,e):It.saveJson(i,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new r_,this.exporter.register(s=>new ea(s)),this.ext=new Xo,this.ext.registerExport(this.exporter)),It.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:It.collectAnimations(e)},n=new o_;t?.pivot&&n.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(s=>{s&&(n.children.push(s),s.matrixAutoUpdate=!1,s.matrix.copy(s.matrixWorld),k.getComponentsInChildren(s,le).forEach(c=>{k.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new Po(n);return this.ext.context=r,new Promise((s,c)=>{try{this.exporter?.parse(n,d=>{o(),s(d)},d=>{o(),c(d)},i)}catch(d){console.error(d),c(d)}finally{console.log("FINALLY")}});function o(){e.forEach(s=>{!s||(s.matrixAutoUpdate=!0,k.getComponentsInChildren(s,le).forEach(c=>{k.isActiveInHierarchy(c.gameObject)&&c.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){let 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(let i of e)!i||i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){let i=t||new s_;return i.set(0,0,0),e.forEach(n=>{i.add(X(n))}),console.log(i),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}}}};import{Color as Nl,GridHelper as a_}from"three";var Wi=class extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!_i)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new a_(e,t,this.color0??new Nl(.4,.4,.4),this.color1??new Nl(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};P([S()],Wi.prototype,"isGizmo",2),P([S(Nl)],Wi.prototype,"color0",2),P([S(Nl)],Wi.prototype,"color1",2);import{GroundProjectedEnv as l_}from"three/examples/jsm/objects/GroundProjectedEnv.js";var qi=class extends M{set scale(e){this._scale=e,this.env?.scale.setScalar(e)}get scale(){return this._scale}_scale=20;set radius(e){this._radius=e,this.env&&(this.env.height=e)}get radius(){return this._radius}_radius=100;set height(e){this._height=e,this.env&&(this.env.height=e)}get height(){return this._height}_height=100;_lastEnvironment;env;_watcher;onEnable(){this.context.time.frameCount>0&&this.updateAndCreate()}start(){this.updateAndCreate()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateAndCreate(){this.updateProjection(),this._watcher||(this._watcher=new Hn(this.context.scene,"environment"),this._watcher.subscribeWrite(e=>{this.updateProjection()})),this._watcher.apply()}updateProjection(){if(!this.context.scene.environment){this.env?.removeFromParent();return}(!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new l_(this.context.scene.environment)),this._lastEnvironment=this.context.scene.environment,this.env.parent||this.gameObject.add(this.env),this.env.scale.setScalar(this._scale),this.env.radius=this._radius,this.env.height=this._height,this.env.isObject3D===!0&&this.env.layers.set(2)}};P([S()],qi.prototype,"scale",1),P([S()],qi.prototype,"radius",1),P([S()],qi.prototype,"height",1);import*as nt from"three";import{Color as c_}from"three";function _h(a){return a*Math.PI/180}var ym=300,xm=D("debuglights");var We=class extends M{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new nt.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){let t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e===1||e===2)}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){let i=this._webARRoot?.arScale;typeof i=="number"&&i>0&&(t/=i)}this.light.intensity=e*t}}get intensity(){return this._intensity}_intensity=1;get shadowDistance(){let e=this.light;return e?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;let t=this.light;if(t){let i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){let e=this.light;return e?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;let t=this.light;t&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}updateIntensity(){this.intensity=this._intensity}awake(){this.color=new nt.Color(this.color??16777215)}onEnable(){this.createLight(),!this.isBaked&&(this.light&&(this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),2),this._webXRStartedListener=Y.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=Y.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){Y.removeEventListener("xrStarted",this._webXRStartedListener),Y.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=k.getComponentInParent(this.gameObject,Tt)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInXR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){if(this.light)return;let e=this.selfIsLight;if(e)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else switch(this.type){case 1:let t=new nt.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-ym*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Mo(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),xm){let o=new nt.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(o)}break;case 0:let i=new nt.SpotLight(this.color,this.intensity*Math.PI,this.range,_h(this.spotAngle/2),1-_h(this.innerSpotAngle/2)/_h(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;let n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:let r=new nt.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light!==void 0){this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4;let t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=ym*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{let i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,xm&&this.context.scene.add(new nt.CameraHelper(t)),this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};P([S()],We.prototype,"type",2),P([S(c_)],We.prototype,"color",2),P([S()],We.prototype,"shadowNearPlane",1),P([S()],We.prototype,"shadowBias",1),P([S()],We.prototype,"shadowNormalBias",1),P([S()],We.prototype,"shadows",1),P([S()],We.prototype,"lightmapBakeType",2),P([S()],We.prototype,"intensity",1),P([S()],We.prototype,"shadowDistance",1),P([S()],We.prototype,"shadowResolution",1);var ij=new nt.Vector3(0,0,0);import*as zl from"three";import{Vector3 as d_}from"three";var ss=D("debugLODs"),h_=D("noLODs");var pi=class{screenRelativeTransitionHeight;distance;renderers};P([S()],pi.prototype,"screenRelativeTransitionHeight",2),P([S()],pi.prototype,"distance",2),P([S()],pi.prototype,"renderers",2);var Eh=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let i of t.renderers){let n=this.findRenderer(i,e.gameObject);n&&n.gameObject?this.renderers.push(n):ss&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=k.foreachComponent(t,n=>n.guid===e||Object.getPrototypeOf(n)?.guid===e?n:null);if(i)return i;for(let n of t.children){let r=this.findRenderer(e,n);if(r)return r}return null}},Tn=class extends M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!h_&&!this._lodsHandler&&!!this.gameObject&&(ss&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let n of this.lodModels){e=Math.max(n.distance,e);let r=new Eh(this,n);this._lods.push(r);for(let o of r.renderers)t.includes(o)||t.push(o)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){let r=new zl.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new zl.Object3D;ss&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],o=this._lodsHandler[n],s=r.gameObject,c=0,d=0;ss&&console.log(n,s.name);for(let h of this._lods){let u=null;h.renderers.includes(r)?u=s:u=i,ss&&console.log("add",h.model.distance,u.name);let f=h.model.distance;d=f-c,c=Math.max(f,c),this.onAddLodLevel(o,u,f)}let l=c+d;ss&&console.log("cull",l),this.onAddLodLevel(o,i,l)}}}update(){if(!this.gameObject||!this._lodsHandler)return;let e=this.context.mainCamera;if(!!e)for(let t of this._lodsHandler)t.update(e)}onAddLodLevel(e,t,i){e.addLevel(t,i*this._distanceFactor);let n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}};P([S(d_)],Tn.prototype,"localReferencePoint",2),P([S(pi)],Tn.prototype,"lodModels",2);var Zr=class extends M{},$r=class extends M{};var Ch=D("debugnestedgltf"),ar=class extends M{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;Ch&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new Ge;t.idProvider=new Ue(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;Ch&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let n=await this.filePath?.instantiate?.call(this.filePath,t);n&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0),this.destroy(),Ch&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,n)}}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}};P([S(Ye)],ar.prototype,"filePath",2);import{Quaternion as u_,Euler as p_,Vector3 as eo,Plane as f_}from"three";var fi=class extends M{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new eo(0,0,0);rotationOffset=new eo(0,0,0);offset=new eo(0,0,0);update(){if(!this.from)return;var e=X(this.from),t=Ie(this.from);this.offset.copy(this.positionOffset);let i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){let s=new f_(this.gameObject.up,0),c=X(this.referenceSpace);s.setFromNormalAndCoplanarPoint(this.gameObject.up,c);let d=new eo(0,0,0);s.projectPoint(e,d),e.copy(d)}this.affectPosition&&se(this.gameObject,e);let n=new p_(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new u_().setFromEuler(n);this.affectRotation&&$e(this.gameObject,t.multiply(r));let o=new eo;this.from.getWorldDirection(o).multiplyScalar(50),this.levelLookDirection&&(o.y=0),this.alignLookDirection&&this.gameObject.lookAt(o)}};P([S(k)],fi.prototype,"referenceSpace",2),P([S(k)],fi.prototype,"from",2),P([S(eo)],fi.prototype,"positionOffset",2),P([S(eo)],fi.prototype,"rotationOffset",2);import*as Ee from"three";import*as mi from"three";var to=class{randomizeRotationDirection=0;duration=5;loop=!0;prewarm=!1;startDelay=void 0;startDelayMultiplier=0;startLifetime=void 0;startLifetimeMultiplier=5;startSpeed=void 0;startSpeedMultiplier=5;startSize3D=!1;startSize=void 0;startSizeMultiplier=1;startSizeX=void 0;startSizeXMultiplier=1;startSizeY=void 0;startSizeYMultiplier=1;startSizeZ=void 0;startSizeZMultiplier=1;startRotation3D=!1;startRotation=void 0;startRotationMultiplier=0;startRotationX=void 0;startRotationXMultiplier=0;startRotationY=void 0;startRotationYMultiplier=0;startRotationZ=void 0;startRotationZMultiplier=0;flipRotation=0;startColor=new mi.Color(1,1,1);startColor1=new mi.Color(0,0,0);gravityModifier=void 0;gravityModifierMultiplier=0;simulationSpace=0;customSimulationSpace=null;simulationSpeed=1;useUnscaledTime=!1;scalingMode=1;playOnAwake=!0;maxParticles=1e3;emitterVelocityMode=1;stopAction=0;ringBufferMode=0;ringBufferLoopRange=new mi.Vector2(0,1);cullingMode=0},io=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},no=class{shapeType=Th.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new mi.Vector3(1,1,1);boxThickness=new mi.Vector3(0,0,0);position=new mi.Vector3(0,0,0);rotation=new mi.Vector3(0,0,0);scale=new mi.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},Th=(p=>(p[p.Sphere=0]="Sphere",p[p.SphereShell=1]="SphereShell",p[p.Hemisphere=2]="Hemisphere",p[p.HemisphereShell=3]="HemisphereShell",p[p.Cone=4]="Cone",p[p.Box=5]="Box",p[p.Mesh=6]="Mesh",p[p.ConeVolume=7]="ConeVolume",p[p.Circle=10]="Circle",p[p.SingleSidedEdge=11]="SingleSidedEdge",p[p.MeshRenderer=12]="MeshRenderer",p[p.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",p[p.BoxShell=14]="BoxShell",p[p.BoxEdge=15]="BoxEdge",p[p.Donut=16]="Donut",p[p.Rectangle=17]="Rectangle",p[p.Sprite=18]="Sprite",p[p.SpriteRenderer=19]="SpriteRenderer",p))(Th||{});var g_=D("debugparticles"),Rh=class{age=0;lifetime=0;position;velocity;color},lr=class extends M{get mainTexture(){if(this.sharedMaterial){let e=this.context.assets.findTexture(this.sharedMaterial);if(e)return e}return null}getMesh(e){return this.mesh?this.context.assets.findMesh(this.mesh):null}sharedMaterial;mesh;awake(){g_&&console.log(this)}},ro=class extends M{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new Ee.Quaternion;tempVec3=new Ee.Vector3;tempQuat=new Ee.Quaternion;awake(){this.renderer=k.getComponent(this.gameObject,lr),console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new Ee.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new Ee.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new Ee.Float32BufferAttribute(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let i=0;i<e.length;i++)e[i*3]=1,e[i*3+1]=1,e[i*3+2]=1;let t=new Ee.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new Ee.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new Ee.Points(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}emit(e){let t=this.activeCount;for(let i=0;i<t;i+=1){if(i>=this.particleStates.length){let r=new Rh;r.lifetime=this.main.startLifetime??1,r.position=new Ee.Vector3,r.velocity=new Ee.Vector3,r.color=new Ee.Color(1,0,0),this.particleStates.push(r),this.initializeParticle(i,r),r.age=r.lifetime*Math.random()}let n=this.particleStates[i];if(n.age>n.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(i,n);continue}n.age+=e,this.particleStates[i]=n}this.activeCount+=e*this.emission.rate,this.activeCount=Math.min(this.main.maxParticles,this.activeCount)}initializeParticle(e,t){if(!this.geometry)return;t.age=0,t.color.set(this.main.startColor),this.main.startColor1&&t.color.lerp(this.main.startColor1,Math.random()),this.geometry.attributes.color.needsUpdate=!0,this.assignPosition(t.position),this.assignVelocity(t.position,t.velocity);let i=t.position;i.multiply(this.shape.scale),i.applyQuaternion(this.shapeRotation),i.add(this.shape.position),this.particleStates.splice(e,1),this.particleStates.push(t)}updateOverLifetime(e,t){}assignPosition(e){switch(this.shape.shapeType){case 0:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).multiplyScalar(this.shape.radius);break;case 5:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5);break;default:e.set(0,0,0);break}}assignVelocity(e,t){switch(this.shape.shapeType){case 0:t.set(e.x,e.y,e.z);break;case 5:t.set(0,0,1),this.shape.sphericalDirectionAmount>0&&(this.tempVec3.set(e.x,e.y,e.z).multiply(this.shape.scale).normalize(),t.lerp(this.tempVec3,this.shape.sphericalDirectionAmount));break;case 4:let i=new Ee.Vector3(0,1,0);t.copy(i);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*J.toRadians(this.shape.arc)),t.copy(this.tempVec3.set(1,0,0).applyQuaternion(this.tempQuat));break;default:t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1);break}switch(t.normalize(),this.shape.shapeType){case 10:e.add(t).multiplyScalar(this.shape.radius);break}t.multiplyScalar(this.main.startSpeedMultiplier)}};import*as _m from"three";function*wm(a,e=null){let t=e?e.time:K.Current.time,i=t.time;for(;t.time-i<a;)yield}var rt=class extends M{awake(){this.context.connection.beginListen("joined-room",this.tryAssignColor.bind(this))}_didAssignPlayerColor=!1;onEnable(){this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}*waitForConnection(){for(;!this.destroyed&&this.enabled&&(yield wm(.2),!this.tryAssignColor()););}tryAssignColor(){let e=k.getComponentInParent(this.gameObject,ue);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=rt.hashCode(e),i=rt.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(let n of this.gameObject.children){let r=n;r.material&&r.material.color&&this.assignColor(i,e,r)}}assignColor(e,t,i){let n=i.material;!n||(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new _m.Color(t/255,i/255,n/255)}};import*as Gl from"three";import{Object3D as w_,ShaderMaterial as __,Texture as E_,Vector2 as Ph,Vector4 as C_}from"three";function b_(){return new Promise((a,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),a())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function Em(a){await b_(),a()}import{PlaneGeometry as v_,MeshBasicMaterial as y_,Mesh as x_}from"three";var Ul=class{static createPrimitive(e,t){let i;switch(e){case 0:let n=new v_(1,1,1,1),r=t?.material??new y_({color:16777215});i=new x_(n,r)}return t?.name&&(i.name=t.name),i}};var Sh=D("debugvideo");var Cm=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(Cm||{}),Ce=class extends M{renderer=null;playOnAwake=!0;playOnEnable;aspectMode=0;renderMode;targetMaterialProperty;targetMaterialRenderer;targetTexture;time=0;_playbackSpeed=1;get playbackSpeed(){return this.videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this.videoElement&&(this.videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this.videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this.videoElement&&(this.videoElement.loop=e)}get currentTime(){return this.videoElement?.currentTime??this.time}set currentTime(e){this.videoElement?this.videoElement.currentTime=e:this.time=e}get isPlaying(){let e=this.videoElement;return e?e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA:!1}get crossOrigin(){return this.videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this.videoElement&&(e!==null?this.videoElement.setAttribute("crossorigin",e):this.videoElement.removeAttribute("crossorigin"))}get videoTexture(){return this._videoTexture}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;_videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setVideo(e){this.clip=e,this.source=0,this.videoElement?(this.videoElement.srcObject=e,this._isPlaying&&this.videoElement.play(),this.updateAspect()):this.create(!0)}setClipURL(e){this.url!==e&&(this.url=e,this.source=1,Sh&&console.log("set url",e),this.videoElement?(this.videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(!0))}awake(){this.create(this.playOnAwake),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this._isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}})}onEnable(){this.playOnEnable===!0&&this.handleBeginPlaying(!0),this.screenspace?this._overlay?.start():this._overlay?.stop()}onDisable(){this.pause()}onDestroy(){this.videoElement&&(this.videoElement.parentElement?.removeChild(this.videoElement),this.videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}_receivedInput=!1;constructor(){super(),Em(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],D("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}play(){!this.videoElement||this._isPlaying&&!this.videoElement?.ended&&!this.videoElement?.paused||(this._isPlaying=!0,this._receivedInput||(this.videoElement.muted=!0),this.updateVideoElementSettings(),this.videoElement?.play().catch(e=>{console.warn(e)}),Sh&&console.log("play",this.videoElement))}stop(){this._isPlaying=!1,this.videoElement&&(this.videoElement.currentTime=0,this.videoElement.pause())}pause(){this._isPlaying=!1,this.videoElement?.pause()}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url;break}if(!!t){if(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"){this.videoElement.src=t;let i=this.videoElement.captureStream?.call(this.videoElement);this.clip=i}else this.videoElement.srcObject=t;this._videoTexture||(this._videoTexture=new Gl.VideoTexture(this.videoElement)),this._videoTexture.flipY=!1,this._videoTexture.encoding=Gl.sRGBEncoding,this.handleBeginPlaying(e),console.log(this)}}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new Oh(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),Sh&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=k.getComponent(this.gameObject,le)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,Cm[this.renderMode],this);return}let i=t.material;if(i)if(this._targetObjects.push(t),i!==this.videoMaterial&&(this.videoMaterial=i.clone(),t.material=this.videoMaterial),!this.targetMaterialProperty)this.videoMaterial.map=this._videoTexture;else switch(this.targetMaterialProperty){default:this.videoMaterial.map=this._videoTexture;break}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&this.play()}updateVideoElementSettings(){!this.videoElement||(this.videoElement.loop=this._isLooping,this.videoElement.currentTime=this.currentTime,this.videoElement.playbackRate=this._playbackSpeed,this.videoElement.playsInline=!0,this.videoElement.muted=!this._receivedInput&&this.audioOutputMode!==0,(this.playOnAwake||this.playOnEnable)&&(this.videoElement.autoplay=!0))}updateVideoElementStyles(){!this.videoElement||(this.videoElement.style.userSelect="none",this.videoElement.style.visibility="hidden",this.videoElement.style.display="none",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){let e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let n;for(let r of i.getVideoTracks()){let o=r.getSettings();if(o&&o.width&&o.height){n=o.width/o.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(let r of this._targetObjects){let o=1;if(r.parent){let s=Is(r.parent);o=s.x/s.y}switch(this.aspectMode){case 1:r.scale.y=1/n*r.scale.x*o;break;case 2:r.scale.x=n*r.scale.y*o;break}}for(let r=0;r<3;r++)yield}}};P([S(w_)],Ce.prototype,"renderer",2),P([S()],Ce.prototype,"playOnAwake",2),P([S()],Ce.prototype,"playOnEnable",2),P([S()],Ce.prototype,"aspectMode",2),P([S()],Ce.prototype,"renderMode",2),P([S()],Ce.prototype,"targetMaterialProperty",2),P([S(le)],Ce.prototype,"targetMaterialRenderer",2),P([S(E_)],Ce.prototype,"targetTexture",2),P([S()],Ce.prototype,"time",2),P([S()],Ce.prototype,"playbackSpeed",1),P([S()],Ce.prototype,"isLooping",1);var Oh=class{context;constructor(e){this.context=e,this._input=new Ih(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;let t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;let e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Ul.createPrimitive(0,{material:new kh(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}let t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();let i=t.material;i?.reset(),this._input?.enable(i)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){let e=this._screenspaceModeQuad?.material;!e||(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input},Ih=class{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});let t=new Ph;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){let r=new Ph(n.movementX,n.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;let r=n.touches[0],o=n.touches[1],s=r.clientX-o.clientX,c=r.clientY-o.clientY,d=Math.sqrt(s*s+c*c);if(this._lastPinch!==0){let l=d-this._lastPinch;this._material.zoom-=l*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}},kh=class extends __{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){let t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new Ph;get offset(){let e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){let t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new C_(0,0,1,1)}},this.vertexShader=`
208
+ `,defines:{USE_LIGHTMAP:""}})}};import{AxesHelper as Cb,Object3D as Tb,Vector4 as Rb}from"three";import{EquirectangularReflectionMapping as wb,sRGBEncoding as xb,Vector3 as rp}from"three";import*as ip from"three";import{Color as vb,Object3D as yb}from"three";var ed=class extends Vn{constructor(){super([vb,ce])}onDeserialize(e){if(e!=null)return e.a!==void 0?new ce(e.r,e.g,e.b,e.a):e.alpha!==void 0?new ce(e.r,e.g,e.b,e.alpha):new ip.Color(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}},pk=new ed,td=class extends Vn{constructor(){super(yb)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let n=t.objectToNode[e.uuid];return _e&&console.log(n,e.name,e.uuid),{node:n}}}onDeserialize(e,t){if(e){if(e.node!==void 0&&t.nodeToObject){let n=t.nodeToObject[e.node];return _e&&console.log("Deserialized object reference?",e,n,t?.nodeToObject),n||console.warn("Did not find node: "+e.node,t.nodeToObject,t.object),n}else if(e.guid){if(!t.context){console.error("Missing context");return}let n,i=t.gltf?.scene;return i&&(n=R.findByGuid(e.guid,i)),n||(n=R.findByGuid(e.guid,t.context.scene)),n?_e&&console.log("Deserialized object reference?",e,n,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),n}}}},_b=new td,nd=class extends Vn{constructor(){super([st,O])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){_e&&console.log(e.guid,t.root,t.object,t.target);let n=this.findObjectForGuid(e.guid,t.root);if(n)return n;if(t.context)return this.findObjectForGuid(e.guid,t.context?.scene)}}findObjectForGuid(e,t){if(t.guid===e)return t;let n=R.foreachComponent(t,i=>{if(i.guid===e)return i},!1);if(n!==void 0)return n;for(let i=0;i<t.children.length;i++){let r=t.children[i],s=this.findObjectForGuid(e,r);if(s)return s}}},$c=new nd,id=class extends Vn{constructor(){super([he])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){_e&&console.log("DESERIALIZE EVENT",e);let n=new Array;for(let s of e.calls){_e&&console.log(s);let a=$c.findObjectForGuid(s.target,t.root);!a&&t.context?.scene&&(a=$c.findObjectForGuid(s.target,t.context?.scene));let c=s.method?.length>0;if(a&&c){let h=()=>console.warn(`Could not find method ${s.method} on object ${a.name}`,a,typeof a[s.method]);if(typeof a[s.method]!="function"){let b=!1;s.method.startsWith("set_")&&s.method.length>4&&(s.method=s.method.substring(4),a[s.method]!==void 0&&(b=!0)),b||h()}}let d,l=s.argument;s.argument!==void 0?(typeof l=="object"&&(l=_b.onDeserialize(s.argument,t),l||(l=$c.onDeserialize(s.argument,t))),d=new Qt(c?(...h)=>u(...h):void 0,s.enabled)):d=new Qt(c?(...h)=>u(...h):void 0,s.enabled);let u=(...h)=>{let b=a[s.method];typeof b=="function"?l!==void 0?b?.call(a,l):b?.call(a,...h):a[s.method]=l};if(d.method||(d.__debuginfo=t.object?.name),!a||!d.method){let h=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;a?console.warn('EventList method not found: "'+s.method+'" on',a):console.warn("EventList is missing target - will be ignored",s.target,h,e)}else n.push(d)}let i=new he(n);_e&&console.log(i);let r=t.target;return r!==void 0&&t.path!==void 0&&i.setEventTarget(t.path,r),i}}},fk=new id;var Co=I("debugreflectionprobe"),op=I("noreflectionprobe"),Cn=class extends O{static get(e,t,n){if(!e||e.isObject3D!==!0||op)return null;let i=Cn._probes.get(t);if(i){for(let r of i)if(r.__didAwake||r.__internalAwake(),r.enabled&&r.isInBox(e,n?1e-8:void 0))return Co&&console.log("Found reflection probe",e.name,r.name),r}return Co&&console.debug("Did not find reflection probe",e.name,n,e),null}_texture;set texture(e){this._texture=e}get texture(){return this._texture}center;size;_boxHelper;isInBox(e,t){return this._boxHelper?.isInBox(e,t)}constructor(){super(),Cn._probes.has(this.context)||Cn._probes.set(this.context,[]),Cn._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addNewComponent(Ce),this._boxHelper.updateBox(!0),Co&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=wb,this.texture.encoding=xb,this.texture.needsUpdate=!0)}onDestroy(){let e=Cn._probes.get(this.context);if(e){let t=e.indexOf(this);t>=0&&e.splice(t,1)}}onSet(e){if(op||e.sharedMaterials?.length<=0||!this.texture)return;let t=Cn._rendererMaterialsCache.get(e);t||(t=[],Cn._rendererMaterialsCache.set(e,t));for(let n=0;n<e.sharedMaterials.length;n++){let i=e.sharedMaterials[n];if(!i||i.envMap===void 0)continue;let r=t[n],s=r?.copy;r||(s=i.clone(),t.push({orig:i,copy:s}),s.__reflection_probe=this,s.envMap=this.texture,Co&&console.log("Set reflection",e.name,e.guid)),e.sharedMaterials[n]=s}}onUnset(e){let t=Cn._rendererMaterialsCache.get(e);if(t)for(let n=0;n<t.length;n++){let i=t[n];e.sharedMaterials[n]=i.orig}}},mt=Cn;j(mt,"_probes",new Map),j(mt,"_rendererMaterialsCache",new Map),C([x(rp)],mt.prototype,"center",2),C([x(rp)],mt.prototype,"size",2);var sp=I("noInstancing"),ap=!!I("debuglightmaps"),Sb=I("debuginstancing"),Pb=I("debugprogressive"),Ob=I("noprogressive");var _r=class{path=null;asset=null;default};var rd=class{_renderer;_targets=[];is(e){return this._renderer===e}constructor(e){this._renderer=e;let t=this.setMaterial.bind(this),n=this.getMaterial.bind(this),i=e.gameObject;if(this._targets=[],i)switch(i.type){case"Group":this._targets=[...i.children];break;case"Mesh":this._targets.push(i);break}return new Proxy(this,{get(r,s){if(typeof s=="string"){let a=parseInt(s);if(!isNaN(a))return n(a)}return r[s]},set(r,s,a){return typeof s=="string"&&t(a,Number.parseInt(s)),Reflect.set(r,s,a)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let n=this._targets[t];!n||n.material===void 0||(n.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let n=t[e];return n?n.material:null}},Ga=class extends O{receiveShadows=!1;shadowCastingMode=od.Off;lightmapIndex=-1;lightmapScaleOffset=new Tn.Vector4(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==="Group")return this.gameObject.children[0]}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(e){this.sharedMaterials[0]=e}get material(){return this.sharedMaterials[0]}set material(e){this.sharedMaterials[0]=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new rd(this)),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(let t of this._lightmaps)t.lightmap=e}get hasLightmap(){let e=this.lightmap;return e!=null}awake(){this.clearInstancingState(),this.probeAnchor&&Co&&this.probeAnchor.add(new Cb(.2)),this._reflectionProbe=null;let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let n=0;n<this.gameObject.children.length;n++){let i=this.gameObject.children[n];if(!(i.type!=="Mesh"||R.getComponent(i,Ga))){if(this.renderOrder.length<=t){console.error("Incorrect element count",this);break}i.renderOrder=this.renderOrder[t],t+=1}}}}else(e==="Mesh"||e==="SkinnedMesh")&&(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree.bind(this)),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0]));if(this.lightmapIndex>=0){let t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps=[],e==="Mesh"){if(!this.gameObject.material?.isMeshBasicMaterial){let n=new xn(this.gameObject,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,ap)}}else if(e==="Group"){for(let n of this.gameObject.children)if(!n.material?.isMeshBasicMaterial){let i=new xn(n,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,ap),i.bindOnBeforeRender()}}}}}_isInstancingEnabled=!1;handles=void 0;prevLayers=void 0;clearInstancingState(){this._isInstancingEnabled=!1,this.handles=void 0,this.prevLayers=void 0}setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this.handles===void 0||this.handles!=null&&this.handles.length>0);if(this._isInstancingEnabled=e,e){if(this.handles===void 0){if(this.handles=kb.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return R.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return R.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(let t of this.handles)t.remove();return!0}return!1}start(){if(this.enableInstancing&&!sp&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.gameObject.type==="Group")for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&(this.gameObject.visible=!0,this.applyStencil()),this.updateReflectionProbe()}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){fr.applyStencil(this)}onBeforeRender(){if(!this.gameObject)return;Ga.envmap=this.scene.environment;let e=this.gameObject[Xs]===!0||this.gameObject.matrixWorldNeedsUpdate;if(this.gameObject.type==="Group"&&this.gameObject.children?.length>0)for(let t of this.gameObject.children)this.applySettings(t);else this.applySettings(this.gameObject);if(e&&(delete this.gameObject[Xs],this.handles)){for(let n=this.handles.length-1;n>=0;n--)this.handles[n].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this.handles&&this.handles.length<=0&&R.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let n=this.handles[t];this.prevLayers||(this.prevLayers=[]);let i=n.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(i):this.prevLayers[t]=i,n.object.layers.disableAll()}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onSet(this)}onBeforeRenderThree(e,t,n,i,r,s){if(!Ob&&r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,Pb?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{Jn.assignTextureLOD(this.context,this.sourceId,r)},2e3)):Jn.assignTextureLOD(this.context,this.sourceId,r)),r.envMapIntensity!==void 0){let a=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/a)}if(this._lightmaps)for(let a of this._lightmaps)a.onBeforeRenderThree(r)}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==od.On?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){if(this._reflectionProbe=null,this.reflectionProbeUsage!==0){let e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=mt.get(e,this.context,t)}}},$=Ga;j($,"envmap",null),C([x()],$.prototype,"receiveShadows",2),C([x()],$.prototype,"shadowCastingMode",2),C([x()],$.prototype,"lightmapIndex",2),C([x(Rb)],$.prototype,"lightmapScaleOffset",2),C([x()],$.prototype,"enableInstancing",2),C([x()],$.prototype,"renderOrder",2),C([x()],$.prototype,"allowOcclusionWhenDynamic",2),C([x(Tb)],$.prototype,"probeAnchor",2),C([x()],$.prototype,"reflectionProbeUsage",2);var Bi=class extends ${},Er=class extends Bi{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},od=(i=>(i[i.Off=0]="Off",i[i.On=1]="On",i[i.TwoSided=2]="TwoSided",i[i.ShadowsOnly=3]="ShadowsOnly",i))(od||{}),sd=class{objs=[];setup(e,t,n,i,r=0){let s=this.tryCreateOrAddInstance(e,t,i);if(s)return n===null&&(n=[]),n.push(s),n;if(r<=0&&e.type!=="Mesh"){let a=r+1;for(let c of e.children)n=this.setup(c,t,n,i,a)}return n}tryCreateOrAddInstance(e,t,n){if(e.type==="Mesh"){let i=n.foundMeshes;if(n.foundMeshes+=1,!n.rend.enableInstancing||i>=n.rend.enableInstancing.length||!n.rend.enableInstancing[i])return null;let r=e,s=r.geometry,a=r.material;for(let d of this.objs)if(!d.isFull()&&d.geo===s&&d.material===a)return d.addInstance(r);let c=new Ua(e.name,s,a,200,t);return this.objs.push(c),c.addInstance(r)}return null}},kb=new sd,ad=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,n){this.instanceIndex=e,this.object=t,this.instancer=n,R.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},ld=class{name="";geo;material;get currentCount(){return this.inst.count}context;inst;handles=[];maxCount;isFull(){return this.currentCount>=this.maxCount}constructor(e,t,n,i,r){this.name=e,this.geo=t,this.material=n,this.context=r,this.maxCount=i,Sb&&(n=new Tn.MeshBasicMaterial({color:this.randomColor()})),this.inst=new Tn.InstancedMesh(t,n,i),this.inst.count=0,this.inst.layers.set(2),this.inst.visible=!0,this.context.scene.add(this.inst)}randomColor(){return new Tn.Color(Math.random(),Math.random(),Math.random())}addInstance(e){if(this.currentCount>=this.maxCount)return console.error("TOO MANY INSTANCES - resize is not yet implemented!",this.inst.count),null;let t=new ad(-1,e,this);return this.add(t),t}add(e){e.instanceIndex<0&&(e.instanceIndex=this.currentCount,e.instanceIndex>=this.handles.length?this.handles.push(e):this.handles[e.instanceIndex]=e),e.object.updateWorldMatrix(!0,!0),this.inst.setMatrixAt(e.instanceIndex,e.object.matrixWorld),this.inst.instanceMatrix.needsUpdate=!0,this.inst.count+=1,this.inst.count>0&&(this.inst.visible=!0)}remove(e){if(!e||e.instanceIndex<0||e.instanceIndex>=this.handles.length||this.inst.count<=0)return;if(this.handles[e.instanceIndex]!==e){console.error("instance handle is not part of renderer, was it removed before?",e.instanceIndex,this.name);let n=this.handles.indexOf(e);if(n<0)return;e.instanceIndex=n}if(this.handles[e.instanceIndex]=null,this.inst.setMatrixAt(e.instanceIndex,ld.nullMatrix),!(e.instanceIndex>=this.currentCount-1)&&this.currentCount>0){let n=this.handles[this.currentCount-1];n&&(n.instanceIndex=e.instanceIndex,n.updateInstanceMatrix(),this.handles[e.instanceIndex]=n,this.handles[this.currentCount-1]=null)}this.inst.count>0&&(this.inst.count-=1),e.instanceIndex=-1,this.inst.count<=0&&(this.inst.visible=!1),this.inst.instanceMatrix.needsUpdate=!0}updateInstance(e,t){this.inst.setMatrixAt(t,e),this.inst.instanceMatrix.needsUpdate=!0}},Ua=ld;j(Ua,"nullMatrix",new Tn.Matrix4);import{Object3D as Mb,Vector3 as Db}from"three";var wr=class extends Ce{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},gt=class extends O{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:gt.calculateCenter(this.objects)},n=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?gt.saveArrayBuffer(n,e):gt.saveJson(n,e)}async export(e,t){if(e===null||e.length<=0){console.log("no objects set to export");return}this.exporter||(this.exporter=new Ib,this.exporter.register(a=>new fs(a)),this.ext=new uo,this.ext.registerExport(this.exporter)),gt.filterTopmostParent(e);let n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:gt.collectAnimations(e)},i=new Mb;t?.pivot&&i.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(a=>{a&&(i.children.push(a),a.matrixAutoUpdate=!1,a.matrix.copy(a.matrixWorld),R.getComponentsInChildren(a,$).forEach(c=>{R.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new Yr(i);return this.ext.context=r,new Promise((a,c)=>{try{this.exporter?.parse(i,d=>{s(),a(d)},d=>{s(),c(d)},n)}catch(d){console.error(d),c(d)}finally{console.log("FINALLY")}});function s(){e.forEach(a=>{!a||(a.matrixAutoUpdate=!0,R.getComponentsInChildren(a,$).forEach(c=>{R.isActiveInHierarchy(c.gameObject)&&c.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){let n=document.createElement("a");n.style.display="none",document.body.appendChild(n),typeof e=="string"?n.href=e:n.href=URL.createObjectURL(e),n.download=t,n.click(),n.remove()}static collectAnimations(e,t){t=t||[];for(let n of e)!n||n.traverseVisible(i=>{i.animations&&i.animations.length>0&&t.push(...i.animations)});return t}static calculateCenter(e,t){let n=t||new Db;return n.set(0,0,0),e.forEach(i=>{n.add(B(i))}),console.log(n),n.divideScalar(e.length),n}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let n=e[t];if(!n){e.splice(t,1),t--;continue}for(;n.parent;){if(e.includes(n.parent)){e.splice(t,1),t--;break}n=n.parent}}}};import{Color as Va,GridHelper as Ab}from"three";var Rn=class extends O{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!rn)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Ab(e,t,this.color0??new Va(.4,.4,.4),this.color1??new Va(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};C([x()],Rn.prototype,"isGizmo",2),C([x(Va)],Rn.prototype,"color0",2),C([x(Va)],Rn.prototype,"color1",2);import{GroundProjectedEnv as Lb}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Sn=class extends O{set scale(e){this._scale=e,this.env?.scale.setScalar(e)}get scale(){return this._scale}_scale=20;set radius(e){this._radius=e,this.env&&(this.env.height=e)}get radius(){return this._radius}_radius=100;set height(e){this._height=e,this.env&&(this.env.height=e)}get height(){return this._height}_height=100;_lastEnvironment;env;_watcher;onEnable(){this.context.time.frameCount>0&&this.updateAndCreate()}start(){this.updateAndCreate()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateAndCreate(){this.updateProjection(),this._watcher||(this._watcher=new Un(this.context.scene,"environment"),this._watcher.subscribeWrite(e=>{this.updateProjection()})),this._watcher.apply()}updateProjection(){if(!this.context.scene.environment){this.env?.removeFromParent();return}(!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new Lb(this.context.scene.environment)),this._lastEnvironment=this.context.scene.environment,this.env.parent||this.gameObject.add(this.env),this.env.scale.setScalar(this._scale),this.env.radius=this._radius,this.env.height=this._height,this.env.isObject3D===!0&&this.env.layers.set(2)}};C([x()],Sn.prototype,"scale",1),C([x()],Sn.prototype,"radius",1),C([x()],Sn.prototype,"height",1);import*as Ne from"three";import{Color as jb}from"three";function cd(o){return o*Math.PI/180}var lp=300,cp=I("debuglights");var De=class extends O{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new Ne.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){let t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e===1||e===2)}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){let n=this._webARRoot?.arScale;typeof n=="number"&&n>0&&(t/=n)}this.light.intensity=e*t}}get intensity(){return this._intensity}_intensity=1;get shadowDistance(){let e=this.light;return e?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;let t=this.light;if(t){let n=t.shadow.camera;n.far=e,n.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){let e=this.light;return e?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;let t=this.light;t&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}updateIntensity(){this.intensity=this._intensity}awake(){this.color=new Ne.Color(this.color??16777215)}onEnable(){this.createLight(),!this.isBaked&&(this.light&&(this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),2),this._webXRStartedListener=U.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=U.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){U.removeEventListener("xrStarted",this._webXRStartedListener),U.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=R.getComponentInParent(this.gameObject,ut)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInXR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){if(this.light)return;let e=this.selfIsLight;if(e)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else switch(this.type){case 1:let t=new Ne.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-lp*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Kr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),cp){let s=new Ne.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(s)}break;case 0:let n=new Ne.SpotLight(this.color,this.intensity*Math.PI,this.range,cd(this.spotAngle/2),1-cd(this.innerSpotAngle/2)/cd(this.spotAngle/2),2);n.position.set(0,0,0),n.rotation.set(0,0,0),this.light=n;let i=n.target;n.add(i),i.position.set(0,0,this.range),i.rotation.set(0,0,0);break;case 2:let r=new Ne.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light!==void 0){this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4;let t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=lp*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{let n=this.gameObject.scale.x;t.left*=n,t.right*=n}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{let n=this.gameObject.scale.y;t.top*=n,t.bottom*=n}this.light.shadow.needsUpdate=!0,cp&&this.context.scene.add(new Ne.CameraHelper(t)),this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}};C([x()],De.prototype,"type",2),C([x(jb)],De.prototype,"color",2),C([x()],De.prototype,"shadowNearPlane",1),C([x()],De.prototype,"shadowBias",1),C([x()],De.prototype,"shadowNormalBias",1),C([x()],De.prototype,"shadows",1),C([x()],De.prototype,"lightmapBakeType",2),C([x()],De.prototype,"intensity",1),C([x()],De.prototype,"shadowDistance",1),C([x()],De.prototype,"shadowResolution",1);var SI=new Ne.Vector3(0,0,0);import*as Na from"three";import{Vector3 as Hb}from"three";var To=I("debugLODs"),Fb=I("noLODs");var qt=class{screenRelativeTransitionHeight;distance;renderers};C([x()],qt.prototype,"screenRelativeTransitionHeight",2),C([x()],qt.prototype,"distance",2),C([x()],qt.prototype,"renderers",2);var dd=class{model;renderers;constructor(e,t){this.model=t,this.renderers=[];for(let n of t.renderers){let i=this.findRenderer(n,e.gameObject);i&&i.gameObject?this.renderers.push(i):To&&console.warn("Renderer not found: "+n,e.gameObject)}}findRenderer(e,t){let n=R.foreachComponent(t,i=>i.guid===e||Object.getPrototypeOf(i)?.guid===e?i:null);if(n)return n;for(let i of t.children){let r=this.findRenderer(e,i);if(r)return r}return null}},ai=class extends O{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!Fb&&!this._lodsHandler&&!!this.gameObject&&(To&&console.log(this),this.lodModels&&Array.isArray(this.lodModels))){let e=0,t=[];for(let i of this.lodModels){e=Math.max(i.distance,e);let r=new dd(this,i);this._lods.push(r);for(let s of r.renderers)t.includes(s)||t.push(s)}this._lodsHandler=new Array;for(let i=0;i<t.length;i++){let r=new Na.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let n=new Na.Object3D;To&&console.log(t);for(let i=0;i<t.length;i++){let r=t[i],s=this._lodsHandler[i],a=r.gameObject,c=0,d=0;To&&console.log(i,a.name);for(let u of this._lods){let h=null;u.renderers.includes(r)?h=a:h=n,To&&console.log("add",u.model.distance,h.name);let b=u.model.distance;d=b-c,c=Math.max(b,c),this.onAddLodLevel(s,h,b)}let l=c+d;To&&console.log("cull",l),this.onAddLodLevel(s,n,l)}}}update(){if(!this.gameObject||!this._lodsHandler)return;let e=this.context.mainCamera;if(!!e)for(let t of this._lodsHandler)t.update(e)}onAddLodLevel(e,t,n){e.addLevel(t,n*this._distanceFactor);let i={lod:e,levelIndex:e.levels.length-1,distance:n};this._settings.push(i)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(let t of this._settings){let n=t.lod.levels[t.levelIndex];n.distance=t.distance*e}}}};C([x(Hb)],ai.prototype,"localReferencePoint",2),C([x(qt)],ai.prototype,"lodModels",2);var ud=I("debugnestedgltf"),Ui=class extends O{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;ud&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new Ie;t.idProvider=new ke(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let n=this.gameObject.matrix;ud&&console.log("Load nested:",this.filePath?.uri??this.filePath,this.gameObject.position);let i=await this.filePath?.instantiate?.call(this.filePath,t);i&&(i.matrixAutoUpdate=!1,i.matrix.identity(),i.applyMatrix4(n),i.matrixAutoUpdate=!0,i.layers.disableAll(),i.layers.set(this.layer)),this.destroy(),ud&&console.log("Nested loading done:",this.filePath?.uri??this.filePath,i)}}hash(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return t}};C([x(je)],Ui.prototype,"filePath",2);import{Quaternion as Bb,Euler as Ub,Vector3 as xr,Plane as Gb}from"three";var Yt=class extends O{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new xr(0,0,0);rotationOffset=new xr(0,0,0);offset=new xr(0,0,0);update(){if(!this.from)return;var e=B(this.from),t=me(this.from);this.offset.copy(this.positionOffset);let n=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(n),e.add(this.offset),this.levelPosition&&this.referenceSpace){let a=new Gb(this.gameObject.up,0),c=B(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,c);let d=new xr(0,0,0);a.projectPoint(e,d),e.copy(d)}this.affectPosition&&J(this.gameObject,e);let i=new Ub(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new Bb().setFromEuler(i);this.affectRotation&&Be(this.gameObject,t.multiply(r));let s=new xr;this.from.getWorldDirection(s).multiplyScalar(50),this.levelLookDirection&&(s.y=0),this.alignLookDirection&&this.gameObject.lookAt(s)}};C([x(R)],Yt.prototype,"referenceSpace",2),C([x(R)],Yt.prototype,"from",2),C([x(xr)],Yt.prototype,"positionOffset",2),C([x(xr)],Yt.prototype,"rotationOffset",2);import*as pe from"three";import*as Kt from"three";var Cr=class{randomizeRotationDirection=0;duration=5;loop=!0;prewarm=!1;startDelay=void 0;startDelayMultiplier=0;startLifetime=void 0;startLifetimeMultiplier=5;startSpeed=void 0;startSpeedMultiplier=5;startSize3D=!1;startSize=void 0;startSizeMultiplier=1;startSizeX=void 0;startSizeXMultiplier=1;startSizeY=void 0;startSizeYMultiplier=1;startSizeZ=void 0;startSizeZMultiplier=1;startRotation3D=!1;startRotation=void 0;startRotationMultiplier=0;startRotationX=void 0;startRotationXMultiplier=0;startRotationY=void 0;startRotationYMultiplier=0;startRotationZ=void 0;startRotationZMultiplier=0;flipRotation=0;startColor=new Kt.Color(1,1,1);startColor1=new Kt.Color(0,0,0);gravityModifier=void 0;gravityModifierMultiplier=0;simulationSpace=0;customSimulationSpace=null;simulationSpeed=1;useUnscaledTime=!1;scalingMode=1;playOnAwake=!0;maxParticles=1e3;emitterVelocityMode=1;stopAction=0;ringBufferMode=0;ringBufferLoopRange=new Kt.Vector2(0,1);cullingMode=0},Tr=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},Rr=class{shapeType=hd.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new Kt.Vector3(1,1,1);boxThickness=new Kt.Vector3(0,0,0);position=new Kt.Vector3(0,0,0);rotation=new Kt.Vector3(0,0,0);scale=new Kt.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},hd=(f=>(f[f.Sphere=0]="Sphere",f[f.SphereShell=1]="SphereShell",f[f.Hemisphere=2]="Hemisphere",f[f.HemisphereShell=3]="HemisphereShell",f[f.Cone=4]="Cone",f[f.Box=5]="Box",f[f.Mesh=6]="Mesh",f[f.ConeVolume=7]="ConeVolume",f[f.Circle=10]="Circle",f[f.SingleSidedEdge=11]="SingleSidedEdge",f[f.MeshRenderer=12]="MeshRenderer",f[f.SkinnedMeshRenderer=13]="SkinnedMeshRenderer",f[f.BoxShell=14]="BoxShell",f[f.BoxEdge=15]="BoxEdge",f[f.Donut=16]="Donut",f[f.Rectangle=17]="Rectangle",f[f.Sprite=18]="Sprite",f[f.SpriteRenderer=19]="SpriteRenderer",f))(hd||{});var Nb=I("debugparticles"),pd=class{age=0;lifetime=0;position;velocity;color},Gi=class extends O{get mainTexture(){if(this.sharedMaterial){let e=this.context.assets.findTexture(this.sharedMaterial);if(e)return e}return null}getMesh(e){return this.mesh?this.context.assets.findMesh(this.mesh):null}sharedMaterial;mesh;awake(){Nb&&console.log(this)}},Sr=class extends O{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new pe.Quaternion;tempVec3=new pe.Vector3;tempQuat=new pe.Quaternion;awake(){this.renderer=R.getComponent(this.gameObject,Gi),console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new pe.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new pe.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new pe.Float32BufferAttribute(this.positionsArray,3),this.geometry.setAttribute("position",this.positions);let e=new Float32Array(this.main.maxParticles*3);for(let n=0;n<e.length;n++)e[n*3]=1,e[n*3+1]=1,e[n*3+2]=1;let t=new pe.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new pe.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new pe.Points(this.geometry,this.material),this.particlesMesh.layers.enable(2),this.gameObject.add(this.particlesMesh),this.activeCount=this.main.prewarm?this.main.maxParticles:0}emit(e){let t=this.activeCount;for(let n=0;n<t;n+=1){if(n>=this.particleStates.length){let r=new pd;r.lifetime=this.main.startLifetime??1,r.position=new pe.Vector3,r.velocity=new pe.Vector3,r.color=new pe.Color(1,0,0),this.particleStates.push(r),this.initializeParticle(n,r),r.age=r.lifetime*Math.random()}let i=this.particleStates[n];if(i.age>i.lifetime){this.activeCount-=1,this.activeCount=Math.max(0,this.activeCount),this.initializeParticle(n,i);continue}i.age+=e,this.particleStates[n]=i}this.activeCount+=e*this.emission.rate,this.activeCount=Math.min(this.main.maxParticles,this.activeCount)}initializeParticle(e,t){if(!this.geometry)return;t.age=0,t.color.set(this.main.startColor),this.main.startColor1&&t.color.lerp(this.main.startColor1,Math.random()),this.geometry.attributes.color.needsUpdate=!0,this.assignPosition(t.position),this.assignVelocity(t.position,t.velocity);let n=t.position;n.multiply(this.shape.scale),n.applyQuaternion(this.shapeRotation),n.add(this.shape.position),this.particleStates.splice(e,1),this.particleStates.push(t)}updateOverLifetime(e,t){}assignPosition(e){switch(this.shape.shapeType){case 0:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).multiplyScalar(this.shape.radius);break;case 5:e.set(Math.random()-.5,Math.random()-.5,Math.random()-.5);break;default:e.set(0,0,0);break}}assignVelocity(e,t){switch(this.shape.shapeType){case 0:t.set(e.x,e.y,e.z);break;case 5:t.set(0,0,1),this.shape.sphericalDirectionAmount>0&&(this.tempVec3.set(e.x,e.y,e.z).multiply(this.shape.scale).normalize(),t.lerp(this.tempVec3,this.shape.sphericalDirectionAmount));break;case 4:let n=new pe.Vector3(0,1,0);t.copy(n);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*W.toRadians(this.shape.arc)),t.copy(this.tempVec3.set(1,0,0).applyQuaternion(this.tempQuat));break;default:t.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1);break}switch(t.normalize(),this.shape.shapeType){case 10:e.add(t).multiplyScalar(this.shape.radius);break}t.multiplyScalar(this.main.startSpeedMultiplier)}};import*as up from"three";function*dp(o,e=null){let t=e?e.time:V.Current.time,n=t.time;for(;t.time-n<o;)yield}var We=class extends O{awake(){this.context.connection.beginListen("joined-room",this.tryAssignColor.bind(this))}_didAssignPlayerColor=!1;onEnable(){this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}*waitForConnection(){for(;!this.destroyed&&this.enabled&&(yield dp(.2),!this.tryAssignColor()););}tryAssignColor(){let e=R.getComponentInParent(this.gameObject,re);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=We.hashCode(e),n=We.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){let i=this.gameObject;this.assignColor(n,e,i)}else if(this.gameObject.children)for(let i of this.gameObject.children){let r=i;r.material&&r.material.color&&this.assignColor(n,e,r)}}assignColor(e,t,n){let i=n.material;!i||(i._playerMaterial!==t&&(i=i.clone(),i._playerMaterial=t,n.material=i),i.color=e)}static hashCode(e){var t=0,n,i;if(e.length===0)return t;for(n=0;n<e.length;n++)i=e.charCodeAt(n),t=(t<<5)-t+i,t|=0;return t}static colorFromHashCode(e){let t=(e&16711680)>>16,n=(e&65280)>>8,i=e&255;return new up.Color(t/255,n/255,i/255)}};import*as za from"three";import{Object3D as qb,ShaderMaterial as Yb,Texture as Kb,Vector2 as md,Vector4 as Jb}from"three";function Wb(){return new Promise((o,e)=>{let n=()=>{n!=null&&(document.removeEventListener("pointerdown",n),document.removeEventListener("click",n),document.removeEventListener("dragstart",n),document.removeEventListener("touchstart",n),o())};document.addEventListener("pointerdown",n),document.addEventListener("click",n),document.addEventListener("dragstart",n),document.addEventListener("touchstart",n)})}async function hp(o){await Wb(),o()}import{PlaneGeometry as zb,MeshBasicMaterial as Xb,Mesh as Qb}from"three";var Wa=class{static createPrimitive(e,t){let n;switch(e){case 0:let i=new zb(1,1,1,1),r=t?.material??new Xb({color:16777215});n=new Qb(i,r)}return t?.name&&(n.name=t.name),n}};var fd=I("debugvideo");var pp=(i=>(i[i.CameraFarPlane=0]="CameraFarPlane",i[i.CameraNearPlane=1]="CameraNearPlane",i[i.RenderTexture=2]="RenderTexture",i[i.MaterialOverride=3]="MaterialOverride",i))(pp||{}),fe=class extends O{renderer=null;playOnAwake=!0;playOnEnable;aspectMode=0;renderMode;targetMaterialProperty;targetMaterialRenderer;targetTexture;time=0;_playbackSpeed=1;get playbackSpeed(){return this.videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this.videoElement&&(this.videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this.videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this.videoElement&&(this.videoElement.loop=e)}get currentTime(){return this.videoElement?.currentTime??this.time}set currentTime(e){this.videoElement?this.videoElement.currentTime=e:this.time=e}get isPlaying(){let e=this.videoElement;return e?e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA:!1}get crossOrigin(){return this.videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this.videoElement&&(e!==null?this.videoElement.setAttribute("crossorigin",e):this.videoElement.removeAttribute("crossorigin"))}get videoTexture(){return this._videoTexture}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;_videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setVideo(e){this.clip=e,this.source=0,this.videoElement?(this.videoElement.srcObject=e,this._isPlaying&&this.videoElement.play(),this.updateAspect()):this.create(!0)}setClipURL(e){this.url!==e&&(this.url=e,this.source=1,fd&&console.log("set url",e),this.videoElement?(this.videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(!0))}awake(){this.create(this.playOnAwake),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this._isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}})}onEnable(){this.playOnEnable===!0&&this.handleBeginPlaying(!0),this.screenspace?this._overlay?.start():this._overlay?.stop()}onDisable(){this.pause()}onDestroy(){this.videoElement&&(this.videoElement.parentElement?.removeChild(this.videoElement),this.videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}_receivedInput=!1;constructor(){super(),hp(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],I("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}play(){!this.videoElement||this._isPlaying&&!this.videoElement?.ended&&!this.videoElement?.paused||(this._isPlaying=!0,this._receivedInput||(this.videoElement.muted=!0),this.updateVideoElementSettings(),this.videoElement?.play().catch(e=>{console.warn(e)}),fd&&console.log("play",this.videoElement))}stop(){this._isPlaying=!1,this.videoElement&&(this.videoElement.currentTime=0,this.videoElement.pause())}pause(){this._isPlaying=!1,this.videoElement?.pause()}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url;break}if(!!t){if(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"){this.videoElement.src=t;let n=this.videoElement.captureStream?.call(this.videoElement);this.clip=n}else this.videoElement.srcObject=t;this._videoTexture||(this._videoTexture=new za.VideoTexture(this.videoElement)),this._videoTexture.flipY=!1,this._videoTexture.encoding=za.sRGBEncoding,this.handleBeginPlaying(e),console.log(this)}}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new gd(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),fd&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=R.getComponent(this.gameObject,$)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,pp[this.renderMode],this);return}let n=t.material;if(n)if(this._targetObjects.push(t),n!==this.videoMaterial&&(this.videoMaterial=n.clone(),t.material=this.videoMaterial),!this.targetMaterialProperty)this.videoMaterial.map=this._videoTexture;else switch(this.targetMaterialProperty){default:this.videoMaterial.map=this._videoTexture;break}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&this.play()}updateVideoElementSettings(){!this.videoElement||(this.videoElement.loop=this._isLooping,this.videoElement.currentTime=this.currentTime,this.videoElement.playbackRate=this._playbackSpeed,this.videoElement.playsInline=!0,this.videoElement.muted=!this._receivedInput&&this.audioOutputMode!==0,(this.playOnAwake||this.playOnEnable)&&(this.videoElement.autoplay=!0))}updateVideoElementStyles(){!this.videoElement||(this.videoElement.style.userSelect="none",this.videoElement.style.visibility="hidden",this.videoElement.style.display="none",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){let e=++this._updateAspectRoutineId,t=void 0,n=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&n===this.clip&&this._isPlaying;){if(!n||typeof n=="string")return;let i;for(let r of n.getVideoTracks()){let s=r.getSettings();if(s&&s.width&&s.height){i=s.width/s.height;break}else i=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(i===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(t===i){yield;continue}for(let r of this._targetObjects){let s=1;if(r.parent){let a=on(r.parent);s=a.x/a.y}switch(this.aspectMode){case 1:r.scale.y=1/i*r.scale.x*s;break;case 2:r.scale.x=i*r.scale.y*s;break}}for(let r=0;r<3;r++)yield}}};C([x(qb)],fe.prototype,"renderer",2),C([x()],fe.prototype,"playOnAwake",2),C([x()],fe.prototype,"playOnEnable",2),C([x()],fe.prototype,"aspectMode",2),C([x()],fe.prototype,"renderMode",2),C([x()],fe.prototype,"targetMaterialProperty",2),C([x($)],fe.prototype,"targetMaterialRenderer",2),C([x(Kb)],fe.prototype,"targetTexture",2),C([x()],fe.prototype,"time",2),C([x()],fe.prototype,"playbackSpeed",1),C([x()],fe.prototype,"isLooping",1);var gd=class{context;constructor(e){this.context=e,this._input=new bd(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;let t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;let e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=Wa.createPrimitive(0,{material:new vd(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}let t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();let n=t.material;n?.reset(),this._input?.enable(n)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){let e=this._screenspaceModeQuad?.material;!e||(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input},bd=class{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=i=>{i.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=i=>{this.overlay.enabled&&(e.zoom+=i.deltaY*5e-4,i.preventDefault())},{passive:!1});let t=new md;window.addEventListener("mousemove",i=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){let r=new md(i.movementX,i.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",i=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(i.movementX,i.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let n=0;window.addEventListener("touchstart",i=>{if(i.touches.length<2){this.context.time.time-n<.3&&this.overlay.stop(),n=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",i=>{if(!this._isPinching||!this._material)return;let r=i.touches[0],s=i.touches[1],a=r.clientX-s.clientX,c=r.clientY-s.clientY,d=Math.sqrt(a*a+c*c);if(this._lastPinch!==0){let l=d-this._lastPinch;this._material.zoom-=l*.004}this._lastPinch=d}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}},vd=class extends Yb{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){let t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new md;get offset(){let e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){let t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new Jb(0,0,1,1)}},this.vertexShader=`
209
209
  uniform sampler2D map;
210
210
  uniform float screenAspect;
211
211
  uniform vec4 offsetScale;
@@ -255,7 +255,7 @@ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
255
255
  else
256
256
  gl_FragColor = texture2D(map, vUv);
257
257
  }
258
- `}};var Tm=ca(el(),1);import{EventDispatcher as jh}from"three";var Rm=D("debugscreenshare");function Vl(a){if(!!a)for(let e of a.getTracks())e.stop()}var Rn=class extends M{onPointerClick(){if(this.isReceiving){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}videoPlayer;device=0;get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){return this._currentStream?.active&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;let e=this._currentStream.getTracks();for(let t of e)if(t.readyState==="live")return!0}return!1}_net;_requestOpen=!1;_currentStream=null;_currentMode=0;awake(){Rm&&console.log(this),ae.registerWaitForAllowAudio(()=>{this.videoPlayer&&this._currentStream&&this._currentMode===2&&this.videoPlayer.setVideo(this._currentStream)})}start(){if(this.videoPlayer||(this.videoPlayer=k.getComponent(this.gameObject,Ce)??void 0),!this.videoPlayer){console.error("Screencapture did not find a VideoPlayer component");return}let e=Wl.getOrCreate(this.context,this.guid);this._net=new Dh(this.context,e),this._net.enable(),this._net.addEventListener(Sm.ReceiveVideo,this.onReceiveVideo.bind(this))}async share(e){e?.device&&(this.device=e.device),this._requestOpen=!0;try{if(this.videoPlayer){let t=e?.constraints??{echoCancellation:!0,autoGainControl:!1},i={video:t,audio:t};switch(this.device){case 1:this.tryShareUserCamera(i,e);break;case 0:if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}let n=await navigator.mediaDevices.getDisplayMedia(i);this._requestOpen?this.setVideo(n,1):Vl(n);break;case 2:let r=0,o=this.context.renderer.domElement.captureStream(r);this.setVideo(o,1);break}}}catch(t){if(t.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",t)}}close(){this._requestOpen=!1,this._currentStream&&(console.warn("Close current stream / disposing resources"),this._net?.stopSendingVideo(this._currentStream),Vl(this._currentStream),this._currentMode=0,this._currentStream=null)}setVideo(e,t){if(e===this._currentStream||(this.close(),!e||!this.videoPlayer))return;this._currentStream=e,this._requestOpen=!0,this._currentMode=t,this.videoPlayer.setVideo(e),t===1&&this._net?.startSendingVideo(e),e.addEventListener("ended",()=>{this.close()})}onReceiveVideo(e){this.setVideo(e.stream,2)}async tryShareUserCamera(e,t){let i=(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="videoinput");console.log("Request camera",i);for(let n of i)try{if(!this._requestOpen)break;if(n.kind!=="videoinput")continue;let r=n.deviceId;if(t?.deviceId!==void 0&&r!==t.deviceId)continue;e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=r);let o=await navigator.mediaDevices.getUserMedia(e);this._requestOpen?this.setVideo(o,1):Vl(o),console.log("Selected camera",n);break}catch(r){console.warn(r)}}};P([S(Ce)],Rn.prototype,"videoPlayer",2),P([S()],Rn.prototype,"device",2);var Sm=(i=>(i.Connected="peer-user-connected",i.ReceiveVideo="receive-video",i.Disconnected="peer-user-disconnected",i))(Sm||{}),Ah=class{type="receive-video";stream;target;constructor(e,t){this.stream=e,this.target=t}},Mh=class{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}};var Lh=class extends jh{userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Vl(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState==="connected"}get isClosed(){return!this.isOpen}constructor(e,t,i){super(),this.userId=e,this.call=t,this.direction=i,this._stream=null,t.on("stream",n=>{if(console.log("Receive video",n.getAudioTracks(),n.getVideoTracks()),this._stream=n,i==="incoming"){let r=new Ah(n,this);this.dispatchEvent(r)}})}},as=class extends jh{static getOrCreate(e,t){if(as.instances.has(t))return as.instances.get(t);let i=new as(e,t);return as.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){let i={metadata:{userId:this.context.connection.connectionId}},n=this._peer?.call(e,t,i);if(n)return this.registerCall(n,"outgoing")}get peer(){return this._peer}id;context;_peer;_incomingCalls=[];_outgoingCalls=[];constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);onUserJoinedOrLeftRoomFn=this.onUserJoinedOrLeftRoom.bind(this);onPeerConnectFn=this.onPeerConnect.bind(this);onPeerReceiveCallFn=this.onPeerReceivingCall.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen("joined-room",this.onConnectRoomFn),this.context.connection.beginListen("user-joined-room",this.onUserJoinedOrLeftRoomFn),this.context.connection.beginListen("user-left-room",this.onUserJoinedOrLeftRoomFn),this.subscribePeerEvents())}disable(){!this._enabled||(this._enabled=!1,this.context.connection.stopListening("joined-room",this.onConnectRoomFn),this.context.connection.stopListening("user-joined-room",this.onUserJoinedOrLeftRoomFn),this.context.connection.stopListening("user-left-room",this.onUserJoinedOrLeftRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}onUserJoinedOrLeftRoom(e){}setupPeer(){if(!!this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){let e=this.getMyPeerId();this._peer=new Tm.default(e)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){!this._peer||(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){}onPeerConnect(e){Rm&&console.log("Peer connected as",e),this.context.connection.send("peer-user-connected",new Mh(this,e))}onPeerReceivingCall(e){e.answer(),this.registerCall(e,"incoming")}registerCall(e,t){let i=e.metadata;(!i||!i.userId)&&console.error("Missing call metadata",e);let n=i.userId;console.log(t==="incoming"?"Receive call from":"Make call to",e.metadata);let r=t==="incoming"?this._incomingCalls:this._outgoingCalls,o=new Lh(n,e,t);return r.push(o),e.on("error",s=>{console.error("Call error",s)}),e.on("close",()=>{console.log("Call ended",e.metadata),e.close();let s=r.indexOf(o);s!==-1&&r.splice(s,1)}),t==="incoming"&&(o.addEventListener("receive-video",s=>{this.dispatchEvent(s)}),e.on("stream",()=>{let s=setInterval(()=>{o.isOpen||(clearInterval(s),o.close())},2e3)})),o}},Wl=as;U(Wl,"instances",new Map);var Dh=class extends jh{context;peer;_sendingVideoStreams=new Map;constructor(e,t){super(),this.context=e,this.peer=t}startSendingVideo(e){this._sendingVideoStreams.has(e)||(this._sendingVideoStreams.set(e,[]),this.updateSendingCalls())}stopSendingVideo(e){if(e){let t=this._sendingVideoStreams.get(e);if(t){console.log("Closing calls",t);for(let i of t)i.close()}this._sendingVideoStreams.delete(e),t&&console.log("Currently sending",this._sendingVideoStreams)}}onConnectRoomFn=this.onConnectRoom.bind(this);onUserConnectedFn=this.onUserConnected.bind(this);onUserLeftFn=this.onUserLeft.bind(this);enable(){this.peer.enable(),this.context.connection.beginListen("peer-user-connected",this.onUserConnectedFn),this.peer.addEventListener("receive-video",this.onReceiveVideo.bind(this))}disable(){this.peer.disable()}onReceiveVideo(e){console.log("RECEIVE VIDEO",e),this.dispatchEvent({type:"receive-video",target:this,stream:e.stream,userId:e.userId})}onConnectRoom(){}onUserConnected(e){if(this.peer.id===e.guid){console.log("USER CONNECTED",e);let t=this._sendingVideoStreams.keys().next().value;this.peer.makeCall(e.peerId,t)}}onUserLeft(e){this.stopCallsToUsersThatAreNotInTheRoomAnymore()}updateSendingCalls(){let e=!1;for(let t of this._sendingVideoStreams.keys()){let i=this._sendingVideoStreams.get(t)||[];for(let n of this.context.connection.usersInRoom()){if(n===this.context.connection.connectionId)continue;if(!i.find(o=>o.userId===n)){let o=this.peer.makeCall(this.peer.getPeerIdFromUserId(n),t);o&&(e=!0,i.push(o))}}this._sendingVideoStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),e&&console.log("Currently sending",this._sendingVideoStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(let e of this._sendingVideoStreams.keys()){let t=this._sendingVideoStreams.get(e);if(!!t)for(let i=t.length-1;i>=0;i--){let n=t[i];this.context.connection.userIsInRoom(n.userId)||(n.close(),t.splice(i,1))}}}};import{ShadowMaterial as T_,AdditiveBlending as R_}from"three";var Sn=class extends M{mode=0;shadowColor=new ye(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=k.getComponent(this.gameObject,le);if(e){let t=e.material;t.blending=R_,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
258
+ `}};var fp=Cs(ta(),1);import{EventDispatcher as xd}from"three";var mp=I("debugscreenshare");function Xa(o){if(!!o)for(let e of o.getTracks())e.stop()}var li=class extends O{onPointerClick(){if(this.isReceiving){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}videoPlayer;device=0;get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){return this._currentStream?.active&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;let e=this._currentStream.getTracks();for(let t of e)if(t.readyState==="live")return!0}return!1}_net;_requestOpen=!1;_currentStream=null;_currentMode=0;awake(){mp&&console.log(this),Z.registerWaitForAllowAudio(()=>{this.videoPlayer&&this._currentStream&&this._currentMode===2&&this.videoPlayer.setVideo(this._currentStream)})}start(){if(this.videoPlayer||(this.videoPlayer=R.getComponent(this.gameObject,fe)??void 0),!this.videoPlayer){console.error("Screencapture did not find a VideoPlayer component");return}let e=Qa.getOrCreate(this.context,this.guid);this._net=new wd(this.context,e),this._net.enable(),this._net.addEventListener(gp.ReceiveVideo,this.onReceiveVideo.bind(this))}async share(e){e?.device&&(this.device=e.device),this._requestOpen=!0;try{if(this.videoPlayer){let t=e?.constraints??{echoCancellation:!0,autoGainControl:!1},n={video:t,audio:t};switch(this.device){case 1:this.tryShareUserCamera(n,e);break;case 0:if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}let i=await navigator.mediaDevices.getDisplayMedia(n);this._requestOpen?this.setVideo(i,1):Xa(i);break;case 2:let r=0,s=this.context.renderer.domElement.captureStream(r);this.setVideo(s,1);break}}}catch(t){if(t.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",t)}}close(){this._requestOpen=!1,this._currentStream&&(console.warn("Close current stream / disposing resources"),this._net?.stopSendingVideo(this._currentStream),Xa(this._currentStream),this._currentMode=0,this._currentStream=null)}setVideo(e,t){if(e===this._currentStream||(this.close(),!e||!this.videoPlayer))return;this._currentStream=e,this._requestOpen=!0,this._currentMode=t,this.videoPlayer.setVideo(e),t===1&&this._net?.startSendingVideo(e),e.addEventListener("ended",()=>{this.close()})}onReceiveVideo(e){this.setVideo(e.stream,2)}async tryShareUserCamera(e,t){let n=(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind==="videoinput");console.log("Request camera",n);for(let i of n)try{if(!this._requestOpen)break;if(i.kind!=="videoinput")continue;let r=i.deviceId;if(t?.deviceId!==void 0&&r!==t.deviceId)continue;e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=r);let s=await navigator.mediaDevices.getUserMedia(e);this._requestOpen?this.setVideo(s,1):Xa(s),console.log("Selected camera",i);break}catch(r){console.warn(r)}}};C([x(fe)],li.prototype,"videoPlayer",2),C([x()],li.prototype,"device",2);var gp=(n=>(n.Connected="peer-user-connected",n.ReceiveVideo="receive-video",n.Disconnected="peer-user-disconnected",n))(gp||{}),yd=class{type="receive-video";stream;target;constructor(e,t){this.stream=e,this.target=t}},_d=class{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}};var Ed=class extends xd{userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Xa(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState==="connected"}get isClosed(){return!this.isOpen}constructor(e,t,n){super(),this.userId=e,this.call=t,this.direction=n,this._stream=null,t.on("stream",i=>{if(console.log("Receive video",i.getAudioTracks(),i.getVideoTracks()),this._stream=i,n==="incoming"){let r=new yd(i,this);this.dispatchEvent(r)}})}},Ro=class extends xd{static getOrCreate(e,t){if(Ro.instances.has(t))return Ro.instances.get(t);let n=new Ro(e,t);return Ro.instances.set(t,n),n}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){let n={metadata:{userId:this.context.connection.connectionId}},i=this._peer?.call(e,t,n);if(i)return this.registerCall(i,"outgoing")}get peer(){return this._peer}id;context;_peer;_incomingCalls=[];_outgoingCalls=[];constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer(),navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);onUserJoinedOrLeftRoomFn=this.onUserJoinedOrLeftRoom.bind(this);onPeerConnectFn=this.onPeerConnect.bind(this);onPeerReceiveCallFn=this.onPeerReceivingCall.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen("joined-room",this.onConnectRoomFn),this.context.connection.beginListen("user-joined-room",this.onUserJoinedOrLeftRoomFn),this.context.connection.beginListen("user-left-room",this.onUserJoinedOrLeftRoomFn),this.subscribePeerEvents())}disable(){!this._enabled||(this._enabled=!1,this.context.connection.stopListening("joined-room",this.onConnectRoomFn),this.context.connection.stopListening("user-joined-room",this.onUserJoinedOrLeftRoomFn),this.context.connection.stopListening("user-left-room",this.onUserJoinedOrLeftRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}onUserJoinedOrLeftRoom(e){}setupPeer(){if(!!this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){let e=this.getMyPeerId();this._peer=new fp.default(e)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){!this._peer||(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){}onPeerConnect(e){mp&&console.log("Peer connected as",e),this.context.connection.send("peer-user-connected",new _d(this,e))}onPeerReceivingCall(e){e.answer(),this.registerCall(e,"incoming")}registerCall(e,t){let n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);let i=n.userId;console.log(t==="incoming"?"Receive call from":"Make call to",e.metadata);let r=t==="incoming"?this._incomingCalls:this._outgoingCalls,s=new Ed(i,e,t);return r.push(s),e.on("error",a=>{console.error("Call error",a)}),e.on("close",()=>{console.log("Call ended",e.metadata),e.close();let a=r.indexOf(s);a!==-1&&r.splice(a,1)}),t==="incoming"&&(s.addEventListener("receive-video",a=>{this.dispatchEvent(a)}),e.on("stream",()=>{let a=setInterval(()=>{s.isOpen||(clearInterval(a),s.close())},2e3)})),s}},Qa=Ro;j(Qa,"instances",new Map);var wd=class extends xd{context;peer;_sendingVideoStreams=new Map;constructor(e,t){super(),this.context=e,this.peer=t}startSendingVideo(e){this._sendingVideoStreams.has(e)||(this._sendingVideoStreams.set(e,[]),this.updateSendingCalls())}stopSendingVideo(e){if(e){let t=this._sendingVideoStreams.get(e);if(t){console.log("Closing calls",t);for(let n of t)n.close()}this._sendingVideoStreams.delete(e),t&&console.log("Currently sending",this._sendingVideoStreams)}}onConnectRoomFn=this.onConnectRoom.bind(this);onUserConnectedFn=this.onUserConnected.bind(this);onUserLeftFn=this.onUserLeft.bind(this);enable(){this.peer.enable(),this.context.connection.beginListen("peer-user-connected",this.onUserConnectedFn),this.peer.addEventListener("receive-video",this.onReceiveVideo.bind(this))}disable(){this.peer.disable()}onReceiveVideo(e){console.log("RECEIVE VIDEO",e),this.dispatchEvent({type:"receive-video",target:this,stream:e.stream,userId:e.userId})}onConnectRoom(){}onUserConnected(e){if(this.peer.id===e.guid){console.log("USER CONNECTED",e);let t=this._sendingVideoStreams.keys().next().value;this.peer.makeCall(e.peerId,t)}}onUserLeft(e){this.stopCallsToUsersThatAreNotInTheRoomAnymore()}updateSendingCalls(){let e=!1;for(let t of this._sendingVideoStreams.keys()){let n=this._sendingVideoStreams.get(t)||[];for(let i of this.context.connection.usersInRoom()){if(i===this.context.connection.connectionId)continue;if(!n.find(s=>s.userId===i)){let s=this.peer.makeCall(this.peer.getPeerIdFromUserId(i),t);s&&(e=!0,n.push(s))}}this._sendingVideoStreams.set(t,n)}this.stopCallsToUsersThatAreNotInTheRoomAnymore(),e&&console.log("Currently sending",this._sendingVideoStreams)}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(let e of this._sendingVideoStreams.keys()){let t=this._sendingVideoStreams.get(e);if(!!t)for(let n=t.length-1;n>=0;n--){let i=t[n];this.context.connection.userIsInRoom(i.userId)||(i.close(),t.splice(n,1))}}}};import{ShadowMaterial as Zb,AdditiveBlending as $b}from"three";var ci=class extends O{mode=0;shadowColor=new ce(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=R.getComponent(this.gameObject,$);if(e){let t=e.material;t.blending=$b,this.applyMaterialOptions(t),t.onBeforeCompile=n=>{n.fragmentShader=n.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
259
259
 
260
260
  // diffuse-only lighting with overdrive to somewhat compensate
261
261
  // for the loss of indirect lighting and to make it more visible.
@@ -266,13 +266,13 @@ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
266
266
  // be blended onto the scene.
267
267
  gl_FragColor = vec4(direct, max);
268
268
  return;
269
- `)}}}applyShadowMaterial(){let e=k.getComponent(this.gameObject,le);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new T_;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t),e.material=t}else{let t=e.material;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t)}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}};P([S()],Sn.prototype,"mode",2),P([S(ye)],Sn.prototype,"shadowColor",2);import{RGBELoader as O_}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as I_}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as k_}from"three";var Pm=D("debugautosync"),Bh=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new Hh(e);return this._syncers[e.guid]=t,t}},Om=new Bh,Hh=class{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};data={};_boundEvent;get networkingKey(){return this.comp.constructor.name}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving.bind(this));let t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}notifyChanged(e,t){this._isReceiving||(this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;let e=this.comp.context.connection;if(!e||!e.isConnected){for(let t in this.changedProperties)delete this.changedProperties[t];return}for(let t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(let t in this.changedProperties){let i=this.changedProperties[t];delete this.changedProperties[t],this.data[t]=i}e.send(this.networkingKey,this.data)}onHandleReceiving(e){if(!this._isInit||!this.comp)return;let t=e.guid;if(!(t&&t!==this.comp.guid)){Pm&&console.log("RECEIVED",this.comp.name,this.comp.guid,e);try{this._isReceiving=!0;for(let i in e){if(i==="guid")continue;let n=e[i];this.comp[i]=n}}catch(i){console.error(i)}finally{this._isReceiving=!1}}}};function S_(a,e){let t=e!==a;if(!t&&a&&e){if(Array.isArray(a)&&Array.isArray(e))t=!0;else if(typeof a=="object"&&typeof e=="object"){for(let i of Object.keys(a))if(a[i]!==e[i]){t=!0;break}}}return t}function P_(a){if(a.__autoPropertySyncHandler)return a.__autoPropertySyncHandler;let e=Om.getOrCreateSyncer(a);return e?.init(a),a.__autoPropertySyncHandler=e,e}var ql=function(a){return function(e,t){let i=null,n=a?e[a]:void 0,r=e,o=r.__internalAwake;Pm&&console.log(t);let s=t+"k__BackingField";r.__internalAwake=function(){if(this[s]!==void 0)return;this[s]=this[t],o.call(this),i=Om.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let l=this[s];this[s]=d,S_(d,l)&&n?.call(this,d,l)!==!1&&P_(this)?.notifyChanged(t,d)},get:function(){return this[s]},configurable:!0,enumerable:!0}),i?.init(this)}}};var Pn=class extends M{url;allowDrop=!0;_loader;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.isInXR||(this.context.scene.environment=this._prevEnvironment,this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents()}async setSkybox(e){if(!e)return;if(!e?.endsWith(".hdr")&&!e.endsWith(".exr")&&console.warn("Potentially invalid skybox url",this.url,"on",this.name),!this._loader){let n=e.endsWith(".exr");this._loader=n?new I_:new O_}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=k_,this._prevBackground=this.context.scene.background,this._prevEnvironment=this.context.scene.environment,console.log("Set skybox",this.url),this.context.scene.environment=t,this.context.scene.background=t,this._prevLoadedEnvironment=t;let i=e.lastIndexOf("/");t.name=e.substring(i>=0?i+1:0)}dragOverEvent;dropEvent;registerDropEvents(){this.dragOverEvent||(this.dragOverEvent=e=>{if(!!this.allowDrop&&!!e.dataTransfer)for(let t of e.dataTransfer.types)t==="text/uri-list"&&e.preventDefault()},this.dropEvent=e=>{if(!!this.allowDrop&&(e.preventDefault(),!!e.dataTransfer)){for(let t of e.dataTransfer.types)if(t==="text/uri-list"){let i=e.dataTransfer.getData(t);console.log(t,i);let n=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(i)?.groups?.name;if(n||(n=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(i)?.groups?.name),console.log(n),n){let r="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+n+"_1k.exr";this.setSkybox(r)}else console.warn("Could not resolve skybox name from dropped url",i)}}},this.context.domElement.addEventListener("dragover",this.dragOverEvent),this.context.domElement.addEventListener("drop",this.dropEvent))}unregisterDropEvents(){!this.dragOverEvent||(this.context.domElement.removeEventListener("dragover",this.dragOverEvent),this.context.domElement.removeEventListener("drop",this.dropEvent))}};P([ql("setSkybox"),S()],Pn.prototype,"url",2),P([S()],Pn.prototype,"allowDrop",2);import*as ls from"three";import{Object3D as A_}from"three";var Fh=class extends M{target=null;followFactor=.1;rotateFactor=.1;flipForward=!1;_firstUpdate=!0;onEnable(){let e=k.getComponentInChildren(this.gameObject,he);e&&e.cam&&(e.gameObject.position.set(0,0,0),e.cam.position.set(0,0,0),e.gameObject.quaternion.identity(),e.cam.quaternion.setFromEuler(new ls.Euler(0,Math.PI,0)))}onBeforeRender(){this.followFactor<=0||this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){let t=X(this.target),i=this._firstUpdate||e?1:J.clamp01(this.context.time.deltaTime*this.followFactor);this.worldPosition=this.worldPosition.lerp(t,i)}if(this.rotateFactor>0){let t=Ie(this.target);this.flipForward&&t.premultiply(Fh._invertForward);let i=this._firstUpdate||e?1:J.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},gi=Fh;U(gi,"_invertForward",new ls.Quaternion().setFromAxisAngle(new ls.Vector3(0,1,0),Math.PI)),P([S(A_)],gi.prototype,"target",2);import{Layers as Am}from"three";var Xl=D("debugspatialtrigger"),Im=new Am,km=new Am;function M_(a,e){return Im.mask=a,km.mask=e,Im.test(km)}var mt=class extends M{triggerMask=0;onEnter;onStay;onExit;start(){Xl&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of Xi.triggers)M_(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){let t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(let e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){Xl&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){Xl&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),this.onExit?.invoke(this,e)}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke(this,e)}};P([S()],mt.prototype,"triggerMask",2),P([S(_e)],mt.prototype,"onEnter",2),P([S(_e)],mt.prototype,"onStay",2),P([S(_e)],mt.prototype,"onExit",2);var ia=class extends M{triggerMask;boxHelper;start(){Xl&&console.log(this.name,this.triggerMask,this)}onEnable(){ia.triggers.push(this),this.boxHelper||(this.boxHelper=k.addNewComponent(this.gameObject,De),this.boxHelper?.showHelper())}onDisable(){ia.triggers.splice(ia.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){k.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof mt&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){k.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof mt&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){k.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof mt&&t.onExitTrigger(this)},!1)}},Xi=ia;U(Xi,"triggers",[]),P([S()],Xi.prototype,"triggerMask",2);import*as cr from"three";var kt=D("debugspectator"),oo=class extends M{cam=null;_mode=0;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}set target(e){if(this._handler){let t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.context.connection.connectionId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),k.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),k.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.context.connection.connectionId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new zh(this.context,this),this._networking=new Vh(this.context,this),this._networking.awake(),k.setActive(this.gameObject,!1),this.cam=k.getComponent(this.gameObject,he),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Nh(this.context,this.cam,this)),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Y.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),Y.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),Y.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.orbit=k.getComponent(this.context.mainCamera,Je)}onDestroy(){this.stopSpectating(),Y.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),Y.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),Y.removeEventListener("xrStopped",this.eventSub_WebXREndEvent),this._handler?.destroy(),this._networking.destroy()}isSupportedPlatform(){let e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),i=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!i}onXRSessionRequestStart(e){!this.isSupportedPlatform()||k.setActive(this.gameObject,!0)}onXRSessionStart(e){!this.isSupportedPlatform()||(kt&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){this.context.removeCamera(this.cam),k.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),kt&&console.log("Follow self",this.target)}onAfterRender(){if(!this.cam)return;let e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting&&!this._handler?.currentTarget)return;this._handler?.update(this._mode);let i=e.getRenderTarget(),n=null;if(!i){if(!e.state.bindFramebuffer||!e.state.bindXRFramebuffer)return;n=e._framebuffer,e.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();let r=this.context.mainCameraComponent;if(r){let c=r.backgroundColor;c&&e.setClearColor(c,c.alpha),this.cam.backgroundColor=c,this.cam.clearFlags=r.clearFlags,this.cam.nearClipPlane=r.nearClipPlane,this.cam.farClipPlane=r.farClipPlane}else e.setClearColor(new cr.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;let o=this.cam?.cam;this.context.updateAspect(o);let s=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,o),e.xr.isPresenting=s,e.xr.enabled=t,i?e.setRenderTarget(i):e.state.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){let e=this._mode===0;for(let t of ue.instances)if(t.avatar&&"isLocalAvatar"in t.avatar){let i=4294967295;this.isSpectatingSelf&&(i=e&&t.avatar.isLocalAvatar?8:16);let n=t.avatar.flags;if(!n)continue;for(let r of n)r.UpdateVisible(i)}}resetAvatarFlags(){for(let e of ue.instances)if(e.avatar&&"flags"in e.avatar){let t=e.avatar.flags;if(!t)continue;for(let i of t)e.avatar?.isLocalAvatar?i.UpdateVisible(8):i.UpdateVisible(16)}}},Nh=class{context;cam;spectator;follow;target;view;currentObject;get currentTarget(){return this.view}constructor(e,t,i){this.context=e,this.cam=t,this.spectator=i}set(e){let t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=k.addNewComponent(this.cam.gameObject,gi)),this.target||(this.target=new cr.Object3D),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,kt&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){kt&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){this.target?.removeFromParent(),this.follow&&k.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){kt&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(kt&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));let t=this.context.mainCamera;t&&(this.cam.cam.near!==t.near||this.cam.cam.far!==t.far)&&(this.cam.cam.near=t.near,this.cam.cam.far=t.far,this.cam.cam.updateProjectionMatrix());let i=this.follow?.target;if(!(!i||!this.follow)){switch(e){case 0:this.view?.viewDevice!=="browser"?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,this.view?.viewDevice!=="browser"?i.quaternion.copy(L_):i.quaternion.identity()}}},L_=new cr.Quaternion().setFromAxisAngle(new cr.Vector3(0,1,0),Math.PI),zh=class{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),window.addEventListener("keydown",n=>{n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener("pointerdown",n=>{i=this.context.time.time}),this.context.input.addEventListener("pointerup",n=>{let r=this.context.time.time-i;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){let e=new Te;e.setMask(16777215);let t=this.context.physics.raycast(e);if(kt&&console.log(...t),t?.length)for(let i of t){if(i.distance<.2)continue;let n=i.object,r=k.getComponentInParent(n,ue),o=r?.connectionId;if(o){let s=this.context.players.getPlayerView(o);this.spectator.target=s,kt&&console.log("spectate",o,r);break}}}},Uh=class{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}},Gh=class{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}},Vh=class{followers=[];context;spectator;_followerEventMethod;_requestFollowMethod;_joinedRoomMethod;constructor(e,t){this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen("joined-room",this._joinedRoomMethod),document.addEventListener("keydown",e=>{e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0)})}destroy(){this.context.connection.stopListening("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListening("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListening("joined-room",this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(kt&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){let i=e?.userId===void 0,n=i?t:e?.userId,r=new Uh(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(kt&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();let t=e?void 0:this.context.connection.connectionId,i=new Gh(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){D("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){let t=e.targetUserId,i=e.guid;if(kt&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){let n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){let t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}_lastRequestFollowUser;onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{let t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return kt&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}_enforceFollowInterval;enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(kt&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}};var so=class extends M{anchor=null;connectedBody=null;connectedAnchor=null;spring=10;damper=.2;rb=null;awake(){if(this.rb=k.getComponent(this.gameObject,oe),!this.connectedBody||!this.connectedBody.body||!this.rb||!this.rb.body)return;this.connectedBody.body.mass=Math.min(this.rb.body.mass*.99,this.connectedBody.body.mass);let e=new Oa(this.rb.body,this.connectedBody.body,{restLength:.01,stiffness:this.spring*.5,damping:this.damper});this.context.physics.addPostStepListener(t=>{e.applyForce()})}update(){}};import*as At from"three";import{Material as D_,Texture as j_}from"three";var dr=class{texture;triangles;uv;vertices;_geometry};P([S(j_)],dr.prototype,"texture",2);var Ql=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new At.BufferGeometry;e._geometry=t;let i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){let o=e.triangles[r];i[r*3]=-e.vertices[o].x,i[r*3+1]=e.vertices[o].y,i[r*3+2]=0;let s=e.uv[o];n[r*2]=s.x,n[r*2+1]=1-s.y}return t.setAttribute("position",new At.BufferAttribute(i,3)),t.setAttribute("uv",new At.BufferAttribute(n,2)),t}},Qi=class extends M{drawMode=0;size={x:1,y:1};color;sharedMaterial;get sprite(){return this._sprite}set sprite(e){e!==this._sprite&&(this._sprite=e,this.updateSprite())}_sprite;_currentSprite;awake(){this._currentSprite=void 0}start(){this.drawMode===2&&console.warn("Tiled draw mode is not supported yet",this),this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){if(!!this.__didAwake&&!!this.sprite&&!!this.sharedMaterial){if(this._currentSprite)this._currentSprite.geometry=Ql.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new At.MeshBasicMaterial({color:16777215,side:At.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new At.Color),e.color.copy(this.color),e.opacity=this.color.alpha),e.alphaTest=.5,this.sprite.texture&&!e.wireframe){let t=this.sprite.texture;e.map=t}this._currentSprite=new At.Mesh(Ql.getOrCreateGeometry(this.sprite),e)}this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite))}}};P([S()],Qi.prototype,"drawMode",2),P([S(ye)],Qi.prototype,"color",2),P([S(D_)],Qi.prototype,"sharedMaterial",2);var Mt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new Mt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new Mt).__init(e.readInt32(e.position())+e.position(),e)}userId(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){let e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new Se).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Se).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}};import{Object3D as B_}from"three";var Yl="SCAM";Go(Yl,Mt.getRootAsSyncedCameraModel);var Lt=new yt,Wh=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){Lt.clear();let i=Lt.createString(this.guid),n=Lt.createString(this.userId);Mt.startSyncedCameraModel(Lt),Mt.addGuid(Lt,i),Mt.addUserId(Lt,n);let r=X(e),o=La(e);Mt.addPos(Lt,Se.createVec3(Lt,r.x,r.y,r.z)),Mt.addRot(Lt,Se.createVec3(Lt,o.x,o.y,o.z));let s=Mt.endSyncedCameraModel(Lt);Lt.finish(s,Yl),t.sendBinary(Lt.asUint8Array())}}},Kl=class extends M{getCameraObject(e){let t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=null;async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinrary(Yl,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Yl,this._receiveCallback)}update(){for(let n in this.remoteCams){let r=this.remoteCams[n],o=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||o>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,o),r?.obj&&k.destroy(r.obj),delete this.remoteCams[n],r&&delete this.userToCamMap[r.userId],Kl.instances.push(r),this.context.players.removePlayerView(r.userId,"browser");continue}}if(Y.IsInWebXR)return;let e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new Wh(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let t=X(e),i=Ie(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,"browser"))}onReceivedRemoteCameraInfoBin(e){let t=e.guid();if(!t)return;let i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){let c=new Ge;c.context=this.context;let d=k.instantiate(this.cameraPrefab,c);n=this.remoteCams[t]={obj:d,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(d),this.userToCamMap[i]=t,Kl.instances.push(n);let l=k.getOrAddComponent(d,ue);l.connectionId=i,l.avatar=d}else return;let r=n.obj;this.context.players.setPlayerView(i,r,"browser"),n.lastUpdate=this.context.time.realtimeSinceStartup,re.markDirty(r);let o=e.pos();o&&Mo(r,o.x(),o.y(),o.z());let s=e.rot();s&&Da(r,s.x(),s.y(),s.z())}},On=Kl;U(On,"instances",[]),P([S([B_,Ye])],On.prototype,"cameraPrefab",2);var qh="view",Mm=D("debugsyncedroom"),Kt=class extends M{roomName;urlParameterName;joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=D(qh);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){let i=D(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=xu(i);this.roomName=n}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(Mm&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(Mm&&console.error('Missing room name on "'+this.name+'". Make sure this is correctly configured in Unity',this.context.connection.isDebugEnabled?this:""),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.context.connection.joinRoom(this.roomName),!0)}_lastPingTime=0;_lastRoomTime=-1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.send("ping",{time:this.context.time.time})),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?(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you)"))}get currentRoomName(){let e=D(qh);return e||D(this.urlParameterName)}setRandomRoomUrlParameter(){let e=fc(),t=this.generateRoomName();D(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),bu(t,e)}generateRoomName(){return yu()+"_"+vu(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){let e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(qh,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};P([S()],Kt.prototype,"roomName",2),P([S()],Kt.prototype,"urlParameterName",2),P([S()],Kt.prototype,"joinRandomRoom",2),P([S()],Kt.prototype,"requireRoomParameter",2),P([S()],Kt.prototype,"autoRejoin",2);function Lm(){let a=D("testwindowcount")||0;a&&a>0&&H_(a)}function H_(a){if(D("testwindow"))return null;let e=new URL(window.location.href);Ro(e.searchParams,es,1),Ro(e.searchParams,"testwindow",1);let t=e.toString(),i=[];window.onbeforeunload=()=>{for(let c of i)c.close()};let n=.05,r=128,o=0,s=0;for(let c=0;c<a;c++){o*r+r*.01>=window.innerWidth&&(s+=1,o=0);let d=o*(r*(1+n))+window.screenLeft,l=s*(r*(1+n))+window.screenTop+90+60*s;o+=1;let h=window.open(t,"test window "+c,`popup=yes width=${r} height=${r} top=${l} left=${d}`);if(!h){console.warn("Failed to open window");continue}i.push(h),h.onload=()=>{h.onbeforeunload=()=>{for(let u=0;u<i.length;u++){let f=i[u];f!==h&&f.close()}i.length=0}}}return i}import{Vector3 as N_}from"three";var ao=class extends M{awake(){Lm()}},lo=class extends M{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(Jo,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new Jl(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 yt(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=Kd(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){let t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}},Jl=class{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)}update(e,t){let i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;let 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){let r=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}};U(Jl,"temp",new N_);import{MathUtils as z_}from"three";import{TransformControls as U_}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as G_}from"three/examples/jsm/controls/OrbitControls";var hr=class extends M{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!_i||!this.context.mainCamera||(this.control=new U_(this.context.mainCamera,this.context.renderer.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=.6,this.control.traverse(e=>{let t=e;if(t.layers.set(2),t){let i=t.material;i&&(i.opacity=.3)}}))}start(){if(this.context.mainCamera){let e=k.getComponentInParent(this.context.mainCamera,G_)??void 0;this.orbit=e}}changeEventListener;windowKeyDownListener;windowKeyUpListener;onEnable(){this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject)),this.changeEventListener=this.onControlChangedEvent.bind(this),this.control?.addEventListener("dragging-changed",this.changeEventListener),this.attachWindowEvents()}onDisable(){this.control?.removeFromParent(),this.changeEventListener&&this.control?.removeEventListener("dragging-changed",this.changeEventListener)}onControlChangedEvent(e){let t=this.orbit;if(t&&(t.enabled=!e.value),e.value){let i=k.getComponentInParent(this.gameObject,ut);i&&i.requestOwnership()}}attachWindowEvents(){let e=this.control;!e||(this.windowKeyDownListener||(this.windowKeyDownListener=t=>{switch(t.keyCode){case 81:e.setSpace(e.space==="local"?"world":"local");break;case 16:e.setTranslationSnap(100),e.setRotationSnap(z_.degToRad(15)),e.setScaleSnap(.25);break;case 87:e.setMode("translate");break;case 69:e.setMode("rotate");break;case 82:e.setMode("scale");break;case 187:case 107:e.setSize(e.size+.1);break;case 189:case 109:e.setSize(Math.max(e.size-.1,.1));break;case 88:e.showX=!e.showX;break;case 89:e.showY=!e.showY;break;case 90:e.showZ=!e.showZ;break;case 32:e.enabled=!e.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=t=>{switch(t.keyCode){case 16:e.setTranslationSnap(null),e.setRotationSnap(null),e.setScaleSnap(null);break}}),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener))}};P([S()],hr.prototype,"isGizmo",2);import{LinearToneMapping as Dm,ACESFilmicToneMapping as V_,ReinhardToneMapping as W_}from"three";var Zl=D("debugvolume"),Bm=(i=>(i[i.None=0]="None",i[i.Neutral=1]="Neutral",i[i.ACES=2]="ACES",i))(Bm||{}),co=class{overrideState=!1;value=0},bi=class{active=!1;parameters},kn=class extends bi{mode;get isToneMapping(){return!0}},An=class extends bi{postExposure};function q_(a){return"mode"in a?kn:"postExposure"in a?An:bi}var jm=Symbol("volumeprofile"),In=class{components;apply(e){this.onUpdate(e,!1)}unapply(e){this.onUpdate(e,!0)}onUpdate(e,t){if(!this.components)return;let i=e.renderer,r=i[jm]!==void 0;if(t){if(!r)return}else i[jm]=this;for(let o of this.components)if(o instanceof kn){let s=o;if(!o.active||t){e.renderer.toneMapping=Dm;continue}switch(Zl&&console.log("VOLUME:",Bm[s.mode?.value??0]),s.mode?.value??0){case 0:e.renderer.toneMapping=Dm;break;case 1:e.renderer.toneMapping=W_;break;case 2:e.renderer.toneMapping=V_;break}}else if(o instanceof An){let s=o;Zl&&console.log(s.postExposure);let c=Math.pow(2,s.postExposure?.value??0),d=s.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=d?c:1}}};P([S([a=>q_(a),bi])],In.prototype,"components",2);var ur=class extends M{sharedProfile;awake(){Zl&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",e=>{e.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onEnable(){Zl&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};P([S(In)],ur.prototype,"sharedProfile",2);import{Vector3 as X_}from"three";var pr=class{guid;dontSave=!0;userId;point={x:0,y:0,z:0};source={x:0,y:0,z:0};target;update(e,t,i,n=void 0){this.userId=e.connection.connectionId,this.point.x=t.x,this.point.y=t.y,this.point.z=t.z,this.source.x=i.x,this.source.y=i.y,this.source.z=i.z,this.target=n}},ho=class extends M{prefab=null;_grabModels=[];_grabModelsUpdateTime=[];_addOrUpdateSub=null;_endSub=null;_freeSub=null;_instances={};awake(){this.prefab&&(this.prefab.visible=!1)}onEnable(){this._addOrUpdateSub=this.context.connection.beginListen("xr-grab-visual-start-or-update",this.onRemoteGrabStartOrUpdate.bind(this)),this._endSub=this.context.connection.beginListen("xr-grab-visual-end",this.onRemoteGrabEnd.bind(this)),this._freeSub=it.AddEventListener("WillFree",this.onAttachedObjectFree.bind(this))}onDisable(){this.context.connection.stopListening("xr-grab-visual-start-or-update",this._addOrUpdateSub),this.context.connection.stopListening("xr-grab-visual-end",this._endSub),it.RemoveEventListener("WillFree",this._freeSub)}addOrUpdateGrab(e){this.context.connection.send("xr-grab-visual-start-or-update",e,2)}endGrab(e){this.context.connection.send("xr-grab-visual-end",e,2)}onRemoteGrabStartOrUpdate(e){if(!this.prefab)return;let t=this._instances[e.guid];if(!t){let i=k.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=k.getComponentsInChildren(i,rt);if(n?.length>0)for(let r of n)r.assignUserColor(e.userId)}return}t.model=e}onRemoteGrabEnd(e){if(!e)return;let t=e.guid;this._instances[t]&&(k.destroy(this._instances[t].instance),delete this._instances[t])}onAttachedObjectFree(e){if(this._grabModels.length<=0)return;let t=this._grabModels[0];this.updateModel(t,e),this.endGrab(t)}onBeforeRender(){if(this.updateRendering(),!!this.prefab&&(this.prefab.visible=!1,this.context.time.frameCount%10===0))for(let e=0;e<it.Current.length;e++){let t=it.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new pr),this._grabModelsUpdateTime.push(0)),this._grabModelsUpdateTime[e]=this.context.time.time;let i=this._grabModels[e];this.updateModel(i,t),this.addOrUpdateGrab(i)}}updateModel(e,t){if(!t.controller||!t.selected)return;e.guid=t.grabUUID;let i=t.selected.guid;e.update(this.context,t.grabPoint,t.controller.worldPosition,i)}temp=new X_;updateRendering(){let e=this.context.time.deltaTime/.5;for(let t in this._instances){let{instance:i,model:n}=this._instances[t];if(!i||!n)continue;let{point:r}=n,o=X(i);this.temp.set(r.x,r.y,r.z),o.lerp(this.temp,e),se(i,o)}}};import{Object3D as Q_}from"three";var vi=class extends M{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=k.getComponentInParent(this.gameObject,we)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(let t of this.eyes)t&&(t.visible=this.eyesOpen)}}};P([S(Q_)],vi.prototype,"eyes",2),P([S()],vi.prototype,"lastBlinkTime",2),P([S()],vi.prototype,"blinkLength",2),P([S()],vi.prototype,"eyesOpen",2);import*as $l from"three";import{Object3D as Xh}from"three";var Qh=class extends M{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=k.getComponentInParent(this.gameObject,Di)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=k.addNewComponent(this.gameObject,Di)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new $l.Vector3;currentTargetPoint=new $l.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=X(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=X(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let o=Qh.forward;if(o.set(0,0,1),o.applyQuaternion(Ie(this.head)),o.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},yi=Qh;U(yi,"forward",new $l.Vector3(0,0,1)),P([S(Xh)],yi.prototype,"head",2),P([S(Xh)],yi.prototype,"eyes",2),P([S(Xh)],yi.prototype,"target",2);import{Object3D as Hm}from"three";var Y_=D("debugmouth"),Mn=class extends M{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=k.findObjectOfType(Ke,this.context),this.marker||(this.marker=k.getComponentInParent(this.gameObject,ue))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){Y_&&(e=null);return}let t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(!!e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){let n=e[i];n&&(n.visible=i===t)}}}};P([S(Hm)],Mn.prototype,"idle",2),P([S(Hm)],Mn.prototype,"talking",2);var uo=class extends M{voip=null;marker=null;_startPosition=null;awake(){this.voip=k.findObjectOfType(Ke,this.context),this.marker=k.getComponentInParent(this.gameObject,ue)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;let e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}};var $h={};fu($h,{AlignmentConstraint:()=>gn,Animation:()=>Ut,AnimationCurve:()=>Jn,AnimationTrackHandler:()=>Ln,Animator:()=>ct,AnimatorController:()=>zt,AttachedObject:()=>it,AudioListener:()=>Vt,AudioSource:()=>ae,AudioTrackHandler:()=>Dn,AvatarBlink_Simple:()=>vi,AvatarEyeLook_Rotation:()=>yi,AvatarLoader:()=>vn,AvatarMarker:()=>ue,AvatarModel:()=>Zn,Avatar_Brain_LookAt:()=>Di,Avatar_MouthShapes:()=>Mn,Avatar_MustacheShake:()=>uo,Avatar_POI:()=>xe,AxesHelper:()=>ki,BaseUIComponent:()=>je,BasicIKConstraint:()=>Gr,BoxCollider:()=>xn,BoxGizmo:()=>zi,BoxHelperComponent:()=>De,Button:()=>Dt,CallInfo:()=>ui,Camera:()=>he,Canvas:()=>Fe,CanvasGroup:()=>tn,Collider:()=>Wt,ColorAdjustments:()=>An,ControlTrackHandler:()=>Ki,Deletable:()=>qr,DeleteBox:()=>er,DeviceFlag:()=>tr,DragControls:()=>di,DropListener:()=>Cn,Duplicatable:()=>hi,EmissionModule:()=>io,EventList:()=>_e,EventListEvent:()=>or,EventSystem:()=>Ve,EventTrigger:()=>Xr,FieldWithDefault:()=>Yr,FlyControls:()=>Qr,GltfExport:()=>It,GltfExportBox:()=>Jr,Graphic:()=>gt,GraphicRaycaster:()=>xo,GridHelper:()=>Wi,GridLayoutGroup:()=>yo,GroundProjectedEnv:()=>qi,HorizontalLayoutGroup:()=>vo,Image:()=>en,InputField:()=>bt,Interactable:()=>Et,Keyboard:()=>go,LODGroup:()=>Tn,LODModel:()=>pi,LayoutGroup:()=>nn,Light:()=>We,LogStats:()=>po,LookAtConstraint:()=>ji,MainModule:()=>to,MaskableGraphic:()=>$i,MeshRenderer:()=>sr,NavMesh:()=>Zr,NavMeshAgent:()=>$r,NestedGltf:()=>ar,Networking:()=>Yt,ObjectRaycaster:()=>yr,OffsetConstraint:()=>fi,OrbitControls:()=>Je,ParticleSystem:()=>ro,ParticleSystemRenderer:()=>lr,PlayableDirector:()=>Zi,PlayerColor:()=>rt,PointerEventData:()=>Xt,RGBAColor:()=>ye,RawImage:()=>br,Raycaster:()=>vr,Rect:()=>gr,RectTransform:()=>ot,ReflectionProbe:()=>Ot,RemoteSkybox:()=>Pn,Renderer:()=>le,RendererLightmap:()=>Ui,Rigidbody:()=>oe,ScreenCapture:()=>Rn,ShadowCatcher:()=>Sn,ShapeModule:()=>no,SignalAsset:()=>fr,SignalReceiver:()=>Yi,SignalReceiverEvent:()=>mr,SignalTrackHandler:()=>Ji,Size:()=>fo,SkinnedMeshRenderer:()=>Kr,SmoothFollow:()=>gi,SpatialHtml:()=>wo,SpatialTrigger:()=>Xi,SpatialTriggerReceiver:()=>mt,SpectatorCamera:()=>oo,SphereCollider:()=>yn,SpringJoint:()=>so,Sprite:()=>dr,SpriteRenderer:()=>Qi,SyncedCamera:()=>On,SyncedRoom:()=>Kt,SyncedTransform:()=>ut,TeleportTarget:()=>rr,TestRunner:()=>ao,TestSimulateUserData:()=>lo,Text:()=>Pe,ToneMapping:()=>kn,TransformGizmo:()=>hr,UIRaycastUtils:()=>Qt,UIRootComponent:()=>Hi,UsageMarker:()=>Ct,VRUserState:()=>Pt,VerticalLayoutGroup:()=>bo,VideoPlayer:()=>Ce,Voip:()=>Ke,Volume:()=>ur,VolumeComponent:()=>bi,VolumeParameter:()=>co,VolumeProfile:()=>In,WebAR:()=>En,WebARSessionRoot:()=>Tt,WebXR:()=>Y,WebXRAvatar:()=>Rt,WebXRController:()=>ie,WebXRSync:()=>Ni,XRFlag:()=>we,XRGrabModel:()=>pr,XRGrabRendering:()=>ho,XRRig:()=>_n,XRState:()=>ft,__Ignore:()=>ps});var K_=D("logstats"),po=class extends M{onEnable(){console.log(this),K_&&this.startCoroutine(this.run(),4)}*run(){for(;this.enabled;){let e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}};import*as zm from"three";var fr=class{guid},mr=class{signal;reaction;$serializedTypes={signal:fr,reaction:_e}},Yi=class extends M{events;start(){console.log(this)}invoke(e){if(!this.events||!Array.isArray(this.events))return;let t=typeof e=="object"?e.guid:e;for(let i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};P([S(mr)],Yi.prototype,"events",2);import*as ne from"three";import{Quaternion as J_,Vector3 as Z_}from"three";var cs=D("debugtimeline"),ds=class{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(!!this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(let t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;let r=i[t];if(n||e>=r.start&&e<=r.end){let o=1,s=!1;return r.easeInDuration>0&&(o*=Math.min((e-r.start)/r.easeInDuration,1)),r.easeOutDuration>0&&!s&&(o*=Math.min((r.end-e)/r.easeOutDuration,1)),o}return 0}},Yh=class{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){let t=e.getClip();this.clip=t;let i=e.getRoot(),n=i.name+".position",r=i.name+".quaternion";cs&&console.log(t.name,t.tracks,n);for(let o of t.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(n))this.rootStartPosition=new ne.Vector3().fromArray(o.values,0),this.rootEndPosition=new ne.Vector3().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),cs&&console.log(this.rootPositionOffset);else if(o.name.endsWith(r)&&(this.rootStartQuaternion=new ne.Quaternion().fromArray(o.values,0),this.rootEndQuaternion=new ne.Quaternion().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),cs)){let s=new ne.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}},Ln=class extends ds{models=[];trackOffset;target;mixer;clips=[];actions=[];_actionOffsets=[];_didBind=!1;createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=t.tracks[0].name.split("."),n=i[i.length-2],r=n+".position",o=n+".quaternion",s=!1,c=!1;for(let d of t.tracks)d.name.endsWith(r)?(s=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(o)&&(c=!0,this.createRotationInterpolant(t,e,d));if(!s||!c){let d=this.mixer?.getRoot(),l=t.tracks[0],h=l.name.lastIndexOf("."),u=l.name.substring(0,h),f=u.substring(u.lastIndexOf(".")+1),x=d.getObjectByName(f);if(x)if(s){if(!c){let b=t.tracks[0].name.substring(0,h)+".quaternion";cs&&console.warn("Create quaternion track",f,x);let y=x.quaternion,g=new ne.QuaternionKeyframeTrack(b,[0,t.duration],[y.x,y.y,y.z,y.w,y.x,y.y,y.z,y.w]);t.tracks.push(g),this.createRotationInterpolant(t,e,g)}}else{let b=u+".position";cs&&console.warn("Create position track",f,x);let y=x.position,g=new ne.VectorKeyframeTrack(b,[0,t.duration],[y.x,y.y,y.z,y.x,y.y,y.z]);t.tracks.push(g),this.createPositionInterpolant(t,e,g)}}}bind(){if(!this._didBind){this._didBind=!0,cs&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(let e of this.actions){let t=new Yh(e);this._actionOffsets.push(t)}for(let e of this.models){let t=e.asset,i=t.position,n=t.rotation;i.x!==void 0&&(i.isVector3||(t.position=new Z_(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new J_(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){let e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new ne.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new ne.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new ne.Vector3;_totalOffsetRotation=new ne.Quaternion;_totalOffsetPosition2=new ne.Vector3;_totalOffsetRotation2=new ne.Quaternion;_summedPos=new ne.Vector3;_tempPos=new ne.Vector3;_summedRot=new ne.Quaternion;_tempRot=new ne.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1;for(let r=0;r<this.clips.length;r++){let o=this.models[r],s=this.actions[r],c=o.asset;s.weight=0;let d=e>=o.start&&e<=o.end,l=o.postExtrapolationMode,h=d;if(!h&&!n&&o.end<e&&o.postExtrapolationMode!==0){let u=r<this.clips.length-1?this.models[r+1]:null;(!u||u.start>e)&&(h=!0,n=!0)}if(h){let u=1;u*=this.evaluateWeight(e,r,this.models,h);let f=this.getClipTime(e,o),x=0,b=c.duration;if(d){if(c.loop)for(x+=Math.floor(f/(b+1e-6));f>b;)f-=b}else if(!d)switch(l){case 2:f%=b;break;case 3:let p=Math.floor(f/b)%2!==0;f%=b,p&&(f=b-f);break}s.time=f,s.timeScale=0;let y=u*this.director.weight;if(s.weight=y,s.clampWhenFinished=!0,s.isRunning()||s.play(),this._useclipOffsets){let g=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,p=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-u),t+=1;let m=this._summedPos.set(0,0,0),v=this._tempPos.set(0,0,0),w=this._summedRot.identity(),E=this._tempRot.identity(),C=c.rotation,T=new ne.Quaternion;T.slerp(C,u);let R=this._actionOffsets[r];if(R.hasOffsets)for(let I=0;I<x;I++)R.rootPositionOffset?v.copy(R.rootPositionOffset):v.set(0,0,0),v.applyQuaternion(w).applyQuaternion(T),R.rootQuaternionOffset&&(E.copy(R.rootQuaternionOffset),w.multiply(E)),m.add(v);p.multiply(T),p.multiply(w),m.add(c.position),g.add(m)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.mixer.update(e)}createRotationInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new ne.Quaternion;this.ensureTrackOffsets();let o=this.trackOffset?.rotation;i.createInterpolant=()=>{let s=n(),c=s.evaluate.bind(s);return s.evaluate=d=>{let l=c(d);return r.set(l[0],l[1],l[2],l[3]),r.premultiply(this._totalOffsetRotation),o&&r.premultiply(o),l[0]=r.x,l[1]=r.y,l[2]=r.z,l[3]=r.w,l},s}}createPositionInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new ne.Vector3;this.ensureTrackOffsets();let o=this.trackOffset?.rotation,s=this.trackOffset?.position,c;i.createInterpolant=()=>{let d=n(),l=d.evaluate.bind(d);return d.evaluate=h=>{let u=l(h);return r.set(u[0],u[1],u[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(f=>f.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),o&&r.applyQuaternion(o),s&&(r.x-=s.x,r.y+=s.y,r.z+=s.z),u[0]=r.x,u[1]=r.y,u[2]=r.z,u},d}}},Dn=class extends ds{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return wi(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){let i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){let t=this.getAudioFilePath(e.asset.clip),i=new ne.Audio(this.listener);i.setVolume(e.asset.volume);let n=new ne.AudioLoader;console.log(t,this.director.sourceId),n.load(t,r=>{i.setBuffer(r),i.loop=e.asset.loop,this.audio.push(i),this.models.push(e)})}onDisable(){for(let e of this.audio)e.isPlaying&&e.stop()}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){let t=this.audio[e];t?.isPlaying&&t.stop()}}evaluate(e){if(!this.track.muted){for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.audio[t];if(e>=i.start&&e<=i.end){if(this.director.isPaused&&(n.isPlaying&&n.stop(),this.lastTime===e))continue;n.isPlaying||(n.offset=i.clipIn+(e-i.start)*i.timeScale,n.play());let r=i.asset.volume;i.easeInDuration>0&&(r*=Math.min((e-i.start)/i.easeInDuration,1)),i.easeOutDuration>0&&(r*=Math.min((i.end-e)/i.easeOutDuration,1)),n.setVolume(r*this.director.weight)}else n.isPlaying&&n.stop()}this.lastTime=e}}},Ji=class extends ds{models=[];didTrigger=[];receivers=[];evaluate(e){if(!(this.receivers.length<=0)&&!this.track.muted)for(let t=0;t<this.models.length;t++){let i=this.models[t],n=this.didTrigger[t],r=i.time-e;if(i.retroActive?r<0:r<0&&Math.abs(r)<.1){if(!n){this.didTrigger[t]=!0;for(let s of this.receivers)!s||s.invoke(i.asset)}}else i.emitOnce||(this.didTrigger[t]=!1)}}},na=class extends ds{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){let n=this.models[t].asset;if(typeof n.sourceObject=="string"){let r=n.sourceObject;na.resolved[r]?n.sourceObject=na.resolved[r]:(n.sourceObject=k.findByGuid(r,e.scene),na.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=k.getComponent(n.sourceObject,Zi);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}else{this.models.splice(t,1);continue}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){let i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;let r=this.getClipTime(e,i);if(n.controlActivation){let o=n.sourceObject;o.visible=!0}if(n.updateDirector){let o=this.timelines[t];o&&(o.isPlaying&&o.pause(),o.time=r,o.evaluate())}}else{let r=this._previousActiveModel?.asset;if(n.controlActivation){let o=n.sourceObject;r?.sourceObject!==o&&(o.visible=!1)}}}}},Ki=na;U(Ki,"resolved",{});var Nm=D("debugtimeline");var ec=class extends M{static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){this._time=e}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}_visibilityChangeEvt;_clonedPlayableAsset=!1;awake(){Nm&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),this.playOnAwake?this.play():this.evaluate(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,this.playableAsset?.tracks,Array.isArray(this.playableAsset?.tracks),this)}onEnable(){for(let e of this._audioTracks)e.onEnable?.();for(let e of this._customTracks)e.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){this.stop();for(let e of this._audioTracks)e.onDisable?.();for(let e of this._customTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(let e of this._audioTracks)e.onDestroy?.()}rebuildGraph(){!this.isValid()||(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}play(){!this.isValid()||(this._isPaused=!1,!this._isPlaying&&(this._isPlaying=!0,this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())))}pause(){this._isPaused=!0}stop(){this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate()),this._isPlaying=!1,this._isPaused=!1,this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:e=Math.min(e,this._duration);break;case 1:e%=this._duration;break;case 2:if(e>this._duration){this.stop();return}break}this.internalEvaluate(e)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(let e of this._allTracks)for(let t of e)yield t}get audioTracks(){return this._audioTracks}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_controlTracks=[];_customTracks=[];_allTracks=[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks];*internalUpdate(){for(;this._isPlaying;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime,this.evaluate()),yield}internalEvaluate(e){for(let t of this.playableAsset.tracks)if(!t.muted)switch(t.type){case"ActivationTrack":for(let i=0;i<t.outputs.length;i++){let n=t.outputs[i];if(typeof n=="object"){let r=!1;for(let s of t.clips)s.start<=e&&e<=s.end&&(r=!0);let o=n;o.visible!==void 0&&(o.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=ys(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;let e=this.findRoot(this.gameObject);for(let t of this.playableAsset.tracks)for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);let r=k.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Nm&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),ec.createTrackFunctions[t.type])continue;t.type!=="AudioTrack"&&t.type!=="ControlTrack"&&t.type!=="MarkerTrack"&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(let e of this.playableAsset.tracks)if(e.muted!==!0)for(let t of e.clips)t.end>this._duration&&(this._duration=t.end)}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=[];for(let t of this.playableAsset.tracks){let i=t.type,n=ec.createTrackFunctions[i];if(n!=null){let r=n(this,t);if(typeof r.evaluate=="function"){r.director=this,r.track=t,this._customTracks.push(r);continue}}if(t.type==="AnimationTrack"){if(t.clips.length<=0)continue;for(let r=t.outputs.length-1;r>=0;r--){let o=t.outputs[r];typeof o.enabled=="boolean"&&(o.enabled=!1);let s=o?.gameObject?.animations;if(s){let c=new Ln;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let d=0;d<t.clips.length;d++){let l=t.clips[d],h=l.asset;if(!h){console.error("MISSING anim model?","clip#"+d,l,t,this.playableAsset,this.name);continue}let u=h.clip,f=u;if((typeof f=="string"||typeof f=="number")&&(f=s.find(b=>b.name===u)),!f){console.warn("Could not find animationClip for model",l,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new zm.AnimationMixer(o.gameObject)),c.clips.push(f),c.mixer.uncacheAction(f),c.createHooks(l.asset,f);let x=c.mixer.clipAction(f);c.actions.push(x),c.models.push(l)}this._animationTracks.push(c)}}}else if(t.type==="AudioTrack"){if(t.clips.length<=0)continue;e.push(t)}else if(t.type==="MarkerTrack"){let r=new Ji;r.director=this,r.track=t;for(let o of t.markers)switch(o.type){case"SignalEmitter":r.models.push(o),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let o=k.getComponent(this.gameObject,Yi);o&&(r.receivers.push(o),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new Ji;r.director=this,r.track=t;for(let o of t.markers)r.models.push(o),r.didTrigger.push(!1);for(let o of t.outputs)r.receivers.push(o);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new Ki;r.director=this,r.track=t;for(let o of t.clips)r.models.push(o);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}ae.registerWaitForAllowAudio(()=>{let t=k.findObjectOfType(Vt,this.context);if(!!t)for(let i of e){let n=new Dn;n.director=this,n.track=i,n.listener=t.listener;for(let r=0;r<i.clips.length;r++){let o=i.clips[r];n.addModel(o)}this._audioTracks.push(n)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},Zi=ec;U(Zi,"createTrackFunctions",{});import{Color as i0,Texture as Xm}from"three";import*as Jh from"three-mesh-ui";import{Matrix4 as e0,Object3D as t0,Vector2 as Wm,Vector3 as Kh}from"three";import{FrontSide as Um,DoubleSide as Gm}from"three";function hs(a,e){if(!a)return;let t=a.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?Gm:Um,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?Gm:Um,a.castShadow=e.castShadows?e.castShadows:!1,a.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of a.children)hs(i,e)}function tc(a,e,t){a[e]===void 0&&console.warn("Field",e,"is undefined on",a);let i=Proxy.revocable(a[e],{set(o,s,c,d){let l=o[s],h=Reflect.set(o,s,c,d);return t(c,l),h}}),n=i.revoke,r=a[e];return i.revoke=()=>{a[e]=r,n()},a[e]=i.proxy,i}function Vm(a,e,t=3){let i=a.__scheduledActions;i||(i=a.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*s(){e?.call(a),r[n]=null}let c=a.startCoroutine(s(),t);r[n]=c}var qm=D("debugui"),fo=class{width;height},gr=class{x;y;width;height},ot=class extends je{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new Kh),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new e0,this.rectBlock=new t0,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new Kh),tc(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0}onDisable(){super.onDisable(),this.removeShadowComponent()}applyTransform(){let e=this.shadowComponent;!e||(this._transformNeedsUpdate=!1,this.isRoot()?e.rotation.y=Math.PI:(e.position.copy(this.gameObject.position),e.position.x*=-1,e.position.z*=-1,e.position.z-=this.offset,e.quaternion.copy(this.gameObject.quaternion),e.rotation.x*=-1,e.rotation.z*=-1,e.scale.copy(this.gameObject.scale)),this.applyAnchoring(e.position),this.lastMatrix.copy(this.gameObject.matrix))}markDirty(){this._transformNeedsUpdate=!0}onBeforeRender(){(this._transformNeedsUpdate||this.lastMatrix.equals(this.gameObject.matrix)===!1)&&(qm&&console.log("updating",this.name),this.applyTransform()),Ve.ensureUpdateMeshUI(Jh,this.context)}applyAnchoring(e){if(this.pivot&&this.sizeDelta){let t=this.pivot.x*2-1,i=this.pivot.y*2-1;i-=this.anchoredPosition.y*.05;let n=this.sizeDelta.x*t,r=this.sizeDelta.y*i;e.x-=n*.5,e.y-=r*.5}}getBasicOptions(){let e={width:this.rect.width,height:this.rect.height,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},qm&&console.log(this.name,e);let t=new Jh.Block(e);return this._createdBlocks.push(t),t}};P([S(gr)],ot.prototype,"rect",2),P([S(Wm)],ot.prototype,"sizeDelta",2),P([S(Kh)],ot.prototype,"anchoredPosition3D",2),P([S(Wm)],ot.prototype,"pivot",2);var gt=class extends je{get isGraphic(){return!0}get color(){return this._color||(this._color=new ye(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new ye(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=k.getComponent(this.gameObject,ot)),this._rect}setState(e){this.makePanel(),this.uiObject&&this.uiObject.setState(e)}setupState(e){this.makePanel(),this.uiObject&&this.uiObject.setupState(e)}setOptions(e){this.makePanel(),this.uiObject&&(this.uiObject.set(e),(e.backgroundColor!==void 0||e.backgroundOpacity!==void 0)&&this.uiObject.updateBackgroundMaterial?.call(this.uiObject))}awake(){super.awake(),this.makePanel(),tc(this,"_color",()=>Vm(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;let e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}async setTexture(e){!e||(this.setOptions({backgroundOpacity:0}),e&&this.setOptions({backgroundTexture:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}))}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};P([S(ye)],gt.prototype,"color",1),P([S()],gt.prototype,"raycastTarget",2);var $i=class extends gt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var ic=class{texture;rect};P([S(Xm)],ic.prototype,"texture",2);var en=class extends $i{sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return this.sprite?.texture?.image?.width===32&&this.sprite?.texture?.image?.height===32}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new i0(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};P([S(ic)],en.prototype,"sprite",2);var br=class extends $i{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};P([S(Xm)],br.prototype,"mainTexture",2);var us=D("debugbutton");var Dt=class extends M{onClick;_isHovered=!1;onPointerEnter(e){us&&console.log("Button Enter",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered")}onPointerExit(){us&&console.log("Button Exit",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!1,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal")}onPointerDown(e){us&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed")}onPointerUp(e){us&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),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){us&&console.trace("Button Click",this.onClick),this.onClick?.invoke()}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(),us&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_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=k.getComponent(this.gameObject,en),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);let n=this.getFinalColor(e.color,this.colors?.highlightedColor),r={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(r);let o=this.getFinalColor(e.color,this.colors?.pressedColor),s={state:"pressed",attributes:{backgroundColor:o,backgroundOpacity:o.alpha}};e.setupState(s);let c=this.getFinalColor(e.color,this.colors?.selectedColor),d={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(d);let l=this.getFinalColor(e.color,this.colors?.disabledColor),h={state:"disabled",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(h)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};P([S(_e)],Dt.prototype,"onClick",2),P([S()],Dt.prototype,"colors",2),P([S()],Dt.prototype,"transition",2),P([S()],Dt.prototype,"animationTriggers",2),P([S(ct)],Dt.prototype,"animator",2),P([S()],Dt.prototype,"interactable",1);var Zh=class extends Hi{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof Zh||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),hs(this.shadowComponent,this);for(let e of k.getComponentsInChildren(this.gameObject,je))hs(e.shadowComponent,this)}}_activeRenderMode=-1;get isScreenSpace(){return this._activeRenderMode===1||this._activeRenderMode===0}updateRenderMode(){if(this.renderMode!==this._activeRenderMode)switch(this.renderMode){case 0:case 1:let e=this.context.mainCameraComponent;if(!e)return;let t=this.gameObject;e.gameObject?.add(t);let n=e.farClipPlane;t.position.x=0,t.position.y=0,t.position.z=-n;let r=Math.tan(J.toRadians(e.fieldOfView)*n)*(e.aspect*1.333333),o=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=o;break;case 2:break}}},Fe=Zh;P([S()],Fe.prototype,"renderOnTop",1),P([S()],Fe.prototype,"depthWrite",1),P([S()],Fe.prototype,"doubleSided",1),P([S()],Fe.prototype,"castShadows",1),P([S()],Fe.prototype,"receiveShadows",1),P([S()],Fe.prototype,"renderMode",1),P([S(Fe)],Fe.prototype,"rootCanvas",1),P([S()],Fe.prototype,"scaleFactor",1);var tn=class extends M{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of k.getComponentsInChildren(this.gameObject,gt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};P([S()],tn.prototype,"alpha",1),P([S()],tn.prototype,"interactable",2),P([S()],tn.prototype,"blocksRaycasts",2);import*as Qm from"three-mesh-ui";import{Color as N}from"three";var n0=D("debugtext");var Pe=class extends gt{canvas;alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;get text(){return this._text}set text(e){if(this._text=e,!this._textMeshUi&&this._text.length>0&&this.context.time.frame>0&&this.createText(e,this.getTextOpts(),this.supportRichText),this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){if(this._fontSize=e,this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}onColorChanged(){if(this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}let e=this.color;this._textMeshUi[0].set({fontColor:e,fontOpacity:e.alpha}),this.markDirty()}}_isWaitingForRebuild=!1;requestRebuild(){this._isWaitingForRebuild||(this._isWaitingForRebuild=!0,this.startCoroutine(this.rebuildDelayedRoutine(),0))}*rebuildDelayedRoutine(){if(this._isWaitingForRebuild=!1,this._textMeshUi){for(let e of this._textMeshUi)e.removeFromParent();this._textMeshUi.length=0}this.createText(this.text,this.getTextOpts(),this.supportRichText),this.markDirty()}onCreate(e){n0&&console.log(this);let t=this.verticalOverflow==0&&this.horizontalOverflow==0;t&&(this.context.renderer.localClippingEnabled=!0);let i=this.rectTransform;this._textContainer=this.uiObject=this.createBlock(i,t,null,!0),this.createText(this.text,this.getTextOpts(),this.supportRichText),this.uiObject,this.uiObject=this.createBlock(i,t,this.uiObject,!1)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;_textContainer=null;getTextOpts(){let e=this.fontSize,t={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&(this.uiObject.onAfterUpdate=this.updateWidth.bind(this))}createBlock(e,t,i,n=!1){let r={};r.hiddenOverflow=t,r.interLine=(this.lineSpacing-1)*this.fontSize*1.333,this.getAlignment(r,n);let o=e.createNewBlock(r);return i&&(Array.isArray(i)?o.add(...i):o.add(i)),o}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((i,n)=>i+n.width,0);t+=e.getFontSize()*5,t+=e.padding*2||0,t+=this.fontSize*1.5,e.set({width:t}),this.ensureShadowComponentOwner()}},1)}ensureShadowComponentOwner(){this.shadowComponent&&this.shadowComponent.traverse(e=>{e[St]===void 0&&(e[St]=this)})}createText(e,t,i){if(!(!e||e.length<=0))if(this._textMeshUi||(this._textMeshUi=[]),i){let n=this.getNextTag(e);if(n)n.startIndex>0&&this.createText(e.substring(0,n.startIndex),t,!1);else return this.createText(e,t,!1);let r=[];for(;n;){let o=this.getNextTag(e,n.endIndex);if(o){let s=this.getText(e,n,o);this.handleTag(n,t,r),this.createText(s,t,!1)}else{let s=e.substring(n.endIndex);this.handleTag(n,t,r),this.createText(s,t,!1)}n=o}}else{let n={...t};n.content=e;let r=new Qm.Text(n);this._textMeshUi.push(r),this._textContainer&&this._textContainer.add(r)}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;let e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;n=!0;let o=this._textMeshUi[r];!o.textContent||(hs(o,i),e[r]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(e.isEndTag){if(i.length>0){let n=i.pop();if(n)for(let r in n.previousValues){let o=n.previousValues[r];t[r]=o}}}else if(e.type.includes("color")){let n=new ra(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=r0(r)}else t.fontColor=new N(1,1,1)}else if(e.type=="b"){let n=new ra(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new ra(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,2)}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){let i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){let r=e.substring(i+1,n);return{type:r,startIndex:i,endIndex:n+1,isEndTag:r.startsWith("/")}}return null}setFont(e,t){let i=this.getFontName(t),n=i;n?.endsWith("-msdf.json")||(n+="-msdf.json"),e.fontFamily=n;let r=i;r?.endsWith(".png")||(r+=".png"),e.fontTexture=r}getFontName(e){return this.font?(this.font=wi(this.sourceId,this.font),this.font):null}};P([S(Fe)],Pe.prototype,"canvas",2),P([S()],Pe.prototype,"alignment",2),P([S()],Pe.prototype,"verticalOverflow",2),P([S()],Pe.prototype,"horizontalOverflow",2),P([S()],Pe.prototype,"lineSpacing",2),P([S()],Pe.prototype,"supportRichText",2),P([S()],Pe.prototype,"font",2),P([S()],Pe.prototype,"fontStyle",2),P([S()],Pe.prototype,"text",1),P([S()],Pe.prototype,"fontSize",1);var ra=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function r0(a){if(a.startsWith("#")){let t=a.substring(1);var e=parseInt(t,16);let i=e>>16&255,n=e>>8&255,r=e&255;return new N(i/255,n/255,r/255)}switch(a){case"black":return new N(0,0,0);case"white":return new N(1,1,1);case"red":return new N(1,0,0);case"lime":return new N(0,1,0);case"blue":return new N(0,0,1);case"yellow":return new N(1,1,0);case"cyan":return new N(0,1,1);case"magenta":return new N(1,0,1);case"silver":return new N(.75,.75,.75);case"gray":return new N(.5,.5,.5);case"maroon":return new N(.5,0,0);case"olive":return new N(.5,.5,0);case"green":return new N(0,.5,0);case"purple":return new N(.5,0,.5);case"teal":return new N(0,.5,.5);case"navy":return new N(0,0,.5);case"darkred":return new N(.54,0,0);case"brown":return new N(.55,.27,0);case"firebrick":return new N(.69,.13,.13);case"crimson":return new N(.86,.08,.24);case"tomato":return new N(1,.39,.28);case"coral":return new N(1,.49,.31);case"indianred":return new N(.6,.31,.51);case"lightcoral":return new N(.94,.5,.5);case"darkorange":return new N(1,.55,0);case"orange":return new N(1,.65,0);case"gold":return new N(1,.84,0);case"darkgoldenrod":return new N(.72,.53,.04);case"goldenrod":return new N(.85,.65,.13);case"palegoldenrod":return new N(.93,.87,.67);case"darkkhaki":return new N(.74,.7,.42);case"khaki":return new N(.94,.9,.55);case"yellowgreen":return new N(.6,.8,.19);case"darkolivegreen":return new N(.33,.42,.18);case"olivedrab":return new N(.42,.56,.14);case"lawngreen":return new N(.49,.99,0);case"chartreuse":return new N(.5,1,0);case"greenyellow":return new N(.68,1,.18);case"darkgreen":return new N(0,.39,0);case"forestgreen":return new N(.13,.55,.13);case"limegreen":return new N(.19,.8,.19);case"lightgreen":return new N(.56,.93,.56);case"palegreen":return new N(.59,.98,.59);case"darkseagreen":return new N(.56,.74,.56);case"mediumspringgreen":return new N(0,.98,.6);case"springgreen":return new N(0,1,.5);case"seagreen":return new N(.18,.31,.31);case"mediumaquamarine":return new N(.4,.8,.66);case"mediumseagreen":return new N(.24,.7,.44);case"lightseagreen":return new N(.13,.7,.67);case"darkslategray":return new N(.18,.31,.31);case"darkcyan":return new N(0,.55,.55);case"aqua":return new N(0,1,1);case"lightcyan":return new N(.8,1,1);case"darkturquoise":return new N(0,.81,.82);case"turquoise":return new N(0,.82,.82);case"mediumturquoise":return new N(.28,.82,.8);case"paleturquoise":return new N(.68,1,.93);case"aquamarine":return new N(.5,1,.83);case"powderblue":return new N(.69,.88,.9);case"cadetblue":return new N(.37,.62,.63);case"steelblue":return new N(.27,.51,.71);case"cornflowerblue":return new N(.39,.58,.93);case"deepskyblue":return new N(0,.7,1);case"dodgerblue":return new N(.12,.56,1);case"lightblue":return new N(.68,.85,.9);case"skyblue":return new N(.53,.81,.92);case"lightskyblue":return new N(.53,.81,.98);case"midnightblue":return new N(.18,.18,.31);case"darkblue":return new N(0,0,.55);case"mediumblue":return new N(0,0,.82);case"royalblue":return new N(.25,.41,.88);case"blueviolet":return new N(.54,.17,.89);case"indigo":return new N(.29,0,.51);case"darkslateblue":return new N(.28,.24,.55);case"slateblue":return new N(.42,.35,.8);case"mediumslateblue":return new N(.48,.41,.9);case"mediumpurple":return new N(.58,.44,.86);case"darkmagenta":return new N(.55,0,.55);case"darkviolet":return new N(.58,0,.83);case"darkorchid":return new N(.6,.2,.8);case"mediumorchid":return new N(.73,.33,.83);case"thistle":return new N(.84,.75,.85);case"plum":return new N(.87,.63,.87);case"violet":return new N(.93,.51,.93);case"fuchsia":return new N(1,0,1);case"orchid":return new N(.85,.44,.84);case"mediumvioletred":return new N(.78,.08,.52);case"palevioletred":return new N(.86,.44,.58);case"hotpink":return new N(1,.4,.71);case"deeppink":return new N(1,.08,.58);case"lightpink":return new N(1,.71,.76);case"pink":return new N(1,.75,.78);case"antiquewhite":return new N(.98,.92,.84);case"beige":return new N(.96,.96,.86);case"bisque":return new N(1,.89,.77);case"blanchedalmond":return new N(1,.92,.82);case"wheat":return new N(.96,.87,.87);case"cornsilk":return new N(1,.97,.86);case"lemonchiffon":return new N(1,.98,.8);case"lightgoldenrodyellow":return new N(.98,.98,.82);case"lightyellow":return new N(1,1,.8);case"saddlebrown":return new N(.55,.27,.07);case"sienna":return new N(.63,.32,.18);case"chocolate":return new N(.82,.41,.12);case"peru":return new N(.82,.52,.25);case"sandybrown":return new N(.96,.64,.38);case"burlywood":return new N(.87,.72,.53);case"tan":return new N(.82,.71,.55);case"rosybrown":return new N(.74,.56,.56);case"moccasin":return new N(1,.89,.71);case"navajowhite":return new N(1,.87,.68);case"peachpuff":return new N(1,.85,.73);case"mistyrose":return new N(1,.89,.88);case"lavenderblush":return new N(1,.94,.93);case"linen":return new N(.98,.94,.9);case"oldlace":return new N(.99,.96,.9);case"papayawhip":return new N(1,.94,.84);case"seashell":return new N(1,.96,.93);case"mintcream":return new N(.98,1,.98);case"slategray":return new N(.44,.5,.56);case"lightslategray":return new N(.47,.53,.6);case"lightsteelblue":return new N(.69,.77,.87);case"lavender":return new N(.9,.9,.98);case"floralwhite":return new N(1,.98,.98);case"aliceblue":return new N(.94,.97,1);case"ghostwhite":return new N(.97,.97,1);case"honeydew":return new N(.94,1,.94);case"ivory":return new N(1,1,.94);case"azure":return new N(.94,1,1);case"snow":return new N(1,.98,.98);case"dimgray":return new N(.4,.4,.4);case"darkgray":return new N(.66,.66,.66);case"lightgray":return new N(.83,.83,.83);case"gainsboro":return new N(.86,.86,.86);case"whitesmoke":return new N(.96,.96,.96)}return new N(1,1,1)}var mo=D("debuginputfield"),Z=class extends M{get text(){return this.textComponent?.text??""}get isFocused(){return Z.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){mo&&console.log(this.name,this)}onEnable(){Z.htmlField||(Z.htmlField=document.createElement("input"),Z.htmlField.classList.add("ar"),document.body.appendChild(Z.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),Z.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&k.setActive(this.placeholder.gameObject,!1)}onDisable(){Z.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){mo&&console.log("CLICK",e,Z.active),Z.activeTime=this.context.time.time,Z.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();Z.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-Z.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(Z.active!==this&&(mo&&console.log("Select",this.name,this,Z.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,Z.htmlField?.value),Z.active?.onDeselected(),Z.active=this,this.placeholder&&k.setActive(this.placeholder.gameObject,!1),Z.htmlField)){if(Z.htmlField.value=this.textComponent?.text||"",mo&&console.log("set input field value",Z.htmlField.value),this.context.isInXR){let e=this.context.arOverlayElement;e&&(Z.htmlField.style.width="0px",Z.htmlField.style.height="0px",e.append(Z.htmlField))}this.selectInputField()}}onDeselected(){Z.active===this&&(Z.active=null,mo&&console.log("Deselect",this.name,this),Z.htmlField&&(Z.htmlField.blur(),document.body.append(Z.htmlField),Z.htmlField.style.width="",Z.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&k.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(Z.active===this){if(mo&&console.log(e.code,e,Z.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}Z.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&k.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&Z.htmlField){if(this.textComponent.text!==Z.htmlField.value){mo&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=Z.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=Z.htmlField.value}}selectInputField(){Z.htmlField&&(Z.htmlField.setSelectionRange(Z.htmlField.value.length,Z.htmlField.value.length),Z.htmlField.focus())}},bt=Z;U(bt,"active",null),U(bt,"activeTime",-1),U(bt,"htmlField",null),P([S(Pe)],bt.prototype,"textComponent",2),P([S(Pe)],bt.prototype,"placeholder",2),P([S(_e)],bt.prototype,"onValueChanged",2),P([S(_e)],bt.prototype,"onEndEdit",2);import*as Ym from"three-mesh-ui";import*as oa from"three";var Km=(s=>(s[s.fr=0]="fr",s[s.ru=1]="ru",s[s.de=2]="de",s[s.es=3]="es",s[s.el=4]="el",s[s.nord=5]="nord",s[s.eng=6]="eng",s))(Km||{}),go=class extends je{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=Km[this.keymap||6];this.makeKeyboard(e)}onEnable(){this.addShadowComponent(this.keyboard)}onDisable(){this.removeShadowComponent()}keyboard=null;_lastKeyPressed;_lastKeyPressedStartTime=0;_lastKeyPressedTime=0;makeKeyboard(e){!e&&!navigator.language&&(e="en");let t=this.font?this.font:"arial",i=k.getComponent(this.gameObject,ot);if(!i){console.error("Missing rect transform, please add this component inside a canvas");return}let n={...i.getBasicOptions(),margin:this.margin||0,padding:this.padding||0,language:e,fontFamily:is+"/"+t+"-msdf.json",fontTexture:is+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new oa.Color(this.colors.keyboardBack),backspaceTexture:is+"/backspace.png",shiftTexture:is+"/shift.png",enterTexture:is+"/enter.png",borderRadius:this.borderRadius||0,autoLayout:!1},r=this.gameObject.scale;n.width*=this.gameObject.scale.x,n.height*=this.gameObject.scale.y,n.fontSize*=Math.max(r.x,r.y),this.keyboard=new Ym.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(o=>{o.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new oa.Color(this.colors.button),backgroundOpacity:1}}),o.setState("normal"),o.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new oa.Color(this.colors.hovered),backgroundOpacity:1}}),o.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new oa.Color(this.colors.selected),backgroundOpacity:1},onSet:()=>{let s=o.info.input,c=o.info.command;if(this._lastKeyPressed!==s)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedTime>.05)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedStartTime<.5||c=="switch"||c=="shift"||c=="switch-set"){this._lastKeyPressedTime=this.context.time.time;return}if(this._lastKeyPressedTime=this.context.time.time,this._lastKeyPressed=s,c)switch(c){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
270
- `);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else o.info.input!==void 0&&this.tryAppend(o.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var nn=class extends M{reverseArrangement=!1},bo=class extends nn{},vo=class extends nn{},yo=class extends nn{};var vr=class extends M{awake(){Ve.createIfNoneExists(this.context)}onEnable(){Ve.instance?.register(this)}onDisable(){Ve.instance?.unregister(this)}performRaycast(e=null){return null}},yr=class extends vr{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new Te,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},xo=class extends yr{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as Jm from"three";import{HTMLMesh as o0}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as s0}from"three/examples/jsm/interactive/InteractiveGroup.js";var wo=class extends M{id=null;keepAspect=!1;start(){if(!this.id||!this.context.mainCamera)return;let 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";let t=new s0(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new o0(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=La(this.gameObject).clone();Da(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let o=new Jm.Box3;o.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);let s=o.max.x-o.min.x,c=o.max.y-o.min.y;if(this.keepAspect){let l=s/c;s>c?i.scale.set(1/s,1/c/l,1):i.scale.set(1/s*l,1/c,1)}else i.scale.set(1/s,1/c,1);let d=this.gameObject.scale;i.scale.multiply(d)},1)}};var ps=class{};var sa=class extends M{toggleKey="p";update(){this.context.input.isKeyDown("p")&&this.context.domElement.classList.toggle("presentation-mode")}};import*as Zm from"three";import{Raycaster as c0,Vector3 as d0}from"three";import*as nc from"three";import{MeshLine as a0,MeshLineMaterial as l0}from"three.meshline";var eu=class{id=0;points=[];line=new a0;material;mesh;constructor(e,t){if(t&&(this.material=t.material),this.material||(this.material=this.defaultLineMaterial),t){let i=t.options;i&&Object.assign(this.material,i)}this.mesh=new nc.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=eu.wp;t.set(e.x,e.y,e.z);let i=this.mesh?.parent;return i&&(t=i.worldToLocal(t),e.x=t.x,e.y=t.y,e.z=t.z),this.points.push(e.x,e.y,e.z),this.line.setPoints(this.points),e}defaultLineMaterial=new l0({color:10066329,lineWidth:.01})},_o=eu;U(_o,"wp",new nc.Vector3);var xr=class extends M{startLine(e,t){let i=Math.random()*Number.MAX_SAFE_INTEGER;return this.internalStartLine(e,i,!0,t)}updateLine(e,t){let i=this.inFlight[e.id];if(!i)return;t.point&&(t.point=i.appendPoint(t.point));let n=this.buffer[e.id];n&&(t.point&&n.push(t.point.x,t.point.y,t.point.z),n.length>5&&(this.sendLineUpdate(i,!1,void 0,n),n.length=0))}endLine(e,t=!0){let i=this.inFlight[e.id];if(!i)return;this.finished.push(i),delete this.inFlight[e.id],t&&this.sendLineUpdate(i,!0,0);let n=this.buffer[e.id];if(n){delete this.buffer[e.id];let r=n;r.length=0,this.freeBuffer.push(r)}return i}getLine(e){return this.inFlight[e.id]}finished=[];inFlight=[];buffer={};freeBuffer=new Array;awake(){this.context.connection.beginListen("line-start",e=>{this.onEnsureLine(e.id,e.parentGuid)}),this.context.connection.beginListen("line-update",e=>{let t=this.onEnsureLine(e.guid,e.parentGuid);t&&e.points&&(e.startIndex<=0?t.points=e.points:e.startIndex>=t.points.length&&t.points.push(...e.points),t.line.setPoints(t.points),t.material.lineWidth=e.width,t.material.color.fromArray(e.color),e.finished===!0&&this.endLine({id:t.id},!1))})}onEnsureLine(e,t){if(this.inFlight[e])return this.inFlight[e];let i=k.findByGuid(t,this.context.scene);if(!!i)return this.internalStartLine(i,e,!1),this.inFlight[e]}internalStartLine(e,t,i=!0,n){let r=new _o(e??this.context.scene,n);r.id=t,this.inFlight[t]=r,i&&this.sendLineStart(r);let o;return this.freeBuffer.length<=0?o=new Array:o=this.freeBuffer.pop(),this.buffer[t]=o,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,i,n){if(e){let r={parentGuid:e.mesh.parent.guid,guid:e.id,points:n?[...n]:e.points,width:e.material.lineWidth,color:e.material.color.toArray(),startIndex:i!==void 0?i:e.points.length,finished:t};this.context.connection.send("line-update",r)}}};import{MeshLineMaterial as h0}from"three.meshline";var rc=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new d0,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},oc=class extends M{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=k.getComponent(this.gameObject,xr),this.lines||(this.lines=k.addNewComponent(this.gameObject,xr))),this.orbit=k.findObjectOfType(Je,this.context)??void 0,this._states.mouse=new rc;let e={};ie.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),ie.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),ie.addEventListener("select-end",(t,i)=>{e[t.controller.uuid]=!1;let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!0,!1)})}_states={};update(){this.orbit&&this._states.mouse&&this.orbit&&(this.orbit.enabled=!this._states.mouse.isDrawing);let e=this.context.input.getPointerPressedCount()>1,t=this.context.input.getPointerPositionRC(0);oc._raycaster.setFromCamera(t,this.context.mainCamera);let i=oc._raycaster.ray;this.updateLine("mouse",i,this.context.input.getPointerPressed(0),this.context.input.getPointerUp(0),e||this.context.input.isKeyPressed("Alt"))}updateLine(e,t,i,n,r=!1){let o=this._states[e];if(o||(this._states[e]=new rc,o=this._states[e]),n)o.isDrawing=!1,o.currentHandle&&(this.lines.endLine(o.currentHandle),o.currentHandle=null);else if(i){if(r)return o;let s=this.getHit(t),c=null,d=o.prevDistance;if(s)o.currentHandle||(o.maxDistance=s.distance),c=s.point,c.add(s.face.normal.multiplyScalar(.01)),o.prevDistance=s.distance;else if(o.maxDistance>0){let l=o.maxDistance;if(!o.currentHandle&&o.lastHit){let h=X(this.context.mainCamera);l=o.lastHit.distanceTo(h)}c=t.origin.add(t.direction.multiplyScalar(o.maxDistance)),o.prevDistance=o.maxDistance}if(c){if(!o.currentHandle){let l=o.lastParent??this.gameObject;this.addToPaintedObject&&s&&(l=s.object),o.lastParent=l,o.currentHandle=this.lines.startLine(l,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(o.prevDistance>o.maxDistance||Math.abs(d-o.prevDistance)>.2)){let l=o.maxDistance;c=t.origin.add(t.direction.multiplyScalar(l)),o.prevDistance=l}if(o.lastHit&&o.lastHit.distanceTo(c)<o.prevDistance*.01)return o;this.lines.updateLine(o.currentHandle,{point:c}),o.lastHit.copy(c)}o.isDrawing=o.currentHandle!==null}return o}_raycastOptions=new Te;getHit(e){(!this.colliders||this.colliders.length===0)&&(this.colliders=[this.gameObject]),this._raycastOptions.targets=this.colliders,this._raycastOptions.ray=e;let t=this.context.physics.raycast(this._raycastOptions);if(t.length>0){for(let i of t)if(!!k.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=rt.colorFromHashCode(rt.hashCode(this.context.connection.connectionId)):e=new Zm.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new h0({color:e,lineWidth:J.lerp(.005,.01,Math.random())})}},fs=oc;U(fs,"_raycaster",new c0);import{Object3D as u0}from"three";var ms=class extends M{asset;joinedRoomFunction;awake(){this.watchTabVisible(),this.joinedRoomFunction=this.onUserJoined.bind(this)}onEnable(){this.context.connection.beginListen("joined-room",this.joinedRoomFunction)}onDisable(){this.context.connection.stopListening("joined-room",this.joinedRoomFunction)}async onUserJoined(e){let t=await this.asset?.instantiateSynced({parent:this.gameObject},!0);if(t){let i=k.getComponent(t,xi);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=xi.all.length-1;t>=0;t--){let i=xi.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};P([S(Ye)],ms.prototype,"asset",2);var Jt=class extends M{static get all(){return Jt._all}static get local(){return Jt._local}static isLocalPlayer(e){return e instanceof u0?k.getComponentInParent(e,Jt)?.isLocalPlayer??!1:e instanceof wt?k.getComponentInParent(e.gameObject,Jt)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&Jt.local.push(this),Jt.all.push(this),this.context.connection.beginListen("user-left-room",e=>{if(e.userId===this.owner){this.doDestroy();return}})}start(){if(!this.owner||!this.context.connection.userIsInRoom(this.owner)){this.doDestroy();return}}doDestroy(){jo(this.gameObject,this.context.connection)}onDestroy(){if(Jt.all.splice(Jt.all.indexOf(this),1),this.isLocalPlayer){let e=Jt._local.indexOf(this);e>=0&&Jt._local.splice(e,1)}}},xi=Jt;U(xi,"_all",[]),U(xi,"_local",[]),P([ql(),S()],xi.prototype,"owner",2);gn[B]=!0;Ut[B]=!0;Jn[B]=!0;ct[B]=!0;zt[B]=!0;Vt[B]=!0;ae[B]=!0;Zn[B]=!0;vn[B]=!0;ki[B]=!0;Gr[B]=!0;De[B]=!0;he[B]=!0;Wt[B]=!0;yn[B]=!0;xn[B]=!0;er[B]=!0;qr[B]=!0;tr[B]=!0;di[B]=!0;Cn[B]=!0;hi[B]=!0;ui[B]=!0;or[B]=!0;_e[B]=!0;Xr[B]=!0;Qr[B]=!0;zi[B]=!0;Jr[B]=!0;It[B]=!0;Wi[B]=!0;qi[B]=!0;Et[B]=!0;Ct[B]=!0;We[B]=!0;pi[B]=!0;Tn[B]=!0;ji[B]=!0;Zr[B]=!0;$r[B]=!0;ar[B]=!0;Yt[B]=!0;fi[B]=!0;Je[B]=!0;lr[B]=!0;ro[B]=!0;to[B]=!0;io[B]=!0;no[B]=!0;rt[B]=!0;Ot[B]=!0;Yr[B]=!0;le[B]=!0;sr[B]=!0;Kr[B]=!0;Ui[B]=!0;oe[B]=!0;Rn[B]=!0;Sn[B]=!0;Pn[B]=!0;gi[B]=!0;mt[B]=!0;Xi[B]=!0;oo[B]=!0;so[B]=!0;dr[B]=!0;Qi[B]=!0;On[B]=!0;Kt[B]=!0;ut[B]=!0;ao[B]=!0;lo[B]=!0;hr[B]=!0;Ce[B]=!0;Ke[B]=!0;co[B]=!0;bi[B]=!0;kn[B]=!0;An[B]=!0;In[B]=!0;ur[B]=!0;Tt[B]=!0;Y[B]=!0;En[B]=!0;ue[B]=!0;Rt[B]=!0;rr[B]=!0;ie[B]=!0;it[B]=!0;pr[B]=!0;ho[B]=!0;_n[B]=!0;Pt[B]=!0;Ni[B]=!0;ft[B]=!0;we[B]=!0;vi[B]=!0;yi[B]=!0;xe[B]=!0;Di[B]=!0;Mn[B]=!0;uo[B]=!0;ps[B]=!0;po[B]=!0;ye[B]=!0;Zi[B]=!0;fr[B]=!0;mr[B]=!0;Yi[B]=!0;Ln[B]=!0;Dn[B]=!0;Ji[B]=!0;Ki[B]=!0;je[B]=!0;Hi[B]=!0;Dt[B]=!0;Fe[B]=!0;tn[B]=!0;Ve[B]=!0;gt[B]=!0;$i[B]=!0;en[B]=!0;br[B]=!0;bt[B]=!0;go[B]=!0;nn[B]=!0;bo[B]=!0;vo[B]=!0;yo[B]=!0;Xt[B]=!0;vr[B]=!0;yr[B]=!0;xo[B]=!0;Qt[B]=!0;fo[B]=!0;gr[B]=!0;ot[B]=!0;wo[B]=!0;Pe[B]=!0;sa[B]=!0;fs[B]=!0;_o[B]=!0;xr[B]=!0;ms[B]=!0;xi[B]=!0;j.add("AlignmentConstraint",gn);j.add("Animation",Ut);j.add("AnimationCurve",Jn);j.add("Animator",ct);j.add("AnimatorController",zt);j.add("AudioListener",Vt);j.add("AudioSource",ae);j.add("AvatarModel",Zn);j.add("AvatarLoader",vn);j.add("AxesHelper",ki);j.add("BasicIKConstraint",Gr);j.add("BoxHelperComponent",De);j.add("Camera",he);j.add("Collider",Wt);j.add("SphereCollider",yn);j.add("BoxCollider",xn);j.add("DeleteBox",er);j.add("Deletable",qr);j.add("DeviceFlag",tr);j.add("DragControls",di);j.add("DropListener",Cn);j.add("Duplicatable",hi);j.add("CallInfo",ui);j.add("EventListEvent",or);j.add("EventList",_e);j.add("EventTrigger",Xr);j.add("FlyControls",Qr);j.add("BoxGizmo",zi);j.add("GltfExportBox",Jr);j.add("GltfExport",It);j.add("GridHelper",Wi);j.add("GroundProjectedEnv",qi);j.add("Interactable",Et);j.add("UsageMarker",Ct);j.add("Light",We);j.add("LODModel",pi);j.add("LODGroup",Tn);j.add("LookAtConstraint",ji);j.add("NavMesh",Zr);j.add("NavMeshAgent",$r);j.add("NestedGltf",ar);j.add("Networking",Yt);j.add("OffsetConstraint",fi);j.add("OrbitControls",Je);j.add("ParticleSystemRenderer",lr);j.add("ParticleSystem",ro);j.add("MainModule",to);j.add("EmissionModule",io);j.add("ShapeModule",no);j.add("PlayerColor",rt);j.add("ReflectionProbe",Ot);j.add("FieldWithDefault",Yr);j.add("Renderer",le);j.add("MeshRenderer",sr);j.add("SkinnedMeshRenderer",Kr);j.add("RendererLightmap",Ui);j.add("Rigidbody",oe);j.add("ScreenCapture",Rn);j.add("ShadowCatcher",Sn);j.add("RemoteSkybox",Pn);j.add("SmoothFollow",gi);j.add("SpatialTriggerReceiver",mt);j.add("SpatialTrigger",Xi);j.add("SpectatorCamera",oo);j.add("SpringJoint",so);j.add("Sprite",dr);j.add("SpriteRenderer",Qi);j.add("SyncedCamera",On);j.add("SyncedRoom",Kt);j.add("SyncedTransform",ut);j.add("TestRunner",ao);j.add("TestSimulateUserData",lo);j.add("TransformGizmo",hr);j.add("VideoPlayer",Ce);j.add("Voip",Ke);j.add("VolumeParameter",co);j.add("VolumeComponent",bi);j.add("ToneMapping",kn);j.add("ColorAdjustments",An);j.add("VolumeProfile",In);j.add("Volume",ur);j.add("WebARSessionRoot",Tt);j.add("WebXR",Y);j.add("WebAR",En);j.add("AvatarMarker",ue);j.add("WebXRAvatar",Rt);j.add("TeleportTarget",rr);j.add("WebXRController",ie);j.add("AttachedObject",it);j.add("XRGrabModel",pr);j.add("XRGrabRendering",ho);j.add("XRRig",_n);j.add("VRUserState",Pt);j.add("WebXRSync",Ni);j.add("XRState",ft);j.add("XRFlag",we);j.add("AvatarBlink_Simple",vi);j.add("AvatarEyeLook_Rotation",yi);j.add("Avatar_POI",xe);j.add("Avatar_Brain_LookAt",Di);j.add("Avatar_MouthShapes",Mn);j.add("Avatar_MustacheShake",uo);j.add("__Ignore",ps);j.add("LogStats",po);j.add("RGBAColor",ye);j.add("PlayableDirector",Zi);j.add("SignalAsset",fr);j.add("SignalReceiverEvent",mr);j.add("SignalReceiver",Yi);j.add("AnimationTrackHandler",Ln);j.add("AudioTrackHandler",Dn);j.add("SignalTrackHandler",Ji);j.add("ControlTrackHandler",Ki);j.add("BaseUIComponent",je);j.add("UIRootComponent",Hi);j.add("Button",Dt);j.add("Canvas",Fe);j.add("CanvasGroup",tn);j.add("EventSystem",Ve);j.add("Graphic",gt);j.add("MaskableGraphic",$i);j.add("Image",en);j.add("RawImage",br);j.add("InputField",bt);j.add("Keyboard",go);j.add("LayoutGroup",nn);j.add("VerticalLayoutGroup",bo);j.add("HorizontalLayoutGroup",vo);j.add("GridLayoutGroup",yo);j.add("PointerEventData",Xt);j.add("Raycaster",vr);j.add("ObjectRaycaster",yr);j.add("GraphicRaycaster",xo);j.add("UIRaycastUtils",Qt);j.add("Size",fo);j.add("Rect",gr);j.add("RectTransform",ot);j.add("SpatialHtml",wo);j.add("Text",Pe);j.add("PresentationMode",sa);j.add("LinesDrawer",fs);j.add("LineInstanceHandler",_o);j.add("LinesManager",xr);j.add("PlayerSync",ms);j.add("PlayerState",xi);var $m=Oe,p0=D("debugtypestore");p0&&console.log(j);function eg(a,e){let i=Ec(a,e);return i!==void 0?i:null}async function tg(a,e,t,i=null,n){if(!t)return;let r=[],o=i;typeof o=="number"&&(o=new Ue(i));let s=new Po(t.scene);s.gltfId=e,s.context=a,s.gltf=t,s.nodeToObject=n?.nodeToObjectMap;let c=[];if(t.scenes)for(let d of t.scenes)await iu(s,d,c,r);if(t.children)for(let d of t.children)await iu(s,d,c,r);a.new_scripts_pre_setup_callbacks.push(()=>{for(let d of c)f0(d,s);if(o){tu(t,o);for(let d of t.scenes)tu(d,o)}})}function tu(a,e){if(e!==null&&!!a){if(a.guid=e.generateUUID(),a&&a.userData&&a.userData.components)for(let t of a.userData.components)t!==null&&(t.guid=e.generateUUID());if(a.children)for(let t of a.children)tu(t,e)}}var aa=[];async function iu(a,e,t,i){if(!e)return;let n=e.userData;if(n){let r=n.builtin_components;if(r&&r.length>0)for(let o of r)try{if(o===null)continue;let s=j.get(o.name);if(s!=null){let c=new s;c.sourceId=a.gltfId,Tr(c,o),Gn(e,c,!1),t.push({instance:c,compData:o,obj:e})}else $m&&console.debug("unknown component: "+o.name),aa.includes(o.name)||aa.push(o.name)}catch(s){console.error(o.name+" - "+s.message,s)}if(aa.length>0){let o=aa.join(", ");console.warn("unknown components: "+o),aa.length=0,Er()&&xs(`<strong>Unknown components in scene</strong>:
269
+ `)}}}applyShadowMaterial(){let e=R.getComponent(this.gameObject,$);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new Zb;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t),e.material=t}else{let t=e.material;t.color=this.shadowColor,t.opacity=this.shadowColor.alpha,this.applyMaterialOptions(t)}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}};C([x()],ci.prototype,"mode",2),C([x(ce)],ci.prototype,"shadowColor",2);import{RGBELoader as nv}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as iv}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as rv}from"three";var bp=I("debugautosync"),Cd=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new Td(e);return this._syncers[e.guid]=t,t}},vp=new Cd,Td=class{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};data={};_boundEvent;get networkingKey(){return this.comp.constructor.name}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving.bind(this));let t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}notifyChanged(e,t){this._isReceiving||(this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;let e=this.comp.context.connection;if(!e||!e.isConnected){for(let t in this.changedProperties)delete this.changedProperties[t];return}for(let t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(let t in this.changedProperties){let n=this.changedProperties[t];delete this.changedProperties[t],this.data[t]=n}e.send(this.networkingKey,this.data)}onHandleReceiving(e){if(!this._isInit||!this.comp)return;let t=e.guid;if(!(t&&t!==this.comp.guid)){bp&&console.log("RECEIVED",this.comp.name,this.comp.guid,e);try{this._isReceiving=!0;for(let n in e){if(n==="guid")continue;let i=e[n];this.comp[n]=i}}catch(n){console.error(n)}finally{this._isReceiving=!1}}}};function ev(o,e){let t=e!==o;if(!t&&o&&e){if(Array.isArray(o)&&Array.isArray(e))t=!0;else if(typeof o=="object"&&typeof e=="object"){for(let n of Object.keys(o))if(o[n]!==e[n]){t=!0;break}}}return t}function tv(o){if(o.__autoPropertySyncHandler)return o.__autoPropertySyncHandler;let e=vp.getOrCreateSyncer(o);return e?.init(o),o.__autoPropertySyncHandler=e,e}var qa=function(o){return function(e,t){let n=null,i=o?e[o]:void 0,r=e,s=r.__internalAwake;bp&&console.log(t);let a=t+"k__BackingField";r.__internalAwake=function(){if(this[a]!==void 0)return;this[a]=this[t],s.call(this),n=vp.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let l=this[a];this[a]=d,ev(d,l)&&i?.call(this,d,l)!==!1&&tv(this)?.notifyChanged(t,d)},get:function(){return this[a]},configurable:!0,enumerable:!0}),n?.init(this)}}};var di=class extends O{url;allowDrop=!0;_loader;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.isInXR||(this.context.scene.environment=this._prevEnvironment,this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents()}async setSkybox(e){if(!e)return;if(!e?.endsWith(".hdr")&&!e.endsWith(".exr")&&console.warn("Potentially invalid skybox url",this.url,"on",this.name),!this._loader){let i=e.endsWith(".exr");this._loader=i?new iv:new nv}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=rv,this._prevBackground=this.context.scene.background,this._prevEnvironment=this.context.scene.environment,console.log("Set skybox",this.url),this.context.scene.environment=t,this.context.scene.background=t,this._prevLoadedEnvironment=t;let n=e.lastIndexOf("/");t.name=e.substring(n>=0?n+1:0)}dragOverEvent;dropEvent;registerDropEvents(){this.dragOverEvent||(this.dragOverEvent=e=>{if(!!this.allowDrop&&!!e.dataTransfer)for(let t of e.dataTransfer.types)t==="text/uri-list"&&e.preventDefault()},this.dropEvent=e=>{if(!!this.allowDrop&&(e.preventDefault(),!!e.dataTransfer)){for(let t of e.dataTransfer.types)if(t==="text/uri-list"){let n=e.dataTransfer.getData(t);console.log(t,n);let i=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(n)?.groups?.name;if(i||(i=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(n)?.groups?.name),console.log(i),i){let r="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+i+"_1k.exr";this.setSkybox(r)}else console.warn("Could not resolve skybox name from dropped url",n)}}},this.context.domElement.addEventListener("dragover",this.dragOverEvent),this.context.domElement.addEventListener("drop",this.dropEvent))}unregisterDropEvents(){!this.dragOverEvent||(this.context.domElement.removeEventListener("dragover",this.dragOverEvent),this.context.domElement.removeEventListener("drop",this.dropEvent))}};C([qa("setSkybox"),x()],di.prototype,"url",2),C([x()],di.prototype,"allowDrop",2);import*as So from"three";import{Object3D as ov}from"three";var Rd=class extends O{target=null;followFactor=.1;rotateFactor=.1;flipForward=!1;_firstUpdate=!0;onEnable(){let e=R.getComponentInChildren(this.gameObject,ie);e&&e.cam&&(e.gameObject.position.set(0,0,0),e.cam.position.set(0,0,0),e.gameObject.quaternion.identity(),e.cam.quaternion.setFromEuler(new So.Euler(0,Math.PI,0)))}onBeforeRender(){this.followFactor<=0||this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){let t=B(this.target),n=this._firstUpdate||e?1:W.clamp01(this.context.time.deltaTime*this.followFactor);this.worldPosition=this.worldPosition.lerp(t,n)}if(this.rotateFactor>0){let t=me(this.target);this.flipForward&&t.premultiply(Rd._invertForward);let n=this._firstUpdate||e?1:W.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,n)}this._firstUpdate=!1}}},Jt=Rd;j(Jt,"_invertForward",new So.Quaternion().setFromAxisAngle(new So.Vector3(0,1,0),Math.PI)),C([x(ov)],Jt.prototype,"target",2);import{Layers as Ep}from"three";var gs=I("debugspatialtrigger"),yp=new Ep,_p=new Ep;function sv(o,e){return yp.mask=o,_p.mask=e,yp.test(_p)}var et=class extends O{triggerMask=0;onEnter;onStay;onExit;start(){gs&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of Pn.triggers)sv(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){let t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(let e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){gs&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){gs&&console.log("EXIT TRIGGER",this.name,e.name,this,e),e.raiseOnExitEvent(this),this.onExit?.invoke(this,e)}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke(this,e)}};C([x()],et.prototype,"triggerMask",2),C([x(he)],et.prototype,"onEnter",2),C([x(he)],et.prototype,"onStay",2),C([x(he)],et.prototype,"onExit",2);var bs=class extends O{triggerMask;boxHelper;start(){gs&&console.log(this.name,this.triggerMask,this)}onEnable(){bs.triggers.push(this),this.boxHelper||(this.boxHelper=R.addNewComponent(this.gameObject,Ce),this.boxHelper?.showHelper(null,gs))}onDisable(){bs.triggers.splice(bs.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof et&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof et&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof et&&t.onExitTrigger(this)},!1)}},Pn=bs;j(Pn,"triggers",[]),C([x()],Pn.prototype,"triggerMask",2);import*as Vi from"three";var bt=I("debugspectator"),Pr=class extends O{cam=null;_mode=0;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){if(this._handler){let t=this._handler.currentTarget?.userId,n=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&n?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),R.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),R.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.localId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new Pd(this.context,this),this._networking=new Id(this.context,this),this._networking.awake(),R.setActive(this.gameObject,!1),this.cam=R.getComponent(this.gameObject,ie),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Sd(this.context,this.cam,this)),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),U.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),U.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),U.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.orbit=R.getComponent(this.context.mainCamera,Fe)}onDestroy(){this.stopSpectating(),U.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),U.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),U.removeEventListener("xrStopped",this.eventSub_WebXREndEvent),this._handler?.destroy(),this._networking.destroy()}isSupportedPlatform(){let e=window.navigator.userAgent,t=/Windows|MacOS/.test(e),n=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return t&&!n}onXRSessionRequestStart(e){!this.isSupportedPlatform()||R.setActive(this.gameObject,!0)}onXRSessionStart(e){!this.isSupportedPlatform()||(bt&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){this.context.removeCamera(this.cam),R.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,"headset"),this.target=this.context.players.getPlayerView(this.localId)),bt&&console.log("Follow self",this.target)}onAfterRender(){if(!this.cam)return;let e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting&&!this._handler?.currentTarget)return;this._handler?.update(this._mode);let n=e.getRenderTarget(),i=null;if(!n){if(!e.state.bindFramebuffer||!e.state.bindXRFramebuffer)return;i=e._framebuffer,e.state.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();let r=this.context.mainCameraComponent;if(r){let c=r.backgroundColor;c&&e.setClearColor(c,c.alpha),this.cam.backgroundColor=c,this.cam.clearFlags=r.clearFlags,this.cam.nearClipPlane=r.nearClipPlane,this.cam.farClipPlane=r.farClipPlane}else e.setClearColor(new Vi.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;let s=this.cam?.cam;this.context.updateAspect(s);let a=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,s),e.xr.isPresenting=a,e.xr.enabled=t,n?e.setRenderTarget(n):e.state.bindXRFramebuffer(i),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){let e=this._mode===0;for(let t of re.instances)if(t.avatar&&"isLocalAvatar"in t.avatar){let n=4294967295;this.isSpectatingSelf&&(n=e&&t.avatar.isLocalAvatar?8:16);let i=t.avatar.flags;if(!i)continue;for(let r of i)r.UpdateVisible(n)}}resetAvatarFlags(){for(let e of re.instances)if(e.avatar&&"flags"in e.avatar){let t=e.avatar.flags;if(!t)continue;for(let n of t)e.avatar?.isLocalAvatar?n.UpdateVisible(8):n.UpdateVisible(16)}}},Sd=class{context;cam;spectator;follow;target;view;currentObject;get currentTarget(){return this.view}constructor(e,t,n){this.context=e,this.cam=t,this.spectator=n}set(e){let t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=R.addNewComponent(this.cam.gameObject,Jt)),this.target||(this.target=new Vi.Object3D),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,bt&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){bt&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){this.target?.removeFromParent(),this.follow&&R.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){bt&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(bt&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));let t=this.context.mainCamera;t&&(this.cam.cam.near!==t.near||this.cam.cam.far!==t.far)&&(this.cam.cam.near=t.near,this.cam.cam.far=t.far,this.cam.cam.updateProjectionMatrix());let n=this.follow?.target;if(!(!n||!this.follow)){switch(e){case 0:this.view?.viewDevice!=="browser"?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),n.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,n.position.set(0,.5,1.5);break}this.follow.flipForward=!1,this.view?.viewDevice!=="browser"?n.quaternion.copy(av):n.quaternion.identity()}}},av=new Vi.Quaternion().setFromAxisAngle(new Vi.Vector3(0,1,0),Math.PI),Pd=class{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),window.addEventListener("keydown",i=>{i.key==="Escape"&&this.spectator.stopSpectating()});let n=0;this.context.input.addEventListener("pointerdown",i=>{n=this.context.time.time}),this.context.input.addEventListener("pointerup",i=>{let r=this.context.time.time-n;r>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&r<.3&&this.trySelectObject()})}trySelectObject(){let e=new ge;e.setMask(16777215);let t=this.context.physics.raycast(e);if(bt&&console.log(...t),t?.length)for(let n of t){if(n.distance<.2)continue;let i=n.object,r=R.getComponentInParent(i,re),s=r?.connectionId;if(s){let a=this.context.players.getPlayerView(s);this.spectator.target=a,bt&&console.log("spectate",s,r);break}}}},Od=class{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,n){this.guid=e,this.targetUserId=t,this.stoppedFollowing=n}},kd=class{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}},Id=class{followers=[];context;spectator;_followerEventMethod;_requestFollowMethod;_joinedRoomMethod;constructor(e,t){this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen("joined-room",this._joinedRoomMethod),document.addEventListener("keydown",e=>{e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0)})}destroy(){this.context.connection.stopListening("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListening("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListening("joined-room",this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(bt&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){let n=e?.userId===void 0,i=n?t:e?.userId,r=new Od(this.context.connection.connectionId,i,n);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(bt&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();let t=e?void 0:this.context.connection.connectionId,n=new kd(this.spectator,t);this.context.connection.send("spectator-request-follow",n)}}onUserJoinedRoom(){I("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){let t=e.targetUserId,n=e.guid;if(bt&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){let i=this.followers.indexOf(n);i!==-1&&(this.followers.splice(i,1),this.removeDisconnectedFollowers(),console.log(n,"unfollows you",this.followers.length))}else this.followers.includes(n)||(this.followers.push(n),this.removeDisconnectedFollowers(),console.log(n,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){let t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}_lastRequestFollowUser;onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{let t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return bt&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}_enforceFollowInterval;enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(bt&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}};import*as vt from"three";import{Material as lv,Texture as cv}from"three";var Ni=class{texture;triangles;uv;vertices;_geometry};C([x(cv)],Ni.prototype,"texture",2);var Ya=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new vt.BufferGeometry;e._geometry=t;let n=new Float32Array(e.triangles.length*3),i=new Float32Array(e.triangles.length*2);for(let r=0;r<e.triangles.length;r+=1){let s=e.triangles[r];n[r*3]=-e.vertices[s].x,n[r*3+1]=e.vertices[s].y,n[r*3+2]=0;let a=e.uv[s];i[r*2]=a.x,i[r*2+1]=1-a.y}return t.setAttribute("position",new vt.BufferAttribute(n,3)),t.setAttribute("uv",new vt.BufferAttribute(i,2)),t}},On=class extends O{drawMode=0;size={x:1,y:1};color;sharedMaterial;get sprite(){return this._sprite}set sprite(e){e!==this._sprite&&(this._sprite=e,this.updateSprite())}_sprite;_currentSprite;awake(){this._currentSprite=void 0}start(){this.drawMode===2&&console.warn("Tiled draw mode is not supported yet",this),this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(){if(!!this.__didAwake&&!!this.sprite&&!!this.sharedMaterial){if(this._currentSprite)this._currentSprite.geometry=Ya.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new vt.MeshBasicMaterial({color:16777215,side:vt.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new vt.Color),e.color.copy(this.color),e.opacity=this.color.alpha),e.alphaTest=.5,this.sprite.texture&&!e.wireframe){let t=this.sprite.texture;e.map=t}this._currentSprite=new vt.Mesh(Ya.getOrCreateGeometry(this.sprite),e)}this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite))}}};C([x()],On.prototype,"drawMode",2),C([x(ce)],On.prototype,"color",2),C([x(lv)],On.prototype,"sharedMaterial",2);var yt=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new yt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new yt).__init(e.readInt32(e.position())+e.position(),e)}userId(e){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){let e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){let t=this.bb.__offset(this.bb_pos,10);return t?(e||new ve).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new ve).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}};import{Object3D as dv}from"three";var Ka="SCAM";so(Ka,yt.getRootAsSyncedCameraModel);var _t=new rt,Md=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){_t.clear();let n=_t.createString(this.guid),i=_t.createString(this.userId);yt.startSyncedCameraModel(_t),yt.addGuid(_t,n),yt.addUserId(_t,i);let r=B(e),s=Ls(e);yt.addPos(_t,ve.createVec3(_t,r.x,r.y,r.z)),yt.addRot(_t,ve.createVec3(_t,s.x,s.y,s.z));let a=yt.endSyncedCameraModel(_t);_t.finish(a,Ka),t.sendBinary(_t.asUint8Array())}}},Ja=class extends O{getCameraObject(e){let t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=null;async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinrary(Ka,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Ka,this._receiveCallback)}update(){for(let i in this.remoteCams){let r=this.remoteCams[i],s=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||s>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,s),r?.obj&&R.destroy(r.obj),delete this.remoteCams[i],r&&delete this.userToCamMap[r.userId],Ja.instances.push(r),this.context.players.removePlayerView(r.userId,"browser");continue}}if(U.IsInWebXR)return;let e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new Md(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let t=B(e),n=me(e);(t.distanceTo(this._lastWorldPosition)>.001||n.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(n),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,"browser"))}onReceivedRemoteCameraInfoBin(e){let t=e.guid();if(!t)return;let n=e.userId();if(!n||!this.context.connection.userIsInRoom(n)||!this.cameraPrefab)return;let i=this.remoteCams[t];if(!i)if("isObject3D"in this.cameraPrefab){let c=new Ie;c.context=this.context;let d=R.instantiate(this.cameraPrefab,c);i=this.remoteCams[t]={obj:d,lastUpdate:this.context.time.realtimeSinceStartup,userId:n},i.obj.visible=!0,this.gameObject.add(d),this.userToCamMap[n]=t,Ja.instances.push(i);let l=R.getOrAddComponent(d,re);l.connectionId=n,l.avatar=d}else return;let r=i.obj;this.context.players.setPlayerView(n,r,"browser"),i.lastUpdate=this.context.time.realtimeSinceStartup,ne.markDirty(r);let s=e.pos();s&&Kr(r,s.x(),s.y(),s.z());let a=e.rot();a&&js(r,a.x(),a.y(),a.z())}},ui=Ja;j(ui,"instances",[]),C([x([dv,je])],ui.prototype,"cameraPrefab",2);var Dd="view",wp=I("debugsyncedroom"),It=class extends O{roomName;urlParameterName;joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=I(Dd);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){let n=I(this.urlParameterName);if(n&&typeof n=="string"){t=!0;let i=cu(n);this.roomName=i}else if(this.joinRandomRoom&&(console.log("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(console.log("generate room name"),this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?(wp&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(wp&&console.error('Missing room name on "'+this.name+'". Make sure this is correctly configured in Unity',this.context.connection.isDebugEnabled?this:""),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.context.connection.joinRoom(this.roomName),!0)}_lastPingTime=0;_lastRoomTime=-1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.send("ping",{time:this.context.time.time})),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?(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you)"))}get currentRoomName(){let e=I(Dd);return e||I(this.urlParameterName)}setRandomRoomUrlParameter(){let e=vl(),t=this.generateRoomName();I(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),su(t,e)}generateRoomName(){return lu()+"_"+au(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){let e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Dd,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};C([x()],It.prototype,"roomName",2),C([x()],It.prototype,"urlParameterName",2),C([x()],It.prototype,"joinRandomRoom",2),C([x()],It.prototype,"requireRoomParameter",2),C([x()],It.prototype,"autoRejoin",2);function xp(){let o=I("testwindowcount")||0;o&&o>0&&uv(o)}function uv(o){if(I("testwindow"))return null;let e=new URL(window.location.href);Qr(e.searchParams,yo,1),Qr(e.searchParams,"testwindow",1);let t=e.toString(),n=[];window.onbeforeunload=()=>{for(let c of n)c.close()};let i=.05,r=128,s=0,a=0;for(let c=0;c<o;c++){s*r+r*.01>=window.innerWidth&&(a+=1,s=0);let d=s*(r*(1+i))+window.screenLeft,l=a*(r*(1+i))+window.screenTop+90+60*a;s+=1;let u=window.open(t,"test window "+c,`popup=yes width=${r} height=${r} top=${l} left=${d}`);if(!u){console.warn("Failed to open window");continue}n.push(u),u.onload=()=>{u.onbeforeunload=()=>{for(let h=0;h<n.length;h++){let b=n[h];b!==u&&b.close()}n.length=0}}}return n}import{Vector3 as pv}from"three";var Or=class extends O{awake(){xp()}},kr=class extends O{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(go,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new Za(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 rt(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let n=Hc(this.context.connection.connectionId,this);this.context.connection.sendBinary(n)}}else if(this.models)for(let e=0;e<this.models.length;e++){let t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}},Za=class{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)}update(e,t){let n=e.worldPosition;this.position.x=n.x,this.position.y=n.y,this.position.z=n.z;let i=e.worldQuaternion;if(this.rotation.x=i.x,this.rotation.y=i.y,this.rotation.z=i.z,this.rotation.w=i.w,this.fast=!1,t){let r=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=r.x,this.velocity.y=r.y,this.velocity.z=r.z}}};j(Za,"temp",new pv);import{MathUtils as fv}from"three";import{TransformControls as mv}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as gv}from"three/examples/jsm/controls/OrbitControls";var Wi=class extends O{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!rn||!this.context.mainCamera||(this.control=new mv(this.context.mainCamera,this.context.renderer.domElement),this.control.visible=!0,this.control.enabled=!0,this.control.getRaycaster().layers.set(2),this.control.size=.6,this.control.traverse(e=>{let t=e;if(t.layers.set(2),t){let n=t.material;n&&(n.opacity=.3)}}))}start(){if(this.context.mainCamera){let e=R.getComponentInParent(this.context.mainCamera,gv)??void 0;this.orbit=e}}changeEventListener;windowKeyDownListener;windowKeyUpListener;onEnable(){this.control&&(this.context.scene.add(this.control),this.control.attach(this.gameObject)),this.changeEventListener=this.onControlChangedEvent.bind(this),this.control?.addEventListener("dragging-changed",this.changeEventListener),this.attachWindowEvents()}onDisable(){this.control?.removeFromParent(),this.changeEventListener&&this.control?.removeEventListener("dragging-changed",this.changeEventListener)}onControlChangedEvent(e){let t=this.orbit;if(t&&(t.enabled=!e.value),e.value){let n=R.getComponentInParent(this.gameObject,Je);n&&n.requestOwnership()}}attachWindowEvents(){let e=this.control;!e||(this.windowKeyDownListener||(this.windowKeyDownListener=t=>{switch(t.keyCode){case 81:e.setSpace(e.space==="local"?"world":"local");break;case 16:e.setTranslationSnap(100),e.setRotationSnap(fv.degToRad(15)),e.setScaleSnap(.25);break;case 87:e.setMode("translate");break;case 69:e.setMode("rotate");break;case 82:e.setMode("scale");break;case 187:case 107:e.setSize(e.size+.1);break;case 189:case 109:e.setSize(Math.max(e.size-.1,.1));break;case 88:e.showX=!e.showX;break;case 89:e.showY=!e.showY;break;case 90:e.showZ=!e.showZ;break;case 32:e.enabled=!e.enabled;break}}),this.windowKeyUpListener||(this.windowKeyUpListener=t=>{switch(t.keyCode){case 16:e.setTranslationSnap(null),e.setRotationSnap(null),e.setScaleSnap(null);break}}),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener))}};C([x()],Wi.prototype,"isGizmo",2);import{LinearToneMapping as Cp,ACESFilmicToneMapping as bv,ReinhardToneMapping as vv}from"three";var $a=I("debugvolume"),Rp=(n=>(n[n.None=0]="None",n[n.Neutral=1]="Neutral",n[n.ACES=2]="ACES",n))(Rp||{}),Ir=class{overrideState=!1;value=0},Zt=class{active=!1;parameters},pi=class extends Zt{mode;get isToneMapping(){return!0}},fi=class extends Zt{postExposure};function yv(o){return"mode"in o?pi:"postExposure"in o?fi:Zt}var Tp=Symbol("volumeprofile"),hi=class{components;apply(e){this.onUpdate(e,!1)}unapply(e){this.onUpdate(e,!0)}onUpdate(e,t){if(!this.components)return;let n=e.renderer,r=n[Tp]!==void 0;if(t){if(!r)return}else n[Tp]=this;for(let s of this.components)if(s instanceof pi){let a=s;if(!s.active||t){e.renderer.toneMapping=Cp;continue}switch($a&&console.log("VOLUME:",Rp[a.mode?.value??0]),a.mode?.value??0){case 0:e.renderer.toneMapping=Cp;break;case 1:e.renderer.toneMapping=vv;break;case 2:e.renderer.toneMapping=bv;break}}else if(s instanceof fi){let a=s;$a&&console.log(a.postExposure);let c=Math.pow(2,a.postExposure?.value??0),d=a.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=d?c:1}}};C([x([o=>yv(o),Zt])],hi.prototype,"components",2);var zi=class extends O{sharedProfile;awake(){$a&&(console.log(this),console.log("Press P to toggle post processing"),window.addEventListener("keydown",e=>{e.key==="p"&&(console.log("Toggle volume: "+this.name,!this.enabled),this.enabled=!this.enabled)}))}onEnable(){$a&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};C([x(hi)],zi.prototype,"sharedProfile",2);import{Vector3 as _v}from"three";var Xi=class{guid;dontSave=!0;userId;point={x:0,y:0,z:0};source={x:0,y:0,z:0};target;update(e,t,n,i=void 0){this.userId=e.connection.connectionId,this.point.x=t.x,this.point.y=t.y,this.point.z=t.z,this.source.x=n.x,this.source.y=n.y,this.source.z=n.z,this.target=i}},Mr=class extends O{prefab=null;_grabModels=[];_grabModelsUpdateTime=[];_addOrUpdateSub=null;_endSub=null;_freeSub=null;_instances={};awake(){this.prefab&&(this.prefab.visible=!1)}onEnable(){this._addOrUpdateSub=this.context.connection.beginListen("xr-grab-visual-start-or-update",this.onRemoteGrabStartOrUpdate.bind(this)),this._endSub=this.context.connection.beginListen("xr-grab-visual-end",this.onRemoteGrabEnd.bind(this)),this._freeSub=Ve.AddEventListener("WillFree",this.onAttachedObjectFree.bind(this))}onDisable(){this.context.connection.stopListening("xr-grab-visual-start-or-update",this._addOrUpdateSub),this.context.connection.stopListening("xr-grab-visual-end",this._endSub),Ve.RemoveEventListener("WillFree",this._freeSub)}addOrUpdateGrab(e){this.context.connection.send("xr-grab-visual-start-or-update",e,2)}endGrab(e){this.context.connection.send("xr-grab-visual-end",e,2)}onRemoteGrabStartOrUpdate(e){if(!this.prefab)return;let t=this._instances[e.guid];if(!t){let n=R.instantiate(this.prefab);if(n.visible=!0,this._instances[e.guid]={instance:n,model:e},e.userId){let i=R.getComponentsInChildren(n,We);if(i?.length>0)for(let r of i)r.assignUserColor(e.userId)}return}t.model=e}onRemoteGrabEnd(e){if(!e)return;let t=e.guid;this._instances[t]&&(R.destroy(this._instances[t].instance),delete this._instances[t])}onAttachedObjectFree(e){if(this._grabModels.length<=0)return;let t=this._grabModels[0];this.updateModel(t,e),this.endGrab(t)}onBeforeRender(){if(this.updateRendering(),!!this.prefab&&(this.prefab.visible=!1,this.context.time.frameCount%10===0))for(let e=0;e<Ve.Current.length;e++){let t=Ve.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new Xi),this._grabModelsUpdateTime.push(0)),this._grabModelsUpdateTime[e]=this.context.time.time;let n=this._grabModels[e];this.updateModel(n,t),this.addOrUpdateGrab(n)}}updateModel(e,t){if(!t.controller||!t.selected)return;e.guid=t.grabUUID;let n=t.selected.guid;e.update(this.context,t.grabPoint,t.controller.worldPosition,n)}temp=new _v;updateRendering(){let e=this.context.time.deltaTime/.5;for(let t in this._instances){let{instance:n,model:i}=this._instances[t];if(!n||!i)continue;let{point:r}=i,s=B(n);this.temp.set(r.x,r.y,r.z),s.lerp(this.temp,e),J(n,s)}}};import{Object3D as Ev}from"three";var $t=class extends O{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=R.getComponentInParent(this.gameObject,ue)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(let t of this.eyes)t&&(t.visible=this.eyesOpen)}}};C([x(Ev)],$t.prototype,"eyes",2),C([x()],$t.prototype,"lastBlinkTime",2),C([x()],$t.prototype,"blinkLength",2),C([x()],$t.prototype,"eyesOpen",2);import*as el from"three";import{Object3D as Ad}from"three";var Ld=class extends O{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=R.getComponentInParent(this.gameObject,gn)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=R.addNewComponent(this.gameObject,gn)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new el.Vector3;currentTargetPoint=new el.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let n=B(e);this.currentTargetPoint.lerp(n,this.context.time.deltaTime/.1);let i=B(this.head),r=this.vec.copy(this.currentTargetPoint).sub(i).normalize();if(r.length()<.1)return;let s=Ld.forward;if(s.set(0,0,1),s.applyQuaternion(me(this.head)),s.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},en=Ld;j(en,"forward",new el.Vector3(0,0,1)),C([x(Ad)],en.prototype,"head",2),C([x(Ad)],en.prototype,"eyes",2),C([x(Ad)],en.prototype,"target",2);import{Object3D as Sp}from"three";var wv=I("debugmouth"),mi=class extends O{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=R.findObjectOfType(He,this.context),this.marker||(this.marker=R.getComponentInParent(this.gameObject,re))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){wv&&(e=null);return}let t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;let t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(!!e){e!=this.idle?this.idle.map(n=>n.visible=!1):this.talking.map(n=>n.visible=!1);for(let n=0;n<e.length;n++){let i=e[n];i&&(i.visible=n===t)}}}};C([x(Sp)],mi.prototype,"idle",2),C([x(Sp)],mi.prototype,"talking",2);var Dr=class extends O{voip=null;marker=null;_startPosition=null;awake(){this.voip=R.findObjectOfType(He,this.context),this.marker=R.getComponentInParent(this.gameObject,re)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;let e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let n=t/100;this.gameObject.position.y=this._startPosition.y+n*.07}};var Ud={};iu(Ud,{AlignmentConstraint:()=>Zn,Animation:()=>dn,AnimationCurve:()=>ki,AnimationTrackHandler:()=>gi,Animator:()=>qe,AnimatorController:()=>Ct,AttachedObject:()=>Ve,AudioListener:()=>Rt,AudioSource:()=>Z,AudioTrackHandler:()=>bi,AvatarBlink_Simple:()=>$t,AvatarEyeLook_Rotation:()=>en,AvatarLoader:()=>ei,AvatarMarker:()=>re,AvatarModel:()=>Ii,Avatar_Brain_LookAt:()=>gn,Avatar_MouthShapes:()=>mi,Avatar_MustacheShake:()=>Dr,Avatar_POI:()=>de,AxesHelper:()=>hn,BaseUIComponent:()=>Te,BasicIKConstraint:()=>mr,BoxCollider:()=>ni,BoxGizmo:()=>wn,BoxHelperComponent:()=>Ce,Button:()=>Et,CallInfo:()=>Qt,Camera:()=>ie,Canvas:()=>Pe,CanvasGroup:()=>jn,Collider:()=>lt,ColorAdjustments:()=>fi,ControlTrackHandler:()=>In,Deletable:()=>br,DeleteBox:()=>Di,DeviceFlag:()=>Ai,DragControls:()=>zt,DropListener:()=>si,Duplicatable:()=>Xt,EmissionModule:()=>Tr,EventList:()=>he,EventListEvent:()=>Fi,EventSystem:()=>Me,EventTrigger:()=>vr,FieldWithDefault:()=>_r,FlyControls:()=>yr,GltfExport:()=>gt,GltfExportBox:()=>wr,Graphic:()=>tt,GraphicRaycaster:()=>Gr,GridHelper:()=>Rn,GridLayoutGroup:()=>Ur,GroundProjectedEnv:()=>Sn,HorizontalLayoutGroup:()=>Br,Image:()=>Ln,InputField:()=>nt,Interactable:()=>ct,Keyboard:()=>Hr,LODGroup:()=>ai,LODModel:()=>qt,LayoutGroup:()=>Hn,Light:()=>De,LogStats:()=>Ar,LookAtConstraint:()=>bn,MainModule:()=>Cr,MaskableGraphic:()=>An,MeshCollider:()=>Mi,MeshRenderer:()=>Bi,NestedGltf:()=>Ui,Networking:()=>kt,ObjectRaycaster:()=>Zi,OffsetConstraint:()=>Yt,OrbitControls:()=>Fe,ParticleSystem:()=>Sr,ParticleSystemRenderer:()=>Gi,PlayableDirector:()=>Dn,PlayerColor:()=>We,PointerEventData:()=>Pt,RGBAColor:()=>ce,RawImage:()=>Ki,Raycaster:()=>Ji,Rect:()=>Yi,RectTransform:()=>ze,ReflectionProbe:()=>mt,RemoteSkybox:()=>di,Renderer:()=>$,RendererLightmap:()=>xn,Rigidbody:()=>K,ScreenCapture:()=>li,ShadowCatcher:()=>ci,ShapeModule:()=>Rr,SignalAsset:()=>Qi,SignalReceiver:()=>kn,SignalReceiverEvent:()=>qi,SignalTrackHandler:()=>Mn,Size:()=>Lr,SkinnedMeshRenderer:()=>Er,SmoothFollow:()=>Jt,SpatialHtml:()=>Vr,SpatialTrigger:()=>Pn,SpatialTriggerReceiver:()=>et,SpectatorCamera:()=>Pr,SphereCollider:()=>ti,Sprite:()=>Ni,SpriteRenderer:()=>On,SyncedCamera:()=>ui,SyncedRoom:()=>It,SyncedTransform:()=>Je,TeleportTarget:()=>Hi,TestRunner:()=>Or,TestSimulateUserData:()=>kr,Text:()=>ye,ToneMapping:()=>pi,TransformGizmo:()=>Wi,UIRaycastUtils:()=>Ot,UIRootComponent:()=>yn,UsageMarker:()=>dt,VRUserState:()=>ft,VerticalLayoutGroup:()=>Fr,VideoPlayer:()=>fe,Voip:()=>He,Volume:()=>zi,VolumeComponent:()=>Zt,VolumeParameter:()=>Ir,VolumeProfile:()=>hi,WebAR:()=>oi,WebARSessionRoot:()=>ut,WebXR:()=>U,WebXRAvatar:()=>ht,WebXRController:()=>q,WebXRSync:()=>En,XRFlag:()=>ue,XRGrabModel:()=>Xi,XRGrabRendering:()=>Mr,XRRig:()=>ri,XRState:()=>$e,__Ignore:()=>Mo});var xv=I("logstats"),Ar=class extends O{onEnable(){console.log(this),xv&&this.startCoroutine(this.run(),4)}*run(){for(;this.enabled;){let e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}};import*as kp from"three";var Qi=class{guid},qi=class{signal;reaction;$serializedTypes={signal:Qi,reaction:he}},kn=class extends O{events;start(){console.log(this)}invoke(e){if(!this.events||!Array.isArray(this.events))return;let t=typeof e=="object"?e.guid:e;for(let n of this.events)if(n.signal.guid===t)try{if(n.reaction){if(!n.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",n,this);continue}}else{console.warn("Missing reaction for signal",n,this);continue}n.reaction.invoke()}catch(i){console.error(i)}}};C([x(qi)],kn.prototype,"events",2);import*as Y from"three";import{Quaternion as Cv,Vector3 as Tv}from"three";var Po=I("debugtimeline"),Oo=class{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(!!this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(let t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,n,i=!0){if(t<0||t>=n.length)return 0;let r=n[t];if(i||e>=r.start&&e<=r.end){let s=1,a=!1;return r.easeInDuration>0&&(s*=Math.min((e-r.start)/r.easeInDuration,1)),r.easeOutDuration>0&&!a&&(s*=Math.min((r.end-e)/r.easeOutDuration,1)),s}return 0}},jd=class{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){let t=e.getClip();this.clip=t;let n=e.getRoot(),i=n.name+".position",r=n.name+".quaternion";Po&&console.log(t.name,t.tracks,i);for(let s of t.tracks)if(!(s.times.length<=0)){if(s.name.endsWith(i))this.rootStartPosition=new Y.Vector3().fromArray(s.values,0),this.rootEndPosition=new Y.Vector3().fromArray(s.values,s.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Po&&console.log(this.rootPositionOffset);else if(s.name.endsWith(r)&&(this.rootStartQuaternion=new Y.Quaternion().fromArray(s.values,0),this.rootEndQuaternion=new Y.Quaternion().fromArray(s.values,s.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Po)){let a=new Y.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}},gi=class extends Oo{models=[];trackOffset;target;mixer;clips=[];actions=[];_actionOffsets=[];_didBind=!1;createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let n=t.tracks[0].name.split("."),i=n[n.length-2],r=i+".position",s=i+".quaternion",a=!1,c=!1;for(let d of t.tracks)d.name.endsWith(r)?(a=!0,this.createPositionInterpolant(t,e,d)):d.name.endsWith(s)&&(c=!0,this.createRotationInterpolant(t,e,d));if(!a||!c){let d=this.mixer?.getRoot(),l=t.tracks[0],u=l.name.lastIndexOf("."),h=l.name.substring(0,u),b=h.substring(h.lastIndexOf(".")+1),_=d.getObjectByName(b);if(_)if(a){if(!c){let v=t.tracks[0].name.substring(0,u)+".quaternion";Po&&console.warn("Create quaternion track",b,_);let y=_.quaternion,m=new Y.QuaternionKeyframeTrack(v,[0,t.duration],[y.x,y.y,y.z,y.w,y.x,y.y,y.z,y.w]);t.tracks.push(m),this.createRotationInterpolant(t,e,m)}}else{let v=h+".position";Po&&console.warn("Create position track",b,_);let y=_.position,m=new Y.VectorKeyframeTrack(v,[0,t.duration],[y.x,y.y,y.z,y.x,y.y,y.z]);t.tracks.push(m),this.createPositionInterpolant(t,e,m)}}}bind(){if(!this._didBind){this._didBind=!0,Po&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(let e of this.actions){let t=new jd(e);this._actionOffsets.push(t)}for(let e of this.models){let t=e.asset,n=t.position,i=t.rotation;n.x!==void 0&&(n.isVector3||(t.position=new Tv(n.x,n.y,n.z)),i.isQuaternion||(t.rotation=new Cv(i.x,i.y,i.z,i.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){let e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new Y.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new Y.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new Y.Vector3;_totalOffsetRotation=new Y.Quaternion;_totalOffsetPosition2=new Y.Vector3;_totalOffsetRotation2=new Y.Quaternion;_summedPos=new Y.Vector3;_tempPos=new Y.Vector3;_summedRot=new Y.Quaternion;_tempRot=new Y.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,n=0,i=!1;for(let r=0;r<this.clips.length;r++){let s=this.models[r],a=this.actions[r],c=s.asset;a.weight=0;let d=e>=s.start&&e<=s.end,l=s.postExtrapolationMode,u=d;if(!u&&!i&&s.end<e&&s.postExtrapolationMode!==0){let h=r<this.clips.length-1?this.models[r+1]:null;(!h||h.start>e)&&(u=!0,i=!0)}if(u){let h=1;h*=this.evaluateWeight(e,r,this.models,u);let b=this.getClipTime(e,s),_=0,v=c.duration;if(d){if(c.loop)for(_+=Math.floor(b/(v+1e-6));b>v;)b-=v}else if(!d)switch(l){case 2:b%=v;break;case 3:let f=Math.floor(b/v)%2!==0;b%=v,f&&(b=v-b);break}a.time=b,a.timeScale=0;let y=h*this.director.weight;if(a.weight=y,a.clampWhenFinished=!0,a.isRunning()||a.play(),this._useclipOffsets){let m=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,f=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(n=1-h),t+=1;let p=this._summedPos.set(0,0,0),g=this._tempPos.set(0,0,0),E=this._summedRot.identity(),w=this._tempRot.identity(),T=c.rotation,S=new Y.Quaternion;S.slerp(T,h);let k=this._actionOffsets[r];if(k.hasOffsets)for(let D=0;D<_;D++)k.rootPositionOffset?g.copy(k.rootPositionOffset):g.set(0,0,0),g.applyQuaternion(E).applyQuaternion(S),k.rootQuaternionOffset&&(w.copy(k.rootQuaternionOffset),E.multiply(w)),p.add(g);f.multiply(S),f.multiply(E),p.add(c.position),m.add(p)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,n),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,n)),this.mixer.update(e)}createRotationInterpolant(e,t,n){let i=n.createInterpolant.bind(n),r=new Y.Quaternion;this.ensureTrackOffsets();let s=this.trackOffset?.rotation;n.createInterpolant=()=>{let a=i(),c=a.evaluate.bind(a);return a.evaluate=d=>{let l=c(d);return r.set(l[0],l[1],l[2],l[3]),r.premultiply(this._totalOffsetRotation),s&&r.premultiply(s),l[0]=r.x,l[1]=r.y,l[2]=r.z,l[3]=r.w,l},a}}createPositionInterpolant(e,t,n){let i=n.createInterpolant.bind(n),r=new Y.Vector3;this.ensureTrackOffsets();let s=this.trackOffset?.rotation,a=this.trackOffset?.position,c;n.createInterpolant=()=>{let d=i(),l=d.evaluate.bind(d);return d.evaluate=u=>{let h=l(u);return r.set(h[0],h[1],h[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(b=>b.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),s&&r.applyQuaternion(s),a&&(r.x-=a.x,r.y+=a.y,r.z+=a.z),h[0]=r.x,h[1]=r.y,h[2]=r.z,h},d}}},bi=class extends Oo{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return nn(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){let n=this.models[t];this.audio[t].setVolume(e?n.asset.volume:0)}}addModel(e){let t=this.getAudioFilePath(e.asset.clip),n=new Y.Audio(this.listener);n.setVolume(e.asset.volume);let i=new Y.AudioLoader;console.log(t,this.director.sourceId),i.load(t,r=>{n.setBuffer(r),n.loop=e.asset.loop,this.audio.push(n),this.models.push(e)})}onDisable(){for(let e of this.audio)e.isPlaying&&e.stop()}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){let t=this.audio[e];t?.isPlaying&&t.stop()}}evaluate(e){if(!this.track.muted){for(let t=0;t<this.models.length;t++){let n=this.models[t],i=this.audio[t];if(e>=n.start&&e<=n.end){if(this.director.isPaused&&(i.isPlaying&&i.stop(),this.lastTime===e))continue;i.isPlaying||(i.offset=n.clipIn+(e-n.start)*n.timeScale,i.play());let r=n.asset.volume;n.easeInDuration>0&&(r*=Math.min((e-n.start)/n.easeInDuration,1)),n.easeOutDuration>0&&(r*=Math.min((n.end-e)/n.easeOutDuration,1)),i.setVolume(r*this.director.weight)}else i.isPlaying&&i.stop()}this.lastTime=e}}},Mn=class extends Oo{models=[];didTrigger=[];receivers=[];evaluate(e){if(!(this.receivers.length<=0)&&!this.track.muted)for(let t=0;t<this.models.length;t++){let n=this.models[t],i=this.didTrigger[t],r=n.time-e;if(n.retroActive?r<0:r<0&&Math.abs(r)<.1){if(!i){this.didTrigger[t]=!0;for(let a of this.receivers)!a||a.invoke(n.asset)}}else n.emitOnce||(this.didTrigger[t]=!1)}}},vs=class extends Oo{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){let i=this.models[t].asset;if(typeof i.sourceObject=="string"){let r=i.sourceObject;vs.resolved[r]?i.sourceObject=vs.resolved[r]:(i.sourceObject=R.findByGuid(r,e.scene),vs.resolved[r]=i.sourceObject)}if(i.sourceObject){let r=R.getComponent(i.sourceObject,Dn);this.timelines.push(r),r&&i.updateDirector&&(r.playOnAwake=!1)}else{this.models.splice(t,1);continue}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){let n=this.models[t],i=n.asset;if(e>=n.start&&e<=n.end){this._previousActiveModel=n;let r=this.getClipTime(e,n);if(i.controlActivation){let s=i.sourceObject;s.visible=!0}if(i.updateDirector){let s=this.timelines[t];s&&(s.isPlaying&&s.pause(),s.time=r,s.evaluate())}}else{let r=this._previousActiveModel?.asset;if(i.controlActivation){let s=i.sourceObject;r?.sourceObject!==s&&(s.visible=!1)}}}}},In=vs;j(In,"resolved",{});var Op=I("debugtimeline");var tl=class extends O{static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){this._time=e}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}_visibilityChangeEvt;_clonedPlayableAsset=!1;awake(){Op&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),this.playOnAwake?this.play():this.evaluate(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,this.playableAsset?.tracks,Array.isArray(this.playableAsset?.tracks),this)}onEnable(){for(let e of this._audioTracks)e.onEnable?.();for(let e of this._customTracks)e.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){this.stop();for(let e of this._audioTracks)e.onDisable?.();for(let e of this._customTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(let e of this._audioTracks)e.onDestroy?.()}rebuildGraph(){!this.isValid()||(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}play(){!this.isValid()||(this._isPaused=!1,!this._isPlaying&&(this._isPlaying=!0,this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())))}pause(){this._isPaused=!0}stop(){this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate()),this._isPlaying=!1,this._isPaused=!1,this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let e=this._time;switch(this.extrapolationMode){case 0:e=Math.min(e,this._duration);break;case 1:e%=this._duration;break;case 2:if(e>this._duration){this.stop();return}break}this.internalEvaluate(e)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(let e of this._allTracks)for(let t of e)yield t}get audioTracks(){return this._audioTracks}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_controlTracks=[];_customTracks=[];_allTracks=[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks];*internalUpdate(){for(;this._isPlaying;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime,this.evaluate()),yield}internalEvaluate(e){for(let t of this.playableAsset.tracks)if(!t.muted)switch(t.type){case"ActivationTrack":for(let n=0;n<t.outputs.length;n++){let i=t.outputs[n];if(typeof i=="object"){let r=!1;for(let a of t.clips)a.start<=e&&e<=a.end&&(r=!0);let s=i;s.visible!==void 0&&(s.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Uo(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;let e=this.findRoot(this.gameObject);for(let t of this.playableAsset.tracks)for(let n=t.outputs.length-1;n>=0;n--){let i=t.outputs[n];if(typeof i=="string"){this._guidsMap&&this._guidsMap[i]&&(i=this._guidsMap[i]);let r=R.findByGuid(i,e);r===null||typeof r!="object"?(t.outputs.splice(n,1),console.warn("Failed to resolve binding",i,t.name,t.type)):(Op&&console.log("Resolved binding",i,"to",r),t.outputs[n]=r)}else if(i===null){if(t.outputs.splice(n,1),tl.createTrackFunctions[t.type])continue;t.type!=="AudioTrack"&&t.type!=="ControlTrack"&&t.type!=="MarkerTrack"&&console.warn("Missing binding",i,t.name,t.type,this.name,this.playableAsset.name)}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(let e of this.playableAsset.tracks)if(e.muted!==!0)for(let t of e.clips)t.end>this._duration&&(this._duration=t.end)}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=[];for(let t of this.playableAsset.tracks){let n=t.type,i=tl.createTrackFunctions[n];if(i!=null){let r=i(this,t);if(typeof r.evaluate=="function"){r.director=this,r.track=t,this._customTracks.push(r);continue}}if(t.type==="AnimationTrack"){if(t.clips.length<=0)continue;for(let r=t.outputs.length-1;r>=0;r--){let s=t.outputs[r];typeof s.enabled=="boolean"&&(s.enabled=!1);let a=s?.gameObject?.animations;if(a){let c=new gi;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let d=0;d<t.clips.length;d++){let l=t.clips[d],u=l.asset;if(!u){console.error("MISSING anim model?","clip#"+d,l,t,this.playableAsset,this.name);continue}let h=u.clip,b=h;if((typeof b=="string"||typeof b=="number")&&(b=a.find(v=>v.name===h)),!b){console.warn("Could not find animationClip for model",l,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new kp.AnimationMixer(s.gameObject)),c.clips.push(b),c.mixer.uncacheAction(b),c.createHooks(l.asset,b);let _=c.mixer.clipAction(b);c.actions.push(_),c.models.push(l)}this._animationTracks.push(c)}}}else if(t.type==="AudioTrack"){if(t.clips.length<=0)continue;e.push(t)}else if(t.type==="MarkerTrack"){let r=new Mn;r.director=this,r.track=t;for(let s of t.markers)switch(s.type){case"SignalEmitter":r.models.push(s),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let s=R.getComponent(this.gameObject,kn);s&&(r.receivers.push(s),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new Mn;r.director=this,r.track=t;for(let s of t.markers)r.models.push(s),r.didTrigger.push(!1);for(let s of t.outputs)r.receivers.push(s);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new In;r.director=this,r.track=t;for(let s of t.clips)r.models.push(s);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}Z.registerWaitForAllowAudio(()=>{let t=R.findObjectOfType(Rt,this.context);if(!!t)for(let n of e){let i=new bi;i.director=this,i.track=n,i.listener=t.listener;for(let r=0;r<n.clips.length;r++){let s=n.clips[r];i.addModel(s)}this._audioTracks.push(i)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},Dn=tl;j(Dn,"createTrackFunctions",{});import{Color as Ov,Texture as jp}from"three";import*as Fd from"three-mesh-ui";import{Matrix4 as Sv,Object3D as Pv,Vector2 as Ap,Vector3 as Hd}from"three";import{FrontSide as Ip,DoubleSide as Mp}from"three";function ko(o,e){if(!o)return;let t=o.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?Mp:Ip,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?Mp:Ip,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let n of o.children)ko(n,e)}function nl(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);let n=Proxy.revocable(o[e],{set(s,a,c,d){let l=s[a],u=Reflect.set(s,a,c,d);return t(c,l),u}}),i=n.revoke,r=o[e];return n.revoke=()=>{o[e]=r,i()},o[e]=n.proxy,n}function Dp(o,e,t=3){let n=o.__scheduledActions;n||(n=o.__scheduledActions={});let i=e.name;n[t]||(n[t]={});let r=n[t];if(r[i])return;function*a(){e?.call(o),r[i]=null}let c=o.startCoroutine(a(),t);r[i]=c}var Lp=I("debugui"),Lr=class{width;height},Yi=class{x;y;width;height},ze=class extends Te{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new Hd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new Sv,this.rectBlock=new Pv,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new Hd),nl(this,"_anchoredPosition",()=>{this._transformNeedsUpdate=!0})}onEnable(){super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0}onDisable(){super.onDisable(),this.removeShadowComponent()}applyTransform(){let e=this.shadowComponent;!e||(this._transformNeedsUpdate=!1,this.isRoot()?e.rotation.y=Math.PI:(e.position.copy(this.gameObject.position),e.position.x*=-1,e.position.z*=-1,e.position.z-=this.offset,e.quaternion.copy(this.gameObject.quaternion),e.rotation.x*=-1,e.rotation.z*=-1,e.scale.copy(this.gameObject.scale)),this.applyAnchoring(e.position),this.lastMatrix.copy(this.gameObject.matrix))}markDirty(){this._transformNeedsUpdate=!0}onBeforeRender(){(this._transformNeedsUpdate||this.lastMatrix.equals(this.gameObject.matrix)===!1)&&(Lp&&console.log("updating",this.name),this.applyTransform()),Me.ensureUpdateMeshUI(Fd,this.context)}applyAnchoring(e){if(this.pivot&&this.sizeDelta){let t=this.pivot.x*2-1,n=this.pivot.y*2-1;n-=this.anchoredPosition.y*.05;let i=this.sizeDelta.x*t,r=this.sizeDelta.y*n;e.x-=i*.5,e.y-=r*.5}}getBasicOptions(){let e={width:this.rect.width,height:this.rect.height,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},Lp&&console.log(this.name,e);let t=new Fd.Block(e);return this._createdBlocks.push(t),t}};C([x(Yi)],ze.prototype,"rect",2),C([x(Ap)],ze.prototype,"sizeDelta",2),C([x(Hd)],ze.prototype,"anchoredPosition3D",2),C([x(Ap)],ze.prototype,"pivot",2);var tt=class extends Te{get isGraphic(){return!0}get color(){return this._color||(this._color=new ce(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new ce(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=R.getComponent(this.gameObject,ze)),this._rect}setState(e){this.makePanel(),this.uiObject&&this.uiObject.setState(e)}setupState(e){this.makePanel(),this.uiObject&&this.uiObject.setupState(e)}setOptions(e){this.makePanel(),this.uiObject&&(this.uiObject.set(e),(e.backgroundColor!==void 0||e.backgroundOpacity!==void 0)&&this.uiObject.updateBackgroundMaterial?.call(this.uiObject))}awake(){super.awake(),this.makePanel(),nl(this,"_color",()=>Dp(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;let e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}async setTexture(e){!e||(this.setOptions({backgroundOpacity:0}),e&&this.setOptions({backgroundTexture:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}))}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};C([x(ce)],tt.prototype,"color",1),C([x()],tt.prototype,"raycastTarget",2);var An=class extends tt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var il=class{texture;rect};C([x(jp)],il.prototype,"texture",2);var Ln=class extends An{sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return this.sprite?.texture?.image?.width===32&&this.sprite?.texture?.image?.height===32}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new Ov(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};C([x(il)],Ln.prototype,"sprite",2);var Ki=class extends An{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};C([x(jp)],Ki.prototype,"mainTexture",2);var Io=I("debugbutton");var Et=class extends O{onClick;_isHovered=!1;onPointerEnter(e){Io&&console.log("Button Enter",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered")}onPointerExit(){Io&&console.log("Button Exit",this.animationTriggers?.highlightedTrigger,this.animator),this._isHovered=!1,this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal")}onPointerDown(e){Io&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.transition==3&&this.animationTriggers&&this.animator?this.animator.SetTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed")}onPointerUp(e){Io&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),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){Io&&console.trace("Button Click",this.onClick),this.onClick?.invoke()}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(),Io&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_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=R.getComponent(this.gameObject,Ln),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),n={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(n);let i=this.getFinalColor(e.color,this.colors?.highlightedColor),r={state:"hovered",attributes:{backgroundColor:i,backgroundOpacity:i.alpha}};e.setupState(r);let s=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(a);let c=this.getFinalColor(e.color,this.colors?.selectedColor),d={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(d);let l=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};C([x(he)],Et.prototype,"onClick",2),C([x()],Et.prototype,"colors",2),C([x()],Et.prototype,"transition",2),C([x()],Et.prototype,"animationTriggers",2),C([x(qe)],Et.prototype,"animator",2),C([x()],Et.prototype,"interactable",1);var Bd=class extends yn{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof Bd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),ko(this.shadowComponent,this);for(let e of R.getComponentsInChildren(this.gameObject,Te))ko(e.shadowComponent,this)}}_activeRenderMode=-1;get isScreenSpace(){return this._activeRenderMode===1||this._activeRenderMode===0}updateRenderMode(){if(this.renderMode!==this._activeRenderMode)switch(this.renderMode){case 0:case 1:let e=this.context.mainCameraComponent;if(!e)return;let t=this.gameObject;e.gameObject?.add(t);let i=e.farClipPlane;t.position.x=0,t.position.y=0,t.position.z=-i;let r=Math.tan(W.toRadians(e.fieldOfView)*i)*(e.aspect*1.333333),s=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=s;break;case 2:break}}},Pe=Bd;C([x()],Pe.prototype,"renderOnTop",1),C([x()],Pe.prototype,"depthWrite",1),C([x()],Pe.prototype,"doubleSided",1),C([x()],Pe.prototype,"castShadows",1),C([x()],Pe.prototype,"receiveShadows",1),C([x()],Pe.prototype,"renderMode",1),C([x(Pe)],Pe.prototype,"rootCanvas",1),C([x()],Pe.prototype,"scaleFactor",1);var jn=class extends O{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of R.getComponentsInChildren(this.gameObject,tt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};C([x()],jn.prototype,"alpha",1),C([x()],jn.prototype,"interactable",2),C([x()],jn.prototype,"blocksRaycasts",2);import*as Hp from"three-mesh-ui";import{Color as L}from"three";var kv=I("debugtext");var ye=class extends tt{canvas;alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;get text(){return this._text}set text(e){if(this._text=e,!this._textMeshUi&&this._text.length>0&&this.context.time.frame>0&&this.createText(e,this.getTextOpts(),this.supportRichText),this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){if(this._fontSize=e,this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}this._textMeshUi[0].set({content:e}),this.markDirty()}}onColorChanged(){if(this._textMeshUi){if(this._textMeshUi.length>1){this.requestRebuild();return}let e=this.color;this._textMeshUi[0].set({fontColor:e,fontOpacity:e.alpha}),this.markDirty()}}_isWaitingForRebuild=!1;requestRebuild(){this._isWaitingForRebuild||(this._isWaitingForRebuild=!0,this.startCoroutine(this.rebuildDelayedRoutine(),0))}*rebuildDelayedRoutine(){if(this._isWaitingForRebuild=!1,this._textMeshUi){for(let e of this._textMeshUi)e.removeFromParent();this._textMeshUi.length=0}this.createText(this.text,this.getTextOpts(),this.supportRichText),this.markDirty()}onCreate(e){kv&&console.log(this);let t=this.verticalOverflow==0&&this.horizontalOverflow==0;t&&(this.context.renderer.localClippingEnabled=!0);let n=this.rectTransform;this._textContainer=this.uiObject=this.createBlock(n,t,null,!0),this.createText(this.text,this.getTextOpts(),this.supportRichText),this.uiObject,this.uiObject=this.createBlock(n,t,this.uiObject,!1)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;_textContainer=null;getTextOpts(){let e=this.fontSize,t={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&(this.uiObject.onAfterUpdate=this.updateWidth.bind(this))}createBlock(e,t,n,i=!1){let r={};r.hiddenOverflow=t,r.interLine=(this.lineSpacing-1)*this.fontSize*1.333,this.getAlignment(r,i);let s=e.createNewBlock(r);return n&&(Array.isArray(n)?s.add(...n):s.add(n)),s}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((n,i)=>n+i.width,0);t+=e.getFontSize()*5,t+=e.padding*2||0,t+=this.fontSize*1.5,e.set({width:t}),this.ensureShadowComponentOwner()}},1)}ensureShadowComponentOwner(){this.shadowComponent&&this.shadowComponent.traverse(e=>{e[pt]===void 0&&(e[pt]=this)})}createText(e,t,n){if(!(!e||e.length<=0))if(this._textMeshUi||(this._textMeshUi=[]),n){let i=this.getNextTag(e);if(i)i.startIndex>0&&this.createText(e.substring(0,i.startIndex),t,!1);else return this.createText(e,t,!1);let r=[];for(;i;){let s=this.getNextTag(e,i.endIndex);if(s){let a=this.getText(e,i,s);this.handleTag(i,t,r),this.createText(a,t,!1)}else{let a=e.substring(i.endIndex);this.handleTag(i,t,r),this.createText(a,t,!1)}i=s}}else{let i={...t};i.content=e;let r=new Hp.Text(i);this._textMeshUi.push(r),this._textContainer&&this._textContainer.add(r)}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;let e=[],t=this.canvas,n={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let i=!1;if(this._textMeshUi)for(let r=0;r<this._textMeshUi.length;r++){if(e[r]===!0)continue;i=!0;let s=this._textMeshUi[r];!s.textContent||(ko(s,n),e[r]=!0)}if(!i)break;yield}}handleTag(e,t,n){if(e.isEndTag){if(n.length>0){let i=n.pop();if(i)for(let r in i.previousValues){let s=i.previousValues[r];t[r]=s}}}else if(e.type.includes("color")){let i=new ys(e,{fontColor:t.fontColor});if(n.push(i),e.type.length>6){let r=e.type.substring(6);t.fontColor=Iv(r)}else t.fontColor=new L(1,1,1)}else if(e.type=="b"){let i=new ys(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});n.push(i),this.setFont(t,1)}else if(e.type=="i"){let i=new ys(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});n.push(i),this.setFont(t,2)}}getText(e,t,n){return e.substring(t.endIndex,n.startIndex)}getNextTag(e,t=0){let n=e.indexOf("<",t),i=e.indexOf(">",n);if(n>=0&&i>=0){let r=e.substring(n+1,i);return{type:r,startIndex:n,endIndex:i+1,isEndTag:r.startsWith("/")}}return null}setFont(e,t){let n=this.getFontName(t),i=n;i?.endsWith("-msdf.json")||(i+="-msdf.json"),e.fontFamily=i;let r=n;r?.endsWith(".png")||(r+=".png"),e.fontTexture=r}getFontName(e){return this.font?(this.font=nn(this.sourceId,this.font),this.font):null}};C([x(Pe)],ye.prototype,"canvas",2),C([x()],ye.prototype,"alignment",2),C([x()],ye.prototype,"verticalOverflow",2),C([x()],ye.prototype,"horizontalOverflow",2),C([x()],ye.prototype,"lineSpacing",2),C([x()],ye.prototype,"supportRichText",2),C([x()],ye.prototype,"font",2),C([x()],ye.prototype,"fontStyle",2),C([x()],ye.prototype,"text",1),C([x()],ye.prototype,"fontSize",1);var ys=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function Iv(o){if(o.startsWith("#")){let t=o.substring(1);var e=parseInt(t,16);let n=e>>16&255,i=e>>8&255,r=e&255;return new L(n/255,i/255,r/255)}switch(o){case"black":return new L(0,0,0);case"white":return new L(1,1,1);case"red":return new L(1,0,0);case"lime":return new L(0,1,0);case"blue":return new L(0,0,1);case"yellow":return new L(1,1,0);case"cyan":return new L(0,1,1);case"magenta":return new L(1,0,1);case"silver":return new L(.75,.75,.75);case"gray":return new L(.5,.5,.5);case"maroon":return new L(.5,0,0);case"olive":return new L(.5,.5,0);case"green":return new L(0,.5,0);case"purple":return new L(.5,0,.5);case"teal":return new L(0,.5,.5);case"navy":return new L(0,0,.5);case"darkred":return new L(.54,0,0);case"brown":return new L(.55,.27,0);case"firebrick":return new L(.69,.13,.13);case"crimson":return new L(.86,.08,.24);case"tomato":return new L(1,.39,.28);case"coral":return new L(1,.49,.31);case"indianred":return new L(.6,.31,.51);case"lightcoral":return new L(.94,.5,.5);case"darkorange":return new L(1,.55,0);case"orange":return new L(1,.65,0);case"gold":return new L(1,.84,0);case"darkgoldenrod":return new L(.72,.53,.04);case"goldenrod":return new L(.85,.65,.13);case"palegoldenrod":return new L(.93,.87,.67);case"darkkhaki":return new L(.74,.7,.42);case"khaki":return new L(.94,.9,.55);case"yellowgreen":return new L(.6,.8,.19);case"darkolivegreen":return new L(.33,.42,.18);case"olivedrab":return new L(.42,.56,.14);case"lawngreen":return new L(.49,.99,0);case"chartreuse":return new L(.5,1,0);case"greenyellow":return new L(.68,1,.18);case"darkgreen":return new L(0,.39,0);case"forestgreen":return new L(.13,.55,.13);case"limegreen":return new L(.19,.8,.19);case"lightgreen":return new L(.56,.93,.56);case"palegreen":return new L(.59,.98,.59);case"darkseagreen":return new L(.56,.74,.56);case"mediumspringgreen":return new L(0,.98,.6);case"springgreen":return new L(0,1,.5);case"seagreen":return new L(.18,.31,.31);case"mediumaquamarine":return new L(.4,.8,.66);case"mediumseagreen":return new L(.24,.7,.44);case"lightseagreen":return new L(.13,.7,.67);case"darkslategray":return new L(.18,.31,.31);case"darkcyan":return new L(0,.55,.55);case"aqua":return new L(0,1,1);case"lightcyan":return new L(.8,1,1);case"darkturquoise":return new L(0,.81,.82);case"turquoise":return new L(0,.82,.82);case"mediumturquoise":return new L(.28,.82,.8);case"paleturquoise":return new L(.68,1,.93);case"aquamarine":return new L(.5,1,.83);case"powderblue":return new L(.69,.88,.9);case"cadetblue":return new L(.37,.62,.63);case"steelblue":return new L(.27,.51,.71);case"cornflowerblue":return new L(.39,.58,.93);case"deepskyblue":return new L(0,.7,1);case"dodgerblue":return new L(.12,.56,1);case"lightblue":return new L(.68,.85,.9);case"skyblue":return new L(.53,.81,.92);case"lightskyblue":return new L(.53,.81,.98);case"midnightblue":return new L(.18,.18,.31);case"darkblue":return new L(0,0,.55);case"mediumblue":return new L(0,0,.82);case"royalblue":return new L(.25,.41,.88);case"blueviolet":return new L(.54,.17,.89);case"indigo":return new L(.29,0,.51);case"darkslateblue":return new L(.28,.24,.55);case"slateblue":return new L(.42,.35,.8);case"mediumslateblue":return new L(.48,.41,.9);case"mediumpurple":return new L(.58,.44,.86);case"darkmagenta":return new L(.55,0,.55);case"darkviolet":return new L(.58,0,.83);case"darkorchid":return new L(.6,.2,.8);case"mediumorchid":return new L(.73,.33,.83);case"thistle":return new L(.84,.75,.85);case"plum":return new L(.87,.63,.87);case"violet":return new L(.93,.51,.93);case"fuchsia":return new L(1,0,1);case"orchid":return new L(.85,.44,.84);case"mediumvioletred":return new L(.78,.08,.52);case"palevioletred":return new L(.86,.44,.58);case"hotpink":return new L(1,.4,.71);case"deeppink":return new L(1,.08,.58);case"lightpink":return new L(1,.71,.76);case"pink":return new L(1,.75,.78);case"antiquewhite":return new L(.98,.92,.84);case"beige":return new L(.96,.96,.86);case"bisque":return new L(1,.89,.77);case"blanchedalmond":return new L(1,.92,.82);case"wheat":return new L(.96,.87,.87);case"cornsilk":return new L(1,.97,.86);case"lemonchiffon":return new L(1,.98,.8);case"lightgoldenrodyellow":return new L(.98,.98,.82);case"lightyellow":return new L(1,1,.8);case"saddlebrown":return new L(.55,.27,.07);case"sienna":return new L(.63,.32,.18);case"chocolate":return new L(.82,.41,.12);case"peru":return new L(.82,.52,.25);case"sandybrown":return new L(.96,.64,.38);case"burlywood":return new L(.87,.72,.53);case"tan":return new L(.82,.71,.55);case"rosybrown":return new L(.74,.56,.56);case"moccasin":return new L(1,.89,.71);case"navajowhite":return new L(1,.87,.68);case"peachpuff":return new L(1,.85,.73);case"mistyrose":return new L(1,.89,.88);case"lavenderblush":return new L(1,.94,.93);case"linen":return new L(.98,.94,.9);case"oldlace":return new L(.99,.96,.9);case"papayawhip":return new L(1,.94,.84);case"seashell":return new L(1,.96,.93);case"mintcream":return new L(.98,1,.98);case"slategray":return new L(.44,.5,.56);case"lightslategray":return new L(.47,.53,.6);case"lightsteelblue":return new L(.69,.77,.87);case"lavender":return new L(.9,.9,.98);case"floralwhite":return new L(1,.98,.98);case"aliceblue":return new L(.94,.97,1);case"ghostwhite":return new L(.97,.97,1);case"honeydew":return new L(.94,1,.94);case"ivory":return new L(1,1,.94);case"azure":return new L(.94,1,1);case"snow":return new L(1,.98,.98);case"dimgray":return new L(.4,.4,.4);case"darkgray":return new L(.66,.66,.66);case"lightgray":return new L(.83,.83,.83);case"gainsboro":return new L(.86,.86,.86);case"whitesmoke":return new L(.96,.96,.96)}return new L(1,1,1)}var jr=I("debuginputfield"),z=class extends O{get text(){return this.textComponent?.text??""}get isFocused(){return z.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){jr&&console.log(this.name,this)}onEnable(){z.htmlField||(z.htmlField=document.createElement("input"),z.htmlField.classList.add("ar"),document.body.appendChild(z.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),z.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&R.setActive(this.placeholder.gameObject,!1)}onDisable(){z.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){jr&&console.log("CLICK",e,z.active),z.activeTime=this.context.time.time,z.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();z.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-z.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(z.active!==this&&(jr&&console.log("Select",this.name,this,z.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,z.htmlField?.value),z.active?.onDeselected(),z.active=this,this.placeholder&&R.setActive(this.placeholder.gameObject,!1),z.htmlField)){if(z.htmlField.value=this.textComponent?.text||"",jr&&console.log("set input field value",z.htmlField.value),this.context.isInXR){let e=this.context.arOverlayElement;e&&(z.htmlField.style.width="0px",z.htmlField.style.height="0px",e.append(z.htmlField))}this.selectInputField()}}onDeselected(){z.active===this&&(z.active=null,jr&&console.log("Deselect",this.name,this),z.htmlField&&(z.htmlField.blur(),document.body.append(z.htmlField),z.htmlField.style.width="",z.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&R.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(z.active===this){if(jr&&console.log(e.code,e,z.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}z.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&R.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&z.htmlField){if(this.textComponent.text!==z.htmlField.value){jr&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=z.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=z.htmlField.value}}selectInputField(){z.htmlField&&(z.htmlField.setSelectionRange(z.htmlField.value.length,z.htmlField.value.length),z.htmlField.focus())}},nt=z;j(nt,"active",null),j(nt,"activeTime",-1),j(nt,"htmlField",null),C([x(ye)],nt.prototype,"textComponent",2),C([x(ye)],nt.prototype,"placeholder",2),C([x(he)],nt.prototype,"onValueChanged",2),C([x(he)],nt.prototype,"onEndEdit",2);import*as Fp from"three-mesh-ui";import*as _s from"three";var Bp=(a=>(a[a.fr=0]="fr",a[a.ru=1]="ru",a[a.de=2]="de",a[a.es=3]="es",a[a.el=4]="el",a[a.nord=5]="nord",a[a.eng=6]="eng",a))(Bp||{}),Hr=class extends Te{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=Bp[this.keymap||6];this.makeKeyboard(e)}onEnable(){this.addShadowComponent(this.keyboard)}onDisable(){this.removeShadowComponent()}keyboard=null;_lastKeyPressed;_lastKeyPressedStartTime=0;_lastKeyPressedTime=0;makeKeyboard(e){!e&&!navigator.language&&(e="en");let t=this.font?this.font:"arial",n=R.getComponent(this.gameObject,ze);if(!n){console.error("Missing rect transform, please add this component inside a canvas");return}let i={...n.getBasicOptions(),margin:this.margin||0,padding:this.padding||0,language:e,fontFamily:Eo+"/"+t+"-msdf.json",fontTexture:Eo+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new _s.Color(this.colors.keyboardBack),backspaceTexture:Eo+"/backspace.png",shiftTexture:Eo+"/shift.png",enterTexture:Eo+"/enter.png",borderRadius:this.borderRadius||0,autoLayout:!1},r=this.gameObject.scale;i.width*=this.gameObject.scale.x,i.height*=this.gameObject.scale.y,i.fontSize*=Math.max(r.x,r.y),this.keyboard=new Fp.Keyboard(i),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(s=>{s.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new _s.Color(this.colors.button),backgroundOpacity:1}}),s.setState("normal"),s.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new _s.Color(this.colors.hovered),backgroundOpacity:1}}),s.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new _s.Color(this.colors.selected),backgroundOpacity:1},onSet:()=>{let a=s.info.input,c=s.info.command;if(this._lastKeyPressed!==a)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedTime>.05)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedStartTime<.5||c=="switch"||c=="shift"||c=="switch-set"){this._lastKeyPressedTime=this.context.time.time;return}if(this._lastKeyPressedTime=this.context.time.time,this._lastKeyPressed=a,c)switch(c){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
270
+ `);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else s.info.input!==void 0&&this.tryAppend(s.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var Hn=class extends O{reverseArrangement=!1},Fr=class extends Hn{},Br=class extends Hn{},Ur=class extends Hn{};var Ji=class extends O{awake(){Me.createIfNoneExists(this.context)}onEnable(){Me.instance?.register(this)}onDisable(){Me.instance?.unregister(this)}performRaycast(e=null){return null}},Zi=class extends Ji{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new ge,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},Gr=class extends Zi{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as Up from"three";import{HTMLMesh as Mv}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as Dv}from"three/examples/jsm/interactive/InteractiveGroup.js";var Vr=class extends O{id=null;keepAspect=!1;start(){if(!this.id||!this.context.mainCamera)return;let 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";let t=new Dv(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let n=new Mv(e);t.add(n),n.visible=!1,console.log(n);let i=n.material;i.transparent=!0,setTimeout(()=>{n.visible=!0;let r=Ls(this.gameObject).clone();js(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let s=new Up.Box3;s.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);let a=s.max.x-s.min.x,c=s.max.y-s.min.y;if(this.keepAspect){let l=a/c;a>c?n.scale.set(1/a,1/c/l,1):n.scale.set(1/a*l,1/c,1)}else n.scale.set(1/a,1/c,1);let d=this.gameObject.scale;n.scale.multiply(d)},1)}};var Mo=class{};var Es=class extends O{toggleKey="p";update(){this.context.input.isKeyDown("p")&&this.context.domElement.classList.toggle("presentation-mode")}};import*as Gp from"three";import{Raycaster as jv,Vector3 as Hv}from"three";import*as rl from"three";import{MeshLine as Av,MeshLineMaterial as Lv}from"three.meshline";var Gd=class{id=0;points=[];line=new Av;material;mesh;constructor(e,t){if(t&&(this.material=t.material),this.material||(this.material=this.defaultLineMaterial),t){let n=t.options;n&&Object.assign(this.material,n)}this.mesh=new rl.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=Gd.wp;t.set(e.x,e.y,e.z);let n=this.mesh?.parent;return n&&(t=n.worldToLocal(t),e.x=t.x,e.y=t.y,e.z=t.z),this.points.push(e.x,e.y,e.z),this.line.setPoints(this.points),e}defaultLineMaterial=new Lv({color:10066329,lineWidth:.01})},Nr=Gd;j(Nr,"wp",new rl.Vector3);var $i=class extends O{startLine(e,t){let n=Math.random()*Number.MAX_SAFE_INTEGER;return this.internalStartLine(e,n,!0,t)}updateLine(e,t){let n=this.inFlight[e.id];if(!n)return;t.point&&(t.point=n.appendPoint(t.point));let i=this.buffer[e.id];i&&(t.point&&i.push(t.point.x,t.point.y,t.point.z),i.length>5&&(this.sendLineUpdate(n,!1,void 0,i),i.length=0))}endLine(e,t=!0){let n=this.inFlight[e.id];if(!n)return;this.finished.push(n),delete this.inFlight[e.id],t&&this.sendLineUpdate(n,!0,0);let i=this.buffer[e.id];if(i){delete this.buffer[e.id];let r=i;r.length=0,this.freeBuffer.push(r)}return n}getLine(e){return this.inFlight[e.id]}finished=[];inFlight=[];buffer={};freeBuffer=new Array;awake(){this.context.connection.beginListen("line-start",e=>{this.onEnsureLine(e.id,e.parentGuid)}),this.context.connection.beginListen("line-update",e=>{let t=this.onEnsureLine(e.guid,e.parentGuid);t&&e.points&&(e.startIndex<=0?t.points=e.points:e.startIndex>=t.points.length&&t.points.push(...e.points),t.line.setPoints(t.points),t.material.lineWidth=e.width,t.material.color.fromArray(e.color),e.finished===!0&&this.endLine({id:t.id},!1))})}onEnsureLine(e,t){if(this.inFlight[e])return this.inFlight[e];let n=R.findByGuid(t,this.context.scene);if(!!n)return this.internalStartLine(n,e,!1),this.inFlight[e]}internalStartLine(e,t,n=!0,i){let r=new Nr(e??this.context.scene,i);r.id=t,this.inFlight[t]=r,n&&this.sendLineStart(r);let s;return this.freeBuffer.length<=0?s=new Array:s=this.freeBuffer.pop(),this.buffer[t]=s,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,n,i){if(e){let r={parentGuid:e.mesh.parent.guid,guid:e.id,points:i?[...i]:e.points,width:e.material.lineWidth,color:e.material.color.toArray(),startIndex:n!==void 0?n:e.points.length,finished:t};this.context.connection.send("line-update",r)}}};import{MeshLineMaterial as Fv}from"three.meshline";var ol=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new Hv,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},sl=class extends O{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=R.getComponent(this.gameObject,$i),this.lines||(this.lines=R.addNewComponent(this.gameObject,$i))),this.orbit=R.findObjectOfType(Fe,this.context)??void 0,this._states.mouse=new ol;let e={};q.addEventListener("select-start",(t,n)=>{e[t.controller.uuid]=!0}),q.addEventListener("update",(t,n)=>{if(e[t.controller.uuid]===!0){let i=t.getRay();this.updateLine(t.controller.uuid,i,!0,!1,!1)}}),q.addEventListener("select-end",(t,n)=>{e[t.controller.uuid]=!1;let i=t.getRay();this.updateLine(t.controller.uuid,i,!0,!0,!1)})}_states={};update(){this.orbit&&this._states.mouse&&this.orbit&&(this.orbit.enabled=!this._states.mouse.isDrawing);let e=this.context.input.getPointerPressedCount()>1,t=this.context.input.getPointerPositionRC(0);sl._raycaster.setFromCamera(t,this.context.mainCamera);let n=sl._raycaster.ray;this.updateLine("mouse",n,this.context.input.getPointerPressed(0),this.context.input.getPointerUp(0),e||this.context.input.isKeyPressed("Alt"))}updateLine(e,t,n,i,r=!1){let s=this._states[e];if(s||(this._states[e]=new ol,s=this._states[e]),i)s.isDrawing=!1,s.currentHandle&&(this.lines.endLine(s.currentHandle),s.currentHandle=null);else if(n){if(r)return s;let a=this.getHit(t),c=null,d=s.prevDistance;if(a)s.currentHandle||(s.maxDistance=a.distance),c=a.point,c.add(a.face.normal.multiplyScalar(.01)),s.prevDistance=a.distance;else if(s.maxDistance>0){let l=s.maxDistance;if(!s.currentHandle&&s.lastHit){let u=B(this.context.mainCamera);l=s.lastHit.distanceTo(u)}c=t.origin.add(t.direction.multiplyScalar(s.maxDistance)),s.prevDistance=s.maxDistance}if(c){if(!s.currentHandle){let l=s.lastParent??this.gameObject;this.addToPaintedObject&&a&&(l=a.object),s.lastParent=l,s.currentHandle=this.lines.startLine(l,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(s.prevDistance>s.maxDistance||Math.abs(d-s.prevDistance)>.2)){let l=s.maxDistance;c=t.origin.add(t.direction.multiplyScalar(l)),s.prevDistance=l}if(s.lastHit&&s.lastHit.distanceTo(c)<s.prevDistance*.01)return s;this.lines.updateLine(s.currentHandle,{point:c}),s.lastHit.copy(c)}s.isDrawing=s.currentHandle!==null}return s}_raycastOptions=new ge;getHit(e){(!this.colliders||this.colliders.length===0)&&(this.colliders=[this.gameObject]),this._raycastOptions.targets=this.colliders,this._raycastOptions.ray=e;let t=this.context.physics.raycast(this._raycastOptions);if(t.length>0){for(let n of t)if(!!R.isActiveInHierarchy(n.object))return n}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=We.colorFromHashCode(We.hashCode(this.context.connection.connectionId)):e=new Gp.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new Fv({color:e,lineWidth:W.lerp(.005,.01,Math.random())})}},Do=sl;j(Do,"_raycaster",new jv);import{Object3D as Bv}from"three";var Ao=class extends O{asset;joinedRoomFunction;awake(){this.watchTabVisible(),this.joinedRoomFunction=this.onUserJoined.bind(this)}onEnable(){this.context.connection.beginListen("joined-room",this.joinedRoomFunction)}onDisable(){this.context.connection.stopListening("joined-room",this.joinedRoomFunction)}async onUserJoined(e){let t=await this.asset?.instantiateSynced({parent:this.gameObject},!0);if(t){let n=R.getComponent(t,tn);n&&(n.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=tn.all.length-1;t>=0;t--){let n=tn.all[t];(!n.owner||!this.context.connection.userIsInRoom(n.owner))&&n.doDestroy()}})}};C([x(je)],Ao.prototype,"asset",2);var Mt=class extends O{static get all(){return Mt._all}static get local(){return Mt._local}static isLocalPlayer(e){return e instanceof Bv?R.getComponentInParent(e,Mt)?.isLocalPlayer??!1:e instanceof st?R.getComponentInParent(e.gameObject,Mt)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&Mt.local.push(this),Mt.all.push(this),this.context.connection.beginListen("user-left-room",e=>{if(e.userId===this.owner){this.doDestroy();return}})}start(){if(!this.owner||!this.context.connection.userIsInRoom(this.owner)){this.doDestroy();return}}doDestroy(){Zr(this.gameObject,this.context.connection)}onDestroy(){if(Mt.all.splice(Mt.all.indexOf(this),1),this.isLocalPlayer){let e=Mt._local.indexOf(this);e>=0&&Mt._local.splice(e,1)}}},tn=Mt;j(tn,"_all",[]),j(tn,"_local",[]),C([qa(),x()],tn.prototype,"owner",2);Zn[A]=!0;dn[A]=!0;ki[A]=!0;qe[A]=!0;Ct[A]=!0;Rt[A]=!0;Z[A]=!0;Ii[A]=!0;ei[A]=!0;hn[A]=!0;mr[A]=!0;Ce[A]=!0;ie[A]=!0;lt[A]=!0;ti[A]=!0;ni[A]=!0;Mi[A]=!0;Di[A]=!0;br[A]=!0;Ai[A]=!0;zt[A]=!0;si[A]=!0;Xt[A]=!0;Qt[A]=!0;Fi[A]=!0;he[A]=!0;vr[A]=!0;yr[A]=!0;wn[A]=!0;wr[A]=!0;gt[A]=!0;Rn[A]=!0;Sn[A]=!0;ct[A]=!0;dt[A]=!0;De[A]=!0;qt[A]=!0;ai[A]=!0;bn[A]=!0;Ui[A]=!0;kt[A]=!0;Yt[A]=!0;Fe[A]=!0;Gi[A]=!0;Sr[A]=!0;Cr[A]=!0;Tr[A]=!0;Rr[A]=!0;We[A]=!0;mt[A]=!0;_r[A]=!0;$[A]=!0;Bi[A]=!0;Er[A]=!0;xn[A]=!0;K[A]=!0;li[A]=!0;ci[A]=!0;di[A]=!0;Jt[A]=!0;et[A]=!0;Pn[A]=!0;Pr[A]=!0;Ni[A]=!0;On[A]=!0;ui[A]=!0;It[A]=!0;Je[A]=!0;Or[A]=!0;kr[A]=!0;Wi[A]=!0;fe[A]=!0;He[A]=!0;Ir[A]=!0;Zt[A]=!0;pi[A]=!0;fi[A]=!0;hi[A]=!0;zi[A]=!0;ut[A]=!0;U[A]=!0;oi[A]=!0;re[A]=!0;ht[A]=!0;Hi[A]=!0;q[A]=!0;Ve[A]=!0;Xi[A]=!0;Mr[A]=!0;ri[A]=!0;ft[A]=!0;En[A]=!0;$e[A]=!0;ue[A]=!0;$t[A]=!0;en[A]=!0;de[A]=!0;gn[A]=!0;mi[A]=!0;Dr[A]=!0;Mo[A]=!0;Ar[A]=!0;ce[A]=!0;Dn[A]=!0;Qi[A]=!0;qi[A]=!0;kn[A]=!0;gi[A]=!0;bi[A]=!0;Mn[A]=!0;In[A]=!0;Te[A]=!0;yn[A]=!0;Et[A]=!0;Pe[A]=!0;jn[A]=!0;Me[A]=!0;tt[A]=!0;An[A]=!0;Ln[A]=!0;Ki[A]=!0;nt[A]=!0;Hr[A]=!0;Hn[A]=!0;Fr[A]=!0;Br[A]=!0;Ur[A]=!0;Pt[A]=!0;Ji[A]=!0;Zi[A]=!0;Gr[A]=!0;Ot[A]=!0;Lr[A]=!0;Yi[A]=!0;ze[A]=!0;Vr[A]=!0;ye[A]=!0;Es[A]=!0;Do[A]=!0;Nr[A]=!0;$i[A]=!0;Ao[A]=!0;tn[A]=!0;M.add("AlignmentConstraint",Zn);M.add("Animation",dn);M.add("AnimationCurve",ki);M.add("Animator",qe);M.add("AnimatorController",Ct);M.add("AudioListener",Rt);M.add("AudioSource",Z);M.add("AvatarModel",Ii);M.add("AvatarLoader",ei);M.add("AxesHelper",hn);M.add("BasicIKConstraint",mr);M.add("BoxHelperComponent",Ce);M.add("Camera",ie);M.add("Collider",lt);M.add("SphereCollider",ti);M.add("BoxCollider",ni);M.add("MeshCollider",Mi);M.add("DeleteBox",Di);M.add("Deletable",br);M.add("DeviceFlag",Ai);M.add("DragControls",zt);M.add("DropListener",si);M.add("Duplicatable",Xt);M.add("CallInfo",Qt);M.add("EventListEvent",Fi);M.add("EventList",he);M.add("EventTrigger",vr);M.add("FlyControls",yr);M.add("BoxGizmo",wn);M.add("GltfExportBox",wr);M.add("GltfExport",gt);M.add("GridHelper",Rn);M.add("GroundProjectedEnv",Sn);M.add("Interactable",ct);M.add("UsageMarker",dt);M.add("Light",De);M.add("LODModel",qt);M.add("LODGroup",ai);M.add("LookAtConstraint",bn);M.add("NestedGltf",Ui);M.add("Networking",kt);M.add("OffsetConstraint",Yt);M.add("OrbitControls",Fe);M.add("ParticleSystemRenderer",Gi);M.add("ParticleSystem",Sr);M.add("MainModule",Cr);M.add("EmissionModule",Tr);M.add("ShapeModule",Rr);M.add("PlayerColor",We);M.add("ReflectionProbe",mt);M.add("FieldWithDefault",_r);M.add("Renderer",$);M.add("MeshRenderer",Bi);M.add("SkinnedMeshRenderer",Er);M.add("RendererLightmap",xn);M.add("Rigidbody",K);M.add("ScreenCapture",li);M.add("ShadowCatcher",ci);M.add("RemoteSkybox",di);M.add("SmoothFollow",Jt);M.add("SpatialTriggerReceiver",et);M.add("SpatialTrigger",Pn);M.add("SpectatorCamera",Pr);M.add("Sprite",Ni);M.add("SpriteRenderer",On);M.add("SyncedCamera",ui);M.add("SyncedRoom",It);M.add("SyncedTransform",Je);M.add("TestRunner",Or);M.add("TestSimulateUserData",kr);M.add("TransformGizmo",Wi);M.add("VideoPlayer",fe);M.add("Voip",He);M.add("VolumeParameter",Ir);M.add("VolumeComponent",Zt);M.add("ToneMapping",pi);M.add("ColorAdjustments",fi);M.add("VolumeProfile",hi);M.add("Volume",zi);M.add("WebARSessionRoot",ut);M.add("WebXR",U);M.add("WebAR",oi);M.add("AvatarMarker",re);M.add("WebXRAvatar",ht);M.add("TeleportTarget",Hi);M.add("WebXRController",q);M.add("AttachedObject",Ve);M.add("XRGrabModel",Xi);M.add("XRGrabRendering",Mr);M.add("XRRig",ri);M.add("VRUserState",ft);M.add("WebXRSync",En);M.add("XRState",$e);M.add("XRFlag",ue);M.add("AvatarBlink_Simple",$t);M.add("AvatarEyeLook_Rotation",en);M.add("Avatar_POI",de);M.add("Avatar_Brain_LookAt",gn);M.add("Avatar_MouthShapes",mi);M.add("Avatar_MustacheShake",Dr);M.add("__Ignore",Mo);M.add("LogStats",Ar);M.add("RGBAColor",ce);M.add("PlayableDirector",Dn);M.add("SignalAsset",Qi);M.add("SignalReceiverEvent",qi);M.add("SignalReceiver",kn);M.add("AnimationTrackHandler",gi);M.add("AudioTrackHandler",bi);M.add("SignalTrackHandler",Mn);M.add("ControlTrackHandler",In);M.add("BaseUIComponent",Te);M.add("UIRootComponent",yn);M.add("Button",Et);M.add("Canvas",Pe);M.add("CanvasGroup",jn);M.add("EventSystem",Me);M.add("Graphic",tt);M.add("MaskableGraphic",An);M.add("Image",Ln);M.add("RawImage",Ki);M.add("InputField",nt);M.add("Keyboard",Hr);M.add("LayoutGroup",Hn);M.add("VerticalLayoutGroup",Fr);M.add("HorizontalLayoutGroup",Br);M.add("GridLayoutGroup",Ur);M.add("PointerEventData",Pt);M.add("Raycaster",Ji);M.add("ObjectRaycaster",Zi);M.add("GraphicRaycaster",Gr);M.add("UIRaycastUtils",Ot);M.add("Size",Lr);M.add("Rect",Yi);M.add("RectTransform",ze);M.add("SpatialHtml",Vr);M.add("Text",ye);M.add("PresentationMode",Es);M.add("LinesDrawer",Do);M.add("LineInstanceHandler",Nr);M.add("LinesManager",$i);M.add("PlayerSync",Ao);M.add("PlayerState",tn);var Vp=_e,Uv=I("debugtypestore");Uv&&console.log(M);function Np(o,e){let n=Sl(o,e);return n!==void 0?n:null}async function Wp(o,e,t,n=null,i){if(!t)return;let r=[],s=n;typeof s=="number"&&(s=new ke(n));let a=new Yr(t.scene);a.gltfId=e,a.context=o,a.gltf=t,a.nodeToObject=i?.nodeToObjectMap;let c=[];if(t.scenes)for(let d of t.scenes)await Nd(a,d,c,r);if(t.children)for(let d of t.children)await Nd(a,d,c,r);o.new_scripts_pre_setup_callbacks.push(()=>{for(let d of c)Gv(d,a);if(s){Vd(t,s);for(let d of t.scenes)Vd(d,s)}})}function Vd(o,e){if(e!==null&&!!o){if(o.guid=e.generateUUID(),o&&o.userData&&o.userData.components)for(let t of o.userData.components)t!==null&&(t.guid=e.generateUUID());if(o.children)for(let t of o.children)Vd(t,e)}}var ws=[];async function Nd(o,e,t,n){if(!e)return;let i=e.userData;if(i){let r=i.builtin_components;if(r&&r.length>0)for(let s of r)try{if(s===null)continue;let a=M.get(s.name);if(a!=null){let c=new a;c.sourceId=o.gltfId,Nn(c,s),wi(e,c,!1),t.push({instance:c,compData:s,obj:e})}else Vp&&console.debug("unknown component: "+s.name),ws.includes(s.name)||ws.push(s.name)}catch(a){console.error(s.name+" - "+a.message,a)}if(ws.length>0){let s=ws.join(", ");console.warn("unknown components: "+s),ws.length=0,tr()&&yi(`<strong>Unknown components in scene</strong>:
271
271
 
272
- ${o}
272
+ ${s}
273
273
 
274
274
  This could mean you forgot to add a npmdef to your ExportInfo
275
- <a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,1)}}if(e.children)for(let r of e.children)await iu(a,r,t,i)}function f0(a,e){let{instance:t,compData:i,obj:n}=a;e.object=n,e.target=t;let r=!0;r=ws(t,i,e)===!0,$m&&console.debug("add "+i.name,i,t)}var la=class{createBuiltinComponents(e,t,i,n,r){return tg(e,t,i,n,r)}writeBuiltinComponentData(e,t){return eg(e,t)}parseSync(e,t,i,n){return g0(e,t,i,n)}loadSync(e,t,i,n,r){return b0(e,t,i,n,r)}};ll(la);var m0=D("printGltf");var wr=class{context;loader;path;gltf;constructor(e,t,i,n){this.context=e,this.path=t,this.loader=i,this.gltf=n}},ig={};function gs(a,e){if(ig[a])for(let t of ig[a])t(e)}async function rg(a,e,t,i,n){m0&&console.log(t),await a.assets.registerGltf(t),await Qe().createBuiltinComponents(a,e,t,i,n)}function g0(a,e,t,i){typeof t!="string"&&console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t);let n=new ng;Xd(n,a,t);let o=qd(n);return new Promise((s,c)=>{try{Nr(n,a),gs(0,new wr(a,t,n)),n.parse(e,t,async d=>{gs(1,new wr(a,t,n,d)),await rg(a,t,d,i,o),gs(10,new wr(a,t,n,d)),s(d)},d=>{console.error("failed loading "+t,d),s(void 0)})}catch(d){console.error(d),c(d)}})}function b0(a,e,t,i=!1,n){let r=new ng;Xd(r,a,e);let s=qd(r);return new Promise((c,d)=>{try{Nr(r,a),gs(0,new wr(a,e,r)),r.load(e,async l=>{gs(1,new wr(a,e,r,l)),await rg(a,e,l,t,s),gs(10,new wr(a,e,r,l)),c(l)},l=>{n?.call(r,l)},l=>{console.error("failed loading "+e,l),c(void 0)})}catch(l){console.error(l),d(l)}})}ll(la);var Eo=D("debugwebcomponent"),nu=class{id;context;previouslyAdded;previousSource;networkEvent;constructor(e,t){this.id=e,this.context=t,this.networkEvent="needle-engine-source-changed",this.id&&(this.networkEvent+="-"+this.id),this.context.connection.beginListen(this.networkEvent,i=>{this.onSourceChanged(i,!0)})}async onSourceChanged(e,t=!1,i=!1){this.previouslyAdded&&(t&&e===this.previousSource||k.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,K.Current=this.context;let n=await Qe().loadSync(this.context,e,this.getHashFromString(e),!1);i||un(this.context);let r=n?.scene;r&&(this.previouslyAdded=r,this.context.scene.add(r))}getHashFromString(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}},v0="needle-engine",y0="vr",x0="desktop",w0=[on,y0,x0],ru=class extends HTMLElement{get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{let i=()=>{this.removeEventListener("loadfinished",i),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",i)}})}get Context(){return this._context}gameObject=k;GameObject=k;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new pa}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let o=this.getAttribute("src");return o?.endsWith(".glb")||o?.endsWith(".gltf")?o:null},i="loadScene",n=t();n&&(i=n);let r=this.getAttribute("alias");if(this._context=new K({name:i,domElement:this,alias:r}),this._watcher=new nu(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(vl).length<=0;){if(!this.isConnected)return;await wu(10)}let o=vl[i]??window[i],s=null;if((!o||n)&&(n&&(i=n),o=async c=>{let d=t();d&&this._watcher&&(s=d,await this._watcher.onSourceChanged(d,!0,!0))}),o){this.classList.add("loading"),console.log("Needle Engine: Begin loading",r??"");let c=!1,d=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:c}));!this._loadingView&&d&&(this._loadingView=new yl(this)),d&&this._loadingView?.onLoadingBegin("begin load");let l=(u,f)=>{this._loadingProgress01=Sd(u),d&&this._loadingView?.onLoadingUpdate(u,f),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:u.name,progress:u.progress,index:u.index,count:u.count,totalProgress01:this._loadingProgress01}}))};this.onBeforeBeginLoading(),await this._context.onCreate(o,{progress:l});let h=t();h&&h!==s&&await this._watcher.onSourceChanged(h,!0,!0),this._loadingProgress01=1,d&&this._loadingView?.onLoadingFinished("create scene"),this.classList.remove("loading"),this.classList.add("loading-finished"),console.log("Needle Engine: finished loading",r??""),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:r??i}})),this.onSetupDesktop()}else console.error('Could not find scene function named "'+i+'", it must be either in global scope or added to build_scene_functions',vl)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this._context&&this._context.onDestroy()}static get observedAttributes(){return["src","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath"]}attributeChangedCallback(e,t,i){switch(e){case"src":this._watcher?.onSourceChanged(i);break;case"loadstart":case"progress":case"loadfinished":typeof i=="string"&&i.length>0&&(Eo&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":Eo&&console.log("dracoDecoderPath",i),Od(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(Eo&&console.log("dracoDecoderType",i),Id(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":Eo&&console.log("ktx2DecoderPath",i),kd(i);break}}registerEventFromAttribute(e,t){if(typeof t=="string"&&t.length>0){let i=(0,eval)(t);typeof i=="function"&&this.addEventListener(e,n=>i?.call(globalThis,this._context,n))}}getAROverlayContainer(){return this._overlay_ar.findOrCreateARContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){let t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e,t){this.onSetupAR(),this._overlay_ar.onBegin(this._context,t,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onElementsChanged(){}onSetupAR(){this.classList.add("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,on))}onSetupVR(){this.classList.remove("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"vr"))}onSetupDesktop(){this.classList.remove("ar-session-active"),this.classList.add("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"desktop"))}setupElementsForMode(e,t,i=null){if(e===this._context?.renderer.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.style.position="absolute",e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(let r of w0)e.classList.contains(r)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){let i=this.children[t];i.style&&e(i)}}onBeforeBeginLoading(){let e=this.getAttribute("dracoDecoderPath");e&&(Eo&&console.log("using custom draco decoder path",e),Od(e));let t=this.getAttribute("dracoDecoderType");t&&(Eo&&console.log("using custom draco decoder type",t),Id(t));let i=this.getAttribute("ktx2DecoderPath");i&&(Eo&&console.log("using custom ktx2 decoder path",i),kd(i))}};window.customElements.define(v0,ru);import*as _0 from"three";var ou={Context:K};globalThis.Needle=ou;function og(a){for(let e in a)ou[e]=a[e]}og(Rd);og($h);for(let a of Object.getOwnPropertyNames(k))switch(a){case"prototype":case"constructor":case"length":case"name":continue;default:ou[a]=k[a];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=_0;export{gn as AlignmentConstraint,Ut as Animation,Jn as AnimationCurve,Ln as AnimationTrackHandler,ct as Animator,zt as AnimatorController,Ye as AssetReference,it as AttachedObject,Vt as AudioListener,ae as AudioSource,Dn as AudioTrackHandler,vi as AvatarBlink_Simple,yi as AvatarEyeLook_Rotation,vn as AvatarLoader,ue as AvatarMarker,Zn as AvatarModel,Di as Avatar_Brain_LookAt,Mn as Avatar_MouthShapes,uo as Avatar_MustacheShake,xe as Avatar_POI,ki as AxesHelper,je as BaseUIComponent,Gr as BasicIKConstraint,M as Behaviour,xn as BoxCollider,zi as BoxGizmo,De as BoxHelperComponent,Dt as Button,ui as CallInfo,he as Camera,Fe as Canvas,tn as CanvasGroup,Wt as Collider,Lo as Collision,An as ColorAdjustments,Ki as ControlTrackHandler,qr as Deletable,er as DeleteBox,tr as DeviceFlag,di as DragControls,Cn as DropListener,hi as Duplicatable,io as EmissionModule,_e as EventList,or as EventListEvent,Ve as EventSystem,Xr as EventTrigger,Yr as FieldWithDefault,Qr as FlyControls,ii as FrameEvent,k as GameObject,It as GltfExport,Jr as GltfExportBox,gt as Graphic,xo as GraphicRaycaster,Wi as GridHelper,yo as GridLayoutGroup,qi as GroundProjectedEnv,Sy as HideFlags,vo as HorizontalLayoutGroup,en as Image,bt as InputField,re as InstancingUtil,Ge as InstantiateOptions,Et as Interactable,go as Keyboard,Tn as LODGroup,pi as LODModel,nn as LayoutGroup,We as Light,po as LogStats,ma as LogType,ji as LookAtConstraint,to as MainModule,$i as MaskableGraphic,sr as MeshRenderer,Zr as NavMesh,$r as NavMeshAgent,ar as NestedGltf,Yt as Networking,yr as ObjectRaycaster,fi as OffsetConstraint,Je as OrbitControls,ro as ParticleSystem,lr as ParticleSystemRenderer,Zi as PlayableDirector,rt as PlayerColor,Xt as PointerEventData,ye as RGBAColor,br as RawImage,vr as Raycaster,gr as Rect,ot as RectTransform,Ot as ReflectionProbe,Pn as RemoteSkybox,le as Renderer,Ui as RendererLightmap,oe as Rigidbody,Rn as ScreenCapture,Sn as ShadowCatcher,no as ShapeModule,fr as SignalAsset,Yi as SignalReceiver,mr as SignalReceiverEvent,Ji as SignalTrackHandler,fo as Size,Kr as SkinnedMeshRenderer,gi as SmoothFollow,wo as SpatialHtml,Xi as SpatialTrigger,mt as SpatialTriggerReceiver,oo as SpectatorCamera,yn as SphereCollider,so as SpringJoint,dr as Sprite,Qi as SpriteRenderer,On as SyncedCamera,Kt as SyncedRoom,ut as SyncedTransform,rr as TeleportTarget,ao as TestRunner,lo as TestSimulateUserData,Pe as Text,kn as ToneMapping,hr as TransformGizmo,Qt as UIRaycastUtils,Hi as UIRootComponent,Ct as UsageMarker,Pt as VRUserState,bo as VerticalLayoutGroup,Ce as VideoPlayer,Ke as Voip,ur as Volume,bi as VolumeComponent,co as VolumeParameter,In as VolumeProfile,En as WebAR,Tt as WebARSessionRoot,Y as WebXR,Rt as WebXRAvatar,ie as WebXRController,Ni as WebXRSync,we as XRFlag,pr as XRGrabModel,ho as XRGrabRendering,_n as XRRig,ft as XRState,ps as __Ignore,Gn as addNewComponentInstance,No as apply,ei as destroy,Yp as destroyComponentInstance,Dr as findByGuid,Jp as findObjectOfType,Zp as findObjectsOfType,Ht as foreachComponent,Br as getComponent,pn as getComponentInChildren,Bo as getComponentInParent,Ho as getComponents,Fo as getComponentsInChildren,Ds as getComponentsInParent,Ga as getOrAddComponent,jr as instantiate,ef as isActiveInHierarchy,Lr as isActiveSelf,Xa as isUsingInstancing,tf as markAsInstancedRendered,Qp as moveComponentInstance,Ua as removeComponent,S as serializeable,qa as setActive,xs as showBalloonMessage};
275
+ <a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,1)}}if(e.children)for(let r of e.children)await Nd(o,r,t,n)}function Gv(o,e){let{instance:t,compData:n,obj:i}=o;e.object=i,e.target=t;let r=!0;r=Vo(t,n,e)===!0,Vp&&console.debug("add "+n.name,n,t)}var xs=class{createBuiltinComponents(e,t,n,i,r){return Wp(e,t,n,i,r)}writeBuiltinComponentData(e,t){return Np(e,t)}parseSync(e,t,n,i){return Nv(e,t,n,i)}loadSync(e,t,n,i,r){return Wv(e,t,n,i,r)}};ca(xs);var Vv=I("printGltf");var er=class{context;loader;path;gltf;constructor(e,t,n,i){this.context=e,this.path=t,this.loader=n,this.gltf=i}},zp={};function Lo(o,e){if(zp[o])for(let t of zp[o])t(e)}async function Qp(o,e,t,n,i){Vv&&console.log(t),await o.assets.registerGltf(t),await Le().createBuiltinComponents(o,e,t,n,i)}function Nv(o,e,t,n){typeof t!="string"&&console.warn("Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file",t,typeof t);let i=new Xp;Dc(i,o,t);let s=Mc(i);return new Promise((a,c)=>{try{Yn(i,o),Lo(0,new er(o,t,i)),i.parse(e,t,async d=>{Lo(1,new er(o,t,i,d)),await Qp(o,t,d,n,s),Lo(10,new er(o,t,i,d)),a(d)},d=>{console.error("failed loading "+t,d),a(void 0)})}catch(d){console.error(d),c(d)}})}function Wv(o,e,t,n=!1,i){let r=new Xp;Dc(r,o,e);let a=Mc(r);return new Promise((c,d)=>{try{Yn(r,o),Lo(0,new er(o,e,r)),r.load(e,async l=>{Lo(1,new er(o,e,r,l)),await Qp(o,e,l,t,a),Lo(10,new er(o,e,r,l)),c(l)},l=>{i?.call(r,l)},l=>{console.error("failed loading "+e,l),c(void 0)})}catch(l){console.error(l),d(l)}})}ca(xs);var Wr=I("debugwebcomponent"),Wd=class{id;context;previouslyAdded;previousSource;networkEvent;constructor(e,t){this.id=e,this.context=t,this.networkEvent="needle-engine-source-changed",this.id&&(this.networkEvent+="-"+this.id),this.context.connection.beginListen(this.networkEvent,n=>{this.onSourceChanged(n,!0)})}async onSourceChanged(e,t=!1,n=!1){this.previouslyAdded&&(t&&e===this.previousSource||R.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,V.Current=this.context;let i=await Le().loadSync(this.context,e,this.getHashFromString(e),!1);n||zn(this.context);let r=i?.scene;r&&(this.previouslyAdded=r,this.context.scene.add(r))}getHashFromString(e){let t=0;for(let n=0;n<e.length;n++)t=e.charCodeAt(n)+((t<<5)-t);return t}},zv="needle-engine",Xv="vr",Qv="desktop",qv=[Gn,Xv,Qv],zd=class extends HTMLElement{get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{let n=()=>{this.removeEventListener("loadfinished",n),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",n)}})}get Context(){return this._context}gameObject=R;GameObject=R;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new Ps}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let s=this.getAttribute("src");return s?.endsWith(".glb")||s?.endsWith(".gltf")?s:null},n="loadScene",i=t();i&&(n=i);let r=this.getAttribute("alias");if(this._context=new V({name:n,domElement:this,alias:r}),this._watcher=new Wd(this.getAttribute("id")??r??"",this._context),n&&n.length>0){if(!i)for(;Object.keys(ya).length<=0;){if(!this.isConnected)return;await du(10)}let s=ya[n]??window[n],a=null;if((!s||i)&&(i&&(n=i),s=async c=>{let d=t();d&&this._watcher&&(a=d,await this._watcher.onSourceChanged(d,!0,!0))}),s){this.classList.add("loading"),console.log("Needle Engine: Begin loading",r??"");let c=!1,d=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:c}));!this._loadingView&&d&&(this._loadingView=new _a(this)),d&&this._loadingView?.onLoadingBegin("begin load");let l=(h,b)=>{this._loadingProgress01=pc(h),d&&this._loadingView?.onLoadingUpdate(h,b),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:h.name,progress:h.progress,index:h.index,count:h.count,totalProgress01:this._loadingProgress01}}))};this.onBeforeBeginLoading(),await this._context.onCreate(s,{progress:l});let u=t();u&&u!==a&&await this._watcher.onSourceChanged(u,!0,!0),this._loadingProgress01=1,d&&this._loadingView?.onLoadingFinished("create scene"),this.classList.remove("loading"),this.classList.add("loading-finished"),console.log("Needle Engine: finished loading",r??""),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:r??n}})),this.onSetupDesktop()}else console.error('Could not find scene function named "'+n+'", it must be either in global scope or added to build_scene_functions',ya)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this._context&&this._context.onDestroy()}static get observedAttributes(){return["src","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath"]}attributeChangedCallback(e,t,n){switch(e){case"src":this._watcher?.onSourceChanged(n);break;case"loadstart":case"progress":case"loadfinished":typeof n=="string"&&n.length>0&&(Wr&&console.log(e+" attribute changed",n),this.registerEventFromAttribute(e,n));break;case"dracoDecoderPath":Wr&&console.log("dracoDecoderPath",n),mc(n);break;case"dracoDecoderType":n==="wasm"||n==="js"?(Wr&&console.log("dracoDecoderType",n),gc(n)):console.error("Invalid dracoDecoderType",n,"expected js or wasm");break;case"ktx2DecoderPath":Wr&&console.log("ktx2DecoderPath",n),bc(n);break}}registerEventFromAttribute(e,t){if(typeof t=="string"&&t.length>0){let n=(0,eval)(t);typeof n=="function"&&this.addEventListener(e,i=>n?.call(globalThis,this._context,i))}}getAROverlayContainer(){return this._overlay_ar.findOrCreateARContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){let t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e,t){this.onSetupAR(),this._overlay_ar.onBegin(this._context,t,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onElementsChanged(){}onSetupAR(){this.classList.add("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Gn))}onSetupVR(){this.classList.remove("ar-session-active"),this.classList.remove("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"vr"))}onSetupDesktop(){this.classList.remove("ar-session-active"),this.classList.add("desktop-session-active"),this.foreachHtmlElement(e=>this.setupElementsForMode(e,"desktop"))}setupElementsForMode(e,t,n=null){if(e===this._context?.renderer.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.style.position="absolute",e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(let r of qv)e.classList.contains(r)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){let n=this.children[t];n.style&&e(n)}}onBeforeBeginLoading(){let e=this.getAttribute("dracoDecoderPath");e&&(Wr&&console.log("using custom draco decoder path",e),mc(e));let t=this.getAttribute("dracoDecoderType");t&&(Wr&&console.log("using custom draco decoder type",t),gc(t));let n=this.getAttribute("ktx2DecoderPath");n&&(Wr&&console.log("using custom ktx2 decoder path",n),bc(n))}};window.customElements.define(zv,zd);import*as Yv from"three";var Xd={Context:V};globalThis.Needle=Xd;function qp(o){for(let e in o)Xd[e]=o[e]}qp(hc);qp(Ud);for(let o of Object.getOwnPropertyNames(R))switch(o){case"prototype":case"constructor":case"length":case"name":continue;default:Xd[o]=R[o];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=Yv;export{Zn as AlignmentConstraint,dn as Animation,ki as AnimationCurve,gi as AnimationTrackHandler,qe as Animator,Ct as AnimatorController,je as AssetReference,Ve as AttachedObject,Rt as AudioListener,Z as AudioSource,bi as AudioTrackHandler,$t as AvatarBlink_Simple,en as AvatarEyeLook_Rotation,ei as AvatarLoader,re as AvatarMarker,Ii as AvatarModel,gn as Avatar_Brain_LookAt,mi as Avatar_MouthShapes,Dr as Avatar_MustacheShake,de as Avatar_POI,hn as AxesHelper,Te as BaseUIComponent,mr as BasicIKConstraint,O as Behaviour,ni as BoxCollider,wn as BoxGizmo,Ce as BoxHelperComponent,Et as Button,Qt as CallInfo,ie as Camera,Pe as Canvas,jn as CanvasGroup,lt as Collider,Xo as Collision,fi as ColorAdjustments,In as ControlTrackHandler,br as Deletable,Di as DeleteBox,Ai as DeviceFlag,zt as DragControls,si as DropListener,Xt as Duplicatable,Tr as EmissionModule,he as EventList,Fi as EventListEvent,Me as EventSystem,vr as EventTrigger,_r as FieldWithDefault,yr as FlyControls,jt as FrameEvent,R as GameObject,gt as GltfExport,wr as GltfExportBox,tt as Graphic,Gr as GraphicRaycaster,Rn as GridHelper,Ur as GridLayoutGroup,Sn as GroundProjectedEnv,Gf as HideFlags,Br as HorizontalLayoutGroup,Ln as Image,nt as InputField,ne as InstancingUtil,Ie as InstantiateOptions,ct as Interactable,Hr as Keyboard,ai as LODGroup,qt as LODModel,Hn as LayoutGroup,De as Light,Ar as LogStats,Go as LogType,bn as LookAtConstraint,Cr as MainModule,An as MaskableGraphic,Mi as MeshCollider,Bi as MeshRenderer,Ui as NestedGltf,kt as Networking,Zi as ObjectRaycaster,Yt as OffsetConstraint,Fe as OrbitControls,Sr as ParticleSystem,Gi as ParticleSystemRenderer,Dn as PlayableDirector,We as PlayerColor,Pt as PointerEventData,ce as RGBAColor,Ki as RawImage,Ji as Raycaster,Yi as Rect,ze as RectTransform,mt as ReflectionProbe,di as RemoteSkybox,$ as Renderer,xn as RendererLightmap,K as Rigidbody,li as ScreenCapture,ci as ShadowCatcher,Rr as ShapeModule,Qi as SignalAsset,kn as SignalReceiver,qi as SignalReceiverEvent,Mn as SignalTrackHandler,Lr as Size,Er as SkinnedMeshRenderer,Jt as SmoothFollow,Vr as SpatialHtml,Pn as SpatialTrigger,et as SpatialTriggerReceiver,Pr as SpectatorCamera,ti as SphereCollider,Ni as Sprite,On as SpriteRenderer,ui as SyncedCamera,It as SyncedRoom,Je as SyncedTransform,Hi as TeleportTarget,Or as TestRunner,kr as TestSimulateUserData,ye as Text,pi as ToneMapping,Wi as TransformGizmo,Ot as UIRaycastUtils,yn as UIRootComponent,dt as UsageMarker,ft as VRUserState,Fr as VerticalLayoutGroup,fe as VideoPlayer,He as Voip,zi as Volume,Zt as VolumeComponent,Ir as VolumeParameter,hi as VolumeProfile,oi as WebAR,ut as WebARSessionRoot,U as WebXR,ht as WebXRAvatar,q as WebXRController,En as WebXRSync,ue as XRFlag,Xi as XRGrabModel,Mr as XRGrabRendering,ri as XRRig,$e as XRState,Mo as __Ignore,wi as addNewComponentInstance,no as apply,At as destroy,Uu as destroyComponentInstance,ar as findByGuid,Vu as findObjectOfType,Nu as findObjectsOfType,Qn as foreachComponent,cr as getComponent,Xn as getComponentInChildren,$r as getComponentInParent,eo as getComponents,to as getComponentsInChildren,Yo as getComponentsInParent,Ws as getOrAddComponent,lr as instantiate,zu as isActiveInHierarchy,sr as isActiveSelf,Ys as isUsingInstancing,Xu as markAsInstancedRendered,Bu as moveComponentInstance,Ns as removeComponent,x as serializeable,qs as setActive,yi as showBalloonMessage,gy as showBalloonWarning,Gt as validate};
276
276
  /*!
277
277
  * Determine if an object is a Buffer
278
278
  *