@needle-tools/engine 2.32.0-pre → 2.33.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 (42) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/needle-engine.d.ts +18 -11
  3. package/dist/needle-engine.js +341 -341
  4. package/dist/needle-engine.js.map +4 -4
  5. package/dist/needle-engine.min.js +14 -14
  6. package/dist/needle-engine.min.js.map +4 -4
  7. package/lib/engine/extensions/NEEDLE_components.js +2 -0
  8. package/lib/engine/extensions/NEEDLE_components.js.map +1 -1
  9. package/lib/engine/extensions/NEEDLE_techniques_webgl.d.ts +1 -0
  10. package/lib/engine/extensions/NEEDLE_techniques_webgl.js +26 -0
  11. package/lib/engine/extensions/NEEDLE_techniques_webgl.js.map +1 -1
  12. package/lib/engine-components/Collider.js +2 -2
  13. package/lib/engine-components/Collider.js.map +1 -1
  14. package/lib/engine-components/Component.js +2 -50
  15. package/lib/engine-components/Component.js.map +1 -1
  16. package/lib/engine-components/ScreenCapture.d.ts +8 -4
  17. package/lib/engine-components/ScreenCapture.js +73 -18
  18. package/lib/engine-components/ScreenCapture.js.map +1 -1
  19. package/lib/engine-components/codegen/{exports.d.ts → components.d.ts} +2 -1
  20. package/lib/engine-components/codegen/{exports.js → components.js} +3 -2
  21. package/lib/engine-components/codegen/components.js.map +1 -0
  22. package/lib/engine-components/js-extensions/Object3D.d.ts +2 -0
  23. package/lib/engine-components/js-extensions/Object3D.js +75 -0
  24. package/lib/engine-components/js-extensions/Object3D.js.map +1 -0
  25. package/lib/needle-engine.d.ts +2 -1
  26. package/lib/needle-engine.js +3 -2
  27. package/lib/needle-engine.js.map +1 -1
  28. package/package.json +1 -1
  29. package/src/engine/codegen/register_types.js +4 -4
  30. package/src/engine/extensions/NEEDLE_components.ts +3 -0
  31. package/src/engine/extensions/NEEDLE_techniques_webgl.ts +34 -2
  32. package/src/engine-components/Collider.ts +2 -2
  33. package/src/engine-components/Component.ts +2 -63
  34. package/src/engine-components/ScreenCapture.ts +73 -20
  35. package/src/engine-components/codegen/{exports.ts → components.ts} +1 -1
  36. package/src/engine-components/js-extensions/Object3D.ts +91 -0
  37. package/src/needle-engine.ts +3 -3
  38. package/lib/engine-components/ComponentExtensions.d.ts +0 -2
  39. package/lib/engine-components/ComponentExtensions.js +0 -3
  40. package/lib/engine-components/ComponentExtensions.js.map +0 -1
  41. package/lib/engine-components/codegen/exports.js.map +0 -1
  42. package/src/engine-components/ComponentExtensions.ts +0 -7
@@ -1,4 +1,4 @@
1
- var em=Object.create;var Zo=Object.defineProperty;var Sh=Object.getOwnPropertyDescriptor;var tm=Object.getOwnPropertyNames;var im=Object.getPrototypeOf,nm=Object.prototype.hasOwnProperty;var rm=(a,e,t)=>e in a?Zo(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var Il=(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 $o=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Ph=(a,e)=>{for(var t in e)Zo(a,t,{get:e[t],enumerable:!0})},om=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of tm(e))!nm.call(a,n)&&n!==t&&Zo(a,n,{get:()=>e[n],enumerable:!(i=Sh(e,n))||i.enumerable});return a};var js=(a,e,t)=>(t=a!=null?em(im(a)):{},om(e||!a||!a.__esModule?Zo(t,"default",{value:a,enumerable:!0}):t,a));var k=(a,e,t,i)=>{for(var n=i>1?void 0:i?Sh(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&&Zo(e,t,n),n};var z=(a,e,t)=>(rm(a,typeof e!="symbol"?e+"":e,t),t);var Pa=$o((vp,zc)=>{parcelRequire=function(a,e,t,i){var n,r=typeof parcelRequire=="function"&&parcelRequire,o=typeof Il=="function"&&Il;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 E=e[l]=new s.Module(l);a[l][0].call(E.exports,b,E,E.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 vp=="object"&&typeof zc<"u"?zc.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),E=0,b="";E<l;)(h=f[E])<128?(b+=String.fromCharCode(h),E++):(192^h)<32?(u=(192^h)<<6|63&f[E+1],b+=String.fromCharCode(u),E+=2):(u=(15&h)<<12|(63&f[E+1])<<6|63&f[E+2],b+=String.fromCharCode(u),E+=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(),E=this.unpack();h[f]=E}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,E=Math.floor(f*Math.pow(2,52)),b=Math.pow(2,32),y=h<<31|u+1023<<20|E/b&1048575,g=E%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,x=w.addEventListener;w.addEventListener=function(R,S){if(R!==m)return x.apply(this,arguments);var O=function(P){var L=v(P);L&&(S.handleEvent?S.handleEvent(L):S(L))};return this._eventMap=this._eventMap||{},this._eventMap[m]||(this._eventMap[m]=new Map),this._eventMap[m].set(S,O),x.apply(this,[R,O])};var T=w.removeEventListener;w.removeEventListener=function(R,S){if(R!==m||!this._eventMap||!this._eventMap[m])return T.apply(this,arguments);if(!this._eventMap[m].has(S))return T.apply(this,arguments);var O=this._eventMap[m].get(S);return this._eventMap[m].delete(S),this._eventMap[m].size===0&&delete this._eventMap[m],Object.keys(this._eventMap).length===0&&delete this._eventMap,T.apply(this,[R,O])},Object.defineProperty(w,"on"+m,{get:function(){return this["_on"+m]},set:function(R){this["_on"+m]&&(this.removeEventListener(m,this["_on"+m]),delete this["_on"+m]),R&&this.addEventListener(m,this["_on"+m]=R)},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 E(p){return Object.prototype.toString.call(p)==="[object Object]"}function b(p){return E(p)?Object.keys(p).reduce(function(m,v){var w=E(p[v]),x=w?b(p[v]):p[v],T=w&&!Object.keys(x).length;return x===void 0||T?m:Object.assign(m,i({},v,x))},{}):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(x){y(p,p.get(x),v)})}))}function g(p,m,v){var w=v?"outbound-rtp":"inbound-rtp",x=new Map;if(m===null)return x;var T=[];return p.forEach(function(R){R.type==="track"&&R.trackIdentifier===m.id&&T.push(R)}),T.forEach(function(R){p.forEach(function(S){S.type===w&&S.trackId===R.id&&y(p,S,x)})}),x}},{}],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 E=u?Object.getOwnPropertyDescriptor(d,f):null;E&&(E.get||E.set)?Object.defineProperty(h,f,E):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(x,T){return x?x+T.charAt(0).toUpperCase()+T.slice(1):T==="deviceId"?"sourceId":T};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(x){m[x]!==void 0&&(g.mandatory=g.mandatory||{},g.mandatory[v(x,p)]=m[x])})}}),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(x,T,R){T in x&&!(R in x)&&(x[R]=x[T],delete x[T])};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(x){var T=(x=x.filter(function(R){return R.kind==="videoinput"})).find(function(R){return v.some(function(S){return R.label.toLowerCase().includes(S)})});return!T&&x.length&&v.includes("back")&&(T=x[x.length-1]),T&&(y.video.deviceId=m.exact?{exact:T.deviceId}:{ideal:T.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)},E=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(E(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(E(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=E,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={},x=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var T in m)if(Object.prototype.hasOwnProperty.call(m,T)){var R=x?Object.getOwnPropertyDescriptor(m,T):null;R&&(R.get||R.set)?Object.defineProperty(w,T,R):w[T]=m[T]}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(x){x.stream.addEventListener("addtrack",function(T){var R;R=m.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(O){return O.track&&O.track.id===T.track.id}):{track:T.track};var S=new Event("track");S.track=T.track,S.receiver=R,S.transceiver={receiver:R},S.streams=[x.stream],w.dispatchEvent(S)}),x.stream.getTracks().forEach(function(T){var R;R=m.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(O){return O.track&&O.track.id===T.id}):{track:T};var S=new Event("track");S.track=T,S.receiver=R,S.transceiver={receiver:R},S.streams=[x.stream],w.dispatchEvent(S)})},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(O,P){return{track:P,get dtmf(){return this._dtmf===void 0&&(P.kind==="audio"?this._dtmf=O.createDTMFSender(P):this._dtmf=null),this._dtmf},_pc:O}};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(O,P){var L=w.apply(this,arguments);return L||(L=v(this,O),this._senders.push(L)),L};var x=m.RTCPeerConnection.prototype.removeTrack;m.RTCPeerConnection.prototype.removeTrack=function(O){x.apply(this,arguments);var P=this._senders.indexOf(O);P!==-1&&this._senders.splice(P,1)}}var T=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(O){var P=this;this._senders=this._senders||[],T.apply(this,[O]),O.getTracks().forEach(function(L){P._senders.push(v(P,L))})};var R=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(O){var P=this;this._senders=this._senders||[],R.apply(this,[O]),O.getTracks().forEach(function(L){var I=P._senders.find(function(B){return B.track===L});I&&P._senders.splice(P._senders.indexOf(I),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 S=m.RTCPeerConnection.prototype.getSenders;m.RTCPeerConnection.prototype.getSenders=function(){var O=this,P=S.apply(this,[]);return P.forEach(function(L){return L._pc=O}),P},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,[x,T,R]=arguments;if(arguments.length>0&&typeof x=="function")return v.apply(this,arguments);if(v.length===0&&(arguments.length===0||typeof x!="function"))return v.apply(this,[]);var S=function(P){var L={};return P.result().forEach(function(I){var B={id:I.id,timestamp:I.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[I.type]||I.type};I.names().forEach(function(j){B[j]=I.stat(j)}),L[B.id]=B}),L},O=function(P){return new Map(Object.keys(P).map(function(L){return[L,P[L]]}))};return arguments.length>=2?v.apply(this,[function(P){T(O(S(P)))},x]):new Promise(function(P,L){v.apply(w,[function(I){P(O(S(I)))},L])}).then(T,R)}}}function E(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 R=this,S=v.apply(this,[]);return S.forEach(function(O){return O._pc=R}),S});var w=m.RTCPeerConnection.prototype.addTrack;w&&(m.RTCPeerConnection.prototype.addTrack=function(){var R=w.apply(this,arguments);return R._pc=this,R}),m.RTCRtpSender.prototype.getStats=function(){var R=this;return this._pc.getStats().then(function(S){return i.filterStats(S,R.track,!0)})}}if(!("getStats"in m.RTCRtpReceiver.prototype)){var x=m.RTCPeerConnection.prototype.getReceivers;x&&(m.RTCPeerConnection.prototype.getReceivers=function(){var R=this,S=x.apply(this,[]);return S.forEach(function(O){return O._pc=R}),S}),i.wrapPeerConnectionEvent(m,"track",function(R){return R.receiver._pc=R.srcElement,R}),m.RTCRtpReceiver.prototype.getStats=function(){var R=this;return this._pc.getStats().then(function(S){return i.filterStats(S,R.track,!1)})}}if("getStats"in m.RTCRtpSender.prototype&&"getStats"in m.RTCRtpReceiver.prototype){var T=m.RTCPeerConnection.prototype.getStats;m.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof m.MediaStreamTrack){var R,S,O,P=arguments[0];return this.getSenders().forEach(function(L){L.track===P&&(R?O=!0:R=L)}),this.getReceivers().forEach(function(L){return L.track===P&&(S?O=!0:S=L),L.track===P}),O||R&&S?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):R?R.getStats():S?S.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return T.apply(this,arguments)}}}}function b(m){m.RTCPeerConnection.prototype.getLocalStreams=function(){var R=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(S){return R._shimmedLocalStreams[S][0]})};var v=m.RTCPeerConnection.prototype.addTrack;m.RTCPeerConnection.prototype.addTrack=function(R,S){if(!S)return v.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var O=v.apply(this,arguments);return this._shimmedLocalStreams[S.id]?this._shimmedLocalStreams[S.id].indexOf(O)===-1&&this._shimmedLocalStreams[S.id].push(O):this._shimmedLocalStreams[S.id]=[S,O],O};var w=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(R){var S=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},R.getTracks().forEach(function(L){if(S.getSenders().find(function(I){return I.track===L}))throw new DOMException("Track already exists.","InvalidAccessError")});var O=this.getSenders();w.apply(this,arguments);var P=this.getSenders().filter(function(L){return O.indexOf(L)===-1});this._shimmedLocalStreams[R.id]=[R].concat(P)};var x=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(R){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[R.id],x.apply(this,arguments)};var T=m.RTCPeerConnection.prototype.removeTrack;m.RTCPeerConnection.prototype.removeTrack=function(R){var S=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},R&&Object.keys(this._shimmedLocalStreams).forEach(function(O){var P=S._shimmedLocalStreams[O].indexOf(R);P!==-1&&S._shimmedLocalStreams[O].splice(P,1),S._shimmedLocalStreams[O].length===1&&delete S._shimmedLocalStreams[O]}),T.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 P=this,L=w.apply(this);return this._reverseStreams=this._reverseStreams||{},L.map(function(I){return P._reverseStreams[I.id]})};var x=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(P){var L=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},P.getTracks().forEach(function(B){if(L.getSenders().find(function(j){return j.track===B}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[P.id]){var I=new m.MediaStream(P.getTracks());this._streams[P.id]=I,this._reverseStreams[I.id]=P,P=I}x.apply(this,[P])};var T=m.RTCPeerConnection.prototype.removeStream;m.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]},m.RTCPeerConnection.prototype.addTrack=function(P,L){var I=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var B=[].slice.call(arguments,1);if(B.length!==1||!B[0].getTracks().find(function(W){return W===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(W){return W.track===P}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var j=this._streams[L.id];if(j)j.addTrack(P),Promise.resolve().then(function(){I.dispatchEvent(new Event("negotiationneeded"))});else{var N=new m.MediaStream([P]);this._streams[L.id]=N,this._reverseStreams[N.id]=L,this.addStream(N)}return this.getSenders().find(function(W){return W.track===P})},["createOffer","createAnswer"].forEach(function(P){var L=m.RTCPeerConnection.prototype[P],I=c({},P,function(){var B=this,j=arguments;return arguments.length&&typeof arguments[0]=="function"?L.apply(this,[function(N){var W=O(B,N);j[0].apply(null,[W])},function(N){j[1]&&j[1].apply(null,N)},arguments[2]]):L.apply(this,arguments).then(function(N){return O(B,N)})});m.RTCPeerConnection.prototype[P]=I[P]});var R=m.RTCPeerConnection.prototype.setLocalDescription;m.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(P=this,L=arguments[0],I=L.sdp,Object.keys(P._reverseStreams||[]).forEach(function(B){var j=P._reverseStreams[B],N=P._streams[j.id];I=I.replace(new RegExp(j.id,"g"),N.id)}),new RTCSessionDescription({type:L.type,sdp:I})),R.apply(this,arguments)):R.apply(this,arguments);var P,L,I};var S=Object.getOwnPropertyDescriptor(m.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(m.RTCPeerConnection.prototype,"localDescription",{get:function(){var P=S.get.apply(this);return P.type===""?P:O(this,P)}}),m.RTCPeerConnection.prototype.removeTrack=function(P){var L,I=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(B){I._streams[B].getTracks().find(function(j){return P.track===j})&&(L=I._streams[B])}),L&&(L.getTracks().length===1?this.removeStream(this._reverseStreams[L.id]):L.removeTrack(P.track),this.dispatchEvent(new Event("negotiationneeded")))}}function O(P,L){var I=L.sdp;return Object.keys(P._reverseStreams||[]).forEach(function(B){var j=P._reverseStreams[B],N=P._streams[j.id];I=I.replace(new RegExp(N.id,"g"),j.id)}),new RTCSessionDescription({type:L.type,sdp:I})}}function g(m,v){!m.RTCPeerConnection&&m.webkitRTCPeerConnection&&(m.RTCPeerConnection=m.webkitRTCPeerConnection),m.RTCPeerConnection&&v.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(w){var x=m.RTCPeerConnection.prototype[w],T=c({},w,function(){return arguments[0]=new(w==="addIceCandidate"?m.RTCIceCandidate:m.RTCSessionDescription)(arguments[0]),x.apply(this,arguments)});m.RTCPeerConnection.prototype[w]=T[w]})}function p(m,v){i.wrapPeerConnectionEvent(m,"negotiationneeded",function(w){var x=w.target;if(!(v.version<72||x.getConfiguration&&x.getConfiguration().sdpSemantics==="plan-b")||x.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 E=f.startsWith("turn")&&!f.startsWith("turn:[")&&f.includes("transport=udp");return E&&!d?(d=!0,!0):E&&!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(`
1
+ var sm=Object.create;var $o=Object.defineProperty;var Ah=Object.getOwnPropertyDescriptor;var am=Object.getOwnPropertyNames;var lm=Object.getPrototypeOf,cm=Object.prototype.hasOwnProperty;var dm=(a,e,t)=>e in a?$o(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var Dl=(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 es=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),kh=(a,e)=>{for(var t in e)$o(a,t,{get:e[t],enumerable:!0})},hm=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of am(e))!cm.call(a,n)&&n!==t&&$o(a,n,{get:()=>e[n],enumerable:!(i=Ah(e,n))||i.enumerable});return a};var Fs=(a,e,t)=>(t=a!=null?sm(lm(a)):{},hm(e||!a||!a.__esModule?$o(t,"default",{value:a,enumerable:!0}):t,a));var k=(a,e,t,i)=>{for(var n=i>1?void 0:i?Ah(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&&$o(e,t,n),n};var z=(a,e,t)=>(dm(a,typeof e!="symbol"?e+"":e,t),t);var ka=es((xp,Gc)=>{parcelRequire=function(a,e,t,i){var n,r=typeof parcelRequire=="function"&&parcelRequire,o=typeof Dl=="function"&&Dl;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 E=e[l]=new s.Module(l);a[l][0].call(E.exports,b,E,E.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 xp=="object"&&typeof Gc<"u"?Gc.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),E=0,b="";E<l;)(h=f[E])<128?(b+=String.fromCharCode(h),E++):(192^h)<32?(u=(192^h)<<6|63&f[E+1],b+=String.fromCharCode(u),E+=2):(u=(15&h)<<12|(63&f[E+1])<<6|63&f[E+2],b+=String.fromCharCode(u),E+=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(),E=this.unpack();h[f]=E}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,E=Math.floor(f*Math.pow(2,52)),b=Math.pow(2,32),y=h<<31|u+1023<<20|E/b&1048575,g=E%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,x=w.addEventListener;w.addEventListener=function(R,S){if(R!==m)return x.apply(this,arguments);var O=function(P){var L=v(P);L&&(S.handleEvent?S.handleEvent(L):S(L))};return this._eventMap=this._eventMap||{},this._eventMap[m]||(this._eventMap[m]=new Map),this._eventMap[m].set(S,O),x.apply(this,[R,O])};var T=w.removeEventListener;w.removeEventListener=function(R,S){if(R!==m||!this._eventMap||!this._eventMap[m])return T.apply(this,arguments);if(!this._eventMap[m].has(S))return T.apply(this,arguments);var O=this._eventMap[m].get(S);return this._eventMap[m].delete(S),this._eventMap[m].size===0&&delete this._eventMap[m],Object.keys(this._eventMap).length===0&&delete this._eventMap,T.apply(this,[R,O])},Object.defineProperty(w,"on"+m,{get:function(){return this["_on"+m]},set:function(R){this["_on"+m]&&(this.removeEventListener(m,this["_on"+m]),delete this["_on"+m]),R&&this.addEventListener(m,this["_on"+m]=R)},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 E(p){return Object.prototype.toString.call(p)==="[object Object]"}function b(p){return E(p)?Object.keys(p).reduce(function(m,v){var w=E(p[v]),x=w?b(p[v]):p[v],T=w&&!Object.keys(x).length;return x===void 0||T?m:Object.assign(m,i({},v,x))},{}):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(x){y(p,p.get(x),v)})}))}function g(p,m,v){var w=v?"outbound-rtp":"inbound-rtp",x=new Map;if(m===null)return x;var T=[];return p.forEach(function(R){R.type==="track"&&R.trackIdentifier===m.id&&T.push(R)}),T.forEach(function(R){p.forEach(function(S){S.type===w&&S.trackId===R.id&&y(p,S,x)})}),x}},{}],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 E=u?Object.getOwnPropertyDescriptor(d,f):null;E&&(E.get||E.set)?Object.defineProperty(h,f,E):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(x,T){return x?x+T.charAt(0).toUpperCase()+T.slice(1):T==="deviceId"?"sourceId":T};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(x){m[x]!==void 0&&(g.mandatory=g.mandatory||{},g.mandatory[v(x,p)]=m[x])})}}),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(x,T,R){T in x&&!(R in x)&&(x[R]=x[T],delete x[T])};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(x){var T=(x=x.filter(function(R){return R.kind==="videoinput"})).find(function(R){return v.some(function(S){return R.label.toLowerCase().includes(S)})});return!T&&x.length&&v.includes("back")&&(T=x[x.length-1]),T&&(y.video.deviceId=m.exact?{exact:T.deviceId}:{ideal:T.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)},E=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(E(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(E(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=E,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={},x=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var T in m)if(Object.prototype.hasOwnProperty.call(m,T)){var R=x?Object.getOwnPropertyDescriptor(m,T):null;R&&(R.get||R.set)?Object.defineProperty(w,T,R):w[T]=m[T]}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(x){x.stream.addEventListener("addtrack",function(T){var R;R=m.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(O){return O.track&&O.track.id===T.track.id}):{track:T.track};var S=new Event("track");S.track=T.track,S.receiver=R,S.transceiver={receiver:R},S.streams=[x.stream],w.dispatchEvent(S)}),x.stream.getTracks().forEach(function(T){var R;R=m.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(O){return O.track&&O.track.id===T.id}):{track:T};var S=new Event("track");S.track=T,S.receiver=R,S.transceiver={receiver:R},S.streams=[x.stream],w.dispatchEvent(S)})},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(O,P){return{track:P,get dtmf(){return this._dtmf===void 0&&(P.kind==="audio"?this._dtmf=O.createDTMFSender(P):this._dtmf=null),this._dtmf},_pc:O}};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(O,P){var L=w.apply(this,arguments);return L||(L=v(this,O),this._senders.push(L)),L};var x=m.RTCPeerConnection.prototype.removeTrack;m.RTCPeerConnection.prototype.removeTrack=function(O){x.apply(this,arguments);var P=this._senders.indexOf(O);P!==-1&&this._senders.splice(P,1)}}var T=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(O){var P=this;this._senders=this._senders||[],T.apply(this,[O]),O.getTracks().forEach(function(L){P._senders.push(v(P,L))})};var R=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(O){var P=this;this._senders=this._senders||[],R.apply(this,[O]),O.getTracks().forEach(function(L){var I=P._senders.find(function(B){return B.track===L});I&&P._senders.splice(P._senders.indexOf(I),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 S=m.RTCPeerConnection.prototype.getSenders;m.RTCPeerConnection.prototype.getSenders=function(){var O=this,P=S.apply(this,[]);return P.forEach(function(L){return L._pc=O}),P},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,[x,T,R]=arguments;if(arguments.length>0&&typeof x=="function")return v.apply(this,arguments);if(v.length===0&&(arguments.length===0||typeof x!="function"))return v.apply(this,[]);var S=function(P){var L={};return P.result().forEach(function(I){var B={id:I.id,timestamp:I.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[I.type]||I.type};I.names().forEach(function(j){B[j]=I.stat(j)}),L[B.id]=B}),L},O=function(P){return new Map(Object.keys(P).map(function(L){return[L,P[L]]}))};return arguments.length>=2?v.apply(this,[function(P){T(O(S(P)))},x]):new Promise(function(P,L){v.apply(w,[function(I){P(O(S(I)))},L])}).then(T,R)}}}function E(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 R=this,S=v.apply(this,[]);return S.forEach(function(O){return O._pc=R}),S});var w=m.RTCPeerConnection.prototype.addTrack;w&&(m.RTCPeerConnection.prototype.addTrack=function(){var R=w.apply(this,arguments);return R._pc=this,R}),m.RTCRtpSender.prototype.getStats=function(){var R=this;return this._pc.getStats().then(function(S){return i.filterStats(S,R.track,!0)})}}if(!("getStats"in m.RTCRtpReceiver.prototype)){var x=m.RTCPeerConnection.prototype.getReceivers;x&&(m.RTCPeerConnection.prototype.getReceivers=function(){var R=this,S=x.apply(this,[]);return S.forEach(function(O){return O._pc=R}),S}),i.wrapPeerConnectionEvent(m,"track",function(R){return R.receiver._pc=R.srcElement,R}),m.RTCRtpReceiver.prototype.getStats=function(){var R=this;return this._pc.getStats().then(function(S){return i.filterStats(S,R.track,!1)})}}if("getStats"in m.RTCRtpSender.prototype&&"getStats"in m.RTCRtpReceiver.prototype){var T=m.RTCPeerConnection.prototype.getStats;m.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof m.MediaStreamTrack){var R,S,O,P=arguments[0];return this.getSenders().forEach(function(L){L.track===P&&(R?O=!0:R=L)}),this.getReceivers().forEach(function(L){return L.track===P&&(S?O=!0:S=L),L.track===P}),O||R&&S?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):R?R.getStats():S?S.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return T.apply(this,arguments)}}}}function b(m){m.RTCPeerConnection.prototype.getLocalStreams=function(){var R=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(S){return R._shimmedLocalStreams[S][0]})};var v=m.RTCPeerConnection.prototype.addTrack;m.RTCPeerConnection.prototype.addTrack=function(R,S){if(!S)return v.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var O=v.apply(this,arguments);return this._shimmedLocalStreams[S.id]?this._shimmedLocalStreams[S.id].indexOf(O)===-1&&this._shimmedLocalStreams[S.id].push(O):this._shimmedLocalStreams[S.id]=[S,O],O};var w=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(R){var S=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},R.getTracks().forEach(function(L){if(S.getSenders().find(function(I){return I.track===L}))throw new DOMException("Track already exists.","InvalidAccessError")});var O=this.getSenders();w.apply(this,arguments);var P=this.getSenders().filter(function(L){return O.indexOf(L)===-1});this._shimmedLocalStreams[R.id]=[R].concat(P)};var x=m.RTCPeerConnection.prototype.removeStream;m.RTCPeerConnection.prototype.removeStream=function(R){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[R.id],x.apply(this,arguments)};var T=m.RTCPeerConnection.prototype.removeTrack;m.RTCPeerConnection.prototype.removeTrack=function(R){var S=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},R&&Object.keys(this._shimmedLocalStreams).forEach(function(O){var P=S._shimmedLocalStreams[O].indexOf(R);P!==-1&&S._shimmedLocalStreams[O].splice(P,1),S._shimmedLocalStreams[O].length===1&&delete S._shimmedLocalStreams[O]}),T.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 P=this,L=w.apply(this);return this._reverseStreams=this._reverseStreams||{},L.map(function(I){return P._reverseStreams[I.id]})};var x=m.RTCPeerConnection.prototype.addStream;m.RTCPeerConnection.prototype.addStream=function(P){var L=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},P.getTracks().forEach(function(B){if(L.getSenders().find(function(j){return j.track===B}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[P.id]){var I=new m.MediaStream(P.getTracks());this._streams[P.id]=I,this._reverseStreams[I.id]=P,P=I}x.apply(this,[P])};var T=m.RTCPeerConnection.prototype.removeStream;m.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]},m.RTCPeerConnection.prototype.addTrack=function(P,L){var I=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var B=[].slice.call(arguments,1);if(B.length!==1||!B[0].getTracks().find(function(W){return W===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(W){return W.track===P}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var j=this._streams[L.id];if(j)j.addTrack(P),Promise.resolve().then(function(){I.dispatchEvent(new Event("negotiationneeded"))});else{var N=new m.MediaStream([P]);this._streams[L.id]=N,this._reverseStreams[N.id]=L,this.addStream(N)}return this.getSenders().find(function(W){return W.track===P})},["createOffer","createAnswer"].forEach(function(P){var L=m.RTCPeerConnection.prototype[P],I=c({},P,function(){var B=this,j=arguments;return arguments.length&&typeof arguments[0]=="function"?L.apply(this,[function(N){var W=O(B,N);j[0].apply(null,[W])},function(N){j[1]&&j[1].apply(null,N)},arguments[2]]):L.apply(this,arguments).then(function(N){return O(B,N)})});m.RTCPeerConnection.prototype[P]=I[P]});var R=m.RTCPeerConnection.prototype.setLocalDescription;m.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(P=this,L=arguments[0],I=L.sdp,Object.keys(P._reverseStreams||[]).forEach(function(B){var j=P._reverseStreams[B],N=P._streams[j.id];I=I.replace(new RegExp(j.id,"g"),N.id)}),new RTCSessionDescription({type:L.type,sdp:I})),R.apply(this,arguments)):R.apply(this,arguments);var P,L,I};var S=Object.getOwnPropertyDescriptor(m.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(m.RTCPeerConnection.prototype,"localDescription",{get:function(){var P=S.get.apply(this);return P.type===""?P:O(this,P)}}),m.RTCPeerConnection.prototype.removeTrack=function(P){var L,I=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(B){I._streams[B].getTracks().find(function(j){return P.track===j})&&(L=I._streams[B])}),L&&(L.getTracks().length===1?this.removeStream(this._reverseStreams[L.id]):L.removeTrack(P.track),this.dispatchEvent(new Event("negotiationneeded")))}}function O(P,L){var I=L.sdp;return Object.keys(P._reverseStreams||[]).forEach(function(B){var j=P._reverseStreams[B],N=P._streams[j.id];I=I.replace(new RegExp(N.id,"g"),j.id)}),new RTCSessionDescription({type:L.type,sdp:I})}}function g(m,v){!m.RTCPeerConnection&&m.webkitRTCPeerConnection&&(m.RTCPeerConnection=m.webkitRTCPeerConnection),m.RTCPeerConnection&&v.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(w){var x=m.RTCPeerConnection.prototype[w],T=c({},w,function(){return arguments[0]=new(w==="addIceCandidate"?m.RTCIceCandidate:m.RTCSessionDescription)(arguments[0]),x.apply(this,arguments)});m.RTCPeerConnection.prototype[w]=T[w]})}function p(m,v){i.wrapPeerConnectionEvent(m,"negotiationneeded",function(w){var x=w.target;if(!(v.version<72||x.getConfiguration&&x.getConfiguration().sdpSemantics==="plan-b")||x.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 E=f.startsWith("turn")&&!f.startsWith("turn:[")&&f.includes("transport=udp");return E&&!d?(d=!0,!0):E&&!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
2
  `).map(function(r){return r.trim()})},i.splitSections=function(n){return n.split(`
3
3
  m=`).map(function(r,o){return(o>0?"m="+r:r).trim()+`\r
4
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
@@ -47,7 +47,7 @@ t=0 0\r
47
47
  `,h.rtpSender&&h.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+h.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+`\r
48
48
  `),y}function o(h,u){var f=!1;return(h=JSON.parse(JSON.stringify(h))).filter(function(E){if(E&&(E.urls||E.url)){var b=E.urls||E.url;E.url&&!E.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 E.url,E.urls=y?b[0]:b,!!b.length}})}function s(h,u){var f={codecs:[],headerExtensions:[],fecMechanisms:[]},E=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=E(y.parameters.apt,p),w=E(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(E){return u.foundation===E.foundation&&u.ip===E.ip&&u.port===E.port&&u.priority===E.priority&&u.protocol===E.protocol&&u.type===E.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 E(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 x=m.getTracks()[w];v.addEventListener("enabled",function(T){x.enabled=T.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 x=!w.candidate||Object.keys(w.candidate).length===0;v.state=x?"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(x){if(!(m.usingBundle&&p>0)){var T=new Event("icecandidate");T.candidate={sdpMid:g,sdpMLineIndex:p};var R=x.candidate,S=!R||Object.keys(R).length===0;if(S)v.state!=="new"&&v.state!=="gathering"||(v.state="completed");else{v.state==="new"&&(v.state="gathering"),R.component=1,R.ufrag=v.getLocalParameters().usernameFragment;var O=i.writeCandidate(R);T.candidate=Object.assign(T.candidate,i.parseCandidate(O)),T.candidate.candidate=O,T.candidate.toJSON=function(){return{candidate:T.candidate.candidate,sdpMid:T.candidate.sdpMid,sdpMLineIndex:T.candidate.sdpMLineIndex,usernameFragment:T.candidate.usernameFragment}}}var P=i.getMediaSections(m._localDescription.sdp);P[T.candidate.sdpMLineIndex]+=S?`a=end-of-candidates\r
49
49
  `:"a="+T.candidate.candidate+`\r
50
- `,m._localDescription.sdp=i.getDescription(m._localDescription.sdp)+P.join("");var L=m.transceivers.every(function(I){return I.iceGatherer&&I.iceGatherer.state==="completed"});m.iceGatheringState!=="gathering"&&(m.iceGatheringState="gathering",m._emitGatheringStateChange()),S||m._dispatchEvent("icecandidate",T),L&&(m._dispatchEvent("icecandidate",new Event("icecandidate")),m.iceGatheringState="complete",m._emitGatheringStateChange())}},h.setTimeout(function(){w.forEach(function(x){v.onlocalcandidate(x)})},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(x,T){var R=i.parseRtpParameters(x);v.transceivers[T].localCapabilities=R}),v.transceivers.forEach(function(x,T){v._gather(x.mid,T)});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(x,T){var R=v.transceivers[T],S=R.iceGatherer,O=R.iceTransport,P=R.dtlsTransport,L=R.localCapabilities,I=R.remoteCapabilities;if(!(i.isRejected(x)&&i.matchPrefix(x,"a=bundle-only").length===0)&&!R.rejected){var B=i.getIceParameters(x,m),j=i.getDtlsParameters(x,m);w&&(j.role="server"),v.usingBundle&&T!==0||(v._gather(R.mid,T),O.state==="new"&&O.start(S,B,w?"controlling":"controlled"),P.state==="new"&&P.start(j));var N=s(L,I);v._transceive(R,N.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(O){m[O.id]=O});var v=[],w=i.splitSections(g.sdp),x=w.shift(),T=i.matchPrefix(x,"a=ice-lite").length>0,R=i.matchPrefix(x,"a=group:BUNDLE ").length>0;p.usingBundle=R;var S=i.matchPrefix(x,"a=ice-options:")[0];return p.canTrickleIceCandidates=!!S&&S.substr(14).split(" ").indexOf("trickle")>=0,w.forEach(function(O,P){var L=i.splitLines(O),I=i.getKind(O),B=i.isRejected(O)&&i.matchPrefix(O,"a=bundle-only").length===0,j=L[0].substr(2).split(" ")[2],N=i.getDirection(O,x),W=i.parseMsid(O),Z=i.getMid(O)||i.generateIdentifier();if(B||I==="application"&&(j==="DTLS/SCTP"||j==="UDP/DTLS/SCTP"))p.transceivers[P]={mid:Z,kind:I,protocol:j,rejected:!0};else{var G,ze,ge,X,qe,cn,Kn,Ii,At;!B&&p.transceivers[P]&&p.transceivers[P].rejected&&(p.transceivers[P]=p._createTransceiver(I,!0));var Eh,wh,_h=i.parseRtpParameters(O);B||(Eh=i.getIceParameters(O,x),(wh=i.getDtlsParameters(O,x)).role="client"),Kn=i.parseRtpEncodingParameters(O);var xh=i.parseRtcpParameters(O),Th=i.matchPrefix(O,"a=end-of-candidates",x).length>0,jr=i.matchPrefix(O,"a=candidate:").map(function(rt){return i.parseCandidate(rt)}).filter(function(rt){return rt.component===1});if((g.type==="offer"||g.type==="answer")&&!B&&R&&P>0&&p.transceivers[P]&&(p._disposeIceAndDtlsTransports(P),p.transceivers[P].iceGatherer=p.transceivers[0].iceGatherer,p.transceivers[P].iceTransport=p.transceivers[0].iceTransport,p.transceivers[P].dtlsTransport=p.transceivers[0].dtlsTransport,p.transceivers[P].rtpSender&&p.transceivers[P].rtpSender.setTransport(p.transceivers[0].dtlsTransport),p.transceivers[P].rtpReceiver&&p.transceivers[P].rtpReceiver.setTransport(p.transceivers[0].dtlsTransport)),g.type!=="offer"||B)g.type==="answer"&&!B&&(ze=(G=p.transceivers[P]).iceGatherer,ge=G.iceTransport,X=G.dtlsTransport,qe=G.rtpReceiver,cn=G.sendEncodingParameters,Ii=G.localCapabilities,p.transceivers[P].recvEncodingParameters=Kn,p.transceivers[P].remoteCapabilities=_h,p.transceivers[P].rtcpParameters=xh,jr.length&&ge.state==="new"&&(!T&&!Th||R&&P!==0?jr.forEach(function(rt){d(G.iceTransport,rt)}):ge.setRemoteCandidates(jr)),R&&P!==0||(ge.state==="new"&&ge.start(ze,Eh,"controlling"),X.state==="new"&&X.start(wh)),!s(G.localCapabilities,G.remoteCapabilities).codecs.filter(function(rt){return rt.name.toLowerCase()==="rtx"}).length&&G.sendEncodingParameters[0].rtx&&delete G.sendEncodingParameters[0].rtx,p._transceive(G,N==="sendrecv"||N==="recvonly",N==="sendrecv"||N==="sendonly"),!qe||N!=="sendrecv"&&N!=="sendonly"?delete G.rtpReceiver:(At=qe.track,W?(m[W.stream]||(m[W.stream]=new h.MediaStream),f(At,m[W.stream]),v.push([At,qe,m[W.stream]])):(m.default||(m.default=new h.MediaStream),f(At,m.default),v.push([At,qe,m.default]))));else{(G=p.transceivers[P]||p._createTransceiver(I)).mid=Z,G.iceGatherer||(G.iceGatherer=p._createIceGatherer(P,R)),jr.length&&G.iceTransport.state==="new"&&(!Th||R&&P!==0?jr.forEach(function(rt){d(G.iceTransport,rt)}):G.iceTransport.setRemoteCandidates(jr)),Ii=h.RTCRtpReceiver.getCapabilities(I),u<15019&&(Ii.codecs=Ii.codecs.filter(function(rt){return rt.name!=="rtx"})),cn=G.sendEncodingParameters||[{ssrc:1001*(2*P+2)}];var Br,Al=!1;N==="sendrecv"||N==="sendonly"?(Al=!G.rtpReceiver,qe=G.rtpReceiver||new h.RTCRtpReceiver(G.dtlsTransport,I),Al&&(At=qe.track,W&&W.stream==="-"||(W?(m[W.stream]||(m[W.stream]=new h.MediaStream,Object.defineProperty(m[W.stream],"id",{get:function(){return W.stream}})),Object.defineProperty(At,"id",{get:function(){return W.track}}),Br=m[W.stream]):(m.default||(m.default=new h.MediaStream),Br=m.default)),Br&&(f(At,Br),G.associatedRemoteMediaStreams.push(Br)),v.push([At,qe,Br]))):G.rtpReceiver&&G.rtpReceiver.track&&(G.associatedRemoteMediaStreams.forEach(function(rt){var kl,Rh,Ch=rt.getTracks().find(function($f){return $f.id===G.rtpReceiver.track.id});Ch&&(kl=Ch,(Rh=rt).removeTrack(kl),Rh.dispatchEvent(new h.MediaStreamTrackEvent("removetrack",{track:kl})))}),G.associatedRemoteMediaStreams=[]),G.localCapabilities=Ii,G.remoteCapabilities=_h,G.rtpReceiver=qe,G.rtcpParameters=xh,G.sendEncodingParameters=cn,G.recvEncodingParameters=Kn,p._transceive(p.transceivers[P],!1,Al)}}}),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(O){var P=m[O];if(P.getTracks().length){if(p.remoteStreams.indexOf(P)===-1){p.remoteStreams.push(P);var L=new Event("addstream");L.stream=P,h.setTimeout(function(){p._dispatchEvent("addstream",L)})}v.forEach(function(I){var B=I[0],j=I[1];P.id===I[2].id&&E(p,B,j,[P])})}}),v.forEach(function(O){O[2]||E(p,O[0],O[1],[])}),h.setTimeout(function(){p&&p.transceivers&&p.transceivers.forEach(function(O){O.iceTransport&&O.iceTransport.state==="new"&&O.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),O.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(T){return T.kind==="audio"}).length,m=g.transceivers.filter(function(T){return T.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(T){T.kind==="audio"?--p<0&&(T.wantReceive=!1):T.kind==="video"&&--m<0&&(T.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(T,R){var S=T.track,O=T.kind,P=T.mid||i.generateIdentifier();T.mid=P,T.iceGatherer||(T.iceGatherer=g._createIceGatherer(R,g.usingBundle));var L=h.RTCRtpSender.getCapabilities(O);u<15019&&(L.codecs=L.codecs.filter(function(B){return B.name!=="rtx"})),L.codecs.forEach(function(B){B.name==="H264"&&B.parameters["level-asymmetry-allowed"]===void 0&&(B.parameters["level-asymmetry-allowed"]="1"),T.remoteCapabilities&&T.remoteCapabilities.codecs&&T.remoteCapabilities.codecs.forEach(function(j){B.name.toLowerCase()===j.name.toLowerCase()&&B.clockRate===j.clockRate&&(B.preferredPayloadType=j.payloadType)})}),L.headerExtensions.forEach(function(B){(T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[]).forEach(function(j){B.uri===j.uri&&(B.id=j.id)})});var I=T.sendEncodingParameters||[{ssrc:1001*(2*R+1)}];S&&u>=15019&&O==="video"&&!I[0].rtx&&(I[0].rtx={ssrc:I[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new h.RTCRtpReceiver(T.dtlsTransport,O)),T.localCapabilities=L,T.sendEncodingParameters=I}),g._config.bundlePolicy!=="max-compat"&&(w+="a=group:BUNDLE "+g.transceivers.map(function(T){return T.mid}).join(" ")+`\r
50
+ `,m._localDescription.sdp=i.getDescription(m._localDescription.sdp)+P.join("");var L=m.transceivers.every(function(I){return I.iceGatherer&&I.iceGatherer.state==="completed"});m.iceGatheringState!=="gathering"&&(m.iceGatheringState="gathering",m._emitGatheringStateChange()),S||m._dispatchEvent("icecandidate",T),L&&(m._dispatchEvent("icecandidate",new Event("icecandidate")),m.iceGatheringState="complete",m._emitGatheringStateChange())}},h.setTimeout(function(){w.forEach(function(x){v.onlocalcandidate(x)})},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(x,T){var R=i.parseRtpParameters(x);v.transceivers[T].localCapabilities=R}),v.transceivers.forEach(function(x,T){v._gather(x.mid,T)});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(x,T){var R=v.transceivers[T],S=R.iceGatherer,O=R.iceTransport,P=R.dtlsTransport,L=R.localCapabilities,I=R.remoteCapabilities;if(!(i.isRejected(x)&&i.matchPrefix(x,"a=bundle-only").length===0)&&!R.rejected){var B=i.getIceParameters(x,m),j=i.getDtlsParameters(x,m);w&&(j.role="server"),v.usingBundle&&T!==0||(v._gather(R.mid,T),O.state==="new"&&O.start(S,B,w?"controlling":"controlled"),P.state==="new"&&P.start(j));var N=s(L,I);v._transceive(R,N.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(O){m[O.id]=O});var v=[],w=i.splitSections(g.sdp),x=w.shift(),T=i.matchPrefix(x,"a=ice-lite").length>0,R=i.matchPrefix(x,"a=group:BUNDLE ").length>0;p.usingBundle=R;var S=i.matchPrefix(x,"a=ice-options:")[0];return p.canTrickleIceCandidates=!!S&&S.substr(14).split(" ").indexOf("trickle")>=0,w.forEach(function(O,P){var L=i.splitLines(O),I=i.getKind(O),B=i.isRejected(O)&&i.matchPrefix(O,"a=bundle-only").length===0,j=L[0].substr(2).split(" ")[2],N=i.getDirection(O,x),W=i.parseMsid(O),Z=i.getMid(O)||i.generateIdentifier();if(B||I==="application"&&(j==="DTLS/SCTP"||j==="UDP/DTLS/SCTP"))p.transceivers[P]={mid:Z,kind:I,protocol:j,rejected:!0};else{var G,Ne,me,X,We,hn,Jn,Mi,kt;!B&&p.transceivers[P]&&p.transceivers[P].rejected&&(p.transceivers[P]=p._createTransceiver(I,!0));var xh,Th,Rh=i.parseRtpParameters(O);B||(xh=i.getIceParameters(O,x),(Th=i.getDtlsParameters(O,x)).role="client"),Jn=i.parseRtpEncodingParameters(O);var Ch=i.parseRtcpParameters(O),Sh=i.matchPrefix(O,"a=end-of-candidates",x).length>0,Br=i.matchPrefix(O,"a=candidate:").map(function(rt){return i.parseCandidate(rt)}).filter(function(rt){return rt.component===1});if((g.type==="offer"||g.type==="answer")&&!B&&R&&P>0&&p.transceivers[P]&&(p._disposeIceAndDtlsTransports(P),p.transceivers[P].iceGatherer=p.transceivers[0].iceGatherer,p.transceivers[P].iceTransport=p.transceivers[0].iceTransport,p.transceivers[P].dtlsTransport=p.transceivers[0].dtlsTransport,p.transceivers[P].rtpSender&&p.transceivers[P].rtpSender.setTransport(p.transceivers[0].dtlsTransport),p.transceivers[P].rtpReceiver&&p.transceivers[P].rtpReceiver.setTransport(p.transceivers[0].dtlsTransport)),g.type!=="offer"||B)g.type==="answer"&&!B&&(Ne=(G=p.transceivers[P]).iceGatherer,me=G.iceTransport,X=G.dtlsTransport,We=G.rtpReceiver,hn=G.sendEncodingParameters,Mi=G.localCapabilities,p.transceivers[P].recvEncodingParameters=Jn,p.transceivers[P].remoteCapabilities=Rh,p.transceivers[P].rtcpParameters=Ch,Br.length&&me.state==="new"&&(!T&&!Sh||R&&P!==0?Br.forEach(function(rt){d(G.iceTransport,rt)}):me.setRemoteCandidates(Br)),R&&P!==0||(me.state==="new"&&me.start(Ne,xh,"controlling"),X.state==="new"&&X.start(Th)),!s(G.localCapabilities,G.remoteCapabilities).codecs.filter(function(rt){return rt.name.toLowerCase()==="rtx"}).length&&G.sendEncodingParameters[0].rtx&&delete G.sendEncodingParameters[0].rtx,p._transceive(G,N==="sendrecv"||N==="recvonly",N==="sendrecv"||N==="sendonly"),!We||N!=="sendrecv"&&N!=="sendonly"?delete G.rtpReceiver:(kt=We.track,W?(m[W.stream]||(m[W.stream]=new h.MediaStream),f(kt,m[W.stream]),v.push([kt,We,m[W.stream]])):(m.default||(m.default=new h.MediaStream),f(kt,m.default),v.push([kt,We,m.default]))));else{(G=p.transceivers[P]||p._createTransceiver(I)).mid=Z,G.iceGatherer||(G.iceGatherer=p._createIceGatherer(P,R)),Br.length&&G.iceTransport.state==="new"&&(!Sh||R&&P!==0?Br.forEach(function(rt){d(G.iceTransport,rt)}):G.iceTransport.setRemoteCandidates(Br)),Mi=h.RTCRtpReceiver.getCapabilities(I),u<15019&&(Mi.codecs=Mi.codecs.filter(function(rt){return rt.name!=="rtx"})),hn=G.sendEncodingParameters||[{ssrc:1001*(2*P+2)}];var Fr,Ml=!1;N==="sendrecv"||N==="sendonly"?(Ml=!G.rtpReceiver,We=G.rtpReceiver||new h.RTCRtpReceiver(G.dtlsTransport,I),Ml&&(kt=We.track,W&&W.stream==="-"||(W?(m[W.stream]||(m[W.stream]=new h.MediaStream,Object.defineProperty(m[W.stream],"id",{get:function(){return W.stream}})),Object.defineProperty(kt,"id",{get:function(){return W.track}}),Fr=m[W.stream]):(m.default||(m.default=new h.MediaStream),Fr=m.default)),Fr&&(f(kt,Fr),G.associatedRemoteMediaStreams.push(Fr)),v.push([kt,We,Fr]))):G.rtpReceiver&&G.rtpReceiver.track&&(G.associatedRemoteMediaStreams.forEach(function(rt){var Ll,Ph,Oh=rt.getTracks().find(function(om){return om.id===G.rtpReceiver.track.id});Oh&&(Ll=Oh,(Ph=rt).removeTrack(Ll),Ph.dispatchEvent(new h.MediaStreamTrackEvent("removetrack",{track:Ll})))}),G.associatedRemoteMediaStreams=[]),G.localCapabilities=Mi,G.remoteCapabilities=Rh,G.rtpReceiver=We,G.rtcpParameters=Ch,G.sendEncodingParameters=hn,G.recvEncodingParameters=Jn,p._transceive(p.transceivers[P],!1,Ml)}}}),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(O){var P=m[O];if(P.getTracks().length){if(p.remoteStreams.indexOf(P)===-1){p.remoteStreams.push(P);var L=new Event("addstream");L.stream=P,h.setTimeout(function(){p._dispatchEvent("addstream",L)})}v.forEach(function(I){var B=I[0],j=I[1];P.id===I[2].id&&E(p,B,j,[P])})}}),v.forEach(function(O){O[2]||E(p,O[0],O[1],[])}),h.setTimeout(function(){p&&p.transceivers&&p.transceivers.forEach(function(O){O.iceTransport&&O.iceTransport.state==="new"&&O.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),O.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(T){return T.kind==="audio"}).length,m=g.transceivers.filter(function(T){return T.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(T){T.kind==="audio"?--p<0&&(T.wantReceive=!1):T.kind==="video"&&--m<0&&(T.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(T,R){var S=T.track,O=T.kind,P=T.mid||i.generateIdentifier();T.mid=P,T.iceGatherer||(T.iceGatherer=g._createIceGatherer(R,g.usingBundle));var L=h.RTCRtpSender.getCapabilities(O);u<15019&&(L.codecs=L.codecs.filter(function(B){return B.name!=="rtx"})),L.codecs.forEach(function(B){B.name==="H264"&&B.parameters["level-asymmetry-allowed"]===void 0&&(B.parameters["level-asymmetry-allowed"]="1"),T.remoteCapabilities&&T.remoteCapabilities.codecs&&T.remoteCapabilities.codecs.forEach(function(j){B.name.toLowerCase()===j.name.toLowerCase()&&B.clockRate===j.clockRate&&(B.preferredPayloadType=j.payloadType)})}),L.headerExtensions.forEach(function(B){(T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[]).forEach(function(j){B.uri===j.uri&&(B.id=j.id)})});var I=T.sendEncodingParameters||[{ssrc:1001*(2*R+1)}];S&&u>=15019&&O==="video"&&!I[0].rtx&&(I[0].rtx={ssrc:I[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new h.RTCRtpReceiver(T.dtlsTransport,O)),T.localCapabilities=L,T.sendEncodingParameters=I}),g._config.bundlePolicy!=="max-compat"&&(w+="a=group:BUNDLE "+g.transceivers.map(function(T){return T.mid}).join(" ")+`\r
51
51
  `),w+=`a=ice-options:trickle\r
52
52
  `,g.transceivers.forEach(function(T,R){w+=r(T,T.localCapabilities,"offer",T.stream,g._dtlsRole),w+=`a=rtcp-rsize\r
53
53
  `,!T.iceGatherer||g.iceGatheringState==="new"||R!==0&&g.usingBundle||(T.iceGatherer.getLocalCandidates().forEach(function(S){S.component=1,w+="a="+i.writeCandidate(S)+`\r
@@ -75,9 +75,9 @@ a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
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),E=0,b=0;b<u;){var y=Math.min(u,b+t.util.chunkedMTU),g=l.slice(b,y),p={__peerData:this._dataCount,n:E,data:g,total:f};h.push(p),b=y,E++}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,E){if(typeof u!="function")throw new TypeError("The listener must be a function");var b=new o(u,f||l,E),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,E=u.length,b=new Array(E);f<E;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,E,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,E),!0;case 6:return m.fn.call(m.context,h,u,f,E,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,x=m.length;for(p=0;p<x;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 E=n?n+l:l;if(!this._events[E])return this;if(!h)return c(this,E),this;var b=this._events[E];if(b.fn)b.fn!==h||f&&!b.once||u&&b.context!==u||c(this,E);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[E]=g.length===1?g[0]:g:c(this,E)}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),E=[];try{for(;(d===void 0||d-- >0)&&!(h=f.next()).done;)E.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 E},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,E){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,E)};return function(f,E){if(typeof E!="function"&&E!==null)throw new TypeError("Class extends value "+String(E)+" is not a constructor or null");function b(){this.constructor=f}u(f,E),f.prototype=E===null?Object.create(E):(b.prototype=E.prototype,new b)}}(),n=this&&this.__read||function(u,f){var E=typeof Symbol=="function"&&u[Symbol.iterator];if(!E)return u;var b,y,g=E.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&&(E=g.return)&&E.call(g)}finally{if(y)throw y.error}}return p},r=this&&this.__spreadArray||function(u,f){for(var E=0,b=f.length,y=u.length;E<b;E++,y++)u[y]=f[E];return u},o=this&&this.__values||function(u){var f=typeof Symbol=="function"&&Symbol.iterator,E=f&&u[f],b=0;if(E)return E.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(E,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=E?"wss://":"ws://";return v._baseUrl=w+b+":"+y+g+"peerjs?key="+p,v}return i(f,u),f.prototype.start=function(E,b){var y=this;this._id=E;var g=this._baseUrl+"&id="+E+"&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 E=this;this._wsPingTimer=setTimeout(function(){E._sendHeartbeat()},this.pingInterval)},f.prototype._sendHeartbeat=function(){if(this._wsOpen()){var E=JSON.stringify({type:l.ServerMessageType.Heartbeat});this._socket.send(E),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 E,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){E={error:v}}finally{try{p&&!p.done&&(b=g.return)&&b.call(g)}finally{if(E)throw E.error}}},f.prototype.send=function(E){if(!this._disconnected)if(this._id)if(E.type){if(this._wsOpen()){var b=JSON.stringify(E);this._socket.send(b)}}else this.emit(l.SocketEventType.Error,"Invalid message");else this._messagesQueue.push(E)},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,E=arguments.length;f<E;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,E){return new(f||(f=Promise))(function(b,y){function g(v){try{m(E.next(v))}catch(w){y(w)}}function p(v){try{m(E.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(x){x(w)})).then(g,p)}m((E=E.apply(h,u||[])).next())})},r=this&&this.__generator||function(h,u){var f,E,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,E&&(b=2&w[0]?E.return:w[0]?E.throw||((b=E.return)&&b.call(E),0):E.next)&&!(b=b.call(E,w[1])).done)return b;switch(E=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++,E=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(x){w=[6,x],E=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 E=this.connection,b={ordered:!!u.reliable},y=f.createDataChannel(E.label,b);E.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,E=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 "+E+":",p.candidate),g.socket.send({type:d.ServerMessageType.Candidate,payload:{candidate:p.candidate,type:y,connectionId:b},dst:E}))},u.oniceconnectionstatechange=function(){switch(u.iceConnectionState){case"failed":c.default.log("iceConnectionState is failed, closing connections to "+E),f.connection.emit(d.ConnectionEventType.Error,new Error("Negotiation of connection to "+E+" failed.")),f.connection.close();break;case"closed":c.default.log("iceConnectionState is closed, closing connections to "+E),f.connection.emit(d.ConnectionEventType.Error,new Error("Connection to "+E+" closed.")),f.connection.close();break;case"disconnected":c.default.log("iceConnectionState changed to disconnected on the connection with "+E);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(E,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(E,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",E=!1;if(this.connection.type===d.ConnectionType.Data){var b=this.connection.dataChannel;b&&(E=!!b.readyState&&b.readyState!=="closed")}(f||E)&&u.close()}},h.prototype._makeOffer=function(){return n(this,void 0,Promise,function(){var u,f,E,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:E=m.sent(),c.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(E.sdp=this.connection.options.sdpTransform(E.sdp)||E.sdp),m.label=3;case 3:return m.trys.push([3,5,,6]),[4,u.setLocalDescription(E)];case 4:return m.sent(),c.default.log("Set localDescription:",E,"for:"+this.connection.peer),b={sdp:E,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,E,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:E=g.sent(),c.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(E.sdp=this.connection.options.sdpTransform(E.sdp)||E.sdp),g.label=3;case 3:return g.trys.push([3,5,,6]),[4,u.setLocalDescription(E)];case 4:return g.sent(),c.default.log("Set localDescription:",E,"for:"+this.connection.peer),f.socket.send({type:d.ServerMessageType.Answer,payload:{sdp:E,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 E,b,y,g;return r(this,function(p){switch(p.label){case 0:f=new RTCSessionDescription(f),E=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,E.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,E,b,y,g,p;return r(this,function(m){switch(m.label){case 0:c.default.log("handleCandidate:",u),f=u.candidate,E=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:E,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(E){f.addTrack(E,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(E,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])})(E,b)};return function(E,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=E}f(E,b),E.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 E,b=1,y=arguments.length;b<y;b++)for(var g in E=arguments[b])Object.prototype.hasOwnProperty.call(E,g)&&(f[g]=E[g]);return f}).apply(this,arguments)},r=this&&this.__values||function(f){var E=typeof Symbol=="function"&&Symbol.iterator,b=E&&f[E],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(E?"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 E(b,y,g){var p=f.call(this,b,y,g)||this;return p._localStream=p.options._stream,p.connectionId=p.options.connectionId||E.ID_PREFIX+s.util.randomToken(),p._negotiator=new d.Negotiator(p),p._localStream&&p._negotiator.startConnection({_stream:p._localStream,originator:!0}),p}return i(E,f),Object.defineProperty(E.prototype,"type",{get:function(){return l.ConnectionType.Media},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),E.prototype.addStream=function(b){c.default.log("Receiving stream",b),this._remoteStream=b,f.prototype.emit.call(this,l.ConnectionEventType.Stream,b)},E.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)}},E.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 x=w.value;this.handleMessage(x)}}catch(T){g={error:T}}finally{try{w&&!w.done&&(p=v.return)&&p.call(v)}finally{if(g)throw g.error}}this._open=!0}},E.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))},E.ID_PREFIX="mc_",E}(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(E,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])})(E,b)};return function(E,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=E}f(E,b),E.prototype=b===null?Object.create(b):(y.prototype=b.prototype,new y)}}(),n=this&&this.__values||function(f){var E=typeof Symbol=="function"&&Symbol.iterator,b=E&&f[E],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(E?"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 E(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||E.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(E,f),Object.defineProperty(E.prototype,"type",{get:function(){return d.ConnectionType.Data},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),E.prototype.initialize=function(b){this._dc=b,this._configureDataChannel()},E.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()}},E.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 x=o.util.unpack(w);y.emit(d.ConnectionEventType.Data,x)});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)},E.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})}},E.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))},E.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."))},E.prototype._bufferedSend=function(b){!this._buffering&&this._trySend(b)||(this._buffer.push(b),this._bufferSize=this._buffer.length)},E.prototype._trySend=function(b){var y=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>E.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},E.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())}},E.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(x){y={error:x}}finally{try{v&&!v.done&&(g=m.return)&&g.call(m)}finally{if(y)throw y.error}}},E.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)}},E.ID_PREFIX="dc_",E.MAX_BUFFERED_AMOUNT=8388608,E}(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,E){function b(p){try{g(u.next(p))}catch(m){E(m)}}function y(p){try{g(u.throw(p))}catch(m){E(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,E,b={label:0,sent:function(){if(1&f[0])throw f[1];return f[1]},trys:[],ops:[]};return E={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(E[Symbol.iterator]=function(){return this}),E;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(E){switch(E.label){case 0:l=this._buildUrl("id"),E.label=1;case 1:return E.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((h=E.sent()).status!==200)throw new Error("Error. Status:"+h.status);return[2,h.text()];case 3:throw u=E.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(E){switch(E.label){case 0:l=this._buildUrl("peers"),E.label=1;case 1:return E.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((h=E.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=E.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,x){w.__proto__=x}||function(w,x){for(var T in x)Object.prototype.hasOwnProperty.call(x,T)&&(w[T]=x[T])})(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 x in m=arguments[v])Object.prototype.hasOwnProperty.call(m,x)&&(p[x]=m[x]);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,x,T=v.call(p),R=[];try{for(;(m===void 0||m-- >0)&&!(w=T.next()).done;)R.push(w.value)}catch(S){x={error:S}}finally{try{w&&!w.done&&(v=T.return)&&v.call(T)}finally{if(x)throw x.error}}return R},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"),E=a("./enums"),b=a("./api"),y=function(){return function(){}}(),g=function(p){function m(v,w){var x,T=p.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,v&&v.constructor==Object?w=v:v&&(x=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),T._options=w,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 b.API(w),T._socket=T._createServerConnection(),d.util.supports.audioVideo||d.util.supports.data?x&&!d.util.validateId(x)?(T._delayedAbort(E.PeerErrorType.InvalidID,'ID "'+x+'" is invalid'),T):(x?T._initialize(x):T._api.retrieveId().then(function(R){return T._initialize(R)}).catch(function(R){return T._abort(E.PeerErrorType.ServerError,R)}),T):(T._delayedAbort(E.PeerErrorType.BrowserIncompatible,"The current browser does not support WebRTC"),T)}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,x=Object.create(null);try{for(var T=r(this._connections),R=T.next();!R.done;R=T.next()){var S=o(R.value,2),O=S[0],P=S[1];x[O]=P}}catch(L){v={error:L}}finally{try{R&&!R.done&&(w=T.return)&&w.call(T)}finally{if(v)throw v.error}}return x},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(E.SocketEventType.Message,function(x){v._handleMessage(x)}),w.on(E.SocketEventType.Error,function(x){v._abort(E.PeerErrorType.SocketError,x)}),w.on(E.SocketEventType.Disconnected,function(){v.disconnected||(v.emitError(E.PeerErrorType.Network,"Lost connection to server."),v.disconnect())}),w.on(E.SocketEventType.Close,function(){v.disconnected||v._abort(E.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,x,T=v.type,R=v.payload,S=v.src;switch(T){case E.ServerMessageType.Open:this._lastServerId=this.id,this._open=!0,this.emit(E.PeerEventType.Open,this.id);break;case E.ServerMessageType.Error:this._abort(E.PeerErrorType.ServerError,R.msg);break;case E.ServerMessageType.IdTaken:this._abort(E.PeerErrorType.UnavailableID,'ID "'+this.id+'" is taken');break;case E.ServerMessageType.InvalidKey:this._abort(E.PeerErrorType.InvalidKey,'API KEY "'+this._options.key+'" is invalid');break;case E.ServerMessageType.Leave:l.default.log("Received leave message from "+S),this._cleanupPeer(S),this._connections.delete(S);break;case E.ServerMessageType.Expire:this.emitError(E.PeerErrorType.PeerUnavailable,"Could not connect to peer "+S);break;case E.ServerMessageType.Offer:var O=R.connectionId;if((j=this.getConnection(S,O))&&(j.close(),l.default.warn("Offer received for existing Connection ID:"+O)),R.type===E.ConnectionType.Media)j=new u.MediaConnection(S,this,{connectionId:O,_payload:R,metadata:R.metadata}),this._addConnection(S,j),this.emit(E.PeerEventType.Call,j);else{if(R.type!==E.ConnectionType.Data)return void l.default.warn("Received malformed connection type:"+R.type);j=new f.DataConnection(S,this,{connectionId:O,_payload:R,metadata:R.metadata,label:R.label,serialization:R.serialization,reliable:R.reliable}),this._addConnection(S,j),this.emit(E.PeerEventType.Connection,j)}var P=this._getMessages(O);try{for(var L=r(P),I=L.next();!I.done;I=L.next()){var B=I.value;j.handleMessage(B)}}catch(N){w={error:N}}finally{try{I&&!I.done&&(x=L.return)&&x.call(L)}finally{if(w)throw w.error}}break;default:if(!R)return void l.default.warn("You received a malformed message from "+S+" of type "+T);var j;O=R.connectionId,(j=this.getConnection(S,O))&&j.peerConnection?j.handleMessage(v):O?this._storeMessage(O,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(E.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");var x=new f.DataConnection(v,this,w);return this._addConnection(v,x),x},m.prototype.call=function(v,w,x){if(x===void 0&&(x={}),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(E.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");if(w){x._stream=w;var T=new u.MediaConnection(v,this,x);return this._addConnection(v,T),T}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 x=w.indexOf(v);x!==-1&&w.splice(x,1)}this._lostMessages.delete(v.connectionId)},m.prototype.getConnection=function(v,w){var x,T,R=this._connections.get(v);if(!R)return null;try{for(var S=r(R),O=S.next();!O.done;O=S.next()){var P=O.value;if(P.connectionId===w)return P}}catch(L){x={error:L}}finally{try{O&&!O.done&&(T=S.return)&&T.call(S)}finally{if(x)throw x.error}}return null},m.prototype._delayedAbort=function(v,w){var x=this;setTimeout(function(){x._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 x;l.default.error("Error:",w),(x=typeof w=="string"?new Error(w):w).type=v,this.emit(E.PeerEventType.Error,x)},m.prototype.destroy=function(){this.destroyed||(l.default.log("Destroy peer with ID:"+this.id),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit(E.PeerEventType.Close))},m.prototype._cleanup=function(){var v,w;try{for(var x=r(this._connections.keys()),T=x.next();!T.done;T=x.next()){var R=T.value;this._cleanupPeer(R),this._connections.delete(R)}}catch(S){v={error:S}}finally{try{T&&!T.done&&(w=x.return)&&w.call(x)}finally{if(v)throw v.error}}this.socket.removeAllListeners()},m.prototype._cleanupPeer=function(v){var w,x,T=this._connections.get(v);if(T)try{for(var R=r(T),S=R.next();!S.done;S=R.next())S.value.close()}catch(O){w={error:O}}finally{try{S&&!S.done&&(x=R.return)&&x.call(R)}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(E.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(x){}),this._api.listAllPeers().then(function(x){return v(x)}).catch(function(x){return w._abort(E.PeerErrorType.ServerError,x)})},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 Rp=$o((pC,Tp)=>{(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}};Tp.exports=e})()});var Jc=$o((fC,Cp)=>{var Kc={utf8:{stringToBytes:function(a){return Kc.bin.stringToBytes(unescape(encodeURIComponent(a)))},bytesToString:function(a){return decodeURIComponent(escape(Kc.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("")}}};Cp.exports=Kc});var Op=$o((mC,Pp)=>{Pp.exports=function(a){return a!=null&&(Sp(a)||ey(a)||!!a._isBuffer)};function Sp(a){return!!a.constructor&&typeof a.constructor.isBuffer=="function"&&a.constructor.isBuffer(a)}function ey(a){return typeof a.readFloatLE=="function"&&typeof a.slice=="function"&&Sp(a.slice(0,0))}});var kp=$o((gC,Ap)=>{(function(){var a=Rp(),e=Jc().utf8,t=Op(),i=Jc().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 E=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=E(d,l,h,u,s[f+0],7,-680876936),u=E(u,d,l,h,s[f+1],12,-389564586),h=E(h,u,d,l,s[f+2],17,606105819),l=E(l,h,u,d,s[f+3],22,-1044525330),d=E(d,l,h,u,s[f+4],7,-176418897),u=E(u,d,l,h,s[f+5],12,1200080426),h=E(h,u,d,l,s[f+6],17,-1473231341),l=E(l,h,u,d,s[f+7],22,-45705983),d=E(d,l,h,u,s[f+8],7,1770035416),u=E(u,d,l,h,s[f+9],12,-1958414417),h=E(h,u,d,l,s[f+10],17,-42063),l=E(l,h,u,d,s[f+11],22,-1990404162),d=E(d,l,h,u,s[f+12],7,1804603682),u=E(u,d,l,h,s[f+13],12,-40341101),h=E(h,u,d,l,s[f+14],17,-1502002290),l=E(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,Ap.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 pw,WebGLRenderer as fw}from"three";import*as De from"three";var Zl={};Ph(Zl,{Behaviour:()=>M,Component:()=>st,GameObject:()=>C,HideFlags:()=>au,InstantiateOptions:()=>ve});import*as se from"three";var dn="__isActiveInHierarchy",Jn="builtin_components";function Zn(a,e){try{e?a(e):a()}catch(t){return console.error(t),!1}return!0}var Hl=()=>a=>a;var jl=!1,Ll=[];setTimeout(()=>{jl&&console.log(Ll)},100);function Bl(){return new URLSearchParams(window.location.search)}function H(a){jl&&!Ll.includes(a)&&Ll.push(a);let e=Bl();if(e.has(a)){let t=e.get(a);return t||!0}return!1}jl=H("help")===!0;function Fr(a,e,t){a.has(e)?a.set(e,t.toString()):a.append(e,t.toString())}function kh(a,e){window.history.replaceState(null,a,"?"+e.toString())}function Ih(a,e){return Math.floor(Math.random()*(e-a+1))+a}var Oh=["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"],Ah=["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 Mh(){let a=Oh[Math.floor(Math.random()*Oh.length)],e=Ah[Math.floor(Math.random()*Ah.length)];return a+"_"+e}function Lh(a){return a=a.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),a.trim()}function hn(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=hn(a,r,t,i);if(o)return o}if(e.children)for(let n in e.children){let r=e.children[n],o=hn(a,r,t,i);if(o)return o}}}function es(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]=es(n,e)}return t}return a}function Dh(a){return new Promise((e,t)=>{setTimeout(e,a)})}var Ml=H("debugsourcepath");function pn(a,e){if(a===void 0)return Ml&&console.warn("getPath: source is undefined, returning uri",e),e;if(e.startsWith("http"))return Ml&&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,Ml&&console.log("getPath:",a,` - changed uri from
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),E=0,b=0;b<u;){var y=Math.min(u,b+t.util.chunkedMTU),g=l.slice(b,y),p={__peerData:this._dataCount,n:E,data:g,total:f};h.push(p),b=y,E++}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,E){if(typeof u!="function")throw new TypeError("The listener must be a function");var b=new o(u,f||l,E),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,E=u.length,b=new Array(E);f<E;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,E,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,E),!0;case 6:return m.fn.call(m.context,h,u,f,E,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,x=m.length;for(p=0;p<x;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 E=n?n+l:l;if(!this._events[E])return this;if(!h)return c(this,E),this;var b=this._events[E];if(b.fn)b.fn!==h||f&&!b.once||u&&b.context!==u||c(this,E);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[E]=g.length===1?g[0]:g:c(this,E)}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),E=[];try{for(;(d===void 0||d-- >0)&&!(h=f.next()).done;)E.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 E},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,E){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,E)};return function(f,E){if(typeof E!="function"&&E!==null)throw new TypeError("Class extends value "+String(E)+" is not a constructor or null");function b(){this.constructor=f}u(f,E),f.prototype=E===null?Object.create(E):(b.prototype=E.prototype,new b)}}(),n=this&&this.__read||function(u,f){var E=typeof Symbol=="function"&&u[Symbol.iterator];if(!E)return u;var b,y,g=E.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&&(E=g.return)&&E.call(g)}finally{if(y)throw y.error}}return p},r=this&&this.__spreadArray||function(u,f){for(var E=0,b=f.length,y=u.length;E<b;E++,y++)u[y]=f[E];return u},o=this&&this.__values||function(u){var f=typeof Symbol=="function"&&Symbol.iterator,E=f&&u[f],b=0;if(E)return E.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(E,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=E?"wss://":"ws://";return v._baseUrl=w+b+":"+y+g+"peerjs?key="+p,v}return i(f,u),f.prototype.start=function(E,b){var y=this;this._id=E;var g=this._baseUrl+"&id="+E+"&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 E=this;this._wsPingTimer=setTimeout(function(){E._sendHeartbeat()},this.pingInterval)},f.prototype._sendHeartbeat=function(){if(this._wsOpen()){var E=JSON.stringify({type:l.ServerMessageType.Heartbeat});this._socket.send(E),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 E,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){E={error:v}}finally{try{p&&!p.done&&(b=g.return)&&b.call(g)}finally{if(E)throw E.error}}},f.prototype.send=function(E){if(!this._disconnected)if(this._id)if(E.type){if(this._wsOpen()){var b=JSON.stringify(E);this._socket.send(b)}}else this.emit(l.SocketEventType.Error,"Invalid message");else this._messagesQueue.push(E)},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,E=arguments.length;f<E;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,E){return new(f||(f=Promise))(function(b,y){function g(v){try{m(E.next(v))}catch(w){y(w)}}function p(v){try{m(E.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(x){x(w)})).then(g,p)}m((E=E.apply(h,u||[])).next())})},r=this&&this.__generator||function(h,u){var f,E,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,E&&(b=2&w[0]?E.return:w[0]?E.throw||((b=E.return)&&b.call(E),0):E.next)&&!(b=b.call(E,w[1])).done)return b;switch(E=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++,E=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(x){w=[6,x],E=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 E=this.connection,b={ordered:!!u.reliable},y=f.createDataChannel(E.label,b);E.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,E=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 "+E+":",p.candidate),g.socket.send({type:d.ServerMessageType.Candidate,payload:{candidate:p.candidate,type:y,connectionId:b},dst:E}))},u.oniceconnectionstatechange=function(){switch(u.iceConnectionState){case"failed":c.default.log("iceConnectionState is failed, closing connections to "+E),f.connection.emit(d.ConnectionEventType.Error,new Error("Negotiation of connection to "+E+" failed.")),f.connection.close();break;case"closed":c.default.log("iceConnectionState is closed, closing connections to "+E),f.connection.emit(d.ConnectionEventType.Error,new Error("Connection to "+E+" closed.")),f.connection.close();break;case"disconnected":c.default.log("iceConnectionState changed to disconnected on the connection with "+E);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(E,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(E,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",E=!1;if(this.connection.type===d.ConnectionType.Data){var b=this.connection.dataChannel;b&&(E=!!b.readyState&&b.readyState!=="closed")}(f||E)&&u.close()}},h.prototype._makeOffer=function(){return n(this,void 0,Promise,function(){var u,f,E,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:E=m.sent(),c.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(E.sdp=this.connection.options.sdpTransform(E.sdp)||E.sdp),m.label=3;case 3:return m.trys.push([3,5,,6]),[4,u.setLocalDescription(E)];case 4:return m.sent(),c.default.log("Set localDescription:",E,"for:"+this.connection.peer),b={sdp:E,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,E,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:E=g.sent(),c.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(E.sdp=this.connection.options.sdpTransform(E.sdp)||E.sdp),g.label=3;case 3:return g.trys.push([3,5,,6]),[4,u.setLocalDescription(E)];case 4:return g.sent(),c.default.log("Set localDescription:",E,"for:"+this.connection.peer),f.socket.send({type:d.ServerMessageType.Answer,payload:{sdp:E,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 E,b,y,g;return r(this,function(p){switch(p.label){case 0:f=new RTCSessionDescription(f),E=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,E.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,E,b,y,g,p;return r(this,function(m){switch(m.label){case 0:c.default.log("handleCandidate:",u),f=u.candidate,E=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:E,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(E){f.addTrack(E,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(E,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])})(E,b)};return function(E,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=E}f(E,b),E.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 E,b=1,y=arguments.length;b<y;b++)for(var g in E=arguments[b])Object.prototype.hasOwnProperty.call(E,g)&&(f[g]=E[g]);return f}).apply(this,arguments)},r=this&&this.__values||function(f){var E=typeof Symbol=="function"&&Symbol.iterator,b=E&&f[E],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(E?"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 E(b,y,g){var p=f.call(this,b,y,g)||this;return p._localStream=p.options._stream,p.connectionId=p.options.connectionId||E.ID_PREFIX+s.util.randomToken(),p._negotiator=new d.Negotiator(p),p._localStream&&p._negotiator.startConnection({_stream:p._localStream,originator:!0}),p}return i(E,f),Object.defineProperty(E.prototype,"type",{get:function(){return l.ConnectionType.Media},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),E.prototype.addStream=function(b){c.default.log("Receiving stream",b),this._remoteStream=b,f.prototype.emit.call(this,l.ConnectionEventType.Stream,b)},E.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)}},E.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 x=w.value;this.handleMessage(x)}}catch(T){g={error:T}}finally{try{w&&!w.done&&(p=v.return)&&p.call(v)}finally{if(g)throw g.error}}this._open=!0}},E.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))},E.ID_PREFIX="mc_",E}(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(E,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])})(E,b)};return function(E,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=E}f(E,b),E.prototype=b===null?Object.create(b):(y.prototype=b.prototype,new y)}}(),n=this&&this.__values||function(f){var E=typeof Symbol=="function"&&Symbol.iterator,b=E&&f[E],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(E?"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 E(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||E.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(E,f),Object.defineProperty(E.prototype,"type",{get:function(){return d.ConnectionType.Data},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),E.prototype.initialize=function(b){this._dc=b,this._configureDataChannel()},E.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()}},E.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 x=o.util.unpack(w);y.emit(d.ConnectionEventType.Data,x)});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)},E.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})}},E.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))},E.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."))},E.prototype._bufferedSend=function(b){!this._buffering&&this._trySend(b)||(this._buffer.push(b),this._bufferSize=this._buffer.length)},E.prototype._trySend=function(b){var y=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>E.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},E.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())}},E.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(x){y={error:x}}finally{try{v&&!v.done&&(g=m.return)&&g.call(m)}finally{if(y)throw y.error}}},E.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)}},E.ID_PREFIX="dc_",E.MAX_BUFFERED_AMOUNT=8388608,E}(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,E){function b(p){try{g(u.next(p))}catch(m){E(m)}}function y(p){try{g(u.throw(p))}catch(m){E(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,E,b={label:0,sent:function(){if(1&f[0])throw f[1];return f[1]},trys:[],ops:[]};return E={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(E[Symbol.iterator]=function(){return this}),E;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(E){switch(E.label){case 0:l=this._buildUrl("id"),E.label=1;case 1:return E.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((h=E.sent()).status!==200)throw new Error("Error. Status:"+h.status);return[2,h.text()];case 3:throw u=E.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(E){switch(E.label){case 0:l=this._buildUrl("peers"),E.label=1;case 1:return E.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((h=E.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=E.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,x){w.__proto__=x}||function(w,x){for(var T in x)Object.prototype.hasOwnProperty.call(x,T)&&(w[T]=x[T])})(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 x in m=arguments[v])Object.prototype.hasOwnProperty.call(m,x)&&(p[x]=m[x]);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,x,T=v.call(p),R=[];try{for(;(m===void 0||m-- >0)&&!(w=T.next()).done;)R.push(w.value)}catch(S){x={error:S}}finally{try{w&&!w.done&&(v=T.return)&&v.call(T)}finally{if(x)throw x.error}}return R},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"),E=a("./enums"),b=a("./api"),y=function(){return function(){}}(),g=function(p){function m(v,w){var x,T=p.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,v&&v.constructor==Object?w=v:v&&(x=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),T._options=w,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 b.API(w),T._socket=T._createServerConnection(),d.util.supports.audioVideo||d.util.supports.data?x&&!d.util.validateId(x)?(T._delayedAbort(E.PeerErrorType.InvalidID,'ID "'+x+'" is invalid'),T):(x?T._initialize(x):T._api.retrieveId().then(function(R){return T._initialize(R)}).catch(function(R){return T._abort(E.PeerErrorType.ServerError,R)}),T):(T._delayedAbort(E.PeerErrorType.BrowserIncompatible,"The current browser does not support WebRTC"),T)}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,x=Object.create(null);try{for(var T=r(this._connections),R=T.next();!R.done;R=T.next()){var S=o(R.value,2),O=S[0],P=S[1];x[O]=P}}catch(L){v={error:L}}finally{try{R&&!R.done&&(w=T.return)&&w.call(T)}finally{if(v)throw v.error}}return x},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(E.SocketEventType.Message,function(x){v._handleMessage(x)}),w.on(E.SocketEventType.Error,function(x){v._abort(E.PeerErrorType.SocketError,x)}),w.on(E.SocketEventType.Disconnected,function(){v.disconnected||(v.emitError(E.PeerErrorType.Network,"Lost connection to server."),v.disconnect())}),w.on(E.SocketEventType.Close,function(){v.disconnected||v._abort(E.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,x,T=v.type,R=v.payload,S=v.src;switch(T){case E.ServerMessageType.Open:this._lastServerId=this.id,this._open=!0,this.emit(E.PeerEventType.Open,this.id);break;case E.ServerMessageType.Error:this._abort(E.PeerErrorType.ServerError,R.msg);break;case E.ServerMessageType.IdTaken:this._abort(E.PeerErrorType.UnavailableID,'ID "'+this.id+'" is taken');break;case E.ServerMessageType.InvalidKey:this._abort(E.PeerErrorType.InvalidKey,'API KEY "'+this._options.key+'" is invalid');break;case E.ServerMessageType.Leave:l.default.log("Received leave message from "+S),this._cleanupPeer(S),this._connections.delete(S);break;case E.ServerMessageType.Expire:this.emitError(E.PeerErrorType.PeerUnavailable,"Could not connect to peer "+S);break;case E.ServerMessageType.Offer:var O=R.connectionId;if((j=this.getConnection(S,O))&&(j.close(),l.default.warn("Offer received for existing Connection ID:"+O)),R.type===E.ConnectionType.Media)j=new u.MediaConnection(S,this,{connectionId:O,_payload:R,metadata:R.metadata}),this._addConnection(S,j),this.emit(E.PeerEventType.Call,j);else{if(R.type!==E.ConnectionType.Data)return void l.default.warn("Received malformed connection type:"+R.type);j=new f.DataConnection(S,this,{connectionId:O,_payload:R,metadata:R.metadata,label:R.label,serialization:R.serialization,reliable:R.reliable}),this._addConnection(S,j),this.emit(E.PeerEventType.Connection,j)}var P=this._getMessages(O);try{for(var L=r(P),I=L.next();!I.done;I=L.next()){var B=I.value;j.handleMessage(B)}}catch(N){w={error:N}}finally{try{I&&!I.done&&(x=L.return)&&x.call(L)}finally{if(w)throw w.error}}break;default:if(!R)return void l.default.warn("You received a malformed message from "+S+" of type "+T);var j;O=R.connectionId,(j=this.getConnection(S,O))&&j.peerConnection?j.handleMessage(v):O?this._storeMessage(O,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(E.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");var x=new f.DataConnection(v,this,w);return this._addConnection(v,x),x},m.prototype.call=function(v,w,x){if(x===void 0&&(x={}),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(E.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");if(w){x._stream=w;var T=new u.MediaConnection(v,this,x);return this._addConnection(v,T),T}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 x=w.indexOf(v);x!==-1&&w.splice(x,1)}this._lostMessages.delete(v.connectionId)},m.prototype.getConnection=function(v,w){var x,T,R=this._connections.get(v);if(!R)return null;try{for(var S=r(R),O=S.next();!O.done;O=S.next()){var P=O.value;if(P.connectionId===w)return P}}catch(L){x={error:L}}finally{try{O&&!O.done&&(T=S.return)&&T.call(S)}finally{if(x)throw x.error}}return null},m.prototype._delayedAbort=function(v,w){var x=this;setTimeout(function(){x._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 x;l.default.error("Error:",w),(x=typeof w=="string"?new Error(w):w).type=v,this.emit(E.PeerEventType.Error,x)},m.prototype.destroy=function(){this.destroyed||(l.default.log("Destroy peer with ID:"+this.id),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit(E.PeerEventType.Close))},m.prototype._cleanup=function(){var v,w;try{for(var x=r(this._connections.keys()),T=x.next();!T.done;T=x.next()){var R=T.value;this._cleanupPeer(R),this._connections.delete(R)}}catch(S){v={error:S}}finally{try{T&&!T.done&&(w=x.return)&&w.call(x)}finally{if(v)throw v.error}}this.socket.removeAllListeners()},m.prototype._cleanupPeer=function(v){var w,x,T=this._connections.get(v);if(T)try{for(var R=r(T),S=R.next();!S.done;S=R.next())S.value.close()}catch(O){w={error:O}}finally{try{S&&!S.done&&(x=R.return)&&x.call(R)}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(E.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(x){}),this._api.listAllPeers().then(function(x){return v(x)}).catch(function(x){return w._abort(E.PeerErrorType.ServerError,x)})},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 Ap=es((SC,Op)=>{(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}};Op.exports=e})()});var ed=es((PC,kp)=>{var $c={utf8:{stringToBytes:function(a){return $c.bin.stringToBytes(unescape(encodeURIComponent(a)))},bytesToString:function(a){return decodeURIComponent(escape($c.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("")}}};kp.exports=$c});var Lp=es((OC,Mp)=>{Mp.exports=function(a){return a!=null&&(Ip(a)||ay(a)||!!a._isBuffer)};function Ip(a){return!!a.constructor&&typeof a.constructor.isBuffer=="function"&&a.constructor.isBuffer(a)}function ay(a){return typeof a.readFloatLE=="function"&&typeof a.slice=="function"&&Ip(a.slice(0,0))}});var Hp=es((AC,Dp)=>{(function(){var a=Ap(),e=ed().utf8,t=Lp(),i=ed().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 E=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=E(d,l,h,u,s[f+0],7,-680876936),u=E(u,d,l,h,s[f+1],12,-389564586),h=E(h,u,d,l,s[f+2],17,606105819),l=E(l,h,u,d,s[f+3],22,-1044525330),d=E(d,l,h,u,s[f+4],7,-176418897),u=E(u,d,l,h,s[f+5],12,1200080426),h=E(h,u,d,l,s[f+6],17,-1473231341),l=E(l,h,u,d,s[f+7],22,-45705983),d=E(d,l,h,u,s[f+8],7,1770035416),u=E(u,d,l,h,s[f+9],12,-1958414417),h=E(h,u,d,l,s[f+10],17,-42063),l=E(l,h,u,d,s[f+11],22,-1990404162),d=E(d,l,h,u,s[f+12],7,1804603682),u=E(u,d,l,h,s[f+13],12,-40341101),h=E(h,u,d,l,s[f+14],17,-1502002290),l=E(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,Dp.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 ww,WebGLRenderer as _w}from"three";import*as De from"three";var tc={};kh(tc,{Behaviour:()=>M,Component:()=>st,GameObject:()=>C,HideFlags:()=>uu,InstantiateOptions:()=>be});import*as qe from"three";var un="__isActiveInHierarchy",Zn="builtin_components";function $n(a,e){try{e?a(e):a()}catch(t){return console.error(t),!1}return!0}var Fl=()=>a=>a;var Nl=!1,jl=[];setTimeout(()=>{Nl&&console.log(jl)},100);function zl(){return new URLSearchParams(window.location.search)}function H(a){Nl&&!jl.includes(a)&&jl.push(a);let e=zl();if(e.has(a)){let t=e.get(a);return t||!0}return!1}Nl=H("help")===!0;function Nr(a,e,t){a.has(e)?a.set(e,t.toString()):a.append(e,t.toString())}function Lh(a,e){window.history.replaceState(null,a,"?"+e.toString())}function Dh(a,e){return Math.floor(Math.random()*(e-a+1))+a}var Ih=["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"],Mh=["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 Hh(){let a=Ih[Math.floor(Math.random()*Ih.length)],e=Mh[Math.floor(Math.random()*Mh.length)];return a+"_"+e}function jh(a){return a=a.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),a.trim()}function pn(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=pn(a,r,t,i);if(o)return o}if(e.children)for(let n in e.children){let r=e.children[n],o=pn(a,r,t,i);if(o)return o}}}function ts(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]=ts(n,e)}return t}return a}function Bh(a){return new Promise((e,t)=>{setTimeout(e,a)})}var Hl=H("debugsourcepath");function mn(a,e){if(a===void 0)return Hl&&console.warn("getPath: source is undefined, returning uri",e),e;if(e.startsWith("http"))return Hl&&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,Hl&&console.log("getPath:",a,` - changed uri from
79
79
  `,e,`
80
- \u2192 `,i),i}return e}var Dl=class{subscribeWrite(e){this.writeCallbacks.push(e)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp="__$_NEEDLE_"+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}},un=class{_watches=[];constructor(e,t){if(Array.isArray(t))for(let i of t)this._watches.push(new un(e,i));else this._watches.push(new Dl(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 lm=H("debugnewscripts"),be=[];function Li(a){if(!(a.new_scripts.length<=0)){if(lm&&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}be.length=0,a.new_scripts.length>0&&be.push(...a.new_scripts),a.new_scripts.length=0;for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),be.splice(e,1),e--;continue}t.context=a,mn(t.gameObject),Fl(t,a)}catch(t){console.error(t),Mi(be[e],a),be.splice(e,1),e--}for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed){Mi(be[e],a),be.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),mn(t.gameObject),t.activeAndEnabled&&Zn(t.__internalAwake.bind(t)))}catch(t){console.error(t),Mi(be[e],a),be.splice(e,1),e--}for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed||t.enabled===!1||(mn(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Zn(t.__internalEnable.bind(t)))}catch(t){console.error(t),Mi(be[e],a),be.splice(e,1),e--}for(let e=0;e<be.length;e++)try{let t=be[e];if(t.destroyed||!t.gameObject)continue;a.new_script_start.push(t)}catch(t){console.error(t),Mi(be[e],a),be.splice(e,1),e--}be.length=0;for(let e of a.new_scripts_post_setup_callbacks)e&&e();a.new_scripts_post_setup_callbacks.length=0}}function jh(a){!a||(a.__internalDisable(),Mi(a,a.context))}function Bs(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;Zn(i.__internalAwake.bind(i)),Zn(i.__internalEnable.bind(i)),Zn(i.__internalStart.bind(i)),a.new_script_start.splice(t,1),t--}catch(i){console.error(i),Mi(a.new_script_start[t],a),a.new_script_start.splice(t,1),t--}}function Fl(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 Mi(a,e){fn(a,e.new_scripts),fn(a,e.new_script_start),fn(a,e.scripts),fn(a,e.scripts_earlyUpdate),fn(a,e.scripts_update),fn(a,e.scripts_lateUpdate),fn(a,e.scripts_onBeforeRender),fn(a,e.scripts_onAfterRender),e.stopAllCoroutinesFrom(a)}function fn(a,e){let t=e.indexOf(a);t>=0&&e.splice(t,1)}var cm={},Hh={};function Bh(){if(!Q.Current){console.trace("Invalid call - no current context.");return}Fh(Q.Current.scene,Q.Current.scene.visible,!0)}function Fh(a,e,t){let i=!1,n=C.isActiveSelf(a);if(cm[a.uuid]=n,e&&(e=C.isActiveSelf(a)),a[dn]=e,!i){let r=Hh[a.uuid];r!==void 0&&r!==e&&t&&dm(a,o=>{e?(Zn(o.__internalAwake.bind(o)),o.onEnable()):o.onDisable()})}if(Hh[a.uuid]=e,a.children)for(let r of a.children)Fh(r,e,t)}function mn(a){let e=!0,t=a,i=!1;for(;t&&t;){if(t.type==="Scene"&&(i=!0),!C.isActiveSelf(t)){e=!1;break}t=t.parent}if(!a){console.error("GO is null");return}a[dn]=e&&i}function dm(a,e){if(a.userData?.components)for(let t of a.userData.components)e(t)}var zl=H("debuggetcomponent");function hm(a){return a==null||a.isObject3D?a:a.object&&a.object.isObject3D?a.object:a}function Vl(a,e){if(!a)return;let t=e?.new_scripts??Q.Current.new_scripts;t.includes(a)||t.push(a)}var Nh=function(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))},Ns=function(a,e,t=!0){e.userData||(e.userData={}),e.userData.components||(e.userData.components=[]),e.userData.components.push(a),a.gameObject=e,Vl(a);try{a.__internalAwake&&t&&(mn(e),a.__internalAwake())}catch(i){console.error(i)}},zh=function(a,e){if(a.gameObject!==e){if(a.gameObject&&a.gameObject.userData.components){let t=a.gameObject.userData.components.indexOf(a);a.gameObject.userData.components.splice(t,1)}if(!e.userData.components)e.userData.components=[];else if(e.userData.components.includes(a))return;e.userData.components.push(a),a.gameObject=e}},Vh=function(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(),Mi(a,a.context??Q.Current),a.__destroyed=!0,a.gameObject=null},Uh=function(a,e,t){if(!e?.userData?.components)return null;zl&&console.log("FIND",a);for(let i=0;i<e.userData.components.length;i++){let n=e.userData.components[i];if(a===null||n.constructor.name===a.name||n.constructor.name===a)if(zl&&console.log("MATCH BY NAME",n),t)t.push(n);else return n}for(let i=0;i<e.userData.components.length;i++){let n=e.userData.components[i],r=Object.getPrototypeOf(n.constructor);do{if(r===a)if(zl&&console.log("MATCH BY PROTOYPE",r),t)t.push(n);else return n;r=Object.getPrototypeOf(r)}while(r)}return t},zs=function(a,e){return Uh(a,e,null)},Vs=function(a,e,t){return t||(t=[]),Uh(a,e,t)},Us=function(a,e,t){let i=zs(a,e);if(t===!1&&i.enabled===!1)return null;if(i)return i;for(let n=0;n<e?.children?.length;n++){let r=Us(a,e.children[n]);if(r)return r}return null},Gs=function(a,e,t){t||(t=[]),Vs(a,e,t);for(let i=0;i<e?.children?.length;i++)Gs(a,e.children[i],t);return t},Fs=function(a,e){if(!e)return null;if(Array.isArray(e)){for(let i=0;i<e.length;i++){let n=hm(e[i]),r=Fs(a,n);if(r)return r}return null}let t=zs(a,e);return t||Fs(a,e.parent)},Ul=function(a,e,t){return t||(t=[]),e?(Vs(a,e,t),Ul(a,e.parent,t)):t},Gh=function(a,e,t){if(!a)return null;if(!e&&(e=Q.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e.isScene===!0||e.isObject3D===!0?e:e?.scene;for(let n in i.children){let r=i.children[n];if(t===!1&&r[dn]===!1)continue;if(r.constructor==a)return r;let o=Us(a,r);if(o)return o}return null},Wh=function(a,e,t){if(!a)return e;if(!t&&(t=Q.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;Gs(a,r,e)}return e};var Gl=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}},Y=new Gl;import*as oe from"three";import{Vector3 as pm,Quaternion as fm,Uniform as mm}from"three";var ql=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]}},Fw=new fm().setFromAxisAngle(new pm(0,1,0),Math.PI);var Xl=new ql(()=>new oe.Vector3,100);oe.Vector3.prototype.slerp=function(a,e){let t=this.length(),i=a.length(),n=Y.lerp(t,i,e);return this.lerp(a,e).normalize().multiplyScalar(n)};function q(a,e=null,t=!0){let i=e??Xl.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 le(a,e){if(!a)return;let t=Xl.get();e!==t&&t.copy(e),(a?.parent??a).worldToLocal(t),a.position.set(t.x,t.y,t.z)}function Nr(a,e,t,i){let n=Xl.get();n.set(e,t,i),le(a,n)}var $n=new oe.Quaternion,ts=new oe.Quaternion,Wl=new oe.Quaternion;function ke(a,e=null){if(!a)return ts.set(0,0,0,1);let t=e??ts;return a.parent?(a.getWorldQuaternion(t),t):t.copy(a.quaternion)}function ot(a,e){if(!a)return;e!==$n&&$n.copy(e);let t=$n;a?.parent?.getWorldQuaternion(Wl),Wl.invert();let n=Wl.multiply(t);a.quaternion.set(n.x,n.y,n.z,n.w)}function Qh(a,e,t,i,n){$n.set(e,t,i,n),ot(a,$n)}var Ws=new oe.Vector3,Nw=new oe.Vector3;function qs(a,e=null){return a?a.parent?(a.getWorldScale(e??Ws),e??Ws):Ws.copy(a.position):Ws.set(0,0,0)}var zw=new oe.Vector3,Vw=new oe.Quaternion;var qh=new oe.Euler,Xh=new oe.Euler,gm=new oe.Vector3;function bm(a){return a.getWorldQuaternion(ts),Xh.setFromQuaternion(ts),Xh}function Yh(a,e){ot(a,ts.setFromEuler(e))}function Xs(a){let e=bm(a),t=gm;return t.set(e.x,e.y,e.z),t.x=Y.toDegrees(t.x),t.y=Y.toDegrees(t.y),t.z=Y.toDegrees(t.z),t}function Qs(a,e,t,i,n=!0){n&&(e=Y.toRadians(e),t=Y.toRadians(t),i=Y.toRadians(i)),qh.set(e,t,i),$n.setFromEuler(qh),ot(a,$n)}function is(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 Uw=new oe.PlaneGeometry(2,2,1,1),Gw=new oe.WebGLRenderer({antialias:!1}),Ww=new oe.PerspectiveCamera,qw=new oe.Scene,Xw=new oe.ShaderMaterial({uniforms:{blitTexture:new mm(null)},vertexShader:`
80
+ \u2192 `,i),i}return e}var Bl=class{subscribeWrite(e){this.writeCallbacks.push(e)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp="__$_NEEDLE_"+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}},fn=class{_watches=[];constructor(e,t){if(Array.isArray(t))for(let i of t)this._watches.push(new fn(e,i));else this._watches.push(new Bl(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 fm=H("debugnewscripts"),ge=[];function Di(a){if(!(a.new_scripts.length<=0)){if(fm&&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}ge.length=0,a.new_scripts.length>0&&ge.push(...a.new_scripts),a.new_scripts.length=0;for(let e=0;e<ge.length;e++)try{let t=ge[e];if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),ge.splice(e,1),e--;continue}t.context=a,bn(t.gameObject),Vl(t,a)}catch(t){console.error(t),Li(ge[e],a),ge.splice(e,1),e--}for(let e=0;e<ge.length;e++)try{let t=ge[e];if(t.destroyed){Li(ge[e],a),ge.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),bn(t.gameObject),t.activeAndEnabled&&$n(t.__internalAwake.bind(t)))}catch(t){console.error(t),Li(ge[e],a),ge.splice(e,1),e--}for(let e=0;e<ge.length;e++)try{let t=ge[e];if(t.destroyed||t.enabled===!1||(bn(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,$n(t.__internalEnable.bind(t)))}catch(t){console.error(t),Li(ge[e],a),ge.splice(e,1),e--}for(let e=0;e<ge.length;e++)try{let t=ge[e];if(t.destroyed||!t.gameObject)continue;a.new_script_start.push(t)}catch(t){console.error(t),Li(ge[e],a),ge.splice(e,1),e--}ge.length=0;for(let e of a.new_scripts_post_setup_callbacks)e&&e();a.new_scripts_post_setup_callbacks.length=0}}function Nh(a){!a||(a.__internalDisable(),Li(a,a.context))}function Ns(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;$n(i.__internalAwake.bind(i)),$n(i.__internalEnable.bind(i)),$n(i.__internalStart.bind(i)),a.new_script_start.splice(t,1),t--}catch(i){console.error(i),Li(a.new_script_start[t],a),a.new_script_start.splice(t,1),t--}}function Vl(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 Li(a,e){gn(a,e.new_scripts),gn(a,e.new_script_start),gn(a,e.scripts),gn(a,e.scripts_earlyUpdate),gn(a,e.scripts_update),gn(a,e.scripts_lateUpdate),gn(a,e.scripts_onBeforeRender),gn(a,e.scripts_onAfterRender),e.stopAllCoroutinesFrom(a)}function gn(a,e){let t=e.indexOf(a);t>=0&&e.splice(t,1)}var mm={},Fh={};function zh(){if(!Q.Current){console.trace("Invalid call - no current context.");return}Vh(Q.Current.scene,Q.Current.scene.visible,!0)}function Vh(a,e,t){let i=!1,n=C.isActiveSelf(a);if(mm[a.uuid]=n,e&&(e=C.isActiveSelf(a)),a[un]=e,!i){let r=Fh[a.uuid];r!==void 0&&r!==e&&t&&gm(a,o=>{e?($n(o.__internalAwake.bind(o)),o.onEnable()):o.onDisable()})}if(Fh[a.uuid]=e,a.children)for(let r of a.children)Vh(r,e,t)}function bn(a){let e=!0,t=a,i=!1;for(;t&&t;){if(t.type==="Scene"&&(i=!0),!C.isActiveSelf(t)){e=!1;break}t=t.parent}if(!a){console.error("GO is null");return}a[un]=e&&i}function gm(a,e){if(a.userData?.components)for(let t of a.userData.components)e(t)}var Gl=H("debuggetcomponent");function bm(a){return a==null||a.isObject3D?a:a.object&&a.object.isObject3D?a.object:a}function Wl(a,e){if(!a)return;let t=e?.new_scripts??Q.Current.new_scripts;t.includes(a)||t.push(a)}var Uh=function(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))},Vs=function(a,e,t=!0){e.userData||(e.userData={}),e.userData.components||(e.userData.components=[]),e.userData.components.push(a),a.gameObject=e,Wl(a);try{a.__internalAwake&&t&&(bn(e),a.__internalAwake())}catch(i){console.error(i)}},Gh=function(a,e){if(a.gameObject!==e){if(a.gameObject&&a.gameObject.userData.components){let t=a.gameObject.userData.components.indexOf(a);a.gameObject.userData.components.splice(t,1)}if(!e.userData.components)e.userData.components=[];else if(e.userData.components.includes(a))return;e.userData.components.push(a),a.gameObject=e}},Wh=function(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(),Li(a,a.context??Q.Current),a.__destroyed=!0,a.gameObject=null},qh=function(a,e,t){if(!e?.userData?.components)return null;Gl&&console.log("FIND",a);for(let i=0;i<e.userData.components.length;i++){let n=e.userData.components[i];if(a===null||n.constructor.name===a.name||n.constructor.name===a)if(Gl&&console.log("MATCH BY NAME",n),t)t.push(n);else return n}for(let i=0;i<e.userData.components.length;i++){let n=e.userData.components[i],r=Object.getPrototypeOf(n.constructor);do{if(r===a)if(Gl&&console.log("MATCH BY PROTOYPE",r),t)t.push(n);else return n;r=Object.getPrototypeOf(r)}while(r)}return t},Us=function(a,e){return qh(a,e,null)},Gs=function(a,e,t){return t||(t=[]),qh(a,e,t)},Ws=function(a,e,t){let i=Us(a,e);if(t===!1&&i.enabled===!1)return null;if(i)return i;for(let n=0;n<e?.children?.length;n++){let r=Ws(a,e.children[n]);if(r)return r}return null},qs=function(a,e,t){t||(t=[]),Gs(a,e,t);for(let i=0;i<e?.children?.length;i++)qs(a,e.children[i],t);return t},zs=function(a,e){if(!e)return null;if(Array.isArray(e)){for(let i=0;i<e.length;i++){let n=bm(e[i]),r=zs(a,n);if(r)return r}return null}let t=Us(a,e);return t||zs(a,e.parent)},ql=function(a,e,t){return t||(t=[]),e?(Gs(a,e,t),ql(a,e.parent,t)):t},Xh=function(a,e,t){if(!a)return null;if(!e&&(e=Q.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e.isScene===!0||e.isObject3D===!0?e:e?.scene;for(let n in i.children){let r=i.children[n];if(t===!1&&r[un]===!1)continue;if(r.constructor==a)return r;let o=Ws(a,r);if(o)return o}return null},Qh=function(a,e,t){if(!a)return e;if(!t&&(t=Q.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;qs(a,r,e)}return e};var Xl=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}},Y=new Xl;import*as oe from"three";import{Vector3 as ym,Quaternion as Em,Uniform as wm}from"three";var Yl=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]}},Xw=new Em().setFromAxisAngle(new ym(0,1,0),Math.PI);var Kl=new Yl(()=>new oe.Vector3,100);oe.Vector3.prototype.slerp=function(a,e){let t=this.length(),i=a.length(),n=Y.lerp(t,i,e);return this.lerp(a,e).normalize().multiplyScalar(n)};function q(a,e=null,t=!0){let i=e??Kl.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 ae(a,e){if(!a)return;let t=Kl.get();e!==t&&t.copy(e),(a?.parent??a).worldToLocal(t),a.position.set(t.x,t.y,t.z)}function zr(a,e,t,i){let n=Kl.get();n.set(e,t,i),ae(a,n)}var er=new oe.Quaternion,is=new oe.Quaternion,Ql=new oe.Quaternion;function Ae(a,e=null){if(!a)return is.set(0,0,0,1);let t=e??is;return a.parent?(a.getWorldQuaternion(t),t):t.copy(a.quaternion)}function ot(a,e){if(!a)return;e!==er&&er.copy(e);let t=er;a?.parent?.getWorldQuaternion(Ql),Ql.invert();let n=Ql.multiply(t);a.quaternion.set(n.x,n.y,n.z,n.w)}function Jh(a,e,t,i,n){er.set(e,t,i,n),ot(a,er)}var Xs=new oe.Vector3,Qw=new oe.Vector3;function Qs(a,e=null){return a?a.parent?(a.getWorldScale(e??Xs),e??Xs):Xs.copy(a.position):Xs.set(0,0,0)}var Yw=new oe.Vector3,Kw=new oe.Quaternion;var Yh=new oe.Euler,Kh=new oe.Euler,_m=new oe.Vector3;function xm(a){return a.getWorldQuaternion(is),Kh.setFromQuaternion(is),Kh}function Zh(a,e){ot(a,is.setFromEuler(e))}function Ys(a){let e=xm(a),t=_m;return t.set(e.x,e.y,e.z),t.x=Y.toDegrees(t.x),t.y=Y.toDegrees(t.y),t.z=Y.toDegrees(t.z),t}function Ks(a,e,t,i,n=!0){n&&(e=Y.toRadians(e),t=Y.toRadians(t),i=Y.toRadians(i)),Yh.set(e,t,i),er.setFromEuler(Yh),ot(a,er)}function ns(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 Jw=new oe.PlaneGeometry(2,2,1,1),Zw=new oe.WebGLRenderer({antialias:!1}),$w=new oe.PerspectiveCamera,e_=new oe.Scene,t_=new oe.ShaderMaterial({uniforms:{blitTexture:new wm(null)},vertexShader:`
81
81
  varying vec2 vUv;
82
82
  void main(){
83
83
  vUv = uv;
@@ -90,7 +90,7 @@ a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
90
90
  uv.y = 1.0 - uv.y;
91
91
  gl_FragColor = vec4(uv.xy, 0, 1);
92
92
  gl_FragColor = texture2D( blitTexture, uv);
93
- }`});import*as ns from"three";var Kh=/^(?:[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 vm(a){return typeof a=="string"&&Kh.test(a)}var Jh=vm;var Ue=[];for(let a=0;a<256;++a)Ue.push((a+256).toString(16).slice(1));function Zh(a,e=0){return(Ue[a[e+0]]+Ue[a[e+1]]+Ue[a[e+2]]+Ue[a[e+3]]+"-"+Ue[a[e+4]]+Ue[a[e+5]]+"-"+Ue[a[e+6]]+Ue[a[e+7]]+"-"+Ue[a[e+8]]+Ue[a[e+9]]+"-"+Ue[a[e+10]]+Ue[a[e+11]]+Ue[a[e+12]]+Ue[a[e+13]]+Ue[a[e+14]]+Ue[a[e+15]]).toLowerCase()}function ym(a){if(!Jh(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 $h=ym;function Em(a){a=unescape(encodeURIComponent(a));let e=[];for(let t=0;t<a.length;++t)e.push(a.charCodeAt(t));return e}var wm="6ba7b810-9dad-11d1-80b4-00c04fd430c8",_m="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Ql(a,e,t){function i(n,r,o,s){var c;if(typeof n=="string"&&(n=Em(n)),typeof r=="string"&&(r=$h(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 Zh(d)}try{i.name=a}catch{}return i.DNS=wm,i.URL=_m,i}function xm(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 Yl(a,e){return a<<e|a>>>32-e}function Tm(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]=Yl(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 E=Math.floor(f/20),b=Yl(c,5)+xm(E,d,l,h)+u+e[E]+s[f]>>>0;u=h,h=l,l=Yl(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 eu=Tm;var Rm=Ql("v5",80,eu),Kl=Rm;var Ys=H("debugcomponents"),Cm="eff8ba80-635d-11ec-90d6-0242ac120003",Ge=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,Kl(e.toString(),Cm)}static createFromString(e){return new Ge(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 Ks=class{guid;constructor(e){this.guid=e}};function zr(a,e,t=!0){if(!a)return;let i=a;if(C.destroy(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 Ks(n);e.send("instance-destroyed",r)}function tu(a,e){let t=new Ks(a);e.send("instance-destroyed",t)}function iu(a){a.connection.beginListen("instance-destroyed",e=>{Ys&&console.log("[Remote] Destroyed",a.scene,e);let t=C.findByGuid(e.guid,a.scene);t&&C.destroy(t)})}var Jl=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function Js(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=Q.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}=Sm(n,e);if(o){let c=o;if(c.guid){Ys&&console.log("[Local] new instance","gameobject:",o?.guid);let d=new Jl(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 Zs(){return Math.random()*9999999}function nu(a){a.connection.beginListen("new-instance-created",async e=>{let t=await Pm(e.originalGuid,a.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let i=new ve;e.position&&(i.position=new ns.Vector3(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new ns.Quaternion(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new ns.Vector3(e.scale.x,e.scale.y,e.scale.z)),i.parent=e.parent,e.seed&&(i.idProvider=new Ge(e.seed)),i.visible=e.visible,i.context=a,Ys&&a.alias&&console.log("[Remote] instantiate in: "+a.alias);let n=C.instantiate(t,i);n&&(e.parent==="scene"&&a.scene.add(n),Ys&&console.log("[Remote] new instance","gameobject:",n?.guid,t))})}function Sm(a,e){let t=Zs(),i=e??new ve;i.idProvider=new Ge(t);let n=C.instantiate(a,i);return{seed:t,instance:n}}var ru={};function ou(a,e){ru[a]=e}async function Pm(a,e){let t=ru[a];if(t!=null){let i=await t(a);if(i)return i}return su(a,e)}function su(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=su(a,t);if(i)return i}return null}var gn=H("debugcomponents"),au=(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))(au||{}),ve=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context};se.Object3D.prototype.SetActive=function(a){this.visible=a};var C=class extends se.Object3D{guid;static setActive(e,t,i=!0){!e||(e.visible=t,mn(e),t&&i&&Bs(Q.Current,e))}static isActiveSelf(e){return e.visible||C.isUsingInstancing(e)}static isActiveInHierarchy(e){return e[dn]||C.isUsingInstancing(e)}static markAsInstancedRendered(e,t){e.__isUsingInstancing=t}static isUsingInstancing(e){return e.__isUsingInstancing===!0}static foreachComponent(e,t,i=!0){if(!!e){if(e.userData.components)for(let n=0;n<e.userData.components.length;n++){let r=e.userData.components[n];if(r instanceof M){let o=t(r);if(o!==void 0)return o}}if(i&&e.children)for(let n=0;n<e.children.length;n++){let r=e.children[n];if(!r)continue;let o=C.foreachComponent(r,t,i);if(o!==void 0)return o}}}static instantiateSynced(e,t){return e?Js(e,t):null}static instantiate(e,t=null){if(e===null)return null;let i=null;t!==null&&(t.x!==void 0?(i=new ve,i.position=t):i=t);let n=Q.Current;i?.context&&(n=i.context),gn&&n.alias&&console.log("context",n.alias),i&&!i.idProvider&&(i.idProvider=new Ge(Date.now()));let r=[],o={},s={},c=this.internalInstantiate(n,e,i,r,o,s);c&&(this.resolveReferences(o),this.resolveAndBindSkinnedMeshBones(s,o)),gn&&(is(e,!0),is(c,!0));let d={};for(let l in r){let h=r[l],u=h.guid;i&&i.idProvider&&(h.guid=i.idProvider.generateUUID(),d[u]=h.guid,gn&&console.log(h.name,h.guid)),Vl(h,n),h.__internalNewInstanceCreated&&h.__internalNewInstanceCreated()}for(let l in r){let h=r[l];h.resolveGuids&&h.resolveGuids(d),h.enabled!==!1&&(h.enabled=!0)}return Li(n),c}static internalInstantiate(e,t,i,n,r,o){if(!t)return null;let s=t.userData;t.userData={};let c=t.children;t.children=[];let d;if(d=t.clone(!1),t.userData=s,t.children=c,r[t.uuid]={original:t,clone:d},t.type==="SkinnedMesh"&&(o[t.uuid]={original:t,clone:d}),i?.visible!==void 0&&(d.visible=i.visible),i?.idProvider){d.uuid=i.idProvider.generateUUID();let h=d;h&&(h.guid=d.uuid)}t.animations&&t.animations.length>0&&(d.animations=[...t.animations]);let l=t.parent;if(l&&l.add(d),i?.position?le(d,i.position):d.position.copy(t.position),i?.rotation?ot(d,i.rotation):d.quaternion.copy(t.quaternion),i?.scale?d.scale.copy(i.scale):d.scale.copy(t.scale),i?.parent&&i.parent!=="scene"){let h=null;if(typeof i.parent=="string"?h=hn(i.parent,e.scene,!0):h=i.parent,h){let u=i.keepWorldPosition===!0?h.attach:h.add;u?u.call(h,d):console.error("Invalid parent object",h,"received when instantiating:",t)}else console.warn("could not find parent:",i.parent)}for(let[h,u]of Object.entries(t.userData))h!=="components"&&(d.userData[h]=u);if(t.userData?.components){let h=t.userData.components,u=[];d.userData.components=u;for(let f=0;f<h.length;f++){let E=h[f],b=Object.create(E);Object.assign(b,E),u.push(b),b.gameObject=d,n.push(b)}}i&&(i.position=void 0,i.rotation=void 0,i.scale=void 0,i.parent=void 0);for(let h in t.children){let u=t.children[h],f=C.internalInstantiate(e,u,i,n,r,o);f&&d.add(f)}return d}static resolveAndBindSkinnedMeshBones(e,t){for(let i in e){let n=e[i],r=n.original,o=r.skeleton,s=n.clone;if(!o){console.warn("Skinned mesh has no skeleton?",n);continue}let c=o.bones,d=s.skeleton.clone();s.skeleton=d,s.bindMatrix.clone().copy(r.bindMatrix),s.bindMatrixInverse.copy(r.bindMatrixInverse);let l=[];d.bones=l;for(let h=0;h<c.length;h++){let u=c[h],E=t[u.uuid].clone;l.push(E)}}for(let i in e){let n=e[i].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}static resolveReferences(e){for(let t in e){let n=e[t].clone;if(n.userData?.components)for(let r=0;r<n.userData.components.length;r++){let o=n.userData.components[r],s=Object.entries(o);for(let[c,d]of s)if(Array.isArray(d)){let l=[];o[c]=l;for(let h=0;h<d.length;h++){let u=d[h];if(typeof u!="object"){l.push(u);continue}let f=this.postProcessNewInstance(o,c,u,e);f!==void 0?l.push(f):l.push(u)}}else if(typeof d=="object"){let l=this.postProcessNewInstance(o,c,d,e);l!==void 0&&(o[c]=l)}}}}static postProcessNewInstance(e,t,i,n){if(i instanceof st||i instanceof M){let r=i.gameObject;if(r){let o=r.uuid,s=n[o]?.clone;if(!s){gn&&console.log("reference did not change",t,e,i);return}let c=r.userData.components.indexOf(i);if(c>=0)return gn&&console.log(t,o),s.userData.components[c];console.warn("could not find component",t,i)}}else if(i instanceof se.Object3D){if(t==="gameObject")return;let r=i;if(r){let o=r.uuid,s=n[o]?.clone;if(s)return gn&&console.log(t,"old",i,"new",s),s}}}static destroySynced(e,t,i=!0){if(!e)return;let n=e;t=t??Q.Current,zr(n,t.connection,i)}static destroy(e,t=!0,i=!0){let n=e;if(n.isComponent){n.destroy();return}let r=e;if(gn&&console.log(r),t&&r.children)for(let s of r.children)C.destroy(s,t,!1);let o=r.userData.components;if(o){let s=o.length;for(let c=0;c<o.length;c++){let d=o[c];d.destroy&&(gn&&console.log("destroying",d),d.destroy()),o.length<s&&(s=o.length,c--)}}i&&r.removeFromParent()}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=Q.Current),t.add(e),mn(e),i?C.foreachComponent(e,n=>{Fl(n,i),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),C.foreachComponent(e,t=>{jh(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 Ns(n,e,i),n}static addComponent(e,t){if(t.gameObject==null)throw new Error("Did you mean to create a new component? Use addNewComponent");zh(t,e)}static removeComponent(e){return Nh(e.gameObject,e),e}static getOrAddComponent(e,t){let i=this.getComponent(e,t);return i||this.addNewComponent(e,t)}static getComponent(e,t){return e===null?null:zs(t,e)}static getComponents(e,t,i=null){return e===null?i??[]:Vs(t,e,i)}static findByGuid(e,t){return hn(e,t,!0,!0)}static findObjectOfType(e,t,i=!0){return Gh(e,t,i)}static findObjectsOfType(e,t){let i=[];return Wh(e,i,t),i}static getComponentInChildren(e,t){return Us(t,e)}static getComponentsInChildren(e,t,i=null){return Gs(t,e,i)}static getComponentInParent(e,t){return Fs(t,e)}static getComponentsInParent(e,t,i=null){return Ul(t,e,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]}};Object.defineProperty(se.Object3D.prototype,"activeSelf",{get:function(){return this.visible},set:function(a){let e=typeof a=="number"?a>.5:a;this.visible=e}});se.Object3D.prototype.addNewComponent=function(a){return C.addNewComponent(this,a)};se.Object3D.prototype.removeComponent=function(a){return C.removeComponent(a)};se.Object3D.prototype.getOrAddComponent=function(a){return C.getOrAddComponent(this,a)};se.Object3D.prototype.getComponent=function(a){return C.getComponent(this,a)};se.Object3D.prototype.getComponents=function(a,e){return C.getComponents(this,a,e)};se.Object3D.prototype.getComponentInChildren=function(a){return C.getComponentInChildren(this,a)};se.Object3D.prototype.getComponentsInChildren=function(a,e){return C.getComponentsInChildren(this,a,e)};se.Object3D.prototype.getComponentInParent=function(a){return C.getComponentInParent(this,a)};se.Object3D.prototype.getComponentsInParent=function(a,e){return C.getComponentsInParent(this,a,e)};var Gt=class{get isComponent(){return!0}__context;get context(){return this.__context??Q.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[dn];return e===void 0?!0: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||Vh(this)}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;__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(){this.__didEnable||(this.__didEnable=!0,this.onEnable())}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this._collisionExitRoutine=void 0,this.onDisable(),this._collisions?.clear())}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 se.Vector3),q(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){le(this.gameObject,e)}setWorldPosition(e,t,i){Gt._worldPositionBuffer.set(e,t,i),this.worldPosition=Gt._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new se.Quaternion),ke(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){ot(this.gameObject,e)}setWorldQuaternion(e,t,i,n){Gt._worldQuaternionBuffer.set(e,t,i,n),this.worldQuaternion=Gt._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new se.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new se.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new se.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=Y.toDegrees(t.x),t.y=Y.toDegrees(t.y),t.z=Y.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){n&&(e=Y.toRadians(e),t=Y.toRadians(t),i=Y.toRadians(i)),Gt._worldEulerBuffer.set(e,t,i),Gt._worldQuaternionBuffer.setFromEuler(Gt._worldEulerBuffer),this.worldQuaternion=Gt._worldQuaternionBuffer}get forward(){return Gt._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}},st=Gt;z(st,"_worldPositionBuffer",new se.Vector3),z(st,"_worldQuaternionBuffer",new se.Quaternion),z(st,"_worldEulerBuffer",new se.Euler),z(st,"_tempQuaternionBuffer2",new se.Quaternion),z(st,"_forward",new se.Vector3(0,0,1));var M=class extends st{get enabled(){return this.__isEnabled??!0}set enabled(e){typeof e=="number"&&(e>=.5?e=!0:e=!1),e!==this.__isEnabled&&(this.__isEnabled=e,this.__didAwake&&(e?this.__internalEnable():this.__internalDisable()))}};import*as Wt from"three";var li=H("gizmos"),Ie=H("debugextension");var ea=H("debugresolvedependencies"),Om=["/extensions/","extensions/"],Am=[{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 Vr(a,e){ea&&console.log(a,e);let t=[];$l(Am,a,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function $l(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=lu(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=ec(s.prefix,r);if(c>=0){ea&&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=lu(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=ec(d.prefix,s);if(l>=0){ea&&console.log(d,l,d.dependencyName),i.push(e?.getDependency(d.dependencyName,l).then(h=>r[o]=h));break}}typeof s=="object"&&$l(a,e,s,i)}else typeof r=="object"&&$l(a,e,r,i)}else typeof t=="string"&&km(a,e,t,i)}function lu(a,e){if(a&&a.plugins&&typeof e=="string"){for(let t of Om)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(Ie&&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 km(a,e,t,i){for(let n of a){let r=ec(n.prefix,t);if(r>=0)return ea&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(o=>o)),!0}return!1}function ec(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 tc=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]}},D=new tc;var ic="NEEDLE_persistent_assets";function cu(a){return a?.___persistentAsset===!0}var ta=class{get name(){return ic}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[ic];if(!t)return;Ie&&console.log(t);let i=new Array;for(let n of t?.assets){let r=Vr(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){Ie&&console.log(t);let n=e.json.extensions[ic];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let o=r.__type;if(o){let s=D.get(o)}}return r}}return null}};var er=H("debugserializer"),nc=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])}er&&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){er&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){er&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return er&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){er&&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){er&&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}}},na=new nc,Di=class{constructor(e){if(Array.isArray(e))for(let t of e)na.register(t.name,this);else na.register(e.name,this)}},Ur=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function oc(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=na.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 ia=[];function du(a,e){if(!a)return e;typeof a.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,a.$serializedTypes));let t=Object.getPrototypeOf(a);return du(t,e)}function rs(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=du(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?rc(s,h,t,void 0,a[r]):rc(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);ia.length=0,a.onAfterDeserializeMember!==void 0&&a.onAfterDeserializeMember(r,s,t)}}Im(a,e)}return a.onAfterDeserialize!==void 0&&a.onAfterDeserialize(e,t),t.path=void 0,!0}function Im(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){er&&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 rc(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"&&cu(n)){if(n.__concreteInstance)return n.__concreteInstance;let l=n;if(!l.$serializedTypes&&o.prototype.$serializedTypes&&(l.$serializedTypes=o.prototype.$serializedTypes),l.$serializedTypes&&rs(l,a,t),n&&o!==void 0)try{let h=new o;Ie&&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:na.getSerializerForConstructor(o)}),Array.isArray(a)){let l=[];for(let h=0;h<a.length;h++){let u=a[h],f=rc(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(...Mm(a));let d=c;return d.$serializedTypes&&rs(d,a,t),c}function Mm(a){if(ia.length=0,typeof a=="object"&&a!==null&&a!==void 0)for(let e of Object.keys(a))ia.push(a[e]);return ia}function tr(a,e){if(e==null||a==null)return;let t=!1;for(let i of Object.keys(e)){let n=Lm(a,i);t&&n===void 0||(!n||n.writable===!0||n?.set!==void 0)&&(a[i]=e[i])}}function Lm(a,e){let t;do t=Object.getOwnPropertyDescriptor(a,e);while(!t&&(a=Object.getPrototypeOf(a)));return t}var os=class{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}};var ra=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 Wt.Vector2];_pointerPositionsLastFrame=[new Wt.Vector2];_pointerPositionsDelta=[new Wt.Vector2];_pointerPositionsRC=[new Wt.Vector2];_pointerPositionDown=[new Wt.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 os(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 os(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 os(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 Wt.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 Wt.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new Wt.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new Wt.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 Wt.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=Q.Current;try{Q.Current=this.context;let n=new Event(e);tr(n,t),this.dispatchEvent(n)}finally{Q.Current=i}}};var kt=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 kt){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],E=i[8],b=n[0],y=n[1],g=n[2],p=n[3],m=n[4],v=n[5],w=n[6],x=n[7],T=n[8];return r[0]=o*b+s*p+c*w,r[1]=o*y+s*m+c*x,r[2]=o*g+s*v+c*T,r[3]=d*b+l*p+h*w,r[4]=d*y+l*m+h*x,r[5]=d*g+l*v+h*T,r[6]=u*b+f*p+E*w,r[7]=u*y+f*m+E*x,r[8]=u*g+f*v+E*T,t}scale(e,t=new kt){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 kt){let n=Dm,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,E=n*c,b=r*o,y=r*s,g=r*c,p=this.elements;return p[3*0+0]=1-(u+E),p[3*0+1]=l-g,p[3*0+2]=h+y,p[3*1+0]=l+g,p[3*1+1]=1-(d+E),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 kt){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}},Dm=[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 kt([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=Hm,r=1/i;n.set(this.x*r,this.y*r,this.z*r);let o=jm;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(hu),hu.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 Hm=new _,jm=new _,hu=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,uu),d=uu),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=pu,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=pu,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)),E=Math.min(Math.min(Math.max(s,c),Math.max(d,l)),Math.max(h,u));return!(E<0||f>E)}},uu=new _,pu=[new _,new _,new _,new _,new _,new _,new _,new _],da=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}},ha=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=Bm,n=Fm;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,E,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),E=Math.sin(u),b=Math.sin((1-t)*u)/E,y=Math.sin(t*u)/E):(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}},Bm=new _,Fm=new _,Nm={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},U=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=U.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}};U.idCounter=0;U.types=Nm;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(fu),fu.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}},fu=new ce,rr=class extends U{constructor(e={}){let{vertices:t=[],faces:i=[],normals:n=[],axes:r,boundingSphereRadius:o}=e;super({type:U.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]];rr.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 E=0;E<i.faces.length;E++){l.copy(i.faceNormals[E]),r.vmult(l,l);let b=l.dot(o);b>u&&(u=b,h=E)}let f=[];for(let E=0;E<i.faces[h].length;E++){let b=i.vertices[i.faces[h][E]],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 _,E=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,E),!E.almostZero()){E.normalize();let m=y.testSepAxis(E,e,t,i,n,r);if(m===!1)return!1;m<b&&(b=m,o.copy(E))}}return n.vsub(t,h),h.dot(o)>0&&o.negate(o),!0}testSepAxis(e,t,i,n,r,o){let s=this;rr.project(s,e,i,n,sc),rr.project(t,e,r,o,ac);let c=sc[0],d=sc[1],l=ac[0],h=ac[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 _,E=new _,b=new _,y=this,g=[],p=n,m=g,v=-1,w=Number.MAX_VALUE;for(let O=0;O<y.faces.length;O++){c.copy(y.faceNormals[O]),i.vmult(c,c);let P=c.dot(e);P<w&&(w=P,v=O)}if(v<0)return;let x=y.faces[v];x.connectedFaces=[];for(let O=0;O<y.faces.length;O++)for(let P=0;P<y.faces[O].length;P++)x.indexOf(y.faces[O][P])!==-1&&O!==v&&x.connectedFaces.indexOf(O)===-1&&x.connectedFaces.push(O);let T=x.length;for(let O=0;O<T;O++){let P=y.vertices[x[O]],L=y.vertices[x[(O+1)%T]];P.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(P),i.vmult(f,f),t.vadd(f,f);let I=x.connectedFaces[O];E.copy(this.faceNormals[I]);let B=this.getPlaneConstantOfFace(I);b.copy(E),i.vmult(b,b);let j=B-b.dot(t);for(this.clipFaceAgainstPlane(p,m,b,j);p.length;)p.shift();for(;m.length;)p.push(m.shift())}E.copy(this.faceNormals[v]);let R=this.getPlaneConstantOfFace(v);b.copy(E),i.vmult(b,b);let S=R-b.dot(t);for(let O=0;O<p.length;O++){let P=b.dot(p[O])+S;if(P<=r&&(console.log("clamped: depth="+P+" to minDist="+r),P=r),P<=o){let L=p[O];if(P<=1e-6){let I={point:L,normal:b,depth:P};s.push(I)}}}}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 E=u;(o===void 0||E.x<o)&&(o=E.x),(d===void 0||E.x>d)&&(d=E.x),(s===void 0||E.y<s)&&(s=E.y),(l===void 0||E.y>l)&&(l=E.y),(c===void 0||E.z<c)&&(c=E.z),(h===void 0||E.z>h)&&(h=E.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=zm,c=0,d=0,l=Vm,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 E=h[f].dot(s);E>c&&(c=E),E<d&&(d=E)}if(d-=u,c-=u,d>c){let f=d;d=c,c=f}r[0]=c,r[1]=d}},sc=[],ac=[],zm=new _,Vm=new _,or=class extends U{constructor(e){super({type:U.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 rr({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++)vn.set(r[o][0],r[o][1],r[o][2]),t.vmult(vn,vn),e.vadd(vn,vn),i(vn.x,vn.y,vn.z)}calculateWorldAABB(e,t,i,n){let r=this.halfExtents;ci[0].set(r.x,r.y,r.z),ci[1].set(-r.x,r.y,r.z),ci[2].set(-r.x,-r.y,r.z),ci[3].set(-r.x,-r.y,-r.z),ci[4].set(r.x,-r.y,-r.z),ci[5].set(r.x,r.y,-r.z),ci[6].set(-r.x,r.y,-r.z),ci[7].set(r.x,-r.y,r.z);let o=ci[0];t.vmult(o,o),e.vadd(o,o),n.copy(o),i.copy(o);for(let s=1;s<8;s++){let c=ci[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)}}},vn=new _,ci=[new _,new _,new _,new _,new _,new _,new _,new _],Ec={DYNAMIC:1,STATIC:2,KINEMATIC:4},wc={AWAKE:0,SLEEPY:1,SLEEPING:2},V=class extends ha{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=V.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?V.STATIC:V.DYNAMIC,typeof e.type==typeof V.STATIC&&(this.type=e.type),this.allowSleep=typeof e.allowSleep<"u"?e.allowSleep:!0,this.sleepState=V.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 kt,this.invMassSolve=0,this.invInertiaSolve=new _,this.invInertiaWorldSolve=new kt,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=V.AWAKE,this.wakeUpAfterNarrowphase=!1,e===V.SLEEPING&&this.dispatchEvent(V.wakeupEvent)}sleep(){this.sleepState=V.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===V.AWAKE&&i<n?(this.sleepState=V.SLEEPY,this.timeLastSleepy=e,this.dispatchEvent(V.sleepyEvent)):t===V.SLEEPY&&i>n?this.wakeUp():t===V.SLEEPY&&e-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(V.sleepEvent))}}updateSolveMassProperties(){this.sleepState===V.SLEEPING||this.type===V.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=Um,o=Gm,s=this.quaternion,c=this.aabb,d=Wm;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=qm,n=Xm;i.setRotationFromQuaternion(this.quaternion),i.transpose(n),i.scale(t,i),i.mmult(n,this.invInertiaWorld)}}applyForce(e,t=new _){if(this.type!==V.DYNAMIC)return;this.sleepState===V.SLEEPING&&this.wakeUp();let i=Qm;t.cross(e,i),this.force.vadd(e,this.force),this.torque.vadd(i,this.torque)}applyLocalForce(e,t=new _){if(this.type!==V.DYNAMIC)return;let i=Ym,n=Km;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyForce(i,n)}applyTorque(e){this.type===V.DYNAMIC&&(this.sleepState===V.SLEEPING&&this.wakeUp(),this.torque.vadd(e,this.torque))}applyImpulse(e,t=new _){if(this.type!==V.DYNAMIC)return;this.sleepState===V.SLEEPING&&this.wakeUp();let i=t,n=Jm;n.copy(e),n.scale(this.invMass,n),this.velocity.vadd(n,this.velocity);let r=Zm;i.cross(e,r),this.invInertiaWorld.vmult(r,r),this.angularVelocity.vadd(r,this.angularVelocity)}applyLocalImpulse(e,t=new _){if(this.type!==V.DYNAMIC)return;let i=$m,n=eg;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyImpulse(i,n)}updateMassProperties(){let e=tg;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===V.DYNAMIC||this.type===V.KINEMATIC)||this.sleepState===V.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 E=h.elements,b=this.angularFactor,y=c.x*b.x,g=c.y*b.y,p=c.z*b.z;r.x+=e*(E[0]*y+E[1]*g+E[2]*p),r.y+=e*(E[3]*y+E[4]*g+E[5]*p),r.z+=e*(E[6]*y+E[7]*g+E[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()}};V.idCounter=0;V.COLLIDE_EVENT_NAME="collide";V.DYNAMIC=Ec.DYNAMIC;V.STATIC=Ec.STATIC;V.KINEMATIC=Ec.KINEMATIC;V.AWAKE=wc.AWAKE;V.SLEEPY=wc.SLEEPY;V.SLEEPING=wc.SLEEPING;V.wakeupEvent={type:"wakeup"};V.sleepyEvent={type:"sleepy"};V.sleepEvent={type:"sleep"};var Um=new _,Gm=new ce,Wm=new Ze,qm=new kt,Xm=new kt,Qm=new _,Ym=new _,Km=new _,Jm=new _,Zm=new _,$m=new _,eg=new _,tg=new _,hc=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&V.STATIC)!==0||e.sleepState===V.SLEEPING)&&((t.type&V.STATIC)!==0||t.sleepState===V.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=ig;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=ng,n=rg,r=og,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."),[]}},ig=new _,ng={keys:[]},rg=[],og=[];var B_=new _,uc=class extends hc{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}},ds=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}},Cu,Su,Pu,Ou,Au,ku,Iu,_c={CLOSEST:1,ANY:2,ALL:4};Cu=U.types.SPHERE;Su=U.types.PLANE;Pu=U.types.BOX;Ou=U.types.CYLINDER;Au=U.types.CONVEXPOLYHEDRON;ku=U.types.HEIGHTFIELD;Iu=U.types.TRIMESH;var ye=class{get[Cu](){return this._intersectSphere}get[Su](){return this._intersectPlane}get[Pu](){return this._intersectBox}get[Ou](){return this._intersectConvex}get[Au](){return this._intersectConvex}get[ku](){return this._intersectHeightfield}get[Iu](){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=ye.ANY,this.result=new ds,this.hasHit=!1,this.callback=i=>{}}intersectWorld(e,t){return this.mode=t.mode||ye.ANY,this.result=t.result||new ds,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(mu),lc.length=0,e.broadphase.aabbQuery(e,mu,lc),this.intersectBodies(lc),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=sg,r=ag;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(wg(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 E=new _,b=new _,y=new _;o.vsub(i,E);let g=-d.dot(E)/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=lg;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=cg,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 E=d;E<h;E++){if(this.result.shouldStop)return;if(e.getAabbAtIndex(f,E,u),!!u.overlapsRay(o)){if(e.getConvexTrianglePillar(f,E,!1),te.pointToWorldFrame(i,t,e.pillarOffset,oa),this._intersectConvex(e.pillarConvex,t,oa,n,r,gu),this.result.shouldStop)return;e.getConvexTrianglePillar(f,E,!0),te.pointToWorldFrame(i,t,e.pillarOffset,oa),this._intersectConvex(e.pillarConvex,t,oa,n,r,gu)}}}_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=dg,E=hg;if(!(u<0))if(u===0)o.lerp(s,u,f),f.vsub(i,E),E.normalize(),this.reportIntersection(E,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,E),E.normalize(),this.reportIntersection(E,f,r,n,-1)),this.result.shouldStop)return;y>=0&&y<=1&&(o.lerp(s,y,f),f.vsub(i,E),E.normalize(),this.reportIntersection(E,f,r,n,-1))}}_intersectConvex(e,t,i,n,r,o){let s=ug,c=bu,d=o&&o.faceList||null,l=e.faces,h=e.vertices,u=e.faceNormals,f=this.direction,E=this.from,b=this.to,y=E.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],x=u[v],T=t,R=i;c.copy(h[w[0]]),T.vmult(c,c),c.vadd(R,c),c.vsub(E,c),T.vmult(x,s);let S=f.dot(s);if(Math.abs(S)<this.precision)continue;let O=s.dot(c)/S;if(!(O<0)){f.scale(O,at),at.vadd(E,at),qt.copy(h[w[0]]),T.vmult(qt,qt),R.vadd(qt,qt);for(let P=1;!p.shouldStop&&P<w.length-1;P++){di.copy(h[w[P]]),hi.copy(h[w[P+1]]),T.vmult(di,di),T.vmult(hi,hi),R.vadd(di,di),R.vadd(hi,hi);let L=at.distanceTo(E);!(ye.pointInTriangle(at,qt,di,hi)||ye.pointInTriangle(at,di,qt,hi))||L>y||this.reportIntersection(s,at,r,n,v)}}}}_intersectTrimesh(e,t,i,n,r,o){let s=pg,c=yg,d=Eg,l=bu,h=fg,u=mg,f=gg,E=vg,b=bg,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,x=c.length;!this.result.shouldStop&&w!==x;w++){let T=c[w];e.getNormal(T,s),e.getVertex(y[T*3],qt),qt.vsub(u,l);let R=h.dot(s),S=s.dot(l)/R;if(S<0)continue;h.scale(S,at),at.vadd(u,at),e.getVertex(y[T*3+1],di),e.getVertex(y[T*3+2],hi);let O=at.distanceSquared(u);!(ye.pointInTriangle(at,di,qt,hi)||ye.pointInTriangle(at,qt,di,hi))||O>v||(te.vectorToWorldFrame(t,s,b),te.pointToWorldFrame(i,t,at,E),this.reportIntersection(b,E,r,n,T))}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 ye.ALL:this.hasHit=!0,d.set(o,s,e,t,i,n,c),d.hasHit=!0,this.callback(d);break;case ye.CLOSEST:(c<d.distance||!d.hasHit)&&(this.hasHit=!0,d.hasHit=!0,d.set(o,s,e,t,i,n,c));break;case ye.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,nr),i.vsub(t,ss),e.vsub(t,cc);let r=nr.dot(nr),o=nr.dot(ss),s=nr.dot(cc),c=ss.dot(ss),d=ss.dot(cc),l,h;return(l=c*s-o*d)>=0&&(h=r*d-o*s)>=0&&l+h<r*c-o*o}};ye.CLOSEST=_c.CLOSEST;ye.ANY=_c.ANY;ye.ALL=_c.ALL;var mu=new Ze,lc=[],ss=new _,cc=new _,sg=new _,ag=new ce,at=new _,qt=new _,di=new _,hi=new _,gu={faceList:[0]},oa=new _,lg=new ye,cg=[],dg=new _,hg=new _,ug=new _,bu=new _,pg=new _,fg=new _,mg=new _,gg=new _,bg=new _,vg=new _;new Ze;var yg=[],Eg=new te,nr=new _,sa=new _;function wg(a,e,t){t.vsub(a,nr);let i=nr.dot(e);return e.scale(i,sa),sa.vadd(a,sa),t.distanceTo(sa)}var ua=class{static defaults(e={},t){for(let i in t)i in e||(e[i]=t[i]);return e}},hs=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=ua.defaults(i,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=e,this.bodyB=t,this.id=hs.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}};hs.idCounter=0;var pa=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)}},sr=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=sr.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 pa,this.jacobianElementB=new pa,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,vu),s.scale(l,yu),i.invInertiaWorldSolve.vmult(o,Eu),n.invInertiaWorldSolve.vmult(c,wu),e.multiplyVectors(vu,Eu)+t.multiplyVectors(yu,wu)}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,aa),d+=aa.dot(e.rotational),c.vmult(t.rotational,aa),d+=aa.dot(t.rotational),d}addToWlambda(e){let t=this.jacobianElementA,i=this.jacobianElementB,n=this.bi,r=this.bj,o=_g;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}};sr.idCounter=0;var vu=new _,yu=new _,Eu=new _,wu=new _,aa=new _,_g=new _,pc=class extends sr{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=xg,d=Tg,l=n.velocity,h=n.angularVelocity;n.force,n.torque;let u=r.velocity,f=r.angularVelocity;r.force,r.torque;let E=Rg,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),E.copy(r.position),E.vadd(s,E),E.vsub(n.position,E),E.vsub(o,E);let p=g.dot(E),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=Cg,t=Sg,i=Pg,n=Og,r=Ag;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)}},xg=new _,Tg=new _,Rg=new _,Cg=new _,Sg=new _,Pg=new _,Og=new _,Ag=new _;var F_=new _,N_=new _;var z_=new _,V_=new _;var U_=new _,G_=new _,fa=class extends sr{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=kg,o=Ig,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}},kg=new _,Ig=new _,qr=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=ua.defaults(i,{friction:.3,restitution:.3,contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}),this.id=qr.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}};qr.idCounter=0;var Xr=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=Xr.idCounter++,this.friction=typeof e.friction<"u"?e.friction:-1,this.restitution=typeof e.restitution<"u"?e.restitution:-1}};Xr.idCounter=0;var ma=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=Mg,s=Lg,c=Dg,d=Hg,l=Ug,h=jg,u=Bg,f=Fg,E=Ng,b=zg,y=Vg;this.getWorldAnchorA(h),this.getWorldAnchorB(u),h.vsub(n.position,f),u.vsub(r.position,E),u.vsub(h,o);let g=o.length();s.copy(o),s.normalize(),r.velocity.vsub(n.velocity,c),r.angularVelocity.cross(E,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),E.cross(d,y),n.torque.vsub(b,n.torque),r.torque.vadd(y,r.torque)}},Mg=new _,Lg=new _,Dg=new _,Hg=new _,jg=new _,Bg=new _,Fg=new _,Ng=new _,zg=new _,Vg=new _,Ug=new _;var W_=new _,q_=new _;var X_=new _,Q_=new _,Y_=new _;new ye;var K_=new _,J_=new _,Z_=[new _(1,0,0),new _(0,1,0),new _(0,0,1)],$_=new _;var ex=new _,tx=new _,ix=new _;var nx=new _,rx=new _,ox=new _,sx=new _;var ax=new _,lx=new _,cx=new _;var ga=class extends U{constructor(e){if(super({type:U.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 dx=new _,hx=new _;var ux=new _,px=new _,fx=new _,mx=new _,gx=new _,bx=new _,vx=new _;var yx=new _;var Ex=new _,wx=new _,_x=new _,xx=new _,Tx=new _,Rx=new _,Cx=new _,Sx=new _,Px=new _;var Ox=new _,Ax=new Ze;var kx=new _,Ix=new Ze,Mx=new _,Lx=new _,Dx=new _,Hx=new _,jx=new _,Bx=new _,Fx=new _,Nx=new Ze,zx=new _,Vx=new te,Ux=new Ze,fc=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 fc{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,E,b,y;if(s!==0)for(let v=0;v!==d;v++)c[v].updateSolveMassProperties();let g=Wg,p=qg,m=Gg;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 x=0;x!==d;x++){let T=c[x],R=T.vlambda,S=T.wlambda;R.set(0,0,0),S.set(0,0,0)}for(i=0;i!==n;i++){E=0;for(let x=0;x!==s;x++){let T=o[x];h=p[x],u=g[x],y=m[x],b=T.computeGWlambda(),f=u*(h-b-T.eps*y),y+f<T.minForce?f=T.minForce-y:y+f>T.maxForce&&(f=T.maxForce-y),m[x]+=f,E+=f>0?f:-f,T.addToWlambda(f)}if(E*E<r)break}for(let x=0;x!==d;x++){let T=c[x],R=T.velocity,S=T.angularVelocity;T.vlambda.vmul(T.linearFactor,T.vlambda),R.vadd(T.vlambda,R),T.wlambda.vmul(T.angularFactor,T.wlambda),S.vadd(T.wlambda,S)}let v=o.length,w=1/l;for(;v--;)o[v].multiplier=m[v]*w}return i}},Gg=[],Wg=[],qg=[];var Gx=V.STATIC;var gc=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}},bc=class extends gc{constructor(...e){super(...e),this.type=_}constructObject(){return new _}},Mu,Lu,Du,Hu,ju,Bu,Fu,Nu,zu,Vu,Uu,Gu,Wu,qu,Xu,Qu,Yu,Ku,Ju,Zu,$u,ep,tp,ip,np,ue={sphereSphere:U.types.SPHERE,spherePlane:U.types.SPHERE|U.types.PLANE,boxBox:U.types.BOX|U.types.BOX,sphereBox:U.types.SPHERE|U.types.BOX,planeBox:U.types.PLANE|U.types.BOX,convexConvex:U.types.CONVEXPOLYHEDRON,sphereConvex:U.types.SPHERE|U.types.CONVEXPOLYHEDRON,planeConvex:U.types.PLANE|U.types.CONVEXPOLYHEDRON,boxConvex:U.types.BOX|U.types.CONVEXPOLYHEDRON,sphereHeightfield:U.types.SPHERE|U.types.HEIGHTFIELD,boxHeightfield:U.types.BOX|U.types.HEIGHTFIELD,convexHeightfield:U.types.CONVEXPOLYHEDRON|U.types.HEIGHTFIELD,sphereParticle:U.types.PARTICLE|U.types.SPHERE,planeParticle:U.types.PLANE|U.types.PARTICLE,boxParticle:U.types.BOX|U.types.PARTICLE,convexParticle:U.types.PARTICLE|U.types.CONVEXPOLYHEDRON,cylinderCylinder:U.types.CYLINDER,sphereCylinder:U.types.SPHERE|U.types.CYLINDER,planeCylinder:U.types.PLANE|U.types.CYLINDER,boxCylinder:U.types.BOX|U.types.CYLINDER,convexCylinder:U.types.CONVEXPOLYHEDRON|U.types.CYLINDER,heightfieldCylinder:U.types.HEIGHTFIELD|U.types.CYLINDER,particleCylinder:U.types.PARTICLE|U.types.CYLINDER,sphereTrimesh:U.types.SPHERE|U.types.TRIMESH,planeTrimesh:U.types.PLANE|U.types.TRIMESH};Mu=ue.sphereSphere;Lu=ue.spherePlane;Du=ue.boxBox;Hu=ue.sphereBox;ju=ue.planeBox;Bu=ue.convexConvex;Fu=ue.sphereConvex;Nu=ue.planeConvex;zu=ue.boxConvex;Vu=ue.sphereHeightfield;Uu=ue.boxHeightfield;Gu=ue.convexHeightfield;Wu=ue.sphereParticle;qu=ue.planeParticle;Xu=ue.boxParticle;Qu=ue.convexParticle;Yu=ue.cylinderCylinder;Ku=ue.sphereCylinder;Ju=ue.planeCylinder;Zu=ue.boxCylinder;$u=ue.convexCylinder;ep=ue.heightfieldCylinder;tp=ue.particleCylinder;ip=ue.sphereTrimesh;np=ue.planeTrimesh;var vc=class{get[Mu](){return this.sphereSphere}get[Lu](){return this.spherePlane}get[Du](){return this.boxBox}get[Hu](){return this.sphereBox}get[ju](){return this.planeBox}get[Bu](){return this.convexConvex}get[Fu](){return this.sphereConvex}get[Nu](){return this.planeConvex}get[zu](){return this.boxConvex}get[Vu](){return this.sphereHeightfield}get[Uu](){return this.boxHeightfield}get[Gu](){return this.convexHeightfield}get[Wu](){return this.sphereParticle}get[qu](){return this.planeParticle}get[Xu](){return this.boxParticle}get[Qu](){return this.convexParticle}get[Yu](){return this.convexConvex}get[Ku](){return this.sphereConvex}get[Ju](){return this.planeConvex}get[Zu](){return this.boxConvex}get[$u](){return this.convexConvex}get[ep](){return this.heightfieldCylinder}get[tp](){return this.particleCylinder}get[ip](){return this.sphereTrimesh}get[np](){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 bc,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 pc(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 E=this.frictionEquationPool,b=E.length?E.pop():new fa(i,n,u*f),y=E.length?E.pop():new fa(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];ir.setZero(),Gr.setZero(),Wr.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?(ir.vadd(t.ni,ir),Gr.vadd(t.ri,Gr),Wr.vadd(t.rj,Wr)):(ir.vsub(t.ni,ir),Gr.vadd(t.rj,Gr),Wr.vadd(t.ri,Wr));let o=1/e;Gr.scale(o,i.ri),Wr.scale(o,i.rj),n.ri.copy(i.ri),n.rj.copy(i.rj),ir.normalize(),ir.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=Yg,d=Kg,l=Xg,h=Qg;for(let u=0,f=e.length;u!==f;u++){let E=e[u],b=t[u],y=null;E.material&&b.material&&(y=i.getContactMaterial(E.material,b.material)||null);let g=E.type&V.KINEMATIC&&b.type&V.STATIC||E.type&V.STATIC&&b.type&V.KINEMATIC||E.type&V.KINEMATIC&&b.type&V.KINEMATIC;for(let p=0;p<E.shapes.length;p++){E.quaternion.mult(E.shapeOrientations[p],c),E.quaternion.vmult(E.shapeOffsets[p],l),l.vadd(E.position,l);let m=E.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 x=null;m.material&&w.material&&(x=i.getContactMaterial(m.material,w.material)||null),this.currentContactMaterial=x||y||i.defaultContactMaterial;let T=m.type|w.type,R=this[T];if(R){let S=!1;m.type<w.type?S=R.call(this,m,w,l,h,c,d,E,b,m,w,g):S=R.call(this,w,m,h,l,d,c,b,E,m,w,g),S&&g&&(i.shapeOverlapKeeper.set(m.id,w.id),i.bodyOverlapKeeper.set(E.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,la),u.ni.scale(u.ni.dot(la),_u),la.vsub(_u,u.rj),-la.dot(u.ni)<=e.radius){if(h)return!0;let f=u.ri,E=u.rj;f.vadd(i,f),f.vsub(s.position,f),E.vadd(n,E),E.vsub(c.position,E),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=_b;i.vsub(n,ca),t.getSideNormals(f,o);let E=e.radius,b=!1,y=Tb,g=Rb,p=Cb,m=null,v=0,w=0,x=0,T=null;for(let N=0,W=f.length;N!==W&&b===!1;N++){let Z=yb;Z.copy(f[N]);let G=Z.length();Z.normalize();let ze=ca.dot(Z);if(ze<G+E&&ze>0){let ge=Eb,X=wb;ge.copy(f[(N+1)%3]),X.copy(f[(N+2)%3]);let qe=ge.length(),cn=X.length();ge.normalize(),X.normalize();let Kn=ca.dot(ge),Ii=ca.dot(X);if(Kn<qe&&Kn>-qe&&Ii<cn&&Ii>-cn){let At=Math.abs(ze-G-E);if((T===null||At<T)&&(T=At,w=Kn,x=Ii,m=G,y.copy(Z),g.copy(ge),p.copy(X),v++,h))return!0}}}if(v){b=!0;let N=this.createContactEquation(s,c,e,t,d,l);y.scale(-E,N.ri),N.ni.copy(y),N.ni.negate(N.ni),y.scale(m,y),g.scale(w,g),y.vadd(g,y),p.scale(x,p),y.vadd(p,N.rj),N.ri.vadd(i,N.ri),N.ri.vsub(s.position,N.ri),N.rj.vadd(n,N.rj),N.rj.vsub(c.position,N.rj),this.result.push(N),this.createFrictionEquationsFromContact(N,this.frictionResult)}let R=u.get(),S=xb;for(let N=0;N!==2&&!b;N++)for(let W=0;W!==2&&!b;W++)for(let Z=0;Z!==2&&!b;Z++)if(R.set(0,0,0),N?R.vadd(f[0],R):R.vsub(f[0],R),W?R.vadd(f[1],R):R.vsub(f[1],R),Z?R.vadd(f[2],R):R.vsub(f[2],R),n.vadd(R,S),S.vsub(i,S),S.lengthSquared()<E*E){if(h)return!0;b=!0;let G=this.createContactEquation(s,c,e,t,d,l);G.ri.copy(S),G.ri.normalize(),G.ni.copy(G.ri),G.ri.scale(E,G.ri),G.rj.copy(R),G.ri.vadd(i,G.ri),G.ri.vsub(s.position,G.ri),G.rj.vadd(n,G.rj),G.rj.vsub(c.position,G.rj),this.result.push(G),this.createFrictionEquationsFromContact(G,this.frictionResult)}u.release(R),R=null;let O=u.get(),P=u.get(),L=u.get(),I=u.get(),B=u.get(),j=f.length;for(let N=0;N!==j&&!b;N++)for(let W=0;W!==j&&!b;W++)if(N%3!==W%3){f[W].cross(f[N],O),O.normalize(),f[N].vadd(f[W],P),L.copy(i),L.vsub(P,L),L.vsub(n,L);let Z=L.dot(O);O.scale(Z,I);let G=0;for(;G===N%3||G===W%3;)G++;B.copy(i),B.vsub(I,B),B.vsub(P,B),B.vsub(n,B);let ze=Math.abs(Z),ge=B.length();if(ze<f[G].length()&&ge<E){if(h)return!0;b=!0;let X=this.createContactEquation(s,c,e,t,d,l);P.vadd(I,X.rj),X.rj.copy(X.rj),B.negate(X.ni),X.ni.normalize(),X.ri.copy(X.rj),X.ri.vadd(n,X.ri),X.ri.vsub(i,X.ri),X.ri.normalize(),X.ri.scale(E,X.ri),X.ri.vadd(i,X.ri),X.ri.vsub(s.position,X.ri),X.rj.vadd(n,X.rj),X.rj.vsub(c.position,X.rj),this.result.push(X),this.createFrictionEquationsFromContact(X,this.frictionResult)}}u.release(O,P,L,I,B)}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 E=zb;if(!(i.distanceTo(n)>e.boundingSphereRadius+t.boundingSphereRadius)&&e.findSeparatingAxis(t,i,r,n,o,E,u,f)){let b=[],y=Vb;e.clipAgainstHull(i,r,t,n,o,E,-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;E.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,Sb);let f=t.faceNormals,E=t.faces,b=t.vertices,y=e.radius,g=!1;for(let p=0;p!==b.length;p++){let m=b[p],v=kb;o.vmult(m,v),n.vadd(v,v);let w=Ab;if(v.vsub(i,w),w.lengthSquared()<y*y){if(h)return!0;g=!0;let x=this.createContactEquation(s,c,e,t,d,l);x.ri.copy(w),x.ri.normalize(),x.ni.copy(x.ri),x.ri.scale(y,x.ri),v.vsub(n,x.rj),x.ri.vadd(i,x.ri),x.ri.vsub(s.position,x.ri),x.rj.vadd(n,x.rj),x.rj.vsub(c.position,x.rj),this.result.push(x),this.createFrictionEquationsFromContact(x,this.frictionResult);return}}for(let p=0,m=E.length;p!==m&&g===!1;p++){let v=f[p],w=E[p],x=Ib;o.vmult(v,x);let T=Mb;o.vmult(b[w[0]],T),T.vadd(n,T);let R=Lb;x.scale(-y,R),i.vadd(R,R);let S=Db;R.vsub(T,S);let O=S.dot(x),P=Hb;if(i.vsub(T,P),O<0&&P.dot(x)>0){let L=[];for(let I=0,B=w.length;I!==B;I++){let j=u.get();o.vmult(b[w[I]],j),n.vadd(j,j),L.push(j)}if(vb(L,x,i)){if(h)return!0;g=!0;let I=this.createContactEquation(s,c,e,t,d,l);x.scale(-y,I.ri),x.negate(I.ni);let B=u.get();x.scale(-O,B);let j=u.get();x.scale(-y,j),i.vsub(n,I.rj),I.rj.vadd(j,I.rj),I.rj.vadd(B,I.rj),I.rj.vadd(n,I.rj),I.rj.vsub(c.position,I.rj),I.ri.vadd(i,I.ri),I.ri.vsub(s.position,I.ri),u.release(B),u.release(j),this.result.push(I),this.createFrictionEquationsFromContact(I,this.frictionResult);for(let N=0,W=L.length;N!==W;N++)u.release(L[N]);return}else for(let I=0;I!==w.length;I++){let B=u.get(),j=u.get();o.vmult(b[w[(I+1)%w.length]],B),o.vmult(b[w[(I+2)%w.length]],j),n.vadd(B,B),n.vadd(j,j);let N=Pb;j.vsub(B,N);let W=Ob;N.unit(W);let Z=u.get(),G=u.get();i.vsub(B,G);let ze=G.dot(W);W.scale(ze,Z),Z.vadd(B,Z);let ge=u.get();if(Z.vsub(i,ge),ze>0&&ze*ze<N.lengthSquared()&&ge.lengthSquared()<y*y){if(h)return!0;let X=this.createContactEquation(s,c,e,t,d,l);Z.vsub(n,X.rj),Z.vsub(i,X.ni),X.ni.normalize(),X.ni.scale(y,X.ri),X.rj.vadd(n,X.rj),X.rj.vsub(c.position,X.rj),X.ri.vadd(i,X.ri),X.ri.vsub(s.position,X.ri),this.result.push(X),this.createFrictionEquationsFromContact(X,this.frictionResult);for(let qe=0,cn=L.length;qe!==cn;qe++)u.release(L[qe]);u.release(B),u.release(j),u.release(Z),u.release(ge),u.release(G);return}u.release(B),u.release(j),u.release(Z),u.release(ge),u.release(G)}for(let I=0,B=L.length;I!==B;I++)u.release(L[I])}}}planeConvex(e,t,i,n,r,o,s,c,d,l,h){let u=jb,f=Bb;f.set(0,0,1),r.vmult(f,f);let E=0,b=Fb;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=Nb;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),E++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(p,this.frictionResult)}this.enableFrictionReduction&&E&&this.createFrictionFromAverage(E)}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,E=t.elementSize,b=ev,y=$b;te.pointToLocalFrame(n,o,i,y);let g=Math.floor((y.x-f)/E)-1,p=Math.ceil((y.x+f)/E)+1,m=Math.floor((y.y-f)/E)-1,v=Math.ceil((y.y+f)/E)+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 x=w[0],T=w[1];if(y.z-f>T||y.z+f<x)return;let R=this.result;for(let S=g;S<p;S++)for(let O=m;O<v;O++){let P=R.length,L=!1;if(t.getConvexTrianglePillar(S,O,!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(S,O,!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(R.length-P>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,E=e.boundingSphereRadius,b=Jb,y=Zb,g=Kb;te.pointToLocalFrame(n,o,i,g);let p=Math.floor((g.x-E)/f)-1,m=Math.ceil((g.x+E)/f)+1,v=Math.floor((g.y-E)/f)-1,w=Math.ceil((g.y+E)/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 x=[];t.getRectMinMax(p,v,m,w,x);let T=x[0],R=x[1];if(!(g.z-E>R||g.z+E<T))for(let S=p;S<m;S++)for(let O=v;O<w;O++){let P=!1;if(t.getConvexTrianglePillar(S,O,!1),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(P=this.convexConvex(e,t.pillarConvex,i,b,r,o,s,c,null,null,h,y,null)),h&&P||(t.getConvexTrianglePillar(S,O,!0),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(P=this.convexConvex(e,t.pillarConvex,i,b,r,o,s,c,null,null,h,y,null)),h&&P))return!0}}sphereParticle(e,t,i,n,r,o,s,c,d,l,h){let u=qb;if(u.set(0,0,1),n.vsub(i,u),u.lengthSquared()<=e.radius*e.radius){if(h)return!0;let E=this.createContactEquation(c,s,t,e,d,l);u.normalize(),E.rj.copy(u),E.rj.scale(e.radius,E.rj),E.ni.copy(u),E.ni.negate(E.ni),E.ri.set(0,0,0),this.result.push(E),this.createFrictionEquationsFromContact(E,this.frictionResult)}}planeParticle(e,t,i,n,r,o,s,c,d,l,h){let u=Ub;u.set(0,0,1),s.quaternion.vmult(u,u);let f=Gb;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=Wb;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=Qb,E=Yb,b=null,y=Xb;if(y.copy(n),y.vsub(i,y),r.conjugate(xu),xu.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],Tu);let w=-v.dot(Tu);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,E),E.vadd(n,E),E.vsub(i,E),g.rj.copy(E),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=rb,f=ob,E=sb,b=ab,y=lb,g=cb,p=pb,m=nb,v=tb,w=fb;te.pointToLocalFrame(n,o,i,y);let x=e.radius;p.lowerBound.set(y.x-x,y.y-x,y.z-x),p.upperBound.set(y.x+x,y.y+x,y.z+x),t.getTrianglesInAABB(p,w);let T=ib,R=e.radius*e.radius;for(let I=0;I<w.length;I++)for(let B=0;B<3;B++)if(t.getVertex(t.indices[w[I]*3+B],T),T.vsub(y,v),v.lengthSquared()<=R){if(m.copy(T),te.pointToWorldFrame(n,o,m,T),T.vsub(i,v),h)return!0;let j=this.createContactEquation(s,c,e,t,d,l);j.ni.copy(v),j.ni.normalize(),j.ri.copy(j.ni),j.ri.scale(e.radius,j.ri),j.ri.vadd(i,j.ri),j.ri.vsub(s.position,j.ri),j.rj.copy(T),j.rj.vsub(c.position,j.rj),this.result.push(j),this.createFrictionEquationsFromContact(j,this.frictionResult)}for(let I=0;I<w.length;I++)for(let B=0;B<3;B++){t.getVertex(t.indices[w[I]*3+B],u),t.getVertex(t.indices[w[I]*3+(B+1)%3],f),f.vsub(u,E),y.vsub(f,g);let j=g.dot(E);y.vsub(u,g);let N=g.dot(E);if(N>0&&j<0&&(y.vsub(u,g),b.copy(E),b.normalize(),N=g.dot(b),b.scale(N,g),g.vadd(u,g),g.distanceTo(y)<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)}}let S=db,O=hb,P=ub,L=eb;for(let I=0,B=w.length;I!==B;I++){t.getTriangleVertices(w[I],S,O,P),t.getNormal(w[I],L),y.vsub(S,g);let j=g.dot(L);if(L.scale(j,g),y.vsub(g,g),j=g.distanceTo(y),ye.pointInTriangle(g,S,O,P)&&j<e.radius){if(h)return!0;let N=this.createContactEquation(s,c,e,t,d,l);g.vsub(y,N.ni),N.ni.normalize(),N.ni.scale(e.radius,N.ri),N.ri.vadd(i,N.ri),N.ri.vsub(s.position,N.ri),te.pointToWorldFrame(n,o,g,g),g.vsub(c.position,N.rj),te.vectorToWorldFrame(o,N.ni,N.ni),te.vectorToWorldFrame(o,N.ri,N.ri),this.result.push(N),this.createFrictionEquationsFromContact(N,this.frictionResult)}}w.length=0}planeTrimesh(e,t,i,n,r,o,s,c,d,l,h){let u=new _,f=Jg;f.set(0,0,1),r.vmult(f,f);for(let E=0;E<t.vertices.length/3;E++){t.getVertex(E,u);let b=new _;b.copy(u),te.pointToWorldFrame(n,o,b,u);let y=Zg;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=$g;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)}}}},ir=new _,Gr=new _,Wr=new _,Xg=new _,Qg=new _,Yg=new ce,Kg=new ce,Jg=new _,Zg=new _,$g=new _,eb=new _,tb=new _,ib=new _,nb=new _,rb=new _,ob=new _,sb=new _,ab=new _,lb=new _,cb=new _,db=new _,hb=new _,ub=new _,pb=new Ze,fb=[],la=new _,_u=new _,mb=new _,gb=new _,bb=new _;function vb(a,e,t){let i=null,n=a.length;for(let r=0;r!==n;r++){let o=a[r],s=mb;a[(r+1)%n].vsub(o,s);let c=gb;s.cross(e,c);let d=bb;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 ca=new _,yb=new _,Eb=new _,wb=new _,_b=[new _,new _,new _,new _,new _,new _],xb=new _,Tb=new _,Rb=new _,Cb=new _,Sb=new _,Pb=new _,Ob=new _,Ab=new _,kb=new _,Ib=new _,Mb=new _,Lb=new _,Db=new _,Hb=new _,jb=new _,Bb=new _,Fb=new _,Nb=new _,zb=new _,Vb=new _,Ub=new _,Gb=new _,Wb=new _,qb=new _,xu=new ce,Xb=new _,Qb=new _,Tu=new _,Yb=new _,Kb=new _,Jb=new _,Zb=[0],$b=new _,ev=new _,ba=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||Ru(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||Ru(t,l)}}};function Ru(a,e){a.push((e&4294901760)>>16,e&65535)}var yc=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]}}},va=class extends ha{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 uc,this.bodies=[],this.hasActiveBodies=!1,this.solver=e.solver!==void 0?e.solver:new mc,this.constraints=[],this.narrowphase=new vc(this),this.collisionMatrix=new da,this.collisionMatrixPrevious=new da,this.bodyOverlapKeeper=new ba,this.shapeOverlapKeeper=new ba,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new yc,this.defaultMaterial=new Xr("default"),this.defaultContactMaterial=new qr(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 ds?this.raycastClosest(e,t,{skipBackfaces:!0},i):this.raycastAll(e,t,{skipBackfaces:!0},i)}raycastAll(e,t,i={},n){return i.mode=ye.ALL,i.from=e,i.to=t,i.callback=n,dc.intersectWorld(this,i)}raycastAny(e,t,i={},n){return i.mode=ye.ANY,i.from=e,i.to=t,i.result=n,dc.intersectWorld(this,i)}raycastClosest(e,t,i={},n){return i.mode=ye.CLOSEST,i.from=e,i.to=t,i.result=n,dc.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 V&&(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=He.now(),r=0;for(;this.accumulator>=e&&r<i&&(this.internalStep(e),this.accumulator-=e,r++,!(He.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=ov,n=sv,r=this.numObjects(),o=this.bodies,s=this.solver,c=this.gravity,d=this.doProfiling,l=this.profile,h=V.DYNAMIC,u=-1/0,f=this.constraints,E=rv;c.length();let b=c.x,y=c.y,g=c.z,p=0;for(d&&(u=He.now()),p=0;p!==r;p++){let I=o[p];if(I.type===h){let B=I.force,j=I.mass;B.x+=j*b,B.y+=j*y,B.z+=j*g}}for(let I=0,B=this.subsystems.length;I!==B;I++)this.subsystems[I].update();d&&(u=He.now()),i.length=0,n.length=0,this.broadphase.collisionPairs(this,i,n),d&&(l.broadphase=He.now()-u);let m=f.length;for(p=0;p!==m;p++){let I=f[p];if(!I.collideConnected)for(let B=i.length-1;B>=0;B-=1)(I.bodyA===i[B]&&I.bodyB===n[B]||I.bodyB===i[B]&&I.bodyA===n[B])&&(i.splice(B,1),n.splice(B,1))}this.collisionMatrixTick(),d&&(u=He.now());let v=nv,w=t.length;for(p=0;p!==w;p++)v.push(t[p]);t.length=0;let x=this.frictionEquations.length;for(p=0;p!==x;p++)E.push(this.frictionEquations[p]);for(this.frictionEquations.length=0,this.narrowphase.getContacts(i,n,this,t,v,this.frictionEquations,E),d&&(l.narrowphase=He.now()-u),d&&(u=He.now()),p=0;p<this.frictionEquations.length;p++)s.addEquation(this.frictionEquations[p]);let T=t.length;for(let I=0;I!==T;I++){let B=t[I],j=B.bi,N=B.bj,W=B.si,Z=B.sj,G;if(j.material&&N.material?G=this.getContactMaterial(j.material,N.material)||this.defaultContactMaterial:G=this.defaultContactMaterial,G.friction,j.material&&N.material&&(j.material.friction>=0&&N.material.friction>=0&&j.material.friction*N.material.friction,j.material.restitution>=0&&N.material.restitution>=0&&(B.restitution=j.material.restitution*N.material.restitution)),s.addEquation(B),j.allowSleep&&j.type===V.DYNAMIC&&j.sleepState===V.SLEEPING&&N.sleepState===V.AWAKE&&N.type!==V.STATIC){let ze=N.velocity.lengthSquared()+N.angularVelocity.lengthSquared(),ge=N.sleepSpeedLimit**2;ze>=ge*2&&(j.wakeUpAfterNarrowphase=!0)}if(N.allowSleep&&N.type===V.DYNAMIC&&N.sleepState===V.SLEEPING&&j.sleepState===V.AWAKE&&j.type!==V.STATIC){let ze=j.velocity.lengthSquared()+j.angularVelocity.lengthSquared(),ge=j.sleepSpeedLimit**2;ze>=ge*2&&(N.wakeUpAfterNarrowphase=!0)}this.collisionMatrix.set(j,N,!0),this.collisionMatrixPrevious.get(j,N)||(as.body=N,as.contact=B,j.dispatchEvent(as),as.body=j,N.dispatchEvent(as)),this.bodyOverlapKeeper.set(j.id,N.id),this.shapeOverlapKeeper.set(W.id,Z.id)}for(this.emitContactEvents(),d&&(l.makeContactConstraints=He.now()-u,u=He.now()),p=0;p!==r;p++){let I=o[p];I.wakeUpAfterNarrowphase&&(I.wakeUp(),I.wakeUpAfterNarrowphase=!1)}for(m=f.length,p=0;p!==m;p++){let I=f[p];I.update();for(let B=0,j=I.equations.length;B!==j;B++){let N=I.equations[B];s.addEquation(N)}}s.solve(e,this),d&&(l.solve=He.now()-u),s.removeAllEquations();let R=Math.pow;for(p=0;p!==r;p++){let I=o[p];if(I.type&h){let B=R(1-I.linearDamping,e),j=I.velocity;j.scale(B,j);let N=I.angularVelocity;if(N){let W=R(1-I.angularDamping,e);N.scale(W,N)}}}for(this.dispatchEvent(iv),p=0;p!==r;p++){let I=o[p];I.preStep&&I.preStep.call(I)}d&&(u=He.now());let O=this.stepnumber%(this.quatNormalizeSkip+1)===0,P=this.quatNormalizeFast;for(p=0;p!==r;p++)o[p].integrate(e,O,P);for(this.clearForces(),this.broadphase.dirty=!0,d&&(l.integrate=He.now()-u),this.stepnumber+=1,this.dispatchEvent(tv),p=0;p!==r;p++){let I=o[p],B=I.postStep;B&&B.call(I)}let L=!0;if(this.allowSleep)for(L=!1,p=0;p!==r;p++){let I=o[p];I.sleepTick(this.time),I.sleepState!==V.SLEEPING&&(L=!0)}this.hasActiveBodies=L}emitContactEvents(){let e=this.hasAnyEventListener("beginContact"),t=this.hasAnyEventListener("endContact");if((e||t)&&this.bodyOverlapKeeper.getDiff(Hi,ji),e){for(let r=0,o=Hi.length;r<o;r+=2)ls.bodyA=this.getBodyById(Hi[r]),ls.bodyB=this.getBodyById(Hi[r+1]),this.dispatchEvent(ls);ls.bodyA=ls.bodyB=null}if(t){for(let r=0,o=ji.length;r<o;r+=2)cs.bodyA=this.getBodyById(ji[r]),cs.bodyB=this.getBodyById(ji[r+1]),this.dispatchEvent(cs);cs.bodyA=cs.bodyB=null}Hi.length=ji.length=0;let i=this.hasAnyEventListener("beginShapeContact"),n=this.hasAnyEventListener("endShapeContact");if((i||n)&&this.shapeOverlapKeeper.getDiff(Hi,ji),i){for(let r=0,o=Hi.length;r<o;r+=2){let s=this.getShapeById(Hi[r]),c=this.getShapeById(Hi[r+1]);Bi.shapeA=s,Bi.shapeB=c,s&&(Bi.bodyA=s.body),c&&(Bi.bodyB=c.body),this.dispatchEvent(Bi)}Bi.bodyA=Bi.bodyB=Bi.shapeA=Bi.shapeB=null}if(n){for(let r=0,o=ji.length;r<o;r+=2){let s=this.getShapeById(ji[r]),c=this.getShapeById(ji[r+1]);Fi.shapeA=s,Fi.shapeB=c,s&&(Fi.bodyA=s.body),c&&(Fi.bodyB=c.body),this.dispatchEvent(Fi)}Fi.bodyA=Fi.bodyB=Fi.shapeA=Fi.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 dc=new ye,He=globalThis.performance||{};if(!He.now){let a=Date.now();He.timing&&He.timing.navigationStart&&(a=He.timing.navigationStart),He.now=()=>Date.now()-a}var tv={type:"postStep"},iv={type:"preStep"},as={type:V.COLLIDE_EVENT_NAME,body:null,contact:null},nv=[],rv=[],ov=[],sv=[],Hi=[],ji=[],ls={type:"beginContact",bodyA:null,bodyB:null},cs={type:"endContact",bodyA:null,bodyB:null},Bi={type:"beginShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null},Fi={type:"endShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null};import*as we from"three";import{MeshBasicMaterial as av,SphereGeometry as rp,BoxGeometry as op,PlaneGeometry as sp,Mesh as yn,CylinderGeometry as lv,BufferGeometry as Tc,Float32BufferAttribute as Rc}from"three";function cv(a,e,{color:t=65280,scale:i=1,onInit:n,onUpdate:r,autoUpdate:o}={}){let s=[],c=new av({color:t??65280,wireframe:!0}),d=new _,l=new _,h=new _,u=new ce,f=new rp(1),E=new op(1,1,1),b=new sp(10,10,10,10);function y(R){let S=new Tc,O=[];for(let L=0;L<R.vertices.length;L++){let I=R.vertices[L];O.push(I.x,I.y,I.z)}S.setAttribute("position",new Rc(O,3));let P=[];for(let L=0;L<R.faces.length;L++){let I=R.faces[L],B=I[0];for(let j=1;j<I.length-1;j++){let N=I[j],W=I[j+1];P.push(B,N,W)}}return S.setIndex(P),S.computeBoundingSphere(),S.computeVertexNormals(),S}function g(R){let S=new Tc,O=[],P=d,L=l,I=h;for(let B=0;B<R.indices.length/3;B++)R.getTriangleVertices(B,P,L,I),O.push(P.x,P.y,P.z),O.push(L.x,L.y,L.z),O.push(I.x,I.y,I.z);return S.setAttribute("position",new Rc(O,3)),S.computeBoundingSphere(),S.computeVertexNormals(),S}function p(R){let S=new Tc,O=R.elementSize||1,P=R.data.flatMap((I,B)=>I.flatMap((j,N)=>[B*O,N*O,j])),L=[];for(let I=0;I<R.data.length-1;I++)for(let B=0;B<R.data[I].length-1;B++){let j=R.data[I].length,N=I*j+B;L.push(N+1,N+j,N+j+1),L.push(N+j,N+1,N)}return S.setIndex(L),S.setAttribute("position",new Rc(P,3)),S.computeBoundingSphere(),S.computeVertexNormals(),S}function m(R){let S=new yn,{SPHERE:O,BOX:P,PLANE:L,CYLINDER:I,CONVEXPOLYHEDRON:B,TRIMESH:j,HEIGHTFIELD:N}=U.types;switch(R.type){case O:{S=new yn(f,c);break}case P:{S=new yn(E,c);break}case L:{S=new yn(b,c);break}case I:{let W=new lv(R.radiusTop,R.radiusBottom,R.height,R.numSegments);S=new yn(W,c),R.geometryId=W.id;break}case B:{let W=y(R);S=new yn(W,c),R.geometryId=W.id;break}case j:{let W=g(R);S=new yn(W,c),R.geometryId=W.id;break}case N:{let W=p(R);S=new yn(W,c),R.geometryId=W.id;break}}return a.add(S),S}function v(R,S){let{SPHERE:O,BOX:P,PLANE:L,CYLINDER:I,CONVEXPOLYHEDRON:B,TRIMESH:j,HEIGHTFIELD:N}=U.types;switch(S.type){case O:{let{radius:W}=S;R.scale.set(W*i,W*i,W*i);break}case P:{R.scale.copy(S.halfExtents),R.scale.multiplyScalar(2*i);break}case L:break;case I:{R.scale.set(1*i,1*i,1*i);break}case B:{R.scale.set(1*i,1*i,1*i);break}case j:{R.scale.copy(S.scale).multiplyScalar(i);break}case N:{R.scale.set(1*i,1*i,1*i);break}}}function w(R,S){if(!R)return!1;let{geometry:O}=R;return O instanceof rp&&S.type===U.types.SPHERE||O instanceof op&&S.type===U.types.BOX||O instanceof sp&&S.type===U.types.PLANE||O.id===S.geometryId&&S.type===U.types.CYLINDER||O.id===S.geometryId&&S.type===U.types.CONVEXPOLYHEDRON||O.id===S.geometryId&&S.type===U.types.TRIMESH||O.id===S.geometryId&&S.type===U.types.HEIGHTFIELD}function x(R,S){let O=s[R],P=!1;return w(O,S)||(O&&a.remove(O),s[R]=O=m(S),P=!0),v(O,S),P}function T(){let R=s,S=d,O=u,P=0;for(let L of e)for(let I=0;I!==L.shapes.length;I++){let B=L.shapes[I],j=x(P,B),N=R[P];N&&(L.quaternion.vmult(L.shapeOffsets[I],S),L.position.vadd(S,S),L.quaternion.mult(L.shapeOrientations[I],O),N.position.copy(S),N.quaternion.copy(O),j&&n instanceof Function&&n(L,N,B),!j&&r instanceof Function&&r(L,N,B)),P++}for(let L=P;L<R.length;L++){let I=R[L];I&&a.remove(I)}R.length=P,o!==!1&&requestAnimationFrame(T)}return o!==!1&&requestAnimationFrame(T),{update:T}}var ap=cv;import*as ui from"three";import*as us from"three";var Ni=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new us.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new us.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 us.ShaderMaterial({vertexShader:`
93
+ }`});import*as rs from"three";var $h=/^(?:[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 Tm(a){return typeof a=="string"&&$h.test(a)}var eu=Tm;var Ve=[];for(let a=0;a<256;++a)Ve.push((a+256).toString(16).slice(1));function tu(a,e=0){return(Ve[a[e+0]]+Ve[a[e+1]]+Ve[a[e+2]]+Ve[a[e+3]]+"-"+Ve[a[e+4]]+Ve[a[e+5]]+"-"+Ve[a[e+6]]+Ve[a[e+7]]+"-"+Ve[a[e+8]]+Ve[a[e+9]]+"-"+Ve[a[e+10]]+Ve[a[e+11]]+Ve[a[e+12]]+Ve[a[e+13]]+Ve[a[e+14]]+Ve[a[e+15]]).toLowerCase()}function Rm(a){if(!eu(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 iu=Rm;function Cm(a){a=unescape(encodeURIComponent(a));let e=[];for(let t=0;t<a.length;++t)e.push(a.charCodeAt(t));return e}var Sm="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Pm="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Jl(a,e,t){function i(n,r,o,s){var c;if(typeof n=="string"&&(n=Cm(n)),typeof r=="string"&&(r=iu(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 tu(d)}try{i.name=a}catch{}return i.DNS=Sm,i.URL=Pm,i}function Om(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 Zl(a,e){return a<<e|a>>>32-e}function Am(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]=Zl(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 E=Math.floor(f/20),b=Zl(c,5)+Om(E,d,l,h)+u+e[E]+s[f]>>>0;u=h,h=l,l=Zl(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 nu=Am;var km=Jl("v5",80,nu),$l=km;var Js=H("debugcomponents"),Im="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,$l(e.toString(),Im)}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 Zs=class{guid;constructor(e){this.guid=e}};function Vr(a,e,t=!0){if(!a)return;let i=a;if(C.destroy(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 Zs(n);e.send("instance-destroyed",r)}function ru(a,e){let t=new Zs(a);e.send("instance-destroyed",t)}function ou(a){a.connection.beginListen("instance-destroyed",e=>{Js&&console.log("[Remote] Destroyed",a.scene,e);let t=C.findByGuid(e.guid,a.scene);t&&C.destroy(t)})}var ec=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function $s(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=Q.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}=Mm(n,e);if(o){let c=o;if(c.guid){Js&&console.log("[Local] new instance","gameobject:",o?.guid);let d=new ec(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 ea(){return Math.random()*9999999}function su(a){a.connection.beginListen("new-instance-created",async e=>{let t=await Lm(e.originalGuid,a.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let i=new be;e.position&&(i.position=new rs.Vector3(e.position.x,e.position.y,e.position.z)),e.rotation&&(i.rotation=new rs.Quaternion(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w)),e.scale&&(i.scale=new rs.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,Js&&a.alias&&console.log("[Remote] instantiate in: "+a.alias);let n=C.instantiate(t,i);n&&(e.parent==="scene"&&a.scene.add(n),Js&&console.log("[Remote] new instance","gameobject:",n?.guid,t))})}function Mm(a,e){let t=ea(),i=e??new be;i.idProvider=new Ue(t);let n=C.instantiate(a,i);return{seed:t,instance:n}}var au={};function lu(a,e){au[a]=e}async function Lm(a,e){let t=au[a];if(t!=null){let i=await t(a);if(i)return i}return cu(a,e)}function cu(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=cu(a,t);if(i)return i}return null}import{Object3D as ft}from"three";var du=Symbol("GameObject.decorated");Object.defineProperty(ft.prototype,"activeSelf",{get:function(){return this.visible},set:function(a){let e=typeof a=="number"?a>.5:a;this.visible=e}});ft.prototype.SetActive=function(a){this.visible=a};ft.prototype.addNewComponent=function(a){return C.addNewComponent(this,a)};ft.prototype.removeComponent=function(a){return C.removeComponent(a)};ft.prototype.getOrAddComponent=function(a){return C.getOrAddComponent(this,a)};ft.prototype.getComponent=function(a){return C.getComponent(this,a)};ft.prototype.getComponents=function(a,e){return C.getComponents(this,a,e)};ft.prototype.getComponentInChildren=function(a){return C.getComponentInChildren(this,a)};ft.prototype.getComponentsInChildren=function(a,e){return C.getComponentsInChildren(this,a,e)};ft.prototype.getComponentInParent=function(a){return C.getComponentInParent(this,a)};ft.prototype.getComponentsInParent=function(a,e){return C.getComponentsInParent(this,a,e)};var ta=Object.keys(ft.prototype),hu=new Array;for(let a=0;a<ta.length;a++){let e=ta[a],t=Object.getOwnPropertyDescriptor(ft.prototype,e);t&&hu.push(t)}function ia(a){if(!a[du]){a[du]=!0;for(let e=0;e<ta.length;e++){let t=ta[e],i=hu[e];i&&Object.defineProperty(a,t,i)}}}var vn=H("debugcomponents"),uu=(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))(uu||{}),be=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context},C=class extends qe.Object3D{guid;static setActive(e,t,i=!0){!e||(e.visible=t,bn(e),t&&i&&Ns(Q.Current,e))}static isActiveSelf(e){return e.visible||C.isUsingInstancing(e)}static isActiveInHierarchy(e){return e[un]||C.isUsingInstancing(e)}static markAsInstancedRendered(e,t){e.__isUsingInstancing=t}static isUsingInstancing(e){return e.__isUsingInstancing===!0}static foreachComponent(e,t,i=!0){if(!!e){if(e.userData.components)for(let n=0;n<e.userData.components.length;n++){let r=e.userData.components[n];if(r instanceof M){let o=t(r);if(o!==void 0)return o}}if(i&&e.children)for(let n=0;n<e.children.length;n++){let r=e.children[n];if(!r)continue;let o=C.foreachComponent(r,t,i);if(o!==void 0)return o}}}static instantiateSynced(e,t){return e?$s(e,t):null}static instantiate(e,t=null){if(e===null)return null;let i=null;t!==null&&(t.x!==void 0?(i=new be,i.position=t):i=t);let n=Q.Current;i?.context&&(n=i.context),vn&&n.alias&&console.log("context",n.alias),i&&!i.idProvider&&(i.idProvider=new Ue(Date.now()));let r=[],o={},s={},c=this.internalInstantiate(n,e,i,r,o,s);c&&(this.resolveReferences(o),this.resolveAndBindSkinnedMeshBones(s,o)),vn&&(ns(e,!0),ns(c,!0));let d={};for(let l in r){let h=r[l],u=h.guid;i&&i.idProvider&&(h.guid=i.idProvider.generateUUID(),d[u]=h.guid,vn&&console.log(h.name,h.guid)),Wl(h,n),h.__internalNewInstanceCreated&&h.__internalNewInstanceCreated()}for(let l in r){let h=r[l];h.resolveGuids&&h.resolveGuids(d),h.enabled!==!1&&(h.enabled=!0)}return Di(n),c}static internalInstantiate(e,t,i,n,r,o){if(!t)return null;let s=t.userData;t.userData={};let c=t.children;t.children=[];let d;if(d=t.clone(!1),ia(d),t.userData=s,t.children=c,r[t.uuid]={original:t,clone:d},t.type==="SkinnedMesh"&&(o[t.uuid]={original:t,clone:d}),i?.visible!==void 0&&(d.visible=i.visible),i?.idProvider){d.uuid=i.idProvider.generateUUID();let h=d;h&&(h.guid=d.uuid)}t.animations&&t.animations.length>0&&(d.animations=[...t.animations]);let l=t.parent;if(l&&l.add(d),i?.position?ae(d,i.position):d.position.copy(t.position),i?.rotation?ot(d,i.rotation):d.quaternion.copy(t.quaternion),i?.scale?d.scale.copy(i.scale):d.scale.copy(t.scale),i?.parent&&i.parent!=="scene"){let h=null;if(typeof i.parent=="string"?h=pn(i.parent,e.scene,!0):h=i.parent,h){let u=i.keepWorldPosition===!0?h.attach:h.add;u?u.call(h,d):console.error("Invalid parent object",h,"received when instantiating:",t)}else console.warn("could not find parent:",i.parent)}for(let[h,u]of Object.entries(t.userData))h!=="components"&&(d.userData[h]=u);if(t.userData?.components){let h=t.userData.components,u=[];d.userData.components=u;for(let f=0;f<h.length;f++){let E=h[f],b=Object.create(E);Object.assign(b,E),u.push(b),b.gameObject=d,n.push(b)}}i&&(i.position=void 0,i.rotation=void 0,i.scale=void 0,i.parent=void 0);for(let h in t.children){let u=t.children[h],f=C.internalInstantiate(e,u,i,n,r,o);f&&d.add(f)}return d}static resolveAndBindSkinnedMeshBones(e,t){for(let i in e){let n=e[i],r=n.original,o=r.skeleton,s=n.clone;if(!o){console.warn("Skinned mesh has no skeleton?",n);continue}let c=o.bones,d=s.skeleton.clone();s.skeleton=d,s.bindMatrix.clone().copy(r.bindMatrix),s.bindMatrixInverse.copy(r.bindMatrixInverse);let l=[];d.bones=l;for(let h=0;h<c.length;h++){let u=c[h],E=t[u.uuid].clone;l.push(E)}}for(let i in e){let n=e[i].clone;n.skeleton.update(),n.bind(n.skeleton,n.bindMatrix),n.updateMatrixWorld(!0)}}static resolveReferences(e){for(let t in e){let n=e[t].clone;if(n.userData?.components)for(let r=0;r<n.userData.components.length;r++){let o=n.userData.components[r],s=Object.entries(o);for(let[c,d]of s)if(Array.isArray(d)){let l=[];o[c]=l;for(let h=0;h<d.length;h++){let u=d[h];if(typeof u!="object"){l.push(u);continue}let f=this.postProcessNewInstance(o,c,u,e);f!==void 0?l.push(f):l.push(u)}}else if(typeof d=="object"){let l=this.postProcessNewInstance(o,c,d,e);l!==void 0&&(o[c]=l)}}}}static postProcessNewInstance(e,t,i,n){if(i instanceof st||i instanceof M){let r=i.gameObject;if(r){let o=r.uuid,s=n[o]?.clone;if(!s){vn&&console.log("reference did not change",t,e,i);return}let c=r.userData.components.indexOf(i);if(c>=0)return vn&&console.log(t,o),s.userData.components[c];console.warn("could not find component",t,i)}}else if(i instanceof qe.Object3D){if(t==="gameObject")return;let r=i;if(r){let o=r.uuid,s=n[o]?.clone;if(s)return vn&&console.log(t,"old",i,"new",s),s}}}static destroySynced(e,t,i=!0){if(!e)return;let n=e;t=t??Q.Current,Vr(n,t.connection,i)}static destroy(e,t=!0,i=!0){let n=e;if(n.isComponent){n.destroy();return}let r=e;if(vn&&console.log(r),t&&r.children)for(let s of r.children)C.destroy(s,t,!1);let o=r.userData.components;if(o){let s=o.length;for(let c=0;c<o.length;c++){let d=o[c];d.destroy&&(vn&&console.log("destroying",d),d.destroy()),o.length<s&&(s=o.length,c--)}}i&&r.removeFromParent()}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=Q.Current),t.add(e),bn(e),i?C.foreachComponent(e,n=>{Vl(n,i),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),C.foreachComponent(e,t=>{Nh(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 Vs(n,e,i),n}static addComponent(e,t){if(t.gameObject==null)throw new Error("Did you mean to create a new component? Use addNewComponent");Gh(t,e)}static removeComponent(e){return Uh(e.gameObject,e),e}static getOrAddComponent(e,t){let i=this.getComponent(e,t);return i||this.addNewComponent(e,t)}static getComponent(e,t){return e===null?null:Us(t,e)}static getComponents(e,t,i=null){return e===null?i??[]:Gs(t,e,i)}static findByGuid(e,t){return pn(e,t,!0,!0)}static findObjectOfType(e,t,i=!0){return Xh(e,t,i)}static findObjectsOfType(e,t){let i=[];return Qh(e,i,t),i}static getComponentInChildren(e,t){return Ws(t,e)}static getComponentsInChildren(e,t,i=null){return qs(t,e,i)}static getComponentInParent(e,t){return zs(t,e)}static getComponentsInParent(e,t,i=null){return ql(t,e,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]}},Wt=class{get isComponent(){return!0}__context;get context(){return this.__context??Q.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[un];return e===void 0?!0: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||Wh(this)}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;__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(){this.__didEnable||(this.__didEnable=!0,this.onEnable())}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this._collisionExitRoutine=void 0,this.onDisable(),this._collisions?.clear())}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 qe.Vector3),q(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){ae(this.gameObject,e)}setWorldPosition(e,t,i){Wt._worldPositionBuffer.set(e,t,i),this.worldPosition=Wt._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new qe.Quaternion),Ae(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){ot(this.gameObject,e)}setWorldQuaternion(e,t,i,n){Wt._worldQuaternionBuffer.set(e,t,i,n),this.worldQuaternion=Wt._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new qe.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new qe.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new qe.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=Y.toDegrees(t.x),t.y=Y.toDegrees(t.y),t.z=Y.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){n&&(e=Y.toRadians(e),t=Y.toRadians(t),i=Y.toRadians(i)),Wt._worldEulerBuffer.set(e,t,i),Wt._worldQuaternionBuffer.setFromEuler(Wt._worldEulerBuffer),this.worldQuaternion=Wt._worldQuaternionBuffer}get forward(){return Wt._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}},st=Wt;z(st,"_worldPositionBuffer",new qe.Vector3),z(st,"_worldQuaternionBuffer",new qe.Quaternion),z(st,"_worldEulerBuffer",new qe.Euler),z(st,"_tempQuaternionBuffer2",new qe.Quaternion),z(st,"_forward",new qe.Vector3(0,0,1));var M=class extends st{get enabled(){return this.__isEnabled??!0}set enabled(e){typeof e=="number"&&(e>=.5?e=!0:e=!1),e!==this.__isEnabled&&(this.__isEnabled=e,this.__didAwake&&(e?this.__internalEnable():this.__internalDisable()))}};import*as qt from"three";var ci=H("gizmos"),ke=H("debugextension");var ra=H("debugresolvedependencies"),Hm=["/extensions/","extensions/"],jm=[{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 Ur(a,e){ra&&console.log(a,e);let t=[];ic(jm,a,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function ic(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=pu(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=nc(s.prefix,r);if(c>=0){ra&&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=pu(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=nc(d.prefix,s);if(l>=0){ra&&console.log(d,l,d.dependencyName),i.push(e?.getDependency(d.dependencyName,l).then(h=>r[o]=h));break}}typeof s=="object"&&ic(a,e,s,i)}else typeof r=="object"&&ic(a,e,r,i)}else typeof t=="string"&&Bm(a,e,t,i)}function pu(a,e){if(a&&a.plugins&&typeof e=="string"){for(let t of Hm)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(ke&&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 Bm(a,e,t,i){for(let n of a){let r=nc(n.prefix,t);if(r>=0)return ra&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(o=>o)),!0}return!1}function nc(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 rc=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]}},D=new rc;var oc="NEEDLE_persistent_assets";function fu(a){return a?.___persistentAsset===!0}var oa=class{get name(){return oc}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[oc];if(!t)return;ke&&console.log(t);let i=new Array;for(let n of t?.assets){let r=Ur(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){ke&&console.log(t);let n=e.json.extensions[oc];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let o=r.__type;if(o){let s=D.get(o)}}return r}}return null}};var tr=H("debugserializer"),sc=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])}tr&&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){tr&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){tr&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return tr&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){tr&&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){tr&&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}}},aa=new sc,Hi=class{constructor(e){if(Array.isArray(e))for(let t of e)aa.register(t.name,this);else aa.register(e.name,this)}},Gr=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;constructor(e){this.root=e}};function lc(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=aa.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 sa=[];function mu(a,e){if(!a)return e;typeof a.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,a.$serializedTypes));let t=Object.getPrototypeOf(a);return mu(t,e)}function os(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=mu(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?ac(s,h,t,void 0,a[r]):ac(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);sa.length=0,a.onAfterDeserializeMember!==void 0&&a.onAfterDeserializeMember(r,s,t)}}Fm(a,e)}return a.onAfterDeserialize!==void 0&&a.onAfterDeserialize(e,t),t.path=void 0,!0}function Fm(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){tr&&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 ac(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"&&fu(n)){if(n.__concreteInstance)return n.__concreteInstance;let l=n;if(!l.$serializedTypes&&o.prototype.$serializedTypes&&(l.$serializedTypes=o.prototype.$serializedTypes),l.$serializedTypes&&os(l,a,t),n&&o!==void 0)try{let h=new o;ke&&console.log("Create concrete instance for persistent asset",n,"instance:",h),ir(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:aa.getSerializerForConstructor(o)}),Array.isArray(a)){let l=[];for(let h=0;h<a.length;h++){let u=a[h],f=ac(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(...Nm(a));let d=c;return d.$serializedTypes&&os(d,a,t),c}function Nm(a){if(sa.length=0,typeof a=="object"&&a!==null&&a!==void 0)for(let e of Object.keys(a))sa.push(a[e]);return sa}function ir(a,e){if(e==null||a==null)return;let t=!1;for(let i of Object.keys(e)){let n=zm(a,i);t&&n===void 0||(!n||n.writable===!0||n?.set!==void 0)&&(a[i]=e[i])}}function zm(a,e){let t;do t=Object.getOwnPropertyDescriptor(a,e);while(!t&&(a=Object.getPrototypeOf(a)));return t}var ss=class{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}};var la=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 qt.Vector2];_pointerPositionsLastFrame=[new qt.Vector2];_pointerPositionsDelta=[new qt.Vector2];_pointerPositionsRC=[new qt.Vector2];_pointerPositionDown=[new qt.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 ss(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 ss(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 ss(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 qt.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 qt.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new qt.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new qt.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 qt.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=Q.Current;try{Q.Current=this.context;let n=new Event(e);ir(n,t),this.dispatchEvent(n)}finally{Q.Current=i}}};var It=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 It){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],E=i[8],b=n[0],y=n[1],g=n[2],p=n[3],m=n[4],v=n[5],w=n[6],x=n[7],T=n[8];return r[0]=o*b+s*p+c*w,r[1]=o*y+s*m+c*x,r[2]=o*g+s*v+c*T,r[3]=d*b+l*p+h*w,r[4]=d*y+l*m+h*x,r[5]=d*g+l*v+h*T,r[6]=u*b+f*p+E*w,r[7]=u*y+f*m+E*x,r[8]=u*g+f*v+E*T,t}scale(e,t=new It){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 It){let n=Vm,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,E=n*c,b=r*o,y=r*s,g=r*c,p=this.elements;return p[3*0+0]=1-(u+E),p[3*0+1]=l-g,p[3*0+2]=h+y,p[3*1+0]=l+g,p[3*1+1]=1-(d+E),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 It){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}},Vm=[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 It([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=Um,r=1/i;n.set(this.x*r,this.y*r,this.z*r);let o=Gm;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(gu),gu.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 Um=new _,Gm=new _,gu=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,bu),d=bu),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=vu,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=vu,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)),E=Math.min(Math.min(Math.max(s,c),Math.max(d,l)),Math.max(h,u));return!(E<0||f>E)}},bu=new _,vu=[new _,new _,new _,new _,new _,new _,new _,new _],fa=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}},ma=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}},le=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=Wm,n=qm;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 le){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 le){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 le){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 le(this.x,this.y,this.z,this.w)}slerp(e,t,i=new le){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,E,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),E=Math.sin(u),b=Math.sin((1-t)*u)/E,y=Math.sin(t*u)/E):(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 le){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}},Wm=new _,qm=new _,Xm={SPHERE:1,PLANE:2,BOX:4,COMPOUND:8,CONVEXPOLYHEDRON:16,HEIGHTFIELD:32,PARTICLE:64,CYLINDER:128,TRIMESH:256},U=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=U.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}};U.idCounter=0;U.types=Xm;var te=class{constructor(e={}){this.position=void 0,this.quaternion=void 0,this.position=new _,this.quaternion=new le,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(yu),yu.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}},yu=new le,or=class extends U{constructor(e={}){let{vertices:t=[],faces:i=[],normals:n=[],axes:r,boundingSphereRadius:o}=e;super({type:U.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]];or.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 E=0;E<i.faces.length;E++){l.copy(i.faceNormals[E]),r.vmult(l,l);let b=l.dot(o);b>u&&(u=b,h=E)}let f=[];for(let E=0;E<i.faces[h].length;E++){let b=i.vertices[i.faces[h][E]],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 _,E=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,E),!E.almostZero()){E.normalize();let m=y.testSepAxis(E,e,t,i,n,r);if(m===!1)return!1;m<b&&(b=m,o.copy(E))}}return n.vsub(t,h),h.dot(o)>0&&o.negate(o),!0}testSepAxis(e,t,i,n,r,o){let s=this;or.project(s,e,i,n,cc),or.project(t,e,r,o,dc);let c=cc[0],d=cc[1],l=dc[0],h=dc[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 _,E=new _,b=new _,y=this,g=[],p=n,m=g,v=-1,w=Number.MAX_VALUE;for(let O=0;O<y.faces.length;O++){c.copy(y.faceNormals[O]),i.vmult(c,c);let P=c.dot(e);P<w&&(w=P,v=O)}if(v<0)return;let x=y.faces[v];x.connectedFaces=[];for(let O=0;O<y.faces.length;O++)for(let P=0;P<y.faces[O].length;P++)x.indexOf(y.faces[O][P])!==-1&&O!==v&&x.connectedFaces.indexOf(O)===-1&&x.connectedFaces.push(O);let T=x.length;for(let O=0;O<T;O++){let P=y.vertices[x[O]],L=y.vertices[x[(O+1)%T]];P.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(P),i.vmult(f,f),t.vadd(f,f);let I=x.connectedFaces[O];E.copy(this.faceNormals[I]);let B=this.getPlaneConstantOfFace(I);b.copy(E),i.vmult(b,b);let j=B-b.dot(t);for(this.clipFaceAgainstPlane(p,m,b,j);p.length;)p.shift();for(;m.length;)p.push(m.shift())}E.copy(this.faceNormals[v]);let R=this.getPlaneConstantOfFace(v);b.copy(E),i.vmult(b,b);let S=R-b.dot(t);for(let O=0;O<p.length;O++){let P=b.dot(p[O])+S;if(P<=r&&(console.log("clamped: depth="+P+" to minDist="+r),P=r),P<=o){let L=p[O];if(P<=1e-6){let I={point:L,normal:b,depth:P};s.push(I)}}}}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 E=u;(o===void 0||E.x<o)&&(o=E.x),(d===void 0||E.x>d)&&(d=E.x),(s===void 0||E.y<s)&&(s=E.y),(l===void 0||E.y>l)&&(l=E.y),(c===void 0||E.z<c)&&(c=E.z),(h===void 0||E.z>h)&&(h=E.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=Qm,c=0,d=0,l=Ym,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 E=h[f].dot(s);E>c&&(c=E),E<d&&(d=E)}if(d-=u,c-=u,d>c){let f=d;d=c,c=f}r[0]=c,r[1]=d}},cc=[],dc=[],Qm=new _,Ym=new _,sr=class extends U{constructor(e){super({type:U.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 or({vertices:r,faces:o,axes:s});this.convexPolyhedronRepresentation=c,c.material=this.material}calculateLocalInertia(e,t=new _){return sr.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++)En.set(r[o][0],r[o][1],r[o][2]),t.vmult(En,En),e.vadd(En,En),i(En.x,En.y,En.z)}calculateWorldAABB(e,t,i,n){let r=this.halfExtents;di[0].set(r.x,r.y,r.z),di[1].set(-r.x,r.y,r.z),di[2].set(-r.x,-r.y,r.z),di[3].set(-r.x,-r.y,-r.z),di[4].set(r.x,-r.y,-r.z),di[5].set(r.x,r.y,-r.z),di[6].set(-r.x,r.y,-r.z),di[7].set(r.x,-r.y,r.z);let o=di[0];t.vmult(o,o),e.vadd(o,o),n.copy(o),i.copy(o);for(let s=1;s<8;s++){let c=di[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)}}},En=new _,di=[new _,new _,new _,new _,new _,new _,new _,new _],xc={DYNAMIC:1,STATIC:2,KINEMATIC:4},Tc={AWAKE:0,SLEEPY:1,SLEEPING:2},V=class extends ma{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=V.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?V.STATIC:V.DYNAMIC,typeof e.type==typeof V.STATIC&&(this.type=e.type),this.allowSleep=typeof e.allowSleep<"u"?e.allowSleep:!0,this.sleepState=V.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 le,this.initQuaternion=new le,this.previousQuaternion=new le,this.interpolatedQuaternion=new le,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 It,this.invMassSolve=0,this.invInertiaSolve=new _,this.invInertiaWorldSolve=new It,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=V.AWAKE,this.wakeUpAfterNarrowphase=!1,e===V.SLEEPING&&this.dispatchEvent(V.wakeupEvent)}sleep(){this.sleepState=V.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===V.AWAKE&&i<n?(this.sleepState=V.SLEEPY,this.timeLastSleepy=e,this.dispatchEvent(V.sleepyEvent)):t===V.SLEEPY&&i>n?this.wakeUp():t===V.SLEEPY&&e-this.timeLastSleepy>this.sleepTimeLimit&&(this.sleep(),this.dispatchEvent(V.sleepEvent))}}updateSolveMassProperties(){this.sleepState===V.SLEEPING||this.type===V.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 le;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=Km,o=Jm,s=this.quaternion,c=this.aabb,d=Zm;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=$m,n=eg;i.setRotationFromQuaternion(this.quaternion),i.transpose(n),i.scale(t,i),i.mmult(n,this.invInertiaWorld)}}applyForce(e,t=new _){if(this.type!==V.DYNAMIC)return;this.sleepState===V.SLEEPING&&this.wakeUp();let i=tg;t.cross(e,i),this.force.vadd(e,this.force),this.torque.vadd(i,this.torque)}applyLocalForce(e,t=new _){if(this.type!==V.DYNAMIC)return;let i=ig,n=ng;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyForce(i,n)}applyTorque(e){this.type===V.DYNAMIC&&(this.sleepState===V.SLEEPING&&this.wakeUp(),this.torque.vadd(e,this.torque))}applyImpulse(e,t=new _){if(this.type!==V.DYNAMIC)return;this.sleepState===V.SLEEPING&&this.wakeUp();let i=t,n=rg;n.copy(e),n.scale(this.invMass,n),this.velocity.vadd(n,this.velocity);let r=og;i.cross(e,r),this.invInertiaWorld.vmult(r,r),this.angularVelocity.vadd(r,this.angularVelocity)}applyLocalImpulse(e,t=new _){if(this.type!==V.DYNAMIC)return;let i=sg,n=ag;this.vectorToWorldFrame(e,i),this.vectorToWorldFrame(t,n),this.applyImpulse(i,n)}updateMassProperties(){let e=lg;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),sr.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===V.DYNAMIC||this.type===V.KINEMATIC)||this.sleepState===V.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 E=h.elements,b=this.angularFactor,y=c.x*b.x,g=c.y*b.y,p=c.z*b.z;r.x+=e*(E[0]*y+E[1]*g+E[2]*p),r.y+=e*(E[3]*y+E[4]*g+E[5]*p),r.z+=e*(E[6]*y+E[7]*g+E[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()}};V.idCounter=0;V.COLLIDE_EVENT_NAME="collide";V.DYNAMIC=xc.DYNAMIC;V.STATIC=xc.STATIC;V.KINEMATIC=xc.KINEMATIC;V.AWAKE=Tc.AWAKE;V.SLEEPY=Tc.SLEEPY;V.SLEEPING=Tc.SLEEPING;V.wakeupEvent={type:"wakeup"};V.sleepyEvent={type:"sleepy"};V.sleepEvent={type:"sleep"};var Km=new _,Jm=new le,Zm=new Ze,$m=new It,eg=new It,tg=new _,ig=new _,ng=new _,rg=new _,og=new _,sg=new _,ag=new _,lg=new _,fc=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&V.STATIC)!==0||e.sleepState===V.SLEEPING)&&((t.type&V.STATIC)!==0||t.sleepState===V.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=cg;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=dg,n=hg,r=ug,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."),[]}},cg=new _,dg={keys:[]},hg=[],ug=[];var Z_=new _,mc=class extends fc{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}},hs=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}},ku,Iu,Mu,Lu,Du,Hu,ju,Rc={CLOSEST:1,ANY:2,ALL:4};ku=U.types.SPHERE;Iu=U.types.PLANE;Mu=U.types.BOX;Lu=U.types.CYLINDER;Du=U.types.CONVEXPOLYHEDRON;Hu=U.types.HEIGHTFIELD;ju=U.types.TRIMESH;var ve=class{get[ku](){return this._intersectSphere}get[Iu](){return this._intersectPlane}get[Mu](){return this._intersectBox}get[Lu](){return this._intersectConvex}get[Du](){return this._intersectConvex}get[Hu](){return this._intersectHeightfield}get[ju](){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=ve.ANY,this.result=new hs,this.hasHit=!1,this.callback=i=>{}}intersectWorld(e,t){return this.mode=t.mode||ve.ANY,this.result=t.result||new hs,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(Eu),hc.length=0,e.broadphase.aabbQuery(e,Eu,hc),this.intersectBodies(hc),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=pg,r=fg;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(Pg(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 E=new _,b=new _,y=new _;o.vsub(i,E);let g=-d.dot(E)/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=mg;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=gg,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 E=d;E<h;E++){if(this.result.shouldStop)return;if(e.getAabbAtIndex(f,E,u),!!u.overlapsRay(o)){if(e.getConvexTrianglePillar(f,E,!1),te.pointToWorldFrame(i,t,e.pillarOffset,ca),this._intersectConvex(e.pillarConvex,t,ca,n,r,wu),this.result.shouldStop)return;e.getConvexTrianglePillar(f,E,!0),te.pointToWorldFrame(i,t,e.pillarOffset,ca),this._intersectConvex(e.pillarConvex,t,ca,n,r,wu)}}}_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=bg,E=vg;if(!(u<0))if(u===0)o.lerp(s,u,f),f.vsub(i,E),E.normalize(),this.reportIntersection(E,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,E),E.normalize(),this.reportIntersection(E,f,r,n,-1)),this.result.shouldStop)return;y>=0&&y<=1&&(o.lerp(s,y,f),f.vsub(i,E),E.normalize(),this.reportIntersection(E,f,r,n,-1))}}_intersectConvex(e,t,i,n,r,o){let s=yg,c=_u,d=o&&o.faceList||null,l=e.faces,h=e.vertices,u=e.faceNormals,f=this.direction,E=this.from,b=this.to,y=E.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],x=u[v],T=t,R=i;c.copy(h[w[0]]),T.vmult(c,c),c.vadd(R,c),c.vsub(E,c),T.vmult(x,s);let S=f.dot(s);if(Math.abs(S)<this.precision)continue;let O=s.dot(c)/S;if(!(O<0)){f.scale(O,at),at.vadd(E,at),Xt.copy(h[w[0]]),T.vmult(Xt,Xt),R.vadd(Xt,Xt);for(let P=1;!p.shouldStop&&P<w.length-1;P++){hi.copy(h[w[P]]),ui.copy(h[w[P+1]]),T.vmult(hi,hi),T.vmult(ui,ui),R.vadd(hi,hi),R.vadd(ui,ui);let L=at.distanceTo(E);!(ve.pointInTriangle(at,Xt,hi,ui)||ve.pointInTriangle(at,hi,Xt,ui))||L>y||this.reportIntersection(s,at,r,n,v)}}}}_intersectTrimesh(e,t,i,n,r,o){let s=Eg,c=Cg,d=Sg,l=_u,h=wg,u=_g,f=xg,E=Rg,b=Tg,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,x=c.length;!this.result.shouldStop&&w!==x;w++){let T=c[w];e.getNormal(T,s),e.getVertex(y[T*3],Xt),Xt.vsub(u,l);let R=h.dot(s),S=s.dot(l)/R;if(S<0)continue;h.scale(S,at),at.vadd(u,at),e.getVertex(y[T*3+1],hi),e.getVertex(y[T*3+2],ui);let O=at.distanceSquared(u);!(ve.pointInTriangle(at,hi,Xt,ui)||ve.pointInTriangle(at,Xt,hi,ui))||O>v||(te.vectorToWorldFrame(t,s,b),te.pointToWorldFrame(i,t,at,E),this.reportIntersection(b,E,r,n,T))}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 ve.ALL:this.hasHit=!0,d.set(o,s,e,t,i,n,c),d.hasHit=!0,this.callback(d);break;case ve.CLOSEST:(c<d.distance||!d.hasHit)&&(this.hasHit=!0,d.hasHit=!0,d.set(o,s,e,t,i,n,c));break;case ve.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,rr),i.vsub(t,as),e.vsub(t,uc);let r=rr.dot(rr),o=rr.dot(as),s=rr.dot(uc),c=as.dot(as),d=as.dot(uc),l,h;return(l=c*s-o*d)>=0&&(h=r*d-o*s)>=0&&l+h<r*c-o*o}};ve.CLOSEST=Rc.CLOSEST;ve.ANY=Rc.ANY;ve.ALL=Rc.ALL;var Eu=new Ze,hc=[],as=new _,uc=new _,pg=new _,fg=new le,at=new _,Xt=new _,hi=new _,ui=new _,wu={faceList:[0]},ca=new _,mg=new ve,gg=[],bg=new _,vg=new _,yg=new _,_u=new _,Eg=new _,wg=new _,_g=new _,xg=new _,Tg=new _,Rg=new _;new Ze;var Cg=[],Sg=new te,rr=new _,da=new _;function Pg(a,e,t){t.vsub(a,rr);let i=rr.dot(e);return e.scale(i,da),da.vadd(a,da),t.distanceTo(da)}var ga=class{static defaults(e={},t){for(let i in t)i in e||(e[i]=t[i]);return e}},us=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=ga.defaults(i,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=e,this.bodyB=t,this.id=us.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}};us.idCounter=0;var ba=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)}},ar=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=ar.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 ba,this.jacobianElementB=new ba,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,xu),s.scale(l,Tu),i.invInertiaWorldSolve.vmult(o,Ru),n.invInertiaWorldSolve.vmult(c,Cu),e.multiplyVectors(xu,Ru)+t.multiplyVectors(Tu,Cu)}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,ha),d+=ha.dot(e.rotational),c.vmult(t.rotational,ha),d+=ha.dot(t.rotational),d}addToWlambda(e){let t=this.jacobianElementA,i=this.jacobianElementB,n=this.bi,r=this.bj,o=Og;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}};ar.idCounter=0;var xu=new _,Tu=new _,Ru=new _,Cu=new _,ha=new _,Og=new _,gc=class extends ar{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=Ag,d=kg,l=n.velocity,h=n.angularVelocity;n.force,n.torque;let u=r.velocity,f=r.angularVelocity;r.force,r.torque;let E=Ig,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),E.copy(r.position),E.vadd(s,E),E.vsub(n.position,E),E.vsub(o,E);let p=g.dot(E),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=Mg,t=Lg,i=Dg,n=Hg,r=jg;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)}},Ag=new _,kg=new _,Ig=new _,Mg=new _,Lg=new _,Dg=new _,Hg=new _,jg=new _;var $_=new _,ex=new _;var tx=new _,ix=new _;var nx=new _,rx=new _,va=class extends ar{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=Bg,o=Fg,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}},Bg=new _,Fg=new _,Xr=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=ga.defaults(i,{friction:.3,restitution:.3,contactEquationStiffness:1e7,contactEquationRelaxation:3,frictionEquationStiffness:1e7,frictionEquationRelaxation:3}),this.id=Xr.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}};Xr.idCounter=0;var Qr=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=Qr.idCounter++,this.friction=typeof e.friction<"u"?e.friction:-1,this.restitution=typeof e.restitution<"u"?e.restitution:-1}};Qr.idCounter=0;var ya=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=Ng,s=zg,c=Vg,d=Ug,l=Kg,h=Gg,u=Wg,f=qg,E=Xg,b=Qg,y=Yg;this.getWorldAnchorA(h),this.getWorldAnchorB(u),h.vsub(n.position,f),u.vsub(r.position,E),u.vsub(h,o);let g=o.length();s.copy(o),s.normalize(),r.velocity.vsub(n.velocity,c),r.angularVelocity.cross(E,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),E.cross(d,y),n.torque.vsub(b,n.torque),r.torque.vadd(y,r.torque)}},Ng=new _,zg=new _,Vg=new _,Ug=new _,Gg=new _,Wg=new _,qg=new _,Xg=new _,Qg=new _,Yg=new _,Kg=new _;var ox=new _,sx=new _;var ax=new _,lx=new _,cx=new _;new ve;var dx=new _,hx=new _,ux=[new _(1,0,0),new _(0,1,0),new _(0,0,1)],px=new _;var fx=new _,mx=new _,gx=new _;var bx=new _,vx=new _,yx=new _,Ex=new _;var wx=new _,_x=new _,xx=new _;var Ea=class extends U{constructor(e){if(super({type:U.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 Tx=new _,Rx=new _;var Cx=new _,Sx=new _,Px=new _,Ox=new _,Ax=new _,kx=new _,Ix=new _;var Mx=new _;var Lx=new _,Dx=new _,Hx=new _,jx=new _,Bx=new _,Fx=new _,Nx=new _,zx=new _,Vx=new _;var Ux=new _,Gx=new Ze;var Wx=new _,qx=new Ze,Xx=new _,Qx=new _,Yx=new _,Kx=new _,Jx=new _,Zx=new _,$x=new _,e0=new Ze,t0=new _,i0=new te,n0=new Ze,bc=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}},vc=class extends bc{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,E,b,y;if(s!==0)for(let v=0;v!==d;v++)c[v].updateSolveMassProperties();let g=Zg,p=$g,m=Jg;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 x=0;x!==d;x++){let T=c[x],R=T.vlambda,S=T.wlambda;R.set(0,0,0),S.set(0,0,0)}for(i=0;i!==n;i++){E=0;for(let x=0;x!==s;x++){let T=o[x];h=p[x],u=g[x],y=m[x],b=T.computeGWlambda(),f=u*(h-b-T.eps*y),y+f<T.minForce?f=T.minForce-y:y+f>T.maxForce&&(f=T.maxForce-y),m[x]+=f,E+=f>0?f:-f,T.addToWlambda(f)}if(E*E<r)break}for(let x=0;x!==d;x++){let T=c[x],R=T.velocity,S=T.angularVelocity;T.vlambda.vmul(T.linearFactor,T.vlambda),R.vadd(T.vlambda,R),T.wlambda.vmul(T.angularFactor,T.wlambda),S.vadd(T.wlambda,S)}let v=o.length,w=1/l;for(;v--;)o[v].multiplier=m[v]*w}return i}},Jg=[],Zg=[],$g=[];var r0=V.STATIC;var yc=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}},Ec=class extends yc{constructor(...e){super(...e),this.type=_}constructObject(){return new _}},Bu,Fu,Nu,zu,Vu,Uu,Gu,Wu,qu,Xu,Qu,Yu,Ku,Ju,Zu,$u,ep,tp,ip,np,rp,op,sp,ap,lp,he={sphereSphere:U.types.SPHERE,spherePlane:U.types.SPHERE|U.types.PLANE,boxBox:U.types.BOX|U.types.BOX,sphereBox:U.types.SPHERE|U.types.BOX,planeBox:U.types.PLANE|U.types.BOX,convexConvex:U.types.CONVEXPOLYHEDRON,sphereConvex:U.types.SPHERE|U.types.CONVEXPOLYHEDRON,planeConvex:U.types.PLANE|U.types.CONVEXPOLYHEDRON,boxConvex:U.types.BOX|U.types.CONVEXPOLYHEDRON,sphereHeightfield:U.types.SPHERE|U.types.HEIGHTFIELD,boxHeightfield:U.types.BOX|U.types.HEIGHTFIELD,convexHeightfield:U.types.CONVEXPOLYHEDRON|U.types.HEIGHTFIELD,sphereParticle:U.types.PARTICLE|U.types.SPHERE,planeParticle:U.types.PLANE|U.types.PARTICLE,boxParticle:U.types.BOX|U.types.PARTICLE,convexParticle:U.types.PARTICLE|U.types.CONVEXPOLYHEDRON,cylinderCylinder:U.types.CYLINDER,sphereCylinder:U.types.SPHERE|U.types.CYLINDER,planeCylinder:U.types.PLANE|U.types.CYLINDER,boxCylinder:U.types.BOX|U.types.CYLINDER,convexCylinder:U.types.CONVEXPOLYHEDRON|U.types.CYLINDER,heightfieldCylinder:U.types.HEIGHTFIELD|U.types.CYLINDER,particleCylinder:U.types.PARTICLE|U.types.CYLINDER,sphereTrimesh:U.types.SPHERE|U.types.TRIMESH,planeTrimesh:U.types.PLANE|U.types.TRIMESH};Bu=he.sphereSphere;Fu=he.spherePlane;Nu=he.boxBox;zu=he.sphereBox;Vu=he.planeBox;Uu=he.convexConvex;Gu=he.sphereConvex;Wu=he.planeConvex;qu=he.boxConvex;Xu=he.sphereHeightfield;Qu=he.boxHeightfield;Yu=he.convexHeightfield;Ku=he.sphereParticle;Ju=he.planeParticle;Zu=he.boxParticle;$u=he.convexParticle;ep=he.cylinderCylinder;tp=he.sphereCylinder;ip=he.planeCylinder;np=he.boxCylinder;rp=he.convexCylinder;op=he.heightfieldCylinder;sp=he.particleCylinder;ap=he.sphereTrimesh;lp=he.planeTrimesh;var wc=class{get[Bu](){return this.sphereSphere}get[Fu](){return this.spherePlane}get[Nu](){return this.boxBox}get[zu](){return this.sphereBox}get[Vu](){return this.planeBox}get[Uu](){return this.convexConvex}get[Gu](){return this.sphereConvex}get[Wu](){return this.planeConvex}get[qu](){return this.boxConvex}get[Xu](){return this.sphereHeightfield}get[Qu](){return this.boxHeightfield}get[Yu](){return this.convexHeightfield}get[Ku](){return this.sphereParticle}get[Ju](){return this.planeParticle}get[Zu](){return this.boxParticle}get[$u](){return this.convexParticle}get[ep](){return this.convexConvex}get[tp](){return this.sphereConvex}get[ip](){return this.planeConvex}get[np](){return this.boxConvex}get[rp](){return this.convexConvex}get[op](){return this.heightfieldCylinder}get[sp](){return this.particleCylinder}get[ap](){return this.sphereTrimesh}get[lp](){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 Ec,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 gc(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 E=this.frictionEquationPool,b=E.length?E.pop():new va(i,n,u*f),y=E.length?E.pop():new va(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];nr.setZero(),Wr.setZero(),qr.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?(nr.vadd(t.ni,nr),Wr.vadd(t.ri,Wr),qr.vadd(t.rj,qr)):(nr.vsub(t.ni,nr),Wr.vadd(t.rj,Wr),qr.vadd(t.ri,qr));let o=1/e;Wr.scale(o,i.ri),qr.scale(o,i.rj),n.ri.copy(i.ri),n.rj.copy(i.rj),nr.normalize(),nr.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=ib,d=nb,l=eb,h=tb;for(let u=0,f=e.length;u!==f;u++){let E=e[u],b=t[u],y=null;E.material&&b.material&&(y=i.getContactMaterial(E.material,b.material)||null);let g=E.type&V.KINEMATIC&&b.type&V.STATIC||E.type&V.STATIC&&b.type&V.KINEMATIC||E.type&V.KINEMATIC&&b.type&V.KINEMATIC;for(let p=0;p<E.shapes.length;p++){E.quaternion.mult(E.shapeOrientations[p],c),E.quaternion.vmult(E.shapeOffsets[p],l),l.vadd(E.position,l);let m=E.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 x=null;m.material&&w.material&&(x=i.getContactMaterial(m.material,w.material)||null),this.currentContactMaterial=x||y||i.defaultContactMaterial;let T=m.type|w.type,R=this[T];if(R){let S=!1;m.type<w.type?S=R.call(this,m,w,l,h,c,d,E,b,m,w,g):S=R.call(this,w,m,h,l,d,c,b,E,m,w,g),S&&g&&(i.shapeOverlapKeeper.set(m.id,w.id),i.bodyOverlapKeeper.set(E.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,ua),u.ni.scale(u.ni.dot(ua),Su),ua.vsub(Su,u.rj),-ua.dot(u.ni)<=e.radius){if(h)return!0;let f=u.ri,E=u.rj;f.vadd(i,f),f.vsub(s.position,f),E.vadd(n,E),E.vsub(c.position,E),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=Ob;i.vsub(n,pa),t.getSideNormals(f,o);let E=e.radius,b=!1,y=kb,g=Ib,p=Mb,m=null,v=0,w=0,x=0,T=null;for(let N=0,W=f.length;N!==W&&b===!1;N++){let Z=Cb;Z.copy(f[N]);let G=Z.length();Z.normalize();let Ne=pa.dot(Z);if(Ne<G+E&&Ne>0){let me=Sb,X=Pb;me.copy(f[(N+1)%3]),X.copy(f[(N+2)%3]);let We=me.length(),hn=X.length();me.normalize(),X.normalize();let Jn=pa.dot(me),Mi=pa.dot(X);if(Jn<We&&Jn>-We&&Mi<hn&&Mi>-hn){let kt=Math.abs(Ne-G-E);if((T===null||kt<T)&&(T=kt,w=Jn,x=Mi,m=G,y.copy(Z),g.copy(me),p.copy(X),v++,h))return!0}}}if(v){b=!0;let N=this.createContactEquation(s,c,e,t,d,l);y.scale(-E,N.ri),N.ni.copy(y),N.ni.negate(N.ni),y.scale(m,y),g.scale(w,g),y.vadd(g,y),p.scale(x,p),y.vadd(p,N.rj),N.ri.vadd(i,N.ri),N.ri.vsub(s.position,N.ri),N.rj.vadd(n,N.rj),N.rj.vsub(c.position,N.rj),this.result.push(N),this.createFrictionEquationsFromContact(N,this.frictionResult)}let R=u.get(),S=Ab;for(let N=0;N!==2&&!b;N++)for(let W=0;W!==2&&!b;W++)for(let Z=0;Z!==2&&!b;Z++)if(R.set(0,0,0),N?R.vadd(f[0],R):R.vsub(f[0],R),W?R.vadd(f[1],R):R.vsub(f[1],R),Z?R.vadd(f[2],R):R.vsub(f[2],R),n.vadd(R,S),S.vsub(i,S),S.lengthSquared()<E*E){if(h)return!0;b=!0;let G=this.createContactEquation(s,c,e,t,d,l);G.ri.copy(S),G.ri.normalize(),G.ni.copy(G.ri),G.ri.scale(E,G.ri),G.rj.copy(R),G.ri.vadd(i,G.ri),G.ri.vsub(s.position,G.ri),G.rj.vadd(n,G.rj),G.rj.vsub(c.position,G.rj),this.result.push(G),this.createFrictionEquationsFromContact(G,this.frictionResult)}u.release(R),R=null;let O=u.get(),P=u.get(),L=u.get(),I=u.get(),B=u.get(),j=f.length;for(let N=0;N!==j&&!b;N++)for(let W=0;W!==j&&!b;W++)if(N%3!==W%3){f[W].cross(f[N],O),O.normalize(),f[N].vadd(f[W],P),L.copy(i),L.vsub(P,L),L.vsub(n,L);let Z=L.dot(O);O.scale(Z,I);let G=0;for(;G===N%3||G===W%3;)G++;B.copy(i),B.vsub(I,B),B.vsub(P,B),B.vsub(n,B);let Ne=Math.abs(Z),me=B.length();if(Ne<f[G].length()&&me<E){if(h)return!0;b=!0;let X=this.createContactEquation(s,c,e,t,d,l);P.vadd(I,X.rj),X.rj.copy(X.rj),B.negate(X.ni),X.ni.normalize(),X.ri.copy(X.rj),X.ri.vadd(n,X.ri),X.ri.vsub(i,X.ri),X.ri.normalize(),X.ri.scale(E,X.ri),X.ri.vadd(i,X.ri),X.ri.vsub(s.position,X.ri),X.rj.vadd(n,X.rj),X.rj.vsub(c.position,X.rj),this.result.push(X),this.createFrictionEquationsFromContact(X,this.frictionResult)}}u.release(O,P,L,I,B)}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 E=Qb;if(!(i.distanceTo(n)>e.boundingSphereRadius+t.boundingSphereRadius)&&e.findSeparatingAxis(t,i,r,n,o,E,u,f)){let b=[],y=Yb;e.clipAgainstHull(i,r,t,n,o,E,-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;E.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,Lb);let f=t.faceNormals,E=t.faces,b=t.vertices,y=e.radius,g=!1;for(let p=0;p!==b.length;p++){let m=b[p],v=Bb;o.vmult(m,v),n.vadd(v,v);let w=jb;if(v.vsub(i,w),w.lengthSquared()<y*y){if(h)return!0;g=!0;let x=this.createContactEquation(s,c,e,t,d,l);x.ri.copy(w),x.ri.normalize(),x.ni.copy(x.ri),x.ri.scale(y,x.ri),v.vsub(n,x.rj),x.ri.vadd(i,x.ri),x.ri.vsub(s.position,x.ri),x.rj.vadd(n,x.rj),x.rj.vsub(c.position,x.rj),this.result.push(x),this.createFrictionEquationsFromContact(x,this.frictionResult);return}}for(let p=0,m=E.length;p!==m&&g===!1;p++){let v=f[p],w=E[p],x=Fb;o.vmult(v,x);let T=Nb;o.vmult(b[w[0]],T),T.vadd(n,T);let R=zb;x.scale(-y,R),i.vadd(R,R);let S=Vb;R.vsub(T,S);let O=S.dot(x),P=Ub;if(i.vsub(T,P),O<0&&P.dot(x)>0){let L=[];for(let I=0,B=w.length;I!==B;I++){let j=u.get();o.vmult(b[w[I]],j),n.vadd(j,j),L.push(j)}if(Rb(L,x,i)){if(h)return!0;g=!0;let I=this.createContactEquation(s,c,e,t,d,l);x.scale(-y,I.ri),x.negate(I.ni);let B=u.get();x.scale(-O,B);let j=u.get();x.scale(-y,j),i.vsub(n,I.rj),I.rj.vadd(j,I.rj),I.rj.vadd(B,I.rj),I.rj.vadd(n,I.rj),I.rj.vsub(c.position,I.rj),I.ri.vadd(i,I.ri),I.ri.vsub(s.position,I.ri),u.release(B),u.release(j),this.result.push(I),this.createFrictionEquationsFromContact(I,this.frictionResult);for(let N=0,W=L.length;N!==W;N++)u.release(L[N]);return}else for(let I=0;I!==w.length;I++){let B=u.get(),j=u.get();o.vmult(b[w[(I+1)%w.length]],B),o.vmult(b[w[(I+2)%w.length]],j),n.vadd(B,B),n.vadd(j,j);let N=Db;j.vsub(B,N);let W=Hb;N.unit(W);let Z=u.get(),G=u.get();i.vsub(B,G);let Ne=G.dot(W);W.scale(Ne,Z),Z.vadd(B,Z);let me=u.get();if(Z.vsub(i,me),Ne>0&&Ne*Ne<N.lengthSquared()&&me.lengthSquared()<y*y){if(h)return!0;let X=this.createContactEquation(s,c,e,t,d,l);Z.vsub(n,X.rj),Z.vsub(i,X.ni),X.ni.normalize(),X.ni.scale(y,X.ri),X.rj.vadd(n,X.rj),X.rj.vsub(c.position,X.rj),X.ri.vadd(i,X.ri),X.ri.vsub(s.position,X.ri),this.result.push(X),this.createFrictionEquationsFromContact(X,this.frictionResult);for(let We=0,hn=L.length;We!==hn;We++)u.release(L[We]);u.release(B),u.release(j),u.release(Z),u.release(me),u.release(G);return}u.release(B),u.release(j),u.release(Z),u.release(me),u.release(G)}for(let I=0,B=L.length;I!==B;I++)u.release(L[I])}}}planeConvex(e,t,i,n,r,o,s,c,d,l,h){let u=Gb,f=Wb;f.set(0,0,1),r.vmult(f,f);let E=0,b=qb;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=Xb;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),E++,this.enableFrictionReduction||this.createFrictionEquationsFromContact(p,this.frictionResult)}this.enableFrictionReduction&&E&&this.createFrictionFromAverage(E)}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,E=t.elementSize,b=av,y=sv;te.pointToLocalFrame(n,o,i,y);let g=Math.floor((y.x-f)/E)-1,p=Math.ceil((y.x+f)/E)+1,m=Math.floor((y.y-f)/E)-1,v=Math.ceil((y.y+f)/E)+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 x=w[0],T=w[1];if(y.z-f>T||y.z+f<x)return;let R=this.result;for(let S=g;S<p;S++)for(let O=m;O<v;O++){let P=R.length,L=!1;if(t.getConvexTrianglePillar(S,O,!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(S,O,!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(R.length-P>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,E=e.boundingSphereRadius,b=rv,y=ov,g=nv;te.pointToLocalFrame(n,o,i,g);let p=Math.floor((g.x-E)/f)-1,m=Math.ceil((g.x+E)/f)+1,v=Math.floor((g.y-E)/f)-1,w=Math.ceil((g.y+E)/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 x=[];t.getRectMinMax(p,v,m,w,x);let T=x[0],R=x[1];if(!(g.z-E>R||g.z+E<T))for(let S=p;S<m;S++)for(let O=v;O<w;O++){let P=!1;if(t.getConvexTrianglePillar(S,O,!1),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(P=this.convexConvex(e,t.pillarConvex,i,b,r,o,s,c,null,null,h,y,null)),h&&P||(t.getConvexTrianglePillar(S,O,!0),te.pointToWorldFrame(n,o,t.pillarOffset,b),i.distanceTo(b)<t.pillarConvex.boundingSphereRadius+e.boundingSphereRadius&&(P=this.convexConvex(e,t.pillarConvex,i,b,r,o,s,c,null,null,h,y,null)),h&&P))return!0}}sphereParticle(e,t,i,n,r,o,s,c,d,l,h){let u=$b;if(u.set(0,0,1),n.vsub(i,u),u.lengthSquared()<=e.radius*e.radius){if(h)return!0;let E=this.createContactEquation(c,s,t,e,d,l);u.normalize(),E.rj.copy(u),E.rj.scale(e.radius,E.rj),E.ni.copy(u),E.ni.negate(E.ni),E.ri.set(0,0,0),this.result.push(E),this.createFrictionEquationsFromContact(E,this.frictionResult)}}planeParticle(e,t,i,n,r,o,s,c,d,l,h){let u=Kb;u.set(0,0,1),s.quaternion.vmult(u,u);let f=Jb;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=Zb;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=tv,E=iv,b=null,y=ev;if(y.copy(n),y.vsub(i,y),r.conjugate(Pu),Pu.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],Ou);let w=-v.dot(Ou);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,E),E.vadd(n,E),E.vsub(i,E),g.rj.copy(E),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=hb,f=ub,E=pb,b=fb,y=mb,g=gb,p=Eb,m=db,v=lb,w=wb;te.pointToLocalFrame(n,o,i,y);let x=e.radius;p.lowerBound.set(y.x-x,y.y-x,y.z-x),p.upperBound.set(y.x+x,y.y+x,y.z+x),t.getTrianglesInAABB(p,w);let T=cb,R=e.radius*e.radius;for(let I=0;I<w.length;I++)for(let B=0;B<3;B++)if(t.getVertex(t.indices[w[I]*3+B],T),T.vsub(y,v),v.lengthSquared()<=R){if(m.copy(T),te.pointToWorldFrame(n,o,m,T),T.vsub(i,v),h)return!0;let j=this.createContactEquation(s,c,e,t,d,l);j.ni.copy(v),j.ni.normalize(),j.ri.copy(j.ni),j.ri.scale(e.radius,j.ri),j.ri.vadd(i,j.ri),j.ri.vsub(s.position,j.ri),j.rj.copy(T),j.rj.vsub(c.position,j.rj),this.result.push(j),this.createFrictionEquationsFromContact(j,this.frictionResult)}for(let I=0;I<w.length;I++)for(let B=0;B<3;B++){t.getVertex(t.indices[w[I]*3+B],u),t.getVertex(t.indices[w[I]*3+(B+1)%3],f),f.vsub(u,E),y.vsub(f,g);let j=g.dot(E);y.vsub(u,g);let N=g.dot(E);if(N>0&&j<0&&(y.vsub(u,g),b.copy(E),b.normalize(),N=g.dot(b),b.scale(N,g),g.vadd(u,g),g.distanceTo(y)<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)}}let S=bb,O=vb,P=yb,L=ab;for(let I=0,B=w.length;I!==B;I++){t.getTriangleVertices(w[I],S,O,P),t.getNormal(w[I],L),y.vsub(S,g);let j=g.dot(L);if(L.scale(j,g),y.vsub(g,g),j=g.distanceTo(y),ve.pointInTriangle(g,S,O,P)&&j<e.radius){if(h)return!0;let N=this.createContactEquation(s,c,e,t,d,l);g.vsub(y,N.ni),N.ni.normalize(),N.ni.scale(e.radius,N.ri),N.ri.vadd(i,N.ri),N.ri.vsub(s.position,N.ri),te.pointToWorldFrame(n,o,g,g),g.vsub(c.position,N.rj),te.vectorToWorldFrame(o,N.ni,N.ni),te.vectorToWorldFrame(o,N.ri,N.ri),this.result.push(N),this.createFrictionEquationsFromContact(N,this.frictionResult)}}w.length=0}planeTrimesh(e,t,i,n,r,o,s,c,d,l,h){let u=new _,f=rb;f.set(0,0,1),r.vmult(f,f);for(let E=0;E<t.vertices.length/3;E++){t.getVertex(E,u);let b=new _;b.copy(u),te.pointToWorldFrame(n,o,b,u);let y=ob;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=sb;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)}}}},nr=new _,Wr=new _,qr=new _,eb=new _,tb=new _,ib=new le,nb=new le,rb=new _,ob=new _,sb=new _,ab=new _,lb=new _,cb=new _,db=new _,hb=new _,ub=new _,pb=new _,fb=new _,mb=new _,gb=new _,bb=new _,vb=new _,yb=new _,Eb=new Ze,wb=[],ua=new _,Su=new _,_b=new _,xb=new _,Tb=new _;function Rb(a,e,t){let i=null,n=a.length;for(let r=0;r!==n;r++){let o=a[r],s=_b;a[(r+1)%n].vsub(o,s);let c=xb;s.cross(e,c);let d=Tb;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 pa=new _,Cb=new _,Sb=new _,Pb=new _,Ob=[new _,new _,new _,new _,new _,new _],Ab=new _,kb=new _,Ib=new _,Mb=new _,Lb=new _,Db=new _,Hb=new _,jb=new _,Bb=new _,Fb=new _,Nb=new _,zb=new _,Vb=new _,Ub=new _,Gb=new _,Wb=new _,qb=new _,Xb=new _,Qb=new _,Yb=new _,Kb=new _,Jb=new _,Zb=new _,$b=new _,Pu=new le,ev=new _,tv=new _,Ou=new _,iv=new _,nv=new _,rv=new _,ov=[0],sv=new _,av=new _,wa=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||Au(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||Au(t,l)}}};function Au(a,e){a.push((e&4294901760)>>16,e&65535)}var _c=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]}}},_a=class extends ma{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 mc,this.bodies=[],this.hasActiveBodies=!1,this.solver=e.solver!==void 0?e.solver:new vc,this.constraints=[],this.narrowphase=new wc(this),this.collisionMatrix=new fa,this.collisionMatrixPrevious=new fa,this.bodyOverlapKeeper=new wa,this.shapeOverlapKeeper=new wa,this.materials=[],this.contactmaterials=[],this.contactMaterialTable=new _c,this.defaultMaterial=new Qr("default"),this.defaultContactMaterial=new Xr(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 hs?this.raycastClosest(e,t,{skipBackfaces:!0},i):this.raycastAll(e,t,{skipBackfaces:!0},i)}raycastAll(e,t,i={},n){return i.mode=ve.ALL,i.from=e,i.to=t,i.callback=n,pc.intersectWorld(this,i)}raycastAny(e,t,i={},n){return i.mode=ve.ANY,i.from=e,i.to=t,i.result=n,pc.intersectWorld(this,i)}raycastClosest(e,t,i={},n){return i.mode=ve.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 V&&(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=He.now(),r=0;for(;this.accumulator>=e&&r<i&&(this.internalStep(e),this.accumulator-=e,r++,!(He.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=uv,n=pv,r=this.numObjects(),o=this.bodies,s=this.solver,c=this.gravity,d=this.doProfiling,l=this.profile,h=V.DYNAMIC,u=-1/0,f=this.constraints,E=hv;c.length();let b=c.x,y=c.y,g=c.z,p=0;for(d&&(u=He.now()),p=0;p!==r;p++){let I=o[p];if(I.type===h){let B=I.force,j=I.mass;B.x+=j*b,B.y+=j*y,B.z+=j*g}}for(let I=0,B=this.subsystems.length;I!==B;I++)this.subsystems[I].update();d&&(u=He.now()),i.length=0,n.length=0,this.broadphase.collisionPairs(this,i,n),d&&(l.broadphase=He.now()-u);let m=f.length;for(p=0;p!==m;p++){let I=f[p];if(!I.collideConnected)for(let B=i.length-1;B>=0;B-=1)(I.bodyA===i[B]&&I.bodyB===n[B]||I.bodyB===i[B]&&I.bodyA===n[B])&&(i.splice(B,1),n.splice(B,1))}this.collisionMatrixTick(),d&&(u=He.now());let v=dv,w=t.length;for(p=0;p!==w;p++)v.push(t[p]);t.length=0;let x=this.frictionEquations.length;for(p=0;p!==x;p++)E.push(this.frictionEquations[p]);for(this.frictionEquations.length=0,this.narrowphase.getContacts(i,n,this,t,v,this.frictionEquations,E),d&&(l.narrowphase=He.now()-u),d&&(u=He.now()),p=0;p<this.frictionEquations.length;p++)s.addEquation(this.frictionEquations[p]);let T=t.length;for(let I=0;I!==T;I++){let B=t[I],j=B.bi,N=B.bj,W=B.si,Z=B.sj,G;if(j.material&&N.material?G=this.getContactMaterial(j.material,N.material)||this.defaultContactMaterial:G=this.defaultContactMaterial,G.friction,j.material&&N.material&&(j.material.friction>=0&&N.material.friction>=0&&j.material.friction*N.material.friction,j.material.restitution>=0&&N.material.restitution>=0&&(B.restitution=j.material.restitution*N.material.restitution)),s.addEquation(B),j.allowSleep&&j.type===V.DYNAMIC&&j.sleepState===V.SLEEPING&&N.sleepState===V.AWAKE&&N.type!==V.STATIC){let Ne=N.velocity.lengthSquared()+N.angularVelocity.lengthSquared(),me=N.sleepSpeedLimit**2;Ne>=me*2&&(j.wakeUpAfterNarrowphase=!0)}if(N.allowSleep&&N.type===V.DYNAMIC&&N.sleepState===V.SLEEPING&&j.sleepState===V.AWAKE&&j.type!==V.STATIC){let Ne=j.velocity.lengthSquared()+j.angularVelocity.lengthSquared(),me=j.sleepSpeedLimit**2;Ne>=me*2&&(N.wakeUpAfterNarrowphase=!0)}this.collisionMatrix.set(j,N,!0),this.collisionMatrixPrevious.get(j,N)||(ls.body=N,ls.contact=B,j.dispatchEvent(ls),ls.body=j,N.dispatchEvent(ls)),this.bodyOverlapKeeper.set(j.id,N.id),this.shapeOverlapKeeper.set(W.id,Z.id)}for(this.emitContactEvents(),d&&(l.makeContactConstraints=He.now()-u,u=He.now()),p=0;p!==r;p++){let I=o[p];I.wakeUpAfterNarrowphase&&(I.wakeUp(),I.wakeUpAfterNarrowphase=!1)}for(m=f.length,p=0;p!==m;p++){let I=f[p];I.update();for(let B=0,j=I.equations.length;B!==j;B++){let N=I.equations[B];s.addEquation(N)}}s.solve(e,this),d&&(l.solve=He.now()-u),s.removeAllEquations();let R=Math.pow;for(p=0;p!==r;p++){let I=o[p];if(I.type&h){let B=R(1-I.linearDamping,e),j=I.velocity;j.scale(B,j);let N=I.angularVelocity;if(N){let W=R(1-I.angularDamping,e);N.scale(W,N)}}}for(this.dispatchEvent(cv),p=0;p!==r;p++){let I=o[p];I.preStep&&I.preStep.call(I)}d&&(u=He.now());let O=this.stepnumber%(this.quatNormalizeSkip+1)===0,P=this.quatNormalizeFast;for(p=0;p!==r;p++)o[p].integrate(e,O,P);for(this.clearForces(),this.broadphase.dirty=!0,d&&(l.integrate=He.now()-u),this.stepnumber+=1,this.dispatchEvent(lv),p=0;p!==r;p++){let I=o[p],B=I.postStep;B&&B.call(I)}let L=!0;if(this.allowSleep)for(L=!1,p=0;p!==r;p++){let I=o[p];I.sleepTick(this.time),I.sleepState!==V.SLEEPING&&(L=!0)}this.hasActiveBodies=L}emitContactEvents(){let e=this.hasAnyEventListener("beginContact"),t=this.hasAnyEventListener("endContact");if((e||t)&&this.bodyOverlapKeeper.getDiff(ji,Bi),e){for(let r=0,o=ji.length;r<o;r+=2)cs.bodyA=this.getBodyById(ji[r]),cs.bodyB=this.getBodyById(ji[r+1]),this.dispatchEvent(cs);cs.bodyA=cs.bodyB=null}if(t){for(let r=0,o=Bi.length;r<o;r+=2)ds.bodyA=this.getBodyById(Bi[r]),ds.bodyB=this.getBodyById(Bi[r+1]),this.dispatchEvent(ds);ds.bodyA=ds.bodyB=null}ji.length=Bi.length=0;let i=this.hasAnyEventListener("beginShapeContact"),n=this.hasAnyEventListener("endShapeContact");if((i||n)&&this.shapeOverlapKeeper.getDiff(ji,Bi),i){for(let r=0,o=ji.length;r<o;r+=2){let s=this.getShapeById(ji[r]),c=this.getShapeById(ji[r+1]);Fi.shapeA=s,Fi.shapeB=c,s&&(Fi.bodyA=s.body),c&&(Fi.bodyB=c.body),this.dispatchEvent(Fi)}Fi.bodyA=Fi.bodyB=Fi.shapeA=Fi.shapeB=null}if(n){for(let r=0,o=Bi.length;r<o;r+=2){let s=this.getShapeById(Bi[r]),c=this.getShapeById(Bi[r+1]);Ni.shapeA=s,Ni.shapeB=c,s&&(Ni.bodyA=s.body),c&&(Ni.bodyB=c.body),this.dispatchEvent(Ni)}Ni.bodyA=Ni.bodyB=Ni.shapeA=Ni.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 ve,He=globalThis.performance||{};if(!He.now){let a=Date.now();He.timing&&He.timing.navigationStart&&(a=He.timing.navigationStart),He.now=()=>Date.now()-a}var lv={type:"postStep"},cv={type:"preStep"},ls={type:V.COLLIDE_EVENT_NAME,body:null,contact:null},dv=[],hv=[],uv=[],pv=[],ji=[],Bi=[],cs={type:"beginContact",bodyA:null,bodyB:null},ds={type:"endContact",bodyA:null,bodyB:null},Fi={type:"beginShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null},Ni={type:"endShapeContact",bodyA:null,bodyB:null,shapeA:null,shapeB:null};import*as Ee from"three";import{MeshBasicMaterial as fv,SphereGeometry as cp,BoxGeometry as dp,PlaneGeometry as hp,Mesh as wn,CylinderGeometry as mv,BufferGeometry as Sc,Float32BufferAttribute as Pc}from"three";function gv(a,e,{color:t=65280,scale:i=1,onInit:n,onUpdate:r,autoUpdate:o}={}){let s=[],c=new fv({color:t??65280,wireframe:!0}),d=new _,l=new _,h=new _,u=new le,f=new cp(1),E=new dp(1,1,1),b=new hp(10,10,10,10);function y(R){let S=new Sc,O=[];for(let L=0;L<R.vertices.length;L++){let I=R.vertices[L];O.push(I.x,I.y,I.z)}S.setAttribute("position",new Pc(O,3));let P=[];for(let L=0;L<R.faces.length;L++){let I=R.faces[L],B=I[0];for(let j=1;j<I.length-1;j++){let N=I[j],W=I[j+1];P.push(B,N,W)}}return S.setIndex(P),S.computeBoundingSphere(),S.computeVertexNormals(),S}function g(R){let S=new Sc,O=[],P=d,L=l,I=h;for(let B=0;B<R.indices.length/3;B++)R.getTriangleVertices(B,P,L,I),O.push(P.x,P.y,P.z),O.push(L.x,L.y,L.z),O.push(I.x,I.y,I.z);return S.setAttribute("position",new Pc(O,3)),S.computeBoundingSphere(),S.computeVertexNormals(),S}function p(R){let S=new Sc,O=R.elementSize||1,P=R.data.flatMap((I,B)=>I.flatMap((j,N)=>[B*O,N*O,j])),L=[];for(let I=0;I<R.data.length-1;I++)for(let B=0;B<R.data[I].length-1;B++){let j=R.data[I].length,N=I*j+B;L.push(N+1,N+j,N+j+1),L.push(N+j,N+1,N)}return S.setIndex(L),S.setAttribute("position",new Pc(P,3)),S.computeBoundingSphere(),S.computeVertexNormals(),S}function m(R){let S=new wn,{SPHERE:O,BOX:P,PLANE:L,CYLINDER:I,CONVEXPOLYHEDRON:B,TRIMESH:j,HEIGHTFIELD:N}=U.types;switch(R.type){case O:{S=new wn(f,c);break}case P:{S=new wn(E,c);break}case L:{S=new wn(b,c);break}case I:{let W=new mv(R.radiusTop,R.radiusBottom,R.height,R.numSegments);S=new wn(W,c),R.geometryId=W.id;break}case B:{let W=y(R);S=new wn(W,c),R.geometryId=W.id;break}case j:{let W=g(R);S=new wn(W,c),R.geometryId=W.id;break}case N:{let W=p(R);S=new wn(W,c),R.geometryId=W.id;break}}return a.add(S),S}function v(R,S){let{SPHERE:O,BOX:P,PLANE:L,CYLINDER:I,CONVEXPOLYHEDRON:B,TRIMESH:j,HEIGHTFIELD:N}=U.types;switch(S.type){case O:{let{radius:W}=S;R.scale.set(W*i,W*i,W*i);break}case P:{R.scale.copy(S.halfExtents),R.scale.multiplyScalar(2*i);break}case L:break;case I:{R.scale.set(1*i,1*i,1*i);break}case B:{R.scale.set(1*i,1*i,1*i);break}case j:{R.scale.copy(S.scale).multiplyScalar(i);break}case N:{R.scale.set(1*i,1*i,1*i);break}}}function w(R,S){if(!R)return!1;let{geometry:O}=R;return O instanceof cp&&S.type===U.types.SPHERE||O instanceof dp&&S.type===U.types.BOX||O instanceof hp&&S.type===U.types.PLANE||O.id===S.geometryId&&S.type===U.types.CYLINDER||O.id===S.geometryId&&S.type===U.types.CONVEXPOLYHEDRON||O.id===S.geometryId&&S.type===U.types.TRIMESH||O.id===S.geometryId&&S.type===U.types.HEIGHTFIELD}function x(R,S){let O=s[R],P=!1;return w(O,S)||(O&&a.remove(O),s[R]=O=m(S),P=!0),v(O,S),P}function T(){let R=s,S=d,O=u,P=0;for(let L of e)for(let I=0;I!==L.shapes.length;I++){let B=L.shapes[I],j=x(P,B),N=R[P];N&&(L.quaternion.vmult(L.shapeOffsets[I],S),L.position.vadd(S,S),L.quaternion.mult(L.shapeOrientations[I],O),N.position.copy(S),N.quaternion.copy(O),j&&n instanceof Function&&n(L,N,B),!j&&r instanceof Function&&r(L,N,B)),P++}for(let L=P;L<R.length;L++){let I=R[L];I&&a.remove(I)}R.length=P,o!==!1&&requestAnimationFrame(T)}return o!==!1&&requestAnimationFrame(T),{update:T}}var up=gv;import*as pi from"three";import*as ps from"three";var zi=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new ps.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new ps.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 ps.ShaderMaterial({vertexShader:`
94
94
  attribute vec2 uv2;
95
95
  varying vec2 vUv2;
96
96
  void main()
@@ -122,9 +122,9 @@ a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
122
122
  // gl_FragColor = vec4(vUv2.xy, 0, 1);
123
123
  gl_FragColor = lightMapTexel;
124
124
  }
125
- `,defines:{USE_LIGHTMAP:""}})}};var A=function(a){if(a===void 0&&(a=null),!Array.isArray(a))a=lp(a);else for(let e=0;e<a.length;e++){let t=a[e];a[e]=lp(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=a}};function lp(a){switch(a?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return a}import{Vector4 as kv}from"three";import{NeverStencilFunc as dv,LessStencilFunc as hv,EqualStencilFunc as uv,LessEqualStencilFunc as pv,GreaterStencilFunc as fv,NotEqualStencilFunc as mv,GreaterEqualStencilFunc as gv,AlwaysStencilFunc as bv,ZeroStencilOp as vv,KeepStencilOp as yv,ReplaceStencilOp as Ev,IncrementStencilOp as wv,DecrementStencilOp as _v,IncrementWrapStencilOp as xv,DecrementWrapStencilOp as Tv,InvertStencilOp as Rv}from"three";var Cc=H("debugstencil");function Cv(a,e){return(a&1<<e.layer)!=0}var ar=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(Cc&&console.log(t,ar.stencils),!t)return;let i=ar.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(Cv(r.layer,e)){Cc&&console.log(r);let o=e.material?.clone();o&&(e.material=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[Pv];if(i){Cc&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let o={...r};o.compareFunc=Sv(o.compareFunc),o.passOp=Sc(o.passOp),o.failOp=Sc(o.failOp),o.zFailOp=Sc(o.zFailOp),ar.stencils[this.source]||(ar.stencils[this.source]=[]),ar.stencils[this.source].push(o)}}}return null}},lr=ar;z(lr,"stencils",{});function Sc(a){switch(a){case 0:return yv;case 1:return vv;case 2:return Ev;case 3:return wv;case 4:return _v;case 6:return xv;case 7:return Tv;case 5:return Rv}return 0}function Sv(a){switch(a){case 1:return dv;case 2:return hv;case 3:return uv;case 4:return pv;case 5:return fv;case 6:return mv;case 7:return gv;case 8:return bv}return 0}var Pv="NEEDLE_render_objects";import{TextureLoader as Ov}from"three";import{GLTFLoader as Av}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as Pc}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as cp}from"three/examples/jsm/loaders/KTX2Loader.js";var ps=H("debugdecoders"),Xt,En;function Oc(a){a!==void 0&&typeof a=="string"&&(Xt||(Xt=new Pc),ps&&console.log("Setting draco decoder path to",a),Xt.setDecoderPath(a))}function Ac(a){a!==void 0&&typeof a=="string"&&(Xt||(Xt=new Pc),ps&&console.log("Setting draco decoder type to",a),Xt.setDecoderConfig({type:a}))}function kc(a){a!==void 0&&typeof a=="string"&&(En||(En=new cp),ps&&console.log("Setting ktx2 transcoder path to",a),En.setTranscoderPath(a))}function cr(a,e){Xt||(Xt=new Pc,Xt.setDecoderPath("./include/draco/"),Xt.setDecoderConfig({type:"js"}),ps&&console.log("Setting draco decoder path to","./include/draco/")),En||(En=new cp,En.setTranscoderPath("./include/ktx2/"),ps&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&En.detectSupport(e.renderer)),a.setDRACOLoader(Xt),a.setKTX2Loader(En)}var Ic="NEEDLE_deferred_texture",It=H("debugdeferredtextures"),fs=class{static assignTextureLOD(e,t,i,n=0){if(!!i)for(let r of Object.keys(i)){let o=i[r];o?.isTexture===!0&&(It&&console.log(`-----------
126
- `,"FIND",i.name,r,o?.name,o?.userData,o),fs.getOrLoadTexture(e,t,i,r,o,n).then(s=>{s?.isTexture===!0&&(s.needsUpdate=!0,It&&console.log("Assign LOD",i.name,r,s.name,s.guid,i,"Prev:",o,"Now:",s,`
127
- --------------`),i[r]=s,i.needsUpdate=!0)}))}}get name(){return Ic}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return It&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[Ic];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(o=>{It&&console.log("register texture",o.name,o.uuid,n),o.userData.deferred=n,fs.cache.set(o.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r,o){let s=r.uuid,c=fs.cache.get(s);if(c){It&&console.log(s,c.uri,c.guid);let d=pn(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 It&&console.log("Texture has already been loaded: "+l,i.name,n,r.name),this.resolved[l];let h=new Av;cr(h,e),It&&console.log("Load "+d,i.name,n,c.guid);let u=await h.loadAsync(d),f=u.parser;It&&console.log("Loading finished "+d,i.name,n,c.guid);let E=-1,b=!1;for(let g of u.parser.json.textures)if(E++,g?.extensions){let p=g?.extensions[Ic];if(p?.guid&&p.guid===c.guid){b=!0;break}}if(!b)return null;let y=await f.getDependency("texture",E);return y&&(y.guid=c.guid),this.resolved[l]=y,It&&console.log(i.name,n,'change "'+r.name+'" \u2192 "'+y.name+'"',d,E,y,i,l),y}else{It&&console.log("Load texture from uri: "+d);let h=await new Ov().loadAsync(d);return h&&It?console.log(c,h):console.warn("failed loading",d),h}}else It&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},zi=fs;z(zi,"cache",new Map),z(zi,"resolved",{});var hp=H("noInstancing"),up=!!H("debuglightmaps"),Iv=H("debuginstancing"),Mv=H("debugprogressiveload"),Lv=H("noprogressiveload"),Qr=class{path=null;asset=null;default};var Mc=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=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}},Bc=class extends M{receiveShadows=!1;shadowCastingMode=Lc.Off;lightmapIndex=-1;lightmapScaleOffset=new ui.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;_lightmaps;get material(){return this.gameObject.material}set material(e){this.gameObject.material=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new Mc(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return hp}_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();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"||C.getComponent(n,Bc))){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 Ni(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,up)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new Ni(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,up),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=Dv.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return C.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return C.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&&!hp&&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())}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){lr.applyStencil(this)}onBeforeRenderThree(e,t,i,n,r,o){if(!Lv&&r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,Mv?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{zi.assignTextureLOD(this.context,this.sourceId,r)},2e3)):zi.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)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[Dc]===!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[Dc],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&&C.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()}}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]}}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==Lc.On?e.castShadow=!0:e.castShadow=!1}},Ee=Bc;k([A()],Ee.prototype,"receiveShadows",2),k([A()],Ee.prototype,"shadowCastingMode",2),k([A()],Ee.prototype,"lightmapIndex",2),k([A(kv)],Ee.prototype,"lightmapScaleOffset",2),k([A()],Ee.prototype,"enableInstancing",2),k([A()],Ee.prototype,"renderOrder",2),k([A()],Ee.prototype,"allowOcclusionWhenDynamic",2);var dr=class extends Ee{},Yr=class extends dr{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},Lc=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(Lc||{}),Dc="NEEDLE_NEED_UPDATE_INSTANCE",ne=class{static markDirty(e,t=!0){if(!!e&&(C.isUsingInstancing(e)&&(e[Dc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)ne.markDirty(i,!0)}},Hc=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 ya(e.name,o,s,200,t);return this.objs.push(c),c.addInstance(r)}return null}},Dv=new Hc,jc=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,C.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)}},Fc=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,Iv&&(i=new ui.MeshBasicMaterial({color:this.randomColor()})),this.inst=new ui.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 ui.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 jc(-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,Fc.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}},ya=Fc;z(ya,"nullMatrix",new ui.Matrix4);import{Vector3 as Hv}from"three";import*as hr from"three";import{Vector3 as pp}from"three";var wn=class extends M{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?V.KINEMATIC:V.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 hr.Matrix4}awake(){this._body=null,this.currentVelocity=new hr.Vector3,this._smoothedVelocity=new hr.Vector3,this.lastWorldPosition=q(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 un(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 Ea;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?wn.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):wn.tempPosition.set(0,0,0)}setVelocity(e,t,i){if(!!this.body){if(e instanceof pp){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?wn.tempPosition.set(this.body?.torque.x,this.body?.torque.y,this.body?.torque.z):wn.tempPosition.set(0,0,0)}setTorque(e,t,i){if(!!this.body){if(e instanceof pp){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){wn.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(wn.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=q(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},de=wn;z(de,"tempPosition",new hr.Vector3),z(de,"copyVector3",new hr.Vector3),k([A()],de.prototype,"mass",2),k([A()],de.prototype,"isKinematic",1),k([A()],de.prototype,"drag",2),k([A()],de.prototype,"angularDrag",2),k([A()],de.prototype,"detectCollisions",2),k([A()],de.prototype,"sleepThreshold",2);import{Vector3 as wa}from"three";var ft=class extends M{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(de))}onDisable(){this._shape}};k([A(de)],ft.prototype,"attachedRigidbody",2),k([A()],ft.prototype,"isTrigger",2);var _n=class extends ft{radius=.5;center=new wa(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};k([A()],_n.prototype,"radius",2),k([A(wa)],_n.prototype,"center",2);var xn=class extends ft{size;center;onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};k([A(wa)],xn.prototype,"size",2),k([A(wa)],xn.prototype,"center",2);var ms=H("debugphysics"),jv=H("debugcollisions"),Ea=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},_a=Symbol("object"),gs=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[_a]=e)}},Ce=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 we.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new we.Layers);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};z(Ce,"AllLayers",4294967295);var Nc=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},xa=class{raycaster=new we.Raycaster;defaultRaycastOptions=new Ce;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new we.Layers;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let i=new we.Sphere(e,t),n=this.sphereMask;n.enableAll(),n.disable(2);for(let r of this.context.scene.children){let o=this.onSphereOverlap(r,i,n);o&&this.sphereResults.push(o)}return this.sphereResults.sort((r,o)=>r.distance-o.distance)}tempBoundingBox=new we.Box3;onSphereOverlap(e,t,i){if(e.type==="Mesh"){if(!e.layers.test(i))return null;let n=e,r=n.geometry;if(r.boundingBox||r.computeBoundingBox(),!r.boundingBox)return null;n.matrixWorldNeedsUpdate&&n.updateMatrixWorld();let o=this.tempBoundingBox.copy(r.boundingBox).applyMatrix4(n.matrixWorld);if(t.intersectsBox(o)){let c=q(e).distanceTo(t.center);return new Nc(e,c,t.center.clone())}}else if(e.children)for(let n of e.children){let r=this.onSphereOverlap(n,t,i);if(r)return r}return null}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 we.Layers?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 va;objects=[];tempPosition=new we.Vector3;tempQuaternion=new we.Quaternion;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),ms){let t={};t.onInit=(i,n,r)=>{n.layers.set(-1)},ap(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=V.KINEMATIC:i.type=V.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 gs(e,i);return n._hasRigidbody=!0,this.objects.push(n),ms&&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 gs(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 ga(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 gs(e,c);this.objects.push(d)}return s}addMeshCollider(e){ms&&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 we.Matrix4;tempMat2=new we.Matrix4;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=V.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=q(e);let l=r.position;o.x-=l.x,o.y-=l.y,o.z-=l.z,s=ke(e);let h=new we.Quaternion(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,ms&&this.context.time.frameCount%60}temp=new we.Vector3;tempQuat=new we.Quaternion;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;i.sleepTick(this.context.time.time),ms&&(!t._didSleepLastStep&&i.sleepState===V.SLEEPING?console.log("BODY SLEEPING",i):t._didSleepLastStep&&i.sleepState!==V.SLEEPING&&console.log("BODY WOKE UP",i)),t._didSleepLastStep=i.sleepState===V.SLEEPING;let n=t.obj;if(i.type===V.KINEMATIC){let r=q(n,this.temp);i.position.set(r.x,r.y,r.z);let o=ke(n,this.tempQuat);i.quaternion.set(o.x,o.y,o.z,o.w);continue}if(t.parent&&n.parent===t.parent){Qh(n,i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w);let r=i.position;Nr(n,r.x,r.y,r.z),i.velocity.length()>i.sleepSpeedLimit&&ne.markDirty(n)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let i=new V;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=V.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){}raiseCollisionEvents(e,t){let i=new bs(e,t);if(jv&&console.log("collision between",t.contact.bi,t.contact.bj,e,t),C.foreachComponent(e,n=>{n.__internalHandleCollision(i,!1)}),i.collider&&!i.collider.attachedRigidbody&&i.collider.isTrigger){let n=new bs(i.gameObject,t,!0);C.foreachComponent(i.gameObject,r=>{r.__internalHandleCollision(n,!0)})}}onEndContact(e){let t=e.bodyA[_a],i=e.bodyB[_a];C.foreachComponent(i,r=>{r.__internalHandleExitCollisionEvent(t,!1)});let n=C.getComponent(t,ft);n&&!n.attachedRigidbody&&n.isTrigger&&C.foreachComponent(n.gameObject,r=>{r.__internalHandleExitCollisionEvent(i,!0)})}},bs=class{invert;collision;targetBody;me;_normal;get normal(){if(!this._normal){let e=this.collision.contact.ni;this._normal=new Hv(e.x,e.y,e.z)}return this._normal}_collider;get collider(){return this._collider===void 0&&(this._collider=C.getComponentInChildren(this.gameObject,ft)),this._collider}get gameObject(){return this.targetBody[_a]}constructor(e,t,i=!1){this.invert=i,this.me=e,this.collision=t,this.targetBody=this.invert?t.target:t.body}};import{Clock as Bv}from"three";var Ta=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 Bv;_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 Nv}from"websocket-ts";function fp(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}var mt=class extends M{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?mt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=H(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=mt.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return fp(e)}};var pi=new Int32Array(2),Ra=new Float32Array(pi.buffer),Ca=new Float64Array(pi.buffer),Kr=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 vs;(function(a){a[a.UTF8_BYTES=1]="UTF8_BYTES",a[a.UTF16_STRING=2]="UTF16_STRING"})(vs||(vs={}));var fi=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new fi(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 pi[0]=this.readInt32(e),Ra[0]}readFloat64(e){return pi[Kr?0:1]=this.readInt32(e),pi[Kr?1:0]=this.readInt32(e+4),Ca[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){Ra[0]=t,this.writeInt32(e,pi[0])}writeFloat64(e,t){Ca[0]=t,this.writeInt32(e,pi[Kr?0:1]),this.writeInt32(e+4,pi[Kr?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===vs.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 gt=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=fi.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=gt.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=fi.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 mp={};function Zr(a,e){mp[a]=e}function gp(a){let e=a.getBufferIdentifier(),t=mp[e];return t(a)}function bp(a){return typeof a.guid=="function"?a.guid():null}var Vc=js(Pa(),1);var Oa=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 Vc.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new Gc(t)})}trySetupClient(e){this._client=new Vc.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)})})}},Uc=class{_peer;constructor(e){this._peer=e}};var Gc=class extends Uc{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 Wc="wss://needle-tiny-starter.glitch.me/socket",bt=!!H("debugnet"),Aa=!!(bt||H("debugowner"));var Rn=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||(Aa&&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 Aa&&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?(Aa&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Aa&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var ka=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Oa),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return bt}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(),bt&&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){bt&&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&&bt&&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)}connect(){if(this.connected)return;bt&&console.log("connecting");let t=C.findObjectOfType(mt,this.context,!1)?.getWebsocketUrl();t&&(Wc=t),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 "+Wc);let e=new Nv(Wc).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{bt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new fi(i),r=n.getBufferIdentifier(),o=this._listenersBinary[r],s=gp(n),c=bp(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(bt&&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(bt&&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),bt&&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),bt&&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),bt&&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));bt&&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*as Yt from"three";import{OrbitControls as zv}from"three/examples/jsm/controls/OrbitControls";import*as ys from"three";var $e=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=C.getComponent(this.gameObject,re)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new zv(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"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):(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=C.getComponent(this.gameObject,re);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 Ce;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&&C.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=q(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};k([A()],$e.prototype,"lookAtConstraint",2);import{Color as Vv}from"three";var xe=class extends Vv{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=Y.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 Uv}from"three";var yp=H("debugcam"),re=class extends M{get aspect(){return this._cam instanceof Uv?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 Yt.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(){yp&&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 Yt.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new Yt.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 qc(this)),this._skybox.enable()}};k([A()],re.prototype,"fieldOfView",1),k([A()],re.prototype,"nearClipPlane",1),k([A()],re.prototype,"farClipPlane",1),k([A()],re.prototype,"clearFlags",1),k([A()],re.prototype,"orthographic",2),k([A()],re.prototype,"orthographicSize",2),k([A()],re.prototype,"ARBackgroundAlpha",2),k([A(xe)],re.prototype,"backgroundColor",1);var qc=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?(yp&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Yt.sRGBEncoding,this._skybox.mapping=Yt.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function Ep(a){let e="created/implictly",t=new Yt.Object3D;a.add(t);let i=C.addNewComponent(t,re,!1);i.sourceId=e;let n=C.addNewComponent(t,$e,!1);return n.sourceId=e,i}import{EffectComposer as mw}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as gw}from"three/examples/jsm/postprocessing/RenderPass";import{AnimationClip as Wv,MathUtils as qv}from"three";var $r=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 wp(a,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??qv.generateUUID(),index:-1,clip:new Wv(a,1,[])}}import{AnimationClip as Xv,AnimationMixer as Qv,AxesHelper as Yv,Euler as _p,LoopOnce as Kv,Quaternion as Kt,Vector3 as Es}from"three";import*as Ma from"three";var Cn=H("debuganimatorcontroller"),Xc=H("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){Cn&&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){Cn&&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 Qv(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=es(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,Cn&&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()&&(Cn&&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 e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,i=t.motion.action,n=0;for(let o of t.transitions){if(++n,!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(let c of o.conditions)if(!this.evaluateCondition(c)){s=!1;break}if(!!s){Cn&&s&&console.log("All conditions are met",o.conditions,i);for(let c of o.conditions){let d=this.model.parameters.find(l=>l.name===c.parameter);d?.type===9&&(d.value=!1)}if(i){let c=t.motion.clip.duration,d=c<=0?1:i.time/c;if(!o.hasExitTime||d>=o.exitTime&&i.time>=i.getClip().duration){i.clampWhenFinished=!0,Cn&&(console.log("transition to "+o.destinationState,o),console.log(i.time,o.exitTime)),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}break}}let r=!1;if(t.motion.isLooping&&i&&i.time>=i.getClip().duration&&(r=!0,i.reset(),i.time=0,i.play()),!r&&t&&!e&&i&&this.animator&&t.behaviours){let o=i?.getClip().duration,s=i.time/o,c=new $r(this._activeState,s,o,this._speed);for(let d of t.behaviours)d.instance&&d.instance.onStateUpdate?.call(d.instance,this.animator,c,0)}}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[n].stateMachine.defaultState),e=this.model.layers[n].stateMachine.states[e]),!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 $r(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(Kv,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 $r(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);Cn&&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 Qc(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=wp(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 Xv;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=D.get(o.typeName),c=new s;c.isStateMachineBehaviour&&(c._context=this.context??void 0,tr(c,o.properties),o.instance=c),Cn&&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},Ia=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}},Se=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new Es;rotationChange=new Kt;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,Se.firstKeyframeRotation[i.uuid]||(Se.firstKeyframeRotation[i.uuid]=new Ma.Quaternion),r){let o=r.values;Se.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}Se.spaceRotation[i.uuid]||(Se.spaceRotation[i.uuid]=new Kt),Se.effectiveSpaceRotation[i.uuid]||(Se.effectiveSpaceRotation[i.uuid]=new Kt),Se.clipOffsetRotation[i.uuid]=new Kt,r&&Se.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=Se.lastObjRotation[this.root.uuid];Se.spaceRotation[this.clip.uuid].copy(t);{let i=new Ma.Euler().setFromQuaternion(t);console.log("START",this.clip.name,Y.toDegrees(i.y))}}getClipRotationOffset(){return Se.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Xc&&i.add(new Yv),Se.lastObjPosition[i.uuid]||(Se.lastObjPosition[i.uuid]=new Es);let n=new Es,r=new Es,o=0;this.positionWrapper=new Ia(t,(s,c)=>{let d=this.action.getEffectiveWeight();if(Xc&&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(Se.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(Xc){let s=t.values,c=new _p().setFromQuaternion(new Kt(s[0],s[1],s[2],s[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",Y.toDegrees(c.y));let d=t.values.length-4,l=new Kt().set(s[d],s[d+1],s[d+2],s[d+3]),h=new _p().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",Y.toDegrees(h.y))}let i=this.root;Se.lastObjRotation[i.uuid]||(Se.lastObjRotation[i.uuid]=new Kt);let n=0,r=new Kt,o=new Kt;this.rotationWrapper=new Ia(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(Se.identityQuaternion,1-e)}},Jt=Se;z(Jt,"lastObjPosition",{}),z(Jt,"lastObjRotation",{}),z(Jt,"firstKeyframeRotation",{}),z(Jt,"spaceRotation",{}),z(Jt,"effectiveSpaceRotation",{}),z(Jt,"clipOffsetRotation",{}),z(Jt,"identityQuaternion",new Kt);var Qc=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 Jt(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 Es;summedRotation=new Kt;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),Jt.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 Jv=H("debuganimator"),vt=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=Y.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=Y.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}Jv&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};k([A()],vt.prototype,"applyRootMotion",2),k([A()],vt.prototype,"hasRootMotion",2),k([A()],vt.prototype,"keepAnimatorControllerStateOnDisable",2),k([A()],vt.prototype,"runtimeAnimatorController",1);import*as eo from"three";var $t=class extends M{playAutomatically=!0;randomStartTime=!0;_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 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}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 o=this.tryFindHandle(e);if(o)return o.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,t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?eo.LoopRepeat:eo.LoopOnce),e.play();let r=new Yc(e,this.mixer,t,o=>{this._handles.splice(this._handles.indexOf(r),1)});return this._handles.push(r),r.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 eo.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};k([A()],$t.prototype,"playAutomatically",2),k([A()],$t.prototype,"randomStartTime",2);var Yc=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 qf}from"three/examples/jsm/loaders/GLTFLoader.js";import{Vector3 as Zv}from"three";var Sn=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new Zv}update(){if(!this.from||!this.to)return;let e=q(this.from).clone(),t=q(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),le(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};k([A(C)],Sn.prototype,"from",2),k([A(C)],Sn.prototype,"to",2);var mi=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};k([A()],mi.prototype,"time",2),k([A()],mi.prototype,"value",2),k([A()],mi.prototype,"inTangent",2),k([A()],mi.prototype,"inWeight",2),k([A()],mi.prototype,"outTangent",2),k([A()],mi.prototype,"outWeight",2),k([A()],mi.prototype,"weightedMode",2);var ur=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 Y.lerp(t.value,i.value,(e-t.time)/(i.time-t.time));t=i}return this.keys[this.keys.length-1].value}};k([A(mi)],ur.prototype,"keys",2);import*as xp from"three";import*as ws from"three";import{PositionalAudioHelper as $v}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var La=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}}};var lt=H("debugaudio");var je=class extends M{static get userInteractionRegistered(){return je._didCallBeginWaitForUserInteraction||(je._didCallBeginWaitForUserInteraction=!0,je._beginWaitForUserInteraction()),je._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),je._didCallBeginWaitForUserInteraction||(je._didCallBeginWaitForUserInteraction=!0,je._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!je._userInteractionRegistered){je._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&&(lt&&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&&je._userInteractionRegistered){let e=C.getComponent(this.context.mainCamera,ei)??C.findObjectOfType(ei,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&&je._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){je._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():je._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){lt&&console.log("audio buffer loaded"),je.registerWaitForAllowAudio(()=>{lt&&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(),lt&&console.log(this.name,this.shouldPlay,je.userInteractionRegistered,this),this.shouldPlay&&je._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(lt&&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?lt&&!this.helper&&(this.helper=new $v(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(lt&&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){lt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,lt&&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,lt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){lt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){lt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,lt&&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,lt&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},he=je;z(he,"_didCallBeginWaitForUserInteraction",!1),z(he,"callbacks",[]),z(he,"_userInteractionRegistered",!1),k([A()],he.prototype,"clip",2),k([A()],he.prototype,"playOnAwake",2),k([A()],he.prototype,"loop",1),k([A()],he.prototype,"spatialBlend",1),k([A()],he.prototype,"minDistance",1),k([A()],he.prototype,"maxDistance",1),k([A()],he.prototype,"volume",1),k([A()],he.prototype,"rollOffMode",2);var ei=class extends M{get listener(){return this._listener==null&&(this._listener=new xp.AudioListener),this._listener}_listener=null;awake(){he.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=C.getComponentInParent(this.gameObject,re);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as iy}from"three/examples/jsm/loaders/GLTFLoader";import*as ja from"three";var Ip=js(kp(),1),Da=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 Mp(a,e){let t=await a.arrayBuffer(),i=Lp(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 Da(!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 E=new Da(f.success,r,i,a.size);return E.url=e,E}function Lp(a){return(0,Ip.default)(new Uint8Array(a))}async function Ha(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=Lp(s);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function Dp(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}var _s=H("debugavatar"),pr=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))}},Pn=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 ve;i=C.instantiate(hn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(_s&&console.log("[Custom Avatar] valid config",t,_s?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,_s?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(_s&&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 Ha(t,t,0,"no url here go away",!0),!r)?null:(await to(e,r,null,0))?.scene??null}let i=new iy;return cr(i,e),new Promise((n,r)=>{let o=this.avatarRegistryUrl+"/"+t;i.load(o,async s=>{await Ba(e,o,s),n(s.scene)},s=>{_s&&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 ja.Vector3;new ja.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 pr(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 ny}from"three";var Vi=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!li)return;this._axes||(this._axes=new ny(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)}};k([A()],Vi.prototype,"length",2),k([A()],Vi.prototype,"depthTest",2),k([A()],Vi.prototype,"isGizmo",2);import*as jp from"three";var io=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=q(this.to).clone(),t=q(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=q(this.hint).clone();o.sub(r);let s=new jp.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),le(this.gameObject,h);let u=r.clone();u.sub(s),this.gameObject.lookAt(u)}};import*as Ui from"three";import*as gi from"three";var ry=new gi.BoxGeometry(1,1,1);function Fa(a=null){let e=new gi.Color(a??14540253),t=new gi.EdgesGeometry(ry);return new gi.LineSegments(t,new gi.LineBasicMaterial({color:e}))}var sy=H("gizmos"),Na=class extends M{box=null;testBox=new Ui.Box3;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new Ui.Box3),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=q(e,Na._position),i=qs(e,Na._size);this.testBox.setFromCenterAndSize(t,i)}return this.box?.intersectsBox(this.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){return this.box||(this.box=new Ui.Box3),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new Ui.Vector3(0,0,0),new Ui.Vector3(1,1,1)),this.box.applyMatrix4(this.gameObject.matrixWorld)),this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!sy&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Fa(e),this.gameObject.add(this._helper)}}},ct=Na;z(ct,"_position",new Ui.Vector3),z(ct,"_size",new Ui.Vector3(.01,.01,.01));var no=class{};var Lt=class extends M{canGrab=!0;onPointerClick(e){}},Dt=class extends M{isUsed=!0;usedBy=null};var fr=class extends ct{},ro=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=C.findObjectsOfType(fr,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(C.getComponentInParent(this.gameObject,Dt)||zr(this.gameObject,this.context.connection))}}};var mr=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||C.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:ay()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};k([A()],mr.prototype,"visibleOn",2);var za;function ay(){if(za===!0||za===!1)return za;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),za=a,a}import*as Gi from"three";var Pe=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 oo=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Pe).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Pe).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Pe).__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 Ht=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 Ht).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Ht).__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 oo).__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 On=H("debugsync"),so="STRS";Zr(so,Ht.getRootAsSyncedTransformModel);var bi=new gt;function Zc(a,e,t=!0){bi.clear();let i=bi.createString(a);Ht.startSyncedTransformModel(bi),Ht.addGuid(bi,i),Ht.addFast(bi,t);let n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;Ht.addTransform(bi,oo.createTransform(bi,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));let s=Ht.endSyncedTransformModel(bi);return bi.finish(s,so),bi.asUint8Array()}var Qe=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(){On&&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(){On&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Gi.Vector3,this._targetRotation=new Gi.Quaternion,this.lastWorldPos=new Gi.Vector3,this.lastWorldRotation=new Gi.Quaternion,this.rb=C.getComponentInChildren(this.gameObject,de),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Rn(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(so,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&tu(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(so,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Gi.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){On&&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 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)&&Yh(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){On&&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:(On&&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 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&&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&&(On&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Gi.Vector3(0,0,0))>1e3&&(On&&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)){On&&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=Zc(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as ee from"three";var Va=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(E){E.addEventListener("end",f),await e.xr.setSession(E),i.textContent="STOP AR",t.domOverlay.root.style.display="",h=E}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 Ua=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(),Ua.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"),Ua.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},lo=Ua;z(lo,"xrSessionIsGranted",!1);lo.registerSessionGrantedListener();import*as _e from"three";import{Matrix4 as by,Vector3 as vy}from"three";import*as Ga from"three";var Bp=js(Pa(),1);import{AudioAnalyser as cy}from"three";var co="noVoip",dt=H("debugvoip"),dy=H("voip");var $c=class{id;constructor(e){this.id=e}};var ed=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(){dt&&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 et.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}dt&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),dt&&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=>{dt&&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){dt&&console.log("call closed",e)}},td=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,he.userInteractionRegistered||dt&&console.log("Incoming call, waiting for user interaction before opening audio"),he.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){dt&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Ga.AudioListener;this.audio=new Ga.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}}}),dt&&console.log("call is setup, you should hear something now"),this.analyzer=new cy(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()}},et=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(H(co)){console.log("VOIP is disabled by url parameter: "+co);return}if(this.requireParam&&!dy){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Bp.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 ed(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];dt&&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){dt&&console.log("Peer connection established and received id"),this.model=new $c(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){dt&&console.log("CONNECTION",t),t.on("data",function(i){dt&&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(),dt&&console.log("received call"),await et.HasMicrophonePermissions()){let o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(o)}else e.answer(null);this.currentIncomingCalls[i]=new td(this,this.gameObject,e),e.on("stream",o=>{dt&&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"}};var ho=H("debugflags");var id=class{Mask=17;Has(e){let t=this.Mask&e;return ho&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Oe.Apply()}Enable(e){this.Mask|=e,Oe.Apply()}Disable(e){this.Mask&=~e,Oe.Apply()}Toggle(e){this.Mask^=e,Oe.Apply()}EnableAll(){this.Mask=-1,Oe.Apply()}DisableAll(){this.Mask=0,Oe.Apply()}},yt=id;z(yt,"Global",new id);var vi=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(yt.Global)}awake(){vi.registry.push(this)}onEnable(){vi.firstApply||(vi.firstApply=!0,vi.Apply())}onDestroy(){let e=vi.registry.indexOf(this);e>=0&&vi.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),ho&&console.log(i),vi.buffer.Mask=i,e=vi.buffer);let n=e;if(n?(ho&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(ho&&console.log("use global mask"),yt.Global.Has(this.visibleIn)),t!==void 0)if(t)ho&&console.trace("is visible",this.name,this.gameObject.uuid),C.setActive(this.gameObject,!0);else{if(ho&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Oe=vi;z(Oe,"registry",[]),z(Oe,"firstApply"),z(Oe,"buffer",new yt);import*as $ from"three";import{XRControllerModelFactory as uy}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as py}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as fy}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import*as zp from"three";import*as ii from"three";var hy=H("debugplayerview");var nd=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}},Wa=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new nd(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&&(hy&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}};var An=H("debugavatar"),ti=class extends M{static getAvatar(e){return e>=0&&e<ti.instances.length?ti.instances[e]:null}static onAvatarMarkerCreated(e){return ti._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return ti._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){ti.instances.push(this),An&&console.log(this);for(let e of ti._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){ti.instances.splice(ti.instances.indexOf(this),1);for(let e of ti._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):C.setActive(this.avatar,e))}},pe=ti;z(pe,"instances",[]),z(pe,"_onNewAvatarMarkerAdded",[]),z(pe,"_onAvatarMarkerDestroyed",[]);var xs=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 ii.Vector3(1,1,1);handLeftScale=new ii.Vector3(1,1,1);handRightScale=new ii.Vector3(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 ii.Object3D;_handLeftTarget=new ii.Object3D;_handRightTarget=new ii.Object3D;_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),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 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(xs.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handLeftScale),ne.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(xs.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.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(){An&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&Te.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&C.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(An&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&Te.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;C.setActive(n,!1),e=C.instantiate(n),C.setActive(e,!0)}An&&console.log(e);let i=await xs.loader.getOrCreateNewAvatarInstance(this.context,e);if(An&&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=C.addNewComponent(this.root,pe),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&&Te.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(...C.getComponentsInChildren(this.root,Oe)),this.flags.length<=0&&this.head){let n=C.addNewComponent(this.head,Oe);n.visibleIn=20,this.flags.push(n),An&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return An&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return An&&console.warn("build avatar failed"),!1}},jt=xs;z(jt,"loader",new Pn),z(jt,"invertRotation",new ii.Quaternion().setFromAxisAngle(new ii.Vector3(0,1,0),Math.PI));var Te=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??Q.Current?.time.time;return}}}};z(Te,"Pois",[]),z(Te,"LastChangeTime",0);var rd=class{guid;position=new zp.Vector3},Wi=class extends M{set controlledTarget(e){this.target=e;let t=D.get("MoveRandom");if(t&&this.target){let i=C.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new rd;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=C.getComponentInParent(this.gameObject,pe),this.avatar){let e=C.getComponentInParent(this.gameObject,pe);this._model=new Rn(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&&le(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(Te.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Te.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=q(this._currentTargetObject);le(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=Te.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}}}}};var qa=H("debugwebxrcontroller");var gr=class extends M{},Be=class extends M{static CreateRaycastLine(){let e=new $.Line(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(1),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new $.SphereGeometry(.5,22,22),t=new $.MeshBasicMaterial({color:this.raycastColor}),i=new $.Mesh(e,t);return i.visible=!1,i.layers.set(1),i}static Create(e,t,i,n){let r=i?C.addNewComponent(i,Be,!1):new Be;r.webXR=e,r.index=t,r.type=n;let o=e.context;return 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),r.hand.add(new py(r.hand)),r.hand.traverse(s=>s.layers.set(2)),r.handPointerModel=new fy(r.hand,r.controller),r.controller.addEventListener("connected",s=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),setTimeout(()=>{r.setControllerLayers(r.controllerGrip,2)},1e3)}),r.hand.addEventListener("connected",s=>{if(s.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(l=>l.layers.set(2)),r.handPointerModel.pointerObject?.traverse(l=>l.layers.set(2));let d=r.hand.joints;if(d)for(let l of Object.keys(d)){let h=d[l];h.parent||r.hand.add(h)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),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 $.Quaternion),ke(e).multiply(this._wristQuaternion.setFromEuler(new $.Euler(-Math.PI/4,0,0)))):null}movementVector=new $.Vector3;worldRot=new $.Quaternion;joystick=new $.Vector2;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),qa&&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 $.Quaternion;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(ke(this.controller),this.useSmoothing?t:1);let i=q(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,le(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)}ot(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,ot(this.raycastLine,this.rayRotation),le(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=Y.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(Y.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;le(e,d)}}}}else i<.1&&(this.didTeleport=!1);o!==null&&(e.scale.set(o,o,o),e.updateMatrixWorld())}isValidTeleportTarget(e){return C.getComponentInParent(e,gr)!=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=Y.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(),e&&e.length>0)for(let i of e){let n=i.object;if(!this.testIsVisible(n)){qa&&console.log("not visible");continue}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&&qa&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=ht.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?C.isActiveInHierarchy(e):!0}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 $.Ray;return e.origin.copy(q(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(!e)return new Array;let t=q(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new Ce;return e.layerMask=new $.Layers,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},ae=Be;z(ae,"Factory",new uy),z(ae,"raycastColor",new $.Color(.9,.3,.3)),z(ae,"raycastNoHitColor",new $.Color(.6,.6,.6)),z(ae,"geometry",new $.BufferGeometry().setFromPoints([new $.Vector3(0,0,0),new $.Vector3(0,0,-1)])),z(ae,"handModels",{}),z(ae,"eventSubs",{}),z(ae,"PreviousCameraFarDistance"),z(ae,"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=C.getComponentInParent(t,Lt);if(!r)return qa&&console.warn("Prevented taking object that is not interactable",t),null;let o=t,s=C.getComponentInParent(t,Qe);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=C.addNewComponent(this.selected,Dt),this.rigidbodies=C.getComponentsInChildren(this.selected,de),q(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();ke(this.selected,this.localQuaternionToGrab).premultiply(h.invert());let u=this.controller.webXR.Rig;return u&&this.rigPositionLastFrame.copy(q(u)),Te.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)),Te.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 $.Vector3;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new $.Vector3;localQuaternionToGrab=new $.Quaternion(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new $.Vector3;controllerWorldPos=new $.Vector3;lastControllerWorldPos=new $.Vector3;controllerPosDelta=new $.Vector3;totalChangeAlongDirection=0;rigPositionLastFrame=new $.Vector3;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),q(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=q(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 $.Vector3),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),ot(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(q(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),le(this.selected,i)}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)}}},ht=tt;z(ht,"Events",{}),z(ht,"Current",[]);import*as uo from"three";var Bt=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 uo.Matrix4;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=C.findObjectOfType(K);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 uo.Matrix4().fromArray(i.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new uo.Matrix4),this._placementPose.copy(t),e){if(this.invertForward){let i=new uo.Matrix4().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)),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 uo.Matrix4().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};k([A()],Bt.prototype,"invertForward",2),k([A()],Bt.prototype,"arScale",1);var kn=class extends M{awake(){}};import{Object3D as my}from"three";var br=H("debugaddressables"),Xa=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}},it=class{static getOrCreate(e,t,i){let n=pn(e,t);br&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,o=r.findAssetReference(n);if(o)return o;let s=new it(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,ou(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&&(br&&console.log("Unload",this.asset),this.asset.scene?C.destroy(this.asset.scene):C.destroy(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,br&&console.log("Preload",this.uri);let e=await Dp(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=Q.Current;this._rawBinary?(this._loading=to(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(br&&console.log("Load async",this.uri),this._loading=vr(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 Li(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=Q.Current;if(e||(e=n.scene),this.mustLoad&&await this.loadAssetAsync(),br&&console.log("Instantiate",this.uri,"parent:",e),this.asset){br&&console.log("Add to scene",this.asset);let r=e instanceof ve?e:null;if(r||(r=new ve),typeof e=="object"&&(e instanceof my?r.parent=e:Object.assign(r,e)),t){r.context=n;let o=this.asset;o.guid=this.uri;let s=Js(o,r,void 0,i);if(s)return s}else{let o=C.instantiate(this.asset,r);if(o)return o}}else br&&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}},od=class extends Di{constructor(){super([it])}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?it.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new od;import*as Et from"three";var yi=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 Me=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 Me).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Me).__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 Pe).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new yi).__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 Pe).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Pe).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new yi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new yi).__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 Vp=H("debugxr"),Ts=H("debugavatar");var ad="VRUS";Zr(ad,Me.getRootAsVrUserStateBuffer);function sd(){return new Date().getTime()}function gy(a){let e=a&4294967295,t=a/Math.pow(2,32)&1048575;return Xe.create(e,t)}var Rs=class{guid;time;avatarId;position=new Et.Vector3;rotation=new Et.Vector4;scale=1;posLeftHand=new Et.Vector3;posRightHand=new Et.Vector3;rotLeftHand=new Et.Quaternion;rotRightHand=new Et.Quaternion;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=sd(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=Rs.quat0,s=Rs.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,Rs.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);Me.startVrUserStateBuffer(e),Me.addGuid(e,i),Me.addTime(e,gy(this.time)),Me.addAvatarId(e,n),Me.addPosition(e,Pe.createVec3(e,this.position.x,this.position.y,this.position.z)),Me.addRotation(e,yi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Me.addScale(e,this.scale),Me.addPosLeftHand(e,Pe.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Me.addPosRightHand(e,Pe.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Me.addRotLeftHand(e,yi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Me.addRotRightHand(e,yi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Me.endVrUserStateBuffer(e);e.finish(r,ad);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()}},Ft=Rs;z(Ft,"invertRotation",new Et.Quaternion().setFromAxisAngle(new Et.Vector3(0,1,0),Math.PI)),z(Ft,"quat0",new Et.Quaternion),z(Ft,"quat1",new Et.Quaternion);var qi=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent(K)),this.webXR||(this.webXR=C.findObjectOfType(K,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=C.findObjectOfType(K,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=C.findObjectOfType(et,this.context)),Ts){let e="debug-avatar-"+Ts,t=new jt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof Ts=="string"&&Ts.length>0)if(await t.setAvatarOverride(Ts)){let i=new Ft(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=C.getComponent(this.gameObject,K),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),K.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),K.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),K.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(ad,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 Ft("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return Vp&&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 jt(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),K.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),K.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),K.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=sd();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=sd();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 jt(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(){Vp&&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 gt(1024);onXRSessionUpdate(e){this.xrState??=new Ft(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new Rn(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 H("avatar")??null}};async function yy(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function Ey(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var ld=!1,cd=!1;yy().then(a=>ld=a);Ey().then(a=>cd=a);var Fe=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(ld||cd)}static get IsARSupported(){return ld}static get IsVRSupported(){return cd}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){Fe.XRSupported||console.warn("WebXR is not supported on this device");let i=lo.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=Va.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Fe.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=it.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!C.findObjectOfType(qi,this.context)){let e=C.addNewComponent(this.gameObject,qi,!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 In(this);let e=Fe.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Fe.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(i=Fe.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Fe.resetButtonStyles(i),Fe.resetButtonStyles(t)},1e3)}_transformOrientation=new _e.Quaternion;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)}Fe._isInXr===!1&&t&&this.onEnterXR(t,e),Fe.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++)ae.Create(this,e,this.gameObject,0);Fe.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(q(this.context.mainCamera)),this._originalCameraRotation.copy(ke(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=C.findObjectOfType(kn,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new _e.Group,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new _e.Vector3;_originalCameraRotation=new _e.Quaternion;onEnterXR(e,t){console.log("[XR] session begin",e),Fe._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 _e.Quaternion(s.x,s.y,s.z,s.w),d=new _e.Euler().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(yt.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"),Fe._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Fe.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),le(this.context.mainCamera,this._originalCameraPosition),ot(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),yt.Global.Set(17),Fe.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){!H("mirror")||setTimeout(()=>{if(!Fe.IsInWebXR)return;let t=new URL(window.location.href);Fr(t.searchParams,co,1),Fr(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=()=>{Fe.IsInWebXR&&e.end()})})},1e3)}},K=Fe;z(K,"_isInXr",!1),z(K,"events",new _e.EventDispatcher),k([A(it)],K.prototype,"defaultAvatar",2);var po=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(){return this.arDomOverlay=this.webxr.context.domElement,this.arOverlayElement=this.arDomOverlay.getAROverlayContainer(),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;for(let n=0;n<4;n++)ae.Create(this.webxr,n,this.webxr.gameObject,i);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=C.findObjectOfType(Bt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(n=>{e.requestHitTestSource({space:n}).then(r=>{this.hitTestSource=r}).catch(r=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported")})}),!this.reticle&&this.sessionRoot&&(this.reticle=new _e.Mesh(new _e.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new _e.MeshBasicMaterial),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,po.tempWebXRObject||(po.tempWebXRObject=new _e.Object3D),this.context.scene.add(po.tempWebXRObject),C.addComponent(po.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene"),this.arDomOverlay&&this.arOverlayElement&&this.arDomOverlay.onEnterAR(e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),C.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay&&this.arDomOverlay.onExitAR(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=wy.clone();if(n){let o=new vy(0,0,0).add(n.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new by().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)}},In=po;z(In,"tempWebXRObject");var wy=new _e.Matrix4().identity().makeTranslation(0,-.5,0);var dd=!1;var fo=class extends Lt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;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(){}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||K.IsInWebXR)return;let t=C.getComponentInParent(e.object,fo);!t||t!==this||(fo.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||K.IsInWebXR||fo.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||K.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(K.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!K.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&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new Qa(this.context.mainCamera);else return;if(!e||!e.object)return;let t=C.getComponentInParent(e.object,fo);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);let r=C.getComponentInChildren(i,Qe);dd&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=C.addNewComponent(i,Dt),this._draggingRigidbodies.length=0;let o=C.getComponentsInChildren(i,de);o&&this._draggingRigidbodies.push(...o);let s=Hl();C.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(dd&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let n=C.getComponentInChildren(e.object,Qe);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=Hl();C.invokeOnChildren(t,i("onDragEnd"))}},wt=fo;z(wt,"_active",null),z(wt,"lastHovered");var ud=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(ud.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&&Te.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}Te.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this._rbs=C.getComponentsInChildren(this._selected,de),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)){dd&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=q(this._camera).clone().sub(q(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 E=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(E,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=q(this._selected);n.y=e.y,e=n}if(le(this._selected,e),le(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=q(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),le(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=q(this._selected),t=new ee.Ray(new ee.Vector3(0,.1,0).add(e),new ee.Vector3(0,-1,0)),i=new Ce;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(){ne.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}},Qa=ud;z(Qa,"geometry",new ee.BufferGeometry().setFromPoints([new ee.Vector3(0,0,0),new ee.Vector3(0,-1,0)]));var Mn=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?mt.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 Gp(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 Wp(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 Ce;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}))}};k([A()],Mn.prototype,"filesBackendUrl",2),k([A()],Mn.prototype,"localhost",2);import{Vector3 as xy,Quaternion as Ty,Object3D as qp}from"three";var Ei=class extends Lt{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 xy(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Ty(0,0,0,1)}let e=C.getComponentInParent(this.gameObject,wt);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),ae.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 ve;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=C.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}};k([A(qp)],Ei.prototype,"parent",2),k([A(qp)],Ei.prototype,"object",2),k([A()],Ei.prototype,"limitCount",2),k([A()],Ei.prototype,"limitInterval",2);var wi=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)}}},Ry=a=>/^[A-Z]*$/.test(a),yr=class extends Event{args},Ae=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&&Ry(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 yr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new wi(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 mo=class extends M{};import{FlyControls as Cy}from"three/examples/jsm/controls/FlyControls";var go=class extends M{_controls=null;onEnable(){let e=C.getComponent(this.gameObject,re)?.cam;this._controls=new Cy(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 Qp from"three";import{Color as Sy}from"three";var Xi=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!li||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Qp.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Fa(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}};k([A()],Xi.prototype,"objectBounds",2),k([A(Sy)],Xi.prototype,"color",2),k([A()],Xi.prototype,"isGizmo",2);import{GLTFExporter as ky}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as pd,Matrix4 as Py,Vector3 as Yp,Quaternion as Oy}from"three";var Cs=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 Py,s=new Array,c=new Array,d=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,o);let E=new Yp,b=new Oy,y=new Yp;o.decompose(E,b,y),s.push(E.x,E.y,E.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 pd(l,3)),ROTATION:i.processAccessor(new pd(h,4)),SCALE:i.processAccessor(new pd(u,3))},n[this.name]=!0}};import{Object3D as Iy,Vector3 as My}from"three";var Ln=Ie,Ya="$___Export_Components",Ay="NEEDLE_components",fd=class{[Jn]},md=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},bo=class{get name(){return Ay}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[Ya]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Ln&&console.log("DONE",JSON.stringify(t)),e[Ya]===void 0)return;let i=e[Ya];delete e[Ya],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 md(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Ln&&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 fd;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=Kp(l,this.context);h!==null&&d.push(h)}d.length>0&&(c[Jn]=d,Ln&&console.log("DID WRITE",n,"nodeIndex",o,d))}}beforeRoot(){return Ln&&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];Ln&&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;Ln&&console.log("NODE",c);let u=this.nodeToObjectMap[d];if(!u){console.error("Could not find object for node index: "+d,c,t);continue}r.push(this.createComponents(u,h))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Jn];if(i){Ln&&console.log(e.name,i);for(let n in i){let r=i[n];Ln&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await Vr(this.parser,r),e.userData=e.userData||{},e.userData[Jn]=e.userData[Jn]||[],e.userData[Jn].push(r)}}}};var vo=class extends ct{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},Nt=class extends M{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:Nt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Nt.saveArrayBuffer(i,e):Nt.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 ky,this.exporter.register(s=>new Cs(s)),this.ext=new bo,this.ext.registerExport(this.exporter)),Nt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:Nt.collectAnimations(e)},n=new Iy;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),C.getComponentsInChildren(s,Ee).forEach(c=>{C.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new Ur(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,C.getComponentsInChildren(s,Ee).forEach(c=>{C.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 My;return i.set(0,0,0),e.forEach(n=>{i.add(q(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 Ka,GridHelper as Ly}from"three";var Qi=class extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!li)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Ly(e,t,this.color0??new Ka(.4,.4,.4),this.color1??new Ka(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};k([A()],Qi.prototype,"isGizmo",2),k([A(Ka)],Qi.prototype,"color0",2),k([A(Ka)],Qi.prototype,"color1",2);import{GroundProjectedEnv as Dy}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Yi=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.updateProjection(),this._watcher||(this._watcher=new un(this.context.scene,"environment"),this._watcher.subscribeWrite(this.updateProjection.bind(this))),this._watcher.apply()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateProjection(){!this.context.scene.environment||((!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new Dy(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))}};k([A()],Yi.prototype,"scale",1),k([A()],Yi.prototype,"radius",1),k([A()],Yi.prototype,"height",1);import*as nt from"three";import{Color as Hy}from"three";function gd(a){return a*Math.PI/180}var Jp=300,Zp=H("debuglights");var Ye=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=K.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=K.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){K.removeEventListener("xrStarted",this._webXRStartedListener),K.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Bt)??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,-Jp*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Nr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Zp){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,gd(this.spotAngle/2),1-gd(this.innerSpotAngle/2)/gd(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=Jp*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,Zp&&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)}};k([A()],Ye.prototype,"type",2),k([A(Hy)],Ye.prototype,"color",2),k([A()],Ye.prototype,"shadowNearPlane",1),k([A()],Ye.prototype,"shadowBias",1),k([A()],Ye.prototype,"shadowNormalBias",1),k([A()],Ye.prototype,"shadows",1),k([A()],Ye.prototype,"lightmapBakeType",2),k([A()],Ye.prototype,"intensity",1),k([A()],Ye.prototype,"shadowDistance",1),k([A()],Ye.prototype,"shadowResolution",1);var UA=new nt.Vector3(0,0,0);import*as Ja from"three";import{Vector3 as jy}from"three";var yo=H("debugLODs"),By=H("noLODs");var _i=class{screenRelativeTransitionHeight;distance;renderers};k([A()],_i.prototype,"screenRelativeTransitionHeight",2),k([A()],_i.prototype,"distance",2),k([A()],_i.prototype,"renderers",2);var bd=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):yo&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=C.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}},Dn=class extends M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!By&&!this._lodsHandler&&!!this.gameObject&&(yo&&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 bd(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 Ja.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new Ja.Object3D;yo&&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;yo&&console.log(n,s.name);for(let h of this._lods){let u=null;h.renderers.includes(r)?u=s:u=i,yo&&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;yo&&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}}}};k([A(jy)],Dn.prototype,"localReferencePoint",2),k([A(_i)],Dn.prototype,"lodModels",2);import{Object3D as Fy}from"three";var Er=class extends M{constraintActive=!0;locked=!1;sources=[]};k([A(Fy)],Er.prototype,"sources",2);var Eo=class extends M{},wo=class extends M{};var vd=H("debugnestedgltf"),wr=class extends M{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;vd&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new ve;t.idProvider=new Ge(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;vd&&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(),vd&&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}};k([A(it)],wr.prototype,"filePath",2);import{Quaternion as Ny,Euler as zy,Vector3 as _r,Plane as Vy}from"three";var xi=class extends M{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new _r(0,0,0);rotationOffset=new _r(0,0,0);offset=new _r(0,0,0);update(){if(!this.from)return;var e=q(this.from),t=ke(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 Vy(this.gameObject.up,0),c=q(this.referenceSpace);s.setFromNormalAndCoplanarPoint(this.gameObject.up,c);let d=new _r(0,0,0);s.projectPoint(e,d),e.copy(d)}this.affectPosition&&le(this.gameObject,e);let n=new zy(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new Ny().setFromEuler(n);this.affectRotation&&ot(this.gameObject,t.multiply(r));let o=new _r;this.from.getWorldDirection(o).multiplyScalar(50),this.levelLookDirection&&(o.y=0),this.alignLookDirection&&this.gameObject.lookAt(o)}};k([A(C)],xi.prototype,"referenceSpace",2),k([A(C)],xi.prototype,"from",2),k([A(_r)],xi.prototype,"positionOffset",2),k([A(_r)],xi.prototype,"rotationOffset",2);import*as Re from"three";import*as ni from"three";var _o=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 ni.Color(1,1,1);startColor1=new ni.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 ni.Vector2(0,1);cullingMode=0},xo=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},To=class{shapeType=yd.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new ni.Vector3(1,1,1);boxThickness=new ni.Vector3(0,0,0);position=new ni.Vector3(0,0,0);rotation=new ni.Vector3(0,0,0);scale=new ni.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},yd=(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))(yd||{});var Gy=H("debugparticles"),Ed=class{age=0;lifetime=0;position;velocity;color},xr=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(){Gy&&console.log(this)}},Ro=class extends M{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new Re.Quaternion;tempVec3=new Re.Vector3;tempQuat=new Re.Quaternion;awake(){this.renderer=C.getComponent(this.gameObject,xr),console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new Re.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new Re.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new Re.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 Re.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new Re.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new Re.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 Ed;r.lifetime=this.main.startLifetime??1,r.position=new Re.Vector3,r.velocity=new Re.Vector3,r.color=new Re.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 Re.Vector3(0,1,0);t.copy(i);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*Y.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 ef from"three";function*$p(a,e=null){let t=e?e.time:Q.Current.time,i=t.time;for(;t.time-i<a;)yield}var ut=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 $p(.2),!this.tryAssignColor()););}tryAssignColor(){let e=C.getComponentInParent(this.gameObject,pe);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ut.hashCode(e),i=ut.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 ef.Color(t/255,i/255,n/255)}};import*as Za from"three";import{Object3D as qy,Texture as Xy}from"three";function Wy(){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 tf(a){await Wy(),a()}var wd=H("debugvideo");var Ne=class extends M{renderer=null;playOnAwake=!0;playOnEnable;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"))}_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.create(!0)}setClipURL(e){this.url!==e&&(this.url=e,this.source=1,wd&&console.log("set url",e),this.videoElement?(this.videoElement.src=e,this._isPlaying&&this.videoElement.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)}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(),tf(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[]}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)}),wd&&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}!t||(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"?this.videoElement.src=t: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))}_targetObjects;getTargetObjects(){return Array.from(this._targetObjects)}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),wd&&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;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);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")}};k([A(qy)],Ne.prototype,"renderer",2),k([A()],Ne.prototype,"playOnAwake",2),k([A()],Ne.prototype,"playOnEnable",2),k([A()],Ne.prototype,"renderMode",2),k([A()],Ne.prototype,"targetMaterialProperty",2),k([A(Ee)],Ne.prototype,"targetMaterialRenderer",2),k([A(Xy)],Ne.prototype,"targetTexture",2),k([A()],Ne.prototype,"time",2),k([A()],Ne.prototype,"playbackSpeed",1),k([A()],Ne.prototype,"isLooping",1);var rf=js(Pa(),1);import*as nf from"three";import{Color as Qy,Object3D as Yy}from"three";var xd=class extends Di{constructor(){super([Qy,xe])}onDeserialize(e){if(e!=null)return e.a!==void 0?new xe(e.r,e.g,e.b,e.a):e.alpha!==void 0?new xe(e.r,e.g,e.b,e.alpha):new nf.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}}},Qk=new xd,Td=class extends Di{constructor(){super(Yy)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return Ie&&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 Ie&&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=C.findByGuid(e.guid,n)),i||(i=C.findByGuid(e.guid,t.context.scene)),i?Ie&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},Ky=new Td,Rd=class extends Di{constructor(){super([st,M])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Ie&&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=C.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}}},_d=new Rd,Cd=class extends Di{constructor(){super([Ae])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){Ie&&console.log("DESERIALIZE EVENT",e);let i=new Array;for(let o of e.calls){Ie&&console.log(o);let s=_d.findObjectForGuid(o.target,t.root);!s&&t.context?.scene&&(s=_d.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=Ky.onDeserialize(o.argument,t),l||(l=_d.onDeserialize(o.argument,t))),d=new wi(c?(...u)=>h(...u):void 0,o.enabled)):d=new wi(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 Ae(i);Ie&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},Yk=new Cd;import{EventDispatcher as kd}from"three";function $a(a){if(!!a)for(let e of a.getTracks())e.stop()}var Hn=class extends M{onPointerClick(){if(this.isSending){this.close();return}this.share()}device=0;aspectMode=1;get isSending(){return this._currentStream&&this._currentMode===1}get isReceiving(){return this._currentStream&&this._currentMode===2}_net;_video;_requestOpen=!1;_currentStream=null;_currentMode=0;awake(){he.registerWaitForAllowAudio(()=>{this._video&&this._currentStream&&this._currentMode===2&&this._video.setVideo(this._currentStream)})}start(){if(this._video=C.getComponentInChildren(this.gameObject,Ne)??void 0,!this._video){console.error("Missing VideoPlayer component");return}let e=el.getOrCreate(this.context,this.guid);this._net=new Ad(this.context,e),this._net.enable(),this._net.addEventListener(of.ReceiveVideo,this.onReceiveVideo.bind(this))}async share(){this._requestOpen=!0;try{if(this._video){let e={echoCancellation:!0,autoGainControl:!1},t={video:e,audio:e};switch(this.device){case 1:this.tryShareUserCamera(t);break;case 0:if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}let i=await navigator.mediaDevices.getDisplayMedia(t);this._requestOpen?this.setVideo(i,1):$a(i);break}}}catch(e){if(e.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",e)}}close(){this._requestOpen=!1,this._currentStream&&(console.warn("Close current stream / disposing resources"),$a(this._currentStream),this._net?.stopSendingVideo(this._currentStream),this._currentMode=0,this._currentStream=null)}setVideo(e,t){e!==this._currentStream&&(this.close(),!(!e||!this._video)&&(this._currentStream=e,this._requestOpen=!0,this._currentMode=t,this._video.setVideo(e),t===1&&this._net?.startSendingVideo(e),this._targetObjects=void 0,this.updateAspect()))}onReceiveVideo(e){this.setVideo(e.stream,2)}async tryShareUserCamera(e){let t=(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind==="videoinput");console.log("Request camera",t);for(let i of t)try{if(!this._requestOpen)break;if(i.kind!=="videoinput")continue;let n=i.deviceId;e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=n);let r=await navigator.mediaDevices.getUserMedia(e);this._requestOpen?this.setVideo(r,1):$a(r),console.log("Selected camera",i);break}catch(n){console.warn(n)}}_targetObjects;updateAspect(){this.startCoroutine(this.updateAspectImpl())}_updateAspectRoutineId=-1;*updateAspectImpl(){let e=++this._updateAspectRoutineId;for(;this.aspectMode!==0&&this._currentStream&&e===this._updateAspectRoutineId;){let t=this._video,i=this._currentStream;if(!t||!i)return;let n;for(let r of i.getVideoTracks()){let o=r.getSettings();if(o.width&&o.height){n=o.width/o.height;break}}if(n===void 0)return;this._targetObjects||(this._targetObjects=t.getTargetObjects());for(let r of this._targetObjects){let o=1;if(r.parent){let s=qs(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}}yield}}};k([A()],Hn.prototype,"device",2),k([A()],Hn.prototype,"aspectMode",2);var of=(i=>(i.Connected="peer-user-connected",i.ReceiveVideo="receive-video",i.Disconnected="peer-user-disconnected",i))(of||{}),Sd=class{type="receive-video";stream;target;constructor(e,t){this.stream=e,this.target=t}},Pd=class{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}};var Od=class extends kd{userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),$a(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 Sd(n,this);this.dispatchEvent(r)}})}},Co=class extends kd{static getOrCreate(e,t){if(Co.instances.has(t))return Co.instances.get(t);let i=new Co(e,t);return Co.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 rf.default(e)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){!this._peer||(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){}onPeerConnect(e){console.log("Peer connected as",e),this.context.connection.send("peer-user-connected",new Pd(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 Od(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}},el=Co;z(el,"instances",new Map);var Ad=class extends kd{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)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 Zy,AdditiveBlending as $y}from"three";var jn=class extends M{mode=0;shadowColor=new xe(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=C.getComponent(this.gameObject,Ee);if(e){let t=e.material;t.blending=$y,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
125
+ `,defines:{USE_LIGHTMAP:""}})}};var A=function(a){if(a===void 0&&(a=null),!Array.isArray(a))a=pp(a);else for(let e=0;e<a.length;e++){let t=a[e];a[e]=pp(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=a}};function pp(a){switch(a?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return a}import{Vector4 as Bv}from"three";import{NeverStencilFunc as bv,LessStencilFunc as vv,EqualStencilFunc as yv,LessEqualStencilFunc as Ev,GreaterStencilFunc as wv,NotEqualStencilFunc as _v,GreaterEqualStencilFunc as xv,AlwaysStencilFunc as Tv,ZeroStencilOp as Rv,KeepStencilOp as Cv,ReplaceStencilOp as Sv,IncrementStencilOp as Pv,DecrementStencilOp as Ov,IncrementWrapStencilOp as Av,DecrementWrapStencilOp as kv,InvertStencilOp as Iv}from"three";var Oc=H("debugstencil");function Mv(a,e){return(a&1<<e.layer)!=0}var lr=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(Oc&&console.log(t,lr.stencils),!t)return;let i=lr.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(Mv(r.layer,e)){Oc&&console.log(r);let o=e.material?.clone();o&&(e.material=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[Dv];if(i){Oc&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let o={...r};o.compareFunc=Lv(o.compareFunc),o.passOp=Ac(o.passOp),o.failOp=Ac(o.failOp),o.zFailOp=Ac(o.zFailOp),lr.stencils[this.source]||(lr.stencils[this.source]=[]),lr.stencils[this.source].push(o)}}}return null}},cr=lr;z(cr,"stencils",{});function Ac(a){switch(a){case 0:return Cv;case 1:return Rv;case 2:return Sv;case 3:return Pv;case 4:return Ov;case 6:return Av;case 7:return kv;case 5:return Iv}return 0}function Lv(a){switch(a){case 1:return bv;case 2:return vv;case 3:return yv;case 4:return Ev;case 5:return wv;case 6:return _v;case 7:return xv;case 8:return Tv}return 0}var Dv="NEEDLE_render_objects";import{TextureLoader as Hv}from"three";import{GLTFLoader as jv}from"three/examples/jsm/loaders/GLTFLoader";import{DRACOLoader as kc}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as fp}from"three/examples/jsm/loaders/KTX2Loader.js";var fs=H("debugdecoders"),Qt,_n;function Ic(a){a!==void 0&&typeof a=="string"&&(Qt||(Qt=new kc),fs&&console.log("Setting draco decoder path to",a),Qt.setDecoderPath(a))}function Mc(a){a!==void 0&&typeof a=="string"&&(Qt||(Qt=new kc),fs&&console.log("Setting draco decoder type to",a),Qt.setDecoderConfig({type:a}))}function Lc(a){a!==void 0&&typeof a=="string"&&(_n||(_n=new fp),fs&&console.log("Setting ktx2 transcoder path to",a),_n.setTranscoderPath(a))}function dr(a,e){Qt||(Qt=new kc,Qt.setDecoderPath("./include/draco/"),Qt.setDecoderConfig({type:"js"}),fs&&console.log("Setting draco decoder path to","./include/draco/")),_n||(_n=new fp,_n.setTranscoderPath("./include/ktx2/"),fs&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&_n.detectSupport(e.renderer)),a.setDRACOLoader(Qt),a.setKTX2Loader(_n)}var Dc="NEEDLE_deferred_texture",Mt=H("debugdeferredtextures"),ms=class{static assignTextureLOD(e,t,i,n=0){if(!!i)for(let r of Object.keys(i)){let o=i[r];o?.isTexture===!0&&(Mt&&console.log(`-----------
126
+ `,"FIND",i.name,r,o?.name,o?.userData,o),ms.getOrLoadTexture(e,t,i,r,o,n).then(s=>{s?.isTexture===!0&&(s.needsUpdate=!0,Mt&&console.log("Assign LOD",i.name,r,s.name,s.guid,i,"Prev:",o,"Now:",s,`
127
+ --------------`),i[r]=s,i.needsUpdate=!0)}))}}get name(){return Dc}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return Mt&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[Dc];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(o=>{Mt&&console.log("register texture",o.name,o.uuid,n),o.userData.deferred=n,ms.cache.set(o.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r,o){let s=r.uuid,c=ms.cache.get(s);if(c){Mt&&console.log(s,c.uri,c.guid);let d=mn(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 Mt&&console.log("Texture has already been loaded: "+l,i.name,n,r.name),this.resolved[l];let h=new jv;dr(h,e),Mt&&console.log("Load "+d,i.name,n,c.guid);let u=await h.loadAsync(d),f=u.parser;Mt&&console.log("Loading finished "+d,i.name,n,c.guid);let E=-1,b=!1;for(let g of u.parser.json.textures)if(E++,g?.extensions){let p=g?.extensions[Dc];if(p?.guid&&p.guid===c.guid){b=!0;break}}if(!b)return null;let y=await f.getDependency("texture",E);return y&&(y.guid=c.guid),this.resolved[l]=y,Mt&&console.log(i.name,n,'change "'+r.name+'" \u2192 "'+y.name+'"',d,E,y,i,l),y}else{Mt&&console.log("Load texture from uri: "+d);let h=await new Hv().loadAsync(d);return h&&Mt?console.log(c,h):console.warn("failed loading",d),h}}else Mt&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},Vi=ms;z(Vi,"cache",new Map),z(Vi,"resolved",{});var gp=H("noInstancing"),bp=!!H("debuglightmaps"),Fv=H("debuginstancing"),Nv=H("debugprogressiveload"),zv=H("noprogressiveload"),Yr=class{path=null;asset=null;default};var Hc=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=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}},zc=class extends M{receiveShadows=!1;shadowCastingMode=jc.Off;lightmapIndex=-1;lightmapScaleOffset=new pi.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;_lightmaps;get material(){return this.gameObject.material}set material(e){this.gameObject.material=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new Hc(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return gp}_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();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"||C.getComponent(n,zc))){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 zi(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,bp)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new zi(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,bp),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=Vv.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return C.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return C.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&&!gp&&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())}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){cr.applyStencil(this)}onBeforeRenderThree(e,t,i,n,r,o){if(!zv&&r._didRequestTextureLOD===void 0&&(r._didRequestTextureLOD=0,Nv?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{Vi.assignTextureLOD(this.context,this.sourceId,r)},2e3)):Vi.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)}onBeforeRender(){if(!this.gameObject)return;let e=this.gameObject[Bc]===!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[Bc],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&&C.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()}}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]}}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==jc.On?e.castShadow=!0:e.castShadow=!1}},ye=zc;k([A()],ye.prototype,"receiveShadows",2),k([A()],ye.prototype,"shadowCastingMode",2),k([A()],ye.prototype,"lightmapIndex",2),k([A(Bv)],ye.prototype,"lightmapScaleOffset",2),k([A()],ye.prototype,"enableInstancing",2),k([A()],ye.prototype,"renderOrder",2),k([A()],ye.prototype,"allowOcclusionWhenDynamic",2);var hr=class extends ye{},Kr=class extends hr{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},jc=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(jc||{}),Bc="NEEDLE_NEED_UPDATE_INSTANCE",ne=class{static markDirty(e,t=!0){if(!!e&&(C.isUsingInstancing(e)&&(e[Bc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)ne.markDirty(i,!0)}},Fc=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 xa(e.name,o,s,200,t);return this.objs.push(c),c.addInstance(r)}return null}},Vv=new Fc,Nc=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,C.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)}},Vc=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,Fv&&(i=new pi.MeshBasicMaterial({color:this.randomColor()})),this.inst=new pi.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 pi.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 Nc(-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,Vc.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}},xa=Vc;z(xa,"nullMatrix",new pi.Matrix4);import{Vector3 as Uv}from"three";import*as ur from"three";import{Vector3 as vp}from"three";var xn=class extends M{mass=1;set isKinematic(e){this._isKinematic=e,this._body&&(this._body.type=e?V.KINEMATIC:V.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 ur.Matrix4}awake(){this._body=null,this.currentVelocity=new ur.Vector3,this._smoothedVelocity=new ur.Vector3,this.lastWorldPosition=q(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 fn(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 Ta;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?xn.tempPosition.set(this.body?.velocity.x,this.body?.velocity.y,this.body?.velocity.z):xn.tempPosition.set(0,0,0)}setVelocity(e,t,i){if(!!this.body){if(e instanceof vp){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?xn.tempPosition.set(this.body?.torque.x,this.body?.torque.y,this.body?.torque.z):xn.tempPosition.set(0,0,0)}setTorque(e,t,i){if(!!this.body){if(e instanceof vp){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){xn.copyVector3.set(e.x,e.y,e.z),this._smoothedVelocity.lerp(xn.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=q(this.gameObject);this.currentVelocity.subVectors(e,this.lastWorldPosition),this.lastWorldPosition.copy(e),this._smoothedVelocity.lerp(this.currentVelocity,this.context.time.deltaTime/.1)}}},ce=xn;z(ce,"tempPosition",new ur.Vector3),z(ce,"copyVector3",new ur.Vector3),k([A()],ce.prototype,"mass",2),k([A()],ce.prototype,"isKinematic",1),k([A()],ce.prototype,"drag",2),k([A()],ce.prototype,"angularDrag",2),k([A()],ce.prototype,"detectCollisions",2),k([A()],ce.prototype,"sleepThreshold",2);import{Vector3 as Jr}from"three";var mt=class extends M{attachedRigidbody=null;isTrigger=!1;_shape=null;awake(){super.awake(),this._shape=null}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(ce))}onDisable(){this._shape}};k([A(ce)],mt.prototype,"attachedRigidbody",2),k([A()],mt.prototype,"isTrigger",2);var Tn=class extends mt{radius=.5;center=new Jr(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addSphereCollider(this.gameObject,this.center,this.radius,this.attachedRigidbody))}};k([A()],Tn.prototype,"radius",2),k([A(Jr)],Tn.prototype,"center",2);var Rn=class extends mt{size=new Jr(1,1,1);center=new Jr(0,0,0);onEnable(){super.onEnable(),this._shape||(this._shape=this.context.physics.addBoxCollider(this.gameObject,this.isTrigger,this.center,this.size,this.attachedRigidbody))}};k([A(Jr)],Rn.prototype,"size",2),k([A(Jr)],Rn.prototype,"center",2);var gs=H("debugphysics"),Gv=H("debugcollisions"),Ta=class{mass=1;kinematic=!1;physicsEvents=!1;drag=0;angularDrag=.05;sleepThreshold=.01},Ra=Symbol("object"),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[Ra]=e)}},Re=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 Ee.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new Ee.Layers);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};z(Re,"AllLayers",4294967295);var Uc=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},Ca=class{raycaster=new Ee.Raycaster;defaultRaycastOptions=new Re;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new Ee.Layers;sphereOverlap(e,t){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let i=new Ee.Sphere(e,t),n=this.sphereMask;n.enableAll(),n.disable(2);for(let r of this.context.scene.children){let o=this.onSphereOverlap(r,i,n);o&&this.sphereResults.push(o)}return this.sphereResults.sort((r,o)=>r.distance-o.distance)}tempBoundingBox=new Ee.Box3;onSphereOverlap(e,t,i){if(e.type==="Mesh"){if(!e.layers.test(i))return null;let n=e,r=n.geometry;if(r.boundingBox||r.computeBoundingBox(),!r.boundingBox)return null;n.matrixWorldNeedsUpdate&&n.updateMatrixWorld();let o=this.tempBoundingBox.copy(r.boundingBox).applyMatrix4(n.matrixWorld);if(t.intersectsBox(o)){let c=q(e).distanceTo(t.center);return new Uc(e,c,t.center.clone())}}else if(e.children)for(let n of e.children){let r=this.onSphereOverlap(n,t,i);if(r)return r}return null}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 Ee.Layers?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 _a;objects=[];tempPosition=new Ee.Vector3;tempQuaternion=new Ee.Quaternion;constructor(e){if(this.context=e,this.world.gravity.set(0,-9.82,0),gs){let t={};t.onInit=(i,n,r)=>{n.layers.set(-1)},up(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=V.KINEMATIC:i.type=V.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),gs&&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 sr(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 Ea(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){gs&&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 Ee.Matrix4;tempMat2=new Ee.Matrix4;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=V.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=q(e);let l=r.position;o.x-=l.x,o.y-=l.y,o.z-=l.z,s=Ae(e);let h=new Ee.Quaternion(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 le(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,gs&&this.context.time.frameCount%60}temp=new Ee.Vector3;tempQuat=new Ee.Quaternion;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;i.sleepTick(this.context.time.time),gs&&(!t._didSleepLastStep&&i.sleepState===V.SLEEPING?console.log("BODY SLEEPING",i):t._didSleepLastStep&&i.sleepState!==V.SLEEPING&&console.log("BODY WOKE UP",i)),t._didSleepLastStep=i.sleepState===V.SLEEPING;let n=t.obj;if(i.type===V.KINEMATIC){let r=q(n,this.temp);i.position.set(r.x,r.y,r.z);let o=Ae(n,this.tempQuat);i.quaternion.set(o.x,o.y,o.z,o.w);continue}if(t.parent&&n.parent===t.parent){Jh(n,i.quaternion.x,i.quaternion.y,i.quaternion.z,i.quaternion.w);let r=i.position;zr(n,r.x,r.y,r.z),i.velocity.length()>i.sleepSpeedLimit&&ne.markDirty(n)}}this._isUpdatingPhysicsWorld=!1}internalCreateBody(e,t){let i=new V;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 le(r.x,r.y,r.z,r.w),i.type=V.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){}raiseCollisionEvents(e,t){let i=new vs(e,t);if(Gv&&console.log("collision between",t.contact.bi,t.contact.bj,e,t),C.foreachComponent(e,n=>{n.__internalHandleCollision(i,!1)}),i.collider&&!i.collider.attachedRigidbody&&i.collider.isTrigger){let n=new vs(i.gameObject,t,!0);C.foreachComponent(i.gameObject,r=>{r.__internalHandleCollision(n,!0)})}}onEndContact(e){let t=e.bodyA[Ra],i=e.bodyB[Ra];C.foreachComponent(i,r=>{r.__internalHandleExitCollisionEvent(t,!1)});let n=C.getComponent(t,mt);n&&!n.attachedRigidbody&&n.isTrigger&&C.foreachComponent(n.gameObject,r=>{r.__internalHandleExitCollisionEvent(i,!0)})}},vs=class{invert;collision;targetBody;me;_normal;get normal(){if(!this._normal){let e=this.collision.contact.ni;this._normal=new Uv(e.x,e.y,e.z)}return this._normal}_collider;get collider(){return this._collider===void 0&&(this._collider=C.getComponentInChildren(this.gameObject,mt)),this._collider}get gameObject(){return this.targetBody[Ra]}constructor(e,t,i=!1){this.invert=i,this.me=e,this.collision=t,this.targetBody=this.invert?t.target:t.body}};import{Clock as Wv}from"three";var Sa=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 Wv;_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 Xv}from"websocket-ts";function yp(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}var gt=class extends M{url=null;urlParameterName=null;localhost=null;getWebsocketUrl(){let e=this.url?gt.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=H(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=gt.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return yp(e)}};var fi=new Int32Array(2),Pa=new Float32Array(fi.buffer),Oa=new Float64Array(fi.buffer),Zr=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 ys;(function(a){a[a.UTF8_BYTES=1]="UTF8_BYTES",a[a.UTF16_STRING=2]="UTF16_STRING"})(ys||(ys={}));var mi=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new mi(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 fi[0]=this.readInt32(e),Pa[0]}readFloat64(e){return fi[Zr?0:1]=this.readInt32(e),fi[Zr?1:0]=this.readInt32(e+4),Oa[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){Pa[0]=t,this.writeInt32(e,fi[0])}writeFloat64(e,t){Oa[0]=t,this.writeInt32(e,fi[Zr?0:1]),this.writeInt32(e+4,fi[Zr?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===ys.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 bt=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=mi.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=bt.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=mi.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 Ep={};function eo(a,e){Ep[a]=e}function wp(a){let e=a.getBufferIdentifier(),t=Ep[e];return t(a)}function _p(a){return typeof a.guid=="function"?a.guid():null}var Wc=Fs(ka(),1);var Ia=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 Wc.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new Xc(t)})}trySetupClient(e){this._client=new Wc.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)})})}},qc=class{_peer;constructor(e){this._peer=e}};var Xc=class extends qc{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 Qc="wss://needle-tiny-starter.glitch.me/socket",vt=!!H("debugnet"),Ma=!!(vt||H("debugowner"));var Sn=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||(Ma&&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 Ma&&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?(Ma&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Ma&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}};var La=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Ia),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return vt}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(),vt&&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){vt&&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&&vt&&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)}connect(){if(this.connected)return;vt&&console.log("connecting");let t=C.findObjectOfType(gt,this.context,!1)?.getWebsocketUrl();t&&(Qc=t),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 "+Qc);let e=new Xv(Qc).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{vt&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new mi(i),r=n.getBufferIdentifier(),o=this._listenersBinary[r],s=wp(n),c=_p(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(vt&&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(vt&&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),vt&&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),vt&&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),vt&&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));vt&&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*as Kt from"three";import{OrbitControls as Qv}from"three/examples/jsm/controls/OrbitControls";import*as Es from"three";var $e=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 Es.Vector3,this._startedListeningToKeyEvents=!1}onEnable(){this._enableTime=this.context.time.time;let t=C.getComponent(this.gameObject,re)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new Qv(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"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):(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=C.getComponent(this.gameObject,re);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");let t=new Es.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new Re;e.screenPoint=new Es.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&&C.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=q(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};k([A()],$e.prototype,"lookAtConstraint",2);import{Color as Yv}from"three";var _e=class extends Yv{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=Y.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 Kv}from"three";var Tp=H("debugcam"),re=class extends M{get aspect(){return this._cam instanceof Kv?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 Kt.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(){Tp&&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 Kt.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new Kt.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 Yc(this)),this._skybox.enable()}};k([A()],re.prototype,"fieldOfView",1),k([A()],re.prototype,"nearClipPlane",1),k([A()],re.prototype,"farClipPlane",1),k([A()],re.prototype,"clearFlags",1),k([A()],re.prototype,"orthographic",2),k([A()],re.prototype,"orthographicSize",2),k([A()],re.prototype,"ARBackgroundAlpha",2),k([A(_e)],re.prototype,"backgroundColor",1);var Yc=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?(Tp&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Kt.sRGBEncoding,this._skybox.mapping=Kt.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};function Rp(a){let e="created/implictly",t=new Kt.Object3D;a.add(t);let i=C.addNewComponent(t,re,!1);i.sourceId=e;let n=C.addNewComponent(t,$e,!1);return n.sourceId=e,i}import{EffectComposer as xw}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as Tw}from"three/examples/jsm/postprocessing/RenderPass";import{AnimationClip as Zv,MathUtils as $v}from"three";var to=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 Cp(a,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??$v.generateUUID(),index:-1,clip:new Zv(a,1,[])}}import{AnimationClip as ey,AnimationMixer as ty,AxesHelper as iy,Euler as Sp,LoopOnce as ny,Quaternion as Jt,Vector3 as ws}from"three";import*as Ha from"three";var Pn=H("debuganimatorcontroller"),Kc=H("debugrootmotion"),$t=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){Pn&&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){Pn&&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 ty(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=ts(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 $t(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,Pn&&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()&&(Pn&&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 e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}let t=this._activeState,i=t.motion.action,n=0;for(let o of t.transitions){if(++n,!o.hasExitTime&&o.conditions.length<=0)continue;let s=!0;for(let c of o.conditions)if(!this.evaluateCondition(c)){s=!1;break}if(!!s){Pn&&s&&console.log("All conditions are met",o.conditions,i);for(let c of o.conditions){let d=this.model.parameters.find(l=>l.name===c.parameter);d?.type===9&&(d.value=!1)}if(i){let c=t.motion.clip.duration,d=c<=0?1:i.time/c;if(!o.hasExitTime||d>=o.exitTime&&i.time>=i.getClip().duration){i.clampWhenFinished=!0,Pn&&(console.log("transition to "+o.destinationState,o),console.log(i.time,o.exitTime)),this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.offset);return}break}}let r=!1;if(t.motion.isLooping&&i&&i.time>=i.getClip().duration&&(r=!0,i.reset(),i.time=0,i.play()),!r&&t&&!e&&i&&this.animator&&t.behaviours){let o=i?.getClip().duration,s=i.time/o,c=new to(this._activeState,s,o,this._speed);for(let d of t.behaviours)d.instance&&d.instance.onStateUpdate?.call(d.instance,this.animator,c,0)}}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(typeof e=="number"&&(e==-1&&(e=this.model.layers[n].stateMachine.defaultState),e=this.model.layers[n].stateMachine.states[e]),!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 to(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(ny,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 to(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);Pn&&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 Jc(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=Cp(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 ey;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=D.get(o.typeName),c=new s;c.isStateMachineBehaviour&&(c._context=this.context??void 0,ir(c,o.properties),o.instance=c),Pn&&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},Da=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}},Ce=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new ws;rotationChange=new Jt;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,Ce.firstKeyframeRotation[i.uuid]||(Ce.firstKeyframeRotation[i.uuid]=new Ha.Quaternion),r){let o=r.values;Ce.firstKeyframeRotation[i.uuid].set(o[0],o[1],o[2],o[3])}Ce.spaceRotation[i.uuid]||(Ce.spaceRotation[i.uuid]=new Jt),Ce.effectiveSpaceRotation[i.uuid]||(Ce.effectiveSpaceRotation[i.uuid]=new Jt),Ce.clipOffsetRotation[i.uuid]=new Jt,r&&Ce.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=Ce.lastObjRotation[this.root.uuid];Ce.spaceRotation[this.clip.uuid].copy(t);{let i=new Ha.Euler().setFromQuaternion(t);console.log("START",this.clip.name,Y.toDegrees(i.y))}}getClipRotationOffset(){return Ce.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;Kc&&i.add(new iy),Ce.lastObjPosition[i.uuid]||(Ce.lastObjPosition[i.uuid]=new ws);let n=new ws,r=new ws,o=0;this.positionWrapper=new Da(t,(s,c)=>{let d=this.action.getEffectiveWeight();if(Kc&&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(Ce.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(Kc){let s=t.values,c=new Sp().setFromQuaternion(new Jt(s[0],s[1],s[2],s[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",Y.toDegrees(c.y));let d=t.values.length-4,l=new Jt().set(s[d],s[d+1],s[d+2],s[d+3]),h=new Sp().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",Y.toDegrees(h.y))}let i=this.root;Ce.lastObjRotation[i.uuid]||(Ce.lastObjRotation[i.uuid]=new Jt);let n=0,r=new Jt,o=new Jt;this.rotationWrapper=new Da(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(Ce.identityQuaternion,1-e)}},Zt=Ce;z(Zt,"lastObjPosition",{}),z(Zt,"lastObjRotation",{}),z(Zt,"firstKeyframeRotation",{}),z(Zt,"spaceRotation",{}),z(Zt,"effectiveSpaceRotation",{}),z(Zt,"clipOffsetRotation",{}),z(Zt,"identityQuaternion",new Jt);var Jc=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 Zt(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 ws;summedRotation=new Jt;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),Zt.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 ry=H("debuganimator"),yt=class extends M{applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof $t?this._animatorController=e:this._animatorController=new $t(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=Y.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=Y.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}ry&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};k([A()],yt.prototype,"applyRootMotion",2),k([A()],yt.prototype,"hasRootMotion",2),k([A()],yt.prototype,"keepAnimatorControllerStateOnDisable",2),k([A()],yt.prototype,"runtimeAnimatorController",1);import*as io from"three";var ei=class extends M{playAutomatically=!0;randomStartTime=!0;_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 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}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 o=this.tryFindHandle(e);if(o)return o.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,t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0&&(e.loop=t.loop?io.LoopRepeat:io.LoopOnce),e.play();let r=new Zc(e,this.mixer,t,o=>{this._handles.splice(this._handles.indexOf(r),1)});return this._handles.push(r),r.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 io.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};k([A()],ei.prototype,"playAutomatically",2),k([A()],ei.prototype,"randomStartTime",2);var Zc=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 Zf}from"three/examples/jsm/loaders/GLTFLoader.js";import{Vector3 as oy}from"three";var On=class extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new oy}update(){if(!this.from||!this.to)return;let e=q(this.from).clone(),t=q(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ae(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(q(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};k([A(C)],On.prototype,"from",2),k([A(C)],On.prototype,"to",2);var gi=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};k([A()],gi.prototype,"time",2),k([A()],gi.prototype,"value",2),k([A()],gi.prototype,"inTangent",2),k([A()],gi.prototype,"inWeight",2),k([A()],gi.prototype,"outTangent",2),k([A()],gi.prototype,"outWeight",2),k([A()],gi.prototype,"weightedMode",2);var pr=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 Y.lerp(t.value,i.value,(e-t.time)/(i.time-t.time));t=i}return this.keys[this.keys.length-1].value}};k([A(gi)],pr.prototype,"keys",2);import*as Pp from"three";import*as _s from"three";import{PositionalAudioHelper as sy}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var ja=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}}};var lt=H("debugaudio");var je=class extends M{static get userInteractionRegistered(){return je._didCallBeginWaitForUserInteraction||(je._didCallBeginWaitForUserInteraction=!0,je._beginWaitForUserInteraction()),je._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),je._didCallBeginWaitForUserInteraction||(je._didCallBeginWaitForUserInteraction=!0,je._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!je._userInteractionRegistered){je._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&&(lt&&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&&je._userInteractionRegistered){let e=C.getComponent(this.context.mainCamera,ti)??C.findObjectOfType(ti,this.context);e?.listener&&(this.sound=new _s.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new _s.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&&je._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){je._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():je._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){lt&&console.log("audio buffer loaded"),je.registerWaitForAllowAudio(()=>{lt&&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(),lt&&console.log(this.name,this.shouldPlay,je.userInteractionRegistered,this),this.shouldPlay&&je._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(lt&&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?lt&&!this.helper&&(this.helper=new sy(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(lt&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new _s.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){lt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,lt&&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,lt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){lt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){lt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&(this._lastContextTime=this.sound?.context.currentTime,lt&&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,lt&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},de=je;z(de,"_didCallBeginWaitForUserInteraction",!1),z(de,"callbacks",[]),z(de,"_userInteractionRegistered",!1),k([A()],de.prototype,"clip",2),k([A()],de.prototype,"playOnAwake",2),k([A()],de.prototype,"loop",1),k([A()],de.prototype,"spatialBlend",1),k([A()],de.prototype,"minDistance",1),k([A()],de.prototype,"maxDistance",1),k([A()],de.prototype,"volume",1),k([A()],de.prototype,"rollOffMode",2);var ti=class extends M{get listener(){return this._listener==null&&(this._listener=new Pp.AudioListener),this._listener}_listener=null;awake(){de.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=C.getComponentInParent(this.gameObject,re);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as cy}from"three/examples/jsm/loaders/GLTFLoader";import*as Na from"three";var jp=Fs(Hp(),1),Ba=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 Bp(a,e){let t=await a.arrayBuffer(),i=Fp(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 Ba(!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 E=new Ba(f.success,r,i,a.size);return E.url=e,E}function Fp(a){return(0,jp.default)(new Uint8Array(a))}async function Fa(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=Fp(s);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),o.arrayBuffer()}catch(r){console.error(r)}return null}async function Np(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}var xs=H("debugavatar"),fr=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))}},An=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 be;i=C.instantiate(pn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(xs&&console.log("[Custom Avatar] valid config",t,xs?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,xs?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(xs&&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 Fa(t,t,0,"no url here go away",!0),!r)?null:(await no(e,r,null,0))?.scene??null}let i=new cy;return dr(i,e),new Promise((n,r)=>{let o=this.avatarRegistryUrl+"/"+t;i.load(o,async s=>{await za(e,o,s),n(s.scene)},s=>{xs&&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 Na.Vector3;new Na.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 fr(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 dy}from"three";var Ui=class extends M{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!ci)return;this._axes||(this._axes=new dy(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)}};k([A()],Ui.prototype,"length",2),k([A()],Ui.prototype,"depthTest",2),k([A()],Ui.prototype,"isGizmo",2);import*as Vp from"three";var ro=class extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=q(this.to).clone(),t=q(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=q(this.hint).clone();o.sub(r);let s=new Vp.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),ae(this.gameObject,h);let u=r.clone();u.sub(s),this.gameObject.lookAt(u)}};import*as Gi from"three";import*as bi from"three";var hy=new bi.BoxGeometry(1,1,1);function Va(a=null){let e=new bi.Color(a??14540253),t=new bi.EdgesGeometry(hy);return new bi.LineSegments(t,new bi.LineBasicMaterial({color:e}))}var py=H("gizmos"),Ua=class extends M{box=null;testBox=new Gi.Box3;_lastMatrixUpdateFrame=-1;isInBox(e){if(!!e){if(this.box||(this.box=new Gi.Box3),this.updateBox(!1),e.type==="Mesh")this.testBox.setFromObject(e);else{let t=q(e,Ua._position),i=Qs(e,Ua._size);this.testBox.setFromCenterAndSize(t,i)}return this.box?.intersectsBox(this.testBox)}}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){return this.box||(this.box=new Gi.Box3),(e||this.context.time.frameCount!=this._lastMatrixUpdateFrame)&&(this._lastMatrixUpdateFrame=this.context.time.frameCount,this.box.setFromCenterAndSize(new Gi.Vector3(0,0,0),new Gi.Vector3(1,1,1)),this.box.applyMatrix4(this.gameObject.matrixWorld)),this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!py&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Va(e),this.gameObject.add(this._helper)}}},ct=Ua;z(ct,"_position",new Gi.Vector3),z(ct,"_size",new Gi.Vector3(.01,.01,.01));var Dt=class extends M{canGrab=!0;onPointerClick(e){}},Ht=class extends M{isUsed=!0;usedBy=null};var mr=class extends ct{},oo=class extends M{deleteBoxes=[];awake(){this.deleteBoxes=C.findObjectsOfType(mr,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(C.getComponentInParent(this.gameObject,Ht)||Vr(this.gameObject,this.context.connection))}}};var gr=class extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||C.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:fy()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};k([A()],gr.prototype,"visibleOn",2);var Ga;function fy(){if(Ga===!0||Ga===!1)return Ga;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),Ga=a,a}import*as Wi 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 so=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 jt=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 jt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new jt).__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 so).__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 kn=H("debugsync"),ao="STRS";eo(ao,jt.getRootAsSyncedTransformModel);var vi=new bt;function td(a,e,t=!0){vi.clear();let i=vi.createString(a);jt.startSyncedTransformModel(vi),jt.addGuid(vi,i),jt.addFast(vi,t);let n=e.worldPosition,r=e.worldEuler,o=e.gameObject.scale;jt.addTransform(vi,so.createTransform(vi,n.x,n.y,n.z,r.x,r.y,r.z,o.x,o.y,o.z));let s=jt.endSyncedTransformModel(vi);return vi.finish(s,ao),vi.asUint8Array()}var Qe=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(){kn&&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(){kn&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Wi.Vector3,this._targetRotation=new Wi.Quaternion,this.lastWorldPos=new Wi.Vector3,this.lastWorldRotation=new Wi.Quaternion,this.rb=C.getComponentInChildren(this.gameObject,ce),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Sn(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(ao,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&ru(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(ao,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Wi.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){kn&&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 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)&&Zh(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){kn&&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:(kn&&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 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&&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&&(kn&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Wi.Vector3(0,0,0))>1e3&&(kn&&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)){kn&&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=td(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as ee from"three";var Wa=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(E){E.addEventListener("end",f),await e.xr.setSession(E),i.textContent="STOP AR",t.domOverlay.root.style.display="",h=E}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 qa=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(),qa.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"),qa.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},co=qa;z(co,"xrSessionIsGranted",!1);co.registerSessionGrantedListener();import*as we from"three";import{Matrix4 as Ty,Vector3 as Ry}from"three";import*as Xa from"three";var Up=Fs(ka(),1);import{AudioAnalyser as gy}from"three";var ho="noVoip",dt=H("debugvoip"),by=H("voip");var id=class{id;constructor(e){this.id=e}};var nd=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(){dt&&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 et.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}dt&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),dt&&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=>{dt&&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){dt&&console.log("call closed",e)}},rd=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,de.userInteractionRegistered||dt&&console.log("Incoming call, waiting for user interaction before opening audio"),de.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){dt&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new Xa.AudioListener;this.audio=new Xa.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}}}),dt&&console.log("call is setup, you should hear something now"),this.analyzer=new gy(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()}},et=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(H(ho)){console.log("VOIP is disabled by url parameter: "+ho);return}if(this.requireParam&&!by){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Up.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 nd(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];dt&&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){dt&&console.log("Peer connection established and received id"),this.model=new id(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){dt&&console.log("CONNECTION",t),t.on("data",function(i){dt&&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(),dt&&console.log("received call"),await et.HasMicrophonePermissions()){let o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(o)}else e.answer(null);this.currentIncomingCalls[i]=new rd(this,this.gameObject,e),e.on("stream",o=>{dt&&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"}};var uo=H("debugflags");var od=class{Mask=17;Has(e){let t=this.Mask&e;return uo&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,Pe.Apply()}Enable(e){this.Mask|=e,Pe.Apply()}Disable(e){this.Mask&=~e,Pe.Apply()}Toggle(e){this.Mask^=e,Pe.Apply()}EnableAll(){this.Mask=-1,Pe.Apply()}DisableAll(){this.Mask=0,Pe.Apply()}},Et=od;z(Et,"Global",new od);var yi=class extends M{static Apply(){for(let e of this.registry)e.UpdateVisible(Et.Global)}awake(){yi.registry.push(this)}onEnable(){yi.firstApply||(yi.firstApply=!0,yi.Apply())}onDestroy(){let e=yi.registry.indexOf(this);e>=0&&yi.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),uo&&console.log(i),yi.buffer.Mask=i,e=yi.buffer);let n=e;if(n?(uo&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(uo&&console.log("use global mask"),Et.Global.Has(this.visibleIn)),t!==void 0)if(t)uo&&console.trace("is visible",this.name,this.gameObject.uuid),C.setActive(this.gameObject,!0);else{if(uo&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},Pe=yi;z(Pe,"registry",[]),z(Pe,"firstApply"),z(Pe,"buffer",new Et);import*as $ from"three";import{XRControllerModelFactory as yy}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{OculusHandModel as Ey}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as wy}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import*as qp from"three";import*as ni from"three";var vy=H("debugplayerview");var sd=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}},Qa=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new sd(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&&(vy&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}};var In=H("debugavatar"),ii=class extends M{static getAvatar(e){return e>=0&&e<ii.instances.length?ii.instances[e]:null}static onAvatarMarkerCreated(e){return ii._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return ii._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){ii.instances.push(this),In&&console.log(this);for(let e of ii._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){ii.instances.splice(ii.instances.indexOf(this),1);for(let e of ii._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):C.setActive(this.avatar,e))}},ue=ii;z(ue,"instances",[]),z(ue,"_onNewAvatarMarkerAdded",[]),z(ue,"_onAvatarMarkerDestroyed",[]);var Ts=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 ni.Vector3(1,1,1);handLeftScale=new ni.Vector3(1,1,1);handRightScale=new ni.Vector3(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 ni.Object3D;_handLeftTarget=new ni.Object3D;_handRightTarget=new ni.Object3D;_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),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 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(Ts.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.scale.multiply(this.handLeftScale),ne.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(Ts.invertRotation),o.scale.set(e.scale,e.scale,e.scale),o.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(){In&&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&&C.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(In&&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;C.setActive(n,!1),e=C.instantiate(n),C.setActive(e,!0)}In&&console.log(e);let i=await Ts.loader.getOrCreateNewAvatarInstance(this.context,e);if(In&&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=C.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(...C.getComponentsInChildren(this.root,Pe)),this.flags.length<=0&&this.head){let n=C.addNewComponent(this.head,Pe);n.visibleIn=20,this.flags.push(n),In&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return In&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return In&&console.warn("build avatar failed"),!1}},Bt=Ts;z(Bt,"loader",new An),z(Bt,"invertRotation",new ni.Quaternion().setFromAxisAngle(new ni.Vector3(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??Q.Current?.time.time;return}}}};z(xe,"Pois",[]),z(xe,"LastChangeTime",0);var ad=class{guid;position=new qp.Vector3},qi=class extends M{set controlledTarget(e){this.target=e;let t=D.get("MoveRandom");if(t&&this.target){let i=C.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new ad;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=C.getComponentInParent(this.gameObject,ue),this.avatar){let e=C.getComponentInParent(this.gameObject,ue);this._model=new Sn(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&&ae(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=q(this._currentTargetObject);ae(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}}}}};var Ya=H("debugwebxrcontroller");var br=class extends M{},Be=class extends M{static CreateRaycastLine(){let e=new $.Line(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(1),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new $.SphereGeometry(.5,22,22),t=new $.MeshBasicMaterial({color:this.raycastColor}),i=new $.Mesh(e,t);return i.visible=!1,i.layers.set(1),i}static Create(e,t,i,n){let r=i?C.addNewComponent(i,Be,!1):new Be;r.webXR=e,r.index=t,r.type=n;let o=e.context;return 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),r.hand.add(new Ey(r.hand)),r.hand.traverse(s=>s.layers.set(2)),r.handPointerModel=new wy(r.hand,r.controller),r.controller.addEventListener("connected",s=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),setTimeout(()=>{r.setControllerLayers(r.controllerGrip,2)},1e3)}),r.hand.addEventListener("connected",s=>{if(s.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(l=>l.layers.set(2)),r.handPointerModel.pointerObject?.traverse(l=>l.layers.set(2));let d=r.hand.joints;if(d)for(let l of Object.keys(d)){let h=d[l];h.parent||r.hand.add(h)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),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 $.Quaternion),Ae(e).multiply(this._wristQuaternion.setFromEuler(new $.Euler(-Math.PI/4,0,0)))):null}movementVector=new $.Vector3;worldRot=new $.Quaternion;joystick=new $.Vector2;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),Ya&&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 $.Quaternion;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(Ae(this.controller),this.useSmoothing?t:1);let i=q(this.controller);if(this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,ae(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)}ot(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=!0,ot(this.raycastLine,this.rayRotation),ae(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=Y.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(Y.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;ae(e,d)}}}}else i<.1&&(this.didTeleport=!1);o!==null&&(e.scale.set(o,o,o),e.updateMatrixWorld())}isValidTeleportTarget(e){return C.getComponentInParent(e,br)!=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=Y.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(),e&&e.length>0)for(let i of e){let n=i.object;if(!this.testIsVisible(n)){Ya&&console.log("not visible");continue}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&&Ya&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=ht.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?C.isActiveInHierarchy(e):!0}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 $.Ray;return e.origin.copy(q(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(!e)return new Array;let t=q(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new Re;return e.layerMask=new $.Layers,e.layerMask.set(0),e.ray=this.getRay(),this.context.physics.raycast(e)}},se=Be;z(se,"Factory",new yy),z(se,"raycastColor",new $.Color(.9,.3,.3)),z(se,"raycastNoHitColor",new $.Color(.6,.6,.6)),z(se,"geometry",new $.BufferGeometry().setFromPoints([new $.Vector3(0,0,0),new $.Vector3(0,0,-1)])),z(se,"handModels",{}),z(se,"eventSubs",{}),z(se,"PreviousCameraFarDistance"),z(se,"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=C.getComponentInParent(t,Dt);if(!r)return Ya&&console.warn("Prevented taking object that is not interactable",t),null;let o=t,s=C.getComponentInParent(t,Qe);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=C.addNewComponent(this.selected,Ht),this.rigidbodies=C.getComponentsInChildren(this.selected,ce),q(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();Ae(this.selected,this.localQuaternionToGrab).premultiply(h.invert());let u=this.controller.webXR.Rig;return u&&this.rigPositionLastFrame.copy(q(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 $.Vector3;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new $.Vector3;localQuaternionToGrab=new $.Quaternion(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new $.Vector3;controllerWorldPos=new $.Vector3;lastControllerWorldPos=new $.Vector3;controllerPosDelta=new $.Vector3;totalChangeAlongDirection=0;rigPositionLastFrame=new $.Vector3;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),q(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=q(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 $.Vector3),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),ot(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(q(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),ae(this.selected,i)}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)}}},ht=tt;z(ht,"Events",{}),z(ht,"Current",[]);import*as po from"three";var Ft=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 po.Matrix4;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=C.findObjectOfType(K);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 po.Matrix4().fromArray(i.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new po.Matrix4),this._placementPose.copy(t),e){if(this.invertForward){let i=new po.Matrix4().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)),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 po.Matrix4().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};k([A()],Ft.prototype,"invertForward",2),k([A()],Ft.prototype,"arScale",1);var Mn=class extends M{awake(){}};import{Object3D as _y}from"three";var vr=H("debugaddressables"),Ka=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}},it=class{static getOrCreate(e,t,i){let n=mn(e,t);vr&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,o=r.findAssetReference(n);if(o)return o;let s=new it(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,lu(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&&(vr&&console.log("Unload",this.asset),this.asset.scene?C.destroy(this.asset.scene):C.destroy(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,vr&&console.log("Preload",this.uri);let e=await Np(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=Q.Current;this._rawBinary?(this._loading=no(t,this._rawBinary,this.uri,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))):(vr&&console.log("Load async",this.uri),this._loading=yr(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 Di(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=Q.Current;if(e||(e=n.scene),this.mustLoad&&await this.loadAssetAsync(),vr&&console.log("Instantiate",this.uri,"parent:",e),this.asset){vr&&console.log("Add to scene",this.asset);let r=e instanceof be?e:null;if(r||(r=new be),typeof e=="object"&&(e instanceof _y?r.parent=e:Object.assign(r,e)),t){r.context=n;let o=this.asset;o.guid=this.uri;let s=$s(o,r,void 0,i);if(s)return s}else{let o=C.instantiate(this.asset,r);if(o)return o}}else vr&&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}},ld=class extends Hi{constructor(){super([it])}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?it.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new ld;import*as wt from"three";var Ei=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 Ie=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 Ie).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Ie).__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 Ei).__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 Ei).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new Ei).__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 Xp=H("debugxr"),Rs=H("debugavatar");var dd="VRUS";eo(dd,Ie.getRootAsVrUserStateBuffer);function cd(){return new Date().getTime()}function xy(a){let e=a&4294967295,t=a/Math.pow(2,32)&1048575;return Xe.create(e,t)}var Cs=class{guid;time;avatarId;position=new wt.Vector3;rotation=new wt.Vector4;scale=1;posLeftHand=new wt.Vector3;posRightHand=new wt.Vector3;rotLeftHand=new wt.Quaternion;rotRightHand=new wt.Quaternion;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=cd(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let o=Cs.quat0,s=Cs.quat1;o.set(i.x,i.y,i.z,i.w),o=o.multiplyQuaternions(o,Cs.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);Ie.startVrUserStateBuffer(e),Ie.addGuid(e,i),Ie.addTime(e,xy(this.time)),Ie.addAvatarId(e,n),Ie.addPosition(e,Se.createVec3(e,this.position.x,this.position.y,this.position.z)),Ie.addRotation(e,Ei.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Ie.addScale(e,this.scale),Ie.addPosLeftHand(e,Se.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Ie.addPosRightHand(e,Se.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Ie.addRotLeftHand(e,Ei.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Ie.addRotRightHand(e,Ei.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Ie.endVrUserStateBuffer(e);e.finish(r,dd);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()}},Nt=Cs;z(Nt,"invertRotation",new wt.Quaternion().setFromAxisAngle(new wt.Vector3(0,1,0),Math.PI)),z(Nt,"quat0",new wt.Quaternion),z(Nt,"quat1",new wt.Quaternion);var Xi=class extends M{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=this.gameObject.getComponent(K)),this.webXR||(this.webXR=C.findObjectOfType(K,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=C.findObjectOfType(K,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=C.findObjectOfType(et,this.context)),Rs){let e="debug-avatar-"+Rs,t=new Bt(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof Rs=="string"&&Rs.length>0)if(await t.setAvatarOverride(Rs)){let i=new Nt(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=C.getComponent(this.gameObject,K),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),K.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),K.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),K.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(dd,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 Nt("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return Xp&&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 Bt(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),K.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),K.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),K.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=cd();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=cd();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 Bt(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(){Xp&&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 bt(1024);onXRSessionUpdate(e){this.xrState??=new Nt(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new Sn(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 H("avatar")??null}};async function Cy(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function Sy(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var hd=!1,ud=!1;Cy().then(a=>hd=a);Sy().then(a=>ud=a);var Fe=class extends M{enableVR=!0;enableAR=!0;defaultAvatar;createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(hd||ud)}static get IsARSupported(){return hd}static get IsVRSupported(){return ud}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){Fe.XRSupported||console.warn("WebXR is not supported on this device");let i=co.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=Wa.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),Fe.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=it.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!C.findObjectOfType(Xi,this.context)){let e=C.addNewComponent(this.gameObject,Xi,!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 Ln(this);let e=Fe.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=Fe.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(e||!this.enableAR)&&(i=Fe.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{Fe.resetButtonStyles(i),Fe.resetButtonStyles(t)},1e3)}_transformOrientation=new we.Quaternion;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)}Fe._isInXr===!1&&t&&this.onEnterXR(t,e),Fe.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++)se.Create(this,e,this.gameObject,0);Fe.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(q(this.context.mainCamera)),this._originalCameraRotation.copy(Ae(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=C.findObjectOfType(Mn,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new we.Group,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new we.Vector3;_originalCameraRotation=new we.Quaternion;onEnterXR(e,t){console.log("[XR] session begin",e),Fe._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 we.Quaternion(s.x,s.y,s.z,s.w),d=new we.Euler().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(Et.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"),Fe._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),Fe.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),ae(this.context.mainCamera,this._originalCameraPosition),ot(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),Et.Global.Set(17),Fe.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){!H("mirror")||setTimeout(()=>{if(!Fe.IsInWebXR)return;let t=new URL(window.location.href);Nr(t.searchParams,ho,1),Nr(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=()=>{Fe.IsInWebXR&&e.end()})})},1e3)}},K=Fe;z(K,"_isInXr",!1),z(K,"events",new we.EventDispatcher),k([A(it)],K.prototype,"defaultAvatar",2);var fo=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(){return this.arDomOverlay=this.webxr.context.domElement,this.arOverlayElement=this.arDomOverlay.getAROverlayContainer(),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;for(let n=0;n<4;n++)se.Create(this.webxr,n,this.webxr.gameObject,i);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=C.findObjectOfType(Ft,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(n=>{e.requestHitTestSource({space:n}).then(r=>{this.hitTestSource=r}).catch(r=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported")})}),!this.reticle&&this.sessionRoot&&(this.reticle=new we.Mesh(new we.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new we.MeshBasicMaterial),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,fo.tempWebXRObject||(fo.tempWebXRObject=new we.Object3D),this.context.scene.add(fo.tempWebXRObject),C.addComponent(fo.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene"),this.arDomOverlay&&this.arOverlayElement&&this.arDomOverlay.onEnterAR(e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),C.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay&&this.arDomOverlay.onExitAR(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=Py.clone();if(n){let o=new Ry(0,0,0).add(n.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new Ty().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)}},Ln=fo;z(Ln,"tempWebXRObject");var Py=new we.Matrix4().identity().makeTranslation(0,-.5,0);var pd=!1;var mo=class extends Dt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;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(){}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||K.IsInWebXR)return;let t=C.getComponentInParent(e.object,mo);!t||t!==this||(mo.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||K.IsInWebXR||mo.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||K.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(K.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!K.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&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new Ja(this.context.mainCamera);else return;if(!e||!e.object)return;let t=C.getComponentInParent(e.object,mo);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);let r=C.getComponentInChildren(i,Qe);pd&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=C.addNewComponent(i,Ht),this._draggingRigidbodies.length=0;let o=C.getComponentsInChildren(i,ce);o&&this._draggingRigidbodies.push(...o);let s=Fl();C.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(pd&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),e?.object){let n=C.getComponentInChildren(e.object,Qe);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=Fl();C.invokeOnChildren(t,i("onDragEnd"))}},_t=mo;z(_t,"_active",null),z(_t,"lastHovered");var md=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(md.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=C.getComponentsInChildren(this._selected,ce),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)){pd&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=q(this._camera).clone().sub(q(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 E=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(E,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=q(this._selected);n.y=e.y,e=n}if(ae(this._selected,e),ae(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=q(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),ae(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=q(this._selected),t=new ee.Ray(new ee.Vector3(0,.1,0).add(e),new ee.Vector3(0,-1,0)),i=new Re;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(){ne.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}},Ja=md;z(Ja,"geometry",new ee.BufferGeometry().setFromPoints([new ee.Vector3(0,0,0),new ee.Vector3(0,-1,0)]));var Dn=class extends M{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?gt.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 Yp(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 Kp(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 Re;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}))}};k([A()],Dn.prototype,"filesBackendUrl",2),k([A()],Dn.prototype,"localhost",2);import{Vector3 as Ay,Quaternion as ky,Object3D as Jp}from"three";var wi=class extends Dt{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 Ay(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new ky(0,0,0,1)}let e=C.getComponentInParent(this.gameObject,_t);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),se.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 be;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=C.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}};k([A(Jp)],wi.prototype,"parent",2),k([A(Jp)],wi.prototype,"object",2),k([A()],wi.prototype,"limitCount",2),k([A()],wi.prototype,"limitInterval",2);var _i=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)}}},Iy=a=>/^[A-Z]*$/.test(a),Er=class extends Event{args},Oe=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&&Iy(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 Er(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new _i(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 go=class extends M{};import{FlyControls as My}from"three/examples/jsm/controls/FlyControls";var bo=class extends M{_controls=null;onEnable(){let e=C.getComponent(this.gameObject,re)?.cam;this._controls=new My(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 $p from"three";import{Color as Ly}from"three";var Qi=class extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!ci||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new $p.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Va(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}};k([A()],Qi.prototype,"objectBounds",2),k([A(Ly)],Qi.prototype,"color",2),k([A()],Qi.prototype,"isGizmo",2);import{GLTFExporter as By}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as gd,Matrix4 as Dy,Vector3 as ef,Quaternion as Hy}from"three";var Ss=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 Dy,s=new Array,c=new Array,d=new Array;for(let f=0;f<e.count;f++){e.getMatrixAt(f,o);let E=new ef,b=new Hy,y=new ef;o.decompose(E,b,y),s.push(E.x,E.y,E.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 gd(l,3)),ROTATION:i.processAccessor(new gd(h,4)),SCALE:i.processAccessor(new gd(u,3))},n[this.name]=!0}};import{Object3D as Fy,Vector3 as Ny}from"three";var Hn=ke,Za="$___Export_Components",jy="NEEDLE_components",bd=class{[Zn]},vd=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},vo=class{get name(){return jy}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[Za]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Hn&&console.log("DONE",JSON.stringify(t)),e[Za]===void 0)return;let i=e[Za];delete e[Za],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 vd(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Hn&&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 bd;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=tf(l,this.context);h!==null&&d.push(h)}d.length>0&&(c[Zn]=d,Hn&&console.log("DID WRITE",n,"nodeIndex",o,d))}}beforeRoot(){return Hn&&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];Hn&&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;Hn&&console.log("NODE",c);let u=this.nodeToObjectMap[d];if(!u){console.error("Could not find object for node index: "+d,c,t);continue}ia(u),r.push(this.createComponents(u,h))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Zn];if(i){Hn&&console.log(e.name,i);for(let n in i){let r=i[n];Hn&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await Ur(this.parser,r),e.userData=e.userData||{},e.userData[Zn]=e.userData[Zn]||[],e.userData[Zn].push(r)}}}};var yo=class extends ct{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},zt=class extends M{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:zt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?zt.saveArrayBuffer(i,e):zt.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 By,this.exporter.register(s=>new Ss(s)),this.ext=new vo,this.ext.registerExport(this.exporter)),zt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:zt.collectAnimations(e)},n=new Fy;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),C.getComponentsInChildren(s,ye).forEach(c=>{C.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new Gr(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,C.getComponentsInChildren(s,ye).forEach(c=>{C.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 Ny;return i.set(0,0,0),e.forEach(n=>{i.add(q(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 $a,GridHelper as zy}from"three";var Yi=class extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!ci)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new zy(e,t,this.color0??new $a(.4,.4,.4),this.color1??new $a(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};k([A()],Yi.prototype,"isGizmo",2),k([A($a)],Yi.prototype,"color0",2),k([A($a)],Yi.prototype,"color1",2);import{GroundProjectedEnv as Vy}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Ki=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.updateProjection(),this._watcher||(this._watcher=new fn(this.context.scene,"environment"),this._watcher.subscribeWrite(this.updateProjection.bind(this))),this._watcher.apply()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateProjection(){!this.context.scene.environment||((!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new Vy(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))}};k([A()],Ki.prototype,"scale",1),k([A()],Ki.prototype,"radius",1),k([A()],Ki.prototype,"height",1);import*as nt from"three";import{Color as Uy}from"three";function yd(a){return a*Math.PI/180}var nf=300,rf=H("debuglights");var Ye=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=K.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=K.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){K.removeEventListener("xrStarted",this._webXRStartedListener),K.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=this.gameObject.getComponentInParent(Ft)??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,-nf*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),zr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),rf){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,yd(this.spotAngle/2),1-yd(this.innerSpotAngle/2)/yd(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=nf*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,rf&&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)}};k([A()],Ye.prototype,"type",2),k([A(Uy)],Ye.prototype,"color",2),k([A()],Ye.prototype,"shadowNearPlane",1),k([A()],Ye.prototype,"shadowBias",1),k([A()],Ye.prototype,"shadowNormalBias",1),k([A()],Ye.prototype,"shadows",1),k([A()],Ye.prototype,"lightmapBakeType",2),k([A()],Ye.prototype,"intensity",1),k([A()],Ye.prototype,"shadowDistance",1),k([A()],Ye.prototype,"shadowResolution",1);var nk=new nt.Vector3(0,0,0);import*as el from"three";import{Vector3 as Gy}from"three";var Eo=H("debugLODs"),Wy=H("noLODs");var xi=class{screenRelativeTransitionHeight;distance;renderers};k([A()],xi.prototype,"screenRelativeTransitionHeight",2),k([A()],xi.prototype,"distance",2),k([A()],xi.prototype,"renderers",2);var Ed=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):Eo&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=C.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}},jn=class extends M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!Wy&&!this._lodsHandler&&!!this.gameObject&&(Eo&&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 Ed(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 el.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new el.Object3D;Eo&&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;Eo&&console.log(n,s.name);for(let h of this._lods){let u=null;h.renderers.includes(r)?u=s:u=i,Eo&&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;Eo&&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}}}};k([A(Gy)],jn.prototype,"localReferencePoint",2),k([A(xi)],jn.prototype,"lodModels",2);import{Object3D as qy}from"three";var wr=class extends M{constraintActive=!0;locked=!1;sources=[]};k([A(qy)],wr.prototype,"sources",2);var wo=class extends M{},_o=class extends M{};var wd=H("debugnestedgltf"),_r=class extends M{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;wd&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new be;t.idProvider=new Ue(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;wd&&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(),wd&&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}};k([A(it)],_r.prototype,"filePath",2);import{Quaternion as Xy,Euler as Qy,Vector3 as xr,Plane as Yy}from"three";var Ti=class extends M{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=q(this.from),t=Ae(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 Yy(this.gameObject.up,0),c=q(this.referenceSpace);s.setFromNormalAndCoplanarPoint(this.gameObject.up,c);let d=new xr(0,0,0);s.projectPoint(e,d),e.copy(d)}this.affectPosition&&ae(this.gameObject,e);let n=new Qy(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new Xy().setFromEuler(n);this.affectRotation&&ot(this.gameObject,t.multiply(r));let o=new xr;this.from.getWorldDirection(o).multiplyScalar(50),this.levelLookDirection&&(o.y=0),this.alignLookDirection&&this.gameObject.lookAt(o)}};k([A(C)],Ti.prototype,"referenceSpace",2),k([A(C)],Ti.prototype,"from",2),k([A(xr)],Ti.prototype,"positionOffset",2),k([A(xr)],Ti.prototype,"rotationOffset",2);import*as Te from"three";import*as ri from"three";var xo=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 ri.Color(1,1,1);startColor1=new ri.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 ri.Vector2(0,1);cullingMode=0},To=class{burstCount=0;enabled=!0;rate=10;rateMutliplier=1;rateOverDistance=0;rateOverDistanceMultiplier=0;rateOverTime=0;rateOverTimeMultiplier=0},Ro=class{shapeType=_d.Box;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;box=new ri.Vector3(1,1,1);boxThickness=new ri.Vector3(0,0,0);position=new ri.Vector3(0,0,0);rotation=new ri.Vector3(0,0,0);scale=new ri.Vector3(1,1,1);radius=1;sphericalDirectionAmount=0},_d=(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))(_d||{});var Jy=H("debugparticles"),xd=class{age=0;lifetime=0;position;velocity;color},Tr=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(){Jy&&console.log(this)}},Co=class extends M{main;emission;shape;renderer;geometry;material;particlesMesh;positions;positionsArray;particleStates=[];activeCount=0;shapeRotation=new Te.Quaternion;tempVec3=new Te.Vector3;tempQuat=new Te.Quaternion;awake(){this.renderer=C.getComponent(this.gameObject,Tr),console.log(this)}onEnable(){if(this.geometry)return;this.particleStates=[],this.shapeRotation.setFromEuler(new Te.Euler(this.shape.rotation.x,this.shape.rotation.y,this.shape.rotation.z)),this.geometry=new Te.BufferGeometry,this.positionsArray=new Float32Array(this.main.maxParticles*3),this.positions=new Te.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 Te.Float32BufferAttribute(e,3);this.geometry.setAttribute("color",t),this.material=new Te.PointsMaterial({size:this.main.startSize,color:16777215,vertexColors:!0}),this.material.map=this.renderer.mainTexture,this.particlesMesh=new Te.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 xd;r.lifetime=this.main.startLifetime??1,r.position=new Te.Vector3,r.velocity=new Te.Vector3,r.color=new Te.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 Te.Vector3(0,1,0);t.copy(i);break;case 10:this.tempQuat.setFromAxisAngle(this.tempVec3.set(0,0,1),Math.random()*Y.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 sf from"three";function*of(a,e=null){let t=e?e.time:Q.Current.time,i=t.time;for(;t.time-i<a;)yield}var ut=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 of(.2),!this.tryAssignColor()););}tryAssignColor(){let e=C.getComponentInParent(this.gameObject,ue);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ut.hashCode(e),i=ut.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 sf.Color(t/255,i/255,n/255)}};import*as tl from"three";import{Object3D as $y,Texture as eE}from"three";function Zy(){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 af(a){await Zy(),a()}var Td=H("debugvideo");var Me=class extends M{renderer=null;playOnAwake=!0;playOnEnable;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"))}_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.create(!0)}setClipURL(e){this.url!==e&&(this.url=e,this.source=1,Td&&console.log("set url",e),this.videoElement?(this.videoElement.src=e,this._isPlaying&&this.videoElement.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)}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(),af(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[]}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)}),Td&&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}!t||(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"?this.videoElement.src=t:this.videoElement.srcObject=t,this.videoTexture||(this.videoTexture=new tl.VideoTexture(this.videoElement)),this.videoTexture.flipY=!1,this.videoTexture.encoding=tl.sRGBEncoding,this.handleBeginPlaying(e))}_targetObjects;getTargetObjects(){return Array.from(this._targetObjects)}createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),Td&&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;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);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")}};k([A($y)],Me.prototype,"renderer",2),k([A()],Me.prototype,"playOnAwake",2),k([A()],Me.prototype,"playOnEnable",2),k([A()],Me.prototype,"renderMode",2),k([A()],Me.prototype,"targetMaterialProperty",2),k([A(ye)],Me.prototype,"targetMaterialRenderer",2),k([A(eE)],Me.prototype,"targetTexture",2),k([A()],Me.prototype,"time",2),k([A()],Me.prototype,"playbackSpeed",1),k([A()],Me.prototype,"isLooping",1);var cf=Fs(ka(),1);import*as lf from"three";import{Color as tE,Object3D as iE}from"three";var Cd=class extends Hi{constructor(){super([tE,_e])}onDeserialize(e){if(e!=null)return e.a!==void 0?new _e(e.r,e.g,e.b,e.a):e.alpha!==void 0?new _e(e.r,e.g,e.b,e.alpha):new lf.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}}},l1=new Cd,Sd=class extends Hi{constructor(){super(iE)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return ke&&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 ke&&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=C.findByGuid(e.guid,n)),i||(i=C.findByGuid(e.guid,t.context.scene)),i?ke&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},nE=new Sd,Pd=class extends Hi{constructor(){super([st,M])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){ke&&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=C.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}}},Rd=new Pd,Od=class extends Hi{constructor(){super([Oe])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){ke&&console.log("DESERIALIZE EVENT",e);let i=new Array;for(let o of e.calls){ke&&console.log(o);let s=Rd.findObjectForGuid(o.target,t.root);!s&&t.context?.scene&&(s=Rd.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=nE.onDeserialize(o.argument,t),l||(l=Rd.onDeserialize(o.argument,t))),d=new _i(c?(...u)=>h(...u):void 0,o.enabled)):d=new _i(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 Oe(i);ke&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},c1=new Od;import{EventDispatcher as Ld}from"three";var oE=H("debugscreenshare");function il(a){if(!!a)for(let e of a.getTracks())e.stop()}var Ji=class extends M{onPointerClick(){if(!this.isReceiving){if(this.isSending){this.close();return}this.share()}}videoPlayer;device=0;aspectMode=1;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(){console.log(this),de.registerWaitForAllowAudio(()=>{this.videoPlayer&&this._currentStream&&this._currentMode===2&&this.videoPlayer.setVideo(this._currentStream)})}start(){if(this.videoPlayer||(this.videoPlayer=C.getComponent(this.gameObject,Me)??void 0),!this.videoPlayer){console.error("Screencapture did not find a VideoPlayer component");return}let e=nl.getOrCreate(this.context,this.guid);this._net=new Md(this.context,e),this._net.enable(),this._net.addEventListener(df.ReceiveVideo,this.onReceiveVideo.bind(this))}async share(){this._requestOpen=!0;try{if(this.videoPlayer){let e={echoCancellation:!0,autoGainControl:!1},t={video:e,audio:e};switch(this.device){case 1:this.tryShareUserCamera(t);break;case 0:if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}let i=await navigator.mediaDevices.getDisplayMedia(t);this._requestOpen?this.setVideo(i,1):il(i);break;case 2:let n=0,r=this.context.renderer.domElement.captureStream(n);this.setVideo(r,1);break}}}catch(e){if(e.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",e)}}close(){this._requestOpen=!1,this._currentStream&&(console.warn("Close current stream / disposing resources"),this._net?.stopSendingVideo(this._currentStream),il(this._currentStream),this._currentMode=0,this._currentStream=null)}setVideo(e,t){e!==this._currentStream&&(this.close(),!(!e||!this.videoPlayer)&&(this._currentStream=e,this._requestOpen=!0,this._currentMode=t,this.videoPlayer.setVideo(e),t===1&&this._net?.startSendingVideo(e),this._targetObjects=void 0,this.updateAspect()))}onReceiveVideo(e){this.setVideo(e.stream,2)}async tryShareUserCamera(e){let t=(await navigator.mediaDevices.enumerateDevices()).filter(i=>i.kind==="videoinput");console.log("Request camera",t);for(let i of t)try{if(!this._requestOpen)break;if(i.kind!=="videoinput")continue;let n=i.deviceId;e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=n);let r=await navigator.mediaDevices.getUserMedia(e);this._requestOpen?this.setVideo(r,1):il(r),console.log("Selected camera",i);break}catch(n){console.warn(n)}}_targetObjects;updateAspect(){this.startCoroutine(this.updateAspectImpl())}_updateAspectRoutineId=-1;*updateAspectImpl(){let e=++this._updateAspectRoutineId,t=void 0;for(;this.aspectMode!==0&&this._currentStream&&e===this._updateAspectRoutineId;){let i=this.videoPlayer,n=this._currentStream;if(!i||!n)return;let r;for(let o of n.getVideoTracks()){let s=o.getSettings();if(s&&s.width&&s.height){r=s.width/s.height;break}else this.device===2&&(r=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight)}if(r===void 0){yield;continue}if(t===r){yield;continue}this._targetObjects||(this._targetObjects=i.getTargetObjects());for(let o of this._targetObjects){let s=1;if(o.parent){let c=Qs(o.parent);s=c.x/c.y}switch(this.aspectMode){case 1:o.scale.y=1/r*o.scale.x*s;break;case 2:o.scale.x=r*o.scale.y*s;break}}for(let o=0;o<3;o++)yield}}};k([A(Me)],Ji.prototype,"videoPlayer",2),k([A()],Ji.prototype,"device",2),k([A()],Ji.prototype,"aspectMode",2);var df=(i=>(i.Connected="peer-user-connected",i.ReceiveVideo="receive-video",i.Disconnected="peer-user-disconnected",i))(df||{}),Ad=class{type="receive-video";stream;target;constructor(e,t){this.stream=e,this.target=t}},kd=class{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}};var Id=class extends Ld{userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),il(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 Ad(n,this);this.dispatchEvent(r)}})}},So=class extends Ld{static getOrCreate(e,t){if(So.instances.has(t))return So.instances.get(t);let i=new So(e,t);return So.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 cf.default(e)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){!this._peer||(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){}onPeerConnect(e){oE&&console.log("Peer connected as",e),this.context.connection.send("peer-user-connected",new kd(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 Id(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}},nl=So;z(nl,"instances",new Map);var Md=class extends Ld{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 sE,AdditiveBlending as aE}from"three";var Bn=class extends M{mode=0;shadowColor=new _e(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=C.getComponent(this.gameObject,ye);if(e){let t=e.material;t.blending=aE,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
128
128
 
129
129
  // diffuse-only lighting with overdrive to somewhat compensate
130
130
  // for the loss of indirect lighting and to make it more visible.
@@ -135,9 +135,9 @@ a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
135
135
  // be blended onto the scene.
136
136
  gl_FragColor = vec4(direct, max);
137
137
  return;
138
- `)}}}applyShadowMaterial(){let e=C.getComponent(this.gameObject,Ee);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new Zy;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)}};k([A()],jn.prototype,"mode",2),k([A(xe)],jn.prototype,"shadowColor",2);import{RGBELoader as iE}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as nE}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as rE}from"three";var sf=H("debugautosync"),Id=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new Md(e);return this._syncers[e.guid]=t,t}},af=new Id,Md=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)){sf&&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 eE(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 tE(a){if(a.__autoPropertySyncHandler)return a.__autoPropertySyncHandler;let e=af.getOrCreateSyncer(a);return e?.init(a),a.__autoPropertySyncHandler=e,e}var tl=function(a){return function(e,t){let i=null,n=a?e[a]:void 0,r=e,o=r.__internalAwake;sf&&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=af.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let l=this[s];this[s]=d,eE(d,l)&&n?.call(this,d,l)!==!1&&tE(this)?.notifyChanged(t,d)},get:function(){return this[s]},configurable:!0,enumerable:!0}),i?.init(this)}}};var Bn=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 nE:new iE}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=rE,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))}};k([tl("setSkybox"),A()],Bn.prototype,"url",2),k([A()],Bn.prototype,"allowDrop",2);import*as So from"three";import{Object3D as oE}from"three";var Ld=class extends M{target=null;followFactor=.1;rotateFactor=.1;flipForward=!1;_firstUpdate=!0;onEnable(){let e=C.getComponentInChildren(this.gameObject,re);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=q(this.target),i=this._firstUpdate||e?1:Y.clamp01(this.context.time.deltaTime*this.followFactor);this.worldPosition=this.worldPosition.lerp(t,i)}if(this.rotateFactor>0){let t=ke(this.target);this.flipForward&&t.premultiply(Ld._invertForward);let i=this._firstUpdate||e?1:Y.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},Ti=Ld;z(Ti,"_invertForward",new So.Quaternion().setFromAxisAngle(new So.Vector3(0,1,0),Math.PI)),k([A(oE)],Ti.prototype,"target",2);import{Layers as df}from"three";var il=H("debugspatialtrigger"),lf=new df,cf=new df;function sE(a,e){return lf.mask=a,cf.mask=e,lf.test(cf)}var _t=class extends M{triggerMask=0;onEnter;onStay;onExit;start(){il&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of Ki.triggers)sE(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){il&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){il&&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)}};k([A()],_t.prototype,"triggerMask",2),k([A(Ae)],_t.prototype,"onEnter",2),k([A(Ae)],_t.prototype,"onStay",2),k([A(Ae)],_t.prototype,"onExit",2);var Ss=class extends M{triggerMask;boxHelper;start(){il&&console.log(this.name,this.triggerMask,this)}onEnable(){Ss.triggers.push(this),this.boxHelper||(this.boxHelper=C.addNewComponent(this.gameObject,ct),this.boxHelper?.showHelper())}onDisable(){Ss.triggers.splice(Ss.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){C.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof _t&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){C.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof _t&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){C.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof _t&&t.onExitTrigger(this)},!1)}},Ki=Ss;z(Ki,"triggers",[]),k([A()],Ki.prototype,"triggerMask",2);import*as Fn from"three";var xt=H("debugspectator"),Po=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(),C.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),C.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 Hd(this.context,this),this._networking=new Fd(this.context,this),this._networking.awake(),C.setActive(this.gameObject,!1),this.cam=C.getComponent(this.gameObject,re),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Dd(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),K.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),K.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),K.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.orbit=C.getComponent(this.context.mainCamera,$e)}onDestroy(){this.stopSpectating(),K.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),K.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),K.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()||C.setActive(this.gameObject,!0)}onXRSessionStart(e){!this.isSupportedPlatform()||(xt&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){this.context.removeCamera(this.cam),C.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),xt&&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 Fn.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 pe.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 pe.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)}}},Dd=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=C.addNewComponent(this.cam.gameObject,Ti)),this.target||(this.target=new Fn.Object3D),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,xt&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){xt&&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&&C.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){xt&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(xt&&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(lE):i.quaternion.identity()}}},lE=new Fn.Quaternion().setFromAxisAngle(new Fn.Vector3(0,1,0),Math.PI),Hd=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 Ce;e.setMask(16777215);let t=this.context.physics.raycast(e);if(xt&&console.log(...t),t?.length)for(let i of t){if(i.distance<.2)continue;let n=i.object,r=C.getComponentInParent(n,pe),o=r?.connectionId;if(o){let s=this.context.players.getPlayerView(o);this.spectator.target=s,xt&&console.log("spectate",o,r);break}}}},jd=class{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}},Bd=class{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}},Fd=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(xt&&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 jd(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(xt&&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 Bd(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){H("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){let t=e.targetUserId,i=e.guid;if(xt&&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 xt&&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):(xt&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}};var Oo=class extends M{anchor=null;connectedBody=null;connectedAnchor=null;spring=10;damper=.2;rb=null;awake(){if(this.rb=C.getComponent(this.gameObject,de),!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 ma(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 Tt from"three";import{Material as cE,Texture as dE}from"three";var Tr=class{texture;triangles;uv;vertices;_geometry};k([A(dE)],Tr.prototype,"texture",2);var nl=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new Tt.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 Tt.BufferAttribute(i,3)),t.setAttribute("uv",new Tt.BufferAttribute(n,2)),t}},Ji=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=nl.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new Tt.MeshBasicMaterial({color:16777215,side:Tt.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new Tt.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 Tt.Mesh(nl.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))}}};k([A()],Ji.prototype,"drawMode",2),k([A(xe)],Ji.prototype,"color",2),k([A(cE)],Ji.prototype,"sharedMaterial",2);var Rt=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 Rt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new Rt).__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 Pe).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Pe).__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 hE}from"three";var rl="SCAM";Zr(rl,Rt.getRootAsSyncedCameraModel);var Ct=new gt,Nd=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){Ct.clear();let i=Ct.createString(this.guid),n=Ct.createString(this.userId);Rt.startSyncedCameraModel(Ct),Rt.addGuid(Ct,i),Rt.addUserId(Ct,n);let r=q(e),o=Xs(e);Rt.addPos(Ct,Pe.createVec3(Ct,r.x,r.y,r.z)),Rt.addRot(Ct,Pe.createVec3(Ct,o.x,o.y,o.z));let s=Rt.endSyncedCameraModel(Ct);Ct.finish(s,rl),t.sendBinary(Ct.asUint8Array())}}},ol=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(rl,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(rl,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&&C.destroy(r.obj),delete this.remoteCams[n],r&&delete this.userToCamMap[r.userId],ol.instances.push(r),this.context.players.removePlayerView(r.userId,"browser");continue}}if(K.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 Nd(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let t=q(e),i=ke(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 ve;c.context=this.context;let d=C.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,ol.instances.push(n);let l=C.getOrAddComponent(d,pe);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,ne.markDirty(r);let o=e.pos();o&&Nr(r,o.x(),o.y(),o.z());let s=e.rot();s&&Qs(r,s.x(),s.y(),s.z())}},Nn=ol;z(Nn,"instances",[]),k([A([hE,it])],Nn.prototype,"cameraPrefab",2);var zd="view",hf=H("debugsyncedroom"),ri=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=H(zd);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=H(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=Lh(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?(hf&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(hf&&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=H(zd);return e||H(this.urlParameterName)}setRandomRoomUrlParameter(){let e=Bl(),t=this.generateRoomName();H(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),kh(t,e)}generateRoomName(){return Mh()+"_"+Ih(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(zd,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};k([A()],ri.prototype,"roomName",2),k([A()],ri.prototype,"urlParameterName",2),k([A()],ri.prototype,"joinRandomRoom",2),k([A()],ri.prototype,"requireRoomParameter",2),k([A()],ri.prototype,"autoRejoin",2);function uf(){let a=H("testwindowcount")||0;a&&a>0&&uE(a)}function uE(a){if(H("testwindow"))return null;let e=new URL(window.location.href);Fr(e.searchParams,co,1),Fr(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 fE}from"three";var Ao=class extends M{awake(){uf()}},ko=class extends M{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(so,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new sl(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 gt(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=Zc(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)}}}},sl=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}}};z(sl,"temp",new fE);import{MathUtils as mE}from"three";import{TransformControls as gE}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as bE}from"three/examples/jsm/controls/OrbitControls";var Rr=class extends M{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!li||!this.context.mainCamera||(this.control=new gE(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=C.getComponentInParent(this.context.mainCamera,bE)??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=C.getComponentInParent(this.gameObject,Qe);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(mE.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))}};k([A()],Rr.prototype,"isGizmo",2);import{LinearToneMapping as pf,ACESFilmicToneMapping as vE,ReinhardToneMapping as yE}from"three";var al=H("debugvolume"),mf=(i=>(i[i.None=0]="None",i[i.Neutral=1]="Neutral",i[i.ACES=2]="ACES",i))(mf||{}),Io=class{overrideState=!1;value=0},Ri=class{active=!1;parameters},Vn=class extends Ri{mode;get isToneMapping(){return!0}},Un=class extends Ri{postExposure};function EE(a){return"mode"in a?Vn:"postExposure"in a?Un:Ri}var ff=Symbol("volumeprofile"),zn=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[ff]!==void 0;if(t){if(!r)return}else i[ff]=this;for(let o of this.components)if(o instanceof Vn){let s=o;if(!o.active||t){e.renderer.toneMapping=pf;continue}switch(al&&console.log("VOLUME:",mf[s.mode?.value??0]),s.mode?.value??0){case 0:e.renderer.toneMapping=pf;break;case 1:e.renderer.toneMapping=yE;break;case 2:e.renderer.toneMapping=vE;break}}else if(o instanceof Un){let s=o;al&&console.log(s.postExposure);let c=Math.pow(2,s.postExposure?.value??0),d=s.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=d?c:1}}};k([A([a=>EE(a),Ri])],zn.prototype,"components",2);var Cr=class extends M{sharedProfile;awake(){al&&(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(){al&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};k([A(zn)],Cr.prototype,"sharedProfile",2);import*as gf from"three";var Sr=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}},Mo=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=ht.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),ht.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=C.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=C.getComponentsInChildren(i,ut);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]&&(C.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<ht.Current.length;e++){let t=ht.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new Sr),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 gf.Vector3;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=q(i);this.temp.set(r.x,r.y,r.z),o.lerp(this.temp,e),le(i,o)}}};import{Object3D as wE}from"three";var Ci=class extends M{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=C.getComponentInParent(this.gameObject,Oe)}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)}}};k([A(wE)],Ci.prototype,"eyes",2),k([A()],Ci.prototype,"lastBlinkTime",2),k([A()],Ci.prototype,"blinkLength",2),k([A()],Ci.prototype,"eyesOpen",2);import*as ll from"three";import{Object3D as Vd}from"three";var Ud=class extends M{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=C.getComponentInParent(this.gameObject,Wi)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=C.addNewComponent(this.gameObject,Wi)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new ll.Vector3;currentTargetPoint=new ll.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=q(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=q(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let o=Ud.forward;if(o.set(0,0,1),o.applyQuaternion(ke(this.head)),o.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},Si=Ud;z(Si,"forward",new ll.Vector3(0,0,1)),k([A(Vd)],Si.prototype,"head",2),k([A(Vd)],Si.prototype,"eyes",2),k([A(Vd)],Si.prototype,"target",2);import{Object3D as bf}from"three";var _E=H("debugmouth"),Gn=class extends M{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=C.findObjectOfType(et,this.context),this.marker||(this.marker=C.getComponentInParent(this.gameObject,pe))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){_E&&(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)}}}};k([A(bf)],Gn.prototype,"idle",2),k([A(bf)],Gn.prototype,"talking",2);var Lo=class extends M{voip=null;marker=null;_startPosition=null;awake(){this.voip=C.findObjectOfType(et,this.context),this.marker=C.getComponentInParent(this.gameObject,pe)}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 xE=H("logstats"),Do=class extends M{onEnable(){console.log(this),xE&&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 Ef from"three";var Pr=class{guid},Or=class{signal;reaction;$serializedTypes={signal:Pr,reaction:Ae}},Zi=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)}}};k([A(Or)],Zi.prototype,"events",2);import*as ie from"three";import{Quaternion as TE,Vector3 as RE}from"three";var Ho=H("debugtimeline"),jo=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}},Gd=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";Ho&&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 ie.Vector3().fromArray(o.values,0),this.rootEndPosition=new ie.Vector3().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Ho&&console.log(this.rootPositionOffset);else if(o.name.endsWith(r)&&(this.rootStartQuaternion=new ie.Quaternion().fromArray(o.values,0),this.rootEndQuaternion=new ie.Quaternion().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Ho)){let s=new ie.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}},Wn=class extends jo{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),E=d.getObjectByName(f);if(E)if(s){if(!c){let b=t.tracks[0].name.substring(0,h)+".quaternion";Ho&&console.warn("Create quaternion track",f,E);let y=E.quaternion,g=new ie.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";Ho&&console.warn("Create position track",f,E);let y=E.position,g=new ie.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,Ho&&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 Gd(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 RE(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new TE(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 ie.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new ie.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new ie.Vector3;_totalOffsetRotation=new ie.Quaternion;_totalOffsetPosition2=new ie.Vector3;_totalOffsetRotation2=new ie.Quaternion;_summedPos=new ie.Vector3;_tempPos=new ie.Vector3;_summedRot=new ie.Quaternion;_tempRot=new ie.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),E=0,b=c.duration;if(d){if(c.loop)for(E+=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(),x=this._tempRot.identity(),T=c.rotation,R=new ie.Quaternion;R.slerp(T,u);let S=this._actionOffsets[r];if(S.hasOffsets)for(let O=0;O<E;O++)S.rootPositionOffset?v.copy(S.rootPositionOffset):v.set(0,0,0),v.applyQuaternion(w).applyQuaternion(R),S.rootQuaternionOffset&&(x.copy(S.rootQuaternionOffset),w.multiply(x)),m.add(v);p.multiply(R),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 ie.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 ie.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}}},qn=class extends jo{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return pn(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 ie.Audio(this.listener);i.setVolume(e.asset.volume);let n=new ie.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}}},en=class extends jo{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)}}},Ps=class extends jo{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;Ps.resolved[r]?n.sourceObject=Ps.resolved[r]:(n.sourceObject=C.findByGuid(r,e.scene),Ps.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=C.getComponent(n.sourceObject,tn);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)}}}}},$i=Ps;z($i,"resolved",{});var yf=H("debugtimeline");var cl=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(){yf&&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=es(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=C.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(yf&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),cl.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=cl.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 Wn;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 Ef.AnimationMixer(o.gameObject)),c.clips.push(f),c.mixer.uncacheAction(f),c.createHooks(l.asset,f);let E=c.mixer.clipAction(f);c.actions.push(E),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 en;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=C.getComponent(this.gameObject,Zi);o&&(r.receivers.push(o),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new en;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 $i;r.director=this,r.track=t;for(let o of t.clips)r.models.push(o);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}he.registerWaitForAllowAudio(()=>{let t=C.findObjectOfType(ei,this.context);if(!!t)for(let i of e){let n=new qn;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)}},tn=cl;z(tn,"createTrackFunctions",{});import*as wf from"three-mesh-ui";var oi=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 SE}from"three";var PE=H("debugeventsystem"),Pi=class extends M{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Pi.systems.length<=0&&Pi.systems.push(...C.findObjectsOfType(Pi,e)));for(let i of Pi.systems)if(i.context===e)return;let t=new SE;C.addNewComponent(t,Pi),e.scene.add(t)}static ensureUpdateMeshUI(e,t){si.update(e,t)}static markUIDirty(e){si.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Pi.systems.push(this)}onDestroy(){Pi.systems.splice(Pi.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)}onEnable(){ae.addEventListener("select-start",(t,i)=>{if(!i.grab)return;si.resetLastSelected();let n=new oi;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=!1,i.grab&&!this.handleEvents(i.grab,n)&&(i.grab=null)});let e=new Ce;ae.addEventListener("select-end",(t,i)=>{if(!i.grab)return;let n=new oi;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=t.selectionClick,this.handleEvents(i.grab,n)}),ae.addEventListener("update",t=>{e.ray=t.getRay();let i=this.performRaycast(e);if(!i)return;let n=new oi;n.inputSource=t,this.handleIntersections(i,n)}),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),K.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 oi(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=C.getComponent(this.context.mainCameraComponent.gameObject,$e)??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}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=C.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=[];handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&PE&&console.log("not allowed",e),!1;t.object=e,this.lastPointerEvent=t;let i=e.parent,n=!1,r=t.isClicked??!1,o=null;if(i&&i.isUI){let s=(t.isPressed||t.isClicked)??!1;if(i.shadowComponentOwner){let c=i.shadowComponentOwner.gameObject;if(c){if(o=this.tryFindCanvasGroup(c),o?.isCanvasGroup===!0){if(o.blocksRaycasts===!1)return!1;if(o.interactable===!1)return!0}if(C.foreachComponent(c,h=>{if(typeof h.raycastTarget=="boolean")return h},!1)?.raycastTarget===!1)return!1;let l=this.handleMeshUIIntersection(e,s);e=c,n=!0}}if(!n&&this.handleMeshUiObjectWithoutShadowDom(i,s))return!0}if(this.objectsHoveredThisFrame.push(e),o===null||o.interactable){let s=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let c=C.getComponentsInParent(e,M,this.handleEventsArray);for(let d=0;d<c.length;d++){if(t.used)return!0;if(c[d].destroyed)continue;let l=c[d];l.interactable!==!1&&(l.onPointerEnter&&(s||l.onPointerEnter(t)),t.isDown&&l.onPointerDown&&!this.raisedPointerDownEvents.includes(l)&&(l.onPointerDown(t),this.raisedPointerDownEvents.push(l)),t.isUp&&l.onPointerUp&&l.onPointerUp(t),t.isClicked&&l.onPointerClick&&l.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=si.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&si.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];si.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?C.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}tryFindCanvasGroup(e){if(!e)return null;let t=C.foreachComponent(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)}},Ke=Pi;z(Ke,"didSearchEventSystem",!1),z(Ke,"systems",[]);var si=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}};z(si,"lastSelected",null),z(si,"lastUpdateFrame",[]),z(si,"needsUpdate",!1);import{AxesHelper as OE}from"three";var Bo="./include";wf.Block.prototype.interactable={get(){return this.interactive},set(a){this.interactable=a}};var We=class extends M{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Ke.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=C.getComponentInParent(this.gameObject,nn)),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=C.getComponentInParent(i,We),!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}if(e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e.shadowComponentOwner=this,e.traverse(n=>{n.shadowComponentOwner===void 0&&(n.shadowComponentOwner=this)}),this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let n=this._parentComponent.shadowComponent;n&&n?.add(e)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),li&&e.add(new OE(.5)),this.onAfterAddedToScene()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e.shadowComponentOwner===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)}},nn=class extends We{awake(){super.awake()}};import{Color as IE,Texture as Sf}from"three";import*as qd from"three-mesh-ui";import{Matrix4 as AE,Object3D as kE,Vector2 as Rf,Vector3 as Wd}from"three";import{FrontSide as _f,DoubleSide as xf}from"three";function Fo(a,e){if(!a)return;let t=a.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?xf:_f,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?xf:_f,a.castShadow=e.castShadows?e.castShadows:!1,a.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of a.children)Fo(i,e)}function dl(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 Tf(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 Cf=H("debugui"),No=class{width;height},Ar=class{x;y;width;height},pt=class extends We{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 Wd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new AE,this.rectBlock=new kE,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new Wd),dl(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)&&(Cf&&console.log("updating",this.name),this.applyTransform()),Ke.ensureUpdateMeshUI(qd,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},Cf&&console.log(this.name,e);let t=new qd.Block(e);return this._createdBlocks.push(t),t}};k([A(Ar)],pt.prototype,"rect",2),k([A(Rf)],pt.prototype,"sizeDelta",2),k([A(Wd)],pt.prototype,"anchoredPosition3D",2),k([A(Rf)],pt.prototype,"pivot",2);var St=class extends We{get isGraphic(){return!0}get color(){return this._color||(this._color=new xe(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 xe(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=this.gameObject.getComponent(pt)),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(),dl(this,"_color",()=>Tf(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)}};k([A(xe)],St.prototype,"color",1),k([A()],St.prototype,"raycastTarget",2);var rn=class extends St{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var hl=class{texture;rect};k([A(Sf)],hl.prototype,"texture",2);var on=class extends rn{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 IE(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};k([A(hl)],on.prototype,"sprite",2);var kr=class extends rn{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};k([A(Sf)],kr.prototype,"mainTexture",2);var zo=H("debugbutton");var zt=class extends M{onClick;_isHovered=!1;onPointerEnter(e){zo&&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(){zo&&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){zo&&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){zo&&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){zo&&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(),zo&&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=C.getComponent(this.gameObject,on),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()}};k([A(Ae)],zt.prototype,"onClick",2),k([A()],zt.prototype,"colors",2),k([A()],zt.prototype,"transition",2),k([A()],zt.prototype,"animationTriggers",2),k([A(vt)],zt.prototype,"animator",2),k([A()],zt.prototype,"interactable",1);var Xd=class extends nn{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 Xd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}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(),Fo(this.shadowComponent,this);for(let e of this.gameObject.getComponentsInChildren(We))Fo(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(Y.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}}},Je=Xd;k([A()],Je.prototype,"renderOnTop",1),k([A()],Je.prototype,"depthWrite",1),k([A()],Je.prototype,"doubleSided",1),k([A()],Je.prototype,"castShadows",1),k([A()],Je.prototype,"receiveShadows",1),k([A()],Je.prototype,"renderMode",1),k([A(Je)],Je.prototype,"rootCanvas",1);var sn=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 C.getComponentsInChildren(this.gameObject,St,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};k([A()],sn.prototype,"alpha",1),k([A()],sn.prototype,"interactable",2),k([A()],sn.prototype,"blocksRaycasts",2);import*as Pf from"three-mesh-ui";import{Color as F}from"three";var ME=H("debugtext");var Le=class extends St{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){ME&&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={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:this.fontSize,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(e,this.fontStyle),e}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.shadowComponentOwner===void 0&&(e.shadowComponentOwner=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 Pf.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||(Fo(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 Os(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=LE(r)}else t.fontColor=new F(1,1,1)}else if(e.type=="b"){let n=new Os(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new Os(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=pn(this.sourceId,this.font),this.font):null}};k([A(Je)],Le.prototype,"canvas",2),k([A()],Le.prototype,"alignment",2),k([A()],Le.prototype,"verticalOverflow",2),k([A()],Le.prototype,"horizontalOverflow",2),k([A()],Le.prototype,"lineSpacing",2),k([A()],Le.prototype,"supportRichText",2),k([A()],Le.prototype,"font",2),k([A()],Le.prototype,"fontStyle",2),k([A()],Le.prototype,"text",1),k([A()],Le.prototype,"fontSize",1);var Os=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function LE(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 F(i/255,n/255,r/255)}switch(a){case"black":return new F(0,0,0);case"white":return new F(1,1,1);case"red":return new F(1,0,0);case"lime":return new F(0,1,0);case"blue":return new F(0,0,1);case"yellow":return new F(1,1,0);case"cyan":return new F(0,1,1);case"magenta":return new F(1,0,1);case"silver":return new F(.75,.75,.75);case"gray":return new F(.5,.5,.5);case"maroon":return new F(.5,0,0);case"olive":return new F(.5,.5,0);case"green":return new F(0,.5,0);case"purple":return new F(.5,0,.5);case"teal":return new F(0,.5,.5);case"navy":return new F(0,0,.5);case"darkred":return new F(.54,0,0);case"brown":return new F(.55,.27,0);case"firebrick":return new F(.69,.13,.13);case"crimson":return new F(.86,.08,.24);case"tomato":return new F(1,.39,.28);case"coral":return new F(1,.49,.31);case"indianred":return new F(.6,.31,.51);case"lightcoral":return new F(.94,.5,.5);case"darkorange":return new F(1,.55,0);case"orange":return new F(1,.65,0);case"gold":return new F(1,.84,0);case"darkgoldenrod":return new F(.72,.53,.04);case"goldenrod":return new F(.85,.65,.13);case"palegoldenrod":return new F(.93,.87,.67);case"darkkhaki":return new F(.74,.7,.42);case"khaki":return new F(.94,.9,.55);case"yellowgreen":return new F(.6,.8,.19);case"darkolivegreen":return new F(.33,.42,.18);case"olivedrab":return new F(.42,.56,.14);case"lawngreen":return new F(.49,.99,0);case"chartreuse":return new F(.5,1,0);case"greenyellow":return new F(.68,1,.18);case"darkgreen":return new F(0,.39,0);case"forestgreen":return new F(.13,.55,.13);case"limegreen":return new F(.19,.8,.19);case"lightgreen":return new F(.56,.93,.56);case"palegreen":return new F(.59,.98,.59);case"darkseagreen":return new F(.56,.74,.56);case"mediumspringgreen":return new F(0,.98,.6);case"springgreen":return new F(0,1,.5);case"seagreen":return new F(.18,.31,.31);case"mediumaquamarine":return new F(.4,.8,.66);case"mediumseagreen":return new F(.24,.7,.44);case"lightseagreen":return new F(.13,.7,.67);case"darkslategray":return new F(.18,.31,.31);case"darkcyan":return new F(0,.55,.55);case"aqua":return new F(0,1,1);case"lightcyan":return new F(.8,1,1);case"darkturquoise":return new F(0,.81,.82);case"turquoise":return new F(0,.82,.82);case"mediumturquoise":return new F(.28,.82,.8);case"paleturquoise":return new F(.68,1,.93);case"aquamarine":return new F(.5,1,.83);case"powderblue":return new F(.69,.88,.9);case"cadetblue":return new F(.37,.62,.63);case"steelblue":return new F(.27,.51,.71);case"cornflowerblue":return new F(.39,.58,.93);case"deepskyblue":return new F(0,.7,1);case"dodgerblue":return new F(.12,.56,1);case"lightblue":return new F(.68,.85,.9);case"skyblue":return new F(.53,.81,.92);case"lightskyblue":return new F(.53,.81,.98);case"midnightblue":return new F(.18,.18,.31);case"darkblue":return new F(0,0,.55);case"mediumblue":return new F(0,0,.82);case"royalblue":return new F(.25,.41,.88);case"blueviolet":return new F(.54,.17,.89);case"indigo":return new F(.29,0,.51);case"darkslateblue":return new F(.28,.24,.55);case"slateblue":return new F(.42,.35,.8);case"mediumslateblue":return new F(.48,.41,.9);case"mediumpurple":return new F(.58,.44,.86);case"darkmagenta":return new F(.55,0,.55);case"darkviolet":return new F(.58,0,.83);case"darkorchid":return new F(.6,.2,.8);case"mediumorchid":return new F(.73,.33,.83);case"thistle":return new F(.84,.75,.85);case"plum":return new F(.87,.63,.87);case"violet":return new F(.93,.51,.93);case"fuchsia":return new F(1,0,1);case"orchid":return new F(.85,.44,.84);case"mediumvioletred":return new F(.78,.08,.52);case"palevioletred":return new F(.86,.44,.58);case"hotpink":return new F(1,.4,.71);case"deeppink":return new F(1,.08,.58);case"lightpink":return new F(1,.71,.76);case"pink":return new F(1,.75,.78);case"antiquewhite":return new F(.98,.92,.84);case"beige":return new F(.96,.96,.86);case"bisque":return new F(1,.89,.77);case"blanchedalmond":return new F(1,.92,.82);case"wheat":return new F(.96,.87,.87);case"cornsilk":return new F(1,.97,.86);case"lemonchiffon":return new F(1,.98,.8);case"lightgoldenrodyellow":return new F(.98,.98,.82);case"lightyellow":return new F(1,1,.8);case"saddlebrown":return new F(.55,.27,.07);case"sienna":return new F(.63,.32,.18);case"chocolate":return new F(.82,.41,.12);case"peru":return new F(.82,.52,.25);case"sandybrown":return new F(.96,.64,.38);case"burlywood":return new F(.87,.72,.53);case"tan":return new F(.82,.71,.55);case"rosybrown":return new F(.74,.56,.56);case"moccasin":return new F(1,.89,.71);case"navajowhite":return new F(1,.87,.68);case"peachpuff":return new F(1,.85,.73);case"mistyrose":return new F(1,.89,.88);case"lavenderblush":return new F(1,.94,.93);case"linen":return new F(.98,.94,.9);case"oldlace":return new F(.99,.96,.9);case"papayawhip":return new F(1,.94,.84);case"seashell":return new F(1,.96,.93);case"mintcream":return new F(.98,1,.98);case"slategray":return new F(.44,.5,.56);case"lightslategray":return new F(.47,.53,.6);case"lightsteelblue":return new F(.69,.77,.87);case"lavender":return new F(.9,.9,.98);case"floralwhite":return new F(1,.98,.98);case"aliceblue":return new F(.94,.97,1);case"ghostwhite":return new F(.97,.97,1);case"honeydew":return new F(.94,1,.94);case"ivory":return new F(1,1,.94);case"azure":return new F(.94,1,1);case"snow":return new F(1,.98,.98);case"dimgray":return new F(.4,.4,.4);case"darkgray":return new F(.66,.66,.66);case"lightgray":return new F(.83,.83,.83);case"gainsboro":return new F(.86,.86,.86);case"whitesmoke":return new F(.96,.96,.96)}return new F(1,1,1)}var Ir=H("debuginputfield"),J=class extends M{get text(){return this.textComponent?.text??""}get isFocused(){return J.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){Ir&&console.log(this.name,this)}onEnable(){J.htmlField||(J.htmlField=document.createElement("input"),J.htmlField.classList.add("ar"),document.body.appendChild(J.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),J.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&C.setActive(this.placeholder.gameObject,!1)}onDisable(){J.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){Ir&&console.log("CLICK",e,J.active),J.activeTime=this.context.time.time,J.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();J.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-J.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(J.active!==this&&(Ir&&console.log("Select",this.name,this,J.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,J.htmlField?.value),J.active?.onDeselected(),J.active=this,this.placeholder&&C.setActive(this.placeholder.gameObject,!1),J.htmlField)){if(J.htmlField.value=this.textComponent?.text||"",Ir&&console.log("set input field value",J.htmlField.value),this.context.isInXR){let e=this.context.arOverlayElement;e&&(J.htmlField.style.width="0px",J.htmlField.style.height="0px",e.append(J.htmlField))}this.selectInputField()}}onDeselected(){J.active===this&&(J.active=null,Ir&&console.log("Deselect",this.name,this),J.htmlField&&(J.htmlField.blur(),document.body.append(J.htmlField),J.htmlField.style.width="",J.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&C.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(J.active===this){if(Ir&&console.log(e.code,e,J.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}J.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&C.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&J.htmlField){if(this.textComponent.text!==J.htmlField.value){Ir&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=J.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=J.htmlField.value}}selectInputField(){J.htmlField&&(J.htmlField.setSelectionRange(J.htmlField.value.length,J.htmlField.value.length),J.htmlField.focus())}},Pt=J;z(Pt,"active",null),z(Pt,"activeTime",-1),z(Pt,"htmlField",null),k([A(Le)],Pt.prototype,"textComponent",2),k([A(Le)],Pt.prototype,"placeholder",2),k([A(Ae)],Pt.prototype,"onValueChanged",2),k([A(Ae)],Pt.prototype,"onEndEdit",2);import*as Of from"three-mesh-ui";import*as As from"three";var Af=(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))(Af||{}),Vo=class extends We{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=Af[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=this.gameObject.getComponent(pt);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:Bo+"/"+t+"-msdf.json",fontTexture:Bo+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new As.Color(this.colors.keyboardBack),backspaceTexture:Bo+"/backspace.png",shiftTexture:Bo+"/shift.png",enterTexture:Bo+"/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 Of.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(o=>{o.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new As.Color(this.colors.button),backgroundOpacity:1}}),o.setState("normal"),o.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new As.Color(this.colors.hovered),backgroundOpacity:1}}),o.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new As.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(`
139
- `);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 an=class extends M{reverseArrangement=!1},Uo=class extends an{},Go=class extends an{},Wo=class extends an{};var Mr=class extends M{awake(){Ke.createIfNoneExists(this.context)}onEnable(){Ke.instance?.register(this)}onDisable(){Ke.instance?.unregister(this)}performRaycast(e=null){return null}},Oi=class extends Mr{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new Ce,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},qo=class extends Oi{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as kf from"three";import{HTMLMesh as DE}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as HE}from"three/examples/jsm/interactive/InteractiveGroup.js";var Xo=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 HE(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new DE(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=Xs(this.gameObject).clone();Qs(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let o=new kf.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 ul=class extends M{toggleKey="p";update(){this.context.input.isKeyDown("p")&&this.context.domElement.classList.toggle("presentation-mode")}};import*as If from"three";import{Raycaster as FE,Vector3 as NE}from"three";import*as pl from"three";import{MeshLine as jE,MeshLineMaterial as BE}from"three.meshline";var Qd=class{id=0;points=[];line=new jE;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 pl.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=Qd.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 BE({color:10066329,lineWidth:.01})},Qo=Qd;z(Qo,"wp",new pl.Vector3);var Lr=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=C.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 Qo(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 zE}from"three.meshline";var fl=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new NE,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},ml=class extends M{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=C.getComponent(this.gameObject,Lr),this.lines||(this.lines=C.addNewComponent(this.gameObject,Lr))),this.orbit=C.findObjectOfType($e,this.context)??void 0,this._states.mouse=new fl;let e={};ae.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),ae.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),ae.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);ml._raycaster.setFromCamera(t,this.context.mainCamera);let i=ml._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 fl,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=q(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 Ce;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(!!C.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=ut.colorFromHashCode(ut.hashCode(this.context.connection.connectionId)):e=new If.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new zE({color:e,lineWidth:Y.lerp(.005,.01,Math.random())})}},ks=ml;z(ks,"_raycaster",new FE);import{Object3D as VE}from"three";var Is=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=C.getComponent(t,Ai);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Ai.all.length-1;t>=0;t--){let i=Ai.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};k([A(it)],Is.prototype,"asset",2);var Vt=class extends M{static get all(){return Vt._all}static get local(){return Vt._local}static isLocalPlayer(e){return e instanceof VE?C.getComponentInParent(e,Vt)?.isLocalPlayer??!1:e instanceof st?C.getComponentInParent(e.gameObject,Vt)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&Vt.local.push(this),Vt.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(Vt.all.splice(Vt.all.indexOf(this),1),this.isLocalPlayer){let e=Vt._local.indexOf(this);e>=0&&Vt._local.splice(e,1)}}},Ai=Vt;z(Ai,"_all",[]),z(Ai,"_local",[]),k([tl(),A()],Ai.prototype,"owner",2);D.add("AlignmentConstraint",Sn);D.add("Animation",$t);D.add("AnimationCurve",ur);D.add("Animator",vt);D.add("AnimatorController",Zt);D.add("AudioListener",ei);D.add("AudioSource",he);D.add("AvatarModel",pr);D.add("AvatarLoader",Pn);D.add("AxesHelper",Vi);D.add("BasicIKConstraint",io);D.add("BoxHelperComponent",ct);D.add("Camera",re);D.add("Collider",ft);D.add("SphereCollider",_n);D.add("BoxCollider",xn);D.add("InstantiateOptions",ve);D.add("UnityObject",no);D.add("DeleteBox",fr);D.add("Deletable",ro);D.add("DeviceFlag",mr);D.add("DragControls",wt);D.add("DropListener",Mn);D.add("Duplicatable",Ei);D.add("CallInfo",wi);D.add("EventListEvent",yr);D.add("EventList",Ae);D.add("EventTrigger",mo);D.add("FlyControls",go);D.add("BoxGizmo",Xi);D.add("GltfExportBox",vo);D.add("GltfExport",Nt);D.add("GridHelper",Qi);D.add("GroundProjectedEnv",Yi);D.add("Interactable",Lt);D.add("UsageMarker",Dt);D.add("Light",Ye);D.add("LODModel",_i);D.add("LODGroup",Dn);D.add("LookAtConstraint",Er);D.add("NavMesh",Eo);D.add("NavMeshAgent",wo);D.add("NestedGltf",wr);D.add("Networking",mt);D.add("OffsetConstraint",xi);D.add("OrbitControls",$e);D.add("ParticleSystemRenderer",xr);D.add("ParticleSystem",Ro);D.add("MainModule",_o);D.add("EmissionModule",xo);D.add("ShapeModule",To);D.add("PlayerColor",ut);D.add("FieldWithDefault",Qr);D.add("Renderer",Ee);D.add("MeshRenderer",dr);D.add("SkinnedMeshRenderer",Yr);D.add("InstancingUtil",ne);D.add("RendererLightmap",Ni);D.add("Rigidbody",de);D.add("ScreenCapture",Hn);D.add("ShadowCatcher",jn);D.add("RemoteSkybox",Bn);D.add("SmoothFollow",Ti);D.add("SpatialTriggerReceiver",_t);D.add("SpatialTrigger",Ki);D.add("SpectatorCamera",Po);D.add("SpringJoint",Oo);D.add("Sprite",Tr);D.add("SpriteRenderer",Ji);D.add("SyncedCamera",Nn);D.add("SyncedRoom",ri);D.add("SyncedTransform",Qe);D.add("TestRunner",Ao);D.add("TestSimulateUserData",ko);D.add("TransformGizmo",Rr);D.add("VideoPlayer",Ne);D.add("Voip",et);D.add("VolumeParameter",Io);D.add("VolumeComponent",Ri);D.add("ToneMapping",Vn);D.add("ColorAdjustments",Un);D.add("VolumeProfile",zn);D.add("Volume",Cr);D.add("WebARSessionRoot",Bt);D.add("WebXR",K);D.add("WebAR",In);D.add("AvatarMarker",pe);D.add("WebXRAvatar",jt);D.add("TeleportTarget",gr);D.add("WebXRController",ae);D.add("AttachedObject",ht);D.add("XRGrabModel",Sr);D.add("XRGrabRendering",Mo);D.add("XRRig",kn);D.add("VRUserState",Ft);D.add("WebXRSync",qi);D.add("XRState",yt);D.add("XRFlag",Oe);D.add("AvatarBlink_Simple",Ci);D.add("AvatarEyeLook_Rotation",Si);D.add("Avatar_POI",Te);D.add("Avatar_Brain_LookAt",Wi);D.add("Avatar_MouthShapes",Gn);D.add("Avatar_MustacheShake",Lo);D.add("LogStats",Do);D.add("RGBAColor",xe);D.add("PlayableDirector",tn);D.add("SignalAsset",Pr);D.add("SignalReceiverEvent",Or);D.add("SignalReceiver",Zi);D.add("AnimationTrackHandler",Wn);D.add("AudioTrackHandler",qn);D.add("SignalTrackHandler",en);D.add("ControlTrackHandler",$i);D.add("BaseUIComponent",We);D.add("UIRootComponent",nn);D.add("Button",zt);D.add("Canvas",Je);D.add("CanvasGroup",sn);D.add("EventSystem",Ke);D.add("Graphic",St);D.add("MaskableGraphic",rn);D.add("Image",on);D.add("RawImage",kr);D.add("InputField",Pt);D.add("Keyboard",Vo);D.add("LayoutGroup",an);D.add("VerticalLayoutGroup",Uo);D.add("HorizontalLayoutGroup",Go);D.add("GridLayoutGroup",Wo);D.add("PointerEventData",oi);D.add("Raycaster",Mr);D.add("ObjectRaycaster",Oi);D.add("GraphicRaycaster",qo);D.add("Size",No);D.add("Rect",Ar);D.add("RectTransform",pt);D.add("SpatialHtml",Xo);D.add("Text",Le);D.add("PresentationMode",ul);D.add("LinesDrawer",ks);D.add("LineInstanceHandler",Qo);D.add("LinesManager",Lr);D.add("PlayerSync",Is);D.add("PlayerState",Ai);var Mf=Ie;function Kp(a,e){let i=oc(a,e);return i!==void 0?i:null}async function Ba(a,e,t,i=null,n){if(!t)return;let r=[],o=i;typeof o=="number"&&(o=new Ge(i));let s=new Ur(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 Kd(s,d,c,r);if(t.children)for(let d of t.children)await Kd(s,d,c,r);a.new_scripts_pre_setup_callbacks.push(()=>{for(let d of c)UE(d,s);if(o){Yd(t,o);for(let d of t.scenes)Yd(d,o)}})}function Yd(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)Yd(t,e)}}var Ms=[];async function Kd(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=D.get(o.name);if(s!=null){let c=new s;c.sourceId=a.gltfId,tr(c,o),Ns(c,e,!1),t.push({instance:c,compData:o,obj:e})}else Mf&&console.debug("unknown component: "+o.name),Ms.includes(o.name)||Ms.push(o.name)}catch(s){console.error(o.name+" - "+s.message,s)}if(Ms.length>0){let o=Ms.join(", ");console.warn("unknown components: "+o),Ms.length=0}}if(e.children)for(let r of e.children)await Kd(a,r,t,i)}function UE(a,e){let{instance:t,compData:i,obj:n}=a;e.object=n,e.target=t;let r=!0;r=rs(t,i,e)===!0,Mf&&console.debug("add "+i.name,i,t)}import*as me from"three";import*as Lf from"three";var GE=new Lf.FileLoader;async function Jd(a){return new Promise((e,t)=>{GE.load(a,e,void 0,t)})}import{Vector4 as Xn,FileLoader as qE,DataTexture as ih,RGBAFormat as XE,Color as QE}from"three";var Ls=new Uint8Array(4);Ls[0]=255;Ls[1]=255;Ls[2]=255;Ls[3]=255;var jf=new ih(Ls,1,1,XE);function Bf(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 ih(n,e,e);return c.needsUpdate=!0,c}function Ff(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 QE;for(let f=0;f<n;f++){let E=Math.floor(f/n*d),b=Y.clamp(E+1,0,d-1),y=c[E],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 x=0;x<i;x++){let T=(f*i+x)*4;l[T+0]=m,l[T+1]=v,l[T+2]=w,l[T+3]=255}}let u=new ih(l,i,n);return u.needsUpdate=!0,u}var $d=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},eh=class{loaded=new Map;async loadShader(e){let t=await Jd(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 Jd(t),n=new $d(e,i);return this.loaded.set(t,n),n}},IF=new eh;function Ds(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 Zd=[],Df=[];function nh(a,e){if(Zd.length===0)for(let t=0;t<27;t++)Zd.push(0);e||(e=Zd);for(let t=0;t<27;t++)Df[t]=e[t];e=Df,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 th=class{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}};async function Nf(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 Hf(r),!o.code&&o.uri&&await Hf(o),!r.code||!o.code)return null;let s=a.techniques[e];return new th(r.code,o.code,s)}}return console.error("Shader technique not found",e),null}async function Hf(a){let e=a.uri;if(!!e)if(e.endsWith(".glsl")){let i=await new qE().loadAsync(e);a.code=i.toString()}else a.code=YE(a.uri)}function YE(a){return decodeURIComponent(Array.prototype.map.call(atob(a),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}import{RawShaderMaterial as JE}from"three";var ln=H("debugshaders"),Yo="NEEDLE_techniques_webgl";var rh=class{objectToWorldMatrix=new me.Matrix4;worldToObjectMatrix=new me.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Ds(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Ds(this.worldToObjectMatrix,this.worldToObject)}};var fe=class extends JE{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);constructor(e,...t){super(...t),this.identifier=e,ln&&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)&&Q.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=Q.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&Q.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=Q.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}ln&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},nh(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new me.Vector4(r,r,r,r)},ln&&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 rh;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&Q.Current.setRequireColor(!0),this.depthTextureUniform&&Q.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,r,o){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=Q.Current;e&&(fe.viewProjection&&this.uniforms[this._viewProjectionName]&&(fe.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Ds(fe.viewProjection,fe._viewProjectionValues)),fe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(fe.viewMatrix.copy(e.matrixWorldInverse),Ds(fe.viewMatrix,fe._viewMatrixValues)),this.uniforms[fe._worldSpaceCameraPosName]&&fe._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.rendererData.timeVec4);let n=i?.mainLight;if(n){let s=n.getWorldPosition(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}},Ut=fe;z(Ut,"viewProjection",new me.Matrix4),z(Ut,"_viewProjectionValues",[]),z(Ut,"viewMatrix",new me.Matrix4),z(Ut,"_viewMatrixValues",[]),z(Ut,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),z(Ut,"_worldSpaceCameraPos",new me.Vector3),z(Ut,"_mainLightColor",new me.Vector4),z(Ut,"_mainLightPosition",new me.Vector3),z(Ut,"_lightData",new me.Vector4);var gl=class{get name(){return Yo}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return ln&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Yo])return ln&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[Yo].technique;if(i<0)return null;let n=this.parser.json.extensions[Yo];if(!n)return null;ln&&console.log(n);let r=n.techniques[i];return r?new Promise(async(o,s)=>{let c=await Nf(n,r.program),d=c?.fragmentShader,l=c?.vertexShader;if(!d||!l)return s();ln&&console.log("loadMaterial",t,c);let h={},u=r.uniforms;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[Yo]){let y=t.extensions[Yo];if(y.technique===i){ln&&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 E=new Ut(this.identifier,{name:t.name??"",uniforms:h,vertexShader:l,fragmentShader:d,lights:!1});switch(h._Cull?.value){case 0:E.side=me.DoubleSide;break;case 1:E.side=me.BackSide;break;case 2:E.side=me.FrontSide;break;default:E.side=me.FrontSide;break}E.transparent=f,f&&(E.depthWrite=!1),nh(h),E.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:jf},console.warn("Missing/unassigned texture, fallback to white: "+g);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+g,u[y]);break}}ln&&console.log(E.uuid,h),o(E)}):null}};import{EXRLoader as ZE}from"three/examples/jsm/loaders/EXRLoader";var oh=H("debugexr"),bl=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",oh&&console.log(e)}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(oh&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let o=r.extensions[t],s=new ZE(i.options.manager);return oh&&console.log("EXT_texture_exr.loadTexture",o,s),i.loadTextureImage(e,o.source,s)}};var zf="NEEDLE_gameobject_data",vl=class{get name(){return zf}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[zf];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{FloatType as $E,HalfFloatType as ew,sRGBEncoding as tw}from"three";var Vf="NEEDLE_lightmaps",iw=H("debuglightmapsextension"),Hs=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(Hs||{}),yl=class{get name(){return Vf}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[Vf];if(i){let n=i.textures;return n.length?(iw&&console.log(i),new Promise(async(r,o)=>{let s=[];for(let c of n)if(c.pointer){let d=Vr(this.parser,c.pointer).then(l=>{let h=l;h?.isTexture&&(this.registry?(c.type!==0&&(h.encoding=tw),(h.type==$E||h.type==ew)&&(h.flipY=!0),this.registry.registerTexture(this.source,c.type,h,c.index)):console.log(Hs[c.type],c.pointer,h))});s.push(d)}await Promise.all(s),r()})):null}}return null}};import{AmbientLight as sw,Color as Uf,HemisphereLight as aw}from"three";import{Vector4 as nw,EquirectangularReflectionMapping as El,sRGBEncoding as wl,WebGLCubeRenderTarget as rw}from"three";import{LightProbeGenerator as ow}from"three/examples/jsm/lights/LightProbeGenerator.js";var sh=H("debugenvlight"),lh=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(lh||{});var _l=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 nw;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 ah(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(sh&&console.log(this.sceneLightSettings?lh[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=wl,n.mapping=El,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=Ff(t[0],t[1],t[2],64,64);i.encoding=wl,i.mapping=El,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=Bf(this.sceneLightSettings.ambientLight,64);t.encoding=wl,t.mapping=El,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 sh&&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={}},ah=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=El,t.encoding=wl}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){sh&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new rw(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=ow.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}};var Gf="NEEDLE_lighting_settings",Ko=H("debugenvlight"),xl=class{get name(){return Gf}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[Gf];if(i){Ko&&console.log(i);let n=C.addNewComponent(e.scene,ch,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new Uf().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new Uf().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},ch=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)}Ko&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(Ko&&console.log("Enable scene lighting",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),e||Ko&&console.warn("This is no active?!",this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&!this._ambientLightObj&&(this._ambientLightObj=new sw(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 aw(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=>{Ko&&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(){Ko&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};function hh(a){let e=new bo;return a.register(t=>(e.parser=t,e)),e}var dh=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 uh(a,e,t){a.register(n=>new vl(n)),a.register(n=>new ta(n)),a.register(n=>new yl(n,e.lightmaps,t)),a.register(n=>new xl(n,t,e)),a.register(n=>new gl(n,t)),a.register(n=>new lr(n,t)),a.register(n=>new zi(n,t,e)),a.register(n=>new bl(n));let i=a.setAnimationPointerResolver;typeof i=="function"&&i.bind(a)(new dh)}var lw=H("printGltf");var Qn=class{context;loader;path;gltf;constructor(e,t,i,n){this.context=e,this.path=t,this.loader=i,this.gltf=n}},Wf={};function Jo(a,e){if(Wf[a])for(let t of Wf[a])t(e)}async function Xf(a,e,t,i,n){lw&&console.log(t),await a.assets.registerGltf(t),await Ba(a,e,t,i,n)}function to(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 qf;uh(n,a,t);let o=hh(n);return new Promise((s,c)=>{try{cr(n,a),Jo(0,new Qn(a,t,n)),n.parse(e,t,async d=>{Jo(1,new Qn(a,t,n,d)),await Xf(a,t,d,i,o),Jo(10,new Qn(a,t,n,d)),s(d)},d=>{console.error("failed loading "+t,d),s(void 0)})}catch(d){console.error(d),c(d)}})}function vr(a,e,t,i=!1,n){let r=new qf;uh(r,a,e);let s=hh(r);return new Promise((c,d)=>{try{cr(r,a),Jo(0,new Qn(a,e,r)),r.load(e,async l=>{Jo(1,new Qn(a,e,r,l)),await Xf(a,e,l,t,s),Jo(10,new Qn(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)}})}import*as Yn from"three";function Tl(a,e,t){let i=C.getComponentInChildren(a,wt);if(i||(i=C.addNewComponent(a,wt,!1),i.guid=e.generateUUID()),i&&!C.getComponent(i.gameObject,Qe)){let r=C.addNewComponent(i.gameObject,Qe,!1);r.guid=e.generateUUID()}if(i&&!C.getComponentInParent(i.gameObject,Oi)){let r=C.addNewComponent(i.gameObject,Oi,!1);r.guid=e.generateUUID()}if(t&&t.animations?.length>0){let r=t.animations[0],o=C.addNewComponent(a,$t,!1);o.animations=[r]}let n=!1;a.traverse(r=>{!r||r.isSkinnedMesh===!0&&(n||console.log("Disabling frustum culling for skinned meshes",t),n=!0,r.frustumCulled=!1)})}var ph=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 Gp(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=Zs(),l=new Ge(d),h=await vr(e,c,l,!0);if(h&&h.scene){let u=h.scene;if(!u.guid){let f=new Ge(d);u.guid=f.generateUUID()}t&&dw(e.connection,a,d,u,t),Tl(u,l,h),n(h)}}}):(console.warn("Unsupported file type: "+i),console.log(a),null)}async function Wp(a,e){return new Promise(async(t,i)=>{let n=Zs(),r=new Ge(n),o=await vr(e,a.toString(),r,!0);if(o&&o.scene){let s=o.scene;Tl(s,r,o),t(o)}else console.warn("Unsupported file type: "+a.toString())})}function Qf(a){a.connection.beginListen("file-spawned",async e=>{if(e.sender!==a.connection.connectionId){console.log("received file event",e),hw(e,a);let t=null;try{t=await Ha(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{uw(e,a)}if(t){let i=new Ge(e.seed),n=await to(a,t,null,i);if(n&&n.scene){let r=n.scene;if(Tl(r,i,n),e.parentGuid){let o=C.findByGuid(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 dw(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 Mp(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 ph(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 fh={};function hw(a,e){let t=new Yn.BoxGeometry,i=new Yn.Mesh(t,new Yn.MeshBasicMaterial({color:65280})),n=new Yn.BoxHelper(i,5592405);if(fh[a.guid]=n,e.scene.add(n),a.parentGuid){let r=C.findByGuid(a.parentGuid,e.scene);r&&r.add(n)}a.position&&n.position.copy(a.position)}function uw(a,e){let t=a.guid,i=fh[t];i&&(delete fh[t],i.removeFromParent())}import*as Yf from"three";var V3=H("debugassets");var Rl=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:
140
- `+i.src),e.preventDefault())}})}texturesLoader=new Yf.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 Jf from"three/examples/jsm/libs/stats.module";import*as ki from"three";var Kf=!!H("debuglightmaps"),Cl=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){Kf&&console.log("Registering lightmap",e,Hs[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 Kf&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};ki.ShaderChunk.lights_fragment_maps=ki.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
138
+ `)}}}applyShadowMaterial(){let e=C.getComponent(this.gameObject,ye);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new sE;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)}};k([A()],Bn.prototype,"mode",2),k([A(_e)],Bn.prototype,"shadowColor",2);import{RGBELoader as dE}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as hE}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as uE}from"three";var hf=H("debugautosync"),Dd=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new Hd(e);return this._syncers[e.guid]=t,t}},uf=new Dd,Hd=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)){hf&&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 lE(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 cE(a){if(a.__autoPropertySyncHandler)return a.__autoPropertySyncHandler;let e=uf.getOrCreateSyncer(a);return e?.init(a),a.__autoPropertySyncHandler=e,e}var rl=function(a){return function(e,t){let i=null,n=a?e[a]:void 0,r=e,o=r.__internalAwake;hf&&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=uf.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(d){let l=this[s];this[s]=d,lE(d,l)&&n?.call(this,d,l)!==!1&&cE(this)?.notifyChanged(t,d)},get:function(){return this[s]},configurable:!0,enumerable:!0}),i?.init(this)}}};var Fn=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 hE:new dE}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=uE,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))}};k([rl("setSkybox"),A()],Fn.prototype,"url",2),k([A()],Fn.prototype,"allowDrop",2);import*as Po from"three";import{Object3D as pE}from"three";var jd=class extends M{target=null;followFactor=.1;rotateFactor=.1;flipForward=!1;_firstUpdate=!0;onEnable(){let e=C.getComponentInChildren(this.gameObject,re);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 Po.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=q(this.target),i=this._firstUpdate||e?1:Y.clamp01(this.context.time.deltaTime*this.followFactor);this.worldPosition=this.worldPosition.lerp(t,i)}if(this.rotateFactor>0){let t=Ae(this.target);this.flipForward&&t.premultiply(jd._invertForward);let i=this._firstUpdate||e?1:Y.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},Ri=jd;z(Ri,"_invertForward",new Po.Quaternion().setFromAxisAngle(new Po.Vector3(0,1,0),Math.PI)),k([A(pE)],Ri.prototype,"target",2);import{Layers as mf}from"three";var ol=H("debugspatialtrigger"),pf=new mf,ff=new mf;function fE(a,e){return pf.mask=a,ff.mask=e,pf.test(ff)}var xt=class extends M{triggerMask=0;onEnter;onStay;onExit;start(){ol&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of Zi.triggers)fE(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){ol&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){ol&&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)}};k([A()],xt.prototype,"triggerMask",2),k([A(Oe)],xt.prototype,"onEnter",2),k([A(Oe)],xt.prototype,"onStay",2),k([A(Oe)],xt.prototype,"onExit",2);var Ps=class extends M{triggerMask;boxHelper;start(){ol&&console.log(this.name,this.triggerMask,this)}onEnable(){Ps.triggers.push(this),this.boxHelper||(this.boxHelper=C.addNewComponent(this.gameObject,ct),this.boxHelper?.showHelper())}onDisable(){Ps.triggers.splice(Ps.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){C.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof xt&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){C.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof xt&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){C.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof xt&&t.onExitTrigger(this)},!1)}},Zi=Ps;z(Zi,"triggers",[]),k([A()],Zi.prototype,"triggerMask",2);import*as Nn from"three";var Tt=H("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(),C.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),C.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 Fd(this.context,this),this._networking=new Vd(this.context,this),this._networking.awake(),C.setActive(this.gameObject,!1),this.cam=C.getComponent(this.gameObject,re),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Bd(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),K.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),K.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),K.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.orbit=C.getComponent(this.context.mainCamera,$e)}onDestroy(){this.stopSpectating(),K.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),K.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),K.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()||C.setActive(this.gameObject,!0)}onXRSessionStart(e){!this.isSupportedPlatform()||(Tt&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){this.context.removeCamera(this.cam),C.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),Tt&&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 Nn.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)}}},Bd=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=C.addNewComponent(this.cam.gameObject,Ri)),this.target||(this.target=new Nn.Object3D),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Tt&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Tt&&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&&C.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){Tt&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(Tt&&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(gE):i.quaternion.identity()}}},gE=new Nn.Quaternion().setFromAxisAngle(new Nn.Vector3(0,1,0),Math.PI),Fd=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 Re;e.setMask(16777215);let t=this.context.physics.raycast(e);if(Tt&&console.log(...t),t?.length)for(let i of t){if(i.distance<.2)continue;let n=i.object,r=C.getComponentInParent(n,ue),o=r?.connectionId;if(o){let s=this.context.players.getPlayerView(o);this.spectator.target=s,Tt&&console.log("spectate",o,r);break}}}},Nd=class{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}},zd=class{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}},Vd=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(Tt&&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 Nd(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Tt&&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 zd(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){H("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){let t=e.targetUserId,i=e.guid;if(Tt&&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 Tt&&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):(Tt&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}};var Ao=class extends M{anchor=null;connectedBody=null;connectedAnchor=null;spring=10;damper=.2;rb=null;awake(){if(this.rb=C.getComponent(this.gameObject,ce),!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 ya(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 Rt from"three";import{Material as bE,Texture as vE}from"three";var Rr=class{texture;triangles;uv;vertices;_geometry};k([A(vE)],Rr.prototype,"texture",2);var sl=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new Rt.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 Rt.BufferAttribute(i,3)),t.setAttribute("uv",new Rt.BufferAttribute(n,2)),t}},$i=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=sl.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new Rt.MeshBasicMaterial({color:16777215,side:Rt.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new Rt.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 Rt.Mesh(sl.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))}}};k([A()],$i.prototype,"drawMode",2),k([A(_e)],$i.prototype,"color",2),k([A(bE)],$i.prototype,"sharedMaterial",2);var Ct=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 Ct).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new Ct).__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 yE}from"three";var al="SCAM";eo(al,Ct.getRootAsSyncedCameraModel);var St=new bt,Ud=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){St.clear();let i=St.createString(this.guid),n=St.createString(this.userId);Ct.startSyncedCameraModel(St),Ct.addGuid(St,i),Ct.addUserId(St,n);let r=q(e),o=Ys(e);Ct.addPos(St,Se.createVec3(St,r.x,r.y,r.z)),Ct.addRot(St,Se.createVec3(St,o.x,o.y,o.z));let s=Ct.endSyncedCameraModel(St);St.finish(s,al),t.sendBinary(St.asUint8Array())}}},ll=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(al,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(al,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&&C.destroy(r.obj),delete this.remoteCams[n],r&&delete this.userToCamMap[r.userId],ll.instances.push(r),this.context.players.removePlayerView(r.userId,"browser");continue}}if(K.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 Ud(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let t=q(e),i=Ae(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 be;c.context=this.context;let d=C.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,ll.instances.push(n);let l=C.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,ne.markDirty(r);let o=e.pos();o&&zr(r,o.x(),o.y(),o.z());let s=e.rot();s&&Ks(r,s.x(),s.y(),s.z())}},zn=ll;z(zn,"instances",[]),k([A([yE,it])],zn.prototype,"cameraPrefab",2);var Gd="view",gf=H("debugsyncedroom"),oi=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=H(Gd);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=H(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=jh(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?(gf&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(gf&&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=H(Gd);return e||H(this.urlParameterName)}setRandomRoomUrlParameter(){let e=zl(),t=this.generateRoomName();H(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Lh(t,e)}generateRoomName(){return Hh()+"_"+Dh(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(Gd,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};k([A()],oi.prototype,"roomName",2),k([A()],oi.prototype,"urlParameterName",2),k([A()],oi.prototype,"joinRandomRoom",2),k([A()],oi.prototype,"requireRoomParameter",2),k([A()],oi.prototype,"autoRejoin",2);function bf(){let a=H("testwindowcount")||0;a&&a>0&&EE(a)}function EE(a){if(H("testwindow"))return null;let e=new URL(window.location.href);Nr(e.searchParams,ho,1),Nr(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 _E}from"three";var ko=class extends M{awake(){bf()}},Io=class extends M{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(ao,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new cl(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 bt(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=td(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)}}}},cl=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}}};z(cl,"temp",new _E);import{MathUtils as xE}from"three";import{TransformControls as TE}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as RE}from"three/examples/jsm/controls/OrbitControls";var Cr=class extends M{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!ci||!this.context.mainCamera||(this.control=new TE(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=C.getComponentInParent(this.context.mainCamera,RE)??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=C.getComponentInParent(this.gameObject,Qe);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(xE.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))}};k([A()],Cr.prototype,"isGizmo",2);import{LinearToneMapping as vf,ACESFilmicToneMapping as CE,ReinhardToneMapping as SE}from"three";var dl=H("debugvolume"),Ef=(i=>(i[i.None=0]="None",i[i.Neutral=1]="Neutral",i[i.ACES=2]="ACES",i))(Ef||{}),Mo=class{overrideState=!1;value=0},Ci=class{active=!1;parameters},Un=class extends Ci{mode;get isToneMapping(){return!0}},Gn=class extends Ci{postExposure};function PE(a){return"mode"in a?Un:"postExposure"in a?Gn:Ci}var yf=Symbol("volumeprofile"),Vn=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[yf]!==void 0;if(t){if(!r)return}else i[yf]=this;for(let o of this.components)if(o instanceof Un){let s=o;if(!o.active||t){e.renderer.toneMapping=vf;continue}switch(dl&&console.log("VOLUME:",Ef[s.mode?.value??0]),s.mode?.value??0){case 0:e.renderer.toneMapping=vf;break;case 1:e.renderer.toneMapping=SE;break;case 2:e.renderer.toneMapping=CE;break}}else if(o instanceof Gn){let s=o;dl&&console.log(s.postExposure);let c=Math.pow(2,s.postExposure?.value??0),d=s.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=d?c:1}}};k([A([a=>PE(a),Ci])],Vn.prototype,"components",2);var Sr=class extends M{sharedProfile;awake(){dl&&(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(){dl&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};k([A(Vn)],Sr.prototype,"sharedProfile",2);import*as wf 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}},Lo=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=ht.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),ht.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=C.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=C.getComponentsInChildren(i,ut);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]&&(C.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<ht.Current.length;e++){let t=ht.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 wf.Vector3;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=q(i);this.temp.set(r.x,r.y,r.z),o.lerp(this.temp,e),ae(i,o)}}};import{Object3D as OE}from"three";var Si=class extends M{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=C.getComponentInParent(this.gameObject,Pe)}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)}}};k([A(OE)],Si.prototype,"eyes",2),k([A()],Si.prototype,"lastBlinkTime",2),k([A()],Si.prototype,"blinkLength",2),k([A()],Si.prototype,"eyesOpen",2);import*as hl from"three";import{Object3D as Wd}from"three";var qd=class extends M{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=C.getComponentInParent(this.gameObject,qi)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=C.addNewComponent(this.gameObject,qi)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new hl.Vector3;currentTargetPoint=new hl.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=q(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=q(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let o=qd.forward;if(o.set(0,0,1),o.applyQuaternion(Ae(this.head)),o.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},Pi=qd;z(Pi,"forward",new hl.Vector3(0,0,1)),k([A(Wd)],Pi.prototype,"head",2),k([A(Wd)],Pi.prototype,"eyes",2),k([A(Wd)],Pi.prototype,"target",2);import{Object3D as _f}from"three";var AE=H("debugmouth"),Wn=class extends M{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=C.findObjectOfType(et,this.context),this.marker||(this.marker=C.getComponentInParent(this.gameObject,ue))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){AE&&(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)}}}};k([A(_f)],Wn.prototype,"idle",2),k([A(_f)],Wn.prototype,"talking",2);var Do=class extends M{voip=null;marker=null;_startPosition=null;awake(){this.voip=C.findObjectOfType(et,this.context),this.marker=C.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 Jd={};kh(Jd,{AlignmentConstraint:()=>On,Animation:()=>ei,AnimationCurve:()=>pr,AnimationTrackHandler:()=>qn,Animator:()=>yt,AnimatorController:()=>$t,AttachedObject:()=>ht,AudioListener:()=>ti,AudioSource:()=>de,AudioTrackHandler:()=>Xn,AvatarBlink_Simple:()=>Si,AvatarEyeLook_Rotation:()=>Pi,AvatarLoader:()=>An,AvatarMarker:()=>ue,AvatarModel:()=>fr,Avatar_Brain_LookAt:()=>qi,Avatar_MouthShapes:()=>Wn,Avatar_MustacheShake:()=>Do,Avatar_POI:()=>xe,AxesHelper:()=>Ui,BaseUIComponent:()=>Ge,BasicIKConstraint:()=>ro,BoxCollider:()=>Rn,BoxGizmo:()=>Qi,BoxHelperComponent:()=>ct,Button:()=>Vt,CallInfo:()=>_i,Camera:()=>re,Canvas:()=>Je,CanvasGroup:()=>ln,Collider:()=>mt,ColorAdjustments:()=>Gn,ControlTrackHandler:()=>tn,Deletable:()=>oo,DeleteBox:()=>mr,DeviceFlag:()=>gr,DragControls:()=>_t,DropListener:()=>Dn,Duplicatable:()=>wi,EmissionModule:()=>To,EventList:()=>Oe,EventListEvent:()=>Er,EventSystem:()=>Ke,EventTrigger:()=>go,FieldWithDefault:()=>Yr,FlyControls:()=>bo,GltfExport:()=>zt,GltfExportBox:()=>yo,Graphic:()=>Pt,GraphicRaycaster:()=>Xo,GridHelper:()=>Yi,GridLayoutGroup:()=>qo,GroundProjectedEnv:()=>Ki,HorizontalLayoutGroup:()=>Wo,Image:()=>an,InputField:()=>Ot,InstancingUtil:()=>ne,InstantiateOptions:()=>be,Interactable:()=>Dt,Keyboard:()=>Uo,LODGroup:()=>jn,LODModel:()=>xi,LayoutGroup:()=>cn,Light:()=>Ye,LogStats:()=>Ho,LookAtConstraint:()=>wr,MainModule:()=>xo,MaskableGraphic:()=>sn,MeshRenderer:()=>hr,NavMesh:()=>wo,NavMeshAgent:()=>_o,NestedGltf:()=>_r,Networking:()=>gt,ObjectRaycaster:()=>Ai,OffsetConstraint:()=>Ti,OrbitControls:()=>$e,ParticleSystem:()=>Co,ParticleSystemRenderer:()=>Tr,PlayableDirector:()=>rn,PlayerColor:()=>ut,PointerEventData:()=>si,RGBAColor:()=>_e,RawImage:()=>Ir,Raycaster:()=>Lr,Rect:()=>kr,RectTransform:()=>pt,RemoteSkybox:()=>Fn,Renderer:()=>ye,RendererLightmap:()=>zi,Rigidbody:()=>ce,ScreenCapture:()=>Ji,ShadowCatcher:()=>Bn,ShapeModule:()=>Ro,SignalAsset:()=>Or,SignalReceiver:()=>en,SignalReceiverEvent:()=>Ar,SignalTrackHandler:()=>nn,Size:()=>zo,SkinnedMeshRenderer:()=>Kr,SmoothFollow:()=>Ri,SpatialHtml:()=>Qo,SpatialTrigger:()=>Zi,SpatialTriggerReceiver:()=>xt,SpectatorCamera:()=>Oo,SphereCollider:()=>Tn,SpringJoint:()=>Ao,Sprite:()=>Rr,SpriteRenderer:()=>$i,SyncedCamera:()=>zn,SyncedRoom:()=>oi,SyncedTransform:()=>Qe,TeleportTarget:()=>br,TestRunner:()=>ko,TestSimulateUserData:()=>Io,Text:()=>Le,ToneMapping:()=>Un,TransformGizmo:()=>Cr,UIRootComponent:()=>on,UsageMarker:()=>Ht,VRUserState:()=>Nt,VerticalLayoutGroup:()=>Go,VideoPlayer:()=>Me,Voip:()=>et,Volume:()=>Sr,VolumeComponent:()=>Ci,VolumeParameter:()=>Mo,VolumeProfile:()=>Vn,WebAR:()=>Ln,WebARSessionRoot:()=>Ft,WebXR:()=>K,WebXRAvatar:()=>Bt,WebXRController:()=>se,WebXRSync:()=>Xi,XRFlag:()=>Pe,XRGrabModel:()=>Pr,XRGrabRendering:()=>Lo,XRRig:()=>Mn,XRState:()=>Et,__Ignore:()=>Is});var kE=H("logstats"),Ho=class extends M{onEnable(){console.log(this),kE&&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 Rf from"three";var Or=class{guid},Ar=class{signal;reaction;$serializedTypes={signal:Or,reaction:Oe}},en=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)}}};k([A(Ar)],en.prototype,"events",2);import*as ie from"three";import{Quaternion as IE,Vector3 as ME}from"three";var jo=H("debugtimeline"),Bo=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}},Xd=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";jo&&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 ie.Vector3().fromArray(o.values,0),this.rootEndPosition=new ie.Vector3().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),jo&&console.log(this.rootPositionOffset);else if(o.name.endsWith(r)&&(this.rootStartQuaternion=new ie.Quaternion().fromArray(o.values,0),this.rootEndQuaternion=new ie.Quaternion().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),jo)){let s=new ie.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",s)}}}},qn=class extends Bo{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),E=d.getObjectByName(f);if(E)if(s){if(!c){let b=t.tracks[0].name.substring(0,h)+".quaternion";jo&&console.warn("Create quaternion track",f,E);let y=E.quaternion,g=new ie.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";jo&&console.warn("Create position track",f,E);let y=E.position,g=new ie.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,jo&&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 Xd(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 ME(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new IE(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 ie.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new ie.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new ie.Vector3;_totalOffsetRotation=new ie.Quaternion;_totalOffsetPosition2=new ie.Vector3;_totalOffsetRotation2=new ie.Quaternion;_summedPos=new ie.Vector3;_tempPos=new ie.Vector3;_summedRot=new ie.Quaternion;_tempRot=new ie.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),E=0,b=c.duration;if(d){if(c.loop)for(E+=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(),x=this._tempRot.identity(),T=c.rotation,R=new ie.Quaternion;R.slerp(T,u);let S=this._actionOffsets[r];if(S.hasOffsets)for(let O=0;O<E;O++)S.rootPositionOffset?v.copy(S.rootPositionOffset):v.set(0,0,0),v.applyQuaternion(w).applyQuaternion(R),S.rootQuaternionOffset&&(x.copy(S.rootQuaternionOffset),w.multiply(x)),m.add(v);p.multiply(R),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 ie.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 ie.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}}},Xn=class extends Bo{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return mn(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 ie.Audio(this.listener);i.setVolume(e.asset.volume);let n=new ie.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}}},nn=class extends Bo{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)}}},Os=class extends Bo{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;Os.resolved[r]?n.sourceObject=Os.resolved[r]:(n.sourceObject=C.findByGuid(r,e.scene),Os.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=C.getComponent(n.sourceObject,rn);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)}}}}},tn=Os;z(tn,"resolved",{});var Tf=H("debugtimeline");var ul=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(){Tf&&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=ts(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=C.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Tf&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),ul.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=ul.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 qn;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 Rf.AnimationMixer(o.gameObject)),c.clips.push(f),c.mixer.uncacheAction(f),c.createHooks(l.asset,f);let E=c.mixer.clipAction(f);c.actions.push(E),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 nn;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=C.getComponent(this.gameObject,en);o&&(r.receivers.push(o),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new nn;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 tn;r.director=this,r.track=t;for(let o of t.clips)r.models.push(o);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}de.registerWaitForAllowAudio(()=>{let t=C.findObjectOfType(ti,this.context);if(!!t)for(let i of e){let n=new Xn;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)}},rn=ul;z(rn,"createTrackFunctions",{});import*as Cf from"three-mesh-ui";var si=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 DE}from"three";var HE=H("debugeventsystem"),Oi=class extends M{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Oi.systems.length<=0&&Oi.systems.push(...C.findObjectsOfType(Oi,e)));for(let i of Oi.systems)if(i.context===e)return;let t=new DE;C.addNewComponent(t,Oi),e.scene.add(t)}static ensureUpdateMeshUI(e,t){ai.update(e,t)}static markUIDirty(e){ai.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Oi.systems.push(this)}onDestroy(){Oi.systems.splice(Oi.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)}onEnable(){se.addEventListener("select-start",(t,i)=>{if(!i.grab)return;ai.resetLastSelected();let n=new si;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=!1,i.grab&&!this.handleEvents(i.grab,n)&&(i.grab=null)});let e=new Re;se.addEventListener("select-end",(t,i)=>{if(!i.grab)return;let n=new si;n.inputSource=t,n.isDown=t.selectionDown,n.isUp=t.selectionUp,n.isPressed=t.selectionPressed,n.isClicked=t.selectionClick,this.handleEvents(i.grab,n)}),se.addEventListener("update",t=>{e.ray=t.getRay();let i=this.performRaycast(e);if(!i)return;let n=new si;n.inputSource=t,this.handleIntersections(i,n)}),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),K.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 si(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=C.getComponent(this.context.mainCameraComponent.gameObject,$e)??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}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=C.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=[];handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&HE&&console.log("not allowed",e),!1;t.object=e,this.lastPointerEvent=t;let i=e.parent,n=!1,r=t.isClicked??!1,o=null;if(i&&i.isUI){let s=(t.isPressed||t.isClicked)??!1;if(i.shadowComponentOwner){let c=i.shadowComponentOwner.gameObject;if(c){if(o=this.tryFindCanvasGroup(c),o?.isCanvasGroup===!0){if(o.blocksRaycasts===!1)return!1;if(o.interactable===!1)return!0}if(C.foreachComponent(c,h=>{if(typeof h.raycastTarget=="boolean")return h},!1)?.raycastTarget===!1)return!1;let l=this.handleMeshUIIntersection(e,s);e=c,n=!0}}if(!n&&this.handleMeshUiObjectWithoutShadowDom(i,s))return!0}if(this.objectsHoveredThisFrame.push(e),o===null||o.interactable){let s=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let c=C.getComponentsInParent(e,M,this.handleEventsArray);for(let d=0;d<c.length;d++){if(t.used)return!0;if(c[d].destroyed)continue;let l=c[d];l.interactable!==!1&&(l.onPointerEnter&&(s||l.onPointerEnter(t)),t.isDown&&l.onPointerDown&&!this.raisedPointerDownEvents.includes(l)&&(l.onPointerDown(t),this.raisedPointerDownEvents.push(l)),t.isUp&&l.onPointerUp&&l.onPointerUp(t),t.isClicked&&l.onPointerClick&&l.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=ai.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&ai.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];ai.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?C.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}tryFindCanvasGroup(e){if(!e)return null;let t=C.foreachComponent(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)}},Ke=Oi;z(Ke,"didSearchEventSystem",!1),z(Ke,"systems",[]);var ai=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}};z(ai,"lastSelected",null),z(ai,"lastUpdateFrame",[]),z(ai,"needsUpdate",!1);import{AxesHelper as jE}from"three";var Fo="./include";Cf.Block.prototype.interactable={get(){return this.interactive},set(a){this.interactable=a}};var Ge=class extends M{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Ke.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=C.getComponentInParent(this.gameObject,on)),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=C.getComponentInParent(i,Ge),!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}if(e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e.shadowComponentOwner=this,e.traverse(n=>{n.shadowComponentOwner===void 0&&(n.shadowComponentOwner=this)}),this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let n=this._parentComponent.shadowComponent;n&&n?.add(e)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),ci&&e.add(new jE(.5)),this.onAfterAddedToScene()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e.shadowComponentOwner===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)}},on=class extends Ge{awake(){super.awake()}};import{Color as NE,Texture as If}from"three";import*as Yd from"three-mesh-ui";import{Matrix4 as BE,Object3D as FE,Vector2 as Af,Vector3 as Qd}from"three";import{FrontSide as Sf,DoubleSide as Pf}from"three";function No(a,e){if(!a)return;let t=a.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?Pf:Sf,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?Pf:Sf,a.castShadow=e.castShadows?e.castShadows:!1,a.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of a.children)No(i,e)}function pl(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 Of(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 kf=H("debugui"),zo=class{width;height},kr=class{x;y;width;height},pt=class extends Ge{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 Qd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new BE,this.rectBlock=new FE,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new Qd),pl(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)&&(kf&&console.log("updating",this.name),this.applyTransform()),Ke.ensureUpdateMeshUI(Yd,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},kf&&console.log(this.name,e);let t=new Yd.Block(e);return this._createdBlocks.push(t),t}};k([A(kr)],pt.prototype,"rect",2),k([A(Af)],pt.prototype,"sizeDelta",2),k([A(Qd)],pt.prototype,"anchoredPosition3D",2),k([A(Af)],pt.prototype,"pivot",2);var Pt=class extends Ge{get isGraphic(){return!0}get color(){return this._color||(this._color=new _e(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 _e(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=this.gameObject.getComponent(pt)),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(),pl(this,"_color",()=>Of(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)}};k([A(_e)],Pt.prototype,"color",1),k([A()],Pt.prototype,"raycastTarget",2);var sn=class extends Pt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var fl=class{texture;rect};k([A(If)],fl.prototype,"texture",2);var an=class extends sn{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 NE(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};k([A(fl)],an.prototype,"sprite",2);var Ir=class extends sn{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};k([A(If)],Ir.prototype,"mainTexture",2);var Vo=H("debugbutton");var Vt=class extends M{onClick;_isHovered=!1;onPointerEnter(e){Vo&&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(){Vo&&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){Vo&&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){Vo&&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){Vo&&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(),Vo&&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=C.getComponent(this.gameObject,an),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()}};k([A(Oe)],Vt.prototype,"onClick",2),k([A()],Vt.prototype,"colors",2),k([A()],Vt.prototype,"transition",2),k([A()],Vt.prototype,"animationTriggers",2),k([A(yt)],Vt.prototype,"animator",2),k([A()],Vt.prototype,"interactable",1);var Kd=class extends on{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 Kd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}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(),No(this.shadowComponent,this);for(let e of this.gameObject.getComponentsInChildren(Ge))No(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(Y.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}}},Je=Kd;k([A()],Je.prototype,"renderOnTop",1),k([A()],Je.prototype,"depthWrite",1),k([A()],Je.prototype,"doubleSided",1),k([A()],Je.prototype,"castShadows",1),k([A()],Je.prototype,"receiveShadows",1),k([A()],Je.prototype,"renderMode",1),k([A(Je)],Je.prototype,"rootCanvas",1);var ln=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 C.getComponentsInChildren(this.gameObject,Pt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};k([A()],ln.prototype,"alpha",1),k([A()],ln.prototype,"interactable",2),k([A()],ln.prototype,"blocksRaycasts",2);import*as Mf from"three-mesh-ui";import{Color as F}from"three";var zE=H("debugtext");var Le=class extends Pt{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){zE&&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={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:this.fontSize,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(e,this.fontStyle),e}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.shadowComponentOwner===void 0&&(e.shadowComponentOwner=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 Mf.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||(No(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 As(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=VE(r)}else t.fontColor=new F(1,1,1)}else if(e.type=="b"){let n=new As(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new As(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=mn(this.sourceId,this.font),this.font):null}};k([A(Je)],Le.prototype,"canvas",2),k([A()],Le.prototype,"alignment",2),k([A()],Le.prototype,"verticalOverflow",2),k([A()],Le.prototype,"horizontalOverflow",2),k([A()],Le.prototype,"lineSpacing",2),k([A()],Le.prototype,"supportRichText",2),k([A()],Le.prototype,"font",2),k([A()],Le.prototype,"fontStyle",2),k([A()],Le.prototype,"text",1),k([A()],Le.prototype,"fontSize",1);var As=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function VE(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 F(i/255,n/255,r/255)}switch(a){case"black":return new F(0,0,0);case"white":return new F(1,1,1);case"red":return new F(1,0,0);case"lime":return new F(0,1,0);case"blue":return new F(0,0,1);case"yellow":return new F(1,1,0);case"cyan":return new F(0,1,1);case"magenta":return new F(1,0,1);case"silver":return new F(.75,.75,.75);case"gray":return new F(.5,.5,.5);case"maroon":return new F(.5,0,0);case"olive":return new F(.5,.5,0);case"green":return new F(0,.5,0);case"purple":return new F(.5,0,.5);case"teal":return new F(0,.5,.5);case"navy":return new F(0,0,.5);case"darkred":return new F(.54,0,0);case"brown":return new F(.55,.27,0);case"firebrick":return new F(.69,.13,.13);case"crimson":return new F(.86,.08,.24);case"tomato":return new F(1,.39,.28);case"coral":return new F(1,.49,.31);case"indianred":return new F(.6,.31,.51);case"lightcoral":return new F(.94,.5,.5);case"darkorange":return new F(1,.55,0);case"orange":return new F(1,.65,0);case"gold":return new F(1,.84,0);case"darkgoldenrod":return new F(.72,.53,.04);case"goldenrod":return new F(.85,.65,.13);case"palegoldenrod":return new F(.93,.87,.67);case"darkkhaki":return new F(.74,.7,.42);case"khaki":return new F(.94,.9,.55);case"yellowgreen":return new F(.6,.8,.19);case"darkolivegreen":return new F(.33,.42,.18);case"olivedrab":return new F(.42,.56,.14);case"lawngreen":return new F(.49,.99,0);case"chartreuse":return new F(.5,1,0);case"greenyellow":return new F(.68,1,.18);case"darkgreen":return new F(0,.39,0);case"forestgreen":return new F(.13,.55,.13);case"limegreen":return new F(.19,.8,.19);case"lightgreen":return new F(.56,.93,.56);case"palegreen":return new F(.59,.98,.59);case"darkseagreen":return new F(.56,.74,.56);case"mediumspringgreen":return new F(0,.98,.6);case"springgreen":return new F(0,1,.5);case"seagreen":return new F(.18,.31,.31);case"mediumaquamarine":return new F(.4,.8,.66);case"mediumseagreen":return new F(.24,.7,.44);case"lightseagreen":return new F(.13,.7,.67);case"darkslategray":return new F(.18,.31,.31);case"darkcyan":return new F(0,.55,.55);case"aqua":return new F(0,1,1);case"lightcyan":return new F(.8,1,1);case"darkturquoise":return new F(0,.81,.82);case"turquoise":return new F(0,.82,.82);case"mediumturquoise":return new F(.28,.82,.8);case"paleturquoise":return new F(.68,1,.93);case"aquamarine":return new F(.5,1,.83);case"powderblue":return new F(.69,.88,.9);case"cadetblue":return new F(.37,.62,.63);case"steelblue":return new F(.27,.51,.71);case"cornflowerblue":return new F(.39,.58,.93);case"deepskyblue":return new F(0,.7,1);case"dodgerblue":return new F(.12,.56,1);case"lightblue":return new F(.68,.85,.9);case"skyblue":return new F(.53,.81,.92);case"lightskyblue":return new F(.53,.81,.98);case"midnightblue":return new F(.18,.18,.31);case"darkblue":return new F(0,0,.55);case"mediumblue":return new F(0,0,.82);case"royalblue":return new F(.25,.41,.88);case"blueviolet":return new F(.54,.17,.89);case"indigo":return new F(.29,0,.51);case"darkslateblue":return new F(.28,.24,.55);case"slateblue":return new F(.42,.35,.8);case"mediumslateblue":return new F(.48,.41,.9);case"mediumpurple":return new F(.58,.44,.86);case"darkmagenta":return new F(.55,0,.55);case"darkviolet":return new F(.58,0,.83);case"darkorchid":return new F(.6,.2,.8);case"mediumorchid":return new F(.73,.33,.83);case"thistle":return new F(.84,.75,.85);case"plum":return new F(.87,.63,.87);case"violet":return new F(.93,.51,.93);case"fuchsia":return new F(1,0,1);case"orchid":return new F(.85,.44,.84);case"mediumvioletred":return new F(.78,.08,.52);case"palevioletred":return new F(.86,.44,.58);case"hotpink":return new F(1,.4,.71);case"deeppink":return new F(1,.08,.58);case"lightpink":return new F(1,.71,.76);case"pink":return new F(1,.75,.78);case"antiquewhite":return new F(.98,.92,.84);case"beige":return new F(.96,.96,.86);case"bisque":return new F(1,.89,.77);case"blanchedalmond":return new F(1,.92,.82);case"wheat":return new F(.96,.87,.87);case"cornsilk":return new F(1,.97,.86);case"lemonchiffon":return new F(1,.98,.8);case"lightgoldenrodyellow":return new F(.98,.98,.82);case"lightyellow":return new F(1,1,.8);case"saddlebrown":return new F(.55,.27,.07);case"sienna":return new F(.63,.32,.18);case"chocolate":return new F(.82,.41,.12);case"peru":return new F(.82,.52,.25);case"sandybrown":return new F(.96,.64,.38);case"burlywood":return new F(.87,.72,.53);case"tan":return new F(.82,.71,.55);case"rosybrown":return new F(.74,.56,.56);case"moccasin":return new F(1,.89,.71);case"navajowhite":return new F(1,.87,.68);case"peachpuff":return new F(1,.85,.73);case"mistyrose":return new F(1,.89,.88);case"lavenderblush":return new F(1,.94,.93);case"linen":return new F(.98,.94,.9);case"oldlace":return new F(.99,.96,.9);case"papayawhip":return new F(1,.94,.84);case"seashell":return new F(1,.96,.93);case"mintcream":return new F(.98,1,.98);case"slategray":return new F(.44,.5,.56);case"lightslategray":return new F(.47,.53,.6);case"lightsteelblue":return new F(.69,.77,.87);case"lavender":return new F(.9,.9,.98);case"floralwhite":return new F(1,.98,.98);case"aliceblue":return new F(.94,.97,1);case"ghostwhite":return new F(.97,.97,1);case"honeydew":return new F(.94,1,.94);case"ivory":return new F(1,1,.94);case"azure":return new F(.94,1,1);case"snow":return new F(1,.98,.98);case"dimgray":return new F(.4,.4,.4);case"darkgray":return new F(.66,.66,.66);case"lightgray":return new F(.83,.83,.83);case"gainsboro":return new F(.86,.86,.86);case"whitesmoke":return new F(.96,.96,.96)}return new F(1,1,1)}var Mr=H("debuginputfield"),J=class extends M{get text(){return this.textComponent?.text??""}get isFocused(){return J.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){Mr&&console.log(this.name,this)}onEnable(){J.htmlField||(J.htmlField=document.createElement("input"),J.htmlField.classList.add("ar"),document.body.appendChild(J.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),J.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&C.setActive(this.placeholder.gameObject,!1)}onDisable(){J.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){Mr&&console.log("CLICK",e,J.active),J.activeTime=this.context.time.time,J.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();J.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-J.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(J.active!==this&&(Mr&&console.log("Select",this.name,this,J.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,J.htmlField?.value),J.active?.onDeselected(),J.active=this,this.placeholder&&C.setActive(this.placeholder.gameObject,!1),J.htmlField)){if(J.htmlField.value=this.textComponent?.text||"",Mr&&console.log("set input field value",J.htmlField.value),this.context.isInXR){let e=this.context.arOverlayElement;e&&(J.htmlField.style.width="0px",J.htmlField.style.height="0px",e.append(J.htmlField))}this.selectInputField()}}onDeselected(){J.active===this&&(J.active=null,Mr&&console.log("Deselect",this.name,this),J.htmlField&&(J.htmlField.blur(),document.body.append(J.htmlField),J.htmlField.style.width="",J.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&C.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(J.active===this){if(Mr&&console.log(e.code,e,J.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}J.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&C.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&J.htmlField){if(this.textComponent.text!==J.htmlField.value){Mr&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=J.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=J.htmlField.value}}selectInputField(){J.htmlField&&(J.htmlField.setSelectionRange(J.htmlField.value.length,J.htmlField.value.length),J.htmlField.focus())}},Ot=J;z(Ot,"active",null),z(Ot,"activeTime",-1),z(Ot,"htmlField",null),k([A(Le)],Ot.prototype,"textComponent",2),k([A(Le)],Ot.prototype,"placeholder",2),k([A(Oe)],Ot.prototype,"onValueChanged",2),k([A(Oe)],Ot.prototype,"onEndEdit",2);import*as Lf from"three-mesh-ui";import*as ks from"three";var Df=(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))(Df||{}),Uo=class extends Ge{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=Df[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=this.gameObject.getComponent(pt);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:Fo+"/"+t+"-msdf.json",fontTexture:Fo+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new ks.Color(this.colors.keyboardBack),backspaceTexture:Fo+"/backspace.png",shiftTexture:Fo+"/shift.png",enterTexture:Fo+"/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 Lf.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(o=>{o.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new ks.Color(this.colors.button),backgroundOpacity:1}}),o.setState("normal"),o.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new ks.Color(this.colors.hovered),backgroundOpacity:1}}),o.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new ks.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(`
139
+ `);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 cn=class extends M{reverseArrangement=!1},Go=class extends cn{},Wo=class extends cn{},qo=class extends cn{};var Lr=class extends M{awake(){Ke.createIfNoneExists(this.context)}onEnable(){Ke.instance?.register(this)}onDisable(){Ke.instance?.unregister(this)}performRaycast(e=null){return null}},Ai=class extends Lr{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new Re,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},Xo=class extends Ai{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as Hf from"three";import{HTMLMesh as UE}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as GE}from"three/examples/jsm/interactive/InteractiveGroup.js";var Qo=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 GE(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new UE(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=Ys(this.gameObject).clone();Ks(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let o=new Hf.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 Is=class{};var ml=class extends M{toggleKey="p";update(){this.context.input.isKeyDown("p")&&this.context.domElement.classList.toggle("presentation-mode")}};import*as jf from"three";import{Raycaster as XE,Vector3 as QE}from"three";import*as gl from"three";import{MeshLine as WE,MeshLineMaterial as qE}from"three.meshline";var Zd=class{id=0;points=[];line=new WE;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 gl.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=Zd.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 qE({color:10066329,lineWidth:.01})},Yo=Zd;z(Yo,"wp",new gl.Vector3);var Dr=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=C.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 Yo(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 YE}from"three.meshline";var bl=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new QE,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},vl=class extends M{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=C.getComponent(this.gameObject,Dr),this.lines||(this.lines=C.addNewComponent(this.gameObject,Dr))),this.orbit=C.findObjectOfType($e,this.context)??void 0,this._states.mouse=new bl;let e={};se.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),se.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),se.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);vl._raycaster.setFromCamera(t,this.context.mainCamera);let i=vl._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 bl,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=q(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 Re;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(!!C.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=ut.colorFromHashCode(ut.hashCode(this.context.connection.connectionId)):e=new jf.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new YE({color:e,lineWidth:Y.lerp(.005,.01,Math.random())})}},Ms=vl;z(Ms,"_raycaster",new XE);import{Object3D as KE}from"three";var Ls=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=C.getComponent(t,ki);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=ki.all.length-1;t>=0;t--){let i=ki.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};k([A(it)],Ls.prototype,"asset",2);var Ut=class extends M{static get all(){return Ut._all}static get local(){return Ut._local}static isLocalPlayer(e){return e instanceof KE?C.getComponentInParent(e,Ut)?.isLocalPlayer??!1:e instanceof st?C.getComponentInParent(e.gameObject,Ut)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&Ut.local.push(this),Ut.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(){Vr(this.gameObject,this.context.connection)}onDestroy(){if(Ut.all.splice(Ut.all.indexOf(this),1),this.isLocalPlayer){let e=Ut._local.indexOf(this);e>=0&&Ut._local.splice(e,1)}}},ki=Ut;z(ki,"_all",[]),z(ki,"_local",[]),k([rl(),A()],ki.prototype,"owner",2);D.add("AlignmentConstraint",On);D.add("Animation",ei);D.add("AnimationCurve",pr);D.add("Animator",yt);D.add("AnimatorController",$t);D.add("AudioListener",ti);D.add("AudioSource",de);D.add("AvatarModel",fr);D.add("AvatarLoader",An);D.add("AxesHelper",Ui);D.add("BasicIKConstraint",ro);D.add("BoxHelperComponent",ct);D.add("Camera",re);D.add("Collider",mt);D.add("SphereCollider",Tn);D.add("BoxCollider",Rn);D.add("InstantiateOptions",be);D.add("DeleteBox",mr);D.add("Deletable",oo);D.add("DeviceFlag",gr);D.add("DragControls",_t);D.add("DropListener",Dn);D.add("Duplicatable",wi);D.add("CallInfo",_i);D.add("EventListEvent",Er);D.add("EventList",Oe);D.add("EventTrigger",go);D.add("FlyControls",bo);D.add("BoxGizmo",Qi);D.add("GltfExportBox",yo);D.add("GltfExport",zt);D.add("GridHelper",Yi);D.add("GroundProjectedEnv",Ki);D.add("Interactable",Dt);D.add("UsageMarker",Ht);D.add("Light",Ye);D.add("LODModel",xi);D.add("LODGroup",jn);D.add("LookAtConstraint",wr);D.add("NavMesh",wo);D.add("NavMeshAgent",_o);D.add("NestedGltf",_r);D.add("Networking",gt);D.add("OffsetConstraint",Ti);D.add("OrbitControls",$e);D.add("ParticleSystemRenderer",Tr);D.add("ParticleSystem",Co);D.add("MainModule",xo);D.add("EmissionModule",To);D.add("ShapeModule",Ro);D.add("PlayerColor",ut);D.add("FieldWithDefault",Yr);D.add("Renderer",ye);D.add("MeshRenderer",hr);D.add("SkinnedMeshRenderer",Kr);D.add("InstancingUtil",ne);D.add("RendererLightmap",zi);D.add("Rigidbody",ce);D.add("ScreenCapture",Ji);D.add("ShadowCatcher",Bn);D.add("RemoteSkybox",Fn);D.add("SmoothFollow",Ri);D.add("SpatialTriggerReceiver",xt);D.add("SpatialTrigger",Zi);D.add("SpectatorCamera",Oo);D.add("SpringJoint",Ao);D.add("Sprite",Rr);D.add("SpriteRenderer",$i);D.add("SyncedCamera",zn);D.add("SyncedRoom",oi);D.add("SyncedTransform",Qe);D.add("TestRunner",ko);D.add("TestSimulateUserData",Io);D.add("TransformGizmo",Cr);D.add("VideoPlayer",Me);D.add("Voip",et);D.add("VolumeParameter",Mo);D.add("VolumeComponent",Ci);D.add("ToneMapping",Un);D.add("ColorAdjustments",Gn);D.add("VolumeProfile",Vn);D.add("Volume",Sr);D.add("WebARSessionRoot",Ft);D.add("WebXR",K);D.add("WebAR",Ln);D.add("AvatarMarker",ue);D.add("WebXRAvatar",Bt);D.add("TeleportTarget",br);D.add("WebXRController",se);D.add("AttachedObject",ht);D.add("XRGrabModel",Pr);D.add("XRGrabRendering",Lo);D.add("XRRig",Mn);D.add("VRUserState",Nt);D.add("WebXRSync",Xi);D.add("XRState",Et);D.add("XRFlag",Pe);D.add("AvatarBlink_Simple",Si);D.add("AvatarEyeLook_Rotation",Pi);D.add("Avatar_POI",xe);D.add("Avatar_Brain_LookAt",qi);D.add("Avatar_MouthShapes",Wn);D.add("Avatar_MustacheShake",Do);D.add("__Ignore",Is);D.add("LogStats",Ho);D.add("RGBAColor",_e);D.add("PlayableDirector",rn);D.add("SignalAsset",Or);D.add("SignalReceiverEvent",Ar);D.add("SignalReceiver",en);D.add("AnimationTrackHandler",qn);D.add("AudioTrackHandler",Xn);D.add("SignalTrackHandler",nn);D.add("ControlTrackHandler",tn);D.add("BaseUIComponent",Ge);D.add("UIRootComponent",on);D.add("Button",Vt);D.add("Canvas",Je);D.add("CanvasGroup",ln);D.add("EventSystem",Ke);D.add("Graphic",Pt);D.add("MaskableGraphic",sn);D.add("Image",an);D.add("RawImage",Ir);D.add("InputField",Ot);D.add("Keyboard",Uo);D.add("LayoutGroup",cn);D.add("VerticalLayoutGroup",Go);D.add("HorizontalLayoutGroup",Wo);D.add("GridLayoutGroup",qo);D.add("PointerEventData",si);D.add("Raycaster",Lr);D.add("ObjectRaycaster",Ai);D.add("GraphicRaycaster",Xo);D.add("Size",zo);D.add("Rect",kr);D.add("RectTransform",pt);D.add("SpatialHtml",Qo);D.add("Text",Le);D.add("PresentationMode",ml);D.add("LinesDrawer",Ms);D.add("LineInstanceHandler",Yo);D.add("LinesManager",Dr);D.add("PlayerSync",Ls);D.add("PlayerState",ki);var Bf=ke;function tf(a,e){let i=lc(a,e);return i!==void 0?i:null}async function za(a,e,t,i=null,n){if(!t)return;let r=[],o=i;typeof o=="number"&&(o=new Ue(i));let s=new Gr(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 eh(s,d,c,r);if(t.children)for(let d of t.children)await eh(s,d,c,r);a.new_scripts_pre_setup_callbacks.push(()=>{for(let d of c)JE(d,s);if(o){$d(t,o);for(let d of t.scenes)$d(d,o)}})}function $d(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)$d(t,e)}}var Ds=[];async function eh(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=D.get(o.name);if(s!=null){let c=new s;c.sourceId=a.gltfId,ir(c,o),Vs(c,e,!1),t.push({instance:c,compData:o,obj:e})}else Bf&&console.debug("unknown component: "+o.name),Ds.includes(o.name)||Ds.push(o.name)}catch(s){console.error(o.name+" - "+s.message,s)}if(Ds.length>0){let o=Ds.join(", ");console.warn("unknown components: "+o),Ds.length=0}}if(e.children)for(let r of e.children)await eh(a,r,t,i)}function JE(a,e){let{instance:t,compData:i,obj:n}=a;e.object=n,e.target=t;let r=!0;r=os(t,i,e)===!0,Bf&&console.debug("add "+i.name,i,t)}import*as fe from"three";import*as Ff from"three";var ZE=new Ff.FileLoader;async function th(a){return new Promise((e,t)=>{ZE.load(a,e,void 0,t)})}import{Vector4 as Qn,FileLoader as ew,DataTexture as sh,RGBAFormat as tw,Color as iw}from"three";var Hs=new Uint8Array(4);Hs[0]=255;Hs[1]=255;Hs[2]=255;Hs[3]=255;var Vf=new sh(Hs,1,1,tw);function Uf(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 sh(n,e,e);return c.needsUpdate=!0,c}function Gf(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 iw;for(let f=0;f<n;f++){let E=Math.floor(f/n*d),b=Y.clamp(E+1,0,d-1),y=c[E],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 x=0;x<i;x++){let T=(f*i+x)*4;l[T+0]=m,l[T+1]=v,l[T+2]=w,l[T+3]=255}}let u=new sh(l,i,n);return u.needsUpdate=!0,u}var nh=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},rh=class{loaded=new Map;async loadShader(e){let t=await th(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 th(t),n=new nh(e,i);return this.loaded.set(t,n),n}},xN=new rh;function js(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 Qn(n,r,o,s);e.push(c)}return e}var ih=[],Nf=[];function ah(a,e){if(ih.length===0)for(let t=0;t<27;t++)ih.push(0);e||(e=ih);for(let t=0;t<27;t++)Nf[t]=e[t];e=Nf,a.unity_SHAr={value:new Qn(e[9],e[3],e[6],e[0])},a.unity_SHBr={value:new Qn(e[12],e[15],e[18],e[21])},a.unity_SHAg={value:new Qn(e[10],e[4],e[7],e[1])},a.unity_SHBg={value:new Qn(e[13],e[16],e[19],e[22])},a.unity_SHAb={value:new Qn(e[11],e[5],e[8],e[2])},a.unity_SHBb={value:new Qn(e[14],e[17],e[20],e[23])},a.unity_SHC={value:new Qn(e[24],e[25],e[26],1)}}var oh=class{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}};async function Wf(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 zf(r),!o.code&&o.uri&&await zf(o),!r.code||!o.code)return null;let s=a.techniques[e];return new oh(r.code,o.code,s)}}return console.error("Shader technique not found",e),null}async function zf(a){let e=a.uri;if(!!e)if(e.endsWith(".glsl")){let i=await new ew().loadAsync(e);a.code=i.toString()}else a.code=nw(a.uri)}function nw(a){return decodeURIComponent(Array.prototype.map.call(atob(a),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}import{RawShaderMaterial as ow}from"three";var dn=H("debugshaders"),Ko="NEEDLE_techniques_webgl";var lh=class{objectToWorldMatrix=new fe.Matrix4;worldToObjectMatrix=new fe.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),js(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),js(this.worldToObjectMatrix,this.worldToObject)}};var pe=class extends ow{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){let e=super.clone();return qf(e),e}constructor(e,...t){super(...t),this.identifier=e,dn&&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)&&Q.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=Q.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&Q.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=Q.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}dn&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},ah(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new fe.Vector4(r,r,r,r)},dn&&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 lh;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&Q.Current.setRequireColor(!0),this.depthTextureUniform&&Q.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,r,o){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=Q.Current;e&&(pe.viewProjection&&this.uniforms[this._viewProjectionName]&&(pe.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),js(pe.viewProjection,pe._viewProjectionValues)),pe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(pe.viewMatrix.copy(e.matrixWorldInverse),js(pe.viewMatrix,pe._viewMatrixValues)),this.uniforms[pe._worldSpaceCameraPosName]&&pe._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.rendererData.timeVec4);let n=i?.mainLight;if(n){let s=n.getWorldPosition(pe._mainLightPosition);this.uniforms._MainLightPosition={value:s.normalize()},pe._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:pe._mainLightColor};let c=n.intensity;pe._lightData.z=c,this.uniforms.unity_LightData={value:pe._lightData}}if(e&&(pe.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=pe._viewProjectionValues),pe.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=pe._viewMatrixValues),this.uniforms[pe._worldSpaceCameraPosName]&&(this.uniforms[pe._worldSpaceCameraPosName]={value:pe._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=pe;z(Gt,"viewProjection",new fe.Matrix4),z(Gt,"_viewProjectionValues",[]),z(Gt,"viewMatrix",new fe.Matrix4),z(Gt,"_viewMatrixValues",[]),z(Gt,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),z(Gt,"_worldSpaceCameraPos",new fe.Vector3),z(Gt,"_mainLightColor",new fe.Vector4),z(Gt,"_mainLightPosition",new fe.Vector3),z(Gt,"_lightData",new fe.Vector4);var yl=class{get name(){return Ko}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return dn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Ko])return dn&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[Ko].technique;if(i<0)return null;let n=this.parser.json.extensions[Ko];if(!n)return null;dn&&console.log(n);let r=n.techniques[i];return r?new Promise(async(o,s)=>{let c=await Wf(n,r.program),d=c?.fragmentShader,l=c?.vertexShader;if(!d||!l)return s();dn&&console.log("loadMaterial",t,c);let h={},u=r.uniforms;for(let y in u){let g=y;switch(g){case"_TimeParameters":let p=new fe.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[Ko]){let y=t.extensions[Ko];if(y.technique===i){dn&&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=fe.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 fe.Vector4(p[0],p[1],p[2],p[3])};continue}h[g]={value:p}}}}let E=new Gt(this.identifier,{name:t.name??"",uniforms:h,vertexShader:l,fragmentShader:d,lights:!1});switch(h._Cull?.value){case 0:E.side=fe.DoubleSide;break;case 1:E.side=fe.BackSide;break;case 2:E.side=fe.FrontSide;break;default:E.side=fe.FrontSide;break}E.transparent=f,f&&(E.depthWrite=!1),ah(h),E.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:Vf},console.warn("Missing/unassigned texture, fallback to white: "+g);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+g,u[y]);break}}dn&&console.log(E.uuid,h),qf(E),o(E)}):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}})}import{EXRLoader as sw}from"three/examples/jsm/loaders/EXRLoader";var ch=H("debugexr"),El=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",ch&&console.log(e)}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(ch&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let o=r.extensions[t],s=new sw(i.options.manager);return ch&&console.log("EXT_texture_exr.loadTexture",o,s),i.loadTextureImage(e,o.source,s)}};var Xf="NEEDLE_gameobject_data",wl=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{FloatType as aw,HalfFloatType as lw,sRGBEncoding as cw}from"three";var Qf="NEEDLE_lightmaps",dw=H("debuglightmapsextension"),Bs=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(Bs||{}),_l=class{get name(){return Qf}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[Qf];if(i){let n=i.textures;return n.length?(dw&&console.log(i),new Promise(async(r,o)=>{let s=[];for(let c of n)if(c.pointer){let d=Ur(this.parser,c.pointer).then(l=>{let h=l;h?.isTexture&&(this.registry?(c.type!==0&&(h.encoding=cw),(h.type==aw||h.type==lw)&&(h.flipY=!0),this.registry.registerTexture(this.source,c.type,h,c.index)):console.log(Bs[c.type],c.pointer,h))});s.push(d)}await Promise.all(s),r()})):null}}return null}};import{AmbientLight as fw,Color as Yf,HemisphereLight as mw}from"three";import{Vector4 as hw,EquirectangularReflectionMapping as xl,sRGBEncoding as Tl,WebGLCubeRenderTarget as uw}from"three";import{LightProbeGenerator as pw}from"three/examples/jsm/lights/LightProbeGenerator.js";var dh=H("debugenvlight"),uh=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(uh||{});var Rl=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 hw;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 hh(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(dh&&console.log(this.sceneLightSettings?uh[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=Tl,n.mapping=xl,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=Gf(t[0],t[1],t[2],64,64);i.encoding=Tl,i.mapping=xl,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=Uf(this.sceneLightSettings.ambientLight,64);t.encoding=Tl,t.mapping=xl,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 dh&&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={}},hh=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=xl,t.encoding=Tl}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){dh&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new uw(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=pw.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}};var Kf="NEEDLE_lighting_settings",Jo=H("debugenvlight"),Cl=class{get name(){return Kf}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[Kf];if(i){Jo&&console.log(i);let n=C.addNewComponent(e.scene,ph,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new Yf().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new Yf().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},ph=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)}Jo&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(Jo&&console.log("Enable scene lighting",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),e||Jo&&console.warn("This is no active?!",this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&!this._ambientLightObj&&(this._ambientLightObj=new fw(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 mw(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=>{Jo&&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(){Jo&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};function mh(a){let e=new vo;return a.register(t=>(e.parser=t,e)),e}var fh=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 gh(a,e,t){a.register(n=>new wl(n)),a.register(n=>new oa(n)),a.register(n=>new _l(n,e.lightmaps,t)),a.register(n=>new Cl(n,t,e)),a.register(n=>new yl(n,t)),a.register(n=>new cr(n,t)),a.register(n=>new Vi(n,t,e)),a.register(n=>new El(n));let i=a.setAnimationPointerResolver;typeof i=="function"&&i.bind(a)(new fh)}var gw=H("printGltf");var Yn=class{context;loader;path;gltf;constructor(e,t,i,n){this.context=e,this.path=t,this.loader=i,this.gltf=n}},Jf={};function Zo(a,e){if(Jf[a])for(let t of Jf[a])t(e)}async function $f(a,e,t,i,n){gw&&console.log(t),await a.assets.registerGltf(t),await za(a,e,t,i,n)}function no(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 Zf;gh(n,a,t);let o=mh(n);return new Promise((s,c)=>{try{dr(n,a),Zo(0,new Yn(a,t,n)),n.parse(e,t,async d=>{Zo(1,new Yn(a,t,n,d)),await $f(a,t,d,i,o),Zo(10,new Yn(a,t,n,d)),s(d)},d=>{console.error("failed loading "+t,d),s(void 0)})}catch(d){console.error(d),c(d)}})}function yr(a,e,t,i=!1,n){let r=new Zf;gh(r,a,e);let s=mh(r);return new Promise((c,d)=>{try{dr(r,a),Zo(0,new Yn(a,e,r)),r.load(e,async l=>{Zo(1,new Yn(a,e,r,l)),await $f(a,e,l,t,s),Zo(10,new Yn(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)}})}import*as Kn from"three";function Sl(a,e,t){let i=C.getComponentInChildren(a,_t);if(i||(i=C.addNewComponent(a,_t,!1),i.guid=e.generateUUID()),i&&!C.getComponent(i.gameObject,Qe)){let r=C.addNewComponent(i.gameObject,Qe,!1);r.guid=e.generateUUID()}if(i&&!C.getComponentInParent(i.gameObject,Ai)){let r=C.addNewComponent(i.gameObject,Ai,!1);r.guid=e.generateUUID()}if(t&&t.animations?.length>0){let r=t.animations[0],o=C.addNewComponent(a,ei,!1);o.animations=[r]}let n=!1;a.traverse(r=>{!r||r.isSkinnedMesh===!0&&(n||console.log("Disabling frustum culling for skinned meshes",t),n=!0,r.frustumCulled=!1)})}var bh=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 Yp(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=ea(),l=new Ue(d),h=await yr(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&&vw(e.connection,a,d,u,t),Sl(u,l,h),n(h)}}}):(console.warn("Unsupported file type: "+i),console.log(a),null)}async function Kp(a,e){return new Promise(async(t,i)=>{let n=ea(),r=new Ue(n),o=await yr(e,a.toString(),r,!0);if(o&&o.scene){let s=o.scene;Sl(s,r,o),t(o)}else console.warn("Unsupported file type: "+a.toString())})}function em(a){a.connection.beginListen("file-spawned",async e=>{if(e.sender!==a.connection.connectionId){console.log("received file event",e),yw(e,a);let t=null;try{t=await Fa(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{Ew(e,a)}if(t){let i=new Ue(e.seed),n=await no(a,t,null,i);if(n&&n.scene){let r=n.scene;if(Sl(r,i,n),e.parentGuid){let o=C.findByGuid(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 vw(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 Bp(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 bh(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 vh={};function yw(a,e){let t=new Kn.BoxGeometry,i=new Kn.Mesh(t,new Kn.MeshBasicMaterial({color:65280})),n=new Kn.BoxHelper(i,5592405);if(vh[a.guid]=n,e.scene.add(n),a.parentGuid){let r=C.findByGuid(a.parentGuid,e.scene);r&&r.add(n)}a.position&&n.position.copy(a.position)}function Ew(a,e){let t=a.guid,i=vh[t];i&&(delete vh[t],i.removeFromParent())}import*as tm from"three";var Mz=H("debugassets");var Pl=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:
140
+ `+i.src),e.preventDefault())}})}texturesLoader=new tm.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 nm from"three/examples/jsm/libs/stats.module";import*as Ii from"three";var im=!!H("debuglightmaps"),Ol=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){im&&console.log("Registering lightmap",e,Bs[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 im&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};Ii.ShaderChunk.lights_fragment_maps=Ii.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
141
141
 
142
142
  vec2 lUv = vUv2.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
143
143
  vec4 lightMapTexel = texture2D( lightMap, lUv);
@@ -145,7 +145,7 @@ a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
145
145
  lightMapTexel.rgb *= lightMapTexel.a * 8.; // no idea where that "8" comes from... heuristically derived
146
146
  lightMapTexel.a = 1.;
147
147
  lightMapTexel = conv_sRGBToLinear(lightMapTexel);
148
- `);ki.ShaderChunk.lightmap_pars_fragment=`
148
+ `);Ii.ShaderChunk.lightmap_pars_fragment=`
149
149
  #ifdef USE_LIGHTMAP
150
150
  uniform sampler2D lightMap;
151
151
  uniform float lightMapIntensity;
@@ -156,12 +156,12 @@ a=extmap-allow-mixed`)!==-1){var m=p.sdp.split(`
156
156
  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 );
157
157
  }
158
158
  #endif
159
- `;ki.ShaderChunk.lights_fragment_begin=ki.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
159
+ `;Ii.ShaderChunk.lights_fragment_begin=Ii.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
160
160
  #if defined(USE_LIGHTMAP)
161
161
  irradiance += 0.;
162
162
  #else
163
163
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
164
- #endif`);ki.UniformsLib.lightmap.lightmapScaleOffset={value:new ki.Vector4(1,1,0,0)};var bw=H("debugSetup"),vw=H("stats"),Sl={};var Ot=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=vw?Jf.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=H("postfx");this.renderer=new fw({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=De.NoToneMapping,this.renderer.setClearColor(new De.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=De.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=De.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=i?new mw(this.renderer):null}this.scene=new De.Scene,this.application=new La(this),this.time=new Ta,this.input=new ra(this),this.physics=new xa(this),this.connection=new ka(this),this.assets=new Rl,this.rendererData=new _l(this),this.addressables=new Xa(this),this.lightmaps=new Cl(this),this.players=new Wa(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,C.destroy(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{Ot.Current=this,e&&await e(this,t)}catch(r){console.error(r),i=!1}if(!i)return;this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),nu(this),iu(this),Qf(this),Ot._current=this;for(let r=0;r<this.new_scripts.length;r++){let o=this.new_scripts[r];if(o.gameObject!==void 0&&o.gameObject!==null){o.gameObject.userData===void 0&&(o.gameObject.userData={}),o.gameObject.userData.components===void 0&&(o.gameObject.userData.components=[]);let s=o.gameObject.userData.components;s.includes(o)||s.push(o)}}if(this.post_setup_callbacks)for(let r=0;r<this.post_setup_callbacks.length;r++)Ot._current=this,await this.post_setup_callbacks[r](this);if(!this.mainCamera){Ot._current=this;let r=C.findObjectsOfType(re,this),o=r.find(s=>s.tag=="MainCamera")??r.find(s=>!0);if(o)o.tag!=="MainCamera"&&console.warn('No mainCamera configured. Some components rely on a mainCamera object being present. When exporting your scene, make sure to set the mainCamera tag on your camera. Using "'+o.name+'" as mainCamera now.'),this.setCurrentCamera(o);else{console.error("No camera found");let s=Ep(this.scene);this.setCurrentCamera(s)}}Ot._current=this,Li(this);let n=this.mainCameraComponent;if(n&&n.applyClearFlagsIfIsActiveCamera(),!this.isManagedExternally&&this.composer&&this.mainCamera){let r=new gw(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(r),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)),bw&&is(this.scene,!0)}render(e,t){for(this._stats?.begin(),Ot._current=this,this.time.update(),Li(this),Bh(),Bs(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&&(Ot._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&&(Ot._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&&(Ot._current=this,n.lateUpdate())}this.mainLight=null,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&&(Ot._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.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&&(Ot._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 De.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new pw(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new De.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=De.NearestFilter,this._renderTarget.texture.magFilter=De.NearestFilter,this._renderTarget.texture.format=De.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)}}},Q=Ot;z(Q,"_current");var Dr="ar",yw="quit-ar",Pl=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(`.${Dr}`).forEach(o=>{!o||o!==this.arContainer&&(this._reparentedObjects.push({el:o,previousParent:o.parentElement}),this.arContainer?.appendChild(o))});let r=t.getElementsByClassName(yw);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(Dr))return e;if(e.children){for(let i of e.children)if(!(!i||!i.classList)&&i.classList.contains(Dr))return i}let t=document.createElement("div");return t.classList.add(Dr),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 Ew=H("debugloadingbar");function mh(a){return a.index/a.count+a.progress.loaded/a.progress.total/a.count}var Ol=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){this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement();return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="",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=mh(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;Ew&&(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=Y.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");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);e||(this._loadingElement.style.color="white",this._loadingElement.style.display="flex");let i=document.createElement("div"),n=20;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 Y.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)",this._loadingElement.appendChild(o),this._loadingElement}};var Hr=H("debugwebcomponent"),gh=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||C.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,Q.Current=this.context;let n=await vr(this.context,e,this.getHashFromString(e));i||Li(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}},ww="needle-engine",_w="vr",xw="desktop",Tw=[Dr,_w,xw],bh=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=C;GameObject=C;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new Pl}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 Q({name:i,domElement:this,alias:r}),this._watcher=new gh(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(Sl).length<=0;){if(!this.isConnected)return;await Dh(10)}let o=Sl[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=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:!0}));!this._loadingView&&c&&(this._loadingView=new Ol(this)),c&&this._loadingView?.onLoadingBegin("begin load");let d=(h,u)=>{this._loadingProgress01=mh(h),c&&this._loadingView?.onLoadingUpdate(h,u),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(o,{progress:d});let l=t();l&&l!==s&&await this._watcher.onSourceChanged(l,!0,!0),this._loadingProgress01=1,c&&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',Sl)}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&&(Hr&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":Hr&&console.log("dracoDecoderPath",i),Oc(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(Hr&&console.log("dracoDecoderType",i),Ac(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":Hr&&console.log("ktx2DecoderPath",i),kc(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,Dr))}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 Tw)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&&(Hr&&console.log("using custom draco decoder path",e),Oc(e));let t=this.getAttribute("dracoDecoderType");t&&(Hr&&console.log("using custom draco decoder type",t),Ac(t));let i=this.getAttribute("ktx2DecoderPath");i&&(Hr&&console.log("using custom ktx2 decoder path",i),kc(i))}};window.customElements.define(ww,bh);var vh={};Ph(vh,{AlignmentConstraint:()=>Sn,Animation:()=>$t,AnimationCurve:()=>ur,AnimationTrackHandler:()=>Wn,Animator:()=>vt,AnimatorController:()=>Zt,AttachedObject:()=>ht,AudioListener:()=>ei,AudioSource:()=>he,AudioTrackHandler:()=>qn,AvatarBlink_Simple:()=>Ci,AvatarEyeLook_Rotation:()=>Si,AvatarLoader:()=>Pn,AvatarMarker:()=>pe,AvatarModel:()=>pr,Avatar_Brain_LookAt:()=>Wi,Avatar_MouthShapes:()=>Gn,Avatar_MustacheShake:()=>Lo,Avatar_POI:()=>Te,AxesHelper:()=>Vi,BaseUIComponent:()=>We,BasicIKConstraint:()=>io,BoxCollider:()=>xn,BoxGizmo:()=>Xi,BoxHelperComponent:()=>ct,Button:()=>zt,CallInfo:()=>wi,Camera:()=>re,Canvas:()=>Je,CanvasGroup:()=>sn,Collider:()=>ft,ColorAdjustments:()=>Un,ControlTrackHandler:()=>$i,Deletable:()=>ro,DeleteBox:()=>fr,DeviceFlag:()=>mr,DragControls:()=>wt,DropListener:()=>Mn,Duplicatable:()=>Ei,EmissionModule:()=>xo,EventList:()=>Ae,EventListEvent:()=>yr,EventSystem:()=>Ke,EventTrigger:()=>mo,FieldWithDefault:()=>Qr,FlyControls:()=>go,GltfExport:()=>Nt,GltfExportBox:()=>vo,Graphic:()=>St,GraphicRaycaster:()=>qo,GridHelper:()=>Qi,GridLayoutGroup:()=>Wo,GroundProjectedEnv:()=>Yi,HorizontalLayoutGroup:()=>Go,Image:()=>on,InputField:()=>Pt,InstancingUtil:()=>ne,InstantiateOptions:()=>ve,Interactable:()=>Lt,Keyboard:()=>Vo,LODGroup:()=>Dn,LODModel:()=>_i,LayoutGroup:()=>an,Light:()=>Ye,LogStats:()=>Do,LookAtConstraint:()=>Er,MainModule:()=>_o,MaskableGraphic:()=>rn,MeshRenderer:()=>dr,NavMesh:()=>Eo,NavMeshAgent:()=>wo,NestedGltf:()=>wr,Networking:()=>mt,ObjectRaycaster:()=>Oi,OffsetConstraint:()=>xi,OrbitControls:()=>$e,ParticleSystem:()=>Ro,ParticleSystemRenderer:()=>xr,PlayableDirector:()=>tn,PlayerColor:()=>ut,PointerEventData:()=>oi,RGBAColor:()=>xe,RawImage:()=>kr,Raycaster:()=>Mr,Rect:()=>Ar,RectTransform:()=>pt,RemoteSkybox:()=>Bn,Renderer:()=>Ee,RendererLightmap:()=>Ni,Rigidbody:()=>de,ScreenCapture:()=>Hn,ShadowCatcher:()=>jn,ShapeModule:()=>To,SignalAsset:()=>Pr,SignalReceiver:()=>Zi,SignalReceiverEvent:()=>Or,SignalTrackHandler:()=>en,Size:()=>No,SkinnedMeshRenderer:()=>Yr,SmoothFollow:()=>Ti,SpatialHtml:()=>Xo,SpatialTrigger:()=>Ki,SpatialTriggerReceiver:()=>_t,SpectatorCamera:()=>Po,SphereCollider:()=>_n,SpringJoint:()=>Oo,Sprite:()=>Tr,SpriteRenderer:()=>Ji,SyncedCamera:()=>Nn,SyncedRoom:()=>ri,SyncedTransform:()=>Qe,TeleportTarget:()=>gr,TestRunner:()=>Ao,TestSimulateUserData:()=>ko,Text:()=>Le,ToneMapping:()=>Vn,TransformGizmo:()=>Rr,UIRootComponent:()=>nn,UnityObject:()=>no,UsageMarker:()=>Dt,VRUserState:()=>Ft,VerticalLayoutGroup:()=>Uo,VideoPlayer:()=>Ne,Voip:()=>et,Volume:()=>Cr,VolumeComponent:()=>Ri,VolumeParameter:()=>Io,VolumeProfile:()=>zn,WebAR:()=>In,WebARSessionRoot:()=>Bt,WebXR:()=>K,WebXRAvatar:()=>jt,WebXRController:()=>ae,WebXRSync:()=>qi,XRFlag:()=>Oe,XRGrabModel:()=>Sr,XRGrabRendering:()=>Mo,XRRig:()=>kn,XRState:()=>yt});import*as Rw from"three";var yh={Context:Q};globalThis.Needle=yh;function Zf(a){for(let e in a)yh[e]=a[e]}Zf(Zl);Zf(vh);for(let a of Object.getOwnPropertyNames(C))switch(a){case"prototype":case"constructor":case"length":case"name":continue;default:yh[a]=C[a];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=Rw;export{Sn as AlignmentConstraint,$t as Animation,ur as AnimationCurve,Wn as AnimationTrackHandler,vt as Animator,Zt as AnimatorController,ht as AttachedObject,ei as AudioListener,he as AudioSource,qn as AudioTrackHandler,Ci as AvatarBlink_Simple,Si as AvatarEyeLook_Rotation,Pn as AvatarLoader,pe as AvatarMarker,pr as AvatarModel,Wi as Avatar_Brain_LookAt,Gn as Avatar_MouthShapes,Lo as Avatar_MustacheShake,Te as Avatar_POI,Vi as AxesHelper,We as BaseUIComponent,io as BasicIKConstraint,M as Behaviour,xn as BoxCollider,Xi as BoxGizmo,ct as BoxHelperComponent,zt as Button,wi as CallInfo,re as Camera,Je as Canvas,sn as CanvasGroup,ft as Collider,bs as Collision,Un as ColorAdjustments,$i as ControlTrackHandler,ro as Deletable,fr as DeleteBox,mr as DeviceFlag,wt as DragControls,Mn as DropListener,Ei as Duplicatable,xo as EmissionModule,Ae as EventList,yr as EventListEvent,Ke as EventSystem,mo as EventTrigger,Qr as FieldWithDefault,go as FlyControls,C as GameObject,Nt as GltfExport,vo as GltfExportBox,St as Graphic,qo as GraphicRaycaster,Qi as GridHelper,Wo as GridLayoutGroup,Yi as GroundProjectedEnv,Go as HorizontalLayoutGroup,on as Image,Pt as InputField,ne as InstancingUtil,ve as InstantiateOptions,Lt as Interactable,Vo as Keyboard,Dn as LODGroup,_i as LODModel,an as LayoutGroup,Ye as Light,Do as LogStats,Er as LookAtConstraint,_o as MainModule,rn as MaskableGraphic,dr as MeshRenderer,Eo as NavMesh,wo as NavMeshAgent,wr as NestedGltf,mt as Networking,Oi as ObjectRaycaster,xi as OffsetConstraint,$e as OrbitControls,Ro as ParticleSystem,xr as ParticleSystemRenderer,tn as PlayableDirector,ut as PlayerColor,oi as PointerEventData,xe as RGBAColor,kr as RawImage,Mr as Raycaster,Ar as Rect,pt as RectTransform,Bn as RemoteSkybox,Ee as Renderer,Ni as RendererLightmap,de as Rigidbody,Hn as ScreenCapture,jn as ShadowCatcher,To as ShapeModule,Pr as SignalAsset,Zi as SignalReceiver,Or as SignalReceiverEvent,en as SignalTrackHandler,No as Size,Yr as SkinnedMeshRenderer,Ti as SmoothFollow,Xo as SpatialHtml,Ki as SpatialTrigger,_t as SpatialTriggerReceiver,Po as SpectatorCamera,_n as SphereCollider,Oo as SpringJoint,Tr as Sprite,Ji as SpriteRenderer,Nn as SyncedCamera,ri as SyncedRoom,Qe as SyncedTransform,gr as TeleportTarget,Ao as TestRunner,ko as TestSimulateUserData,Le as Text,Vn as ToneMapping,Rr as TransformGizmo,nn as UIRootComponent,no as UnityObject,Dt as UsageMarker,Ft as VRUserState,Uo as VerticalLayoutGroup,Ne as VideoPlayer,et as Voip,Cr as Volume,Ri as VolumeComponent,Io as VolumeParameter,zn as VolumeProfile,In as WebAR,Bt as WebARSessionRoot,K as WebXR,jt as WebXRAvatar,ae as WebXRController,qi as WebXRSync,Oe as XRFlag,Sr as XRGrabModel,Mo as XRGrabRendering,kn as XRRig,yt as XRState,A as serializeable};
164
+ #endif`);Ii.UniformsLib.lightmap.lightmapScaleOffset={value:new Ii.Vector4(1,1,0,0)};var Rw=H("debugSetup"),Cw=H("stats"),Al={};var At=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=Cw?nm.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=H("postfx");this.renderer=new _w({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=De.NoToneMapping,this.renderer.setClearColor(new De.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=De.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=De.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=i?new xw(this.renderer):null}this.scene=new De.Scene,this.application=new ja(this),this.time=new Sa,this.input=new la(this),this.physics=new Ca(this),this.connection=new La(this),this.assets=new Pl,this.rendererData=new Rl(this),this.addressables=new Ka(this),this.lightmaps=new Ol(this),this.players=new Qa(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,C.destroy(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{At.Current=this,e&&await e(this,t)}catch(r){console.error(r),i=!1}if(!i)return;this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),su(this),ou(this),em(this),At._current=this;for(let r=0;r<this.new_scripts.length;r++){let o=this.new_scripts[r];if(o.gameObject!==void 0&&o.gameObject!==null){o.gameObject.userData===void 0&&(o.gameObject.userData={}),o.gameObject.userData.components===void 0&&(o.gameObject.userData.components=[]);let s=o.gameObject.userData.components;s.includes(o)||s.push(o)}}if(this.post_setup_callbacks)for(let r=0;r<this.post_setup_callbacks.length;r++)At._current=this,await this.post_setup_callbacks[r](this);if(!this.mainCamera){At._current=this;let r=C.findObjectsOfType(re,this),o=r.find(s=>s.tag=="MainCamera")??r.find(s=>!0);if(o)o.tag!=="MainCamera"&&console.warn('No mainCamera configured. Some components rely on a mainCamera object being present. When exporting your scene, make sure to set the mainCamera tag on your camera. Using "'+o.name+'" as mainCamera now.'),this.setCurrentCamera(o);else{console.error("No camera found");let s=Rp(this.scene);this.setCurrentCamera(s)}}At._current=this,Di(this);let n=this.mainCameraComponent;if(n&&n.applyClearFlagsIfIsActiveCamera(),!this.isManagedExternally&&this.composer&&this.mainCamera){let r=new Tw(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(r),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)),Rw&&ns(this.scene,!0)}render(e,t){for(this._stats?.begin(),At._current=this,this.time.update(),Di(this),zh(),Ns(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&&(At._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&&(At._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&&(At._current=this,n.lateUpdate())}this.mainLight=null,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&&(At._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.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&&(At._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 De.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new ww(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new De.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=De.NearestFilter,this._renderTarget.texture.magFilter=De.NearestFilter,this._renderTarget.texture.format=De.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)}}},Q=At;z(Q,"_current");var Hr="ar",Sw="quit-ar",kl=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(`.${Hr}`).forEach(o=>{!o||o!==this.arContainer&&(this._reparentedObjects.push({el:o,previousParent:o.parentElement}),this.arContainer?.appendChild(o))});let r=t.getElementsByClassName(Sw);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(Hr))return e;if(e.children){for(let i of e.children)if(!(!i||!i.classList)&&i.classList.contains(Hr))return i}let t=document.createElement("div");return t.classList.add(Hr),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 Pw=H("debugloadingbar");function yh(a){return a.index/a.count+a.progress.loaded/a.progress.total/a.count}var Il=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){this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement();return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="",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=yh(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;Pw&&(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=Y.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");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);e||(this._loadingElement.style.color="white",this._loadingElement.style.display="flex");let i=document.createElement("div"),n=20;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 Y.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)",this._loadingElement.appendChild(o),this._loadingElement}};var jr=H("debugwebcomponent"),Eh=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||C.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,Q.Current=this.context;let n=await yr(this.context,e,this.getHashFromString(e));i||Di(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}},Ow="needle-engine",Aw="vr",kw="desktop",Iw=[Hr,Aw,kw],wh=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=C;GameObject=C;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new kl}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 Q({name:i,domElement:this,alias:r}),this._watcher=new Eh(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(Al).length<=0;){if(!this.isConnected)return;await Bh(10)}let o=Al[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=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:!0}));!this._loadingView&&c&&(this._loadingView=new Il(this)),c&&this._loadingView?.onLoadingBegin("begin load");let d=(h,u)=>{this._loadingProgress01=yh(h),c&&this._loadingView?.onLoadingUpdate(h,u),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(o,{progress:d});let l=t();l&&l!==s&&await this._watcher.onSourceChanged(l,!0,!0),this._loadingProgress01=1,c&&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',Al)}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&&(jr&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":jr&&console.log("dracoDecoderPath",i),Ic(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(jr&&console.log("dracoDecoderType",i),Mc(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":jr&&console.log("ktx2DecoderPath",i),Lc(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,Hr))}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 Iw)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&&(jr&&console.log("using custom draco decoder path",e),Ic(e));let t=this.getAttribute("dracoDecoderType");t&&(jr&&console.log("using custom draco decoder type",t),Mc(t));let i=this.getAttribute("ktx2DecoderPath");i&&(jr&&console.log("using custom ktx2 decoder path",i),Lc(i))}};window.customElements.define(Ow,wh);import*as Mw from"three";var _h={Context:Q};globalThis.Needle=_h;function rm(a){for(let e in a)_h[e]=a[e]}rm(tc);rm(Jd);for(let a of Object.getOwnPropertyNames(C))switch(a){case"prototype":case"constructor":case"length":case"name":continue;default:_h[a]=C[a];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=Mw;export{On as AlignmentConstraint,ei as Animation,pr as AnimationCurve,qn as AnimationTrackHandler,yt as Animator,$t as AnimatorController,ht as AttachedObject,ti as AudioListener,de as AudioSource,Xn as AudioTrackHandler,Si as AvatarBlink_Simple,Pi as AvatarEyeLook_Rotation,An as AvatarLoader,ue as AvatarMarker,fr as AvatarModel,qi as Avatar_Brain_LookAt,Wn as Avatar_MouthShapes,Do as Avatar_MustacheShake,xe as Avatar_POI,Ui as AxesHelper,Ge as BaseUIComponent,ro as BasicIKConstraint,M as Behaviour,Rn as BoxCollider,Qi as BoxGizmo,ct as BoxHelperComponent,Vt as Button,_i as CallInfo,re as Camera,Je as Canvas,ln as CanvasGroup,mt as Collider,vs as Collision,Gn as ColorAdjustments,tn as ControlTrackHandler,oo as Deletable,mr as DeleteBox,gr as DeviceFlag,_t as DragControls,Dn as DropListener,wi as Duplicatable,To as EmissionModule,Oe as EventList,Er as EventListEvent,Ke as EventSystem,go as EventTrigger,Yr as FieldWithDefault,bo as FlyControls,C as GameObject,zt as GltfExport,yo as GltfExportBox,Pt as Graphic,Xo as GraphicRaycaster,Yi as GridHelper,qo as GridLayoutGroup,Ki as GroundProjectedEnv,Wo as HorizontalLayoutGroup,an as Image,Ot as InputField,ne as InstancingUtil,be as InstantiateOptions,Dt as Interactable,Uo as Keyboard,jn as LODGroup,xi as LODModel,cn as LayoutGroup,Ye as Light,Ho as LogStats,wr as LookAtConstraint,xo as MainModule,sn as MaskableGraphic,hr as MeshRenderer,wo as NavMesh,_o as NavMeshAgent,_r as NestedGltf,gt as Networking,Ai as ObjectRaycaster,Ti as OffsetConstraint,$e as OrbitControls,Co as ParticleSystem,Tr as ParticleSystemRenderer,rn as PlayableDirector,ut as PlayerColor,si as PointerEventData,_e as RGBAColor,Ir as RawImage,Lr as Raycaster,kr as Rect,pt as RectTransform,Fn as RemoteSkybox,ye as Renderer,zi as RendererLightmap,ce as Rigidbody,Ji as ScreenCapture,Bn as ShadowCatcher,Ro as ShapeModule,Or as SignalAsset,en as SignalReceiver,Ar as SignalReceiverEvent,nn as SignalTrackHandler,zo as Size,Kr as SkinnedMeshRenderer,Ri as SmoothFollow,Qo as SpatialHtml,Zi as SpatialTrigger,xt as SpatialTriggerReceiver,Oo as SpectatorCamera,Tn as SphereCollider,Ao as SpringJoint,Rr as Sprite,$i as SpriteRenderer,zn as SyncedCamera,oi as SyncedRoom,Qe as SyncedTransform,br as TeleportTarget,ko as TestRunner,Io as TestSimulateUserData,Le as Text,Un as ToneMapping,Cr as TransformGizmo,on as UIRootComponent,Ht as UsageMarker,Nt as VRUserState,Go as VerticalLayoutGroup,Me as VideoPlayer,et as Voip,Sr as Volume,Ci as VolumeComponent,Mo as VolumeParameter,Vn as VolumeProfile,Ln as WebAR,Ft as WebARSessionRoot,K as WebXR,Bt as WebXRAvatar,se as WebXRController,Xi as WebXRSync,Pe as XRFlag,Pr as XRGrabModel,Lo as XRGrabRendering,Mn as XRRig,Et as XRState,Is as __Ignore,ia as apply,A as serializeable};
165
165
  /*!
166
166
  * Determine if an object is a Buffer
167
167
  *