@needle-tools/engine 2.44.0-pre → 2.44.1-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.
- package/CHANGELOG.md +4 -0
- package/dist/needle-engine.d.ts +3 -0
- package/dist/needle-engine.js +41 -41
- package/dist/needle-engine.js.map +2 -2
- package/dist/needle-engine.min.js +32 -32
- package/dist/needle-engine.min.js.map +2 -2
- package/lib/engine/api.d.ts +1 -0
- package/lib/engine/api.js +1 -0
- package/lib/engine/api.js.map +1 -1
- package/lib/engine-components/Skybox.d.ts +2 -0
- package/lib/engine-components/Skybox.js +12 -2
- package/lib/engine-components/Skybox.js.map +1 -1
- package/package.json +1 -1
- package/src/engine/api.ts +1 -0
- package/src/engine-components/Skybox.ts +13 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var cm=Object.create;var fs=Object.defineProperty;var ih=Object.getOwnPropertyDescriptor;var um=Object.getOwnPropertyNames;var dm=Object.getPrototypeOf,hm=Object.prototype.hasOwnProperty;var pm=(o,e,t)=>e in o?fs(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var $l=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+o+'" is not supported')});var ms=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),nh=(o,e)=>{for(var t in e)fs(o,t,{get:e[t],enumerable:!0})},fm=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of um(e))!hm.call(o,n)&&n!==t&&fs(o,n,{get:()=>e[n],enumerable:!(i=ih(e,n))||i.enumerable});return o};var ra=(o,e,t)=>(t=o!=null?cm(dm(o)):{},fm(e||!o||!o.__esModule?fs(t,"default",{value:o,enumerable:!0}):t,o));var E=(o,e,t,i)=>{for(var n=i>1?void 0:i?ih(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(n=(i?s(e,t,n):s(n))||n);return i&&n&&fs(e,t,n),n};var L=(o,e,t)=>(pm(o,typeof e!="symbol"?e+"":e,t),t);var ja=ms((ap,Ac)=>{parcelRequire=function(o,e,t,i){var n,r=typeof parcelRequire=="function"&&parcelRequire,s=typeof $l=="function"&&$l;function a(l,d){if(!e[l]){if(!o[l]){var h=typeof parcelRequire=="function"&&parcelRequire;if(!d&&h)return h(l,!0);if(r)return r(l,!0);if(s&&typeof l=="string")return s(l);var b=new Error("Cannot find module '"+l+"'");throw b.code="MODULE_NOT_FOUND",b}v.resolve=function(y){return o[l][1][y]||y},v.cache={};var _=e[l]=new a.Module(l);o[l][0].call(_.exports,v,_,_.exports,this)}return e[l].exports;function v(y){return a(v.resolve(y))}}a.isParcelRequire=!0,a.Module=function(l){this.id=l,this.bundle=a,this.exports={}},a.modules=o,a.cache=e,a.parent=r,a.register=function(l,d){o[l]=[function(h,b){b.exports=d},{}]};for(var c=0;c<t.length;c++)try{a(t[c])}catch(l){n||(n=l)}if(t.length){var u=a(t[t.length-1]);typeof ap=="object"&&typeof Ac<"u"?Ac.exports=u:typeof define=="function"&&define.amd?define(function(){return u}):i&&(this[i]=u)}if(parcelRequire=a,n)throw n;return a}({EgBh:[function(o,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(s){typeof s=="number"?this._pieces.push(s):(this.flush(),this._parts.push(s))},r.prototype.flush=function(){if(this._pieces.length>0){var s=new Uint8Array(this._pieces);i.useArrayBufferView||(s=s.buffer),this._parts.push(s),this._pieces=[]}},r.prototype.getBuffer=function(){if(this.flush(),i.useBlobBuilder){for(var s=new n,a=0,c=this._parts.length;a<c;a++)s.append(this._parts[a]);return s.getBlob()}return new Blob(this._parts)},e.exports.BufferBuilder=r},{}],kdPp:[function(o,e,t){var i=o("./bufferbuilder").BufferBuilder,n=o("./bufferbuilder").binaryFeatures,r={unpack:function(l){return new s(l).unpack()},pack:function(l){var d=new a;return d.pack(l),d.getBuffer()}};function s(l){this.index=0,this.dataBuffer=l,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}function a(){this.bufferBuilder=new i}function c(l){var d=l.charCodeAt(0);return d<=2047?"00":d<=65535?"000":d<=2097151?"0000":d<=67108863?"00000":"000000"}function u(l){return l.length>600?new Blob([l]).size:l.replace(/[^\u0000-\u007F]/g,c).length}e.exports=r,s.prototype.unpack=function(){var l,d=this.unpack_uint8();if(d<128)return d;if((224^d)<32)return(224^d)-32;if((l=160^d)<=15)return this.unpack_raw(l);if((l=176^d)<=15)return this.unpack_string(l);if((l=144^d)<=15)return this.unpack_array(l);if((l=128^d)<=15)return this.unpack_map(l);switch(d){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:case 213:case 214:case 215:return;case 216:return l=this.unpack_uint16(),this.unpack_string(l);case 217:return l=this.unpack_uint32(),this.unpack_string(l);case 218:return l=this.unpack_uint16(),this.unpack_raw(l);case 219:return l=this.unpack_uint32(),this.unpack_raw(l);case 220:return l=this.unpack_uint16(),this.unpack_array(l);case 221:return l=this.unpack_uint32(),this.unpack_array(l);case 222:return l=this.unpack_uint16(),this.unpack_map(l);case 223:return l=this.unpack_uint32(),this.unpack_map(l)}},s.prototype.unpack_uint8=function(){var l=255&this.dataView[this.index];return this.index++,l},s.prototype.unpack_uint16=function(){var l=this.read(2),d=256*(255&l[0])+(255&l[1]);return this.index+=2,d},s.prototype.unpack_uint32=function(){var l=this.read(4),d=256*(256*(256*l[0]+l[1])+l[2])+l[3];return this.index+=4,d},s.prototype.unpack_uint64=function(){var l=this.read(8),d=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,d},s.prototype.unpack_int8=function(){var l=this.unpack_uint8();return l<128?l:l-256},s.prototype.unpack_int16=function(){var l=this.unpack_uint16();return l<32768?l:l-65536},s.prototype.unpack_int32=function(){var l=this.unpack_uint32();return l<Math.pow(2,31)?l:l-Math.pow(2,32)},s.prototype.unpack_int64=function(){var l=this.unpack_uint64();return l<Math.pow(2,63)?l:l-Math.pow(2,64)},s.prototype.unpack_raw=function(l){if(this.length<this.index+l)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+l+" "+this.length);var d=this.dataBuffer.slice(this.index,this.index+l);return this.index+=l,d},s.prototype.unpack_string=function(l){for(var d,h,b=this.read(l),_=0,v="";_<l;)(d=b[_])<128?(v+=String.fromCharCode(d),_++):(192^d)<32?(h=(192^d)<<6|63&b[_+1],v+=String.fromCharCode(h),_+=2):(h=(15&d)<<12|(63&b[_+1])<<6|63&b[_+2],v+=String.fromCharCode(h),_+=3);return this.index+=l,v},s.prototype.unpack_array=function(l){for(var d=new Array(l),h=0;h<l;h++)d[h]=this.unpack();return d},s.prototype.unpack_map=function(l){for(var d={},h=0;h<l;h++){var b=this.unpack(),_=this.unpack();d[b]=_}return d},s.prototype.unpack_float=function(){var l=this.unpack_uint32(),d=(l>>23&255)-127;return(l>>31===0?1:-1)*(8388607&l|8388608)*Math.pow(2,d-23)},s.prototype.unpack_double=function(){var l=this.unpack_uint32(),d=this.unpack_uint32(),h=(l>>20&2047)-1023;return(l>>31===0?1:-1)*((1048575&l|1048576)*Math.pow(2,h-20)+d*Math.pow(2,h-52))},s.prototype.read=function(l){var d=this.index;if(d+l<=this.length)return this.dataView.subarray(d,d+l);throw new Error("BinaryPackFailure: read index out of range")},a.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},a.prototype.pack=function(l){var d=typeof l;if(d==="string")this.pack_string(l);else if(d==="number")Math.floor(l)===l?this.pack_integer(l):this.pack_double(l);else if(d==="boolean")l===!0?this.bufferBuilder.append(195):l===!1&&this.bufferBuilder.append(194);else if(d==="undefined")this.bufferBuilder.append(192);else{if(d!=="object")throw new Error('Type "'+d+'" not yet supported');if(l===null)this.bufferBuilder.append(192);else{var h=l.constructor;if(h==Array)this.pack_array(l);else if(h==Blob||h==File||l instanceof Blob||l instanceof File)this.pack_bin(l);else if(h==ArrayBuffer)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(h==Object||h.toString().startsWith("class"))this.pack_object(l);else if(h==Date)this.pack_string(l.toString());else{if(typeof l.toBinaryPack!="function")throw new Error('Type "'+h.toString()+'" not yet supported');this.bufferBuilder.append(l.toBinaryPack())}}}this.bufferBuilder.flush()},a.prototype.pack_bin=function(l){var d=l.length||l.byteLength||l.size;if(d<=15)this.pack_uint8(160+d);else if(d<=65535)this.bufferBuilder.append(218),this.pack_uint16(d);else{if(!(d<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(219),this.pack_uint32(d)}this.bufferBuilder.append(l)},a.prototype.pack_string=function(l){var d=u(l);if(d<=15)this.pack_uint8(176+d);else if(d<=65535)this.bufferBuilder.append(216),this.pack_uint16(d);else{if(!(d<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(217),this.pack_uint32(d)}this.bufferBuilder.append(l)},a.prototype.pack_array=function(l){var d=l.length;if(d<=15)this.pack_uint8(144+d);else if(d<=65535)this.bufferBuilder.append(220),this.pack_uint16(d);else{if(!(d<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(221),this.pack_uint32(d)}for(var h=0;h<d;h++)this.pack(l[h])},a.prototype.pack_integer=function(l){if(l>=-32&&l<=127)this.bufferBuilder.append(255&l);else if(l>=0&&l<=255)this.bufferBuilder.append(204),this.pack_uint8(l);else if(l>=-128&&l<=127)this.bufferBuilder.append(208),this.pack_int8(l);else if(l>=0&&l<=65535)this.bufferBuilder.append(205),this.pack_uint16(l);else if(l>=-32768&&l<=32767)this.bufferBuilder.append(209),this.pack_int16(l);else if(l>=0&&l<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(l);else if(l>=-2147483648&&l<=2147483647)this.bufferBuilder.append(210),this.pack_int32(l);else if(l>=-9223372036854776e3&&l<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(l);else{if(!(l>=0&&l<=18446744073709552e3))throw new Error("Invalid integer");this.bufferBuilder.append(207),this.pack_uint64(l)}},a.prototype.pack_double=function(l){var d=0;l<0&&(d=1,l=-l);var h=Math.floor(Math.log(l)/Math.LN2),b=l/Math.pow(2,h)-1,_=Math.floor(b*Math.pow(2,52)),v=Math.pow(2,32),y=d<<31|h+1023<<20|_/v&1048575,f=_%v;this.bufferBuilder.append(203),this.pack_int32(y),this.pack_int32(f)},a.prototype.pack_object=function(l){var d=Object.keys(l).length;if(d<=15)this.pack_uint8(128+d);else if(d<=65535)this.bufferBuilder.append(222),this.pack_uint16(d);else{if(!(d<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(223),this.pack_uint32(d)}for(var h in l)l.hasOwnProperty(h)&&(this.pack(h),this.pack(l[h]))},a.prototype.pack_uint8=function(l){this.bufferBuilder.append(l)},a.prototype.pack_uint16=function(l){this.bufferBuilder.append(l>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_uint32=function(l){var d=4294967295&l;this.bufferBuilder.append((4278190080&d)>>>24),this.bufferBuilder.append((16711680&d)>>>16),this.bufferBuilder.append((65280&d)>>>8),this.bufferBuilder.append(255&d)},a.prototype.pack_uint64=function(l){var d=l/Math.pow(2,32),h=l%Math.pow(2,32);this.bufferBuilder.append((4278190080&d)>>>24),this.bufferBuilder.append((16711680&d)>>>16),this.bufferBuilder.append((65280&d)>>>8),this.bufferBuilder.append(255&d),this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h)},a.prototype.pack_int8=function(l){this.bufferBuilder.append(255&l)},a.prototype.pack_int16=function(l){this.bufferBuilder.append((65280&l)>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_int32=function(l){this.bufferBuilder.append(l>>>24&255),this.bufferBuilder.append((16711680&l)>>>16),this.bufferBuilder.append((65280&l)>>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_int64=function(l){var d=Math.floor(l/Math.pow(2,32)),h=l%Math.pow(2,32);this.bufferBuilder.append((4278190080&d)>>>24),this.bufferBuilder.append((16711680&d)>>>16),this.bufferBuilder.append((65280&d)>>>8),this.bufferBuilder.append(255&d),this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h)}},{"./bufferbuilder":"EgBh"}],iSxC:[function(o,e,t){"use strict";function i(m,p,g){return p in m?Object.defineProperty(m,p,{value:g,enumerable:!0,configurable:!0,writable:!0}):m[p]=g,m}function n(m){return(n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(p){return typeof p}:function(p){return p&&typeof Symbol=="function"&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p})(m)}Object.defineProperty(t,"__esModule",{value:!0}),t.extractVersion=a,t.wrapPeerConnectionEvent=c,t.disableLog=u,t.disableWarnings=l,t.log=d,t.deprecated=h,t.detectBrowser=b,t.compactObject=v,t.walkStats=y,t.filterStats=f;var r=!0,s=!0;function a(m,p,g){var x=m.match(p);return x&&x.length>=g&&parseInt(x[g],10)}function c(m,p,g){if(m.RTCPeerConnection){var x=m.RTCPeerConnection.prototype,C=x.addEventListener;x.addEventListener=function(S,D){if(S!==p)return C.apply(this,arguments);var A=function(P){var H=g(P);H&&(D.handleEvent?D.handleEvent(H):D(H))};return this._eventMap=this._eventMap||{},this._eventMap[p]||(this._eventMap[p]=new Map),this._eventMap[p].set(D,A),C.apply(this,[S,A])};var T=x.removeEventListener;x.removeEventListener=function(S,D){if(S!==p||!this._eventMap||!this._eventMap[p])return T.apply(this,arguments);if(!this._eventMap[p].has(D))return T.apply(this,arguments);var A=this._eventMap[p].get(D);return this._eventMap[p].delete(D),this._eventMap[p].size===0&&delete this._eventMap[p],Object.keys(this._eventMap).length===0&&delete this._eventMap,T.apply(this,[S,A])},Object.defineProperty(x,"on"+p,{get:function(){return this["_on"+p]},set:function(S){this["_on"+p]&&(this.removeEventListener(p,this["_on"+p]),delete this["_on"+p]),S&&this.addEventListener(p,this["_on"+p]=S)},enumerable:!0,configurable:!0})}}function u(m){return typeof m!="boolean"?new Error("Argument type: "+n(m)+". Please use a boolean."):(r=m,m?"adapter.js logging disabled":"adapter.js logging enabled")}function l(m){return typeof m!="boolean"?new Error("Argument type: "+n(m)+". Please use a boolean."):(s=!m,"adapter.js deprecation warnings "+(m?"disabled":"enabled"))}function d(){if((typeof window>"u"?"undefined":n(window))==="object"){if(r)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function h(m,p){s&&console.warn(m+" is deprecated, please use "+p+" instead.")}function b(m){var p={browser:null,version:null};if(m===void 0||!m.navigator)return p.browser="Not a browser.",p;var{navigator:g}=m;if(g.mozGetUserMedia)p.browser="firefox",p.version=a(g.userAgent,/Firefox\/(\d+)\./,1);else if(g.webkitGetUserMedia||m.isSecureContext===!1&&m.webkitRTCPeerConnection&&!m.RTCIceGatherer)p.browser="chrome",p.version=a(g.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(g.mediaDevices&&g.userAgent.match(/Edge\/(\d+).(\d+)$/))p.browser="edge",p.version=a(g.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!m.RTCPeerConnection||!g.userAgent.match(/AppleWebKit\/(\d+)\./))return p.browser="Not a supported browser.",p;p.browser="safari",p.version=a(g.userAgent,/AppleWebKit\/(\d+)\./,1),p.supportsUnifiedPlan=m.RTCRtpTransceiver&&"currentDirection"in m.RTCRtpTransceiver.prototype}return p}function _(m){return Object.prototype.toString.call(m)==="[object Object]"}function v(m){return _(m)?Object.keys(m).reduce(function(p,g){var x=_(m[g]),C=x?v(m[g]):m[g],T=x&&!Object.keys(C).length;return C===void 0||T?p:Object.assign(p,i({},g,C))},{}):m}function y(m,p,g){p&&!g.has(p.id)&&(g.set(p.id,p),Object.keys(p).forEach(function(x){x.endsWith("Id")?y(m,m.get(p[x]),g):x.endsWith("Ids")&&p[x].forEach(function(C){y(m,m.get(C),g)})}))}function f(m,p,g){var x=g?"outbound-rtp":"inbound-rtp",C=new Map;if(p===null)return C;var T=[];return m.forEach(function(S){S.type==="track"&&S.trackIdentifier===p.id&&T.push(S)}),T.forEach(function(S){m.forEach(function(D){D.type===x&&D.trackId===S.id&&y(m,D,C)})}),C}},{}],s6SN:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=c;var i=r(o("../utils.js"));function n(){if(typeof WeakMap!="function")return null;var u=new WeakMap;return n=function(){return u},u}function r(u){if(u&&u.__esModule)return u;if(u===null||typeof u!="object"&&typeof u!="function")return{default:u};var l=n();if(l&&l.has(u))return l.get(u);var d={},h=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var b in u)if(Object.prototype.hasOwnProperty.call(u,b)){var _=h?Object.getOwnPropertyDescriptor(u,b):null;_&&(_.get||_.set)?Object.defineProperty(d,b,_):d[b]=u[b]}return d.default=u,l&&l.set(u,d),d}function s(u){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l})(u)}var a=i.log;function c(u,l){var d=u&&u.navigator;if(d.mediaDevices){var h=function(y){if(s(y)!=="object"||y.mandatory||y.optional)return y;var f={};return Object.keys(y).forEach(function(m){if(m!=="require"&&m!=="advanced"&&m!=="mediaSource"){var p=s(y[m])==="object"?y[m]:{ideal:y[m]};p.exact!==void 0&&typeof p.exact=="number"&&(p.min=p.max=p.exact);var g=function(C,T){return C?C+T.charAt(0).toUpperCase()+T.slice(1):T==="deviceId"?"sourceId":T};if(p.ideal!==void 0){f.optional=f.optional||[];var x={};typeof p.ideal=="number"?(x[g("min",m)]=p.ideal,f.optional.push(x),(x={})[g("max",m)]=p.ideal,f.optional.push(x)):(x[g("",m)]=p.ideal,f.optional.push(x))}p.exact!==void 0&&typeof p.exact!="number"?(f.mandatory=f.mandatory||{},f.mandatory[g("",m)]=p.exact):["min","max"].forEach(function(C){p[C]!==void 0&&(f.mandatory=f.mandatory||{},f.mandatory[g(C,m)]=p[C])})}}),y.advanced&&(f.optional=(f.optional||[]).concat(y.advanced)),f},b=function(y,f){if(l.version>=61)return f(y);if((y=JSON.parse(JSON.stringify(y)))&&s(y.audio)==="object"){var m=function(C,T,S){T in C&&!(S in C)&&(C[S]=C[T],delete C[T])};m((y=JSON.parse(JSON.stringify(y))).audio,"autoGainControl","googAutoGainControl"),m(y.audio,"noiseSuppression","googNoiseSuppression"),y.audio=h(y.audio)}if(y&&s(y.video)==="object"){var p=y.video.facingMode;p=p&&(s(p)==="object"?p:{ideal:p});var g,x=l.version<66;if(p&&(p.exact==="user"||p.exact==="environment"||p.ideal==="user"||p.ideal==="environment")&&(!d.mediaDevices.getSupportedConstraints||!d.mediaDevices.getSupportedConstraints().facingMode||x)&&(delete y.video.facingMode,p.exact==="environment"||p.ideal==="environment"?g=["back","rear"]:p.exact!=="user"&&p.ideal!=="user"||(g=["front"]),g))return d.mediaDevices.enumerateDevices().then(function(C){var T=(C=C.filter(function(S){return S.kind==="videoinput"})).find(function(S){return g.some(function(D){return S.label.toLowerCase().includes(D)})});return!T&&C.length&&g.includes("back")&&(T=C[C.length-1]),T&&(y.video.deviceId=p.exact?{exact:T.deviceId}:{ideal:T.deviceId}),y.video=h(y.video),a("chrome: "+JSON.stringify(y)),f(y)});y.video=h(y.video)}return a("chrome: "+JSON.stringify(y)),f(y)},_=function(y){return l.version>=64?y:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[y.name]||y.name,message:y.message,constraint:y.constraint||y.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(d.getUserMedia=function(y,f,m){b(y,function(p){d.webkitGetUserMedia(p,f,function(g){m&&m(_(g))})})}.bind(d),d.mediaDevices.getUserMedia){var v=d.mediaDevices.getUserMedia.bind(d.mediaDevices);d.mediaDevices.getUserMedia=function(y){return b(y,function(f){return v(f).then(function(m){if(f.audio&&!m.getAudioTracks().length||f.video&&!m.getVideoTracks().length)throw m.getTracks().forEach(function(p){p.stop()}),new DOMException("","NotFoundError");return m},function(m){return Promise.reject(_(m))})})}}}}},{"../utils.js":"iSxC"}],VHa8:[function(o,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(s){return r(s).then(function(a){var c=s.video&&s.video.width,u=s.video&&s.video.height,l=s.video&&s.video.frameRate;return s.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:a,maxFrameRate:l||3}},c&&(s.video.mandatory.maxWidth=c),u&&(s.video.mandatory.maxHeight=u),n.navigator.mediaDevices.getUserMedia(s)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],uI5X:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimMediaStream=l,t.shimOnTrack=d,t.shimGetSendersWithDtmf=h,t.shimGetStats=b,t.shimSenderReceiverGetStats=_,t.shimAddTrackRemoveTrackWithNative=v,t.shimAddTrackRemoveTrack=y,t.shimPeerConnection=f,t.fixNegotiationNeeded=m,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}});var i=a(o("../utils.js")),n=o("./getusermedia"),r=o("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var p=new WeakMap;return s=function(){return p},p}function a(p){if(p&&p.__esModule)return p;if(p===null||typeof p!="object"&&typeof p!="function")return{default:p};var g=s();if(g&&g.has(p))return g.get(p);var x={},C=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var T in p)if(Object.prototype.hasOwnProperty.call(p,T)){var S=C?Object.getOwnPropertyDescriptor(p,T):null;S&&(S.get||S.set)?Object.defineProperty(x,T,S):x[T]=p[T]}return x.default=p,g&&g.set(p,x),x}function c(p,g,x){return g in p?Object.defineProperty(p,g,{value:x,enumerable:!0,configurable:!0,writable:!0}):p[g]=x,p}function u(p){return(u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(g){return typeof g}:function(g){return g&&typeof Symbol=="function"&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g})(p)}function l(p){p.MediaStream=p.MediaStream||p.webkitMediaStream}function d(p){if(u(p)!=="object"||!p.RTCPeerConnection||"ontrack"in p.RTCPeerConnection.prototype)i.wrapPeerConnectionEvent(p,"track",function(x){return x.transceiver||Object.defineProperty(x,"transceiver",{value:{receiver:x.receiver}}),x});else{Object.defineProperty(p.RTCPeerConnection.prototype,"ontrack",{get:function(){return this._ontrack},set:function(x){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=x)},enumerable:!0,configurable:!0});var g=p.RTCPeerConnection.prototype.setRemoteDescription;p.RTCPeerConnection.prototype.setRemoteDescription=function(){var x=this;return this._ontrackpoly||(this._ontrackpoly=function(C){C.stream.addEventListener("addtrack",function(T){var S;S=p.RTCPeerConnection.prototype.getReceivers?x.getReceivers().find(function(A){return A.track&&A.track.id===T.track.id}):{track:T.track};var D=new Event("track");D.track=T.track,D.receiver=S,D.transceiver={receiver:S},D.streams=[C.stream],x.dispatchEvent(D)}),C.stream.getTracks().forEach(function(T){var S;S=p.RTCPeerConnection.prototype.getReceivers?x.getReceivers().find(function(A){return A.track&&A.track.id===T.id}):{track:T};var D=new Event("track");D.track=T,D.receiver=S,D.transceiver={receiver:S},D.streams=[C.stream],x.dispatchEvent(D)})},this.addEventListener("addstream",this._ontrackpoly)),g.apply(this,arguments)}}}function h(p){if(u(p)==="object"&&p.RTCPeerConnection&&!("getSenders"in p.RTCPeerConnection.prototype)&&"createDTMFSender"in p.RTCPeerConnection.prototype){var g=function(A,P){return{track:P,get dtmf(){return this._dtmf===void 0&&(P.kind==="audio"?this._dtmf=A.createDTMFSender(P):this._dtmf=null),this._dtmf},_pc:A}};if(!p.RTCPeerConnection.prototype.getSenders){p.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var x=p.RTCPeerConnection.prototype.addTrack;p.RTCPeerConnection.prototype.addTrack=function(A,P){var H=x.apply(this,arguments);return H||(H=g(this,A),this._senders.push(H)),H};var C=p.RTCPeerConnection.prototype.removeTrack;p.RTCPeerConnection.prototype.removeTrack=function(A){C.apply(this,arguments);var P=this._senders.indexOf(A);P!==-1&&this._senders.splice(P,1)}}var T=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(A){var P=this;this._senders=this._senders||[],T.apply(this,[A]),A.getTracks().forEach(function(H){P._senders.push(g(P,H))})};var S=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(A){var P=this;this._senders=this._senders||[],S.apply(this,[A]),A.getTracks().forEach(function(H){var B=P._senders.find(function(N){return N.track===H});B&&P._senders.splice(P._senders.indexOf(B),1)})}}else if(u(p)==="object"&&p.RTCPeerConnection&&"getSenders"in p.RTCPeerConnection.prototype&&"createDTMFSender"in p.RTCPeerConnection.prototype&&p.RTCRtpSender&&!("dtmf"in p.RTCRtpSender.prototype)){var D=p.RTCPeerConnection.prototype.getSenders;p.RTCPeerConnection.prototype.getSenders=function(){var A=this,P=D.apply(this,[]);return P.forEach(function(H){return H._pc=A}),P},Object.defineProperty(p.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function b(p){if(p.RTCPeerConnection){var g=p.RTCPeerConnection.prototype.getStats;p.RTCPeerConnection.prototype.getStats=function(){var x=this,[C,T,S]=arguments;if(arguments.length>0&&typeof C=="function")return g.apply(this,arguments);if(g.length===0&&(arguments.length===0||typeof C!="function"))return g.apply(this,[]);var D=function(P){var H={};return P.result().forEach(function(B){var N={id:B.id,timestamp:B.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[B.type]||B.type};B.names().forEach(function(W){N[W]=B.stat(W)}),H[N.id]=N}),H},A=function(P){return new Map(Object.keys(P).map(function(H){return[H,P[H]]}))};return arguments.length>=2?g.apply(this,[function(P){T(A(D(P)))},C]):new Promise(function(P,H){g.apply(x,[function(B){P(A(D(B)))},H])}).then(T,S)}}}function _(p){if(u(p)==="object"&&p.RTCPeerConnection&&p.RTCRtpSender&&p.RTCRtpReceiver){if(!("getStats"in p.RTCRtpSender.prototype)){var g=p.RTCPeerConnection.prototype.getSenders;g&&(p.RTCPeerConnection.prototype.getSenders=function(){var S=this,D=g.apply(this,[]);return D.forEach(function(A){return A._pc=S}),D});var x=p.RTCPeerConnection.prototype.addTrack;x&&(p.RTCPeerConnection.prototype.addTrack=function(){var S=x.apply(this,arguments);return S._pc=this,S}),p.RTCRtpSender.prototype.getStats=function(){var S=this;return this._pc.getStats().then(function(D){return i.filterStats(D,S.track,!0)})}}if(!("getStats"in p.RTCRtpReceiver.prototype)){var C=p.RTCPeerConnection.prototype.getReceivers;C&&(p.RTCPeerConnection.prototype.getReceivers=function(){var S=this,D=C.apply(this,[]);return D.forEach(function(A){return A._pc=S}),D}),i.wrapPeerConnectionEvent(p,"track",function(S){return S.receiver._pc=S.srcElement,S}),p.RTCRtpReceiver.prototype.getStats=function(){var S=this;return this._pc.getStats().then(function(D){return i.filterStats(D,S.track,!1)})}}if("getStats"in p.RTCRtpSender.prototype&&"getStats"in p.RTCRtpReceiver.prototype){var T=p.RTCPeerConnection.prototype.getStats;p.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof p.MediaStreamTrack){var S,D,A,P=arguments[0];return this.getSenders().forEach(function(H){H.track===P&&(S?A=!0:S=H)}),this.getReceivers().forEach(function(H){return H.track===P&&(D?A=!0:D=H),H.track===P}),A||S&&D?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):S?S.getStats():D?D.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return T.apply(this,arguments)}}}}function v(p){p.RTCPeerConnection.prototype.getLocalStreams=function(){var S=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(D){return S._shimmedLocalStreams[D][0]})};var g=p.RTCPeerConnection.prototype.addTrack;p.RTCPeerConnection.prototype.addTrack=function(S,D){if(!D)return g.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var A=g.apply(this,arguments);return this._shimmedLocalStreams[D.id]?this._shimmedLocalStreams[D.id].indexOf(A)===-1&&this._shimmedLocalStreams[D.id].push(A):this._shimmedLocalStreams[D.id]=[D,A],A};var x=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(S){var D=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},S.getTracks().forEach(function(H){if(D.getSenders().find(function(B){return B.track===H}))throw new DOMException("Track already exists.","InvalidAccessError")});var A=this.getSenders();x.apply(this,arguments);var P=this.getSenders().filter(function(H){return A.indexOf(H)===-1});this._shimmedLocalStreams[S.id]=[S].concat(P)};var C=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(S){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[S.id],C.apply(this,arguments)};var T=p.RTCPeerConnection.prototype.removeTrack;p.RTCPeerConnection.prototype.removeTrack=function(S){var D=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},S&&Object.keys(this._shimmedLocalStreams).forEach(function(A){var P=D._shimmedLocalStreams[A].indexOf(S);P!==-1&&D._shimmedLocalStreams[A].splice(P,1),D._shimmedLocalStreams[A].length===1&&delete D._shimmedLocalStreams[A]}),T.apply(this,arguments)}}function y(p,g){if(p.RTCPeerConnection){if(p.RTCPeerConnection.prototype.addTrack&&g.version>=65)return v(p);var x=p.RTCPeerConnection.prototype.getLocalStreams;p.RTCPeerConnection.prototype.getLocalStreams=function(){var P=this,H=x.apply(this);return this._reverseStreams=this._reverseStreams||{},H.map(function(B){return P._reverseStreams[B.id]})};var C=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(P){var H=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},P.getTracks().forEach(function(N){if(H.getSenders().find(function(W){return W.track===N}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[P.id]){var B=new p.MediaStream(P.getTracks());this._streams[P.id]=B,this._reverseStreams[B.id]=P,P=B}C.apply(this,[P])};var T=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(P){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},T.apply(this,[this._streams[P.id]||P]),delete this._reverseStreams[this._streams[P.id]?this._streams[P.id].id:P.id],delete this._streams[P.id]},p.RTCPeerConnection.prototype.addTrack=function(P,H){var B=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var N=[].slice.call(arguments,1);if(N.length!==1||!N[0].getTracks().find(function(ue){return ue===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(ue){return ue.track===P}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var W=this._streams[H.id];if(W)W.addTrack(P),Promise.resolve().then(function(){B.dispatchEvent(new Event("negotiationneeded"))});else{var re=new p.MediaStream([P]);this._streams[H.id]=re,this._reverseStreams[re.id]=H,this.addStream(re)}return this.getSenders().find(function(ue){return ue.track===P})},["createOffer","createAnswer"].forEach(function(P){var H=p.RTCPeerConnection.prototype[P],B=c({},P,function(){var N=this,W=arguments;return arguments.length&&typeof arguments[0]=="function"?H.apply(this,[function(re){var ue=A(N,re);W[0].apply(null,[ue])},function(re){W[1]&&W[1].apply(null,re)},arguments[2]]):H.apply(this,arguments).then(function(re){return A(N,re)})});p.RTCPeerConnection.prototype[P]=B[P]});var S=p.RTCPeerConnection.prototype.setLocalDescription;p.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(P=this,H=arguments[0],B=H.sdp,Object.keys(P._reverseStreams||[]).forEach(function(N){var W=P._reverseStreams[N],re=P._streams[W.id];B=B.replace(new RegExp(W.id,"g"),re.id)}),new RTCSessionDescription({type:H.type,sdp:B})),S.apply(this,arguments)):S.apply(this,arguments);var P,H,B};var D=Object.getOwnPropertyDescriptor(p.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(p.RTCPeerConnection.prototype,"localDescription",{get:function(){var P=D.get.apply(this);return P.type===""?P:A(this,P)}}),p.RTCPeerConnection.prototype.removeTrack=function(P){var H,B=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!P._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(P._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(function(N){B._streams[N].getTracks().find(function(W){return P.track===W})&&(H=B._streams[N])}),H&&(H.getTracks().length===1?this.removeStream(this._reverseStreams[H.id]):H.removeTrack(P.track),this.dispatchEvent(new Event("negotiationneeded")))}}function A(P,H){var B=H.sdp;return Object.keys(P._reverseStreams||[]).forEach(function(N){var W=P._reverseStreams[N],re=P._streams[W.id];B=B.replace(new RegExp(re.id,"g"),W.id)}),new RTCSessionDescription({type:H.type,sdp:B})}}function f(p,g){!p.RTCPeerConnection&&p.webkitRTCPeerConnection&&(p.RTCPeerConnection=p.webkitRTCPeerConnection),p.RTCPeerConnection&&g.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(x){var C=p.RTCPeerConnection.prototype[x],T=c({},x,function(){return arguments[0]=new(x==="addIceCandidate"?p.RTCIceCandidate:p.RTCSessionDescription)(arguments[0]),C.apply(this,arguments)});p.RTCPeerConnection.prototype[x]=T[x]})}function m(p,g){i.wrapPeerConnectionEvent(p,"negotiationneeded",function(x){var C=x.target;if(!(g.version<72||C.getConfiguration&&C.getConfiguration().sdpSemantics==="plan-b")||C.signalingState==="stable")return x})}},{"../utils.js":"iSxC","./getusermedia":"s6SN","./getdisplaymedia":"VHa8"}],NZ1C:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterIceServers=s;var i=r(o("../utils"));function n(){if(typeof WeakMap!="function")return null;var a=new WeakMap;return n=function(){return a},a}function r(a){if(a&&a.__esModule)return a;if(a===null||typeof a!="object"&&typeof a!="function")return{default:a};var c=n();if(c&&c.has(a))return c.get(a);var u={},l=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var d in a)if(Object.prototype.hasOwnProperty.call(a,d)){var h=l?Object.getOwnPropertyDescriptor(a,d):null;h&&(h.get||h.set)?Object.defineProperty(u,d,h):u[d]=a[d]}return u.default=a,c&&c.set(a,u),u}function s(a,c){var u=!1;return(a=JSON.parse(JSON.stringify(a))).filter(function(l){if(l&&(l.urls||l.url)){var d=l.urls||l.url;l.url&&!l.urls&&i.deprecated("RTCIceServer.url","RTCIceServer.urls");var h=typeof d=="string";return h&&(d=[d]),d=d.filter(function(b){if(b.indexOf("stun:")===0)return!1;var _=b.startsWith("turn")&&!b.startsWith("turn:[")&&b.includes("transport=udp");return _&&!u?(u=!0,!0):_&&!u}),delete l.url,l.urls=h?d[0]:d,!!d.length}})}},{"../utils":"iSxC"}],YHvh:[function(o,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 cm=Object.create;var fs=Object.defineProperty;var ih=Object.getOwnPropertyDescriptor;var um=Object.getOwnPropertyNames;var dm=Object.getPrototypeOf,hm=Object.prototype.hasOwnProperty;var pm=(o,e,t)=>e in o?fs(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var $l=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+o+'" is not supported')});var ms=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),nh=(o,e)=>{for(var t in e)fs(o,t,{get:e[t],enumerable:!0})},fm=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of um(e))!hm.call(o,n)&&n!==t&&fs(o,n,{get:()=>e[n],enumerable:!(i=ih(e,n))||i.enumerable});return o};var ra=(o,e,t)=>(t=o!=null?cm(dm(o)):{},fm(e||!o||!o.__esModule?fs(t,"default",{value:o,enumerable:!0}):t,o));var E=(o,e,t,i)=>{for(var n=i>1?void 0:i?ih(e,t):e,r=o.length-1,s;r>=0;r--)(s=o[r])&&(n=(i?s(e,t,n):s(n))||n);return i&&n&&fs(e,t,n),n};var L=(o,e,t)=>(pm(o,typeof e!="symbol"?e+"":e,t),t);var ja=ms((ap,Ac)=>{parcelRequire=function(o,e,t,i){var n,r=typeof parcelRequire=="function"&&parcelRequire,s=typeof $l=="function"&&$l;function a(l,d){if(!e[l]){if(!o[l]){var h=typeof parcelRequire=="function"&&parcelRequire;if(!d&&h)return h(l,!0);if(r)return r(l,!0);if(s&&typeof l=="string")return s(l);var b=new Error("Cannot find module '"+l+"'");throw b.code="MODULE_NOT_FOUND",b}v.resolve=function(y){return o[l][1][y]||y},v.cache={};var _=e[l]=new a.Module(l);o[l][0].call(_.exports,v,_,_.exports,this)}return e[l].exports;function v(y){return a(v.resolve(y))}}a.isParcelRequire=!0,a.Module=function(l){this.id=l,this.bundle=a,this.exports={}},a.modules=o,a.cache=e,a.parent=r,a.register=function(l,d){o[l]=[function(h,b){b.exports=d},{}]};for(var c=0;c<t.length;c++)try{a(t[c])}catch(l){n||(n=l)}if(t.length){var u=a(t[t.length-1]);typeof ap=="object"&&typeof Ac<"u"?Ac.exports=u:typeof define=="function"&&define.amd?define(function(){return u}):i&&(this[i]=u)}if(parcelRequire=a,n)throw n;return a}({EgBh:[function(o,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(s){typeof s=="number"?this._pieces.push(s):(this.flush(),this._parts.push(s))},r.prototype.flush=function(){if(this._pieces.length>0){var s=new Uint8Array(this._pieces);i.useArrayBufferView||(s=s.buffer),this._parts.push(s),this._pieces=[]}},r.prototype.getBuffer=function(){if(this.flush(),i.useBlobBuilder){for(var s=new n,a=0,c=this._parts.length;a<c;a++)s.append(this._parts[a]);return s.getBlob()}return new Blob(this._parts)},e.exports.BufferBuilder=r},{}],kdPp:[function(o,e,t){var i=o("./bufferbuilder").BufferBuilder,n=o("./bufferbuilder").binaryFeatures,r={unpack:function(l){return new s(l).unpack()},pack:function(l){var d=new a;return d.pack(l),d.getBuffer()}};function s(l){this.index=0,this.dataBuffer=l,this.dataView=new Uint8Array(this.dataBuffer),this.length=this.dataBuffer.byteLength}function a(){this.bufferBuilder=new i}function c(l){var d=l.charCodeAt(0);return d<=2047?"00":d<=65535?"000":d<=2097151?"0000":d<=67108863?"00000":"000000"}function u(l){return l.length>600?new Blob([l]).size:l.replace(/[^\u0000-\u007F]/g,c).length}e.exports=r,s.prototype.unpack=function(){var l,d=this.unpack_uint8();if(d<128)return d;if((224^d)<32)return(224^d)-32;if((l=160^d)<=15)return this.unpack_raw(l);if((l=176^d)<=15)return this.unpack_string(l);if((l=144^d)<=15)return this.unpack_array(l);if((l=128^d)<=15)return this.unpack_map(l);switch(d){case 192:return null;case 193:return;case 194:return!1;case 195:return!0;case 202:return this.unpack_float();case 203:return this.unpack_double();case 204:return this.unpack_uint8();case 205:return this.unpack_uint16();case 206:return this.unpack_uint32();case 207:return this.unpack_uint64();case 208:return this.unpack_int8();case 209:return this.unpack_int16();case 210:return this.unpack_int32();case 211:return this.unpack_int64();case 212:case 213:case 214:case 215:return;case 216:return l=this.unpack_uint16(),this.unpack_string(l);case 217:return l=this.unpack_uint32(),this.unpack_string(l);case 218:return l=this.unpack_uint16(),this.unpack_raw(l);case 219:return l=this.unpack_uint32(),this.unpack_raw(l);case 220:return l=this.unpack_uint16(),this.unpack_array(l);case 221:return l=this.unpack_uint32(),this.unpack_array(l);case 222:return l=this.unpack_uint16(),this.unpack_map(l);case 223:return l=this.unpack_uint32(),this.unpack_map(l)}},s.prototype.unpack_uint8=function(){var l=255&this.dataView[this.index];return this.index++,l},s.prototype.unpack_uint16=function(){var l=this.read(2),d=256*(255&l[0])+(255&l[1]);return this.index+=2,d},s.prototype.unpack_uint32=function(){var l=this.read(4),d=256*(256*(256*l[0]+l[1])+l[2])+l[3];return this.index+=4,d},s.prototype.unpack_uint64=function(){var l=this.read(8),d=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,d},s.prototype.unpack_int8=function(){var l=this.unpack_uint8();return l<128?l:l-256},s.prototype.unpack_int16=function(){var l=this.unpack_uint16();return l<32768?l:l-65536},s.prototype.unpack_int32=function(){var l=this.unpack_uint32();return l<Math.pow(2,31)?l:l-Math.pow(2,32)},s.prototype.unpack_int64=function(){var l=this.unpack_uint64();return l<Math.pow(2,63)?l:l-Math.pow(2,64)},s.prototype.unpack_raw=function(l){if(this.length<this.index+l)throw new Error("BinaryPackFailure: index is out of range "+this.index+" "+l+" "+this.length);var d=this.dataBuffer.slice(this.index,this.index+l);return this.index+=l,d},s.prototype.unpack_string=function(l){for(var d,h,b=this.read(l),_=0,v="";_<l;)(d=b[_])<128?(v+=String.fromCharCode(d),_++):(192^d)<32?(h=(192^d)<<6|63&b[_+1],v+=String.fromCharCode(h),_+=2):(h=(15&d)<<12|(63&b[_+1])<<6|63&b[_+2],v+=String.fromCharCode(h),_+=3);return this.index+=l,v},s.prototype.unpack_array=function(l){for(var d=new Array(l),h=0;h<l;h++)d[h]=this.unpack();return d},s.prototype.unpack_map=function(l){for(var d={},h=0;h<l;h++){var b=this.unpack(),_=this.unpack();d[b]=_}return d},s.prototype.unpack_float=function(){var l=this.unpack_uint32(),d=(l>>23&255)-127;return(l>>31===0?1:-1)*(8388607&l|8388608)*Math.pow(2,d-23)},s.prototype.unpack_double=function(){var l=this.unpack_uint32(),d=this.unpack_uint32(),h=(l>>20&2047)-1023;return(l>>31===0?1:-1)*((1048575&l|1048576)*Math.pow(2,h-20)+d*Math.pow(2,h-52))},s.prototype.read=function(l){var d=this.index;if(d+l<=this.length)return this.dataView.subarray(d,d+l);throw new Error("BinaryPackFailure: read index out of range")},a.prototype.getBuffer=function(){return this.bufferBuilder.getBuffer()},a.prototype.pack=function(l){var d=typeof l;if(d==="string")this.pack_string(l);else if(d==="number")Math.floor(l)===l?this.pack_integer(l):this.pack_double(l);else if(d==="boolean")l===!0?this.bufferBuilder.append(195):l===!1&&this.bufferBuilder.append(194);else if(d==="undefined")this.bufferBuilder.append(192);else{if(d!=="object")throw new Error('Type "'+d+'" not yet supported');if(l===null)this.bufferBuilder.append(192);else{var h=l.constructor;if(h==Array)this.pack_array(l);else if(h==Blob||h==File||l instanceof Blob||l instanceof File)this.pack_bin(l);else if(h==ArrayBuffer)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(h==Object||h.toString().startsWith("class"))this.pack_object(l);else if(h==Date)this.pack_string(l.toString());else{if(typeof l.toBinaryPack!="function")throw new Error('Type "'+h.toString()+'" not yet supported');this.bufferBuilder.append(l.toBinaryPack())}}}this.bufferBuilder.flush()},a.prototype.pack_bin=function(l){var d=l.length||l.byteLength||l.size;if(d<=15)this.pack_uint8(160+d);else if(d<=65535)this.bufferBuilder.append(218),this.pack_uint16(d);else{if(!(d<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(219),this.pack_uint32(d)}this.bufferBuilder.append(l)},a.prototype.pack_string=function(l){var d=u(l);if(d<=15)this.pack_uint8(176+d);else if(d<=65535)this.bufferBuilder.append(216),this.pack_uint16(d);else{if(!(d<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(217),this.pack_uint32(d)}this.bufferBuilder.append(l)},a.prototype.pack_array=function(l){var d=l.length;if(d<=15)this.pack_uint8(144+d);else if(d<=65535)this.bufferBuilder.append(220),this.pack_uint16(d);else{if(!(d<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(221),this.pack_uint32(d)}for(var h=0;h<d;h++)this.pack(l[h])},a.prototype.pack_integer=function(l){if(l>=-32&&l<=127)this.bufferBuilder.append(255&l);else if(l>=0&&l<=255)this.bufferBuilder.append(204),this.pack_uint8(l);else if(l>=-128&&l<=127)this.bufferBuilder.append(208),this.pack_int8(l);else if(l>=0&&l<=65535)this.bufferBuilder.append(205),this.pack_uint16(l);else if(l>=-32768&&l<=32767)this.bufferBuilder.append(209),this.pack_int16(l);else if(l>=0&&l<=4294967295)this.bufferBuilder.append(206),this.pack_uint32(l);else if(l>=-2147483648&&l<=2147483647)this.bufferBuilder.append(210),this.pack_int32(l);else if(l>=-9223372036854776e3&&l<=9223372036854776e3)this.bufferBuilder.append(211),this.pack_int64(l);else{if(!(l>=0&&l<=18446744073709552e3))throw new Error("Invalid integer");this.bufferBuilder.append(207),this.pack_uint64(l)}},a.prototype.pack_double=function(l){var d=0;l<0&&(d=1,l=-l);var h=Math.floor(Math.log(l)/Math.LN2),b=l/Math.pow(2,h)-1,_=Math.floor(b*Math.pow(2,52)),v=Math.pow(2,32),y=d<<31|h+1023<<20|_/v&1048575,f=_%v;this.bufferBuilder.append(203),this.pack_int32(y),this.pack_int32(f)},a.prototype.pack_object=function(l){var d=Object.keys(l).length;if(d<=15)this.pack_uint8(128+d);else if(d<=65535)this.bufferBuilder.append(222),this.pack_uint16(d);else{if(!(d<=4294967295))throw new Error("Invalid length");this.bufferBuilder.append(223),this.pack_uint32(d)}for(var h in l)l.hasOwnProperty(h)&&(this.pack(h),this.pack(l[h]))},a.prototype.pack_uint8=function(l){this.bufferBuilder.append(l)},a.prototype.pack_uint16=function(l){this.bufferBuilder.append(l>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_uint32=function(l){var d=4294967295&l;this.bufferBuilder.append((4278190080&d)>>>24),this.bufferBuilder.append((16711680&d)>>>16),this.bufferBuilder.append((65280&d)>>>8),this.bufferBuilder.append(255&d)},a.prototype.pack_uint64=function(l){var d=l/Math.pow(2,32),h=l%Math.pow(2,32);this.bufferBuilder.append((4278190080&d)>>>24),this.bufferBuilder.append((16711680&d)>>>16),this.bufferBuilder.append((65280&d)>>>8),this.bufferBuilder.append(255&d),this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h)},a.prototype.pack_int8=function(l){this.bufferBuilder.append(255&l)},a.prototype.pack_int16=function(l){this.bufferBuilder.append((65280&l)>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_int32=function(l){this.bufferBuilder.append(l>>>24&255),this.bufferBuilder.append((16711680&l)>>>16),this.bufferBuilder.append((65280&l)>>>8),this.bufferBuilder.append(255&l)},a.prototype.pack_int64=function(l){var d=Math.floor(l/Math.pow(2,32)),h=l%Math.pow(2,32);this.bufferBuilder.append((4278190080&d)>>>24),this.bufferBuilder.append((16711680&d)>>>16),this.bufferBuilder.append((65280&d)>>>8),this.bufferBuilder.append(255&d),this.bufferBuilder.append((4278190080&h)>>>24),this.bufferBuilder.append((16711680&h)>>>16),this.bufferBuilder.append((65280&h)>>>8),this.bufferBuilder.append(255&h)}},{"./bufferbuilder":"EgBh"}],iSxC:[function(o,e,t){"use strict";function i(m,p,g){return p in m?Object.defineProperty(m,p,{value:g,enumerable:!0,configurable:!0,writable:!0}):m[p]=g,m}function n(m){return(n=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(p){return typeof p}:function(p){return p&&typeof Symbol=="function"&&p.constructor===Symbol&&p!==Symbol.prototype?"symbol":typeof p})(m)}Object.defineProperty(t,"__esModule",{value:!0}),t.extractVersion=a,t.wrapPeerConnectionEvent=c,t.disableLog=u,t.disableWarnings=l,t.log=d,t.deprecated=h,t.detectBrowser=b,t.compactObject=v,t.walkStats=y,t.filterStats=f;var r=!0,s=!0;function a(m,p,g){var w=m.match(p);return w&&w.length>=g&&parseInt(w[g],10)}function c(m,p,g){if(m.RTCPeerConnection){var w=m.RTCPeerConnection.prototype,C=w.addEventListener;w.addEventListener=function(S,D){if(S!==p)return C.apply(this,arguments);var A=function(P){var H=g(P);H&&(D.handleEvent?D.handleEvent(H):D(H))};return this._eventMap=this._eventMap||{},this._eventMap[p]||(this._eventMap[p]=new Map),this._eventMap[p].set(D,A),C.apply(this,[S,A])};var T=w.removeEventListener;w.removeEventListener=function(S,D){if(S!==p||!this._eventMap||!this._eventMap[p])return T.apply(this,arguments);if(!this._eventMap[p].has(D))return T.apply(this,arguments);var A=this._eventMap[p].get(D);return this._eventMap[p].delete(D),this._eventMap[p].size===0&&delete this._eventMap[p],Object.keys(this._eventMap).length===0&&delete this._eventMap,T.apply(this,[S,A])},Object.defineProperty(w,"on"+p,{get:function(){return this["_on"+p]},set:function(S){this["_on"+p]&&(this.removeEventListener(p,this["_on"+p]),delete this["_on"+p]),S&&this.addEventListener(p,this["_on"+p]=S)},enumerable:!0,configurable:!0})}}function u(m){return typeof m!="boolean"?new Error("Argument type: "+n(m)+". Please use a boolean."):(r=m,m?"adapter.js logging disabled":"adapter.js logging enabled")}function l(m){return typeof m!="boolean"?new Error("Argument type: "+n(m)+". Please use a boolean."):(s=!m,"adapter.js deprecation warnings "+(m?"disabled":"enabled"))}function d(){if((typeof window>"u"?"undefined":n(window))==="object"){if(r)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function h(m,p){s&&console.warn(m+" is deprecated, please use "+p+" instead.")}function b(m){var p={browser:null,version:null};if(m===void 0||!m.navigator)return p.browser="Not a browser.",p;var{navigator:g}=m;if(g.mozGetUserMedia)p.browser="firefox",p.version=a(g.userAgent,/Firefox\/(\d+)\./,1);else if(g.webkitGetUserMedia||m.isSecureContext===!1&&m.webkitRTCPeerConnection&&!m.RTCIceGatherer)p.browser="chrome",p.version=a(g.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(g.mediaDevices&&g.userAgent.match(/Edge\/(\d+).(\d+)$/))p.browser="edge",p.version=a(g.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!m.RTCPeerConnection||!g.userAgent.match(/AppleWebKit\/(\d+)\./))return p.browser="Not a supported browser.",p;p.browser="safari",p.version=a(g.userAgent,/AppleWebKit\/(\d+)\./,1),p.supportsUnifiedPlan=m.RTCRtpTransceiver&&"currentDirection"in m.RTCRtpTransceiver.prototype}return p}function _(m){return Object.prototype.toString.call(m)==="[object Object]"}function v(m){return _(m)?Object.keys(m).reduce(function(p,g){var w=_(m[g]),C=w?v(m[g]):m[g],T=w&&!Object.keys(C).length;return C===void 0||T?p:Object.assign(p,i({},g,C))},{}):m}function y(m,p,g){p&&!g.has(p.id)&&(g.set(p.id,p),Object.keys(p).forEach(function(w){w.endsWith("Id")?y(m,m.get(p[w]),g):w.endsWith("Ids")&&p[w].forEach(function(C){y(m,m.get(C),g)})}))}function f(m,p,g){var w=g?"outbound-rtp":"inbound-rtp",C=new Map;if(p===null)return C;var T=[];return m.forEach(function(S){S.type==="track"&&S.trackIdentifier===p.id&&T.push(S)}),T.forEach(function(S){m.forEach(function(D){D.type===w&&D.trackId===S.id&&y(m,D,C)})}),C}},{}],s6SN:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=c;var i=r(o("../utils.js"));function n(){if(typeof WeakMap!="function")return null;var u=new WeakMap;return n=function(){return u},u}function r(u){if(u&&u.__esModule)return u;if(u===null||typeof u!="object"&&typeof u!="function")return{default:u};var l=n();if(l&&l.has(u))return l.get(u);var d={},h=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var b in u)if(Object.prototype.hasOwnProperty.call(u,b)){var _=h?Object.getOwnPropertyDescriptor(u,b):null;_&&(_.get||_.set)?Object.defineProperty(d,b,_):d[b]=u[b]}return d.default=u,l&&l.set(u,d),d}function s(u){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(l){return typeof l}:function(l){return l&&typeof Symbol=="function"&&l.constructor===Symbol&&l!==Symbol.prototype?"symbol":typeof l})(u)}var a=i.log;function c(u,l){var d=u&&u.navigator;if(d.mediaDevices){var h=function(y){if(s(y)!=="object"||y.mandatory||y.optional)return y;var f={};return Object.keys(y).forEach(function(m){if(m!=="require"&&m!=="advanced"&&m!=="mediaSource"){var p=s(y[m])==="object"?y[m]:{ideal:y[m]};p.exact!==void 0&&typeof p.exact=="number"&&(p.min=p.max=p.exact);var g=function(C,T){return C?C+T.charAt(0).toUpperCase()+T.slice(1):T==="deviceId"?"sourceId":T};if(p.ideal!==void 0){f.optional=f.optional||[];var w={};typeof p.ideal=="number"?(w[g("min",m)]=p.ideal,f.optional.push(w),(w={})[g("max",m)]=p.ideal,f.optional.push(w)):(w[g("",m)]=p.ideal,f.optional.push(w))}p.exact!==void 0&&typeof p.exact!="number"?(f.mandatory=f.mandatory||{},f.mandatory[g("",m)]=p.exact):["min","max"].forEach(function(C){p[C]!==void 0&&(f.mandatory=f.mandatory||{},f.mandatory[g(C,m)]=p[C])})}}),y.advanced&&(f.optional=(f.optional||[]).concat(y.advanced)),f},b=function(y,f){if(l.version>=61)return f(y);if((y=JSON.parse(JSON.stringify(y)))&&s(y.audio)==="object"){var m=function(C,T,S){T in C&&!(S in C)&&(C[S]=C[T],delete C[T])};m((y=JSON.parse(JSON.stringify(y))).audio,"autoGainControl","googAutoGainControl"),m(y.audio,"noiseSuppression","googNoiseSuppression"),y.audio=h(y.audio)}if(y&&s(y.video)==="object"){var p=y.video.facingMode;p=p&&(s(p)==="object"?p:{ideal:p});var g,w=l.version<66;if(p&&(p.exact==="user"||p.exact==="environment"||p.ideal==="user"||p.ideal==="environment")&&(!d.mediaDevices.getSupportedConstraints||!d.mediaDevices.getSupportedConstraints().facingMode||w)&&(delete y.video.facingMode,p.exact==="environment"||p.ideal==="environment"?g=["back","rear"]:p.exact!=="user"&&p.ideal!=="user"||(g=["front"]),g))return d.mediaDevices.enumerateDevices().then(function(C){var T=(C=C.filter(function(S){return S.kind==="videoinput"})).find(function(S){return g.some(function(D){return S.label.toLowerCase().includes(D)})});return!T&&C.length&&g.includes("back")&&(T=C[C.length-1]),T&&(y.video.deviceId=p.exact?{exact:T.deviceId}:{ideal:T.deviceId}),y.video=h(y.video),a("chrome: "+JSON.stringify(y)),f(y)});y.video=h(y.video)}return a("chrome: "+JSON.stringify(y)),f(y)},_=function(y){return l.version>=64?y:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[y.name]||y.name,message:y.message,constraint:y.constraint||y.constraintName,toString:function(){return this.name+(this.message&&": ")+this.message}}};if(d.getUserMedia=function(y,f,m){b(y,function(p){d.webkitGetUserMedia(p,f,function(g){m&&m(_(g))})})}.bind(d),d.mediaDevices.getUserMedia){var v=d.mediaDevices.getUserMedia.bind(d.mediaDevices);d.mediaDevices.getUserMedia=function(y){return b(y,function(f){return v(f).then(function(m){if(f.audio&&!m.getAudioTracks().length||f.video&&!m.getVideoTracks().length)throw m.getTracks().forEach(function(p){p.stop()}),new DOMException("","NotFoundError");return m},function(m){return Promise.reject(_(m))})})}}}}},{"../utils.js":"iSxC"}],VHa8:[function(o,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(s){return r(s).then(function(a){var c=s.video&&s.video.width,u=s.video&&s.video.height,l=s.video&&s.video.frameRate;return s.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:a,maxFrameRate:l||3}},c&&(s.video.mandatory.maxWidth=c),u&&(s.video.mandatory.maxHeight=u),n.navigator.mediaDevices.getUserMedia(s)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],uI5X:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimMediaStream=l,t.shimOnTrack=d,t.shimGetSendersWithDtmf=h,t.shimGetStats=b,t.shimSenderReceiverGetStats=_,t.shimAddTrackRemoveTrackWithNative=v,t.shimAddTrackRemoveTrack=y,t.shimPeerConnection=f,t.fixNegotiationNeeded=m,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return n.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return r.shimGetDisplayMedia}});var i=a(o("../utils.js")),n=o("./getusermedia"),r=o("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var p=new WeakMap;return s=function(){return p},p}function a(p){if(p&&p.__esModule)return p;if(p===null||typeof p!="object"&&typeof p!="function")return{default:p};var g=s();if(g&&g.has(p))return g.get(p);var w={},C=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var T in p)if(Object.prototype.hasOwnProperty.call(p,T)){var S=C?Object.getOwnPropertyDescriptor(p,T):null;S&&(S.get||S.set)?Object.defineProperty(w,T,S):w[T]=p[T]}return w.default=p,g&&g.set(p,w),w}function c(p,g,w){return g in p?Object.defineProperty(p,g,{value:w,enumerable:!0,configurable:!0,writable:!0}):p[g]=w,p}function u(p){return(u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(g){return typeof g}:function(g){return g&&typeof Symbol=="function"&&g.constructor===Symbol&&g!==Symbol.prototype?"symbol":typeof g})(p)}function l(p){p.MediaStream=p.MediaStream||p.webkitMediaStream}function d(p){if(u(p)!=="object"||!p.RTCPeerConnection||"ontrack"in p.RTCPeerConnection.prototype)i.wrapPeerConnectionEvent(p,"track",function(w){return w.transceiver||Object.defineProperty(w,"transceiver",{value:{receiver:w.receiver}}),w});else{Object.defineProperty(p.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 g=p.RTCPeerConnection.prototype.setRemoteDescription;p.RTCPeerConnection.prototype.setRemoteDescription=function(){var w=this;return this._ontrackpoly||(this._ontrackpoly=function(C){C.stream.addEventListener("addtrack",function(T){var S;S=p.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(A){return A.track&&A.track.id===T.track.id}):{track:T.track};var D=new Event("track");D.track=T.track,D.receiver=S,D.transceiver={receiver:S},D.streams=[C.stream],w.dispatchEvent(D)}),C.stream.getTracks().forEach(function(T){var S;S=p.RTCPeerConnection.prototype.getReceivers?w.getReceivers().find(function(A){return A.track&&A.track.id===T.id}):{track:T};var D=new Event("track");D.track=T,D.receiver=S,D.transceiver={receiver:S},D.streams=[C.stream],w.dispatchEvent(D)})},this.addEventListener("addstream",this._ontrackpoly)),g.apply(this,arguments)}}}function h(p){if(u(p)==="object"&&p.RTCPeerConnection&&!("getSenders"in p.RTCPeerConnection.prototype)&&"createDTMFSender"in p.RTCPeerConnection.prototype){var g=function(A,P){return{track:P,get dtmf(){return this._dtmf===void 0&&(P.kind==="audio"?this._dtmf=A.createDTMFSender(P):this._dtmf=null),this._dtmf},_pc:A}};if(!p.RTCPeerConnection.prototype.getSenders){p.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};var w=p.RTCPeerConnection.prototype.addTrack;p.RTCPeerConnection.prototype.addTrack=function(A,P){var H=w.apply(this,arguments);return H||(H=g(this,A),this._senders.push(H)),H};var C=p.RTCPeerConnection.prototype.removeTrack;p.RTCPeerConnection.prototype.removeTrack=function(A){C.apply(this,arguments);var P=this._senders.indexOf(A);P!==-1&&this._senders.splice(P,1)}}var T=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(A){var P=this;this._senders=this._senders||[],T.apply(this,[A]),A.getTracks().forEach(function(H){P._senders.push(g(P,H))})};var S=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(A){var P=this;this._senders=this._senders||[],S.apply(this,[A]),A.getTracks().forEach(function(H){var B=P._senders.find(function(N){return N.track===H});B&&P._senders.splice(P._senders.indexOf(B),1)})}}else if(u(p)==="object"&&p.RTCPeerConnection&&"getSenders"in p.RTCPeerConnection.prototype&&"createDTMFSender"in p.RTCPeerConnection.prototype&&p.RTCRtpSender&&!("dtmf"in p.RTCRtpSender.prototype)){var D=p.RTCPeerConnection.prototype.getSenders;p.RTCPeerConnection.prototype.getSenders=function(){var A=this,P=D.apply(this,[]);return P.forEach(function(H){return H._pc=A}),P},Object.defineProperty(p.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function b(p){if(p.RTCPeerConnection){var g=p.RTCPeerConnection.prototype.getStats;p.RTCPeerConnection.prototype.getStats=function(){var w=this,[C,T,S]=arguments;if(arguments.length>0&&typeof C=="function")return g.apply(this,arguments);if(g.length===0&&(arguments.length===0||typeof C!="function"))return g.apply(this,[]);var D=function(P){var H={};return P.result().forEach(function(B){var N={id:B.id,timestamp:B.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[B.type]||B.type};B.names().forEach(function(W){N[W]=B.stat(W)}),H[N.id]=N}),H},A=function(P){return new Map(Object.keys(P).map(function(H){return[H,P[H]]}))};return arguments.length>=2?g.apply(this,[function(P){T(A(D(P)))},C]):new Promise(function(P,H){g.apply(w,[function(B){P(A(D(B)))},H])}).then(T,S)}}}function _(p){if(u(p)==="object"&&p.RTCPeerConnection&&p.RTCRtpSender&&p.RTCRtpReceiver){if(!("getStats"in p.RTCRtpSender.prototype)){var g=p.RTCPeerConnection.prototype.getSenders;g&&(p.RTCPeerConnection.prototype.getSenders=function(){var S=this,D=g.apply(this,[]);return D.forEach(function(A){return A._pc=S}),D});var w=p.RTCPeerConnection.prototype.addTrack;w&&(p.RTCPeerConnection.prototype.addTrack=function(){var S=w.apply(this,arguments);return S._pc=this,S}),p.RTCRtpSender.prototype.getStats=function(){var S=this;return this._pc.getStats().then(function(D){return i.filterStats(D,S.track,!0)})}}if(!("getStats"in p.RTCRtpReceiver.prototype)){var C=p.RTCPeerConnection.prototype.getReceivers;C&&(p.RTCPeerConnection.prototype.getReceivers=function(){var S=this,D=C.apply(this,[]);return D.forEach(function(A){return A._pc=S}),D}),i.wrapPeerConnectionEvent(p,"track",function(S){return S.receiver._pc=S.srcElement,S}),p.RTCRtpReceiver.prototype.getStats=function(){var S=this;return this._pc.getStats().then(function(D){return i.filterStats(D,S.track,!1)})}}if("getStats"in p.RTCRtpSender.prototype&&"getStats"in p.RTCRtpReceiver.prototype){var T=p.RTCPeerConnection.prototype.getStats;p.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof p.MediaStreamTrack){var S,D,A,P=arguments[0];return this.getSenders().forEach(function(H){H.track===P&&(S?A=!0:S=H)}),this.getReceivers().forEach(function(H){return H.track===P&&(D?A=!0:D=H),H.track===P}),A||S&&D?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):S?S.getStats():D?D.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return T.apply(this,arguments)}}}}function v(p){p.RTCPeerConnection.prototype.getLocalStreams=function(){var S=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(function(D){return S._shimmedLocalStreams[D][0]})};var g=p.RTCPeerConnection.prototype.addTrack;p.RTCPeerConnection.prototype.addTrack=function(S,D){if(!D)return g.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};var A=g.apply(this,arguments);return this._shimmedLocalStreams[D.id]?this._shimmedLocalStreams[D.id].indexOf(A)===-1&&this._shimmedLocalStreams[D.id].push(A):this._shimmedLocalStreams[D.id]=[D,A],A};var w=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(S){var D=this;this._shimmedLocalStreams=this._shimmedLocalStreams||{},S.getTracks().forEach(function(H){if(D.getSenders().find(function(B){return B.track===H}))throw new DOMException("Track already exists.","InvalidAccessError")});var A=this.getSenders();w.apply(this,arguments);var P=this.getSenders().filter(function(H){return A.indexOf(H)===-1});this._shimmedLocalStreams[S.id]=[S].concat(P)};var C=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(S){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[S.id],C.apply(this,arguments)};var T=p.RTCPeerConnection.prototype.removeTrack;p.RTCPeerConnection.prototype.removeTrack=function(S){var D=this;return this._shimmedLocalStreams=this._shimmedLocalStreams||{},S&&Object.keys(this._shimmedLocalStreams).forEach(function(A){var P=D._shimmedLocalStreams[A].indexOf(S);P!==-1&&D._shimmedLocalStreams[A].splice(P,1),D._shimmedLocalStreams[A].length===1&&delete D._shimmedLocalStreams[A]}),T.apply(this,arguments)}}function y(p,g){if(p.RTCPeerConnection){if(p.RTCPeerConnection.prototype.addTrack&&g.version>=65)return v(p);var w=p.RTCPeerConnection.prototype.getLocalStreams;p.RTCPeerConnection.prototype.getLocalStreams=function(){var P=this,H=w.apply(this);return this._reverseStreams=this._reverseStreams||{},H.map(function(B){return P._reverseStreams[B.id]})};var C=p.RTCPeerConnection.prototype.addStream;p.RTCPeerConnection.prototype.addStream=function(P){var H=this;if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},P.getTracks().forEach(function(N){if(H.getSenders().find(function(W){return W.track===N}))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[P.id]){var B=new p.MediaStream(P.getTracks());this._streams[P.id]=B,this._reverseStreams[B.id]=P,P=B}C.apply(this,[P])};var T=p.RTCPeerConnection.prototype.removeStream;p.RTCPeerConnection.prototype.removeStream=function(P){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},T.apply(this,[this._streams[P.id]||P]),delete this._reverseStreams[this._streams[P.id]?this._streams[P.id].id:P.id],delete this._streams[P.id]},p.RTCPeerConnection.prototype.addTrack=function(P,H){var B=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");var N=[].slice.call(arguments,1);if(N.length!==1||!N[0].getTracks().find(function(ue){return ue===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(ue){return ue.track===P}))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};var W=this._streams[H.id];if(W)W.addTrack(P),Promise.resolve().then(function(){B.dispatchEvent(new Event("negotiationneeded"))});else{var re=new p.MediaStream([P]);this._streams[H.id]=re,this._reverseStreams[re.id]=H,this.addStream(re)}return this.getSenders().find(function(ue){return ue.track===P})},["createOffer","createAnswer"].forEach(function(P){var H=p.RTCPeerConnection.prototype[P],B=c({},P,function(){var N=this,W=arguments;return arguments.length&&typeof arguments[0]=="function"?H.apply(this,[function(re){var ue=A(N,re);W[0].apply(null,[ue])},function(re){W[1]&&W[1].apply(null,re)},arguments[2]]):H.apply(this,arguments).then(function(re){return A(N,re)})});p.RTCPeerConnection.prototype[P]=B[P]});var S=p.RTCPeerConnection.prototype.setLocalDescription;p.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=(P=this,H=arguments[0],B=H.sdp,Object.keys(P._reverseStreams||[]).forEach(function(N){var W=P._reverseStreams[N],re=P._streams[W.id];B=B.replace(new RegExp(W.id,"g"),re.id)}),new RTCSessionDescription({type:H.type,sdp:B})),S.apply(this,arguments)):S.apply(this,arguments);var P,H,B};var D=Object.getOwnPropertyDescriptor(p.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(p.RTCPeerConnection.prototype,"localDescription",{get:function(){var P=D.get.apply(this);return P.type===""?P:A(this,P)}}),p.RTCPeerConnection.prototype.removeTrack=function(P){var H,B=this;if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!P._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(P._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(function(N){B._streams[N].getTracks().find(function(W){return P.track===W})&&(H=B._streams[N])}),H&&(H.getTracks().length===1?this.removeStream(this._reverseStreams[H.id]):H.removeTrack(P.track),this.dispatchEvent(new Event("negotiationneeded")))}}function A(P,H){var B=H.sdp;return Object.keys(P._reverseStreams||[]).forEach(function(N){var W=P._reverseStreams[N],re=P._streams[W.id];B=B.replace(new RegExp(re.id,"g"),W.id)}),new RTCSessionDescription({type:H.type,sdp:B})}}function f(p,g){!p.RTCPeerConnection&&p.webkitRTCPeerConnection&&(p.RTCPeerConnection=p.webkitRTCPeerConnection),p.RTCPeerConnection&&g.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(w){var C=p.RTCPeerConnection.prototype[w],T=c({},w,function(){return arguments[0]=new(w==="addIceCandidate"?p.RTCIceCandidate:p.RTCSessionDescription)(arguments[0]),C.apply(this,arguments)});p.RTCPeerConnection.prototype[w]=T[w]})}function m(p,g){i.wrapPeerConnectionEvent(p,"negotiationneeded",function(w){var C=w.target;if(!(g.version<72||C.getConfiguration&&C.getConfiguration().sdpSemantics==="plan-b")||C.signalingState==="stable")return w})}},{"../utils.js":"iSxC","./getusermedia":"s6SN","./getdisplaymedia":"VHa8"}],NZ1C:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.filterIceServers=s;var i=r(o("../utils"));function n(){if(typeof WeakMap!="function")return null;var a=new WeakMap;return n=function(){return a},a}function r(a){if(a&&a.__esModule)return a;if(a===null||typeof a!="object"&&typeof a!="function")return{default:a};var c=n();if(c&&c.has(a))return c.get(a);var u={},l=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var d in a)if(Object.prototype.hasOwnProperty.call(a,d)){var h=l?Object.getOwnPropertyDescriptor(a,d):null;h&&(h.get||h.set)?Object.defineProperty(u,d,h):u[d]=a[d]}return u.default=a,c&&c.set(a,u),u}function s(a,c){var u=!1;return(a=JSON.parse(JSON.stringify(a))).filter(function(l){if(l&&(l.urls||l.url)){var d=l.urls||l.url;l.url&&!l.urls&&i.deprecated("RTCIceServer.url","RTCIceServer.urls");var h=typeof d=="string";return h&&(d=[d]),d=d.filter(function(b){if(b.indexOf("stun:")===0)return!1;var _=b.startsWith("turn")&&!b.startsWith("turn:[")&&b.includes("transport=udp");return _&&!u?(u=!0,!0):_&&!u}),delete l.url,l.urls=h?d[0]:d,!!d.length}})}},{"../utils":"iSxC"}],YHvh:[function(o,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,s){return(s>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(s){return s.indexOf(r)===0})},i.parseCandidate=function(n){for(var r,s={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]},a=8;a<r.length;a+=2)switch(r[a]){case"raddr":s.relatedAddress=r[a+1];break;case"rport":s.relatedPort=parseInt(r[a+1],10);break;case"tcptype":s.tcpType=r[a+1];break;case"ufrag":s.ufrag=r[a+1],s.usernameFragment=r[a+1];break;default:s[r[a]]=r[a+1]}return s},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 s=n.type;return r.push("typ"),r.push(s),s!=="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(" "),s={payloadType:parseInt(r.shift(),10)};return r=r[0].split("/"),s.name=r[0],s.clockRate=parseInt(r[1],10),s.channels=r.length===3?parseInt(r[2],10):1,s.numChannels=s.channels,s},i.writeRtpMap=function(n){var r=n.payloadType;n.preferredPayloadType!==void 0&&(r=n.preferredPayloadType);var s=n.channels||n.numChannels||1;return"a=rtpmap:"+r+" "+n.name+"/"+n.clockRate+(s!==1?"/"+s:"")+`\r
|
|
@@ -45,28 +45,28 @@ t=0 0\r
|
|
|
45
45
|
`;y+="a="+m,y+="a=ssrc:"+d.sendEncodingParameters[0].ssrc+" "+m,d.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+d.sendEncodingParameters[0].rtx.ssrc+" "+m,y+="a=ssrc-group:FID "+d.sendEncodingParameters[0].ssrc+" "+d.sendEncodingParameters[0].rtx.ssrc+`\r
|
|
46
46
|
`)}return y+="a=ssrc:"+d.sendEncodingParameters[0].ssrc+" cname:"+i.localCName+`\r
|
|
47
47
|
`,d.rtpSender&&d.sendEncodingParameters[0].rtx&&(y+="a=ssrc:"+d.sendEncodingParameters[0].rtx.ssrc+" cname:"+i.localCName+`\r
|
|
48
|
-
`),y}function s(d,h){var b=!1;return(d=JSON.parse(JSON.stringify(d))).filter(function(_){if(_&&(_.urls||_.url)){var v=_.urls||_.url;_.url&&!_.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var y=typeof v=="string";return y&&(v=[v]),v=v.filter(function(f){return f.indexOf("turn:")===0&&f.indexOf("transport=udp")!==-1&&f.indexOf("turn:[")===-1&&!b?(b=!0,!0):f.indexOf("stun:")===0&&h>=14393&&f.indexOf("?transport=udp")===-1}),delete _.url,_.urls=y?v[0]:v,!!v.length}})}function a(d,h){var b={codecs:[],headerExtensions:[],fecMechanisms:[]},_=function(y,f){y=parseInt(y,10);for(var m=0;m<f.length;m++)if(f[m].payloadType===y||f[m].preferredPayloadType===y)return f[m]},v=function(y,f,m,p){var g=_(y.parameters.apt,m),
|
|
48
|
+
`),y}function s(d,h){var b=!1;return(d=JSON.parse(JSON.stringify(d))).filter(function(_){if(_&&(_.urls||_.url)){var v=_.urls||_.url;_.url&&!_.urls&&console.warn("RTCIceServer.url is deprecated! Use urls instead.");var y=typeof v=="string";return y&&(v=[v]),v=v.filter(function(f){return f.indexOf("turn:")===0&&f.indexOf("transport=udp")!==-1&&f.indexOf("turn:[")===-1&&!b?(b=!0,!0):f.indexOf("stun:")===0&&h>=14393&&f.indexOf("?transport=udp")===-1}),delete _.url,_.urls=y?v[0]:v,!!v.length}})}function a(d,h){var b={codecs:[],headerExtensions:[],fecMechanisms:[]},_=function(y,f){y=parseInt(y,10);for(var m=0;m<f.length;m++)if(f[m].payloadType===y||f[m].preferredPayloadType===y)return f[m]},v=function(y,f,m,p){var g=_(y.parameters.apt,m),w=_(f.parameters.apt,p);return g&&w&&g.name.toLowerCase()===w.name.toLowerCase()};return d.codecs.forEach(function(y){for(var f=0;f<h.codecs.length;f++){var m=h.codecs[f];if(y.name.toLowerCase()===m.name.toLowerCase()&&y.clockRate===m.clockRate){if(y.name.toLowerCase()==="rtx"&&y.parameters&&m.parameters.apt&&!v(y,m,d.codecs,h.codecs))continue;(m=JSON.parse(JSON.stringify(m))).numChannels=Math.min(y.numChannels,m.numChannels),b.codecs.push(m),m.rtcpFeedback=m.rtcpFeedback.filter(function(p){for(var g=0;g<y.rtcpFeedback.length;g++)if(y.rtcpFeedback[g].type===p.type&&y.rtcpFeedback[g].parameter===p.parameter)return!0;return!1});break}}}),d.headerExtensions.forEach(function(y){for(var f=0;f<h.headerExtensions.length;f++){var m=h.headerExtensions[f];if(y.uri===m.uri){b.headerExtensions.push(m);break}}}),b}function c(d,h,b){return{offer:{setLocalDescription:["stable","have-local-offer"],setRemoteDescription:["stable","have-remote-offer"]},answer:{setLocalDescription:["have-remote-offer","have-local-pranswer"],setRemoteDescription:["have-local-offer","have-remote-pranswer"]}}[h][d].indexOf(b)!==-1}function u(d,h){var b=d.getRemoteCandidates().find(function(_){return h.foundation===_.foundation&&h.ip===_.ip&&h.port===_.port&&h.priority===_.priority&&h.protocol===_.protocol&&h.type===_.type});return b||d.addRemoteCandidate(h),!b}function l(d,h){var b=new Error(h);return b.name=d,b.code={NotSupportedError:9,InvalidStateError:11,InvalidAccessError:15,TypeError:void 0,OperationError:void 0}[d],b}e.exports=function(d,h){function b(f,m){m.addTrack(f),m.dispatchEvent(new d.MediaStreamTrackEvent("addtrack",{track:f}))}function _(f,m,p,g){var w=new Event("track");w.track=m,w.receiver=p,w.transceiver={receiver:p},w.streams=g,d.setTimeout(function(){f._dispatchEvent("track",w)})}var v=function(f){var m=this,p=document.createDocumentFragment();if(["addEventListener","removeEventListener","dispatchEvent"].forEach(function(w){m[w]=p[w].bind(p)}),this.canTrickleIceCandidates=null,this.needNegotiation=!1,this.localStreams=[],this.remoteStreams=[],this._localDescription=null,this._remoteDescription=null,this.signalingState="stable",this.iceConnectionState="new",this.connectionState="new",this.iceGatheringState="new",f=JSON.parse(JSON.stringify(f||{})),this.usingBundle=f.bundlePolicy==="max-bundle",f.rtcpMuxPolicy==="negotiate")throw l("NotSupportedError","rtcpMuxPolicy 'negotiate' is not supported");switch(f.rtcpMuxPolicy||(f.rtcpMuxPolicy="require"),f.iceTransportPolicy){case"all":case"relay":break;default:f.iceTransportPolicy="all"}switch(f.bundlePolicy){case"balanced":case"max-compat":case"max-bundle":break;default:f.bundlePolicy="balanced"}if(f.iceServers=s(f.iceServers||[],h),this._iceGatherers=[],f.iceCandidatePoolSize)for(var g=f.iceCandidatePoolSize;g>0;g--)this._iceGatherers.push(new d.RTCIceGatherer({iceServers:f.iceServers,gatherPolicy:f.iceTransportPolicy}));else f.iceCandidatePoolSize=0;this._config=f,this.transceivers=[],this._sdpSessionId=i.generateSessionId(),this._sdpSessionVersion=0,this._dtlsRole=void 0,this._isClosed=!1};Object.defineProperty(v.prototype,"localDescription",{configurable:!0,get:function(){return this._localDescription}}),Object.defineProperty(v.prototype,"remoteDescription",{configurable:!0,get:function(){return this._remoteDescription}}),v.prototype.onicecandidate=null,v.prototype.onaddstream=null,v.prototype.ontrack=null,v.prototype.onremovestream=null,v.prototype.onsignalingstatechange=null,v.prototype.oniceconnectionstatechange=null,v.prototype.onconnectionstatechange=null,v.prototype.onicegatheringstatechange=null,v.prototype.onnegotiationneeded=null,v.prototype.ondatachannel=null,v.prototype._dispatchEvent=function(f,m){this._isClosed||(this.dispatchEvent(m),typeof this["on"+f]=="function"&&this["on"+f](m))},v.prototype._emitGatheringStateChange=function(){var f=new Event("icegatheringstatechange");this._dispatchEvent("icegatheringstatechange",f)},v.prototype.getConfiguration=function(){return this._config},v.prototype.getLocalStreams=function(){return this.localStreams},v.prototype.getRemoteStreams=function(){return this.remoteStreams},v.prototype._createTransceiver=function(f,m){var p=this.transceivers.length>0,g={track:null,iceGatherer:null,iceTransport:null,dtlsTransport:null,localCapabilities:null,remoteCapabilities:null,rtpSender:null,rtpReceiver:null,kind:f,mid:null,sendEncodingParameters:null,recvEncodingParameters:null,stream:null,associatedRemoteMediaStreams:[],wantReceive:!0};if(this.usingBundle&&p)g.iceTransport=this.transceivers[0].iceTransport,g.dtlsTransport=this.transceivers[0].dtlsTransport;else{var w=this._createIceAndDtlsTransports();g.iceTransport=w.iceTransport,g.dtlsTransport=w.dtlsTransport}return m||this.transceivers.push(g),g},v.prototype.addTrack=function(f,m){if(this._isClosed)throw l("InvalidStateError","Attempted to call addTrack on a closed peerconnection.");var p;if(this.transceivers.find(function(w){return w.track===f}))throw l("InvalidAccessError","Track already exists.");for(var g=0;g<this.transceivers.length;g++)this.transceivers[g].track||this.transceivers[g].kind!==f.kind||(p=this.transceivers[g]);return p||(p=this._createTransceiver(f.kind)),this._maybeFireNegotiationNeeded(),this.localStreams.indexOf(m)===-1&&this.localStreams.push(m),p.track=f,p.stream=m,p.rtpSender=new d.RTCRtpSender(f,p.dtlsTransport),p.rtpSender},v.prototype.addStream=function(f){var m=this;if(h>=15025)f.getTracks().forEach(function(g){m.addTrack(g,f)});else{var p=f.clone();f.getTracks().forEach(function(g,w){var C=p.getTracks()[w];g.addEventListener("enabled",function(T){C.enabled=T.enabled})}),p.getTracks().forEach(function(g){m.addTrack(g,p)})}},v.prototype.removeTrack=function(f){if(this._isClosed)throw l("InvalidStateError","Attempted to call removeTrack on a closed peerconnection.");if(!(f instanceof d.RTCRtpSender))throw new TypeError("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.");var m=this.transceivers.find(function(g){return g.rtpSender===f});if(!m)throw l("InvalidAccessError","Sender was not created by this connection.");var p=m.stream;m.rtpSender.stop(),m.rtpSender=null,m.track=null,m.stream=null,this.transceivers.map(function(g){return g.stream}).indexOf(p)===-1&&this.localStreams.indexOf(p)>-1&&this.localStreams.splice(this.localStreams.indexOf(p),1),this._maybeFireNegotiationNeeded()},v.prototype.removeStream=function(f){var m=this;f.getTracks().forEach(function(p){var g=m.getSenders().find(function(w){return w.track===p});g&&m.removeTrack(g)})},v.prototype.getSenders=function(){return this.transceivers.filter(function(f){return!!f.rtpSender}).map(function(f){return f.rtpSender})},v.prototype.getReceivers=function(){return this.transceivers.filter(function(f){return!!f.rtpReceiver}).map(function(f){return f.rtpReceiver})},v.prototype._createIceGatherer=function(f,m){var p=this;if(m&&f>0)return this.transceivers[0].iceGatherer;if(this._iceGatherers.length)return this._iceGatherers.shift();var g=new d.RTCIceGatherer({iceServers:this._config.iceServers,gatherPolicy:this._config.iceTransportPolicy});return Object.defineProperty(g,"state",{value:"new",writable:!0}),this.transceivers[f].bufferedCandidateEvents=[],this.transceivers[f].bufferCandidates=function(w){var C=!w.candidate||Object.keys(w.candidate).length===0;g.state=C?"completed":"gathering",p.transceivers[f].bufferedCandidateEvents!==null&&p.transceivers[f].bufferedCandidateEvents.push(w)},g.addEventListener("localcandidate",this.transceivers[f].bufferCandidates),g},v.prototype._gather=function(f,m){var p=this,g=this.transceivers[m].iceGatherer;if(!g.onlocalcandidate){var w=this.transceivers[m].bufferedCandidateEvents;this.transceivers[m].bufferedCandidateEvents=null,g.removeEventListener("localcandidate",this.transceivers[m].bufferCandidates),g.onlocalcandidate=function(C){if(!(p.usingBundle&&m>0)){var T=new Event("icecandidate");T.candidate={sdpMid:f,sdpMLineIndex:m};var S=C.candidate,D=!S||Object.keys(S).length===0;if(D)g.state!=="new"&&g.state!=="gathering"||(g.state="completed");else{g.state==="new"&&(g.state="gathering"),S.component=1,S.ufrag=g.getLocalParameters().usernameFragment;var A=i.writeCandidate(S);T.candidate=Object.assign(T.candidate,i.parseCandidate(A)),T.candidate.candidate=A,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(p._localDescription.sdp);P[T.candidate.sdpMLineIndex]+=D?`a=end-of-candidates\r
|
|
49
49
|
`:"a="+T.candidate.candidate+`\r
|
|
50
|
-
`,p._localDescription.sdp=i.getDescription(p._localDescription.sdp)+P.join("");var H=p.transceivers.every(function(B){return B.iceGatherer&&B.iceGatherer.state==="completed"});p.iceGatheringState!=="gathering"&&(p.iceGatheringState="gathering",p._emitGatheringStateChange()),D||p._dispatchEvent("icecandidate",T),H&&(p._dispatchEvent("icecandidate",new Event("icecandidate")),p.iceGatheringState="complete",p._emitGatheringStateChange())}},d.setTimeout(function(){x.forEach(function(C){g.onlocalcandidate(C)})},0)}},v.prototype._createIceAndDtlsTransports=function(){var f=this,m=new d.RTCIceTransport(null);m.onicestatechange=function(){f._updateIceConnectionState(),f._updateConnectionState()};var p=new d.RTCDtlsTransport(m);return p.ondtlsstatechange=function(){f._updateConnectionState()},p.onerror=function(){Object.defineProperty(p,"state",{value:"failed",writable:!0}),f._updateConnectionState()},{iceTransport:m,dtlsTransport:p}},v.prototype._disposeIceAndDtlsTransports=function(f){var m=this.transceivers[f].iceGatherer;m&&(delete m.onlocalcandidate,delete this.transceivers[f].iceGatherer);var p=this.transceivers[f].iceTransport;p&&(delete p.onicestatechange,delete this.transceivers[f].iceTransport);var g=this.transceivers[f].dtlsTransport;g&&(delete g.ondtlsstatechange,delete g.onerror,delete this.transceivers[f].dtlsTransport)},v.prototype._transceive=function(f,m,p){var g=a(f.localCapabilities,f.remoteCapabilities);m&&f.rtpSender&&(g.encodings=f.sendEncodingParameters,g.rtcp={cname:i.localCName,compound:f.rtcpParameters.compound},f.recvEncodingParameters.length&&(g.rtcp.ssrc=f.recvEncodingParameters[0].ssrc),f.rtpSender.send(g)),p&&f.rtpReceiver&&g.codecs.length>0&&(f.kind==="video"&&f.recvEncodingParameters&&h<15019&&f.recvEncodingParameters.forEach(function(x){delete x.rtx}),f.recvEncodingParameters.length?g.encodings=f.recvEncodingParameters:g.encodings=[{}],g.rtcp={compound:f.rtcpParameters.compound},f.rtcpParameters.cname&&(g.rtcp.cname=f.rtcpParameters.cname),f.sendEncodingParameters.length&&(g.rtcp.ssrc=f.sendEncodingParameters[0].ssrc),f.rtpReceiver.receive(g))},v.prototype.setLocalDescription=function(f){var m,p,g=this;if(["offer","answer"].indexOf(f.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+f.type+'"'));if(!c("setLocalDescription",f.type,g.signalingState)||g._isClosed)return Promise.reject(l("InvalidStateError","Can not set local "+f.type+" in state "+g.signalingState));if(f.type==="offer")m=i.splitSections(f.sdp),p=m.shift(),m.forEach(function(C,T){var S=i.parseRtpParameters(C);g.transceivers[T].localCapabilities=S}),g.transceivers.forEach(function(C,T){g._gather(C.mid,T)});else if(f.type==="answer"){m=i.splitSections(g._remoteDescription.sdp),p=m.shift();var x=i.matchPrefix(p,"a=ice-lite").length>0;m.forEach(function(C,T){var S=g.transceivers[T],D=S.iceGatherer,A=S.iceTransport,P=S.dtlsTransport,H=S.localCapabilities,B=S.remoteCapabilities;if(!(i.isRejected(C)&&i.matchPrefix(C,"a=bundle-only").length===0)&&!S.rejected){var N=i.getIceParameters(C,p),W=i.getDtlsParameters(C,p);x&&(W.role="server"),g.usingBundle&&T!==0||(g._gather(S.mid,T),A.state==="new"&&A.start(D,N,x?"controlling":"controlled"),P.state==="new"&&P.start(W));var re=a(H,B);g._transceive(S,re.codecs.length>0,!1)}})}return g._localDescription={type:f.type,sdp:f.sdp},f.type==="offer"?g._updateSignalingState("have-local-offer"):g._updateSignalingState("stable"),Promise.resolve()},v.prototype.setRemoteDescription=function(f){var m=this;if(["offer","answer"].indexOf(f.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+f.type+'"'));if(!c("setRemoteDescription",f.type,m.signalingState)||m._isClosed)return Promise.reject(l("InvalidStateError","Can not set remote "+f.type+" in state "+m.signalingState));var p={};m.remoteStreams.forEach(function(A){p[A.id]=A});var g=[],x=i.splitSections(f.sdp),C=x.shift(),T=i.matchPrefix(C,"a=ice-lite").length>0,S=i.matchPrefix(C,"a=group:BUNDLE ").length>0;m.usingBundle=S;var D=i.matchPrefix(C,"a=ice-options:")[0];return m.canTrickleIceCandidates=!!D&&D.substr(14).split(" ").indexOf("trickle")>=0,x.forEach(function(A,P){var H=i.splitLines(A),B=i.getKind(A),N=i.isRejected(A)&&i.matchPrefix(A,"a=bundle-only").length===0,W=H[0].substr(2).split(" ")[2],re=i.getDirection(A,C),ue=i.parseMsid(A),Qd=i.getMid(A)||i.generateIdentifier();if(N||B==="application"&&(W==="DTLS/SCTP"||W==="UDP/DTLS/SCTP"))m.transceivers[P]={mid:Qd,kind:B,protocol:W,rejected:!0};else{var q,qd,hs,ql,dn,Yl,Kl,ps,hn;!N&&m.transceivers[P]&&m.transceivers[P].rejected&&(m.transceivers[P]=m._createTransceiver(B,!0));var Yd,Kd,Jd=i.parseRtpParameters(A);N||(Yd=i.getIceParameters(A,C),(Kd=i.getDtlsParameters(A,C)).role="client"),Kl=i.parseRtpEncodingParameters(A);var Zd=i.parseRtcpParameters(A),$d=i.matchPrefix(A,"a=end-of-candidates",C).length>0,wo=i.matchPrefix(A,"a=candidate:").map(function(at){return i.parseCandidate(at)}).filter(function(at){return at.component===1});if((f.type==="offer"||f.type==="answer")&&!N&&S&&P>0&&m.transceivers[P]&&(m._disposeIceAndDtlsTransports(P),m.transceivers[P].iceGatherer=m.transceivers[0].iceGatherer,m.transceivers[P].iceTransport=m.transceivers[0].iceTransport,m.transceivers[P].dtlsTransport=m.transceivers[0].dtlsTransport,m.transceivers[P].rtpSender&&m.transceivers[P].rtpSender.setTransport(m.transceivers[0].dtlsTransport),m.transceivers[P].rtpReceiver&&m.transceivers[P].rtpReceiver.setTransport(m.transceivers[0].dtlsTransport)),f.type!=="offer"||N)f.type==="answer"&&!N&&(qd=(q=m.transceivers[P]).iceGatherer,hs=q.iceTransport,ql=q.dtlsTransport,dn=q.rtpReceiver,Yl=q.sendEncodingParameters,ps=q.localCapabilities,m.transceivers[P].recvEncodingParameters=Kl,m.transceivers[P].remoteCapabilities=Jd,m.transceivers[P].rtcpParameters=Zd,wo.length&&hs.state==="new"&&(!T&&!$d||S&&P!==0?wo.forEach(function(at){u(q.iceTransport,at)}):hs.setRemoteCandidates(wo)),S&&P!==0||(hs.state==="new"&&hs.start(qd,Yd,"controlling"),ql.state==="new"&&ql.start(Kd)),!a(q.localCapabilities,q.remoteCapabilities).codecs.filter(function(at){return at.name.toLowerCase()==="rtx"}).length&&q.sendEncodingParameters[0].rtx&&delete q.sendEncodingParameters[0].rtx,m._transceive(q,re==="sendrecv"||re==="recvonly",re==="sendrecv"||re==="sendonly"),!dn||re!=="sendrecv"&&re!=="sendonly"?delete q.rtpReceiver:(hn=dn.track,ue?(p[ue.stream]||(p[ue.stream]=new d.MediaStream),b(hn,p[ue.stream]),g.push([hn,dn,p[ue.stream]])):(p.default||(p.default=new d.MediaStream),b(hn,p.default),g.push([hn,dn,p.default]))));else{(q=m.transceivers[P]||m._createTransceiver(B)).mid=Qd,q.iceGatherer||(q.iceGatherer=m._createIceGatherer(P,S)),wo.length&&q.iceTransport.state==="new"&&(!$d||S&&P!==0?wo.forEach(function(at){u(q.iceTransport,at)}):q.iceTransport.setRemoteCandidates(wo)),ps=d.RTCRtpReceiver.getCapabilities(B),h<15019&&(ps.codecs=ps.codecs.filter(function(at){return at.name!=="rtx"})),Yl=q.sendEncodingParameters||[{ssrc:1001*(2*P+2)}];var Eo,Jl=!1;re==="sendrecv"||re==="sendonly"?(Jl=!q.rtpReceiver,dn=q.rtpReceiver||new d.RTCRtpReceiver(q.dtlsTransport,B),Jl&&(hn=dn.track,ue&&ue.stream==="-"||(ue?(p[ue.stream]||(p[ue.stream]=new d.MediaStream,Object.defineProperty(p[ue.stream],"id",{get:function(){return ue.stream}})),Object.defineProperty(hn,"id",{get:function(){return ue.track}}),Eo=p[ue.stream]):(p.default||(p.default=new d.MediaStream),Eo=p.default)),Eo&&(b(hn,Eo),q.associatedRemoteMediaStreams.push(Eo)),g.push([hn,dn,Eo]))):q.rtpReceiver&&q.rtpReceiver.track&&(q.associatedRemoteMediaStreams.forEach(function(at){var Zl,eh,th=at.getTracks().find(function(lm){return lm.id===q.rtpReceiver.track.id});th&&(Zl=th,(eh=at).removeTrack(Zl),eh.dispatchEvent(new d.MediaStreamTrackEvent("removetrack",{track:Zl})))}),q.associatedRemoteMediaStreams=[]),q.localCapabilities=ps,q.remoteCapabilities=Jd,q.rtpReceiver=dn,q.rtcpParameters=Zd,q.sendEncodingParameters=Yl,q.recvEncodingParameters=Kl,m._transceive(m.transceivers[P],!1,Jl)}}}),m._dtlsRole===void 0&&(m._dtlsRole=f.type==="offer"?"active":"passive"),m._remoteDescription={type:f.type,sdp:f.sdp},f.type==="offer"?m._updateSignalingState("have-remote-offer"):m._updateSignalingState("stable"),Object.keys(p).forEach(function(A){var P=p[A];if(P.getTracks().length){if(m.remoteStreams.indexOf(P)===-1){m.remoteStreams.push(P);var H=new Event("addstream");H.stream=P,d.setTimeout(function(){m._dispatchEvent("addstream",H)})}g.forEach(function(B){var N=B[0],W=B[1];P.id===B[2].id&&_(m,N,W,[P])})}}),g.forEach(function(A){A[2]||_(m,A[0],A[1],[])}),d.setTimeout(function(){m&&m.transceivers&&m.transceivers.forEach(function(A){A.iceTransport&&A.iceTransport.state==="new"&&A.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),A.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},v.prototype.close=function(){this.transceivers.forEach(function(f){f.iceTransport&&f.iceTransport.stop(),f.dtlsTransport&&f.dtlsTransport.stop(),f.rtpSender&&f.rtpSender.stop(),f.rtpReceiver&&f.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},v.prototype._updateSignalingState=function(f){this.signalingState=f;var m=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",m)},v.prototype._maybeFireNegotiationNeeded=function(){var f=this;this.signalingState==="stable"&&this.needNegotiation!==!0&&(this.needNegotiation=!0,d.setTimeout(function(){if(f.needNegotiation){f.needNegotiation=!1;var m=new Event("negotiationneeded");f._dispatchEvent("negotiationneeded",m)}},0))},v.prototype._updateIceConnectionState=function(){var f,m={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(g){g.iceTransport&&!g.rejected&&m[g.iceTransport.state]++}),f="new",m.failed>0?f="failed":m.checking>0?f="checking":m.disconnected>0?f="disconnected":m.new>0?f="new":m.connected>0?f="connected":m.completed>0&&(f="completed"),f!==this.iceConnectionState){this.iceConnectionState=f;var p=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",p)}},v.prototype._updateConnectionState=function(){var f,m={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(g){g.iceTransport&&g.dtlsTransport&&!g.rejected&&(m[g.iceTransport.state]++,m[g.dtlsTransport.state]++)}),m.connected+=m.completed,f="new",m.failed>0?f="failed":m.connecting>0?f="connecting":m.disconnected>0?f="disconnected":m.new>0?f="new":m.connected>0&&(f="connected"),f!==this.connectionState){this.connectionState=f;var p=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",p)}},v.prototype.createOffer=function(){var f=this;if(f._isClosed)return Promise.reject(l("InvalidStateError","Can not call createOffer after close"));var m=f.transceivers.filter(function(T){return T.kind==="audio"}).length,p=f.transceivers.filter(function(T){return T.kind==="video"}).length,g=arguments[0];if(g){if(g.mandatory||g.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");g.offerToReceiveAudio!==void 0&&(m=g.offerToReceiveAudio===!0?1:g.offerToReceiveAudio===!1?0:g.offerToReceiveAudio),g.offerToReceiveVideo!==void 0&&(p=g.offerToReceiveVideo===!0?1:g.offerToReceiveVideo===!1?0:g.offerToReceiveVideo)}for(f.transceivers.forEach(function(T){T.kind==="audio"?--m<0&&(T.wantReceive=!1):T.kind==="video"&&--p<0&&(T.wantReceive=!1)});m>0||p>0;)m>0&&(f._createTransceiver("audio"),m--),p>0&&(f._createTransceiver("video"),p--);var x=i.writeSessionBoilerplate(f._sdpSessionId,f._sdpSessionVersion++);f.transceivers.forEach(function(T,S){var D=T.track,A=T.kind,P=T.mid||i.generateIdentifier();T.mid=P,T.iceGatherer||(T.iceGatherer=f._createIceGatherer(S,f.usingBundle));var H=d.RTCRtpSender.getCapabilities(A);h<15019&&(H.codecs=H.codecs.filter(function(N){return N.name!=="rtx"})),H.codecs.forEach(function(N){N.name==="H264"&&N.parameters["level-asymmetry-allowed"]===void 0&&(N.parameters["level-asymmetry-allowed"]="1"),T.remoteCapabilities&&T.remoteCapabilities.codecs&&T.remoteCapabilities.codecs.forEach(function(W){N.name.toLowerCase()===W.name.toLowerCase()&&N.clockRate===W.clockRate&&(N.preferredPayloadType=W.payloadType)})}),H.headerExtensions.forEach(function(N){(T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[]).forEach(function(W){N.uri===W.uri&&(N.id=W.id)})});var B=T.sendEncodingParameters||[{ssrc:1001*(2*S+1)}];D&&h>=15019&&A==="video"&&!B[0].rtx&&(B[0].rtx={ssrc:B[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new d.RTCRtpReceiver(T.dtlsTransport,A)),T.localCapabilities=H,T.sendEncodingParameters=B}),f._config.bundlePolicy!=="max-compat"&&(x+="a=group:BUNDLE "+f.transceivers.map(function(T){return T.mid}).join(" ")+`\r
|
|
51
|
-
`),
|
|
52
|
-
`,f.transceivers.forEach(function(T,S){
|
|
53
|
-
`,!T.iceGatherer||f.iceGatheringState==="new"||S!==0&&f.usingBundle||(T.iceGatherer.getLocalCandidates().forEach(function(D){D.component=1,
|
|
54
|
-
`}),T.iceGatherer.state==="completed"&&(
|
|
55
|
-
`))});var C=new d.RTCSessionDescription({type:"offer",sdp:
|
|
50
|
+
`,p._localDescription.sdp=i.getDescription(p._localDescription.sdp)+P.join("");var H=p.transceivers.every(function(B){return B.iceGatherer&&B.iceGatherer.state==="completed"});p.iceGatheringState!=="gathering"&&(p.iceGatheringState="gathering",p._emitGatheringStateChange()),D||p._dispatchEvent("icecandidate",T),H&&(p._dispatchEvent("icecandidate",new Event("icecandidate")),p.iceGatheringState="complete",p._emitGatheringStateChange())}},d.setTimeout(function(){w.forEach(function(C){g.onlocalcandidate(C)})},0)}},v.prototype._createIceAndDtlsTransports=function(){var f=this,m=new d.RTCIceTransport(null);m.onicestatechange=function(){f._updateIceConnectionState(),f._updateConnectionState()};var p=new d.RTCDtlsTransport(m);return p.ondtlsstatechange=function(){f._updateConnectionState()},p.onerror=function(){Object.defineProperty(p,"state",{value:"failed",writable:!0}),f._updateConnectionState()},{iceTransport:m,dtlsTransport:p}},v.prototype._disposeIceAndDtlsTransports=function(f){var m=this.transceivers[f].iceGatherer;m&&(delete m.onlocalcandidate,delete this.transceivers[f].iceGatherer);var p=this.transceivers[f].iceTransport;p&&(delete p.onicestatechange,delete this.transceivers[f].iceTransport);var g=this.transceivers[f].dtlsTransport;g&&(delete g.ondtlsstatechange,delete g.onerror,delete this.transceivers[f].dtlsTransport)},v.prototype._transceive=function(f,m,p){var g=a(f.localCapabilities,f.remoteCapabilities);m&&f.rtpSender&&(g.encodings=f.sendEncodingParameters,g.rtcp={cname:i.localCName,compound:f.rtcpParameters.compound},f.recvEncodingParameters.length&&(g.rtcp.ssrc=f.recvEncodingParameters[0].ssrc),f.rtpSender.send(g)),p&&f.rtpReceiver&&g.codecs.length>0&&(f.kind==="video"&&f.recvEncodingParameters&&h<15019&&f.recvEncodingParameters.forEach(function(w){delete w.rtx}),f.recvEncodingParameters.length?g.encodings=f.recvEncodingParameters:g.encodings=[{}],g.rtcp={compound:f.rtcpParameters.compound},f.rtcpParameters.cname&&(g.rtcp.cname=f.rtcpParameters.cname),f.sendEncodingParameters.length&&(g.rtcp.ssrc=f.sendEncodingParameters[0].ssrc),f.rtpReceiver.receive(g))},v.prototype.setLocalDescription=function(f){var m,p,g=this;if(["offer","answer"].indexOf(f.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+f.type+'"'));if(!c("setLocalDescription",f.type,g.signalingState)||g._isClosed)return Promise.reject(l("InvalidStateError","Can not set local "+f.type+" in state "+g.signalingState));if(f.type==="offer")m=i.splitSections(f.sdp),p=m.shift(),m.forEach(function(C,T){var S=i.parseRtpParameters(C);g.transceivers[T].localCapabilities=S}),g.transceivers.forEach(function(C,T){g._gather(C.mid,T)});else if(f.type==="answer"){m=i.splitSections(g._remoteDescription.sdp),p=m.shift();var w=i.matchPrefix(p,"a=ice-lite").length>0;m.forEach(function(C,T){var S=g.transceivers[T],D=S.iceGatherer,A=S.iceTransport,P=S.dtlsTransport,H=S.localCapabilities,B=S.remoteCapabilities;if(!(i.isRejected(C)&&i.matchPrefix(C,"a=bundle-only").length===0)&&!S.rejected){var N=i.getIceParameters(C,p),W=i.getDtlsParameters(C,p);w&&(W.role="server"),g.usingBundle&&T!==0||(g._gather(S.mid,T),A.state==="new"&&A.start(D,N,w?"controlling":"controlled"),P.state==="new"&&P.start(W));var re=a(H,B);g._transceive(S,re.codecs.length>0,!1)}})}return g._localDescription={type:f.type,sdp:f.sdp},f.type==="offer"?g._updateSignalingState("have-local-offer"):g._updateSignalingState("stable"),Promise.resolve()},v.prototype.setRemoteDescription=function(f){var m=this;if(["offer","answer"].indexOf(f.type)===-1)return Promise.reject(l("TypeError",'Unsupported type "'+f.type+'"'));if(!c("setRemoteDescription",f.type,m.signalingState)||m._isClosed)return Promise.reject(l("InvalidStateError","Can not set remote "+f.type+" in state "+m.signalingState));var p={};m.remoteStreams.forEach(function(A){p[A.id]=A});var g=[],w=i.splitSections(f.sdp),C=w.shift(),T=i.matchPrefix(C,"a=ice-lite").length>0,S=i.matchPrefix(C,"a=group:BUNDLE ").length>0;m.usingBundle=S;var D=i.matchPrefix(C,"a=ice-options:")[0];return m.canTrickleIceCandidates=!!D&&D.substr(14).split(" ").indexOf("trickle")>=0,w.forEach(function(A,P){var H=i.splitLines(A),B=i.getKind(A),N=i.isRejected(A)&&i.matchPrefix(A,"a=bundle-only").length===0,W=H[0].substr(2).split(" ")[2],re=i.getDirection(A,C),ue=i.parseMsid(A),Qd=i.getMid(A)||i.generateIdentifier();if(N||B==="application"&&(W==="DTLS/SCTP"||W==="UDP/DTLS/SCTP"))m.transceivers[P]={mid:Qd,kind:B,protocol:W,rejected:!0};else{var q,qd,hs,ql,hn,Yl,Kl,ps,pn;!N&&m.transceivers[P]&&m.transceivers[P].rejected&&(m.transceivers[P]=m._createTransceiver(B,!0));var Yd,Kd,Jd=i.parseRtpParameters(A);N||(Yd=i.getIceParameters(A,C),(Kd=i.getDtlsParameters(A,C)).role="client"),Kl=i.parseRtpEncodingParameters(A);var Zd=i.parseRtcpParameters(A),$d=i.matchPrefix(A,"a=end-of-candidates",C).length>0,wo=i.matchPrefix(A,"a=candidate:").map(function(at){return i.parseCandidate(at)}).filter(function(at){return at.component===1});if((f.type==="offer"||f.type==="answer")&&!N&&S&&P>0&&m.transceivers[P]&&(m._disposeIceAndDtlsTransports(P),m.transceivers[P].iceGatherer=m.transceivers[0].iceGatherer,m.transceivers[P].iceTransport=m.transceivers[0].iceTransport,m.transceivers[P].dtlsTransport=m.transceivers[0].dtlsTransport,m.transceivers[P].rtpSender&&m.transceivers[P].rtpSender.setTransport(m.transceivers[0].dtlsTransport),m.transceivers[P].rtpReceiver&&m.transceivers[P].rtpReceiver.setTransport(m.transceivers[0].dtlsTransport)),f.type!=="offer"||N)f.type==="answer"&&!N&&(qd=(q=m.transceivers[P]).iceGatherer,hs=q.iceTransport,ql=q.dtlsTransport,hn=q.rtpReceiver,Yl=q.sendEncodingParameters,ps=q.localCapabilities,m.transceivers[P].recvEncodingParameters=Kl,m.transceivers[P].remoteCapabilities=Jd,m.transceivers[P].rtcpParameters=Zd,wo.length&&hs.state==="new"&&(!T&&!$d||S&&P!==0?wo.forEach(function(at){u(q.iceTransport,at)}):hs.setRemoteCandidates(wo)),S&&P!==0||(hs.state==="new"&&hs.start(qd,Yd,"controlling"),ql.state==="new"&&ql.start(Kd)),!a(q.localCapabilities,q.remoteCapabilities).codecs.filter(function(at){return at.name.toLowerCase()==="rtx"}).length&&q.sendEncodingParameters[0].rtx&&delete q.sendEncodingParameters[0].rtx,m._transceive(q,re==="sendrecv"||re==="recvonly",re==="sendrecv"||re==="sendonly"),!hn||re!=="sendrecv"&&re!=="sendonly"?delete q.rtpReceiver:(pn=hn.track,ue?(p[ue.stream]||(p[ue.stream]=new d.MediaStream),b(pn,p[ue.stream]),g.push([pn,hn,p[ue.stream]])):(p.default||(p.default=new d.MediaStream),b(pn,p.default),g.push([pn,hn,p.default]))));else{(q=m.transceivers[P]||m._createTransceiver(B)).mid=Qd,q.iceGatherer||(q.iceGatherer=m._createIceGatherer(P,S)),wo.length&&q.iceTransport.state==="new"&&(!$d||S&&P!==0?wo.forEach(function(at){u(q.iceTransport,at)}):q.iceTransport.setRemoteCandidates(wo)),ps=d.RTCRtpReceiver.getCapabilities(B),h<15019&&(ps.codecs=ps.codecs.filter(function(at){return at.name!=="rtx"})),Yl=q.sendEncodingParameters||[{ssrc:1001*(2*P+2)}];var Eo,Jl=!1;re==="sendrecv"||re==="sendonly"?(Jl=!q.rtpReceiver,hn=q.rtpReceiver||new d.RTCRtpReceiver(q.dtlsTransport,B),Jl&&(pn=hn.track,ue&&ue.stream==="-"||(ue?(p[ue.stream]||(p[ue.stream]=new d.MediaStream,Object.defineProperty(p[ue.stream],"id",{get:function(){return ue.stream}})),Object.defineProperty(pn,"id",{get:function(){return ue.track}}),Eo=p[ue.stream]):(p.default||(p.default=new d.MediaStream),Eo=p.default)),Eo&&(b(pn,Eo),q.associatedRemoteMediaStreams.push(Eo)),g.push([pn,hn,Eo]))):q.rtpReceiver&&q.rtpReceiver.track&&(q.associatedRemoteMediaStreams.forEach(function(at){var Zl,eh,th=at.getTracks().find(function(lm){return lm.id===q.rtpReceiver.track.id});th&&(Zl=th,(eh=at).removeTrack(Zl),eh.dispatchEvent(new d.MediaStreamTrackEvent("removetrack",{track:Zl})))}),q.associatedRemoteMediaStreams=[]),q.localCapabilities=ps,q.remoteCapabilities=Jd,q.rtpReceiver=hn,q.rtcpParameters=Zd,q.sendEncodingParameters=Yl,q.recvEncodingParameters=Kl,m._transceive(m.transceivers[P],!1,Jl)}}}),m._dtlsRole===void 0&&(m._dtlsRole=f.type==="offer"?"active":"passive"),m._remoteDescription={type:f.type,sdp:f.sdp},f.type==="offer"?m._updateSignalingState("have-remote-offer"):m._updateSignalingState("stable"),Object.keys(p).forEach(function(A){var P=p[A];if(P.getTracks().length){if(m.remoteStreams.indexOf(P)===-1){m.remoteStreams.push(P);var H=new Event("addstream");H.stream=P,d.setTimeout(function(){m._dispatchEvent("addstream",H)})}g.forEach(function(B){var N=B[0],W=B[1];P.id===B[2].id&&_(m,N,W,[P])})}}),g.forEach(function(A){A[2]||_(m,A[0],A[1],[])}),d.setTimeout(function(){m&&m.transceivers&&m.transceivers.forEach(function(A){A.iceTransport&&A.iceTransport.state==="new"&&A.iceTransport.getRemoteCandidates().length>0&&(console.warn("Timeout for addRemoteCandidate. Consider sending an end-of-candidates notification"),A.iceTransport.addRemoteCandidate({}))})},4e3),Promise.resolve()},v.prototype.close=function(){this.transceivers.forEach(function(f){f.iceTransport&&f.iceTransport.stop(),f.dtlsTransport&&f.dtlsTransport.stop(),f.rtpSender&&f.rtpSender.stop(),f.rtpReceiver&&f.rtpReceiver.stop()}),this._isClosed=!0,this._updateSignalingState("closed")},v.prototype._updateSignalingState=function(f){this.signalingState=f;var m=new Event("signalingstatechange");this._dispatchEvent("signalingstatechange",m)},v.prototype._maybeFireNegotiationNeeded=function(){var f=this;this.signalingState==="stable"&&this.needNegotiation!==!0&&(this.needNegotiation=!0,d.setTimeout(function(){if(f.needNegotiation){f.needNegotiation=!1;var m=new Event("negotiationneeded");f._dispatchEvent("negotiationneeded",m)}},0))},v.prototype._updateIceConnectionState=function(){var f,m={new:0,closed:0,checking:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(g){g.iceTransport&&!g.rejected&&m[g.iceTransport.state]++}),f="new",m.failed>0?f="failed":m.checking>0?f="checking":m.disconnected>0?f="disconnected":m.new>0?f="new":m.connected>0?f="connected":m.completed>0&&(f="completed"),f!==this.iceConnectionState){this.iceConnectionState=f;var p=new Event("iceconnectionstatechange");this._dispatchEvent("iceconnectionstatechange",p)}},v.prototype._updateConnectionState=function(){var f,m={new:0,closed:0,connecting:0,connected:0,completed:0,disconnected:0,failed:0};if(this.transceivers.forEach(function(g){g.iceTransport&&g.dtlsTransport&&!g.rejected&&(m[g.iceTransport.state]++,m[g.dtlsTransport.state]++)}),m.connected+=m.completed,f="new",m.failed>0?f="failed":m.connecting>0?f="connecting":m.disconnected>0?f="disconnected":m.new>0?f="new":m.connected>0&&(f="connected"),f!==this.connectionState){this.connectionState=f;var p=new Event("connectionstatechange");this._dispatchEvent("connectionstatechange",p)}},v.prototype.createOffer=function(){var f=this;if(f._isClosed)return Promise.reject(l("InvalidStateError","Can not call createOffer after close"));var m=f.transceivers.filter(function(T){return T.kind==="audio"}).length,p=f.transceivers.filter(function(T){return T.kind==="video"}).length,g=arguments[0];if(g){if(g.mandatory||g.optional)throw new TypeError("Legacy mandatory/optional constraints not supported.");g.offerToReceiveAudio!==void 0&&(m=g.offerToReceiveAudio===!0?1:g.offerToReceiveAudio===!1?0:g.offerToReceiveAudio),g.offerToReceiveVideo!==void 0&&(p=g.offerToReceiveVideo===!0?1:g.offerToReceiveVideo===!1?0:g.offerToReceiveVideo)}for(f.transceivers.forEach(function(T){T.kind==="audio"?--m<0&&(T.wantReceive=!1):T.kind==="video"&&--p<0&&(T.wantReceive=!1)});m>0||p>0;)m>0&&(f._createTransceiver("audio"),m--),p>0&&(f._createTransceiver("video"),p--);var w=i.writeSessionBoilerplate(f._sdpSessionId,f._sdpSessionVersion++);f.transceivers.forEach(function(T,S){var D=T.track,A=T.kind,P=T.mid||i.generateIdentifier();T.mid=P,T.iceGatherer||(T.iceGatherer=f._createIceGatherer(S,f.usingBundle));var H=d.RTCRtpSender.getCapabilities(A);h<15019&&(H.codecs=H.codecs.filter(function(N){return N.name!=="rtx"})),H.codecs.forEach(function(N){N.name==="H264"&&N.parameters["level-asymmetry-allowed"]===void 0&&(N.parameters["level-asymmetry-allowed"]="1"),T.remoteCapabilities&&T.remoteCapabilities.codecs&&T.remoteCapabilities.codecs.forEach(function(W){N.name.toLowerCase()===W.name.toLowerCase()&&N.clockRate===W.clockRate&&(N.preferredPayloadType=W.payloadType)})}),H.headerExtensions.forEach(function(N){(T.remoteCapabilities&&T.remoteCapabilities.headerExtensions||[]).forEach(function(W){N.uri===W.uri&&(N.id=W.id)})});var B=T.sendEncodingParameters||[{ssrc:1001*(2*S+1)}];D&&h>=15019&&A==="video"&&!B[0].rtx&&(B[0].rtx={ssrc:B[0].ssrc+1}),T.wantReceive&&(T.rtpReceiver=new d.RTCRtpReceiver(T.dtlsTransport,A)),T.localCapabilities=H,T.sendEncodingParameters=B}),f._config.bundlePolicy!=="max-compat"&&(w+="a=group:BUNDLE "+f.transceivers.map(function(T){return T.mid}).join(" ")+`\r
|
|
51
|
+
`),w+=`a=ice-options:trickle\r
|
|
52
|
+
`,f.transceivers.forEach(function(T,S){w+=r(T,T.localCapabilities,"offer",T.stream,f._dtlsRole),w+=`a=rtcp-rsize\r
|
|
53
|
+
`,!T.iceGatherer||f.iceGatheringState==="new"||S!==0&&f.usingBundle||(T.iceGatherer.getLocalCandidates().forEach(function(D){D.component=1,w+="a="+i.writeCandidate(D)+`\r
|
|
54
|
+
`}),T.iceGatherer.state==="completed"&&(w+=`a=end-of-candidates\r
|
|
55
|
+
`))});var C=new d.RTCSessionDescription({type:"offer",sdp:w});return Promise.resolve(C)},v.prototype.createAnswer=function(){var f=this;if(f._isClosed)return Promise.reject(l("InvalidStateError","Can not call createAnswer after close"));if(f.signalingState!=="have-remote-offer"&&f.signalingState!=="have-local-pranswer")return Promise.reject(l("InvalidStateError","Can not call createAnswer in signalingState "+f.signalingState));var m=i.writeSessionBoilerplate(f._sdpSessionId,f._sdpSessionVersion++);f.usingBundle&&(m+="a=group:BUNDLE "+f.transceivers.map(function(w){return w.mid}).join(" ")+`\r
|
|
56
56
|
`),m+=`a=ice-options:trickle\r
|
|
57
|
-
`;var p=i.getMediaSections(f._remoteDescription.sdp).length;f.transceivers.forEach(function(
|
|
58
|
-
`:m+="m=application 0 "+
|
|
59
|
-
`:
|
|
57
|
+
`;var p=i.getMediaSections(f._remoteDescription.sdp).length;f.transceivers.forEach(function(w,C){if(!(C+1>p)){if(w.rejected)return w.kind==="application"?w.protocol==="DTLS/SCTP"?m+=`m=application 0 DTLS/SCTP 5000\r
|
|
58
|
+
`:m+="m=application 0 "+w.protocol+` webrtc-datachannel\r
|
|
59
|
+
`:w.kind==="audio"?m+=`m=audio 0 UDP/TLS/RTP/SAVPF 0\r
|
|
60
60
|
a=rtpmap:0 PCMU/8000\r
|
|
61
|
-
`:
|
|
61
|
+
`:w.kind==="video"&&(m+=`m=video 0 UDP/TLS/RTP/SAVPF 120\r
|
|
62
62
|
a=rtpmap:120 VP8/90000\r
|
|
63
63
|
`),void(m+=`c=IN IP4 0.0.0.0\r
|
|
64
64
|
a=inactive\r
|
|
65
|
-
a=mid:`+
|
|
66
|
-
`);var T;
|
|
67
|
-
`)}});var g=new d.RTCSessionDescription({type:"answer",sdp:m});return Promise.resolve(g)},v.prototype.addIceCandidate=function(f){var m,p=this;return f&&f.sdpMLineIndex===void 0&&!f.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(g,
|
|
65
|
+
a=mid:`+w.mid+`\r
|
|
66
|
+
`);var T;w.stream&&(w.kind==="audio"?T=w.stream.getAudioTracks()[0]:w.kind==="video"&&(T=w.stream.getVideoTracks()[0]),T&&h>=15019&&w.kind==="video"&&!w.sendEncodingParameters[0].rtx&&(w.sendEncodingParameters[0].rtx={ssrc:w.sendEncodingParameters[0].ssrc+1}));var S=a(w.localCapabilities,w.remoteCapabilities);!S.codecs.filter(function(D){return D.name.toLowerCase()==="rtx"}).length&&w.sendEncodingParameters[0].rtx&&delete w.sendEncodingParameters[0].rtx,m+=r(w,S,"answer",w.stream,f._dtlsRole),w.rtcpParameters&&w.rtcpParameters.reducedSize&&(m+=`a=rtcp-rsize\r
|
|
67
|
+
`)}});var g=new d.RTCSessionDescription({type:"answer",sdp:m});return Promise.resolve(g)},v.prototype.addIceCandidate=function(f){var m,p=this;return f&&f.sdpMLineIndex===void 0&&!f.sdpMid?Promise.reject(new TypeError("sdpMLineIndex or sdpMid required")):new Promise(function(g,w){if(!p._remoteDescription)return w(l("InvalidStateError","Can not add ICE candidate without a remote description"));if(f&&f.candidate!==""){var C=f.sdpMLineIndex;if(f.sdpMid){for(var T=0;T<p.transceivers.length;T++)if(p.transceivers[T].mid===f.sdpMid){C=T;break}}var S=p.transceivers[C];if(!S)return w(l("OperationError","Can not add ICE candidate"));if(S.rejected)return g();var D=Object.keys(f.candidate).length>0?i.parseCandidate(f.candidate):{};if(D.protocol==="tcp"&&(D.port===0||D.port===9)||D.component&&D.component!==1)return g();if((C===0||C>0&&S.iceTransport!==p.transceivers[0].iceTransport)&&!u(S.iceTransport,D))return w(l("OperationError","Can not add ICE candidate"));var A=f.candidate.trim();A.indexOf("a=")===0&&(A=A.substr(2)),(m=i.getMediaSections(p._remoteDescription.sdp))[C]+="a="+(D.type?A:"end-of-candidates")+`\r
|
|
68
68
|
`,p._remoteDescription.sdp=i.getDescription(p._remoteDescription.sdp)+m.join("")}else for(var P=0;P<p.transceivers.length&&(p.transceivers[P].rejected||(p.transceivers[P].iceTransport.addRemoteCandidate({}),(m=i.getMediaSections(p._remoteDescription.sdp))[P]+=`a=end-of-candidates\r
|
|
69
|
-
`,p._remoteDescription.sdp=i.getDescription(p._remoteDescription.sdp)+m.join(""),!p.usingBundle));P++);g()})},v.prototype.getStats=function(f){if(f&&f instanceof d.MediaStreamTrack){var m=null;if(this.transceivers.forEach(function(g){g.rtpSender&&g.rtpSender.track===f?m=g.rtpSender:g.rtpReceiver&&g.rtpReceiver.track===f&&(m=g.rtpReceiver)}),!m)throw l("InvalidAccessError","Invalid selector.");return m.getStats()}var p=[];return this.transceivers.forEach(function(g){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(x){g[x]&&p.push(g[x].getStats())})}),Promise.all(p).then(function(g){var x=new Map;return g.forEach(function(C){C.forEach(function(T){x.set(T.id,T)})}),x})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(f){var m=d[f];if(m&&m.prototype&&m.prototype.getStats){var p=m.prototype.getStats;m.prototype.getStats=function(){return p.apply(this).then(function(g){var x=new Map;return Object.keys(g).forEach(function(C){g[C].type=n(g[C]),x.set(C,g[C])}),x})}}});var y=["createOffer","createAnswer"];return y.forEach(function(f){var m=v.prototype[f];v.prototype[f]=function(){var p=arguments;return typeof p[0]=="function"||typeof p[1]=="function"?m.apply(this,[arguments[2]]).then(function(g){typeof p[0]=="function"&&p[0].apply(null,[g])},function(g){typeof p[1]=="function"&&p[1].apply(null,[g])}):m.apply(this,arguments)}}),(y=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(f){var m=v.prototype[f];v.prototype[f]=function(){var p=arguments;return typeof p[1]=="function"||typeof p[2]=="function"?m.apply(this,arguments).then(function(){typeof p[1]=="function"&&p[1].apply(null)},function(g){typeof p[2]=="function"&&p[2].apply(null,[g])}):m.apply(this,arguments)}}),["getStats"].forEach(function(f){var m=v.prototype[f];v.prototype[f]=function(){var p=arguments;return typeof p[1]=="function"?m.apply(this,arguments).then(function(){typeof p[1]=="function"&&p[1].apply(null)}):m.apply(this,arguments)}}),v}},{sdp:"YHvh"}],YdKx:[function(o,e,t){"use strict";function i(n){var r=n&&n.navigator,s=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(a){return s(a).catch(function(c){return Promise.reject(function(u){return{name:{PermissionDeniedError:"NotAllowedError"}[u.name]||u.name,message:u.message,constraint:u.constraint,toString:function(){return this.name}}}(c))})}}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=i},{}],P3bV:[function(o,e,t){"use strict";function i(n){"getDisplayMedia"in n.navigator&&n.navigator.mediaDevices&&(n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||(n.navigator.mediaDevices.getDisplayMedia=n.navigator.getDisplayMedia.bind(n.navigator)))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],XRic:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimPeerConnection=d,t.shimReplaceTrack=h,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return s.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return a.shimGetDisplayMedia}});var i=l(o("../utils")),n=o("./filtericeservers"),r=c(o("rtcpeerconnection-shim")),s=o("./getusermedia"),a=o("./getdisplaymedia");function c(b){return b&&b.__esModule?b:{default:b}}function u(){if(typeof WeakMap!="function")return null;var b=new WeakMap;return u=function(){return b},b}function l(b){if(b&&b.__esModule)return b;if(b===null||typeof b!="object"&&typeof b!="function")return{default:b};var _=u();if(_&&_.has(b))return _.get(b);var v={},y=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var f in b)if(Object.prototype.hasOwnProperty.call(b,f)){var m=y?Object.getOwnPropertyDescriptor(b,f):null;m&&(m.get||m.set)?Object.defineProperty(v,f,m):v[f]=b[f]}return v.default=b,_&&_.set(b,v),v}function d(b,_){if(b.RTCIceGatherer&&(b.RTCIceCandidate||(b.RTCIceCandidate=function(f){return f}),b.RTCSessionDescription||(b.RTCSessionDescription=function(f){return f}),_.version<15025)){var v=Object.getOwnPropertyDescriptor(b.MediaStreamTrack.prototype,"enabled");Object.defineProperty(b.MediaStreamTrack.prototype,"enabled",{set:function(f){v.set.call(this,f);var m=new Event("enabled");m.enabled=f,this.dispatchEvent(m)}})}!b.RTCRtpSender||"dtmf"in b.RTCRtpSender.prototype||Object.defineProperty(b.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new b.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),b.RTCDtmfSender&&!b.RTCDTMFSender&&(b.RTCDTMFSender=b.RTCDtmfSender);var y=(0,r.default)(b,_.version);b.RTCPeerConnection=function(f){return f&&f.iceServers&&(f.iceServers=(0,n.filterIceServers)(f.iceServers,_.version),i.log("ICE servers after filtering:",f.iceServers)),new y(f)},b.RTCPeerConnection.prototype=y.prototype}function h(b){!b.RTCRtpSender||"replaceTrack"in b.RTCRtpSender.prototype||(b.RTCRtpSender.prototype.replaceTrack=b.RTCRtpSender.prototype.setTrack)}},{"../utils":"iSxC","./filtericeservers":"NZ1C","rtcpeerconnection-shim":"NJ2u","./getusermedia":"YdKx","./getdisplaymedia":"P3bV"}],GzSv:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=a;var i=r(o("../utils"));function n(){if(typeof WeakMap!="function")return null;var c=new WeakMap;return n=function(){return c},c}function r(c){if(c&&c.__esModule)return c;if(c===null||typeof c!="object"&&typeof c!="function")return{default:c};var u=n();if(u&&u.has(c))return u.get(c);var l={},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in c)if(Object.prototype.hasOwnProperty.call(c,h)){var b=d?Object.getOwnPropertyDescriptor(c,h):null;b&&(b.get||b.set)?Object.defineProperty(l,h,b):l[h]=c[h]}return l.default=c,u&&u.set(c,l),l}function s(c){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(u){return typeof u}:function(u){return u&&typeof Symbol=="function"&&u.constructor===Symbol&&u!==Symbol.prototype?"symbol":typeof u})(c)}function a(c,u){var l=c&&c.navigator,d=c&&c.MediaStreamTrack;if(l.getUserMedia=function(y,f,m){i.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),l.mediaDevices.getUserMedia(y).then(f,m)},!(u.version>55&&"autoGainControl"in l.mediaDevices.getSupportedConstraints())){var h=function(y,f,m){f in y&&!(m in y)&&(y[m]=y[f],delete y[f])},b=l.mediaDevices.getUserMedia.bind(l.mediaDevices);if(l.mediaDevices.getUserMedia=function(y){return s(y)==="object"&&s(y.audio)==="object"&&(y=JSON.parse(JSON.stringify(y)),h(y.audio,"autoGainControl","mozAutoGainControl"),h(y.audio,"noiseSuppression","mozNoiseSuppression")),b(y)},d&&d.prototype.getSettings){var _=d.prototype.getSettings;d.prototype.getSettings=function(){var y=_.apply(this,arguments);return h(y,"mozAutoGainControl","autoGainControl"),h(y,"mozNoiseSuppression","noiseSuppression"),y}}if(d&&d.prototype.applyConstraints){var v=d.prototype.applyConstraints;d.prototype.applyConstraints=function(y){return this.kind==="audio"&&s(y)==="object"&&(y=JSON.parse(JSON.stringify(y)),h(y,"autoGainControl","mozAutoGainControl"),h(y,"noiseSuppression","mozNoiseSuppression")),v.apply(this,[y])}}}}},{"../utils":"iSxC"}],UuGU:[function(o,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(s){if(!s||!s.video){var a=new DOMException("getDisplayMedia without video constraints is undefined");return a.name="NotFoundError",a.code=8,Promise.reject(a)}return s.video===!0?s.video={mediaSource:r}:s.video.mediaSource=r,n.navigator.mediaDevices.getUserMedia(s)})}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],Fzdr:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimOnTrack=l,t.shimPeerConnection=d,t.shimSenderGetStats=h,t.shimReceiverGetStats=b,t.shimRemoveStream=_,t.shimRTCDataChannel=v,t.shimAddTransceiver=y,t.shimGetParameters=f,t.shimCreateOffer=m,t.shimCreateAnswer=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=a(o("../utils")),n=o("./getusermedia"),r=o("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var g=new WeakMap;return s=function(){return g},g}function a(g){if(g&&g.__esModule)return g;if(g===null||typeof g!="object"&&typeof g!="function")return{default:g};var x=s();if(x&&x.has(g))return x.get(g);var C={},T=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var S in g)if(Object.prototype.hasOwnProperty.call(g,S)){var D=T?Object.getOwnPropertyDescriptor(g,S):null;D&&(D.get||D.set)?Object.defineProperty(C,S,D):C[S]=g[S]}return C.default=g,x&&x.set(g,C),C}function c(g,x,C){return x in g?Object.defineProperty(g,x,{value:C,enumerable:!0,configurable:!0,writable:!0}):g[x]=C,g}function u(g){return(u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(x){return typeof x}:function(x){return x&&typeof Symbol=="function"&&x.constructor===Symbol&&x!==Symbol.prototype?"symbol":typeof x})(g)}function l(g){u(g)==="object"&&g.RTCTrackEvent&&"receiver"in g.RTCTrackEvent.prototype&&!("transceiver"in g.RTCTrackEvent.prototype)&&Object.defineProperty(g.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function d(g,x){if(u(g)==="object"&&(g.RTCPeerConnection||g.mozRTCPeerConnection)){!g.RTCPeerConnection&&g.mozRTCPeerConnection&&(g.RTCPeerConnection=g.mozRTCPeerConnection),x.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(S){var D=g.RTCPeerConnection.prototype[S],A=c({},S,function(){return arguments[0]=new(S==="addIceCandidate"?g.RTCIceCandidate:g.RTCSessionDescription)(arguments[0]),D.apply(this,arguments)});g.RTCPeerConnection.prototype[S]=A[S]});var C={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},T=g.RTCPeerConnection.prototype.getStats;g.RTCPeerConnection.prototype.getStats=function(){var[S,D,A]=arguments;return T.apply(this,[S||null]).then(function(P){if(x.version<53&&!D)try{P.forEach(function(H){H.type=C[H.type]||H.type})}catch(H){if(H.name!=="TypeError")throw H;P.forEach(function(B,N){P.set(N,Object.assign({},B,{type:C[B.type]||B.type}))})}return P}).then(D,A)}}}function h(g){if(u(g)==="object"&&g.RTCPeerConnection&&g.RTCRtpSender&&!(g.RTCRtpSender&&"getStats"in g.RTCRtpSender.prototype)){var x=g.RTCPeerConnection.prototype.getSenders;x&&(g.RTCPeerConnection.prototype.getSenders=function(){var T=this,S=x.apply(this,[]);return S.forEach(function(D){return D._pc=T}),S});var C=g.RTCPeerConnection.prototype.addTrack;C&&(g.RTCPeerConnection.prototype.addTrack=function(){var T=C.apply(this,arguments);return T._pc=this,T}),g.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function b(g){if(u(g)==="object"&&g.RTCPeerConnection&&g.RTCRtpSender&&!(g.RTCRtpSender&&"getStats"in g.RTCRtpReceiver.prototype)){var x=g.RTCPeerConnection.prototype.getReceivers;x&&(g.RTCPeerConnection.prototype.getReceivers=function(){var C=this,T=x.apply(this,[]);return T.forEach(function(S){return S._pc=C}),T}),i.wrapPeerConnectionEvent(g,"track",function(C){return C.receiver._pc=C.srcElement,C}),g.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function _(g){!g.RTCPeerConnection||"removeStream"in g.RTCPeerConnection.prototype||(g.RTCPeerConnection.prototype.removeStream=function(x){var C=this;i.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(T){T.track&&x.getTracks().includes(T.track)&&C.removeTrack(T)})})}function v(g){g.DataChannel&&!g.RTCDataChannel&&(g.RTCDataChannel=g.DataChannel)}function y(g){if(u(g)==="object"&&g.RTCPeerConnection){var x=g.RTCPeerConnection.prototype.addTransceiver;x&&(g.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var C=arguments[1],T=C&&"sendEncodings"in C;T&&C.sendEncodings.forEach(function(P){if("rid"in P&&!/^[a-z0-9]{0,16}$/i.test(P.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in P&&!(parseFloat(P.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in P&&!(parseFloat(P.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var S=x.apply(this,arguments);if(T){var{sender:D}=S,A=D.getParameters();"encodings"in A&&(A.encodings.length!==1||Object.keys(A.encodings[0]).length!==0)||(A.encodings=C.sendEncodings,D.sendEncodings=C.sendEncodings,this.setParametersPromises.push(D.setParameters(A).then(function(){delete D.sendEncodings}).catch(function(){delete D.sendEncodings})))}return S})}}function f(g){if(u(g)==="object"&&g.RTCRtpSender){var x=g.RTCRtpSender.prototype.getParameters;x&&(g.RTCRtpSender.prototype.getParameters=function(){var C=x.apply(this,arguments);return"encodings"in C||(C.encodings=[].concat(this.sendEncodings||[{}])),C})}}function m(g){if(u(g)==="object"&&g.RTCPeerConnection){var x=g.RTCPeerConnection.prototype.createOffer;g.RTCPeerConnection.prototype.createOffer=function(){var C=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return x.apply(T,C)}).finally(function(){T.setParametersPromises=[]}):x.apply(this,arguments)}}}function p(g){if(u(g)==="object"&&g.RTCPeerConnection){var x=g.RTCPeerConnection.prototype.createAnswer;g.RTCPeerConnection.prototype.createAnswer=function(){var C=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return x.apply(T,C)}).finally(function(){T.setParametersPromises=[]}):x.apply(this,arguments)}}}},{"../utils":"iSxC","./getusermedia":"GzSv","./getdisplaymedia":"UuGU"}],t1lL:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimLocalStreamsAPI=a,t.shimRemoteStreamsAPI=c,t.shimCallbacksAPI=u,t.shimGetUserMedia=l,t.shimConstraints=d,t.shimRTCIceServerUrls=h,t.shimTrackEventTransceiver=b,t.shimCreateOfferLegacy=_,t.shimAudioContext=v;var i=r(o("../utils"));function n(){if(typeof WeakMap!="function")return null;var y=new WeakMap;return n=function(){return y},y}function r(y){if(y&&y.__esModule)return y;if(y===null||typeof y!="object"&&typeof y!="function")return{default:y};var f=n();if(f&&f.has(y))return f.get(y);var m={},p=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in y)if(Object.prototype.hasOwnProperty.call(y,g)){var x=p?Object.getOwnPropertyDescriptor(y,g):null;x&&(x.get||x.set)?Object.defineProperty(m,g,x):m[g]=y[g]}return m.default=y,f&&f.set(y,m),m}function s(y){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(f){return typeof f}:function(f){return f&&typeof Symbol=="function"&&f.constructor===Symbol&&f!==Symbol.prototype?"symbol":typeof f})(y)}function a(y){if(s(y)==="object"&&y.RTCPeerConnection){if("getLocalStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in y.RTCPeerConnection.prototype)){var f=y.RTCPeerConnection.prototype.addTrack;y.RTCPeerConnection.prototype.addStream=function(m){var p=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(m)||this._localStreams.push(m),m.getAudioTracks().forEach(function(g){return f.call(p,g,m)}),m.getVideoTracks().forEach(function(g){return f.call(p,g,m)})},y.RTCPeerConnection.prototype.addTrack=function(m){for(var p=this,g=arguments.length,x=new Array(g>1?g-1:0),C=1;C<g;C++)x[C-1]=arguments[C];return x&&x.forEach(function(T){p._localStreams?p._localStreams.includes(T)||p._localStreams.push(T):p._localStreams=[T]}),f.apply(this,arguments)}}"removeStream"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.removeStream=function(m){var p=this;this._localStreams||(this._localStreams=[]);var g=this._localStreams.indexOf(m);if(g!==-1){this._localStreams.splice(g,1);var x=m.getTracks();this.getSenders().forEach(function(C){x.includes(C.track)&&p.removeTrack(C)})}})}}function c(y){if(s(y)==="object"&&y.RTCPeerConnection&&("getRemoteStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in y.RTCPeerConnection.prototype))){Object.defineProperty(y.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(m){var p=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=m),this.addEventListener("track",this._onaddstreampoly=function(g){g.streams.forEach(function(x){if(p._remoteStreams||(p._remoteStreams=[]),!p._remoteStreams.includes(x)){p._remoteStreams.push(x);var C=new Event("addstream");C.stream=x,p.dispatchEvent(C)}})})}});var f=y.RTCPeerConnection.prototype.setRemoteDescription;y.RTCPeerConnection.prototype.setRemoteDescription=function(){var m=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(p){p.streams.forEach(function(g){if(m._remoteStreams||(m._remoteStreams=[]),!(m._remoteStreams.indexOf(g)>=0)){m._remoteStreams.push(g);var x=new Event("addstream");x.stream=g,m.dispatchEvent(x)}})}),f.apply(m,arguments)}}}function u(y){if(s(y)==="object"&&y.RTCPeerConnection){var f=y.RTCPeerConnection.prototype,m=f.createOffer,p=f.createAnswer,g=f.setLocalDescription,x=f.setRemoteDescription,C=f.addIceCandidate;f.createOffer=function(S,D){var A=arguments.length>=2?arguments[2]:arguments[0],P=m.apply(this,[A]);return D?(P.then(S,D),Promise.resolve()):P},f.createAnswer=function(S,D){var A=arguments.length>=2?arguments[2]:arguments[0],P=p.apply(this,[A]);return D?(P.then(S,D),Promise.resolve()):P};var T=function(S,D,A){var P=g.apply(this,[S]);return A?(P.then(D,A),Promise.resolve()):P};f.setLocalDescription=T,T=function(S,D,A){var P=x.apply(this,[S]);return A?(P.then(D,A),Promise.resolve()):P},f.setRemoteDescription=T,T=function(S,D,A){var P=C.apply(this,[S]);return A?(P.then(D,A),Promise.resolve()):P},f.addIceCandidate=T}}function l(y){var f=y&&y.navigator;if(f.mediaDevices&&f.mediaDevices.getUserMedia){var m=f.mediaDevices,p=m.getUserMedia.bind(m);f.mediaDevices.getUserMedia=function(g){return p(d(g))}}!f.getUserMedia&&f.mediaDevices&&f.mediaDevices.getUserMedia&&(f.getUserMedia=function(g,x,C){f.mediaDevices.getUserMedia(g).then(x,C)}.bind(f))}function d(y){return y&&y.video!==void 0?Object.assign({},y,{video:i.compactObject(y.video)}):y}function h(y){if(y.RTCPeerConnection){var f=y.RTCPeerConnection;y.RTCPeerConnection=function(m,p){if(m&&m.iceServers){for(var g=[],x=0;x<m.iceServers.length;x++){var C=m.iceServers[x];!C.hasOwnProperty("urls")&&C.hasOwnProperty("url")?(i.deprecated("RTCIceServer.url","RTCIceServer.urls"),(C=JSON.parse(JSON.stringify(C))).urls=C.url,delete C.url,g.push(C)):g.push(m.iceServers[x])}m.iceServers=g}return new f(m,p)},y.RTCPeerConnection.prototype=f.prototype,"generateCertificate"in f&&Object.defineProperty(y.RTCPeerConnection,"generateCertificate",{get:function(){return f.generateCertificate}})}}function b(y){s(y)==="object"&&y.RTCTrackEvent&&"receiver"in y.RTCTrackEvent.prototype&&!("transceiver"in y.RTCTrackEvent.prototype)&&Object.defineProperty(y.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function _(y){var f=y.RTCPeerConnection.prototype.createOffer;y.RTCPeerConnection.prototype.createOffer=function(m){if(m){m.offerToReceiveAudio!==void 0&&(m.offerToReceiveAudio=!!m.offerToReceiveAudio);var p=this.getTransceivers().find(function(x){return x.receiver.track.kind==="audio"});m.offerToReceiveAudio===!1&&p?p.direction==="sendrecv"?p.setDirection?p.setDirection("sendonly"):p.direction="sendonly":p.direction==="recvonly"&&(p.setDirection?p.setDirection("inactive"):p.direction="inactive"):m.offerToReceiveAudio!==!0||p||this.addTransceiver("audio"),m.offerToReceiveVideo!==void 0&&(m.offerToReceiveVideo=!!m.offerToReceiveVideo);var g=this.getTransceivers().find(function(x){return x.receiver.track.kind==="video"});m.offerToReceiveVideo===!1&&g?g.direction==="sendrecv"?g.setDirection?g.setDirection("sendonly"):g.direction="sendonly":g.direction==="recvonly"&&(g.setDirection?g.setDirection("inactive"):g.direction="inactive"):m.offerToReceiveVideo!==!0||g||this.addTransceiver("video")}return f.apply(this,arguments)}}function v(y){s(y)!=="object"||y.AudioContext||(y.AudioContext=y.webkitAudioContext)}},{"../utils":"iSxC"}],GOQK:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimRTCIceCandidate=u,t.shimMaxMessageSize=l,t.shimSendThrowTypeError=d,t.shimConnectionState=h,t.removeExtmapAllowMixed=b,t.shimAddIceCandidateNullOrEmpty=_;var i=a(o("sdp")),n=s(o("./utils"));function r(){if(typeof WeakMap!="function")return null;var v=new WeakMap;return r=function(){return v},v}function s(v){if(v&&v.__esModule)return v;if(v===null||typeof v!="object"&&typeof v!="function")return{default:v};var y=r();if(y&&y.has(v))return y.get(v);var f={},m=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var p in v)if(Object.prototype.hasOwnProperty.call(v,p)){var g=m?Object.getOwnPropertyDescriptor(v,p):null;g&&(g.get||g.set)?Object.defineProperty(f,p,g):f[p]=v[p]}return f.default=v,y&&y.set(v,f),f}function a(v){return v&&v.__esModule?v:{default:v}}function c(v){return(c=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(y){return typeof y}:function(y){return y&&typeof Symbol=="function"&&y.constructor===Symbol&&y!==Symbol.prototype?"symbol":typeof y})(v)}function u(v){if(v.RTCIceCandidate&&!(v.RTCIceCandidate&&"foundation"in v.RTCIceCandidate.prototype)){var y=v.RTCIceCandidate;v.RTCIceCandidate=function(f){if(c(f)==="object"&&f.candidate&&f.candidate.indexOf("a=")===0&&((f=JSON.parse(JSON.stringify(f))).candidate=f.candidate.substr(2)),f.candidate&&f.candidate.length){var m=new y(f),p=i.default.parseCandidate(f.candidate),g=Object.assign(m,p);return g.toJSON=function(){return{candidate:g.candidate,sdpMid:g.sdpMid,sdpMLineIndex:g.sdpMLineIndex,usernameFragment:g.usernameFragment}},g}return new y(f)},v.RTCIceCandidate.prototype=y.prototype,n.wrapPeerConnectionEvent(v,"icecandidate",function(f){return f.candidate&&Object.defineProperty(f,"candidate",{value:new v.RTCIceCandidate(f.candidate),writable:"false"}),f})}}function l(v,y){if(v.RTCPeerConnection){"sctp"in v.RTCPeerConnection.prototype||Object.defineProperty(v.RTCPeerConnection.prototype,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp}});var f=v.RTCPeerConnection.prototype.setRemoteDescription;v.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,y.browser==="chrome"&&y.version>=76){var{sdpSemantics:m}=this.getConfiguration();m==="plan-b"&&Object.defineProperty(this,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(A){if(!A||!A.sdp)return!1;var P=i.default.splitSections(A.sdp);return P.shift(),P.some(function(H){var B=i.default.parseMLine(H);return B&&B.kind==="application"&&B.protocol.indexOf("SCTP")!==-1})}(arguments[0])){var p,g=function(A){var P=A.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(P===null||P.length<2)return-1;var H=parseInt(P[1],10);return H!=H?-1:H}(arguments[0]),x=(S=g,D=65536,y.browser==="firefox"&&(D=y.version<57?S===-1?16384:2147483637:y.version<60?y.version===57?65535:65536:2147483637),D),C=function(A,P){var H=65536;y.browser==="firefox"&&y.version===57&&(H=65535);var B=i.default.matchPrefix(A.sdp,"a=max-message-size:");return B.length>0?H=parseInt(B[0].substr(19),10):y.browser==="firefox"&&P!==-1&&(H=2147483637),H}(arguments[0],g);p=x===0&&C===0?Number.POSITIVE_INFINITY:x===0||C===0?Math.max(x,C):Math.min(x,C);var T={};Object.defineProperty(T,"maxMessageSize",{get:function(){return p}}),this._sctp=T}var S,D;return f.apply(this,arguments)}}}function d(v){if(v.RTCPeerConnection&&"createDataChannel"in v.RTCPeerConnection.prototype){var y=v.RTCPeerConnection.prototype.createDataChannel;v.RTCPeerConnection.prototype.createDataChannel=function(){var m=y.apply(this,arguments);return f(m,this),m},n.wrapPeerConnectionEvent(v,"datachannel",function(m){return f(m.channel,m.target),m})}function f(m,p){var g=m.send;m.send=function(){var x=arguments[0],C=x.length||x.size||x.byteLength;if(m.readyState==="open"&&p.sctp&&C>p.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+p.sctp.maxMessageSize+" bytes)");return g.apply(m,arguments)}}}function h(v){if(v.RTCPeerConnection&&!("connectionState"in v.RTCPeerConnection.prototype)){var y=v.RTCPeerConnection.prototype;Object.defineProperty(y,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(y,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(f){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),f&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=f)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(f){var m=y[f];y[f]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(p){var g=p.target;if(g._lastConnectionState!==g.connectionState){g._lastConnectionState=g.connectionState;var x=new Event("connectionstatechange",p);g.dispatchEvent(x)}return p},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),m.apply(this,arguments)}})}}function b(v,y){if(v.RTCPeerConnection&&!(y.browser==="chrome"&&y.version>=71||y.browser==="safari"&&y.version>=605)){var f=v.RTCPeerConnection.prototype.setRemoteDescription;v.RTCPeerConnection.prototype.setRemoteDescription=function(m){if(m&&m.sdp&&m.sdp.indexOf(`
|
|
69
|
+
`,p._remoteDescription.sdp=i.getDescription(p._remoteDescription.sdp)+m.join(""),!p.usingBundle));P++);g()})},v.prototype.getStats=function(f){if(f&&f instanceof d.MediaStreamTrack){var m=null;if(this.transceivers.forEach(function(g){g.rtpSender&&g.rtpSender.track===f?m=g.rtpSender:g.rtpReceiver&&g.rtpReceiver.track===f&&(m=g.rtpReceiver)}),!m)throw l("InvalidAccessError","Invalid selector.");return m.getStats()}var p=[];return this.transceivers.forEach(function(g){["rtpSender","rtpReceiver","iceGatherer","iceTransport","dtlsTransport"].forEach(function(w){g[w]&&p.push(g[w].getStats())})}),Promise.all(p).then(function(g){var w=new Map;return g.forEach(function(C){C.forEach(function(T){w.set(T.id,T)})}),w})},["RTCRtpSender","RTCRtpReceiver","RTCIceGatherer","RTCIceTransport","RTCDtlsTransport"].forEach(function(f){var m=d[f];if(m&&m.prototype&&m.prototype.getStats){var p=m.prototype.getStats;m.prototype.getStats=function(){return p.apply(this).then(function(g){var w=new Map;return Object.keys(g).forEach(function(C){g[C].type=n(g[C]),w.set(C,g[C])}),w})}}});var y=["createOffer","createAnswer"];return y.forEach(function(f){var m=v.prototype[f];v.prototype[f]=function(){var p=arguments;return typeof p[0]=="function"||typeof p[1]=="function"?m.apply(this,[arguments[2]]).then(function(g){typeof p[0]=="function"&&p[0].apply(null,[g])},function(g){typeof p[1]=="function"&&p[1].apply(null,[g])}):m.apply(this,arguments)}}),(y=["setLocalDescription","setRemoteDescription","addIceCandidate"]).forEach(function(f){var m=v.prototype[f];v.prototype[f]=function(){var p=arguments;return typeof p[1]=="function"||typeof p[2]=="function"?m.apply(this,arguments).then(function(){typeof p[1]=="function"&&p[1].apply(null)},function(g){typeof p[2]=="function"&&p[2].apply(null,[g])}):m.apply(this,arguments)}}),["getStats"].forEach(function(f){var m=v.prototype[f];v.prototype[f]=function(){var p=arguments;return typeof p[1]=="function"?m.apply(this,arguments).then(function(){typeof p[1]=="function"&&p[1].apply(null)}):m.apply(this,arguments)}}),v}},{sdp:"YHvh"}],YdKx:[function(o,e,t){"use strict";function i(n){var r=n&&n.navigator,s=r.mediaDevices.getUserMedia.bind(r.mediaDevices);r.mediaDevices.getUserMedia=function(a){return s(a).catch(function(c){return Promise.reject(function(u){return{name:{PermissionDeniedError:"NotAllowedError"}[u.name]||u.name,message:u.message,constraint:u.constraint,toString:function(){return this.name}}}(c))})}}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=i},{}],P3bV:[function(o,e,t){"use strict";function i(n){"getDisplayMedia"in n.navigator&&n.navigator.mediaDevices&&(n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||(n.navigator.mediaDevices.getDisplayMedia=n.navigator.getDisplayMedia.bind(n.navigator)))}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],XRic:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimPeerConnection=d,t.shimReplaceTrack=h,Object.defineProperty(t,"shimGetUserMedia",{enumerable:!0,get:function(){return s.shimGetUserMedia}}),Object.defineProperty(t,"shimGetDisplayMedia",{enumerable:!0,get:function(){return a.shimGetDisplayMedia}});var i=l(o("../utils")),n=o("./filtericeservers"),r=c(o("rtcpeerconnection-shim")),s=o("./getusermedia"),a=o("./getdisplaymedia");function c(b){return b&&b.__esModule?b:{default:b}}function u(){if(typeof WeakMap!="function")return null;var b=new WeakMap;return u=function(){return b},b}function l(b){if(b&&b.__esModule)return b;if(b===null||typeof b!="object"&&typeof b!="function")return{default:b};var _=u();if(_&&_.has(b))return _.get(b);var v={},y=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var f in b)if(Object.prototype.hasOwnProperty.call(b,f)){var m=y?Object.getOwnPropertyDescriptor(b,f):null;m&&(m.get||m.set)?Object.defineProperty(v,f,m):v[f]=b[f]}return v.default=b,_&&_.set(b,v),v}function d(b,_){if(b.RTCIceGatherer&&(b.RTCIceCandidate||(b.RTCIceCandidate=function(f){return f}),b.RTCSessionDescription||(b.RTCSessionDescription=function(f){return f}),_.version<15025)){var v=Object.getOwnPropertyDescriptor(b.MediaStreamTrack.prototype,"enabled");Object.defineProperty(b.MediaStreamTrack.prototype,"enabled",{set:function(f){v.set.call(this,f);var m=new Event("enabled");m.enabled=f,this.dispatchEvent(m)}})}!b.RTCRtpSender||"dtmf"in b.RTCRtpSender.prototype||Object.defineProperty(b.RTCRtpSender.prototype,"dtmf",{get:function(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=new b.RTCDtmfSender(this):this.track.kind==="video"&&(this._dtmf=null)),this._dtmf}}),b.RTCDtmfSender&&!b.RTCDTMFSender&&(b.RTCDTMFSender=b.RTCDtmfSender);var y=(0,r.default)(b,_.version);b.RTCPeerConnection=function(f){return f&&f.iceServers&&(f.iceServers=(0,n.filterIceServers)(f.iceServers,_.version),i.log("ICE servers after filtering:",f.iceServers)),new y(f)},b.RTCPeerConnection.prototype=y.prototype}function h(b){!b.RTCRtpSender||"replaceTrack"in b.RTCRtpSender.prototype||(b.RTCRtpSender.prototype.replaceTrack=b.RTCRtpSender.prototype.setTrack)}},{"../utils":"iSxC","./filtericeservers":"NZ1C","rtcpeerconnection-shim":"NJ2u","./getusermedia":"YdKx","./getdisplaymedia":"P3bV"}],GzSv:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetUserMedia=a;var i=r(o("../utils"));function n(){if(typeof WeakMap!="function")return null;var c=new WeakMap;return n=function(){return c},c}function r(c){if(c&&c.__esModule)return c;if(c===null||typeof c!="object"&&typeof c!="function")return{default:c};var u=n();if(u&&u.has(c))return u.get(c);var l={},d=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var h in c)if(Object.prototype.hasOwnProperty.call(c,h)){var b=d?Object.getOwnPropertyDescriptor(c,h):null;b&&(b.get||b.set)?Object.defineProperty(l,h,b):l[h]=c[h]}return l.default=c,u&&u.set(c,l),l}function s(c){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(u){return typeof u}:function(u){return u&&typeof Symbol=="function"&&u.constructor===Symbol&&u!==Symbol.prototype?"symbol":typeof u})(c)}function a(c,u){var l=c&&c.navigator,d=c&&c.MediaStreamTrack;if(l.getUserMedia=function(y,f,m){i.deprecated("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),l.mediaDevices.getUserMedia(y).then(f,m)},!(u.version>55&&"autoGainControl"in l.mediaDevices.getSupportedConstraints())){var h=function(y,f,m){f in y&&!(m in y)&&(y[m]=y[f],delete y[f])},b=l.mediaDevices.getUserMedia.bind(l.mediaDevices);if(l.mediaDevices.getUserMedia=function(y){return s(y)==="object"&&s(y.audio)==="object"&&(y=JSON.parse(JSON.stringify(y)),h(y.audio,"autoGainControl","mozAutoGainControl"),h(y.audio,"noiseSuppression","mozNoiseSuppression")),b(y)},d&&d.prototype.getSettings){var _=d.prototype.getSettings;d.prototype.getSettings=function(){var y=_.apply(this,arguments);return h(y,"mozAutoGainControl","autoGainControl"),h(y,"mozNoiseSuppression","noiseSuppression"),y}}if(d&&d.prototype.applyConstraints){var v=d.prototype.applyConstraints;d.prototype.applyConstraints=function(y){return this.kind==="audio"&&s(y)==="object"&&(y=JSON.parse(JSON.stringify(y)),h(y,"autoGainControl","mozAutoGainControl"),h(y,"noiseSuppression","mozNoiseSuppression")),v.apply(this,[y])}}}}},{"../utils":"iSxC"}],UuGU:[function(o,e,t){"use strict";function i(n,r){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(s){if(!s||!s.video){var a=new DOMException("getDisplayMedia without video constraints is undefined");return a.name="NotFoundError",a.code=8,Promise.reject(a)}return s.video===!0?s.video={mediaSource:r}:s.video.mediaSource=r,n.navigator.mediaDevices.getUserMedia(s)})}Object.defineProperty(t,"__esModule",{value:!0}),t.shimGetDisplayMedia=i},{}],Fzdr:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimOnTrack=l,t.shimPeerConnection=d,t.shimSenderGetStats=h,t.shimReceiverGetStats=b,t.shimRemoveStream=_,t.shimRTCDataChannel=v,t.shimAddTransceiver=y,t.shimGetParameters=f,t.shimCreateOffer=m,t.shimCreateAnswer=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=a(o("../utils")),n=o("./getusermedia"),r=o("./getdisplaymedia");function s(){if(typeof WeakMap!="function")return null;var g=new WeakMap;return s=function(){return g},g}function a(g){if(g&&g.__esModule)return g;if(g===null||typeof g!="object"&&typeof g!="function")return{default:g};var w=s();if(w&&w.has(g))return w.get(g);var C={},T=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var S in g)if(Object.prototype.hasOwnProperty.call(g,S)){var D=T?Object.getOwnPropertyDescriptor(g,S):null;D&&(D.get||D.set)?Object.defineProperty(C,S,D):C[S]=g[S]}return C.default=g,w&&w.set(g,C),C}function c(g,w,C){return w in g?Object.defineProperty(g,w,{value:C,enumerable:!0,configurable:!0,writable:!0}):g[w]=C,g}function u(g){return(u=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(w){return typeof w}:function(w){return w&&typeof Symbol=="function"&&w.constructor===Symbol&&w!==Symbol.prototype?"symbol":typeof w})(g)}function l(g){u(g)==="object"&&g.RTCTrackEvent&&"receiver"in g.RTCTrackEvent.prototype&&!("transceiver"in g.RTCTrackEvent.prototype)&&Object.defineProperty(g.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function d(g,w){if(u(g)==="object"&&(g.RTCPeerConnection||g.mozRTCPeerConnection)){!g.RTCPeerConnection&&g.mozRTCPeerConnection&&(g.RTCPeerConnection=g.mozRTCPeerConnection),w.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(S){var D=g.RTCPeerConnection.prototype[S],A=c({},S,function(){return arguments[0]=new(S==="addIceCandidate"?g.RTCIceCandidate:g.RTCSessionDescription)(arguments[0]),D.apply(this,arguments)});g.RTCPeerConnection.prototype[S]=A[S]});var C={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},T=g.RTCPeerConnection.prototype.getStats;g.RTCPeerConnection.prototype.getStats=function(){var[S,D,A]=arguments;return T.apply(this,[S||null]).then(function(P){if(w.version<53&&!D)try{P.forEach(function(H){H.type=C[H.type]||H.type})}catch(H){if(H.name!=="TypeError")throw H;P.forEach(function(B,N){P.set(N,Object.assign({},B,{type:C[B.type]||B.type}))})}return P}).then(D,A)}}}function h(g){if(u(g)==="object"&&g.RTCPeerConnection&&g.RTCRtpSender&&!(g.RTCRtpSender&&"getStats"in g.RTCRtpSender.prototype)){var w=g.RTCPeerConnection.prototype.getSenders;w&&(g.RTCPeerConnection.prototype.getSenders=function(){var T=this,S=w.apply(this,[]);return S.forEach(function(D){return D._pc=T}),S});var C=g.RTCPeerConnection.prototype.addTrack;C&&(g.RTCPeerConnection.prototype.addTrack=function(){var T=C.apply(this,arguments);return T._pc=this,T}),g.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}}function b(g){if(u(g)==="object"&&g.RTCPeerConnection&&g.RTCRtpSender&&!(g.RTCRtpSender&&"getStats"in g.RTCRtpReceiver.prototype)){var w=g.RTCPeerConnection.prototype.getReceivers;w&&(g.RTCPeerConnection.prototype.getReceivers=function(){var C=this,T=w.apply(this,[]);return T.forEach(function(S){return S._pc=C}),T}),i.wrapPeerConnectionEvent(g,"track",function(C){return C.receiver._pc=C.srcElement,C}),g.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}}function _(g){!g.RTCPeerConnection||"removeStream"in g.RTCPeerConnection.prototype||(g.RTCPeerConnection.prototype.removeStream=function(w){var C=this;i.deprecated("removeStream","removeTrack"),this.getSenders().forEach(function(T){T.track&&w.getTracks().includes(T.track)&&C.removeTrack(T)})})}function v(g){g.DataChannel&&!g.RTCDataChannel&&(g.RTCDataChannel=g.DataChannel)}function y(g){if(u(g)==="object"&&g.RTCPeerConnection){var w=g.RTCPeerConnection.prototype.addTransceiver;w&&(g.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];var C=arguments[1],T=C&&"sendEncodings"in C;T&&C.sendEncodings.forEach(function(P){if("rid"in P&&!/^[a-z0-9]{0,16}$/i.test(P.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in P&&!(parseFloat(P.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in P&&!(parseFloat(P.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});var S=w.apply(this,arguments);if(T){var{sender:D}=S,A=D.getParameters();"encodings"in A&&(A.encodings.length!==1||Object.keys(A.encodings[0]).length!==0)||(A.encodings=C.sendEncodings,D.sendEncodings=C.sendEncodings,this.setParametersPromises.push(D.setParameters(A).then(function(){delete D.sendEncodings}).catch(function(){delete D.sendEncodings})))}return S})}}function f(g){if(u(g)==="object"&&g.RTCRtpSender){var w=g.RTCRtpSender.prototype.getParameters;w&&(g.RTCRtpSender.prototype.getParameters=function(){var C=w.apply(this,arguments);return"encodings"in C||(C.encodings=[].concat(this.sendEncodings||[{}])),C})}}function m(g){if(u(g)==="object"&&g.RTCPeerConnection){var w=g.RTCPeerConnection.prototype.createOffer;g.RTCPeerConnection.prototype.createOffer=function(){var C=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return w.apply(T,C)}).finally(function(){T.setParametersPromises=[]}):w.apply(this,arguments)}}}function p(g){if(u(g)==="object"&&g.RTCPeerConnection){var w=g.RTCPeerConnection.prototype.createAnswer;g.RTCPeerConnection.prototype.createAnswer=function(){var C=arguments,T=this;return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(function(){return w.apply(T,C)}).finally(function(){T.setParametersPromises=[]}):w.apply(this,arguments)}}}},{"../utils":"iSxC","./getusermedia":"GzSv","./getdisplaymedia":"UuGU"}],t1lL:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimLocalStreamsAPI=a,t.shimRemoteStreamsAPI=c,t.shimCallbacksAPI=u,t.shimGetUserMedia=l,t.shimConstraints=d,t.shimRTCIceServerUrls=h,t.shimTrackEventTransceiver=b,t.shimCreateOfferLegacy=_,t.shimAudioContext=v;var i=r(o("../utils"));function n(){if(typeof WeakMap!="function")return null;var y=new WeakMap;return n=function(){return y},y}function r(y){if(y&&y.__esModule)return y;if(y===null||typeof y!="object"&&typeof y!="function")return{default:y};var f=n();if(f&&f.has(y))return f.get(y);var m={},p=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in y)if(Object.prototype.hasOwnProperty.call(y,g)){var w=p?Object.getOwnPropertyDescriptor(y,g):null;w&&(w.get||w.set)?Object.defineProperty(m,g,w):m[g]=y[g]}return m.default=y,f&&f.set(y,m),m}function s(y){return(s=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(f){return typeof f}:function(f){return f&&typeof Symbol=="function"&&f.constructor===Symbol&&f!==Symbol.prototype?"symbol":typeof f})(y)}function a(y){if(s(y)==="object"&&y.RTCPeerConnection){if("getLocalStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in y.RTCPeerConnection.prototype)){var f=y.RTCPeerConnection.prototype.addTrack;y.RTCPeerConnection.prototype.addStream=function(m){var p=this;this._localStreams||(this._localStreams=[]),this._localStreams.includes(m)||this._localStreams.push(m),m.getAudioTracks().forEach(function(g){return f.call(p,g,m)}),m.getVideoTracks().forEach(function(g){return f.call(p,g,m)})},y.RTCPeerConnection.prototype.addTrack=function(m){for(var p=this,g=arguments.length,w=new Array(g>1?g-1:0),C=1;C<g;C++)w[C-1]=arguments[C];return w&&w.forEach(function(T){p._localStreams?p._localStreams.includes(T)||p._localStreams.push(T):p._localStreams=[T]}),f.apply(this,arguments)}}"removeStream"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.removeStream=function(m){var p=this;this._localStreams||(this._localStreams=[]);var g=this._localStreams.indexOf(m);if(g!==-1){this._localStreams.splice(g,1);var w=m.getTracks();this.getSenders().forEach(function(C){w.includes(C.track)&&p.removeTrack(C)})}})}}function c(y){if(s(y)==="object"&&y.RTCPeerConnection&&("getRemoteStreams"in y.RTCPeerConnection.prototype||(y.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in y.RTCPeerConnection.prototype))){Object.defineProperty(y.RTCPeerConnection.prototype,"onaddstream",{get:function(){return this._onaddstream},set:function(m){var p=this;this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=m),this.addEventListener("track",this._onaddstreampoly=function(g){g.streams.forEach(function(w){if(p._remoteStreams||(p._remoteStreams=[]),!p._remoteStreams.includes(w)){p._remoteStreams.push(w);var C=new Event("addstream");C.stream=w,p.dispatchEvent(C)}})})}});var f=y.RTCPeerConnection.prototype.setRemoteDescription;y.RTCPeerConnection.prototype.setRemoteDescription=function(){var m=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(p){p.streams.forEach(function(g){if(m._remoteStreams||(m._remoteStreams=[]),!(m._remoteStreams.indexOf(g)>=0)){m._remoteStreams.push(g);var w=new Event("addstream");w.stream=g,m.dispatchEvent(w)}})}),f.apply(m,arguments)}}}function u(y){if(s(y)==="object"&&y.RTCPeerConnection){var f=y.RTCPeerConnection.prototype,m=f.createOffer,p=f.createAnswer,g=f.setLocalDescription,w=f.setRemoteDescription,C=f.addIceCandidate;f.createOffer=function(S,D){var A=arguments.length>=2?arguments[2]:arguments[0],P=m.apply(this,[A]);return D?(P.then(S,D),Promise.resolve()):P},f.createAnswer=function(S,D){var A=arguments.length>=2?arguments[2]:arguments[0],P=p.apply(this,[A]);return D?(P.then(S,D),Promise.resolve()):P};var T=function(S,D,A){var P=g.apply(this,[S]);return A?(P.then(D,A),Promise.resolve()):P};f.setLocalDescription=T,T=function(S,D,A){var P=w.apply(this,[S]);return A?(P.then(D,A),Promise.resolve()):P},f.setRemoteDescription=T,T=function(S,D,A){var P=C.apply(this,[S]);return A?(P.then(D,A),Promise.resolve()):P},f.addIceCandidate=T}}function l(y){var f=y&&y.navigator;if(f.mediaDevices&&f.mediaDevices.getUserMedia){var m=f.mediaDevices,p=m.getUserMedia.bind(m);f.mediaDevices.getUserMedia=function(g){return p(d(g))}}!f.getUserMedia&&f.mediaDevices&&f.mediaDevices.getUserMedia&&(f.getUserMedia=function(g,w,C){f.mediaDevices.getUserMedia(g).then(w,C)}.bind(f))}function d(y){return y&&y.video!==void 0?Object.assign({},y,{video:i.compactObject(y.video)}):y}function h(y){if(y.RTCPeerConnection){var f=y.RTCPeerConnection;y.RTCPeerConnection=function(m,p){if(m&&m.iceServers){for(var g=[],w=0;w<m.iceServers.length;w++){var C=m.iceServers[w];!C.hasOwnProperty("urls")&&C.hasOwnProperty("url")?(i.deprecated("RTCIceServer.url","RTCIceServer.urls"),(C=JSON.parse(JSON.stringify(C))).urls=C.url,delete C.url,g.push(C)):g.push(m.iceServers[w])}m.iceServers=g}return new f(m,p)},y.RTCPeerConnection.prototype=f.prototype,"generateCertificate"in f&&Object.defineProperty(y.RTCPeerConnection,"generateCertificate",{get:function(){return f.generateCertificate}})}}function b(y){s(y)==="object"&&y.RTCTrackEvent&&"receiver"in y.RTCTrackEvent.prototype&&!("transceiver"in y.RTCTrackEvent.prototype)&&Object.defineProperty(y.RTCTrackEvent.prototype,"transceiver",{get:function(){return{receiver:this.receiver}}})}function _(y){var f=y.RTCPeerConnection.prototype.createOffer;y.RTCPeerConnection.prototype.createOffer=function(m){if(m){m.offerToReceiveAudio!==void 0&&(m.offerToReceiveAudio=!!m.offerToReceiveAudio);var p=this.getTransceivers().find(function(w){return w.receiver.track.kind==="audio"});m.offerToReceiveAudio===!1&&p?p.direction==="sendrecv"?p.setDirection?p.setDirection("sendonly"):p.direction="sendonly":p.direction==="recvonly"&&(p.setDirection?p.setDirection("inactive"):p.direction="inactive"):m.offerToReceiveAudio!==!0||p||this.addTransceiver("audio"),m.offerToReceiveVideo!==void 0&&(m.offerToReceiveVideo=!!m.offerToReceiveVideo);var g=this.getTransceivers().find(function(w){return w.receiver.track.kind==="video"});m.offerToReceiveVideo===!1&&g?g.direction==="sendrecv"?g.setDirection?g.setDirection("sendonly"):g.direction="sendonly":g.direction==="recvonly"&&(g.setDirection?g.setDirection("inactive"):g.direction="inactive"):m.offerToReceiveVideo!==!0||g||this.addTransceiver("video")}return f.apply(this,arguments)}}function v(y){s(y)!=="object"||y.AudioContext||(y.AudioContext=y.webkitAudioContext)}},{"../utils":"iSxC"}],GOQK:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shimRTCIceCandidate=u,t.shimMaxMessageSize=l,t.shimSendThrowTypeError=d,t.shimConnectionState=h,t.removeExtmapAllowMixed=b,t.shimAddIceCandidateNullOrEmpty=_;var i=a(o("sdp")),n=s(o("./utils"));function r(){if(typeof WeakMap!="function")return null;var v=new WeakMap;return r=function(){return v},v}function s(v){if(v&&v.__esModule)return v;if(v===null||typeof v!="object"&&typeof v!="function")return{default:v};var y=r();if(y&&y.has(v))return y.get(v);var f={},m=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var p in v)if(Object.prototype.hasOwnProperty.call(v,p)){var g=m?Object.getOwnPropertyDescriptor(v,p):null;g&&(g.get||g.set)?Object.defineProperty(f,p,g):f[p]=v[p]}return f.default=v,y&&y.set(v,f),f}function a(v){return v&&v.__esModule?v:{default:v}}function c(v){return(c=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(y){return typeof y}:function(y){return y&&typeof Symbol=="function"&&y.constructor===Symbol&&y!==Symbol.prototype?"symbol":typeof y})(v)}function u(v){if(v.RTCIceCandidate&&!(v.RTCIceCandidate&&"foundation"in v.RTCIceCandidate.prototype)){var y=v.RTCIceCandidate;v.RTCIceCandidate=function(f){if(c(f)==="object"&&f.candidate&&f.candidate.indexOf("a=")===0&&((f=JSON.parse(JSON.stringify(f))).candidate=f.candidate.substr(2)),f.candidate&&f.candidate.length){var m=new y(f),p=i.default.parseCandidate(f.candidate),g=Object.assign(m,p);return g.toJSON=function(){return{candidate:g.candidate,sdpMid:g.sdpMid,sdpMLineIndex:g.sdpMLineIndex,usernameFragment:g.usernameFragment}},g}return new y(f)},v.RTCIceCandidate.prototype=y.prototype,n.wrapPeerConnectionEvent(v,"icecandidate",function(f){return f.candidate&&Object.defineProperty(f,"candidate",{value:new v.RTCIceCandidate(f.candidate),writable:"false"}),f})}}function l(v,y){if(v.RTCPeerConnection){"sctp"in v.RTCPeerConnection.prototype||Object.defineProperty(v.RTCPeerConnection.prototype,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp}});var f=v.RTCPeerConnection.prototype.setRemoteDescription;v.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,y.browser==="chrome"&&y.version>=76){var{sdpSemantics:m}=this.getConfiguration();m==="plan-b"&&Object.defineProperty(this,"sctp",{get:function(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(A){if(!A||!A.sdp)return!1;var P=i.default.splitSections(A.sdp);return P.shift(),P.some(function(H){var B=i.default.parseMLine(H);return B&&B.kind==="application"&&B.protocol.indexOf("SCTP")!==-1})}(arguments[0])){var p,g=function(A){var P=A.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(P===null||P.length<2)return-1;var H=parseInt(P[1],10);return H!=H?-1:H}(arguments[0]),w=(S=g,D=65536,y.browser==="firefox"&&(D=y.version<57?S===-1?16384:2147483637:y.version<60?y.version===57?65535:65536:2147483637),D),C=function(A,P){var H=65536;y.browser==="firefox"&&y.version===57&&(H=65535);var B=i.default.matchPrefix(A.sdp,"a=max-message-size:");return B.length>0?H=parseInt(B[0].substr(19),10):y.browser==="firefox"&&P!==-1&&(H=2147483637),H}(arguments[0],g);p=w===0&&C===0?Number.POSITIVE_INFINITY:w===0||C===0?Math.max(w,C):Math.min(w,C);var T={};Object.defineProperty(T,"maxMessageSize",{get:function(){return p}}),this._sctp=T}var S,D;return f.apply(this,arguments)}}}function d(v){if(v.RTCPeerConnection&&"createDataChannel"in v.RTCPeerConnection.prototype){var y=v.RTCPeerConnection.prototype.createDataChannel;v.RTCPeerConnection.prototype.createDataChannel=function(){var m=y.apply(this,arguments);return f(m,this),m},n.wrapPeerConnectionEvent(v,"datachannel",function(m){return f(m.channel,m.target),m})}function f(m,p){var g=m.send;m.send=function(){var w=arguments[0],C=w.length||w.size||w.byteLength;if(m.readyState==="open"&&p.sctp&&C>p.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+p.sctp.maxMessageSize+" bytes)");return g.apply(m,arguments)}}}function h(v){if(v.RTCPeerConnection&&!("connectionState"in v.RTCPeerConnection.prototype)){var y=v.RTCPeerConnection.prototype;Object.defineProperty(y,"connectionState",{get:function(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(y,"onconnectionstatechange",{get:function(){return this._onconnectionstatechange||null},set:function(f){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),f&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=f)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(function(f){var m=y[f];y[f]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=function(p){var g=p.target;if(g._lastConnectionState!==g.connectionState){g._lastConnectionState=g.connectionState;var w=new Event("connectionstatechange",p);g.dispatchEvent(w)}return p},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),m.apply(this,arguments)}})}}function b(v,y){if(v.RTCPeerConnection&&!(y.browser==="chrome"&&y.version>=71||y.browser==="safari"&&y.version>=605)){var f=v.RTCPeerConnection.prototype.setRemoteDescription;v.RTCPeerConnection.prototype.setRemoteDescription=function(m){if(m&&m.sdp&&m.sdp.indexOf(`
|
|
70
70
|
a=extmap-allow-mixed`)!==-1){var p=m.sdp.split(`
|
|
71
71
|
`).filter(function(g){return g.trim()!=="a=extmap-allow-mixed"}).join(`
|
|
72
72
|
`);v.RTCSessionDescription&&m instanceof v.RTCSessionDescription?arguments[0]=new v.RTCSessionDescription({type:m.type,sdp:p}):m.sdp=p}return f.apply(this,arguments)}}}function _(v,y){if(v.RTCPeerConnection&&v.RTCPeerConnection.prototype){var f=v.RTCPeerConnection.prototype.addIceCandidate;f&&f.length!==0&&(v.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(y.browser==="chrome"&&y.version<78||y.browser==="firefox"&&y.version<68||y.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():f.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}}},{sdp:"YHvh","./utils":"iSxC"}],KtlG:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.adapterFactory=d;var i=l(o("./utils")),n=l(o("./chrome/chrome_shim")),r=l(o("./edge/edge_shim")),s=l(o("./firefox/firefox_shim")),a=l(o("./safari/safari_shim")),c=l(o("./common_shim"));function u(){if(typeof WeakMap!="function")return null;var h=new WeakMap;return u=function(){return h},h}function l(h){if(h&&h.__esModule)return h;if(h===null||typeof h!="object"&&typeof h!="function")return{default:h};var b=u();if(b&&b.has(h))return b.get(h);var _={},v=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var y in h)if(Object.prototype.hasOwnProperty.call(h,y)){var f=v?Object.getOwnPropertyDescriptor(h,y):null;f&&(f.get||f.set)?Object.defineProperty(_,y,f):_[y]=h[y]}return _.default=h,b&&b.set(h,_),_}function d(){var{window:h}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},b=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimEdge:!0,shimSafari:!0},_=i.log,v=i.detectBrowser(h),y={browserDetails:v,commonShim:c,extractVersion:i.extractVersion,disableLog:i.disableLog,disableWarnings:i.disableWarnings};switch(v.browser){case"chrome":if(!n||!n.shimPeerConnection||!b.shimChrome)return _("Chrome shim is not included in this adapter release."),y;if(v.version===null)return _("Chrome shim can not determine version, not shimming."),y;_("adapter.js shimming chrome."),y.browserShim=n,c.shimAddIceCandidateNullOrEmpty(h,v),n.shimGetUserMedia(h,v),n.shimMediaStream(h,v),n.shimPeerConnection(h,v),n.shimOnTrack(h,v),n.shimAddTrackRemoveTrack(h,v),n.shimGetSendersWithDtmf(h,v),n.shimGetStats(h,v),n.shimSenderReceiverGetStats(h,v),n.fixNegotiationNeeded(h,v),c.shimRTCIceCandidate(h,v),c.shimConnectionState(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v),c.removeExtmapAllowMixed(h,v);break;case"firefox":if(!s||!s.shimPeerConnection||!b.shimFirefox)return _("Firefox shim is not included in this adapter release."),y;_("adapter.js shimming firefox."),y.browserShim=s,c.shimAddIceCandidateNullOrEmpty(h,v),s.shimGetUserMedia(h,v),s.shimPeerConnection(h,v),s.shimOnTrack(h,v),s.shimRemoveStream(h,v),s.shimSenderGetStats(h,v),s.shimReceiverGetStats(h,v),s.shimRTCDataChannel(h,v),s.shimAddTransceiver(h,v),s.shimGetParameters(h,v),s.shimCreateOffer(h,v),s.shimCreateAnswer(h,v),c.shimRTCIceCandidate(h,v),c.shimConnectionState(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v);break;case"edge":if(!r||!r.shimPeerConnection||!b.shimEdge)return _("MS edge shim is not included in this adapter release."),y;_("adapter.js shimming edge."),y.browserShim=r,r.shimGetUserMedia(h,v),r.shimGetDisplayMedia(h,v),r.shimPeerConnection(h,v),r.shimReplaceTrack(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v);break;case"safari":if(!a||!b.shimSafari)return _("Safari shim is not included in this adapter release."),y;_("adapter.js shimming safari."),y.browserShim=a,c.shimAddIceCandidateNullOrEmpty(h,v),a.shimRTCIceServerUrls(h,v),a.shimCreateOfferLegacy(h,v),a.shimCallbacksAPI(h,v),a.shimLocalStreamsAPI(h,v),a.shimRemoteStreamsAPI(h,v),a.shimTrackEventTransceiver(h,v),a.shimGetUserMedia(h,v),a.shimAudioContext(h,v),c.shimRTCIceCandidate(h,v),c.shimMaxMessageSize(h,v),c.shimSendThrowTypeError(h,v),c.removeExtmapAllowMixed(h,v);break;default:_("Unsupported browser!")}return y}},{"./utils":"iSxC","./chrome/chrome_shim":"uI5X","./edge/edge_shim":"XRic","./firefox/firefox_shim":"Fzdr","./safari/safari_shim":"t1lL","./common_shim":"GOQK"}],tI1X:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=o("./adapter_factory.js"),n=(0,i.adapterFactory)({window:typeof window>"u"?void 0:window}),r=n;t.default=r},{"./adapter_factory.js":"KtlG"}],sXtV:[function(o,e,t){"use strict";var i=this&&this.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(t,"__esModule",{value:!0}),t.webRTCAdapter=void 0;var n=i(o("webrtc-adapter"));t.webRTCAdapter=n.default},{"webrtc-adapter":"tI1X"}],I31f:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Supports=void 0;var i=o("./adapter");t.Supports=new(function(){function n(){this.isIOS=["iPad","iPhone","iPod"].includes(navigator.platform),this.supportedBrowsers=["firefox","chrome","safari"],this.minFirefoxVersion=59,this.minChromeVersion=72,this.minSafariVersion=605}return n.prototype.isWebRTCSupported=function(){return typeof RTCPeerConnection<"u"},n.prototype.isBrowserSupported=function(){var r=this.getBrowser(),s=this.getVersion();return!!this.supportedBrowsers.includes(r)&&(r==="chrome"?s>=this.minChromeVersion:r==="firefox"?s>=this.minFirefoxVersion:r==="safari"&&!this.isIOS&&s>=this.minSafariVersion)},n.prototype.getBrowser=function(){return i.webRTCAdapter.browserDetails.browser},n.prototype.getVersion=function(){return i.webRTCAdapter.browserDetails.version||0},n.prototype.isUnifiedPlanSupported=function(){var r,s=this.getBrowser(),a=i.webRTCAdapter.browserDetails.version||0;if(s==="chrome"&&a<72)return!1;if(s==="firefox"&&a>=59)return!0;if(!(window.RTCRtpTransceiver&&"currentDirection"in RTCRtpTransceiver.prototype))return!1;var c=!1;try{(r=new RTCPeerConnection).addTransceiver("audio"),c=!0}catch{}finally{r&&r.close()}return c},n.prototype.toString=function(){return`Supports:
|
|
@@ -75,9 +75,9 @@ a=extmap-allow-mixed`)!==-1){var p=m.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(o,e,t){"use strict";var i=this&&this.__createBinding||(Object.create?function(u,l,d,h){h===void 0&&(h=d),Object.defineProperty(u,h,{enumerable:!0,get:function(){return l[d]}})}:function(u,l,d,h){h===void 0&&(h=d),u[h]=l[d]}),n=this&&this.__setModuleDefault||(Object.create?function(u,l){Object.defineProperty(u,"default",{enumerable:!0,value:l})}:function(u,l){u.default=l}),r=this&&this.__importStar||function(u){if(u&&u.__esModule)return u;var l={};if(u!=null)for(var d in u)d!=="default"&&Object.prototype.hasOwnProperty.call(u,d)&&i(l,u,d);return n(l,u),l};Object.defineProperty(t,"__esModule",{value:!0}),t.util=void 0;var s=r(o("peerjs-js-binarypack")),a=o("./supports"),c={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"turn:0.peerjs.com:3478",username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"};t.util=new(function(){function u(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=c,this.browser=a.Supports.getBrowser(),this.browserVersion=a.Supports.getVersion(),this.supports=function(){var l,d={browser:a.Supports.isBrowserSupported(),webRTC:a.Supports.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!d.webRTC)return d;try{l=new RTCPeerConnection(c),d.audioVideo=!0;var h=void 0;try{h=l.createDataChannel("_PEERJSTEST",{ordered:!0}),d.data=!0,d.reliable=!!h.ordered;try{h.binaryType="blob",d.binaryBlob=!a.Supports.isIOS}catch{}}catch{}finally{h&&h.close()}}catch{}finally{l&&l.close()}return d}(),this.pack=s.pack,this.unpack=s.unpack,this._dataCount=1}return u.prototype.noop=function(){},u.prototype.validateId=function(l){return!l||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(l)},u.prototype.chunk=function(l){for(var d=[],h=l.size,b=Math.ceil(h/t.util.chunkedMTU),_=0,v=0;v<h;){var y=Math.min(h,v+t.util.chunkedMTU),f=l.slice(v,y),m={__peerData:this._dataCount,n:_,data:f,total:b};d.push(m),v=y,_++}return this._dataCount++,d},u.prototype.blobToArrayBuffer=function(l,d){var h=new FileReader;return h.onload=function(b){b.target&&d(b.target.result)},h.readAsArrayBuffer(l),h},u.prototype.binaryStringToArrayBuffer=function(l){for(var d=new Uint8Array(l.length),h=0;h<l.length;h++)d[h]=255&l.charCodeAt(h);return d.buffer},u.prototype.randomToken=function(){return Math.random().toString(36).substr(2)},u.prototype.isSecure=function(){return location.protocol==="https:"},u}())},{"peerjs-js-binarypack":"kdPp","./supports":"I31f"}],JJlS:[function(o,e,t){"use strict";var i=Object.prototype.hasOwnProperty,n="~";function r(){}function s(l,d,h){this.fn=l,this.context=d,this.once=h||!1}function a(l,d,h,b,_){if(typeof h!="function")throw new TypeError("The listener must be a function");var v=new s(h,b||l,_),y=n?n+d:d;return l._events[y]?l._events[y].fn?l._events[y]=[l._events[y],v]:l._events[y].push(v):(l._events[y]=v,l._eventsCount++),l}function c(l,d){--l._eventsCount==0?l._events=new r:delete l._events[d]}function u(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1)),u.prototype.eventNames=function(){var l,d,h=[];if(this._eventsCount===0)return h;for(d in l=this._events)i.call(l,d)&&h.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(l)):h},u.prototype.listeners=function(l){var d=n?n+l:l,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var b=0,_=h.length,v=new Array(_);b<_;b++)v[b]=h[b].fn;return v},u.prototype.listenerCount=function(l){var d=n?n+l:l,h=this._events[d];return h?h.fn?1:h.length:0},u.prototype.emit=function(l,d,h,b,_,v){var y=n?n+l:l;if(!this._events[y])return!1;var f,m,p=this._events[y],g=arguments.length;if(p.fn){switch(p.once&&this.removeListener(l,p.fn,void 0,!0),g){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,d),!0;case 3:return p.fn.call(p.context,d,h),!0;case 4:return p.fn.call(p.context,d,h,b),!0;case 5:return p.fn.call(p.context,d,h,b,_),!0;case 6:return p.fn.call(p.context,d,h,b,_,v),!0}for(m=1,f=new Array(g-1);m<g;m++)f[m-1]=arguments[m];p.fn.apply(p.context,f)}else{var x,C=p.length;for(m=0;m<C;m++)switch(p[m].once&&this.removeListener(l,p[m].fn,void 0,!0),g){case 1:p[m].fn.call(p[m].context);break;case 2:p[m].fn.call(p[m].context,d);break;case 3:p[m].fn.call(p[m].context,d,h);break;case 4:p[m].fn.call(p[m].context,d,h,b);break;default:if(!f)for(x=1,f=new Array(g-1);x<g;x++)f[x-1]=arguments[x];p[m].fn.apply(p[m].context,f)}}return!0},u.prototype.on=function(l,d,h){return a(this,l,d,h,!1)},u.prototype.once=function(l,d,h){return a(this,l,d,h,!0)},u.prototype.removeListener=function(l,d,h,b){var _=n?n+l:l;if(!this._events[_])return this;if(!d)return c(this,_),this;var v=this._events[_];if(v.fn)v.fn!==d||b&&!v.once||h&&v.context!==h||c(this,_);else{for(var y=0,f=[],m=v.length;y<m;y++)(v[y].fn!==d||b&&!v[y].once||h&&v[y].context!==h)&&f.push(v[y]);f.length?this._events[_]=f.length===1?f[0]:f:c(this,_)}return this},u.prototype.removeAllListeners=function(l){var d;return l?(d=n?n+l:l,this._events[d]&&c(this,d)):(this._events=new r,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=n,u.EventEmitter=u,typeof e<"u"&&(e.exports=u)},{}],WOs9:[function(o,e,t){"use strict";var i=this&&this.__read||function(c,u){var l=typeof Symbol=="function"&&c[Symbol.iterator];if(!l)return c;var d,h,b=l.call(c),_=[];try{for(;(u===void 0||u-- >0)&&!(d=b.next()).done;)_.push(d.value)}catch(v){h={error:v}}finally{try{d&&!d.done&&(l=b.return)&&l.call(b)}finally{if(h)throw h.error}}return _},n=this&&this.__spreadArray||function(c,u){for(var l=0,d=u.length,h=c.length;l<d;l++,h++)c[h]=u[l];return c};Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0;var r,s="PeerJS: ";(function(c){c[c.Disabled=0]="Disabled",c[c.Errors=1]="Errors",c[c.Warnings=2]="Warnings",c[c.All=3]="All"})(r=t.LogLevel||(t.LogLevel={}));var a=function(){function c(){this._logLevel=r.Disabled}return Object.defineProperty(c.prototype,"logLevel",{get:function(){return this._logLevel},set:function(u){this._logLevel=u},enumerable:!1,configurable:!0}),c.prototype.log=function(){for(var u=[],l=0;l<arguments.length;l++)u[l]=arguments[l];this._logLevel>=r.All&&this._print.apply(this,n([r.All],i(u)))},c.prototype.warn=function(){for(var u=[],l=0;l<arguments.length;l++)u[l]=arguments[l];this._logLevel>=r.Warnings&&this._print.apply(this,n([r.Warnings],i(u)))},c.prototype.error=function(){for(var u=[],l=0;l<arguments.length;l++)u[l]=arguments[l];this._logLevel>=r.Errors&&this._print.apply(this,n([r.Errors],i(u)))},c.prototype.setLogFunction=function(u){this._print=u},c.prototype._print=function(u){for(var l=[],d=1;d<arguments.length;d++)l[d-1]=arguments[d];var h=n([s],i(l));for(var b in h)h[b]instanceof Error&&(h[b]="("+h[b].name+") "+h[b].message);u>=r.All?console.log.apply(console,n([],i(h))):u>=r.Warnings?console.warn.apply(console,n(["WARNING"],i(h))):u>=r.Errors&&console.error.apply(console,n(["ERROR"],i(h)))},c}();t.default=new a},{}],ZRYf:[function(o,e,t){"use strict";var i,n,r,s,a,c,u;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"}(s=t.PeerErrorType||(t.PeerErrorType={})),function(l){l.Binary="binary",l.BinaryUTF8="binary-utf8",l.JSON="json"}(a=t.SerializationType||(t.SerializationType={})),function(l){l.Message="message",l.Disconnected="disconnected",l.Error="error",l.Close="close"}(c=t.SocketEventType||(t.SocketEventType={})),function(l){l.Heartbeat="HEARTBEAT",l.Candidate="CANDIDATE",l.Offer="OFFER",l.Answer="ANSWER",l.Open="OPEN",l.Error="ERROR",l.IdTaken="ID-TAKEN",l.InvalidKey="INVALID-KEY",l.Leave="LEAVE",l.Expire="EXPIRE"}(u=t.ServerMessageType||(t.ServerMessageType={}))},{}],wJlv:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var h=function(b,_){return(h=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(v,y){v.__proto__=y}||function(v,y){for(var f in y)Object.prototype.hasOwnProperty.call(y,f)&&(v[f]=y[f])})(b,_)};return function(b,_){if(typeof _!="function"&&_!==null)throw new TypeError("Class extends value "+String(_)+" is not a constructor or null");function v(){this.constructor=b}h(b,_),b.prototype=_===null?Object.create(_):(v.prototype=_.prototype,new v)}}(),n=this&&this.__read||function(h,b){var _=typeof Symbol=="function"&&h[Symbol.iterator];if(!_)return h;var v,y,f=_.call(h),m=[];try{for(;(b===void 0||b-- >0)&&!(v=f.next()).done;)m.push(v.value)}catch(p){y={error:p}}finally{try{v&&!v.done&&(_=f.return)&&_.call(f)}finally{if(y)throw y.error}}return m},r=this&&this.__spreadArray||function(h,b){for(var _=0,v=b.length,y=h.length;_<v;_++,y++)h[y]=b[_];return h},s=this&&this.__values||function(h){var b=typeof Symbol=="function"&&Symbol.iterator,_=b&&h[b],v=0;if(_)return _.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&v>=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(b?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;var c=o("eventemitter3"),u=a(o("./logger")),l=o("./enums"),d=function(h){function b(_,v,y,f,m,p){p===void 0&&(p=5e3);var g=h.call(this)||this;g.pingInterval=p,g._disconnected=!0,g._messagesQueue=[];var x=_?"wss://":"ws://";return g._baseUrl=x+v+":"+y+f+"peerjs?key="+m,g}return i(b,h),b.prototype.start=function(_,v){var y=this;this._id=_;var f=this._baseUrl+"&id="+_+"&token="+v;!this._socket&&this._disconnected&&(this._socket=new WebSocket(f),this._disconnected=!1,this._socket.onmessage=function(m){var p;try{p=JSON.parse(m.data),u.default.log("Server message received:",p)}catch{return void u.default.log("Invalid server message",m.data)}y.emit(l.SocketEventType.Message,p)},this._socket.onclose=function(m){y._disconnected||(u.default.log("Socket closed.",m),y._cleanup(),y._disconnected=!0,y.emit(l.SocketEventType.Disconnected))},this._socket.onopen=function(){y._disconnected||(y._sendQueuedMessages(),u.default.log("Socket open"),y._scheduleHeartbeat())})},b.prototype._scheduleHeartbeat=function(){var _=this;this._wsPingTimer=setTimeout(function(){_._sendHeartbeat()},this.pingInterval)},b.prototype._sendHeartbeat=function(){if(this._wsOpen()){var _=JSON.stringify({type:l.ServerMessageType.Heartbeat});this._socket.send(_),this._scheduleHeartbeat()}else u.default.log("Cannot send heartbeat, because socket closed")},b.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},b.prototype._sendQueuedMessages=function(){var _,v,y=r([],n(this._messagesQueue));this._messagesQueue=[];try{for(var f=s(y),m=f.next();!m.done;m=f.next()){var p=m.value;this.send(p)}}catch(g){_={error:g}}finally{try{m&&!m.done&&(v=f.return)&&v.call(f)}finally{if(_)throw _.error}}},b.prototype.send=function(_){if(!this._disconnected)if(this._id)if(_.type){if(this._wsOpen()){var v=JSON.stringify(_);this._socket.send(v)}}else this.emit(l.SocketEventType.Error,"Invalid message");else this._messagesQueue.push(_)},b.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},b.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},b}(c.EventEmitter);t.Socket=d},{eventemitter3:"JJlS","./logger":"WOs9","./enums":"ZRYf"}],HCdX:[function(o,e,t){"use strict";var i=this&&this.__assign||function(){return(i=Object.assign||function(d){for(var h,b=1,_=arguments.length;b<_;b++)for(var v in h=arguments[b])Object.prototype.hasOwnProperty.call(h,v)&&(d[v]=h[v]);return d}).apply(this,arguments)},n=this&&this.__awaiter||function(d,h,b,_){return new(b||(b=Promise))(function(v,y){function f(g){try{p(_.next(g))}catch(x){y(x)}}function m(g){try{p(_.throw(g))}catch(x){y(x)}}function p(g){var x;g.done?v(g.value):(x=g.value,x instanceof b?x:new b(function(C){C(x)})).then(f,m)}p((_=_.apply(d,h||[])).next())})},r=this&&this.__generator||function(d,h){var b,_,v,y,f={label:0,sent:function(){if(1&v[0])throw v[1];return v[1]},trys:[],ops:[]};return y={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function m(p){return function(g){return function(x){if(b)throw new TypeError("Generator is already executing.");for(;f;)try{if(b=1,_&&(v=2&x[0]?_.return:x[0]?_.throw||((v=_.return)&&v.call(_),0):_.next)&&!(v=v.call(_,x[1])).done)return v;switch(_=0,v&&(x=[2&x[0],v.value]),x[0]){case 0:case 1:v=x;break;case 4:return f.label++,{value:x[1],done:!1};case 5:f.label++,_=x[1],x=[0];continue;case 7:x=f.ops.pop(),f.trys.pop();continue;default:if(!(v=(v=f.trys).length>0&&v[v.length-1])&&(x[0]===6||x[0]===2)){f=0;continue}if(x[0]===3&&(!v||x[1]>v[0]&&x[1]<v[3])){f.label=x[1];break}if(x[0]===6&&f.label<v[1]){f.label=v[1],v=x;break}if(v&&f.label<v[2]){f.label=v[2],f.ops.push(x);break}v[2]&&f.ops.pop(),f.trys.pop();continue}x=h.call(d,f)}catch(C){x=[6,C],_=0}finally{b=v=0}if(5&x[0])throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}([p,g])}}},s=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(t,"__esModule",{value:!0}),t.Negotiator=void 0;var a=o("./util"),c=s(o("./logger")),u=o("./enums"),l=function(){function d(h){this.connection=h}return d.prototype.startConnection=function(h){var b=this._startPeerConnection();if(this.connection.peerConnection=b,this.connection.type===u.ConnectionType.Media&&h._stream&&this._addTracksToConnection(h._stream,b),h.originator){if(this.connection.type===u.ConnectionType.Data){var _=this.connection,v={ordered:!!h.reliable},y=b.createDataChannel(_.label,v);_.initialize(y)}this._makeOffer()}else this.handleSDP("OFFER",h.sdp)},d.prototype._startPeerConnection=function(){c.default.log("Creating RTCPeerConnection.");var h=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(h),h},d.prototype._setupListeners=function(h){var b=this,_=this.connection.peer,v=this.connection.connectionId,y=this.connection.type,f=this.connection.provider;c.default.log("Listening for ICE candidates."),h.onicecandidate=function(m){m.candidate&&m.candidate.candidate&&(c.default.log("Received ICE candidates for "+_+":",m.candidate),f.socket.send({type:u.ServerMessageType.Candidate,payload:{candidate:m.candidate,type:y,connectionId:v},dst:_}))},h.oniceconnectionstatechange=function(){switch(h.iceConnectionState){case"failed":c.default.log("iceConnectionState is failed, closing connections to "+_),b.connection.emit(u.ConnectionEventType.Error,new Error("Negotiation of connection to "+_+" failed.")),b.connection.close();break;case"closed":c.default.log("iceConnectionState is closed, closing connections to "+_),b.connection.emit(u.ConnectionEventType.Error,new Error("Connection to "+_+" closed.")),b.connection.close();break;case"disconnected":c.default.log("iceConnectionState changed to disconnected on the connection with "+_);break;case"completed":h.onicecandidate=a.util.noop}b.connection.emit(u.ConnectionEventType.IceStateChanged,h.iceConnectionState)},c.default.log("Listening for data channel"),h.ondatachannel=function(m){c.default.log("Received data channel");var p=m.channel;f.getConnection(_,v).initialize(p)},c.default.log("Listening for remote stream"),h.ontrack=function(m){c.default.log("Received remote stream");var p=m.streams[0],g=f.getConnection(_,v);if(g.type===u.ConnectionType.Media){var x=g;b._addStreamToMediaConnection(p,x)}}},d.prototype.cleanup=function(){c.default.log("Cleaning up PeerConnection to "+this.connection.peer);var h=this.connection.peerConnection;if(h){this.connection.peerConnection=null,h.onicecandidate=h.oniceconnectionstatechange=h.ondatachannel=h.ontrack=function(){};var b=h.signalingState!=="closed",_=!1;if(this.connection.type===u.ConnectionType.Data){var v=this.connection.dataChannel;v&&(_=!!v.readyState&&v.readyState!=="closed")}(b||_)&&h.close()}},d.prototype._makeOffer=function(){return n(this,void 0,Promise,function(){var h,b,_,v,y,f,m;return r(this,function(p){switch(p.label){case 0:h=this.connection.peerConnection,b=this.connection.provider,p.label=1;case 1:return p.trys.push([1,7,,8]),[4,h.createOffer(this.connection.options.constraints)];case 2:_=p.sent(),c.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(_.sdp=this.connection.options.sdpTransform(_.sdp)||_.sdp),p.label=3;case 3:return p.trys.push([3,5,,6]),[4,h.setLocalDescription(_)];case 4:return p.sent(),c.default.log("Set localDescription:",_,"for:"+this.connection.peer),v={sdp:_,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:a.util.browser},this.connection.type===u.ConnectionType.Data&&(y=this.connection,v=i(i({},v),{label:y.label,reliable:y.reliable,serialization:y.serialization})),b.socket.send({type:u.ServerMessageType.Offer,payload:v,dst:this.connection.peer}),[3,6];case 5:return(f=p.sent())!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(b.emitError(u.PeerErrorType.WebRTC,f),c.default.log("Failed to setLocalDescription, ",f)),[3,6];case 6:return[3,8];case 7:return m=p.sent(),b.emitError(u.PeerErrorType.WebRTC,m),c.default.log("Failed to createOffer, ",m),[3,8];case 8:return[2]}})})},d.prototype._makeAnswer=function(){return n(this,void 0,Promise,function(){var h,b,_,v,y;return r(this,function(f){switch(f.label){case 0:h=this.connection.peerConnection,b=this.connection.provider,f.label=1;case 1:return f.trys.push([1,7,,8]),[4,h.createAnswer()];case 2:_=f.sent(),c.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(_.sdp=this.connection.options.sdpTransform(_.sdp)||_.sdp),f.label=3;case 3:return f.trys.push([3,5,,6]),[4,h.setLocalDescription(_)];case 4:return f.sent(),c.default.log("Set localDescription:",_,"for:"+this.connection.peer),b.socket.send({type:u.ServerMessageType.Answer,payload:{sdp:_,type:this.connection.type,connectionId:this.connection.connectionId,browser:a.util.browser},dst:this.connection.peer}),[3,6];case 5:return v=f.sent(),b.emitError(u.PeerErrorType.WebRTC,v),c.default.log("Failed to setLocalDescription, ",v),[3,6];case 6:return[3,8];case 7:return y=f.sent(),b.emitError(u.PeerErrorType.WebRTC,y),c.default.log("Failed to create answer, ",y),[3,8];case 8:return[2]}})})},d.prototype.handleSDP=function(h,b){return n(this,void 0,Promise,function(){var _,v,y,f;return r(this,function(m){switch(m.label){case 0:b=new RTCSessionDescription(b),_=this.connection.peerConnection,v=this.connection.provider,c.default.log("Setting remote description",b),y=this,m.label=1;case 1:return m.trys.push([1,5,,6]),[4,_.setRemoteDescription(b)];case 2:return m.sent(),c.default.log("Set remoteDescription:"+h+" for:"+this.connection.peer),h!=="OFFER"?[3,4]:[4,y._makeAnswer()];case 3:m.sent(),m.label=4;case 4:return[3,6];case 5:return f=m.sent(),v.emitError(u.PeerErrorType.WebRTC,f),c.default.log("Failed to setRemoteDescription, ",f),[3,6];case 6:return[2]}})})},d.prototype.handleCandidate=function(h){return n(this,void 0,Promise,function(){var b,_,v,y,f,m;return r(this,function(p){switch(p.label){case 0:c.default.log("handleCandidate:",h),b=h.candidate,_=h.sdpMLineIndex,v=h.sdpMid,y=this.connection.peerConnection,f=this.connection.provider,p.label=1;case 1:return p.trys.push([1,3,,4]),[4,y.addIceCandidate(new RTCIceCandidate({sdpMid:v,sdpMLineIndex:_,candidate:b}))];case 2:return p.sent(),c.default.log("Added ICE candidate for:"+this.connection.peer),[3,4];case 3:return m=p.sent(),f.emitError(u.PeerErrorType.WebRTC,m),c.default.log("Failed to handleCandidate, ",m),[3,4];case 4:return[2]}})})},d.prototype._addTracksToConnection=function(h,b){if(c.default.log("add tracks from stream "+h.id+" to peer connection"),!b.addTrack)return c.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");h.getTracks().forEach(function(_){b.addTrack(_,h)})},d.prototype._addStreamToMediaConnection=function(h,b){c.default.log("add stream "+h.id+" to media connection "+b.connectionId),b.addStream(h)},d}();t.Negotiator=l},{"./util":"BHXf","./logger":"WOs9","./enums":"ZRYf"}],tQFK:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var s=function(a,c){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,l){u.__proto__=l}||function(u,l){for(var d in l)Object.prototype.hasOwnProperty.call(l,d)&&(u[d]=l[d])})(a,c)};return function(a,c){if(typeof c!="function"&&c!==null)throw new TypeError("Class extends value "+String(c)+" is not a constructor or null");function u(){this.constructor=a}s(a,c),a.prototype=c===null?Object.create(c):(u.prototype=c.prototype,new u)}}();Object.defineProperty(t,"__esModule",{value:!0}),t.BaseConnection=void 0;var n=o("eventemitter3"),r=function(s){function a(c,u,l){var d=s.call(this)||this;return d.peer=c,d.provider=u,d.options=l,d._open=!1,d.metadata=l.metadata,d}return i(a,s),Object.defineProperty(a.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),a}(n.EventEmitter);t.BaseConnection=r},{eventemitter3:"JJlS"}],dbHP:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var b=function(_,v){return(b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,f){y.__proto__=f}||function(y,f){for(var m in f)Object.prototype.hasOwnProperty.call(f,m)&&(y[m]=f[m])})(_,v)};return function(_,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function y(){this.constructor=_}b(_,v),_.prototype=v===null?Object.create(v):(y.prototype=v.prototype,new y)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(b){for(var _,v=1,y=arguments.length;v<y;v++)for(var f in _=arguments[v])Object.prototype.hasOwnProperty.call(_,f)&&(b[f]=_[f]);return b}).apply(this,arguments)},r=this&&this.__values||function(b){var _=typeof Symbol=="function"&&Symbol.iterator,v=_&&b[_],y=0;if(v)return v.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&y>=b.length&&(b=void 0),{value:b&&b[y++],done:!b}}};throw new TypeError(_?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(t,"__esModule",{value:!0}),t.MediaConnection=void 0;var a=o("./util"),c=s(o("./logger")),u=o("./negotiator"),l=o("./enums"),d=o("./baseconnection"),h=function(b){function _(v,y,f){var m=b.call(this,v,y,f)||this;return m._localStream=m.options._stream,m.connectionId=m.options.connectionId||_.ID_PREFIX+a.util.randomToken(),m._negotiator=new u.Negotiator(m),m._localStream&&m._negotiator.startConnection({_stream:m._localStream,originator:!0}),m}return i(_,b),Object.defineProperty(_.prototype,"type",{get:function(){return l.ConnectionType.Media},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),_.prototype.addStream=function(v){c.default.log("Receiving stream",v),this._remoteStream=v,b.prototype.emit.call(this,l.ConnectionEventType.Stream,v)},_.prototype.handleMessage=function(v){var y=v.type,f=v.payload;switch(v.type){case l.ServerMessageType.Answer:this._negotiator.handleSDP(y,f.sdp),this._open=!0;break;case l.ServerMessageType.Candidate:this._negotiator.handleCandidate(f.candidate);break;default:c.default.warn("Unrecognized message type:"+y+" from peer:"+this.peer)}},_.prototype.answer=function(v,y){var f,m;if(y===void 0&&(y={}),this._localStream)c.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");else{this._localStream=v,y&&y.sdpTransform&&(this.options.sdpTransform=y.sdpTransform),this._negotiator.startConnection(n(n({},this.options._payload),{_stream:v}));var p=this.provider._getMessages(this.connectionId);try{for(var g=r(p),x=g.next();!x.done;x=g.next()){var C=x.value;this.handleMessage(C)}}catch(T){f={error:T}}finally{try{x&&!x.done&&(m=g.return)&&m.call(g)}finally{if(f)throw f.error}}this._open=!0}},_.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,b.prototype.emit.call(this,l.ConnectionEventType.Close))},_.ID_PREFIX="mc_",_}(d.BaseConnection);t.MediaConnection=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK"}],GGp6:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var c=function(u,l){return(c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,h){d.__proto__=h}||function(d,h){for(var b in h)Object.prototype.hasOwnProperty.call(h,b)&&(d[b]=h[b])})(u,l)};return function(u,l){if(typeof l!="function"&&l!==null)throw new TypeError("Class extends value "+String(l)+" is not a constructor or null");function d(){this.constructor=u}c(u,l),u.prototype=l===null?Object.create(l):(d.prototype=l.prototype,new d)}}(),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=o("eventemitter3"),s=n(o("./logger")),a=function(c){function u(){var l=c.call(this)||this;return l.fileReader=new FileReader,l._queue=[],l._processing=!1,l.fileReader.onload=function(d){l._processing=!1,d.target&&l.emit("done",d.target.result),l.doNextTask()},l.fileReader.onerror=function(d){s.default.error("EncodingQueue error:",d),l._processing=!1,l.destroy(),l.emit("error",d)},l}return i(u,c),Object.defineProperty(u.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),u.prototype.enque=function(l){this.queue.push(l),this.processing||this.doNextTask()},u.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},u.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},u}(r.EventEmitter);t.EncodingQueue=a},{eventemitter3:"JJlS","./logger":"WOs9"}],GBTQ:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var b=function(_,v){return(b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,f){y.__proto__=f}||function(y,f){for(var m in f)Object.prototype.hasOwnProperty.call(f,m)&&(y[m]=f[m])})(_,v)};return function(_,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function y(){this.constructor=_}b(_,v),_.prototype=v===null?Object.create(v):(y.prototype=v.prototype,new y)}}(),n=this&&this.__values||function(b){var _=typeof Symbol=="function"&&Symbol.iterator,v=_&&b[_],y=0;if(v)return v.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&y>=b.length&&(b=void 0),{value:b&&b[y++],done:!b}}};throw new TypeError(_?"Object is not iterable.":"Symbol.iterator is not defined.")},r=this&&this.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnection=void 0;var s=o("./util"),a=r(o("./logger")),c=o("./negotiator"),u=o("./enums"),l=o("./baseconnection"),d=o("./encodingQueue"),h=function(b){function _(v,y,f){var m=b.call(this,v,y,f)||this;return m.stringify=JSON.stringify,m.parse=JSON.parse,m._buffer=[],m._bufferSize=0,m._buffering=!1,m._chunkedData={},m._encodingQueue=new d.EncodingQueue,m.connectionId=m.options.connectionId||_.ID_PREFIX+s.util.randomToken(),m.label=m.options.label||m.connectionId,m.serialization=m.options.serialization||u.SerializationType.Binary,m.reliable=!!m.options.reliable,m._encodingQueue.on("done",function(p){m._bufferedSend(p)}),m._encodingQueue.on("error",function(){a.default.error("DC#"+m.connectionId+": Error occured in encoding from blob to arraybuffer, close DC"),m.close()}),m._negotiator=new c.Negotiator(m),m._negotiator.startConnection(m.options._payload||{originator:!0}),m}return i(_,b),Object.defineProperty(_.prototype,"type",{get:function(){return u.ConnectionType.Data},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),_.prototype.initialize=function(v){this._dc=v,this._configureDataChannel()},_.prototype._configureDataChannel=function(){var v=this;s.util.supports.binaryBlob&&!s.util.supports.reliable||(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){a.default.log("DC#"+v.connectionId+" dc connection success"),v._open=!0,v.emit(u.ConnectionEventType.Open)},this.dataChannel.onmessage=function(y){a.default.log("DC#"+v.connectionId+" dc onmessage:",y.data),v._handleDataMessage(y)},this.dataChannel.onclose=function(){a.default.log("DC#"+v.connectionId+" dc closed for:",v.peer),v.close()}},_.prototype._handleDataMessage=function(v){var y=this,f=v.data,m=f.constructor,p=f;if(this.serialization===u.SerializationType.Binary||this.serialization===u.SerializationType.BinaryUTF8){if(m===Blob)return void s.util.blobToArrayBuffer(f,function(x){var C=s.util.unpack(x);y.emit(u.ConnectionEventType.Data,C)});if(m===ArrayBuffer)p=s.util.unpack(f);else if(m===String){var g=s.util.binaryStringToArrayBuffer(f);p=s.util.unpack(g)}}else this.serialization===u.SerializationType.JSON&&(p=this.parse(f));p.__peerData?this._handleChunk(p):b.prototype.emit.call(this,u.ConnectionEventType.Data,p)},_.prototype._handleChunk=function(v){var y=v.__peerData,f=this._chunkedData[y]||{data:[],count:0,total:v.total};if(f.data[v.n]=v.data,f.count++,this._chunkedData[y]=f,f.total===f.count){delete this._chunkedData[y];var m=new Blob(f.data);this._handleDataMessage({data:m})}},_.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,b.prototype.emit.call(this,u.ConnectionEventType.Close))},_.prototype.send=function(v,y){if(this.open)if(this.serialization===u.SerializationType.JSON)this._bufferedSend(this.stringify(v));else if(this.serialization===u.SerializationType.Binary||this.serialization===u.SerializationType.BinaryUTF8){var f=s.util.pack(v);if(!y&&f.size>s.util.chunkedMTU)return void this._sendChunks(f);s.util.supports.binaryBlob?this._bufferedSend(f):this._encodingQueue.enque(f)}else this._bufferedSend(v);else b.prototype.emit.call(this,u.ConnectionEventType.Error,new Error("Connection is not open. You should listen for the `open` event before sending messages."))},_.prototype._bufferedSend=function(v){!this._buffering&&this._trySend(v)||(this._buffer.push(v),this._bufferSize=this._buffer.length)},_.prototype._trySend=function(v){var y=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>_.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){y._buffering=!1,y._tryBuffer()},50),!1;try{this.dataChannel.send(v)}catch(f){return a.default.error("DC#:"+this.connectionId+" Error when sending:",f),this._buffering=!0,this.close(),!1}return!0},_.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var v=this._buffer[0];this._trySend(v)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},_.prototype._sendChunks=function(v){var y,f,m=s.util.chunk(v);a.default.log("DC#"+this.connectionId+" Try to send "+m.length+" chunks...");try{for(var p=n(m),g=p.next();!g.done;g=p.next()){var x=g.value;this.send(x,!0)}}catch(C){y={error:C}}finally{try{g&&!g.done&&(f=p.return)&&f.call(p)}finally{if(y)throw y.error}}},_.prototype.handleMessage=function(v){var y=v.payload;switch(v.type){case u.ServerMessageType.Answer:this._negotiator.handleSDP(v.type,y.sdp);break;case u.ServerMessageType.Candidate:this._negotiator.handleCandidate(y.candidate);break;default:a.default.warn("Unrecognized message type:",v.type,"from peer:",this.peer)}},_.ID_PREFIX="dc_",_.MAX_BUFFERED_AMOUNT=8388608,_}(l.BaseConnection);t.DataConnection=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK","./encodingQueue":"GGp6"}],in7L:[function(o,e,t){"use strict";var i=this&&this.__awaiter||function(u,l,d,h){return new(d||(d=Promise))(function(b,_){function v(m){try{f(h.next(m))}catch(p){_(p)}}function y(m){try{f(h.throw(m))}catch(p){_(p)}}function f(m){var p;m.done?b(m.value):(p=m.value,p instanceof d?p:new d(function(g){g(p)})).then(v,y)}f((h=h.apply(u,l||[])).next())})},n=this&&this.__generator||function(u,l){var d,h,b,_,v={label:0,sent:function(){if(1&b[0])throw b[1];return b[1]},trys:[],ops:[]};return _={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(_[Symbol.iterator]=function(){return this}),_;function y(f){return function(m){return function(p){if(d)throw new TypeError("Generator is already executing.");for(;v;)try{if(d=1,h&&(b=2&p[0]?h.return:p[0]?h.throw||((b=h.return)&&b.call(h),0):h.next)&&!(b=b.call(h,p[1])).done)return b;switch(h=0,b&&(p=[2&p[0],b.value]),p[0]){case 0:case 1:b=p;break;case 4:return v.label++,{value:p[1],done:!1};case 5:v.label++,h=p[1],p=[0];continue;case 7:p=v.ops.pop(),v.trys.pop();continue;default:if(!(b=(b=v.trys).length>0&&b[b.length-1])&&(p[0]===6||p[0]===2)){v=0;continue}if(p[0]===3&&(!b||p[1]>b[0]&&p[1]<b[3])){v.label=p[1];break}if(p[0]===6&&v.label<b[1]){v.label=b[1],b=p;break}if(b&&v.label<b[2]){v.label=b[2],v.ops.push(p);break}b[2]&&v.ops.pop(),v.trys.pop();continue}p=l.call(u,v)}catch(g){p=[6,g],h=0}finally{d=b=0}if(5&p[0])throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}([f,m])}}},r=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.API=void 0;var s=o("./util"),a=r(o("./logger")),c=function(){function u(l){this._options=l}return u.prototype._buildUrl=function(l){var d=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+l;return d+="?ts="+new Date().getTime()+Math.random()},u.prototype.retrieveId=function(){return i(this,void 0,Promise,function(){var l,d,h,b;return n(this,function(_){switch(_.label){case 0:l=this._buildUrl("id"),_.label=1;case 1:return _.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((d=_.sent()).status!==200)throw new Error("Error. Status:"+d.status);return[2,d.text()];case 3:throw h=_.sent(),a.default.error("Error retrieving ID",h),b="",this._options.path==="/"&&this._options.host!==s.util.CLOUD_HOST&&(b=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+b);case 4:return[2]}})})},u.prototype.listAllPeers=function(){return i(this,void 0,Promise,function(){var l,d,h,b;return n(this,function(_){switch(_.label){case 0:l=this._buildUrl("peers"),_.label=1;case 1:return _.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((d=_.sent()).status!==200)throw d.status===401?(h="",h=this._options.host===s.util.CLOUD_HOST?"It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":"You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+h)):new Error("Error. Status:"+d.status);return[2,d.json()];case 3:throw b=_.sent(),a.default.error("Error retrieving list peers",b),new Error("Could not get list peers from the server."+b);case 4:return[2]}})})},u}();t.API=c},{"./util":"BHXf","./logger":"WOs9"}],Hxpd:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var m=function(p,g){return(m=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(x,C){x.__proto__=C}||function(x,C){for(var T in C)Object.prototype.hasOwnProperty.call(C,T)&&(x[T]=C[T])})(p,g)};return function(p,g){if(typeof g!="function"&&g!==null)throw new TypeError("Class extends value "+String(g)+" is not a constructor or null");function x(){this.constructor=p}m(p,g),p.prototype=g===null?Object.create(g):(x.prototype=g.prototype,new x)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(m){for(var p,g=1,x=arguments.length;g<x;g++)for(var C in p=arguments[g])Object.prototype.hasOwnProperty.call(p,C)&&(m[C]=p[C]);return m}).apply(this,arguments)},r=this&&this.__values||function(m){var p=typeof Symbol=="function"&&Symbol.iterator,g=p&&m[p],x=0;if(g)return g.call(m);if(m&&typeof m.length=="number")return{next:function(){return m&&x>=m.length&&(m=void 0),{value:m&&m[x++],done:!m}}};throw new TypeError(p?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__read||function(m,p){var g=typeof Symbol=="function"&&m[Symbol.iterator];if(!g)return m;var x,C,T=g.call(m),S=[];try{for(;(p===void 0||p-- >0)&&!(x=T.next()).done;)S.push(x.value)}catch(D){C={error:D}}finally{try{x&&!x.done&&(g=T.return)&&g.call(T)}finally{if(C)throw C.error}}return S},a=this&&this.__importDefault||function(m){return m&&m.__esModule?m:{default:m}};Object.defineProperty(t,"__esModule",{value:!0}),t.Peer=void 0;var c=o("eventemitter3"),u=o("./util"),l=a(o("./logger")),d=o("./socket"),h=o("./mediaconnection"),b=o("./dataconnection"),_=o("./enums"),v=o("./api"),y=function(){return function(){}}(),f=function(m){function p(g,x){var C,T=m.call(this)||this;return T._id=null,T._lastServerId=null,T._destroyed=!1,T._disconnected=!1,T._open=!1,T._connections=new Map,T._lostMessages=new Map,g&&g.constructor==Object?x=g:g&&(C=g.toString()),x=n({debug:0,host:u.util.CLOUD_HOST,port:u.util.CLOUD_PORT,path:"/",key:p.DEFAULT_KEY,token:u.util.randomToken(),config:u.util.defaultConfig},x),T._options=x,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!==u.util.CLOUD_HOST?T._options.secure=u.util.isSecure():T._options.host==u.util.CLOUD_HOST&&(T._options.secure=!0),T._options.logFunction&&l.default.setLogFunction(T._options.logFunction),l.default.logLevel=T._options.debug||0,T._api=new v.API(x),T._socket=T._createServerConnection(),u.util.supports.audioVideo||u.util.supports.data?C&&!u.util.validateId(C)?(T._delayedAbort(_.PeerErrorType.InvalidID,'ID "'+C+'" is invalid'),T):(C?T._initialize(C):T._api.retrieveId().then(function(S){return T._initialize(S)}).catch(function(S){return T._abort(_.PeerErrorType.ServerError,S)}),T):(T._delayedAbort(_.PeerErrorType.BrowserIncompatible,"The current browser does not support WebRTC"),T)}return i(p,m),Object.defineProperty(p.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"connections",{get:function(){var g,x,C=Object.create(null);try{for(var T=r(this._connections),S=T.next();!S.done;S=T.next()){var D=s(S.value,2),A=D[0],P=D[1];C[A]=P}}catch(H){g={error:H}}finally{try{S&&!S.done&&(x=T.return)&&x.call(T)}finally{if(g)throw g.error}}return C},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),p.prototype._createServerConnection=function(){var g=this,x=new d.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return x.on(_.SocketEventType.Message,function(C){g._handleMessage(C)}),x.on(_.SocketEventType.Error,function(C){g._abort(_.PeerErrorType.SocketError,C)}),x.on(_.SocketEventType.Disconnected,function(){g.disconnected||(g.emitError(_.PeerErrorType.Network,"Lost connection to server."),g.disconnect())}),x.on(_.SocketEventType.Close,function(){g.disconnected||g._abort(_.PeerErrorType.SocketClosed,"Underlying socket is already closed.")}),x},p.prototype._initialize=function(g){this._id=g,this.socket.start(g,this._options.token)},p.prototype._handleMessage=function(g){var x,C,T=g.type,S=g.payload,D=g.src;switch(T){case _.ServerMessageType.Open:this._lastServerId=this.id,this._open=!0,this.emit(_.PeerEventType.Open,this.id);break;case _.ServerMessageType.Error:this._abort(_.PeerErrorType.ServerError,S.msg);break;case _.ServerMessageType.IdTaken:this._abort(_.PeerErrorType.UnavailableID,'ID "'+this.id+'" is taken');break;case _.ServerMessageType.InvalidKey:this._abort(_.PeerErrorType.InvalidKey,'API KEY "'+this._options.key+'" is invalid');break;case _.ServerMessageType.Leave:l.default.log("Received leave message from "+D),this._cleanupPeer(D),this._connections.delete(D);break;case _.ServerMessageType.Expire:this.emitError(_.PeerErrorType.PeerUnavailable,"Could not connect to peer "+D);break;case _.ServerMessageType.Offer:var A=S.connectionId;if((W=this.getConnection(D,A))&&(W.close(),l.default.warn("Offer received for existing Connection ID:"+A)),S.type===_.ConnectionType.Media)W=new h.MediaConnection(D,this,{connectionId:A,_payload:S,metadata:S.metadata}),this._addConnection(D,W),this.emit(_.PeerEventType.Call,W);else{if(S.type!==_.ConnectionType.Data)return void l.default.warn("Received malformed connection type:"+S.type);W=new b.DataConnection(D,this,{connectionId:A,_payload:S,metadata:S.metadata,label:S.label,serialization:S.serialization,reliable:S.reliable}),this._addConnection(D,W),this.emit(_.PeerEventType.Connection,W)}var P=this._getMessages(A);try{for(var H=r(P),B=H.next();!B.done;B=H.next()){var N=B.value;W.handleMessage(N)}}catch(re){x={error:re}}finally{try{B&&!B.done&&(C=H.return)&&C.call(H)}finally{if(x)throw x.error}}break;default:if(!S)return void l.default.warn("You received a malformed message from "+D+" of type "+T);var W;A=S.connectionId,(W=this.getConnection(D,A))&&W.peerConnection?W.handleMessage(g):A?this._storeMessage(A,g):l.default.warn("You received an unrecognized message:",g)}},p.prototype._storeMessage=function(g,x){this._lostMessages.has(g)||this._lostMessages.set(g,[]),this._lostMessages.get(g).push(x)},p.prototype._getMessages=function(g){var x=this._lostMessages.get(g);return x?(this._lostMessages.delete(g),x):[]},p.prototype.connect=function(g,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, or call reconnect on this peer if you believe its ID to still be available."),void this.emitError(_.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");var C=new b.DataConnection(g,this,x);return this._addConnection(g,C),C},p.prototype.call=function(g,x,C){if(C===void 0&&(C={}),this.disconnected)return l.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),void this.emitError(_.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");if(x){C._stream=x;var T=new h.MediaConnection(g,this,C);return this._addConnection(g,T),T}l.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.")},p.prototype._addConnection=function(g,x){l.default.log("add connection "+x.type+":"+x.connectionId+" to peerId:"+g),this._connections.has(g)||this._connections.set(g,[]),this._connections.get(g).push(x)},p.prototype._removeConnection=function(g){var x=this._connections.get(g.peer);if(x){var C=x.indexOf(g);C!==-1&&x.splice(C,1)}this._lostMessages.delete(g.connectionId)},p.prototype.getConnection=function(g,x){var C,T,S=this._connections.get(g);if(!S)return null;try{for(var D=r(S),A=D.next();!A.done;A=D.next()){var P=A.value;if(P.connectionId===x)return P}}catch(H){C={error:H}}finally{try{A&&!A.done&&(T=D.return)&&T.call(D)}finally{if(C)throw C.error}}return null},p.prototype._delayedAbort=function(g,x){var C=this;setTimeout(function(){C._abort(g,x)},0)},p.prototype._abort=function(g,x){l.default.error("Aborting!"),this.emitError(g,x),this._lastServerId?this.disconnect():this.destroy()},p.prototype.emitError=function(g,x){var C;l.default.error("Error:",x),(C=typeof x=="string"?new Error(x):x).type=g,this.emit(_.PeerEventType.Error,C)},p.prototype.destroy=function(){this.destroyed||(l.default.log("Destroy peer with ID:"+this.id),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit(_.PeerEventType.Close))},p.prototype._cleanup=function(){var g,x;try{for(var C=r(this._connections.keys()),T=C.next();!T.done;T=C.next()){var S=T.value;this._cleanupPeer(S),this._connections.delete(S)}}catch(D){g={error:D}}finally{try{T&&!T.done&&(x=C.return)&&x.call(C)}finally{if(g)throw g.error}}this.socket.removeAllListeners()},p.prototype._cleanupPeer=function(g){var x,C,T=this._connections.get(g);if(T)try{for(var S=r(T),D=S.next();!D.done;D=S.next())D.value.close()}catch(A){x={error:A}}finally{try{D&&!D.done&&(C=S.return)&&C.call(S)}finally{if(x)throw x.error}}},p.prototype.disconnect=function(){if(!this.disconnected){var g=this.id;l.default.log("Disconnect peer with ID:"+g),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=g,this._id=null,this.emit(_.PeerEventType.Disconnected,g)}},p.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)l.default.log("Attempting reconnection to server with ID "+this._lastServerId),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(this.disconnected||this.open)throw new Error("Peer "+this.id+" cannot reconnect because it is not disconnected from the server!");l.default.error("In a hurry? We're still trying to make the initial connection!")}},p.prototype.listAllPeers=function(g){var x=this;g===void 0&&(g=function(C){}),this._api.listAllPeers().then(function(C){return g(C)}).catch(function(C){return x._abort(_.PeerErrorType.ServerError,C)})},p.DEFAULT_KEY="peerjs",p}(c.EventEmitter);t.Peer=f},{eventemitter3:"JJlS","./util":"BHXf","./logger":"WOs9","./socket":"wJlv","./mediaconnection":"dbHP","./dataconnection":"GBTQ","./enums":"ZRYf","./api":"in7L"}],iTK6:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.peerjs=void 0;var i=o("./util"),n=o("./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 cp=ms((qE,lp)=>{(function(){var o="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],s=0;s<4;s++)n*8+s*6<=t.length*8?i.push(o.charAt(r>>>6*(3-s)&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((o.indexOf(t.charAt(n-1))&Math.pow(2,-2*r+8)-1)<<r*2|o.indexOf(t.charAt(n))>>>6-r*2);return i}};lp.exports=e})()});var Bc=ms((YE,up)=>{var Fc={utf8:{stringToBytes:function(o){return Fc.bin.stringToBytes(unescape(encodeURIComponent(o)))},bytesToString:function(o){return decodeURIComponent(escape(Fc.bin.bytesToString(o)))}},bin:{stringToBytes:function(o){for(var e=[],t=0;t<o.length;t++)e.push(o.charCodeAt(t)&255);return e},bytesToString:function(o){for(var e=[],t=0;t<o.length;t++)e.push(String.fromCharCode(o[t]));return e.join("")}}};up.exports=Fc});var pp=ms((KE,hp)=>{hp.exports=function(o){return o!=null&&(dp(o)||Fg(o)||!!o._isBuffer)};function dp(o){return!!o.constructor&&typeof o.constructor.isBuffer=="function"&&o.constructor.isBuffer(o)}function Fg(o){return typeof o.readFloatLE=="function"&&typeof o.slice=="function"&&dp(o.slice(0,0))}});var mp=ms((JE,fp)=>{(function(){var o=cp(),e=Bc().utf8,t=pp(),i=Bc().bin,n=function(r,s){r.constructor==String?s&&s.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 a=o.bytesToWords(r),c=r.length*8,u=1732584193,l=-271733879,d=-1732584194,h=271733878,b=0;b<a.length;b++)a[b]=(a[b]<<8|a[b]>>>24)&16711935|(a[b]<<24|a[b]>>>8)&4278255360;a[c>>>5]|=128<<c%32,a[(c+64>>>9<<4)+14]=c;for(var _=n._ff,v=n._gg,y=n._hh,f=n._ii,b=0;b<a.length;b+=16){var m=u,p=l,g=d,x=h;u=_(u,l,d,h,a[b+0],7,-680876936),h=_(h,u,l,d,a[b+1],12,-389564586),d=_(d,h,u,l,a[b+2],17,606105819),l=_(l,d,h,u,a[b+3],22,-1044525330),u=_(u,l,d,h,a[b+4],7,-176418897),h=_(h,u,l,d,a[b+5],12,1200080426),d=_(d,h,u,l,a[b+6],17,-1473231341),l=_(l,d,h,u,a[b+7],22,-45705983),u=_(u,l,d,h,a[b+8],7,1770035416),h=_(h,u,l,d,a[b+9],12,-1958414417),d=_(d,h,u,l,a[b+10],17,-42063),l=_(l,d,h,u,a[b+11],22,-1990404162),u=_(u,l,d,h,a[b+12],7,1804603682),h=_(h,u,l,d,a[b+13],12,-40341101),d=_(d,h,u,l,a[b+14],17,-1502002290),l=_(l,d,h,u,a[b+15],22,1236535329),u=v(u,l,d,h,a[b+1],5,-165796510),h=v(h,u,l,d,a[b+6],9,-1069501632),d=v(d,h,u,l,a[b+11],14,643717713),l=v(l,d,h,u,a[b+0],20,-373897302),u=v(u,l,d,h,a[b+5],5,-701558691),h=v(h,u,l,d,a[b+10],9,38016083),d=v(d,h,u,l,a[b+15],14,-660478335),l=v(l,d,h,u,a[b+4],20,-405537848),u=v(u,l,d,h,a[b+9],5,568446438),h=v(h,u,l,d,a[b+14],9,-1019803690),d=v(d,h,u,l,a[b+3],14,-187363961),l=v(l,d,h,u,a[b+8],20,1163531501),u=v(u,l,d,h,a[b+13],5,-1444681467),h=v(h,u,l,d,a[b+2],9,-51403784),d=v(d,h,u,l,a[b+7],14,1735328473),l=v(l,d,h,u,a[b+12],20,-1926607734),u=y(u,l,d,h,a[b+5],4,-378558),h=y(h,u,l,d,a[b+8],11,-2022574463),d=y(d,h,u,l,a[b+11],16,1839030562),l=y(l,d,h,u,a[b+14],23,-35309556),u=y(u,l,d,h,a[b+1],4,-1530992060),h=y(h,u,l,d,a[b+4],11,1272893353),d=y(d,h,u,l,a[b+7],16,-155497632),l=y(l,d,h,u,a[b+10],23,-1094730640),u=y(u,l,d,h,a[b+13],4,681279174),h=y(h,u,l,d,a[b+0],11,-358537222),d=y(d,h,u,l,a[b+3],16,-722521979),l=y(l,d,h,u,a[b+6],23,76029189),u=y(u,l,d,h,a[b+9],4,-640364487),h=y(h,u,l,d,a[b+12],11,-421815835),d=y(d,h,u,l,a[b+15],16,530742520),l=y(l,d,h,u,a[b+2],23,-995338651),u=f(u,l,d,h,a[b+0],6,-198630844),h=f(h,u,l,d,a[b+7],10,1126891415),d=f(d,h,u,l,a[b+14],15,-1416354905),l=f(l,d,h,u,a[b+5],21,-57434055),u=f(u,l,d,h,a[b+12],6,1700485571),h=f(h,u,l,d,a[b+3],10,-1894986606),d=f(d,h,u,l,a[b+10],15,-1051523),l=f(l,d,h,u,a[b+1],21,-2054922799),u=f(u,l,d,h,a[b+8],6,1873313359),h=f(h,u,l,d,a[b+15],10,-30611744),d=f(d,h,u,l,a[b+6],15,-1560198380),l=f(l,d,h,u,a[b+13],21,1309151649),u=f(u,l,d,h,a[b+4],6,-145523070),h=f(h,u,l,d,a[b+11],10,-1120210379),d=f(d,h,u,l,a[b+2],15,718787259),l=f(l,d,h,u,a[b+9],21,-343485551),u=u+m>>>0,l=l+p>>>0,d=d+g>>>0,h=h+x>>>0}return o.endian([u,l,d,h])};n._ff=function(r,s,a,c,u,l,d){var h=r+(s&a|~s&c)+(u>>>0)+d;return(h<<l|h>>>32-l)+s},n._gg=function(r,s,a,c,u,l,d){var h=r+(s&c|a&~c)+(u>>>0)+d;return(h<<l|h>>>32-l)+s},n._hh=function(r,s,a,c,u,l,d){var h=r+(s^a^c)+(u>>>0)+d;return(h<<l|h>>>32-l)+s},n._ii=function(r,s,a,c,u,l,d){var h=r+(a^(s|~c))+(u>>>0)+d;return(h<<l|h>>>32-l)+s},n._blocksize=16,n._digestsize=16,fp.exports=function(r,s){if(r==null)throw new Error("Illegal argument "+r);var a=o.wordsToBytes(n(r,s));return s&&s.asBytes?a:s&&s.asString?i.bytesToString(a):o.bytesToHex(a)}})()});import{DepthTexture as sb,WebGLRenderer as ab}from"three";import*as Re from"three";import*as si from"three";var nc=()=>o=>o;var Wn=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]}},rc=!1,tc=[];setTimeout(()=>{rc&&console.log(tc)},100);function oc(){return new URLSearchParams(window.location.search)}function M(o){rc&&!tc.includes(o)&&tc.push(o);let e=oc();if(e.has(o)){let t=e.get(o);return t||!0}return!1}rc=M("help")===!0;function Co(o,e,t){o.has(e)?o.set(e,t.toString()):o.append(e,t.toString())}function sh(o,e){window.history.replaceState(null,o,"?"+e.toString())}function ah(o,e){return Math.floor(Math.random()*(e-o+1))+o}var rh=["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"],oh=["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 lh(){let o=rh[Math.floor(Math.random()*rh.length)],e=oh[Math.floor(Math.random()*oh.length)];return o+"_"+e}function ch(o){return o=o.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),o.trim()}function Nn(o,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===o)return e;if(e.guid==o)return e;if(i&&e.userData?.components){for(let n of e.userData.components)if(n.guid===o)return n}if(t){if(e.scenes)for(let n in e.scenes){let r=e.scenes[n],s=Nn(o,r,t,i);if(s)return s}if(e.children)for(let n in e.children){let r=e.children[n],s=Nn(o,r,t,i);if(s)return s}}}function gs(o,e){if(o!=null&&typeof o=="object"){let t;Array.isArray(o)?t=[]:(t=Object.create(o),Object.assign(t,o));for(let i of Object.keys(o)){let n=o[i];e&&!e(o,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=gs(n,e)}return t}return o}function uh(o){return new Promise((e,t)=>{setTimeout(e,o)})}var ec=M("debugsourcepath");function Oi(o,e){if(o===void 0)return ec&&console.warn("getPath: source is undefined, returning uri",e),e;if(e.startsWith("http"))return ec&&console.warn("getPath: uri is absolute, returning uri",e),e;let t=o.lastIndexOf("/");if(t>=0){let i=o.substring(0,t+1),n=e.lastIndexOf("/");return n>=0?i+=e.substring(n+1):i+=e,ec&&console.log("getPath:",o,` - changed uri from
|
|
78
|
+
isUnifiedPlanSupported:`+this.isUnifiedPlanSupported()},n}())},{"./adapter":"sXtV"}],BHXf:[function(o,e,t){"use strict";var i=this&&this.__createBinding||(Object.create?function(u,l,d,h){h===void 0&&(h=d),Object.defineProperty(u,h,{enumerable:!0,get:function(){return l[d]}})}:function(u,l,d,h){h===void 0&&(h=d),u[h]=l[d]}),n=this&&this.__setModuleDefault||(Object.create?function(u,l){Object.defineProperty(u,"default",{enumerable:!0,value:l})}:function(u,l){u.default=l}),r=this&&this.__importStar||function(u){if(u&&u.__esModule)return u;var l={};if(u!=null)for(var d in u)d!=="default"&&Object.prototype.hasOwnProperty.call(u,d)&&i(l,u,d);return n(l,u),l};Object.defineProperty(t,"__esModule",{value:!0}),t.util=void 0;var s=r(o("peerjs-js-binarypack")),a=o("./supports"),c={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:"turn:0.peerjs.com:3478",username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"};t.util=new(function(){function u(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=c,this.browser=a.Supports.getBrowser(),this.browserVersion=a.Supports.getVersion(),this.supports=function(){var l,d={browser:a.Supports.isBrowserSupported(),webRTC:a.Supports.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!d.webRTC)return d;try{l=new RTCPeerConnection(c),d.audioVideo=!0;var h=void 0;try{h=l.createDataChannel("_PEERJSTEST",{ordered:!0}),d.data=!0,d.reliable=!!h.ordered;try{h.binaryType="blob",d.binaryBlob=!a.Supports.isIOS}catch{}}catch{}finally{h&&h.close()}}catch{}finally{l&&l.close()}return d}(),this.pack=s.pack,this.unpack=s.unpack,this._dataCount=1}return u.prototype.noop=function(){},u.prototype.validateId=function(l){return!l||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(l)},u.prototype.chunk=function(l){for(var d=[],h=l.size,b=Math.ceil(h/t.util.chunkedMTU),_=0,v=0;v<h;){var y=Math.min(h,v+t.util.chunkedMTU),f=l.slice(v,y),m={__peerData:this._dataCount,n:_,data:f,total:b};d.push(m),v=y,_++}return this._dataCount++,d},u.prototype.blobToArrayBuffer=function(l,d){var h=new FileReader;return h.onload=function(b){b.target&&d(b.target.result)},h.readAsArrayBuffer(l),h},u.prototype.binaryStringToArrayBuffer=function(l){for(var d=new Uint8Array(l.length),h=0;h<l.length;h++)d[h]=255&l.charCodeAt(h);return d.buffer},u.prototype.randomToken=function(){return Math.random().toString(36).substr(2)},u.prototype.isSecure=function(){return location.protocol==="https:"},u}())},{"peerjs-js-binarypack":"kdPp","./supports":"I31f"}],JJlS:[function(o,e,t){"use strict";var i=Object.prototype.hasOwnProperty,n="~";function r(){}function s(l,d,h){this.fn=l,this.context=d,this.once=h||!1}function a(l,d,h,b,_){if(typeof h!="function")throw new TypeError("The listener must be a function");var v=new s(h,b||l,_),y=n?n+d:d;return l._events[y]?l._events[y].fn?l._events[y]=[l._events[y],v]:l._events[y].push(v):(l._events[y]=v,l._eventsCount++),l}function c(l,d){--l._eventsCount==0?l._events=new r:delete l._events[d]}function u(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1)),u.prototype.eventNames=function(){var l,d,h=[];if(this._eventsCount===0)return h;for(d in l=this._events)i.call(l,d)&&h.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(l)):h},u.prototype.listeners=function(l){var d=n?n+l:l,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var b=0,_=h.length,v=new Array(_);b<_;b++)v[b]=h[b].fn;return v},u.prototype.listenerCount=function(l){var d=n?n+l:l,h=this._events[d];return h?h.fn?1:h.length:0},u.prototype.emit=function(l,d,h,b,_,v){var y=n?n+l:l;if(!this._events[y])return!1;var f,m,p=this._events[y],g=arguments.length;if(p.fn){switch(p.once&&this.removeListener(l,p.fn,void 0,!0),g){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,d),!0;case 3:return p.fn.call(p.context,d,h),!0;case 4:return p.fn.call(p.context,d,h,b),!0;case 5:return p.fn.call(p.context,d,h,b,_),!0;case 6:return p.fn.call(p.context,d,h,b,_,v),!0}for(m=1,f=new Array(g-1);m<g;m++)f[m-1]=arguments[m];p.fn.apply(p.context,f)}else{var w,C=p.length;for(m=0;m<C;m++)switch(p[m].once&&this.removeListener(l,p[m].fn,void 0,!0),g){case 1:p[m].fn.call(p[m].context);break;case 2:p[m].fn.call(p[m].context,d);break;case 3:p[m].fn.call(p[m].context,d,h);break;case 4:p[m].fn.call(p[m].context,d,h,b);break;default:if(!f)for(w=1,f=new Array(g-1);w<g;w++)f[w-1]=arguments[w];p[m].fn.apply(p[m].context,f)}}return!0},u.prototype.on=function(l,d,h){return a(this,l,d,h,!1)},u.prototype.once=function(l,d,h){return a(this,l,d,h,!0)},u.prototype.removeListener=function(l,d,h,b){var _=n?n+l:l;if(!this._events[_])return this;if(!d)return c(this,_),this;var v=this._events[_];if(v.fn)v.fn!==d||b&&!v.once||h&&v.context!==h||c(this,_);else{for(var y=0,f=[],m=v.length;y<m;y++)(v[y].fn!==d||b&&!v[y].once||h&&v[y].context!==h)&&f.push(v[y]);f.length?this._events[_]=f.length===1?f[0]:f:c(this,_)}return this},u.prototype.removeAllListeners=function(l){var d;return l?(d=n?n+l:l,this._events[d]&&c(this,d)):(this._events=new r,this._eventsCount=0),this},u.prototype.off=u.prototype.removeListener,u.prototype.addListener=u.prototype.on,u.prefixed=n,u.EventEmitter=u,typeof e<"u"&&(e.exports=u)},{}],WOs9:[function(o,e,t){"use strict";var i=this&&this.__read||function(c,u){var l=typeof Symbol=="function"&&c[Symbol.iterator];if(!l)return c;var d,h,b=l.call(c),_=[];try{for(;(u===void 0||u-- >0)&&!(d=b.next()).done;)_.push(d.value)}catch(v){h={error:v}}finally{try{d&&!d.done&&(l=b.return)&&l.call(b)}finally{if(h)throw h.error}}return _},n=this&&this.__spreadArray||function(c,u){for(var l=0,d=u.length,h=c.length;l<d;l++,h++)c[h]=u[l];return c};Object.defineProperty(t,"__esModule",{value:!0}),t.LogLevel=void 0;var r,s="PeerJS: ";(function(c){c[c.Disabled=0]="Disabled",c[c.Errors=1]="Errors",c[c.Warnings=2]="Warnings",c[c.All=3]="All"})(r=t.LogLevel||(t.LogLevel={}));var a=function(){function c(){this._logLevel=r.Disabled}return Object.defineProperty(c.prototype,"logLevel",{get:function(){return this._logLevel},set:function(u){this._logLevel=u},enumerable:!1,configurable:!0}),c.prototype.log=function(){for(var u=[],l=0;l<arguments.length;l++)u[l]=arguments[l];this._logLevel>=r.All&&this._print.apply(this,n([r.All],i(u)))},c.prototype.warn=function(){for(var u=[],l=0;l<arguments.length;l++)u[l]=arguments[l];this._logLevel>=r.Warnings&&this._print.apply(this,n([r.Warnings],i(u)))},c.prototype.error=function(){for(var u=[],l=0;l<arguments.length;l++)u[l]=arguments[l];this._logLevel>=r.Errors&&this._print.apply(this,n([r.Errors],i(u)))},c.prototype.setLogFunction=function(u){this._print=u},c.prototype._print=function(u){for(var l=[],d=1;d<arguments.length;d++)l[d-1]=arguments[d];var h=n([s],i(l));for(var b in h)h[b]instanceof Error&&(h[b]="("+h[b].name+") "+h[b].message);u>=r.All?console.log.apply(console,n([],i(h))):u>=r.Warnings?console.warn.apply(console,n(["WARNING"],i(h))):u>=r.Errors&&console.error.apply(console,n(["ERROR"],i(h)))},c}();t.default=new a},{}],ZRYf:[function(o,e,t){"use strict";var i,n,r,s,a,c,u;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"}(s=t.PeerErrorType||(t.PeerErrorType={})),function(l){l.Binary="binary",l.BinaryUTF8="binary-utf8",l.JSON="json"}(a=t.SerializationType||(t.SerializationType={})),function(l){l.Message="message",l.Disconnected="disconnected",l.Error="error",l.Close="close"}(c=t.SocketEventType||(t.SocketEventType={})),function(l){l.Heartbeat="HEARTBEAT",l.Candidate="CANDIDATE",l.Offer="OFFER",l.Answer="ANSWER",l.Open="OPEN",l.Error="ERROR",l.IdTaken="ID-TAKEN",l.InvalidKey="INVALID-KEY",l.Leave="LEAVE",l.Expire="EXPIRE"}(u=t.ServerMessageType||(t.ServerMessageType={}))},{}],wJlv:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var h=function(b,_){return(h=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(v,y){v.__proto__=y}||function(v,y){for(var f in y)Object.prototype.hasOwnProperty.call(y,f)&&(v[f]=y[f])})(b,_)};return function(b,_){if(typeof _!="function"&&_!==null)throw new TypeError("Class extends value "+String(_)+" is not a constructor or null");function v(){this.constructor=b}h(b,_),b.prototype=_===null?Object.create(_):(v.prototype=_.prototype,new v)}}(),n=this&&this.__read||function(h,b){var _=typeof Symbol=="function"&&h[Symbol.iterator];if(!_)return h;var v,y,f=_.call(h),m=[];try{for(;(b===void 0||b-- >0)&&!(v=f.next()).done;)m.push(v.value)}catch(p){y={error:p}}finally{try{v&&!v.done&&(_=f.return)&&_.call(f)}finally{if(y)throw y.error}}return m},r=this&&this.__spreadArray||function(h,b){for(var _=0,v=b.length,y=h.length;_<v;_++,y++)h[y]=b[_];return h},s=this&&this.__values||function(h){var b=typeof Symbol=="function"&&Symbol.iterator,_=b&&h[b],v=0;if(_)return _.call(h);if(h&&typeof h.length=="number")return{next:function(){return h&&v>=h.length&&(h=void 0),{value:h&&h[v++],done:!h}}};throw new TypeError(b?"Object is not iterable.":"Symbol.iterator is not defined.")},a=this&&this.__importDefault||function(h){return h&&h.__esModule?h:{default:h}};Object.defineProperty(t,"__esModule",{value:!0}),t.Socket=void 0;var c=o("eventemitter3"),u=a(o("./logger")),l=o("./enums"),d=function(h){function b(_,v,y,f,m,p){p===void 0&&(p=5e3);var g=h.call(this)||this;g.pingInterval=p,g._disconnected=!0,g._messagesQueue=[];var w=_?"wss://":"ws://";return g._baseUrl=w+v+":"+y+f+"peerjs?key="+m,g}return i(b,h),b.prototype.start=function(_,v){var y=this;this._id=_;var f=this._baseUrl+"&id="+_+"&token="+v;!this._socket&&this._disconnected&&(this._socket=new WebSocket(f),this._disconnected=!1,this._socket.onmessage=function(m){var p;try{p=JSON.parse(m.data),u.default.log("Server message received:",p)}catch{return void u.default.log("Invalid server message",m.data)}y.emit(l.SocketEventType.Message,p)},this._socket.onclose=function(m){y._disconnected||(u.default.log("Socket closed.",m),y._cleanup(),y._disconnected=!0,y.emit(l.SocketEventType.Disconnected))},this._socket.onopen=function(){y._disconnected||(y._sendQueuedMessages(),u.default.log("Socket open"),y._scheduleHeartbeat())})},b.prototype._scheduleHeartbeat=function(){var _=this;this._wsPingTimer=setTimeout(function(){_._sendHeartbeat()},this.pingInterval)},b.prototype._sendHeartbeat=function(){if(this._wsOpen()){var _=JSON.stringify({type:l.ServerMessageType.Heartbeat});this._socket.send(_),this._scheduleHeartbeat()}else u.default.log("Cannot send heartbeat, because socket closed")},b.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},b.prototype._sendQueuedMessages=function(){var _,v,y=r([],n(this._messagesQueue));this._messagesQueue=[];try{for(var f=s(y),m=f.next();!m.done;m=f.next()){var p=m.value;this.send(p)}}catch(g){_={error:g}}finally{try{m&&!m.done&&(v=f.return)&&v.call(f)}finally{if(_)throw _.error}}},b.prototype.send=function(_){if(!this._disconnected)if(this._id)if(_.type){if(this._wsOpen()){var v=JSON.stringify(_);this._socket.send(v)}}else this.emit(l.SocketEventType.Error,"Invalid message");else this._messagesQueue.push(_)},b.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},b.prototype._cleanup=function(){this._socket&&(this._socket.onopen=this._socket.onmessage=this._socket.onclose=null,this._socket.close(),this._socket=void 0),clearTimeout(this._wsPingTimer)},b}(c.EventEmitter);t.Socket=d},{eventemitter3:"JJlS","./logger":"WOs9","./enums":"ZRYf"}],HCdX:[function(o,e,t){"use strict";var i=this&&this.__assign||function(){return(i=Object.assign||function(d){for(var h,b=1,_=arguments.length;b<_;b++)for(var v in h=arguments[b])Object.prototype.hasOwnProperty.call(h,v)&&(d[v]=h[v]);return d}).apply(this,arguments)},n=this&&this.__awaiter||function(d,h,b,_){return new(b||(b=Promise))(function(v,y){function f(g){try{p(_.next(g))}catch(w){y(w)}}function m(g){try{p(_.throw(g))}catch(w){y(w)}}function p(g){var w;g.done?v(g.value):(w=g.value,w instanceof b?w:new b(function(C){C(w)})).then(f,m)}p((_=_.apply(d,h||[])).next())})},r=this&&this.__generator||function(d,h){var b,_,v,y,f={label:0,sent:function(){if(1&v[0])throw v[1];return v[1]},trys:[],ops:[]};return y={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(y[Symbol.iterator]=function(){return this}),y;function m(p){return function(g){return function(w){if(b)throw new TypeError("Generator is already executing.");for(;f;)try{if(b=1,_&&(v=2&w[0]?_.return:w[0]?_.throw||((v=_.return)&&v.call(_),0):_.next)&&!(v=v.call(_,w[1])).done)return v;switch(_=0,v&&(w=[2&w[0],v.value]),w[0]){case 0:case 1:v=w;break;case 4:return f.label++,{value:w[1],done:!1};case 5:f.label++,_=w[1],w=[0];continue;case 7:w=f.ops.pop(),f.trys.pop();continue;default:if(!(v=(v=f.trys).length>0&&v[v.length-1])&&(w[0]===6||w[0]===2)){f=0;continue}if(w[0]===3&&(!v||w[1]>v[0]&&w[1]<v[3])){f.label=w[1];break}if(w[0]===6&&f.label<v[1]){f.label=v[1],v=w;break}if(v&&f.label<v[2]){f.label=v[2],f.ops.push(w);break}v[2]&&f.ops.pop(),f.trys.pop();continue}w=h.call(d,f)}catch(C){w=[6,C],_=0}finally{b=v=0}if(5&w[0])throw w[1];return{value:w[0]?w[1]:void 0,done:!0}}([p,g])}}},s=this&&this.__importDefault||function(d){return d&&d.__esModule?d:{default:d}};Object.defineProperty(t,"__esModule",{value:!0}),t.Negotiator=void 0;var a=o("./util"),c=s(o("./logger")),u=o("./enums"),l=function(){function d(h){this.connection=h}return d.prototype.startConnection=function(h){var b=this._startPeerConnection();if(this.connection.peerConnection=b,this.connection.type===u.ConnectionType.Media&&h._stream&&this._addTracksToConnection(h._stream,b),h.originator){if(this.connection.type===u.ConnectionType.Data){var _=this.connection,v={ordered:!!h.reliable},y=b.createDataChannel(_.label,v);_.initialize(y)}this._makeOffer()}else this.handleSDP("OFFER",h.sdp)},d.prototype._startPeerConnection=function(){c.default.log("Creating RTCPeerConnection.");var h=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(h),h},d.prototype._setupListeners=function(h){var b=this,_=this.connection.peer,v=this.connection.connectionId,y=this.connection.type,f=this.connection.provider;c.default.log("Listening for ICE candidates."),h.onicecandidate=function(m){m.candidate&&m.candidate.candidate&&(c.default.log("Received ICE candidates for "+_+":",m.candidate),f.socket.send({type:u.ServerMessageType.Candidate,payload:{candidate:m.candidate,type:y,connectionId:v},dst:_}))},h.oniceconnectionstatechange=function(){switch(h.iceConnectionState){case"failed":c.default.log("iceConnectionState is failed, closing connections to "+_),b.connection.emit(u.ConnectionEventType.Error,new Error("Negotiation of connection to "+_+" failed.")),b.connection.close();break;case"closed":c.default.log("iceConnectionState is closed, closing connections to "+_),b.connection.emit(u.ConnectionEventType.Error,new Error("Connection to "+_+" closed.")),b.connection.close();break;case"disconnected":c.default.log("iceConnectionState changed to disconnected on the connection with "+_);break;case"completed":h.onicecandidate=a.util.noop}b.connection.emit(u.ConnectionEventType.IceStateChanged,h.iceConnectionState)},c.default.log("Listening for data channel"),h.ondatachannel=function(m){c.default.log("Received data channel");var p=m.channel;f.getConnection(_,v).initialize(p)},c.default.log("Listening for remote stream"),h.ontrack=function(m){c.default.log("Received remote stream");var p=m.streams[0],g=f.getConnection(_,v);if(g.type===u.ConnectionType.Media){var w=g;b._addStreamToMediaConnection(p,w)}}},d.prototype.cleanup=function(){c.default.log("Cleaning up PeerConnection to "+this.connection.peer);var h=this.connection.peerConnection;if(h){this.connection.peerConnection=null,h.onicecandidate=h.oniceconnectionstatechange=h.ondatachannel=h.ontrack=function(){};var b=h.signalingState!=="closed",_=!1;if(this.connection.type===u.ConnectionType.Data){var v=this.connection.dataChannel;v&&(_=!!v.readyState&&v.readyState!=="closed")}(b||_)&&h.close()}},d.prototype._makeOffer=function(){return n(this,void 0,Promise,function(){var h,b,_,v,y,f,m;return r(this,function(p){switch(p.label){case 0:h=this.connection.peerConnection,b=this.connection.provider,p.label=1;case 1:return p.trys.push([1,7,,8]),[4,h.createOffer(this.connection.options.constraints)];case 2:_=p.sent(),c.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(_.sdp=this.connection.options.sdpTransform(_.sdp)||_.sdp),p.label=3;case 3:return p.trys.push([3,5,,6]),[4,h.setLocalDescription(_)];case 4:return p.sent(),c.default.log("Set localDescription:",_,"for:"+this.connection.peer),v={sdp:_,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:a.util.browser},this.connection.type===u.ConnectionType.Data&&(y=this.connection,v=i(i({},v),{label:y.label,reliable:y.reliable,serialization:y.serialization})),b.socket.send({type:u.ServerMessageType.Offer,payload:v,dst:this.connection.peer}),[3,6];case 5:return(f=p.sent())!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(b.emitError(u.PeerErrorType.WebRTC,f),c.default.log("Failed to setLocalDescription, ",f)),[3,6];case 6:return[3,8];case 7:return m=p.sent(),b.emitError(u.PeerErrorType.WebRTC,m),c.default.log("Failed to createOffer, ",m),[3,8];case 8:return[2]}})})},d.prototype._makeAnswer=function(){return n(this,void 0,Promise,function(){var h,b,_,v,y;return r(this,function(f){switch(f.label){case 0:h=this.connection.peerConnection,b=this.connection.provider,f.label=1;case 1:return f.trys.push([1,7,,8]),[4,h.createAnswer()];case 2:_=f.sent(),c.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(_.sdp=this.connection.options.sdpTransform(_.sdp)||_.sdp),f.label=3;case 3:return f.trys.push([3,5,,6]),[4,h.setLocalDescription(_)];case 4:return f.sent(),c.default.log("Set localDescription:",_,"for:"+this.connection.peer),b.socket.send({type:u.ServerMessageType.Answer,payload:{sdp:_,type:this.connection.type,connectionId:this.connection.connectionId,browser:a.util.browser},dst:this.connection.peer}),[3,6];case 5:return v=f.sent(),b.emitError(u.PeerErrorType.WebRTC,v),c.default.log("Failed to setLocalDescription, ",v),[3,6];case 6:return[3,8];case 7:return y=f.sent(),b.emitError(u.PeerErrorType.WebRTC,y),c.default.log("Failed to create answer, ",y),[3,8];case 8:return[2]}})})},d.prototype.handleSDP=function(h,b){return n(this,void 0,Promise,function(){var _,v,y,f;return r(this,function(m){switch(m.label){case 0:b=new RTCSessionDescription(b),_=this.connection.peerConnection,v=this.connection.provider,c.default.log("Setting remote description",b),y=this,m.label=1;case 1:return m.trys.push([1,5,,6]),[4,_.setRemoteDescription(b)];case 2:return m.sent(),c.default.log("Set remoteDescription:"+h+" for:"+this.connection.peer),h!=="OFFER"?[3,4]:[4,y._makeAnswer()];case 3:m.sent(),m.label=4;case 4:return[3,6];case 5:return f=m.sent(),v.emitError(u.PeerErrorType.WebRTC,f),c.default.log("Failed to setRemoteDescription, ",f),[3,6];case 6:return[2]}})})},d.prototype.handleCandidate=function(h){return n(this,void 0,Promise,function(){var b,_,v,y,f,m;return r(this,function(p){switch(p.label){case 0:c.default.log("handleCandidate:",h),b=h.candidate,_=h.sdpMLineIndex,v=h.sdpMid,y=this.connection.peerConnection,f=this.connection.provider,p.label=1;case 1:return p.trys.push([1,3,,4]),[4,y.addIceCandidate(new RTCIceCandidate({sdpMid:v,sdpMLineIndex:_,candidate:b}))];case 2:return p.sent(),c.default.log("Added ICE candidate for:"+this.connection.peer),[3,4];case 3:return m=p.sent(),f.emitError(u.PeerErrorType.WebRTC,m),c.default.log("Failed to handleCandidate, ",m),[3,4];case 4:return[2]}})})},d.prototype._addTracksToConnection=function(h,b){if(c.default.log("add tracks from stream "+h.id+" to peer connection"),!b.addTrack)return c.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");h.getTracks().forEach(function(_){b.addTrack(_,h)})},d.prototype._addStreamToMediaConnection=function(h,b){c.default.log("add stream "+h.id+" to media connection "+b.connectionId),b.addStream(h)},d}();t.Negotiator=l},{"./util":"BHXf","./logger":"WOs9","./enums":"ZRYf"}],tQFK:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var s=function(a,c){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,l){u.__proto__=l}||function(u,l){for(var d in l)Object.prototype.hasOwnProperty.call(l,d)&&(u[d]=l[d])})(a,c)};return function(a,c){if(typeof c!="function"&&c!==null)throw new TypeError("Class extends value "+String(c)+" is not a constructor or null");function u(){this.constructor=a}s(a,c),a.prototype=c===null?Object.create(c):(u.prototype=c.prototype,new u)}}();Object.defineProperty(t,"__esModule",{value:!0}),t.BaseConnection=void 0;var n=o("eventemitter3"),r=function(s){function a(c,u,l){var d=s.call(this)||this;return d.peer=c,d.provider=u,d.options=l,d._open=!1,d.metadata=l.metadata,d}return i(a,s),Object.defineProperty(a.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),a}(n.EventEmitter);t.BaseConnection=r},{eventemitter3:"JJlS"}],dbHP:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var b=function(_,v){return(b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,f){y.__proto__=f}||function(y,f){for(var m in f)Object.prototype.hasOwnProperty.call(f,m)&&(y[m]=f[m])})(_,v)};return function(_,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function y(){this.constructor=_}b(_,v),_.prototype=v===null?Object.create(v):(y.prototype=v.prototype,new y)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(b){for(var _,v=1,y=arguments.length;v<y;v++)for(var f in _=arguments[v])Object.prototype.hasOwnProperty.call(_,f)&&(b[f]=_[f]);return b}).apply(this,arguments)},r=this&&this.__values||function(b){var _=typeof Symbol=="function"&&Symbol.iterator,v=_&&b[_],y=0;if(v)return v.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&y>=b.length&&(b=void 0),{value:b&&b[y++],done:!b}}};throw new TypeError(_?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(t,"__esModule",{value:!0}),t.MediaConnection=void 0;var a=o("./util"),c=s(o("./logger")),u=o("./negotiator"),l=o("./enums"),d=o("./baseconnection"),h=function(b){function _(v,y,f){var m=b.call(this,v,y,f)||this;return m._localStream=m.options._stream,m.connectionId=m.options.connectionId||_.ID_PREFIX+a.util.randomToken(),m._negotiator=new u.Negotiator(m),m._localStream&&m._negotiator.startConnection({_stream:m._localStream,originator:!0}),m}return i(_,b),Object.defineProperty(_.prototype,"type",{get:function(){return l.ConnectionType.Media},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),_.prototype.addStream=function(v){c.default.log("Receiving stream",v),this._remoteStream=v,b.prototype.emit.call(this,l.ConnectionEventType.Stream,v)},_.prototype.handleMessage=function(v){var y=v.type,f=v.payload;switch(v.type){case l.ServerMessageType.Answer:this._negotiator.handleSDP(y,f.sdp),this._open=!0;break;case l.ServerMessageType.Candidate:this._negotiator.handleCandidate(f.candidate);break;default:c.default.warn("Unrecognized message type:"+y+" from peer:"+this.peer)}},_.prototype.answer=function(v,y){var f,m;if(y===void 0&&(y={}),this._localStream)c.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");else{this._localStream=v,y&&y.sdpTransform&&(this.options.sdpTransform=y.sdpTransform),this._negotiator.startConnection(n(n({},this.options._payload),{_stream:v}));var p=this.provider._getMessages(this.connectionId);try{for(var g=r(p),w=g.next();!w.done;w=g.next()){var C=w.value;this.handleMessage(C)}}catch(T){f={error:T}}finally{try{w&&!w.done&&(m=g.return)&&m.call(g)}finally{if(f)throw f.error}}this._open=!0}},_.prototype.close=function(){this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this._localStream=null,this._remoteStream=null,this.provider&&(this.provider._removeConnection(this),this.provider=null),this.options&&this.options._stream&&(this.options._stream=null),this.open&&(this._open=!1,b.prototype.emit.call(this,l.ConnectionEventType.Close))},_.ID_PREFIX="mc_",_}(d.BaseConnection);t.MediaConnection=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK"}],GGp6:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var c=function(u,l){return(c=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,h){d.__proto__=h}||function(d,h){for(var b in h)Object.prototype.hasOwnProperty.call(h,b)&&(d[b]=h[b])})(u,l)};return function(u,l){if(typeof l!="function"&&l!==null)throw new TypeError("Class extends value "+String(l)+" is not a constructor or null");function d(){this.constructor=u}c(u,l),u.prototype=l===null?Object.create(l):(d.prototype=l.prototype,new d)}}(),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=o("eventemitter3"),s=n(o("./logger")),a=function(c){function u(){var l=c.call(this)||this;return l.fileReader=new FileReader,l._queue=[],l._processing=!1,l.fileReader.onload=function(d){l._processing=!1,d.target&&l.emit("done",d.target.result),l.doNextTask()},l.fileReader.onerror=function(d){s.default.error("EncodingQueue error:",d),l._processing=!1,l.destroy(),l.emit("error",d)},l}return i(u,c),Object.defineProperty(u.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(u.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),u.prototype.enque=function(l){this.queue.push(l),this.processing||this.doNextTask()},u.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},u.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},u}(r.EventEmitter);t.EncodingQueue=a},{eventemitter3:"JJlS","./logger":"WOs9"}],GBTQ:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var b=function(_,v){return(b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,f){y.__proto__=f}||function(y,f){for(var m in f)Object.prototype.hasOwnProperty.call(f,m)&&(y[m]=f[m])})(_,v)};return function(_,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");function y(){this.constructor=_}b(_,v),_.prototype=v===null?Object.create(v):(y.prototype=v.prototype,new y)}}(),n=this&&this.__values||function(b){var _=typeof Symbol=="function"&&Symbol.iterator,v=_&&b[_],y=0;if(v)return v.call(b);if(b&&typeof b.length=="number")return{next:function(){return b&&y>=b.length&&(b=void 0),{value:b&&b[y++],done:!b}}};throw new TypeError(_?"Object is not iterable.":"Symbol.iterator is not defined.")},r=this&&this.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(t,"__esModule",{value:!0}),t.DataConnection=void 0;var s=o("./util"),a=r(o("./logger")),c=o("./negotiator"),u=o("./enums"),l=o("./baseconnection"),d=o("./encodingQueue"),h=function(b){function _(v,y,f){var m=b.call(this,v,y,f)||this;return m.stringify=JSON.stringify,m.parse=JSON.parse,m._buffer=[],m._bufferSize=0,m._buffering=!1,m._chunkedData={},m._encodingQueue=new d.EncodingQueue,m.connectionId=m.options.connectionId||_.ID_PREFIX+s.util.randomToken(),m.label=m.options.label||m.connectionId,m.serialization=m.options.serialization||u.SerializationType.Binary,m.reliable=!!m.options.reliable,m._encodingQueue.on("done",function(p){m._bufferedSend(p)}),m._encodingQueue.on("error",function(){a.default.error("DC#"+m.connectionId+": Error occured in encoding from blob to arraybuffer, close DC"),m.close()}),m._negotiator=new c.Negotiator(m),m._negotiator.startConnection(m.options._payload||{originator:!0}),m}return i(_,b),Object.defineProperty(_.prototype,"type",{get:function(){return u.ConnectionType.Data},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(_.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),_.prototype.initialize=function(v){this._dc=v,this._configureDataChannel()},_.prototype._configureDataChannel=function(){var v=this;s.util.supports.binaryBlob&&!s.util.supports.reliable||(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){a.default.log("DC#"+v.connectionId+" dc connection success"),v._open=!0,v.emit(u.ConnectionEventType.Open)},this.dataChannel.onmessage=function(y){a.default.log("DC#"+v.connectionId+" dc onmessage:",y.data),v._handleDataMessage(y)},this.dataChannel.onclose=function(){a.default.log("DC#"+v.connectionId+" dc closed for:",v.peer),v.close()}},_.prototype._handleDataMessage=function(v){var y=this,f=v.data,m=f.constructor,p=f;if(this.serialization===u.SerializationType.Binary||this.serialization===u.SerializationType.BinaryUTF8){if(m===Blob)return void s.util.blobToArrayBuffer(f,function(w){var C=s.util.unpack(w);y.emit(u.ConnectionEventType.Data,C)});if(m===ArrayBuffer)p=s.util.unpack(f);else if(m===String){var g=s.util.binaryStringToArrayBuffer(f);p=s.util.unpack(g)}}else this.serialization===u.SerializationType.JSON&&(p=this.parse(f));p.__peerData?this._handleChunk(p):b.prototype.emit.call(this,u.ConnectionEventType.Data,p)},_.prototype._handleChunk=function(v){var y=v.__peerData,f=this._chunkedData[y]||{data:[],count:0,total:v.total};if(f.data[v.n]=v.data,f.count++,this._chunkedData[y]=f,f.total===f.count){delete this._chunkedData[y];var m=new Blob(f.data);this._handleDataMessage({data:m})}},_.prototype.close=function(){this._buffer=[],this._bufferSize=0,this._chunkedData={},this._negotiator&&(this._negotiator.cleanup(),this._negotiator=null),this.provider&&(this.provider._removeConnection(this),this.provider=null),this.dataChannel&&(this.dataChannel.onopen=null,this.dataChannel.onmessage=null,this.dataChannel.onclose=null,this._dc=null),this._encodingQueue&&(this._encodingQueue.destroy(),this._encodingQueue.removeAllListeners(),this._encodingQueue=null),this.open&&(this._open=!1,b.prototype.emit.call(this,u.ConnectionEventType.Close))},_.prototype.send=function(v,y){if(this.open)if(this.serialization===u.SerializationType.JSON)this._bufferedSend(this.stringify(v));else if(this.serialization===u.SerializationType.Binary||this.serialization===u.SerializationType.BinaryUTF8){var f=s.util.pack(v);if(!y&&f.size>s.util.chunkedMTU)return void this._sendChunks(f);s.util.supports.binaryBlob?this._bufferedSend(f):this._encodingQueue.enque(f)}else this._bufferedSend(v);else b.prototype.emit.call(this,u.ConnectionEventType.Error,new Error("Connection is not open. You should listen for the `open` event before sending messages."))},_.prototype._bufferedSend=function(v){!this._buffering&&this._trySend(v)||(this._buffer.push(v),this._bufferSize=this._buffer.length)},_.prototype._trySend=function(v){var y=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>_.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){y._buffering=!1,y._tryBuffer()},50),!1;try{this.dataChannel.send(v)}catch(f){return a.default.error("DC#:"+this.connectionId+" Error when sending:",f),this._buffering=!0,this.close(),!1}return!0},_.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var v=this._buffer[0];this._trySend(v)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},_.prototype._sendChunks=function(v){var y,f,m=s.util.chunk(v);a.default.log("DC#"+this.connectionId+" Try to send "+m.length+" chunks...");try{for(var p=n(m),g=p.next();!g.done;g=p.next()){var w=g.value;this.send(w,!0)}}catch(C){y={error:C}}finally{try{g&&!g.done&&(f=p.return)&&f.call(p)}finally{if(y)throw y.error}}},_.prototype.handleMessage=function(v){var y=v.payload;switch(v.type){case u.ServerMessageType.Answer:this._negotiator.handleSDP(v.type,y.sdp);break;case u.ServerMessageType.Candidate:this._negotiator.handleCandidate(y.candidate);break;default:a.default.warn("Unrecognized message type:",v.type,"from peer:",this.peer)}},_.ID_PREFIX="dc_",_.MAX_BUFFERED_AMOUNT=8388608,_}(l.BaseConnection);t.DataConnection=h},{"./util":"BHXf","./logger":"WOs9","./negotiator":"HCdX","./enums":"ZRYf","./baseconnection":"tQFK","./encodingQueue":"GGp6"}],in7L:[function(o,e,t){"use strict";var i=this&&this.__awaiter||function(u,l,d,h){return new(d||(d=Promise))(function(b,_){function v(m){try{f(h.next(m))}catch(p){_(p)}}function y(m){try{f(h.throw(m))}catch(p){_(p)}}function f(m){var p;m.done?b(m.value):(p=m.value,p instanceof d?p:new d(function(g){g(p)})).then(v,y)}f((h=h.apply(u,l||[])).next())})},n=this&&this.__generator||function(u,l){var d,h,b,_,v={label:0,sent:function(){if(1&b[0])throw b[1];return b[1]},trys:[],ops:[]};return _={next:y(0),throw:y(1),return:y(2)},typeof Symbol=="function"&&(_[Symbol.iterator]=function(){return this}),_;function y(f){return function(m){return function(p){if(d)throw new TypeError("Generator is already executing.");for(;v;)try{if(d=1,h&&(b=2&p[0]?h.return:p[0]?h.throw||((b=h.return)&&b.call(h),0):h.next)&&!(b=b.call(h,p[1])).done)return b;switch(h=0,b&&(p=[2&p[0],b.value]),p[0]){case 0:case 1:b=p;break;case 4:return v.label++,{value:p[1],done:!1};case 5:v.label++,h=p[1],p=[0];continue;case 7:p=v.ops.pop(),v.trys.pop();continue;default:if(!(b=(b=v.trys).length>0&&b[b.length-1])&&(p[0]===6||p[0]===2)){v=0;continue}if(p[0]===3&&(!b||p[1]>b[0]&&p[1]<b[3])){v.label=p[1];break}if(p[0]===6&&v.label<b[1]){v.label=b[1],b=p;break}if(b&&v.label<b[2]){v.label=b[2],v.ops.push(p);break}b[2]&&v.ops.pop(),v.trys.pop();continue}p=l.call(u,v)}catch(g){p=[6,g],h=0}finally{d=b=0}if(5&p[0])throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}([f,m])}}},r=this&&this.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(t,"__esModule",{value:!0}),t.API=void 0;var s=o("./util"),a=r(o("./logger")),c=function(){function u(l){this._options=l}return u.prototype._buildUrl=function(l){var d=(this._options.secure?"https://":"http://")+this._options.host+":"+this._options.port+this._options.path+this._options.key+"/"+l;return d+="?ts="+new Date().getTime()+Math.random()},u.prototype.retrieveId=function(){return i(this,void 0,Promise,function(){var l,d,h,b;return n(this,function(_){switch(_.label){case 0:l=this._buildUrl("id"),_.label=1;case 1:return _.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((d=_.sent()).status!==200)throw new Error("Error. Status:"+d.status);return[2,d.text()];case 3:throw h=_.sent(),a.default.error("Error retrieving ID",h),b="",this._options.path==="/"&&this._options.host!==s.util.CLOUD_HOST&&(b=" If you passed in a `path` to your self-hosted PeerServer, you'll also need to pass in that same path when creating a new Peer."),new Error("Could not get an ID from the server."+b);case 4:return[2]}})})},u.prototype.listAllPeers=function(){return i(this,void 0,Promise,function(){var l,d,h,b;return n(this,function(_){switch(_.label){case 0:l=this._buildUrl("peers"),_.label=1;case 1:return _.trys.push([1,3,,4]),[4,fetch(l)];case 2:if((d=_.sent()).status!==200)throw d.status===401?(h="",h=this._options.host===s.util.CLOUD_HOST?"It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":"You need to enable `allow_discovery` on your self-hosted PeerServer to use this feature.",new Error("It doesn't look like you have permission to list peers IDs. "+h)):new Error("Error. Status:"+d.status);return[2,d.json()];case 3:throw b=_.sent(),a.default.error("Error retrieving list peers",b),new Error("Could not get list peers from the server."+b);case 4:return[2]}})})},u}();t.API=c},{"./util":"BHXf","./logger":"WOs9"}],Hxpd:[function(o,e,t){"use strict";var i=this&&this.__extends||function(){var m=function(p,g){return(m=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(w,C){w.__proto__=C}||function(w,C){for(var T in C)Object.prototype.hasOwnProperty.call(C,T)&&(w[T]=C[T])})(p,g)};return function(p,g){if(typeof g!="function"&&g!==null)throw new TypeError("Class extends value "+String(g)+" is not a constructor or null");function w(){this.constructor=p}m(p,g),p.prototype=g===null?Object.create(g):(w.prototype=g.prototype,new w)}}(),n=this&&this.__assign||function(){return(n=Object.assign||function(m){for(var p,g=1,w=arguments.length;g<w;g++)for(var C in p=arguments[g])Object.prototype.hasOwnProperty.call(p,C)&&(m[C]=p[C]);return m}).apply(this,arguments)},r=this&&this.__values||function(m){var p=typeof Symbol=="function"&&Symbol.iterator,g=p&&m[p],w=0;if(g)return g.call(m);if(m&&typeof m.length=="number")return{next:function(){return m&&w>=m.length&&(m=void 0),{value:m&&m[w++],done:!m}}};throw new TypeError(p?"Object is not iterable.":"Symbol.iterator is not defined.")},s=this&&this.__read||function(m,p){var g=typeof Symbol=="function"&&m[Symbol.iterator];if(!g)return m;var w,C,T=g.call(m),S=[];try{for(;(p===void 0||p-- >0)&&!(w=T.next()).done;)S.push(w.value)}catch(D){C={error:D}}finally{try{w&&!w.done&&(g=T.return)&&g.call(T)}finally{if(C)throw C.error}}return S},a=this&&this.__importDefault||function(m){return m&&m.__esModule?m:{default:m}};Object.defineProperty(t,"__esModule",{value:!0}),t.Peer=void 0;var c=o("eventemitter3"),u=o("./util"),l=a(o("./logger")),d=o("./socket"),h=o("./mediaconnection"),b=o("./dataconnection"),_=o("./enums"),v=o("./api"),y=function(){return function(){}}(),f=function(m){function p(g,w){var C,T=m.call(this)||this;return T._id=null,T._lastServerId=null,T._destroyed=!1,T._disconnected=!1,T._open=!1,T._connections=new Map,T._lostMessages=new Map,g&&g.constructor==Object?w=g:g&&(C=g.toString()),w=n({debug:0,host:u.util.CLOUD_HOST,port:u.util.CLOUD_PORT,path:"/",key:p.DEFAULT_KEY,token:u.util.randomToken(),config:u.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!==u.util.CLOUD_HOST?T._options.secure=u.util.isSecure():T._options.host==u.util.CLOUD_HOST&&(T._options.secure=!0),T._options.logFunction&&l.default.setLogFunction(T._options.logFunction),l.default.logLevel=T._options.debug||0,T._api=new v.API(w),T._socket=T._createServerConnection(),u.util.supports.audioVideo||u.util.supports.data?C&&!u.util.validateId(C)?(T._delayedAbort(_.PeerErrorType.InvalidID,'ID "'+C+'" is invalid'),T):(C?T._initialize(C):T._api.retrieveId().then(function(S){return T._initialize(S)}).catch(function(S){return T._abort(_.PeerErrorType.ServerError,S)}),T):(T._delayedAbort(_.PeerErrorType.BrowserIncompatible,"The current browser does not support WebRTC"),T)}return i(p,m),Object.defineProperty(p.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"connections",{get:function(){var g,w,C=Object.create(null);try{for(var T=r(this._connections),S=T.next();!S.done;S=T.next()){var D=s(S.value,2),A=D[0],P=D[1];C[A]=P}}catch(H){g={error:H}}finally{try{S&&!S.done&&(w=T.return)&&w.call(T)}finally{if(g)throw g.error}}return C},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(p.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),p.prototype._createServerConnection=function(){var g=this,w=new d.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return w.on(_.SocketEventType.Message,function(C){g._handleMessage(C)}),w.on(_.SocketEventType.Error,function(C){g._abort(_.PeerErrorType.SocketError,C)}),w.on(_.SocketEventType.Disconnected,function(){g.disconnected||(g.emitError(_.PeerErrorType.Network,"Lost connection to server."),g.disconnect())}),w.on(_.SocketEventType.Close,function(){g.disconnected||g._abort(_.PeerErrorType.SocketClosed,"Underlying socket is already closed.")}),w},p.prototype._initialize=function(g){this._id=g,this.socket.start(g,this._options.token)},p.prototype._handleMessage=function(g){var w,C,T=g.type,S=g.payload,D=g.src;switch(T){case _.ServerMessageType.Open:this._lastServerId=this.id,this._open=!0,this.emit(_.PeerEventType.Open,this.id);break;case _.ServerMessageType.Error:this._abort(_.PeerErrorType.ServerError,S.msg);break;case _.ServerMessageType.IdTaken:this._abort(_.PeerErrorType.UnavailableID,'ID "'+this.id+'" is taken');break;case _.ServerMessageType.InvalidKey:this._abort(_.PeerErrorType.InvalidKey,'API KEY "'+this._options.key+'" is invalid');break;case _.ServerMessageType.Leave:l.default.log("Received leave message from "+D),this._cleanupPeer(D),this._connections.delete(D);break;case _.ServerMessageType.Expire:this.emitError(_.PeerErrorType.PeerUnavailable,"Could not connect to peer "+D);break;case _.ServerMessageType.Offer:var A=S.connectionId;if((W=this.getConnection(D,A))&&(W.close(),l.default.warn("Offer received for existing Connection ID:"+A)),S.type===_.ConnectionType.Media)W=new h.MediaConnection(D,this,{connectionId:A,_payload:S,metadata:S.metadata}),this._addConnection(D,W),this.emit(_.PeerEventType.Call,W);else{if(S.type!==_.ConnectionType.Data)return void l.default.warn("Received malformed connection type:"+S.type);W=new b.DataConnection(D,this,{connectionId:A,_payload:S,metadata:S.metadata,label:S.label,serialization:S.serialization,reliable:S.reliable}),this._addConnection(D,W),this.emit(_.PeerEventType.Connection,W)}var P=this._getMessages(A);try{for(var H=r(P),B=H.next();!B.done;B=H.next()){var N=B.value;W.handleMessage(N)}}catch(re){w={error:re}}finally{try{B&&!B.done&&(C=H.return)&&C.call(H)}finally{if(w)throw w.error}}break;default:if(!S)return void l.default.warn("You received a malformed message from "+D+" of type "+T);var W;A=S.connectionId,(W=this.getConnection(D,A))&&W.peerConnection?W.handleMessage(g):A?this._storeMessage(A,g):l.default.warn("You received an unrecognized message:",g)}},p.prototype._storeMessage=function(g,w){this._lostMessages.has(g)||this._lostMessages.set(g,[]),this._lostMessages.get(g).push(w)},p.prototype._getMessages=function(g){var w=this._lostMessages.get(g);return w?(this._lostMessages.delete(g),w):[]},p.prototype.connect=function(g,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(_.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");var C=new b.DataConnection(g,this,w);return this._addConnection(g,C),C},p.prototype.call=function(g,w,C){if(C===void 0&&(C={}),this.disconnected)return l.default.warn("You cannot connect to a new Peer because you called .disconnect() on this Peer and ended your connection with the server. You can create a new Peer to reconnect."),void this.emitError(_.PeerErrorType.Disconnected,"Cannot connect to new Peer after disconnecting from server.");if(w){C._stream=w;var T=new h.MediaConnection(g,this,C);return this._addConnection(g,T),T}l.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.")},p.prototype._addConnection=function(g,w){l.default.log("add connection "+w.type+":"+w.connectionId+" to peerId:"+g),this._connections.has(g)||this._connections.set(g,[]),this._connections.get(g).push(w)},p.prototype._removeConnection=function(g){var w=this._connections.get(g.peer);if(w){var C=w.indexOf(g);C!==-1&&w.splice(C,1)}this._lostMessages.delete(g.connectionId)},p.prototype.getConnection=function(g,w){var C,T,S=this._connections.get(g);if(!S)return null;try{for(var D=r(S),A=D.next();!A.done;A=D.next()){var P=A.value;if(P.connectionId===w)return P}}catch(H){C={error:H}}finally{try{A&&!A.done&&(T=D.return)&&T.call(D)}finally{if(C)throw C.error}}return null},p.prototype._delayedAbort=function(g,w){var C=this;setTimeout(function(){C._abort(g,w)},0)},p.prototype._abort=function(g,w){l.default.error("Aborting!"),this.emitError(g,w),this._lastServerId?this.disconnect():this.destroy()},p.prototype.emitError=function(g,w){var C;l.default.error("Error:",w),(C=typeof w=="string"?new Error(w):w).type=g,this.emit(_.PeerEventType.Error,C)},p.prototype.destroy=function(){this.destroyed||(l.default.log("Destroy peer with ID:"+this.id),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit(_.PeerEventType.Close))},p.prototype._cleanup=function(){var g,w;try{for(var C=r(this._connections.keys()),T=C.next();!T.done;T=C.next()){var S=T.value;this._cleanupPeer(S),this._connections.delete(S)}}catch(D){g={error:D}}finally{try{T&&!T.done&&(w=C.return)&&w.call(C)}finally{if(g)throw g.error}}this.socket.removeAllListeners()},p.prototype._cleanupPeer=function(g){var w,C,T=this._connections.get(g);if(T)try{for(var S=r(T),D=S.next();!D.done;D=S.next())D.value.close()}catch(A){w={error:A}}finally{try{D&&!D.done&&(C=S.return)&&C.call(S)}finally{if(w)throw w.error}}},p.prototype.disconnect=function(){if(!this.disconnected){var g=this.id;l.default.log("Disconnect peer with ID:"+g),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=g,this._id=null,this.emit(_.PeerEventType.Disconnected,g)}},p.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)l.default.log("Attempting reconnection to server with ID "+this._lastServerId),this._disconnected=!1,this._initialize(this._lastServerId);else{if(this.destroyed)throw new Error("This peer cannot reconnect to the server. It has already been destroyed.");if(this.disconnected||this.open)throw new Error("Peer "+this.id+" cannot reconnect because it is not disconnected from the server!");l.default.error("In a hurry? We're still trying to make the initial connection!")}},p.prototype.listAllPeers=function(g){var w=this;g===void 0&&(g=function(C){}),this._api.listAllPeers().then(function(C){return g(C)}).catch(function(C){return w._abort(_.PeerErrorType.ServerError,C)})},p.DEFAULT_KEY="peerjs",p}(c.EventEmitter);t.Peer=f},{eventemitter3:"JJlS","./util":"BHXf","./logger":"WOs9","./socket":"wJlv","./mediaconnection":"dbHP","./dataconnection":"GBTQ","./enums":"ZRYf","./api":"in7L"}],iTK6:[function(o,e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.peerjs=void 0;var i=o("./util"),n=o("./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 cp=ms((qE,lp)=>{(function(){var o="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],s=0;s<4;s++)n*8+s*6<=t.length*8?i.push(o.charAt(r>>>6*(3-s)&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((o.indexOf(t.charAt(n-1))&Math.pow(2,-2*r+8)-1)<<r*2|o.indexOf(t.charAt(n))>>>6-r*2);return i}};lp.exports=e})()});var Bc=ms((YE,up)=>{var Fc={utf8:{stringToBytes:function(o){return Fc.bin.stringToBytes(unescape(encodeURIComponent(o)))},bytesToString:function(o){return decodeURIComponent(escape(Fc.bin.bytesToString(o)))}},bin:{stringToBytes:function(o){for(var e=[],t=0;t<o.length;t++)e.push(o.charCodeAt(t)&255);return e},bytesToString:function(o){for(var e=[],t=0;t<o.length;t++)e.push(String.fromCharCode(o[t]));return e.join("")}}};up.exports=Fc});var pp=ms((KE,hp)=>{hp.exports=function(o){return o!=null&&(dp(o)||Fg(o)||!!o._isBuffer)};function dp(o){return!!o.constructor&&typeof o.constructor.isBuffer=="function"&&o.constructor.isBuffer(o)}function Fg(o){return typeof o.readFloatLE=="function"&&typeof o.slice=="function"&&dp(o.slice(0,0))}});var mp=ms((JE,fp)=>{(function(){var o=cp(),e=Bc().utf8,t=pp(),i=Bc().bin,n=function(r,s){r.constructor==String?s&&s.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 a=o.bytesToWords(r),c=r.length*8,u=1732584193,l=-271733879,d=-1732584194,h=271733878,b=0;b<a.length;b++)a[b]=(a[b]<<8|a[b]>>>24)&16711935|(a[b]<<24|a[b]>>>8)&4278255360;a[c>>>5]|=128<<c%32,a[(c+64>>>9<<4)+14]=c;for(var _=n._ff,v=n._gg,y=n._hh,f=n._ii,b=0;b<a.length;b+=16){var m=u,p=l,g=d,w=h;u=_(u,l,d,h,a[b+0],7,-680876936),h=_(h,u,l,d,a[b+1],12,-389564586),d=_(d,h,u,l,a[b+2],17,606105819),l=_(l,d,h,u,a[b+3],22,-1044525330),u=_(u,l,d,h,a[b+4],7,-176418897),h=_(h,u,l,d,a[b+5],12,1200080426),d=_(d,h,u,l,a[b+6],17,-1473231341),l=_(l,d,h,u,a[b+7],22,-45705983),u=_(u,l,d,h,a[b+8],7,1770035416),h=_(h,u,l,d,a[b+9],12,-1958414417),d=_(d,h,u,l,a[b+10],17,-42063),l=_(l,d,h,u,a[b+11],22,-1990404162),u=_(u,l,d,h,a[b+12],7,1804603682),h=_(h,u,l,d,a[b+13],12,-40341101),d=_(d,h,u,l,a[b+14],17,-1502002290),l=_(l,d,h,u,a[b+15],22,1236535329),u=v(u,l,d,h,a[b+1],5,-165796510),h=v(h,u,l,d,a[b+6],9,-1069501632),d=v(d,h,u,l,a[b+11],14,643717713),l=v(l,d,h,u,a[b+0],20,-373897302),u=v(u,l,d,h,a[b+5],5,-701558691),h=v(h,u,l,d,a[b+10],9,38016083),d=v(d,h,u,l,a[b+15],14,-660478335),l=v(l,d,h,u,a[b+4],20,-405537848),u=v(u,l,d,h,a[b+9],5,568446438),h=v(h,u,l,d,a[b+14],9,-1019803690),d=v(d,h,u,l,a[b+3],14,-187363961),l=v(l,d,h,u,a[b+8],20,1163531501),u=v(u,l,d,h,a[b+13],5,-1444681467),h=v(h,u,l,d,a[b+2],9,-51403784),d=v(d,h,u,l,a[b+7],14,1735328473),l=v(l,d,h,u,a[b+12],20,-1926607734),u=y(u,l,d,h,a[b+5],4,-378558),h=y(h,u,l,d,a[b+8],11,-2022574463),d=y(d,h,u,l,a[b+11],16,1839030562),l=y(l,d,h,u,a[b+14],23,-35309556),u=y(u,l,d,h,a[b+1],4,-1530992060),h=y(h,u,l,d,a[b+4],11,1272893353),d=y(d,h,u,l,a[b+7],16,-155497632),l=y(l,d,h,u,a[b+10],23,-1094730640),u=y(u,l,d,h,a[b+13],4,681279174),h=y(h,u,l,d,a[b+0],11,-358537222),d=y(d,h,u,l,a[b+3],16,-722521979),l=y(l,d,h,u,a[b+6],23,76029189),u=y(u,l,d,h,a[b+9],4,-640364487),h=y(h,u,l,d,a[b+12],11,-421815835),d=y(d,h,u,l,a[b+15],16,530742520),l=y(l,d,h,u,a[b+2],23,-995338651),u=f(u,l,d,h,a[b+0],6,-198630844),h=f(h,u,l,d,a[b+7],10,1126891415),d=f(d,h,u,l,a[b+14],15,-1416354905),l=f(l,d,h,u,a[b+5],21,-57434055),u=f(u,l,d,h,a[b+12],6,1700485571),h=f(h,u,l,d,a[b+3],10,-1894986606),d=f(d,h,u,l,a[b+10],15,-1051523),l=f(l,d,h,u,a[b+1],21,-2054922799),u=f(u,l,d,h,a[b+8],6,1873313359),h=f(h,u,l,d,a[b+15],10,-30611744),d=f(d,h,u,l,a[b+6],15,-1560198380),l=f(l,d,h,u,a[b+13],21,1309151649),u=f(u,l,d,h,a[b+4],6,-145523070),h=f(h,u,l,d,a[b+11],10,-1120210379),d=f(d,h,u,l,a[b+2],15,718787259),l=f(l,d,h,u,a[b+9],21,-343485551),u=u+m>>>0,l=l+p>>>0,d=d+g>>>0,h=h+w>>>0}return o.endian([u,l,d,h])};n._ff=function(r,s,a,c,u,l,d){var h=r+(s&a|~s&c)+(u>>>0)+d;return(h<<l|h>>>32-l)+s},n._gg=function(r,s,a,c,u,l,d){var h=r+(s&c|a&~c)+(u>>>0)+d;return(h<<l|h>>>32-l)+s},n._hh=function(r,s,a,c,u,l,d){var h=r+(s^a^c)+(u>>>0)+d;return(h<<l|h>>>32-l)+s},n._ii=function(r,s,a,c,u,l,d){var h=r+(a^(s|~c))+(u>>>0)+d;return(h<<l|h>>>32-l)+s},n._blocksize=16,n._digestsize=16,fp.exports=function(r,s){if(r==null)throw new Error("Illegal argument "+r);var a=o.wordsToBytes(n(r,s));return s&&s.asBytes?a:s&&s.asString?i.bytesToString(a):o.bytesToHex(a)}})()});import{DepthTexture as sb,WebGLRenderer as ab}from"three";import*as Re from"three";import*as si from"three";var nc=()=>o=>o;var Wn=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]}},rc=!1,tc=[];setTimeout(()=>{rc&&console.log(tc)},100);function oc(){return new URLSearchParams(window.location.search)}function M(o){rc&&!tc.includes(o)&&tc.push(o);let e=oc();if(e.has(o)){let t=e.get(o);return t||!0}return!1}rc=M("help")===!0;function Co(o,e,t){o.has(e)?o.set(e,t.toString()):o.append(e,t.toString())}function sh(o,e){window.history.replaceState(null,o,"?"+e.toString())}function ah(o,e){return Math.floor(Math.random()*(e-o+1))+o}var rh=["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"],oh=["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 lh(){let o=rh[Math.floor(Math.random()*rh.length)],e=oh[Math.floor(Math.random()*oh.length)];return o+"_"+e}function ch(o){return o=o.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),o.trim()}function Nn(o,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===o)return e;if(e.guid==o)return e;if(i&&e.userData?.components){for(let n of e.userData.components)if(n.guid===o)return n}if(t){if(e.scenes)for(let n in e.scenes){let r=e.scenes[n],s=Nn(o,r,t,i);if(s)return s}if(e.children)for(let n in e.children){let r=e.children[n],s=Nn(o,r,t,i);if(s)return s}}}function gs(o,e){if(o!=null&&typeof o=="object"){let t;Array.isArray(o)?t=[]:(t=Object.create(o),Object.assign(t,o));for(let i of Object.keys(o)){let n=o[i];e&&!e(o,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=gs(n,e)}return t}return o}function uh(o){return new Promise((e,t)=>{setTimeout(e,o)})}var ec=M("debugsourcepath");function ki(o,e){if(o===void 0)return ec&&console.warn("getPath: source is undefined, returning uri",e),e;if(e.startsWith("http"))return ec&&console.warn("getPath: uri is absolute, returning uri",e),e;let t=o.lastIndexOf("/");if(t>=0){let i=o.substring(0,t+1),n=e.lastIndexOf("/");return n>=0?i+=e.substring(n+1):i+=e,ec&&console.log("getPath:",o,` - changed uri from
|
|
79
79
|
`,e,`
|
|
80
|
-
\u2192 `,i),i}return e}var ic=class{subscribeWrite(e){this.writeCallbacks.push(e)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;let e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");let i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:s=>{e[this._wrapperProp]=s;for(let a of this.writeCallbacks)a(s,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;let e=this._object,t=this._prop;Reflect.deleteProperty(e,t);let i=e[this._wrapperProp];e[t]=i,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}},
|
|
80
|
+
\u2192 `,i),i}return e}var ic=class{subscribeWrite(e){this.writeCallbacks.push(e)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;let e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");let i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:s=>{e[this._wrapperProp]=s;for(let a of this.writeCallbacks)a(s,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;let e=this._object,t=this._prop;Reflect.deleteProperty(e,t);let 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 ic(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}};function dh(){return typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1}function Xn(o=window.location.hostname){return new RegExp("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}|localhost","gm").test(o)===!0}function hh(){return window.location.hostname.includes("glitch.me")}var mn="ar",mm="quit-ar",oa=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(`.${mn}`).forEach(s=>{!s||s!==this.arContainer&&(this._reparentedObjects.push({el:s,previousParent:s.parentElement}),this.arContainer?.appendChild(s))});let r=t.getElementsByClassName(mm);if(!r||r.length<=0)console.warn("Missing quit AR elements"),this.createFallbackCloseARButton(this.arContainer);else for(let s=0;s<r.length;s++){let a=r[s];!a||(a.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(a))}}onEnd(e){for(let t of this._createdAROnlyElements)t.remove&&t.remove();for(let t of this._reparentedObjects){let i=t.el;t.previousParent?.appendChild(i)}this._reparentedObjects.length=0}findOrCreateARContainer(e){if(e.classList.contains(mn))return e;if(e.children)for(let i=0;i<e.children.length;i++){let n=e.children[i];if(!(!n||!n.classList)&&n.classList.contains(mn))return n}let t=document.createElement("div");return t.classList.add(mn),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 W_=M("debugdebug"),gm=M("noerrors"),sc=new Map,N_=new RegExp(" at .+/(.+?.ts)","g"),bs=(i=>(i[i.Log=0]="Log",i[i.Warn=1]="Warn",i[i.Error=2]="Error",i))(bs||{});function ph(o,e,t,i){if(gm)return;let r=V.Current?.domElement??document.querySelector("needle-engine");if(!!r){if(Array.isArray(e)){let s="";for(let a=0;a<e.length;a++)typeof e[a]!="object"&&(a>0&&(s+=" "),s+=e[a]);e=s}bm(o,r,e)}}var ac=new Set;function bm(o,e,t){let i=ym(e);if(i.childElementCount>=20||ac.has(t))return;ac.add(t);let n=xm(o,t);i.prepend(n),setTimeout(()=>{ac.delete(t),_m(n)},1e4)}var vm=`
|
|
81
81
|
|
|
82
82
|
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
|
|
83
83
|
|
|
@@ -114,7 +114,7 @@ a:hover {
|
|
|
114
114
|
color: rgba(255,100,120, 1);
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
-
`;function ym(o){if(sc.has(o))return sc.get(o);{let e=document.createElement("div");e.classList.add(
|
|
117
|
+
`;function ym(o){if(sc.has(o))return sc.get(o);{let e=document.createElement("div");e.classList.add(mn),e.classList.add("desktop"),e.classList.add("debug-container"),e.style.position="absolute",e.style.top="0",e.style.right="5px",e.style.paddingTop="0px",e.style.maxWidth="70%",e.style.maxHeight="calc(100% - 5px)",e.style.zIndex="1000",e.style.pointerEvents="scroll",e.style.display="flex",e.style.alignItems="end",e.style.flexDirection="column",e.style.color="white",e.style.overflow="auto",o.appendChild(e),sc.set(o,e);let t=document.createElement("style");return t.innerHTML=vm,e.appendChild(t),e}}var fh=Symbol("logtype"),sa=new Map;function _m(o){o.remove();let e=o[fh],t=sa.get(e)??[];t.push(o),sa.set(e,t)}function xm(o,e){if(sa.has(o)){let i=sa.get(o);if(i.length>0)return i.pop()}let t=document.createElement("div");switch(t.style.marginRight="5px",t.style.padding=".5em",t.style.backgroundColor="rgba(0,0,0,.9)",t.style.marginTop="5px",t.style.marginBottom="3px",t.style.borderRadius="8px",t.style.pointerEvents="all",t.style.userSelect="text",t.style.maxWidth="250px",t.style.whiteSpace="pre-wrap",t.style["backdrop-filter"]="blur(10px)",t.style.backgroundColor="rgba(20,20,20,.8)",t.style.boxShadow="inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)",t.style.border="1px solid rgba(160,160,160,.2)",t[fh]=o,o){case 0:t.classList.add("log"),t.style.color="rgba(200,200,200,.7)",t.style.backgroundColor="rgba(40,40,40,.7)";break;case 1:t.classList.add("warn"),t.style.color="rgb(255, 255, 150)",t.style.backgroundColor="rgba(50,50,20,.8)";break;case 2:t.classList.add("error"),t.style.color="rgb(255, 50, 50",t.style.backgroundColor="rgba(50,20,20,.8)";break}return t.title="Open the browser console (F12) for more information",t.innerHTML=e,t}function Ze(o,e=0){ph(e,o)}function vs(o){Ze(o,1)}var Mi=M("gizmos"),Te=M("debugextension");var la=M("debugresolvedependencies"),wm=["/extensions/","extensions/"],Em=[{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 To(o,e){la&&console.log(o,e);let t=[];lc(Em,o,e,t);let i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function lc(o,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 s=mh(e,r);if(s!==null)typeof s.then=="function"?i.push(s.then(a=>t[n]=a)):t[n]=s;else for(let a of o){let c=cc(a.prefix,r);if(c>=0){la&&console.log(a,c,a.dependencyName),i.push(e?.getDependency(a.dependencyName,c).then(u=>(t[n]=u,u)));break}}}else if(Array.isArray(r))for(let s=0;s<r.length;s++){let a=r[s],c=mh(e,a);if(c!==null){typeof c.then=="function"?i.push(c.then(u=>r[s]=u)):r[s]=c;continue}for(let u of o){let l=cc(u.prefix,a);if(l>=0){la&&console.log(u,l,u.dependencyName),i.push(e?.getDependency(u.dependencyName,l).then(d=>r[s]=d));break}}typeof a=="object"&&lc(o,e,a,i)}else typeof r=="object"&&lc(o,e,r,i)}else typeof t=="string"&&Cm(o,e,t,i)}function mh(o,e){if(o&&o.plugins&&typeof e=="string"){for(let t of wm)if(e.startsWith(t)){let i=e.substring(t.length),n=i.indexOf("/");n>=0&&(i=i.substring(0,n));let r=o.plugins[i];if(Te&&console.log(i,r),typeof r?.resolve=="function"){let s=e.substring(t.length+i.length+1);return r.resolve(o,s)}break}}return null}function Cm(o,e,t,i){for(let n of o){let r=cc(n.prefix,t);if(r>=0)return la&&console.log(n,r,n.dependencyName),i.push(e?.getDependency(n.dependencyName,r).then(s=>s)),!0}return!1}function cc(o,e){if(typeof e=="string"&&e.startsWith(o)){let t=e.substring(o.length),i=Number.parseInt(t);if(i>=0)return i}return-1}var uc=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]}},I=Symbol("BuiltInType"),O=new uc;var dc="NEEDLE_persistent_assets";function gh(o){return o?.___persistentAsset===!0}var ca=class{get name(){return dc}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;let t=this.parser.json.extensions[dc];if(!t)return;Te&&console.log(t);let i=new Array;for(let n of t?.assets){let r=To(this.parser,n);r&&i.push(r)}await Promise.all(i)}resolve(e,t){let i=Number.parseInt(t);if(i>=0){Te&&console.log(t);let n=e.json.extensions[dc];if(n){let r=n?.assets[i];if(r&&typeof r=="object"){r.___persistentAsset=!0;let s=r.__type;if(s){let a=O.get(s)}}return r}}return null}};var Pr=M("debugserializer"),hc=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])}Pr&&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){Pr&&console.log("invalid type");return}let i=e.name??e.constructor?.name;if(!i){Pr&&console.log("invalid name",i);return}let n=this.getSerializer(i);if(n!==void 0)return Pr&&console.log("FOUND "+i,e.name,e.constructor.name,n,this.typeMap),n;let r=Object.getPrototypeOf(e);if(!(r.prototype||r.constructor)){Pr&&console.warn("No prototype for "+i,e,e.name,e.prototype,e.constructor.name);return}let a=r.prototype??r.constructor;if(a!==e){let c=this.getSerializerForConstructor(a,++t);if(c){Pr&&console.log("FOUND "+a.constructor.name,a.name,a,c);let u=a.name??a.constructor.name;u==="Function"?console.error("Registering Function is not allowed, something went wrong",e,a,c):this.register(u,c)}return c}}},da=new hc,gn=class{constructor(e){if(Array.isArray(e))for(let t of e)da.register(t.name,this);else da.register(e.name,this)}},ha=class{isDevMode=Xn();cache={};registerDefinedKeys(e,t){!this.isDevMode||this.cache[e]===void 0&&(this.cache[e]=Object.keys(t))}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}},Ro=class{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;implementationInformation;constructor(e){this.root=e}};function fc(o,e){let t=o.$serializedTypes;if(t===void 0)return null;let i={};for(let n in t){let r=o[n];if(r!=null&&typeof r=="object"){let s=da.getSerializerForConstructor(r);if(s){i[n]=s.onSerialize(r,e);continue}}i[n]=r}return i.name=o.constructor.name,typeof o.guid=="string"&&(i.guid=o.guid),i}var ua=[];function bh(o,e){if(!o)return e;typeof o.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,o.$serializedTypes));let t=Object.getPrototypeOf(o);return bh(t,e)}function ys(o,e,t){if(!o)return!1;if(t.target=o,o.onBeforeDeserialize!==void 0){let r=o.onBeforeDeserialize(e,t);if(typeof r=="boolean")return r}let i=bh(o);if(e){if(typeof e.guid=="string"&&(o.guid=e.guid),i)for(let r in i){let s=i[r],a=e[r];if(!(o[r]!==void 0&&a===void 0))if(t.path=r,s===null)o[r]=a;else{let c=function(u){let d=u.type;return d?pc(a,d,t,void 0,o[r]):pc(a,u,t,void 0,o[r])};var n=c;if(o.onBeforeDeserializeMember!==void 0&&o.onBeforeDeserializeMember(r,a,t)===!0)continue;if(Array.isArray(s))for(let u=0;u<s.length;u++){let l=s[u],d=c(l);if(d!==void 0||u===s.length-1){o[r]=d;break}}else o[r]=c(s);ua.length=0,o.onAfterDeserializeMember!==void 0&&o.onAfterDeserializeMember(r,a,t)}}Sm(o,e)}return Rm(o,e,t.implementationInformation),o.onAfterDeserialize!==void 0&&o.onAfterDeserialize(e,t),t.path=void 0,!0}var Tm=M("noerrors");function Rm(o,e,t){if(Tm||!e||Xn()===!1||!o||o.constructor&&o.constructor[I]===!0)return;let i=o.constructor?.name,n=Object.getOwnPropertyNames(e);for(let r of n){if(r==="sourceId")continue;let s=o[r],a=e[r];t?.getDefinedKey(i,r)!==!1&&a!=null&&(typeof a=="object"?(s===void 0||!s.isObject3D)&&(typeof a.node=="number"||typeof a.guid=="string")&&(s!==void 0&&Object.keys(s).length>1||(Ze(`<strong>Missing serialization for object reference!</strong>
|
|
118
118
|
|
|
119
119
|
Please change to:
|
|
120
120
|
@serializable(Object3D)
|
|
@@ -128,7 +128,7 @@ Please change to:
|
|
|
128
128
|
${r}? : AssetReference;
|
|
129
129
|
|
|
130
130
|
in script ${i}.ts
|
|
131
|
-
<a href="https://docs.needle.tools/serializeable" target="_blank">documentation</a>`,1),console.warn(i,r,o[r],o)))}}function Sm(o,e){for(let i of Object.keys(e)){let n=e[i];if(typeof n=="object"&&n!==null&&n!==void 0){let r=o[i];if(!r){Pr&&console.log(i,"is undefined on",o);continue}for(let s of Object.keys(n))r[s]===void 0&&t(n[s])&&!t(r)&&(r[s]=n[s])}}function t(i){switch(typeof i){case"number":case"string":case"boolean":return!0}return!1}}function pc(o,e,t,i,n){let r=typeof e=="function"&&e.prototype===void 0,s=e;if(r)try{if(s=e?.call(e,n),r=!1,s==null)return}catch(l){console.error("Error in callback",l,o)}if(!r&&n instanceof s)return n;if(n&&typeof n=="object"&&gh(n)){if(n.__concreteInstance)return n.__concreteInstance;let l=n;if(!l.$serializedTypes&&s.prototype.$serializedTypes&&(l.$serializedTypes=s.prototype.$serializedTypes),l.$serializedTypes&&ys(l,o,t),n&&s!==void 0)try{let d=new s;Te&&console.log("Create concrete instance for persistent asset",n,"instance:",d),oi(d,n),n.__concreteInstance=d,n=d}catch(d){console.error("Error creating instance or creating values on instance",d,n,s)}return n}if(i||(i={serializer:da.getSerializerForConstructor(s)}),Array.isArray(o)){let l=[];for(let d=0;d<o.length;d++){let h=o[d],b=pc(h,e,t,i,h);l.push(b)}return l}let a=i.serializer;if(a)return a.onDeserialize(o,t);let c;o&&(o.isMaterial||o.isTexture||o.isObject3D)?c=o:c=new s(...Pm(o));let u=c;return u.$serializedTypes&&ys(u,o,t),c}function Pm(o){if(ua.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(let e of Object.keys(o))ua.push(o[e]);return ua}var pa=Symbol("assigned component properties");function oi(o,e,t){if(e==null||o==null)return;let i=!1;o[pa]=!0;let n=o.constructor?.name??"unknown";t?.registerDefinedKeys(n,o);for(let r of Object.keys(e)){let s=Om(o,r);i&&s===void 0||(!s||s.writable===!0||s?.set!==void 0)&&(o[r]=e[r])}delete o[pa]}function Om(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}var _s=M("debuginput"),xs=class{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}};var fa=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]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new si.Vector2];_pointerPositionsLastFrame=[new si.Vector2];_pointerPositionsDelta=[new si.Vector2];_pointerPositionsRC=[new si.Vector2];_pointerPositionDown=[new si.Vector2];_pointerDownTime=[];_pointerUpTime=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_mouseWheelDeltaY=[0];_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){_s&&Ze("Create Pointer down"),this.onDown(e)}createPointerMove(e){_s&&Ze("Create Pointer move"),this.onMove(e)}createPointerUp(e){_s&&Ze("Create Pointer up"),this.onUp(e)}convertScreenspaceToRaycastSpace(e){e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1}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;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0}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 xs(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 xs(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 xs(e)))}onMouseWheel(e){this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;let t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY}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)}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})}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 si.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),this.onDispatchEvent("pointermove",e))}onUp(e){if(this.setPointerState(e.button,this._pointerPressed,!1),this.setPointerStateT(e.button,this._pointerEvent,e.source),!this.isInRect(e)){_s&&vs("Pointer out of bounds: "+e.clientX+", "+e.clientY);return}if(this.setPointerState(e.button,this._pointerUp,!0),this.updatePointerPosition(e),!this._pointerPositionDown[e.button]){_s&&vs("Received pointer up event without matching down event for button: "+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,this.onDispatchEvent("pointerup",e)}updatePointerPosition(e){for(;e.button>=this._pointerPositions.length;)this._pointerPositions.push(new si.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new si.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new si.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 si.Vector2);let r=this._pointerPositionsRC[e.button];r.set(i,n),this.convertScreenspaceToRaycastSpace(r)}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=V.Current;try{V.Current=this.context;let n=new Event(e);oi(n,t),this.dispatchEvent(n)}finally{V.Current=i}}};import{Box3 as vg,BufferAttribute as np,BufferGeometry as yg,Layers as Mc,LineBasicMaterial as _g,LineSegments as xg,Matrix4 as wg,Quaternion as Eg,Raycaster as Cg,Sphere as Tg,Vector2 as Rg,Vector3 as Sc}from"three";import*as de from"three";var mc=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}remap(e,t,i,n,r){return n+(r-n)*(e-t)/(i-t)}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}gammaToLinear(e){return Math.pow(e,2.2)}linearToGamma(e){return Math.pow(e,1/2.2)}},F=new mc;import{WebGLRenderer as km,Vector3 as Mm,Quaternion as Im,Uniform as vh,Texture as Dm,ShaderMaterial as yh}from"three";var Cx=new Im().setFromAxisAngle(new Mm(0,1,0),Math.PI);var bc=new Wn(()=>new de.Vector3,100);function U(o,e=null,t=!0){let i=e??bc.get();return o?o.parent?(t&&o.updateWorldMatrix(!0,!1),o.matrixWorldNeedsUpdate&&o.updateMatrixWorld(),i.setFromMatrixPosition(o.matrixWorld),i):i.copy(o.position):i.set(0,0,0)}function te(o,e){if(!o)return;let t=bc.get();e!==t&&t.copy(e),(o?.parent??o).worldToLocal(t),o.position.set(t.x,t.y,t.z)}function gn(o,e,t,i){let n=bc.get();n.set(e,t,i),te(o,n)}var Or=new de.Quaternion,ws=new de.Quaternion,gc=new de.Quaternion;function he(o,e=null){if(!o)return ws.set(0,0,0,1);let t=e??ws;return o.parent?(o.getWorldQuaternion(t),t):t.copy(o.quaternion)}function $e(o,e){if(!o)return;e!==Or&&Or.copy(e);let t=Or;o?.parent?.getWorldQuaternion(gc),gc.invert();let n=gc.multiply(t);o.quaternion.set(n.x,n.y,n.z,n.w)}function wh(o,e,t,i,n){Or.set(e,t,i,n),$e(o,Or)}var ma=new de.Vector3,Tx=new de.Vector3;function Fe(o,e=null){return o?o.parent?(o.getWorldScale(e??ma),e??ma):ma.copy(o.scale):ma.set(0,0,0)}var Rx=new de.Vector3,Sx=new de.Quaternion;var _h=new de.Euler,xh=new de.Euler,Am=new de.Vector3;function Lm(o){return o.getWorldQuaternion(ws),xh.setFromQuaternion(ws),xh}function Eh(o,e){$e(o,ws.setFromEuler(e))}function ga(o){let e=Lm(o),t=Am;return t.set(e.x,e.y,e.z),t.x=F.toDegrees(t.x),t.y=F.toDegrees(t.y),t.z=F.toDegrees(t.z),t}function ba(o,e,t,i,n=!0){n&&(e=F.toRadians(e),t=F.toRadians(t),i=F.toRadians(i)),_h.set(e,t,i),Or.setFromEuler(_h),$e(o,Or)}function Es(o,e=!0){!o||(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(o):o.traverse(function(t){for(var i="|___",n=t;n.parent!==null;)i=" "+i,n=n.parent;console.log(i+t.name+" <"+t.type+">")}))}function Ch(o){if(o){let e=o;return e.blendMode!==void 0&&e.clampWhenFinished!==void 0&&e.enabled!==void 0&&e.fadeIn!==void 0&&e.getClip!==void 0}return!1}var So=class{static createBlitMaterial(e){return new yh({uniforms:{map:new vh(null)},vertexShader:this.vertex,fragmentShader:e})}static copyTexture(e,t){let i=t??this.blipMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;let n=this.mesh;n.material=i,n.frustumCulled=!1,this.scene.children.length=0,this.scene.add(n),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);let r=new Dm(this.renderer.domElement);return r.name="Copy",r.needsUpdate=!0,r}static textureToCanvas(e,t){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=jm(e));let i=e.image;if(Hm(i)){let n=document.createElement("canvas");n.width=i.width,n.height=i.height;let r=n.getContext("2d");return r?(r.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}},ai=So;L(ai,"planeGeometry",new de.PlaneGeometry(2,2,1,1)),L(ai,"renderer",new km({antialias:!1})),L(ai,"perspectiveCam",new de.PerspectiveCamera),L(ai,"scene",new de.Scene),L(ai,"vertex",`
|
|
131
|
+
<a href="https://docs.needle.tools/serializeable" target="_blank">documentation</a>`,1),console.warn(i,r,o[r],o)))}}function Sm(o,e){for(let i of Object.keys(e)){let n=e[i];if(typeof n=="object"&&n!==null&&n!==void 0){let r=o[i];if(!r){Pr&&console.log(i,"is undefined on",o);continue}for(let s of Object.keys(n))r[s]===void 0&&t(n[s])&&!t(r)&&(r[s]=n[s])}}function t(i){switch(typeof i){case"number":case"string":case"boolean":return!0}return!1}}function pc(o,e,t,i,n){let r=typeof e=="function"&&e.prototype===void 0,s=e;if(r)try{if(s=e?.call(e,n),r=!1,s==null)return}catch(l){console.error("Error in callback",l,o)}if(!r&&n instanceof s)return n;if(n&&typeof n=="object"&&gh(n)){if(n.__concreteInstance)return n.__concreteInstance;let l=n;if(!l.$serializedTypes&&s.prototype.$serializedTypes&&(l.$serializedTypes=s.prototype.$serializedTypes),l.$serializedTypes&&ys(l,o,t),n&&s!==void 0)try{let d=new s;Te&&console.log("Create concrete instance for persistent asset",n,"instance:",d),oi(d,n),n.__concreteInstance=d,n=d}catch(d){console.error("Error creating instance or creating values on instance",d,n,s)}return n}if(i||(i={serializer:da.getSerializerForConstructor(s)}),Array.isArray(o)){let l=[];for(let d=0;d<o.length;d++){let h=o[d],b=pc(h,e,t,i,h);l.push(b)}return l}let a=i.serializer;if(a)return a.onDeserialize(o,t);let c;o&&(o.isMaterial||o.isTexture||o.isObject3D)?c=o:c=new s(...Pm(o));let u=c;return u.$serializedTypes&&ys(u,o,t),c}function Pm(o){if(ua.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(let e of Object.keys(o))ua.push(o[e]);return ua}var pa=Symbol("assigned component properties");function oi(o,e,t){if(e==null||o==null)return;let i=!1;o[pa]=!0;let n=o.constructor?.name??"unknown";t?.registerDefinedKeys(n,o);for(let r of Object.keys(e)){let s=Om(o,r);i&&s===void 0||(!s||s.writable===!0||s?.set!==void 0)&&(o[r]=e[r])}delete o[pa]}function Om(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}var _s=M("debuginput"),xs=class{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}};var fa=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]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new si.Vector2];_pointerPositionsLastFrame=[new si.Vector2];_pointerPositionsDelta=[new si.Vector2];_pointerPositionsRC=[new si.Vector2];_pointerPositionDown=[new si.Vector2];_pointerDownTime=[];_pointerUpTime=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_mouseWheelDeltaY=[0];_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){_s&&Ze("Create Pointer down"),this.onDown(e)}createPointerMove(e){_s&&Ze("Create Pointer move"),this.onMove(e)}createPointerUp(e){_s&&Ze("Create Pointer up"),this.onUp(e)}convertScreenspaceToRaycastSpace(e){e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1}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;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0}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 xs(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 xs(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 xs(e)))}onMouseWheel(e){this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;let t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY}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)}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})}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 si.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),this.onDispatchEvent("pointermove",e))}onUp(e){if(this.setPointerState(e.button,this._pointerPressed,!1),this.setPointerStateT(e.button,this._pointerEvent,e.source),!this.isInRect(e)){_s&&vs("Pointer out of bounds: "+e.clientX+", "+e.clientY);return}if(this.setPointerState(e.button,this._pointerUp,!0),this.updatePointerPosition(e),!this._pointerPositionDown[e.button]){_s&&vs("Received pointer up event without matching down event for button: "+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,this.onDispatchEvent("pointerup",e)}updatePointerPosition(e){for(;e.button>=this._pointerPositions.length;)this._pointerPositions.push(new si.Vector2);for(;e.button>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new si.Vector2);for(;e.button>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new si.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 si.Vector2);let r=this._pointerPositionsRC[e.button];r.set(i,n),this.convertScreenspaceToRaycastSpace(r)}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=V.Current;try{V.Current=this.context;let n=new Event(e);oi(n,t),this.dispatchEvent(n)}finally{V.Current=i}}};import{Box3 as vg,BufferAttribute as np,BufferGeometry as yg,Layers as Mc,LineBasicMaterial as _g,LineSegments as xg,Matrix4 as wg,Quaternion as Eg,Raycaster as Cg,Sphere as Tg,Vector2 as Rg,Vector3 as Sc}from"three";import*as de from"three";var mc=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}remap(e,t,i,n,r){return n+(r-n)*(e-t)/(i-t)}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}gammaToLinear(e){return Math.pow(e,2.2)}linearToGamma(e){return Math.pow(e,1/2.2)}},F=new mc;import{WebGLRenderer as km,Vector3 as Mm,Quaternion as Im,Uniform as vh,Texture as Dm,ShaderMaterial as yh}from"three";var Cx=new Im().setFromAxisAngle(new Mm(0,1,0),Math.PI);var bc=new Wn(()=>new de.Vector3,100);function U(o,e=null,t=!0){let i=e??bc.get();return o?o.parent?(t&&o.updateWorldMatrix(!0,!1),o.matrixWorldNeedsUpdate&&o.updateMatrixWorld(),i.setFromMatrixPosition(o.matrixWorld),i):i.copy(o.position):i.set(0,0,0)}function te(o,e){if(!o)return;let t=bc.get();e!==t&&t.copy(e),(o?.parent??o).worldToLocal(t),o.position.set(t.x,t.y,t.z)}function bn(o,e,t,i){let n=bc.get();n.set(e,t,i),te(o,n)}var Or=new de.Quaternion,ws=new de.Quaternion,gc=new de.Quaternion;function he(o,e=null){if(!o)return ws.set(0,0,0,1);let t=e??ws;return o.parent?(o.getWorldQuaternion(t),t):t.copy(o.quaternion)}function $e(o,e){if(!o)return;e!==Or&&Or.copy(e);let t=Or;o?.parent?.getWorldQuaternion(gc),gc.invert();let n=gc.multiply(t);o.quaternion.set(n.x,n.y,n.z,n.w)}function wh(o,e,t,i,n){Or.set(e,t,i,n),$e(o,Or)}var ma=new de.Vector3,Tx=new de.Vector3;function Fe(o,e=null){return o?o.parent?(o.getWorldScale(e??ma),e??ma):ma.copy(o.scale):ma.set(0,0,0)}var Rx=new de.Vector3,Sx=new de.Quaternion;var _h=new de.Euler,xh=new de.Euler,Am=new de.Vector3;function Lm(o){return o.getWorldQuaternion(ws),xh.setFromQuaternion(ws),xh}function Eh(o,e){$e(o,ws.setFromEuler(e))}function ga(o){let e=Lm(o),t=Am;return t.set(e.x,e.y,e.z),t.x=F.toDegrees(t.x),t.y=F.toDegrees(t.y),t.z=F.toDegrees(t.z),t}function ba(o,e,t,i,n=!0){n&&(e=F.toRadians(e),t=F.toRadians(t),i=F.toRadians(i)),_h.set(e,t,i),Or.setFromEuler(_h),$e(o,Or)}function Es(o,e=!0){!o||(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(o):o.traverse(function(t){for(var i="|___",n=t;n.parent!==null;)i=" "+i,n=n.parent;console.log(i+t.name+" <"+t.type+">")}))}function Ch(o){if(o){let e=o;return e.blendMode!==void 0&&e.clampWhenFinished!==void 0&&e.enabled!==void 0&&e.fadeIn!==void 0&&e.getClip!==void 0}return!1}var So=class{static createBlitMaterial(e){return new yh({uniforms:{map:new vh(null)},vertexShader:this.vertex,fragmentShader:e})}static copyTexture(e,t){let i=t??this.blipMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;let n=this.mesh;n.material=i,n.frustumCulled=!1,this.scene.children.length=0,this.scene.add(n),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);let r=new Dm(this.renderer.domElement);return r.name="Copy",r.needsUpdate=!0,r}static textureToCanvas(e,t){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=jm(e));let i=e.image;if(Hm(i)){let n=document.createElement("canvas");n.width=i.width,n.height=i.height;let r=n.getContext("2d");return r?(r.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}},ai=So;L(ai,"planeGeometry",new de.PlaneGeometry(2,2,1,1)),L(ai,"renderer",new km({antialias:!1})),L(ai,"perspectiveCam",new de.PerspectiveCamera),L(ai,"scene",new de.Scene),L(ai,"vertex",`
|
|
132
132
|
varying vec2 vUv;
|
|
133
133
|
void main(){
|
|
134
134
|
vUv = uv;
|
|
@@ -141,13 +141,13 @@ in script ${i}.ts
|
|
|
141
141
|
uv.y = 1.0 - uv.y;
|
|
142
142
|
gl_FragColor = texture2D( map, uv);
|
|
143
143
|
// gl_FragColor = vec4(uv.xy, 0, 1);
|
|
144
|
-
}`),L(ai,"blipMaterial",new yh({uniforms:{map:new vh(null)},vertexShader:So.vertex,fragmentShader:So.fragment})),L(ai,"mesh",new de.Mesh(So.planeGeometry,So.blipMaterial));function jm(o){return ai.copyTexture(o)}function Hm(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}import{Vector3 as Fm}from"three";var jx=Symbol("object"),Th=new Wn(()=>new Fm,20),va=class{_point;_normal;distance;impulse;friction;get point(){return Th.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return Th.get().set(this._normal.x,this._normal.y,this._normal.z)}constructor(e,t,i,n,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=r}},Cs=class{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}};function Mr(o,e){try{e?o(e):o()}catch(t){return console.error(t),!1}return!0}var Mi="__isActiveInHierarchy",Ir="builtin_components";var Gm=M("debugnewscripts"),pe=[];function vn(o){if(!(o.new_scripts.length<=0)){if(Gm&&console.log("Register new components",o.new_scripts.length,o.alias?"element: "+o.alias:""),o.new_scripts_pre_setup_callbacks.length>0){for(let e of o.new_scripts_pre_setup_callbacks)!e||e();o.new_scripts_pre_setup_callbacks.length=0}pe.length=0,o.new_scripts.length>0&&pe.push(...o.new_scripts),o.new_scripts.length=0;for(let e=0;e<pe.length;e++)try{let t=pe[e];if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),pe.splice(e,1),e--;continue}t.context=o,Ts(t.gameObject),yc(t,o)}catch(t){console.error(t),bn(pe[e],o),pe.splice(e,1),e--}for(let e=0;e<pe.length;e++)try{let t=pe[e];if(t.destroyed){bn(pe[e],o),pe.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),Ts(t.gameObject),t.activeAndEnabled&&Mr(t.__internalAwake.bind(t)))}catch(t){console.error(t),bn(pe[e],o),pe.splice(e,1),e--}for(let e=0;e<pe.length;e++)try{let t=pe[e];if(t.destroyed||t.enabled===!1||(Ts(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Mr(t.__internalEnable.bind(t)))}catch(t){console.error(t),bn(pe[e],o),pe.splice(e,1),e--}for(let e=0;e<pe.length;e++)try{let t=pe[e];if(t.destroyed||!t.gameObject)continue;o.new_script_start.push(t)}catch(t){console.error(t),bn(pe[e],o),pe.splice(e,1),e--}pe.length=0;for(let e of o.new_scripts_post_setup_callbacks)e&&e();o.new_scripts_post_setup_callbacks.length=0}}function Rh(o){!o||(o.__internalDisable(),bn(o,o.context))}function ya(o,e){for(let t=0;t<o.new_script_start.length;t++)try{let i=o.new_script_start[t];if(e!==void 0&&i.gameObject!==e||i.destroyed||i.activeAndEnabled===!1)continue;Mr(i.__internalAwake.bind(i)),Mr(i.__internalEnable.bind(i)),Mr(i.__internalStart.bind(i)),o.new_script_start.splice(t,1),t--}catch(i){console.error(i),bn(o.new_script_start[t],o),o.new_script_start.splice(t,1),t--}}function yc(o,e){e.scripts.indexOf(o)===-1&&(e.scripts.push(o),o.earlyUpdate&&e.scripts_earlyUpdate.push(o),o.update&&e.scripts_update.push(o),o.lateUpdate&&e.scripts_lateUpdate.push(o),o.onBeforeRender&&e.scripts_onBeforeRender.push(o),o.onAfterRender&&e.scripts_onAfterRender.push(o))}function bn(o,e){Qn(o,e.new_scripts),Qn(o,e.new_script_start),Qn(o,e.scripts),Qn(o,e.scripts_earlyUpdate),Qn(o,e.scripts_update),Qn(o,e.scripts_lateUpdate),Qn(o,e.scripts_onBeforeRender),Qn(o,e.scripts_onAfterRender),e.stopAllCoroutinesFrom(o)}function Qn(o,e){let t=e.indexOf(o);t>=0&&e.splice(t,1)}var Vm={},vc={};function Po(o){if(o||(o=V.Current.scene),!o){console.trace("Invalid call - no current context.");return}Sh(o,Dr(o),!0)}function Sh(o,e,t){let i=!1,n=Dr(o);if(Vm[o.uuid]=n,e&&(e=Dr(o)),o[Mi]=e,!i){let r=vc[o.uuid];r!==void 0&&r!==e&&t&&zm(o,s=>{e?(Mr(s.__internalAwake.bind(s)),s.enabled=!0):s.enabled=!1})}if(vc[o.uuid]=e,o.children)for(let r of o.children)Sh(r,e,t)}function Ts(o){let e=!0,t=o,i=!1;for(;t&&t;){if(t.type==="Scene"&&(i=!0),!Dr(t)){e=!1;break}t=t.parent}if(!o){console.error("GO is null");return}vc[o.uuid]=e,o[Mi]=e&&i}function zm(o,e){if(o.userData?.components)for(let t of o.userData.components)e(t)}import*as Rs from"three";var Oh=/^(?:[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 Wm(o){return typeof o=="string"&&Oh.test(o)}var kh=Wm;var Be=[];for(let o=0;o<256;++o)Be.push((o+256).toString(16).slice(1));function Mh(o,e=0){return(Be[o[e+0]]+Be[o[e+1]]+Be[o[e+2]]+Be[o[e+3]]+"-"+Be[o[e+4]]+Be[o[e+5]]+"-"+Be[o[e+6]]+Be[o[e+7]]+"-"+Be[o[e+8]]+Be[o[e+9]]+"-"+Be[o[e+10]]+Be[o[e+11]]+Be[o[e+12]]+Be[o[e+13]]+Be[o[e+14]]+Be[o[e+15]]).toLowerCase()}function Nm(o){if(!kh(o))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(o.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(o.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(o.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(o.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(o.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var Ih=Nm;function Xm(o){o=unescape(encodeURIComponent(o));let e=[];for(let t=0;t<o.length;++t)e.push(o.charCodeAt(t));return e}var Qm="6ba7b810-9dad-11d1-80b4-00c04fd430c8",qm="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function _c(o,e,t){function i(n,r,s,a){var c;if(typeof n=="string"&&(n=Xm(n)),typeof r=="string"&&(r=Ih(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 u=new Uint8Array(16+n.length);if(u.set(r),u.set(n,r.length),u=t(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,s){a=a||0;for(let l=0;l<16;++l)s[a+l]=u[l];return s}return Mh(u)}try{i.name=o}catch{}return i.DNS=Qm,i.URL=qm,i}function Ym(o,e,t,i){switch(o){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 xc(o,e){return o<<e|o>>>32-e}function Km(o){let e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof o=="string"){let s=unescape(encodeURIComponent(o));o=[];for(let a=0;a<s.length;++a)o.push(s.charCodeAt(a))}else Array.isArray(o)||(o=Array.prototype.slice.call(o));o.push(128);let i=o.length/4+2,n=Math.ceil(i/16),r=new Array(n);for(let s=0;s<n;++s){let a=new Uint32Array(16);for(let c=0;c<16;++c)a[c]=o[s*64+c*4]<<24|o[s*64+c*4+1]<<16|o[s*64+c*4+2]<<8|o[s*64+c*4+3];r[s]=a}r[n-1][14]=(o.length-1)*8/Math.pow(2,32),r[n-1][14]=Math.floor(r[n-1][14]),r[n-1][15]=(o.length-1)*8&4294967295;for(let s=0;s<n;++s){let a=new Uint32Array(80);for(let b=0;b<16;++b)a[b]=r[s][b];for(let b=16;b<80;++b)a[b]=xc(a[b-3]^a[b-8]^a[b-14]^a[b-16],1);let c=t[0],u=t[1],l=t[2],d=t[3],h=t[4];for(let b=0;b<80;++b){let _=Math.floor(b/20),v=xc(c,5)+Ym(_,u,l,d)+h+e[_]+a[b]>>>0;h=d,d=l,l=xc(u,30)>>>0,u=c,c=v}t[0]=t[0]+c>>>0,t[1]=t[1]+u>>>0,t[2]=t[2]+l>>>0,t[3]=t[3]+d>>>0,t[4]=t[4]+h>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}var Dh=Km;var Jm=_c("v5",80,Dh),wc=Jm;var _a=M("debugcomponents"),Zm="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,wc(e.toString(),Zm)}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 xa=class{guid;constructor(e){this.guid=e}};function Oo(o,e,t=!0){if(!o)return;let i=o;if(li(o,t),!e){console.warn("Can not send destroy: No networking connection provided",o.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",o.guid);return}let n=o.guid;if(!n&&i.uuid&&(n=i.uuid),!n){console.warn("Can not send destroy: failed to find guid",o);return}let r=new xa(n);e.send("instance-destroyed",r,2)}function Ah(o,e){let t=new xa(o);e.send("instance-destroyed",t,2)}function Lh(o){o.connection.beginListen("instance-destroyed",e=>{_a&&console.log("[Remote] Destroyed",o.scene,e);let t=Ar(e.guid,o.scene);t&&li(t)})}var Ec=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function wa(o,e,t,i){let n=o;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(e.context||(e.context=V.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;let r=e?{...e}:null,{instance:s,seed:a}=$m(n,e);if(s){let c=s;if(c.guid){_a&&console.log("[Local] new instance","gameobject:",s?.guid);let u=new Ec(n.guid,c.guid);u.seed=a,r&&(r.position&&(u.position={x:r.position.x,y:r.position.y,z:r.position.z}),r.rotation&&(u.rotation={x:r.rotation.x,y:r.rotation.y,z:r.rotation.z,w:r.rotation.w}),r.scale&&(u.scale={x:r.scale.x,y:r.scale.y,z:r.scale.z})),u.position||(u.position={x:c.position.x,y:c.position.y,z:c.position.z}),u.rotation||(u.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),u.scale||(u.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),u.visible=n.visible,r?.parent&&(typeof r.parent=="string"?u.parent=r.parent:u.parent=r.parent.guid),u.hostData=t,i===!1&&(u.dontSave=!0),e?.context?.connection.send("new-instance-created",u)}else console.warn("Missing guid, can not send new instance event",c)}return s}function Ea(){return Math.random()*9999999}function jh(o){o.connection.beginListen("new-instance-created",async e=>{let t=await eg(e.originalGuid,o.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let i=new Ge;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=o,_a&&o.alias&&console.log("[Remote] instantiate in: "+o.alias);let n=Lr(t,i);n&&(e.parent==="scene"&&o.scene.add(n),_a&&console.log("[Remote] new instance","gameobject:",n?.guid,t))})}function $m(o,e){let t=Ea(),i=e??new Ge;i.idProvider=new Ue(t);let n=Lr(o,i);return{seed:t,instance:n}}var Hh={};function Fh(o,e){Hh[o]=e}async function eg(o,e){let t=Hh[o];if(t!=null){let i=await t(o);if(i)return i}return Bh(o,e)}function Bh(o,e){if(e===null||!o)return null;if(e.guid===o)return e;if(e.children)for(let t of e.children){let i=Bh(o,t);if(i)return i}return null}var Uh=new Map;function Gh(o,e){if(!o)return;if(!e){console.warn("No prototype found",o,o.prototype,o.constructor);return}let t=Uh.get(e);t&&t.apply(o)}function Vh(o){let e=tg(o.prototype);Uh.set(o,e)}function tg(o){return new Tc(o)}var Tc=class{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){let i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){let i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}};import{Object3D as lt}from"three";var Rc=M("debuggetcomponent");function ig(o){return o==null||o.isObject3D?o:o.object&&o.object.isObject3D?o.object:o}function Ca(o,e){if(!o||!o.userData.components)return;let t=o.userData.components.indexOf(e);t<0||(e.gameObject=null,o.userData.components.splice(t,1))}function Ta(o,e){let t=jr(o,e);if(t)return t;let i=new e;return qn(o,i)}function qn(o,e,t=!0){o||new Error("Can not add componet to null object"),o.userData||(o.userData={}),o.userData.components||(o.userData.components=[]),o.userData.components.push(e),e.gameObject=o,Do(o),Ra(e);try{e.__internalAwake&&t&&(Ts(o),e.__internalAwake())}catch(i){console.error(i)}return e}function Wh(o,e){if(e.gameObject!==o){if(e.gameObject&&e.gameObject.userData.components){let t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}if(!o.userData.components)o.userData.components=[];else if(o.userData.components.includes(e))return;o.userData.components.push(e),e.gameObject=o}}function Nh(o){if(o.gameObject&&o.gameObject.userData.components){let e=o.gameObject.userData.components.indexOf(o);o.gameObject.userData.components.splice(e,1)}o.__internalDisable&&o.__internalDisable(),o.onDestroy&&o.onDestroy(),bn(o,o.context??V.Current),o.__internalDestroy(),o.gameObject=null}var zh=!1;function Xh(o,e,t){if(o!=null){if(!o.isObject3D){console.error("Object is not object3D");return}if(!o?.userData?.components)return null;if(typeof e=="string"&&(zh||(zh=!0,console.warn(`Accessing components by name is not supported.
|
|
144
|
+
}`),L(ai,"blipMaterial",new yh({uniforms:{map:new vh(null)},vertexShader:So.vertex,fragmentShader:So.fragment})),L(ai,"mesh",new de.Mesh(So.planeGeometry,So.blipMaterial));function jm(o){return ai.copyTexture(o)}function Hm(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}import{Vector3 as Fm}from"three";var jx=Symbol("object"),Th=new Wn(()=>new Fm,20),va=class{_point;_normal;distance;impulse;friction;get point(){return Th.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return Th.get().set(this._normal.x,this._normal.y,this._normal.z)}constructor(e,t,i,n,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=r}},Cs=class{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}};function Mr(o,e){try{e?o(e):o()}catch(t){return console.error(t),!1}return!0}var Ii="__isActiveInHierarchy",Ir="builtin_components";var Gm=M("debugnewscripts"),pe=[];function yn(o){if(!(o.new_scripts.length<=0)){if(Gm&&console.log("Register new components",o.new_scripts.length,o.alias?"element: "+o.alias:""),o.new_scripts_pre_setup_callbacks.length>0){for(let e of o.new_scripts_pre_setup_callbacks)!e||e();o.new_scripts_pre_setup_callbacks.length=0}pe.length=0,o.new_scripts.length>0&&pe.push(...o.new_scripts),o.new_scripts.length=0;for(let e=0;e<pe.length;e++)try{let t=pe[e];if(t.destroyed)continue;if(!t.gameObject){console.error("MISSING GAMEOBJECT - will ignore",t),pe.splice(e,1),e--;continue}t.context=o,Ts(t.gameObject),yc(t,o)}catch(t){console.error(t),vn(pe[e],o),pe.splice(e,1),e--}for(let e=0;e<pe.length;e++)try{let t=pe[e];if(t.destroyed){vn(pe[e],o),pe.splice(e,1),e--;continue}t.__internalAwake!==void 0&&(t.gameObject||console.error("MISSING GAMEOBJECT",t,t.gameObject),Ts(t.gameObject),t.activeAndEnabled&&Mr(t.__internalAwake.bind(t)))}catch(t){console.error(t),vn(pe[e],o),pe.splice(e,1),e--}for(let e=0;e<pe.length;e++)try{let t=pe[e];if(t.destroyed||t.enabled===!1||(Ts(t.gameObject),t.activeAndEnabled===!1))continue;t.__internalEnable!==void 0&&(t.enabled=!0,Mr(t.__internalEnable.bind(t)))}catch(t){console.error(t),vn(pe[e],o),pe.splice(e,1),e--}for(let e=0;e<pe.length;e++)try{let t=pe[e];if(t.destroyed||!t.gameObject)continue;o.new_script_start.push(t)}catch(t){console.error(t),vn(pe[e],o),pe.splice(e,1),e--}pe.length=0;for(let e of o.new_scripts_post_setup_callbacks)e&&e();o.new_scripts_post_setup_callbacks.length=0}}function Rh(o){!o||(o.__internalDisable(),vn(o,o.context))}function ya(o,e){for(let t=0;t<o.new_script_start.length;t++)try{let i=o.new_script_start[t];if(e!==void 0&&i.gameObject!==e||i.destroyed||i.activeAndEnabled===!1)continue;Mr(i.__internalAwake.bind(i)),Mr(i.__internalEnable.bind(i)),Mr(i.__internalStart.bind(i)),o.new_script_start.splice(t,1),t--}catch(i){console.error(i),vn(o.new_script_start[t],o),o.new_script_start.splice(t,1),t--}}function yc(o,e){e.scripts.indexOf(o)===-1&&(e.scripts.push(o),o.earlyUpdate&&e.scripts_earlyUpdate.push(o),o.update&&e.scripts_update.push(o),o.lateUpdate&&e.scripts_lateUpdate.push(o),o.onBeforeRender&&e.scripts_onBeforeRender.push(o),o.onAfterRender&&e.scripts_onAfterRender.push(o))}function vn(o,e){Qn(o,e.new_scripts),Qn(o,e.new_script_start),Qn(o,e.scripts),Qn(o,e.scripts_earlyUpdate),Qn(o,e.scripts_update),Qn(o,e.scripts_lateUpdate),Qn(o,e.scripts_onBeforeRender),Qn(o,e.scripts_onAfterRender),e.stopAllCoroutinesFrom(o)}function Qn(o,e){let t=e.indexOf(o);t>=0&&e.splice(t,1)}var Vm={},vc={};function Po(o){if(o||(o=V.Current.scene),!o){console.trace("Invalid call - no current context.");return}Sh(o,Dr(o),!0)}function Sh(o,e,t){let i=!1,n=Dr(o);if(Vm[o.uuid]=n,e&&(e=Dr(o)),o[Ii]=e,!i){let r=vc[o.uuid];r!==void 0&&r!==e&&t&&zm(o,s=>{e?(Mr(s.__internalAwake.bind(s)),s.enabled=!0):s.enabled=!1})}if(vc[o.uuid]=e,o.children)for(let r of o.children)Sh(r,e,t)}function Ts(o){let e=!0,t=o,i=!1;for(;t&&t;){if(t.type==="Scene"&&(i=!0),!Dr(t)){e=!1;break}t=t.parent}if(!o){console.error("GO is null");return}vc[o.uuid]=e,o[Ii]=e&&i}function zm(o,e){if(o.userData?.components)for(let t of o.userData.components)e(t)}import*as Rs from"three";var Oh=/^(?:[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 Wm(o){return typeof o=="string"&&Oh.test(o)}var kh=Wm;var Be=[];for(let o=0;o<256;++o)Be.push((o+256).toString(16).slice(1));function Mh(o,e=0){return(Be[o[e+0]]+Be[o[e+1]]+Be[o[e+2]]+Be[o[e+3]]+"-"+Be[o[e+4]]+Be[o[e+5]]+"-"+Be[o[e+6]]+Be[o[e+7]]+"-"+Be[o[e+8]]+Be[o[e+9]]+"-"+Be[o[e+10]]+Be[o[e+11]]+Be[o[e+12]]+Be[o[e+13]]+Be[o[e+14]]+Be[o[e+15]]).toLowerCase()}function Nm(o){if(!kh(o))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(o.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(o.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(o.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(o.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(o.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var Ih=Nm;function Xm(o){o=unescape(encodeURIComponent(o));let e=[];for(let t=0;t<o.length;++t)e.push(o.charCodeAt(t));return e}var Qm="6ba7b810-9dad-11d1-80b4-00c04fd430c8",qm="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function _c(o,e,t){function i(n,r,s,a){var c;if(typeof n=="string"&&(n=Xm(n)),typeof r=="string"&&(r=Ih(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 u=new Uint8Array(16+n.length);if(u.set(r),u.set(n,r.length),u=t(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,s){a=a||0;for(let l=0;l<16;++l)s[a+l]=u[l];return s}return Mh(u)}try{i.name=o}catch{}return i.DNS=Qm,i.URL=qm,i}function Ym(o,e,t,i){switch(o){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 xc(o,e){return o<<e|o>>>32-e}function Km(o){let e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof o=="string"){let s=unescape(encodeURIComponent(o));o=[];for(let a=0;a<s.length;++a)o.push(s.charCodeAt(a))}else Array.isArray(o)||(o=Array.prototype.slice.call(o));o.push(128);let i=o.length/4+2,n=Math.ceil(i/16),r=new Array(n);for(let s=0;s<n;++s){let a=new Uint32Array(16);for(let c=0;c<16;++c)a[c]=o[s*64+c*4]<<24|o[s*64+c*4+1]<<16|o[s*64+c*4+2]<<8|o[s*64+c*4+3];r[s]=a}r[n-1][14]=(o.length-1)*8/Math.pow(2,32),r[n-1][14]=Math.floor(r[n-1][14]),r[n-1][15]=(o.length-1)*8&4294967295;for(let s=0;s<n;++s){let a=new Uint32Array(80);for(let b=0;b<16;++b)a[b]=r[s][b];for(let b=16;b<80;++b)a[b]=xc(a[b-3]^a[b-8]^a[b-14]^a[b-16],1);let c=t[0],u=t[1],l=t[2],d=t[3],h=t[4];for(let b=0;b<80;++b){let _=Math.floor(b/20),v=xc(c,5)+Ym(_,u,l,d)+h+e[_]+a[b]>>>0;h=d,d=l,l=xc(u,30)>>>0,u=c,c=v}t[0]=t[0]+c>>>0,t[1]=t[1]+u>>>0,t[2]=t[2]+l>>>0,t[3]=t[3]+d>>>0,t[4]=t[4]+h>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}var Dh=Km;var Jm=_c("v5",80,Dh),wc=Jm;var _a=M("debugcomponents"),Zm="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,wc(e.toString(),Zm)}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 xa=class{guid;constructor(e){this.guid=e}};function Oo(o,e,t=!0){if(!o)return;let i=o;if(li(o,t),!e){console.warn("Can not send destroy: No networking connection provided",o.guid);return}if(!e.isConnected){console.warn("Can not send destroy: not connected",o.guid);return}let n=o.guid;if(!n&&i.uuid&&(n=i.uuid),!n){console.warn("Can not send destroy: failed to find guid",o);return}let r=new xa(n);e.send("instance-destroyed",r,2)}function Ah(o,e){let t=new xa(o);e.send("instance-destroyed",t,2)}function Lh(o){o.connection.beginListen("instance-destroyed",e=>{_a&&console.log("[Remote] Destroyed",o.scene,e);let t=Ar(e.guid,o.scene);t&&li(t)})}var Ec=class{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;constructor(e,t){this.originalGuid=e,this.guid=t}};function wa(o,e,t,i){let n=o;if(!n.guid)return console.warn("Can not instantiate: No guid",n),null;if(e.context||(e.context=V.Current),!e.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;let r=e?{...e}:null,{instance:s,seed:a}=$m(n,e);if(s){let c=s;if(c.guid){_a&&console.log("[Local] new instance","gameobject:",s?.guid);let u=new Ec(n.guid,c.guid);u.seed=a,r&&(r.position&&(u.position={x:r.position.x,y:r.position.y,z:r.position.z}),r.rotation&&(u.rotation={x:r.rotation.x,y:r.rotation.y,z:r.rotation.z,w:r.rotation.w}),r.scale&&(u.scale={x:r.scale.x,y:r.scale.y,z:r.scale.z})),u.position||(u.position={x:c.position.x,y:c.position.y,z:c.position.z}),u.rotation||(u.rotation={x:c.quaternion.x,y:c.quaternion.y,z:c.quaternion.z,w:c.quaternion.w}),u.scale||(u.scale={x:c.scale.x,y:c.scale.y,z:c.scale.z}),u.visible=n.visible,r?.parent&&(typeof r.parent=="string"?u.parent=r.parent:u.parent=r.parent.guid),u.hostData=t,i===!1&&(u.dontSave=!0),e?.context?.connection.send("new-instance-created",u)}else console.warn("Missing guid, can not send new instance event",c)}return s}function Ea(){return Math.random()*9999999}function jh(o){o.connection.beginListen("new-instance-created",async e=>{let t=await eg(e.originalGuid,o.scene);if(!t){console.warn("could not find object that was instantiated: "+e.guid);return}let i=new Ge;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=o,_a&&o.alias&&console.log("[Remote] instantiate in: "+o.alias);let n=Lr(t,i);n&&(e.parent==="scene"&&o.scene.add(n),_a&&console.log("[Remote] new instance","gameobject:",n?.guid,t))})}function $m(o,e){let t=Ea(),i=e??new Ge;i.idProvider=new Ue(t);let n=Lr(o,i);return{seed:t,instance:n}}var Hh={};function Fh(o,e){Hh[o]=e}async function eg(o,e){let t=Hh[o];if(t!=null){let i=await t(o);if(i)return i}return Bh(o,e)}function Bh(o,e){if(e===null||!o)return null;if(e.guid===o)return e;if(e.children)for(let t of e.children){let i=Bh(o,t);if(i)return i}return null}var Uh=new Map;function Gh(o,e){if(!o)return;if(!e){console.warn("No prototype found",o,o.prototype,o.constructor);return}let t=Uh.get(e);t&&t.apply(o)}function Vh(o){let e=tg(o.prototype);Uh.set(o,e)}function tg(o){return new Tc(o)}var Tc=class{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){let i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){let i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}};import{Object3D as lt}from"three";var Rc=M("debuggetcomponent");function ig(o){return o==null||o.isObject3D?o:o.object&&o.object.isObject3D?o.object:o}function Ca(o,e){if(!o||!o.userData.components)return;let t=o.userData.components.indexOf(e);t<0||(e.gameObject=null,o.userData.components.splice(t,1))}function Ta(o,e){let t=jr(o,e);if(t)return t;let i=new e;return qn(o,i)}function qn(o,e,t=!0){o||new Error("Can not add componet to null object"),o.userData||(o.userData={}),o.userData.components||(o.userData.components=[]),o.userData.components.push(e),e.gameObject=o,Do(o),Ra(e);try{e.__internalAwake&&t&&(Ts(o),e.__internalAwake())}catch(i){console.error(i)}return e}function Wh(o,e){if(e.gameObject!==o){if(e.gameObject&&e.gameObject.userData.components){let t=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(t,1)}if(!o.userData.components)o.userData.components=[];else if(o.userData.components.includes(e))return;o.userData.components.push(e),e.gameObject=o}}function Nh(o){if(o.gameObject&&o.gameObject.userData.components){let e=o.gameObject.userData.components.indexOf(o);o.gameObject.userData.components.splice(e,1)}o.__internalDisable&&o.__internalDisable(),o.onDestroy&&o.onDestroy(),vn(o,o.context??V.Current),o.__internalDestroy(),o.gameObject=null}var zh=!1;function Xh(o,e,t){if(o!=null){if(!o.isObject3D){console.error("Object is not object3D");return}if(!o?.userData?.components)return null;if(typeof e=="string"&&(zh||(zh=!0,console.warn(`Accessing components by name is not supported.
|
|
145
145
|
Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
|
|
146
146
|
|
|
147
147
|
You can import other modules your main module to get access to types
|
|
148
148
|
or if you use npmdefs you can make types available globally using globalThis:
|
|
149
|
-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`))),Rc&&console.log("FIND",e),e!=null){for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i];if(e===null||n.constructor.name===e.name||n.constructor.name===e)if(Rc&&console.log("MATCH BY NAME",n),t)t.push(n);else return n}for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i],r=Object.getPrototypeOf(n.constructor);do{if(r===e)if(Rc&&console.log("MATCH BY PROTOYPE",r),t)t.push(n);else return n;r=Object.getPrototypeOf(r)}while(r)}return t}}}function jr(o,e){return Xh(o,e)}function Mo(o,e,t){return t||(t=[]),Xh(o,e,t)}function Hr(o,e,t){let i=jr(o,e);if(t===!1&&i.enabled===!1)return null;if(i)return i;for(let n=0;n<o?.children?.length;n++){let r=Hr(o.children[n],e);if(r)return r}return null}function Io(o,e,t){t||(t=[]),Mo(o,e,t);for(let i=0;i<o?.children?.length;i++)Io(o.children[i],e,t);return t}function ko(o,e){if(!o)return null;if(Array.isArray(o)){for(let i=0;i<o.length;i++){let n=ig(o[i]),r=ko(n,e);if(r)return r}return null}let t=jr(o,e);return t||(o.parent?ko(o.parent,e):null)}function Ss(o,e,t){return t||(t=[]),o?(Mo(o,e,t),o.parent?Ss(o.parent,e,t):t):t}function Qh(o,e,t){if(!o)return null;if(!e&&(e=V.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e;if(i.isScene||(i=e?.scene),!i)return null;for(let n in i.children){let r=i.children[n];if(t===!1&&r[Mi]===!1)continue;if(r.constructor==o)return r;let s=Hr(r,o);if(s)return s}return null}function qh(o,e,t){if(!o)return e;if(!t&&(t=V.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;let 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==o)return r;Io(r,o,e)}return e}function Do(o){o&&o.isObject3D===!0&&Gh(o,lt)}lt.prototype.SetActive=function(o){this.visible=o};lt.prototype.addNewComponent=function(o){return qn(this,new o)};lt.prototype.removeComponent=function(o){return Ca(this,o)};lt.prototype.getOrAddComponent=function(o){return Ta(this,o)};lt.prototype.getComponent=function(o){return jr(this,o)};lt.prototype.getComponents=function(o,e){return Mo(this,o,e)};lt.prototype.getComponentInChildren=function(o){return Hr(this,o)};lt.prototype.getComponentsInChildren=function(o,e){return Io(this,o,e)};lt.prototype.getComponentInParent=function(o){return ko(this,o)};lt.prototype.getComponentsInParent=function(o,e){return Ss(this,o,e)};Object.getOwnPropertyDescriptor(lt.prototype,"activeSelf")||Object.defineProperty(lt.prototype,"activeSelf",{get:function(){return this.visible},set:function(o){let e=typeof o=="number"?o>.5:o;this.visible=e}});Vh(lt);var Sa=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),oe=class{static isUsingInstancing(e){return e.__isUsingInstancing===!0}static markDirty(e,t=!0){if(!!e&&(this.isUsingInstancing(e)&&(e[Sa]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)oe.markDirty(i,!0)}};var Fr=M("debuggetcomponent"),ng=(u=>(u[u.None=0]="None",u[u.HideInHierarchy=1]="HideInHierarchy",u[u.HideInInspector=2]="HideInInspector",u[u.DontSaveInEditor=4]="DontSaveInEditor",u[u.NotEditable=8]="NotEditable",u[u.DontSaveInBuild=16]="DontSaveInBuild",u[u.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",u[u.DontSave=52]="DontSave",u[u.HideAndDontSave=61]="HideAndDontSave",u))(ng||{}),Ge=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context},Pa=Symbol("isActive");function Dr(o){let e=o.visible||ka(o);return o[Pa]===void 0&&(o[Pa]=e),o[Pa]&&e}function Oa(o,e,t=!0){o[Pa]=e,t&&(o.visible=e)}function Kh(o){return o[Mi]||ka(o)}function Jh(o,e){o.__isUsingInstancing=e}function ka(o){return oe.isUsingInstancing(o)}function Ar(o,e){return Nn(o,e,!0,!0)}function li(o,e=!0,t=!0){let i=o;if(i.isComponent){i.__internalDisable(),i.__internalDestroy();return}let n=o;if(Fr&&console.log(n),e&&n.children)for(let s of n.children)li(s,e,!1);let r=n.userData.components;if(r){let s=r.length;for(let a=0;a<r.length;a++){let c=r[a];c.__internalDisable(),c.__internalDestroy(),r.length<s&&(s=r.length,a--)}}t&&n.removeFromParent()}function ci(o,e,t=!0){if(!!o){if(o.isObject3D||new Error("Expected Object3D but got "+o),o.userData?.components)for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i];if(n?.isComponent===!0){let r=e(n);if(r!==void 0)return r}}if(t&&o.children)for(let i=0;i<o.children.length;i++){let n=o.children[i];if(!n)continue;let r=ci(n,e,t);if(r!==void 0)return r}}}function Lr(o,e=null){if(o===null)return null;let t=null;e!==null&&(e.x!==void 0?(t=new Ge,t.position=e):t=e);let i=V.Current;t?.context&&(i=t.context),Fr&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new Ue(Date.now()));let n=[],r={},s={},a=Zh(i,o,t,n,r,s);a&&(og(r),rg(s,r)),Fr&&(Es(o,!0),Es(a,!0));let c={};for(let u in n){let l=n[u],d=l.guid;t&&t.idProvider&&(l.guid=t.idProvider.generateUUID(),c[d]=l.guid,Fr&&console.log(l.name,l.guid)),Ra(l,i),l.__internalNewInstanceCreated&&l.__internalNewInstanceCreated()}for(let u in n){let l=n[u];l.resolveGuids&&l.resolveGuids(c),l.enabled!==!1&&(l.enabled=!0)}return vn(i),a}function Zh(o,e,t,i,n,r){if(!e)return null;let s=e.userData;e.userData={};let a=e.children;e.children=[];let c;if(c=e.clone(!1),Do(c),e.userData=s,e.children=a,n[e.uuid]={original:e,clone:c},e.type==="SkinnedMesh"&&(r[e.uuid]={original:e,clone:c}),t?.visible!==void 0&&(c.visible=t.visible),t?.idProvider){c.uuid=t.idProvider.generateUUID();let l=c;l&&(l.guid=c.uuid)}e.animations&&e.animations.length>0&&(c.animations=[...e.animations]);let u=e.parent;if(u&&u.add(c),t?.position?te(c,t.position):c.position.copy(e.position),t?.rotation?$e(c,t.rotation):c.quaternion.copy(e.quaternion),t?.scale?c.scale.copy(t.scale):c.scale.copy(e.scale),t?.parent&&t.parent!=="scene"){let l=null;if(typeof t.parent=="string"?l=Nn(t.parent,o.scene,!0):l=t.parent,l){let d=t.keepWorldPosition===!0?l.attach:l.add;d?d.call(l,c):console.error("Invalid parent object",l,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(let[l,d]of Object.entries(e.userData))l!=="components"&&(c.userData[l]=d);if(e.userData?.components){let l=e.userData.components,d=[];c.userData.components=d;for(let h=0;h<l.length;h++){let b=l[h],_=Object.create(b);oi(_,b),d.push(_),_.gameObject=c,i.push(_)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(let l in e.children){let d=e.children[l],h=Zh(o,d,t,i,n,r);h&&c.add(h)}return c}function rg(o,e){for(let t in o){let i=o[t],n=i.original,r=n.skeleton,s=i.clone;if(!r){console.warn("Skinned mesh has no skeleton?",i);continue}let a=r.bones,c=s.skeleton.clone();s.skeleton=c,s.bindMatrix.clone().copy(n.bindMatrix),s.bindMatrixInverse.copy(n.bindMatrixInverse);let u=[];c.bones=u;for(let l=0;l<a.length;l++){let d=a[l],b=e[d.uuid].clone;u.push(b)}}for(let t in o){let i=o[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function og(o){for(let e in o){let i=o[e].clone;if(i.userData?.components)for(let n=0;n<i.userData.components.length;n++){let r=i.userData.components[n],s=Object.entries(r);for(let[a,c]of s)if(Array.isArray(c)){let u=[];r[a]=u;for(let l=0;l<c.length;l++){let d=c[l];if(typeof d!="object"){u.push(d);continue}let h=Yh(r,a,d,o);h!==void 0?u.push(h):u.push(d)}}else if(typeof c=="object"){let u=Yh(r,a,c,o);u!==void 0&&(r[a]=u)}}}}function Yh(o,e,t,i){if(t!=null){if(t.isComponent===!0){let n=t.gameObject;if(n){let r=n.uuid,s=i[r]?.clone;if(!s){Fr&&console.log("reference did not change",e,o,t);return}let a=n.userData.components.indexOf(t);if(a>=0)return Fr&&console.log(e,r),s.userData.components[a];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;let n=t;if(n){let r=n.uuid,s=i[r]?.clone;if(s)return Fr&&console.log(e,"old",t,"new",s),s}}}}import yn,{ActiveEvents as Sg,Collider as Pg,ColliderDesc as Ps,EventQueue as Og,JointData as kg,RigidBody as Mg,RigidBodyType as Pc,World as Ig}from"@dimforge/rapier3d-compat";import{BufferAttribute as sg,Line as ag,BoxGeometry as ip,EdgesGeometry as lg,Color as cg,LineSegments as ug,LineBasicMaterial as dg,Mesh as $h,SphereGeometry as hg,Vector3 as pg,Quaternion as fg}from"three";var _t=new pg,ep=new fg,Br=8947848,Ur=class{static DrawRay(e,t,i=Br,n=0,r=!0){let s=et.getLine(n),a=s.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),_t.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+_t.x,e.y+_t.y,e.z+_t.z),a.needsUpdate=!0,s.material.color.set(i),s.material.depthTest=r}static DrawDirection(e,t,i=Br,n=0,r=!0,s=1){let a=et.getLine(n),c=a.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(_t.set(0,0,-s),ep.set(t.x,t.y,t.z,t.w),_t.applyQuaternion(ep)):(_t.set(t.x,t.y,t.z),_t.multiplyScalar(s)),c.setXYZ(1,e.x+_t.x,e.y+_t.y,e.z+_t.z),c.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=r}static DrawLine(e,t,i=Br,n=0,r=!0){let s=et.getLine(n),a=s.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,s.material.color.set(i),s.material.depthTest=r}static DrawWireSphere(e,t,i=Br,n=0,r=!0){let s=et.getSphere(t,n,!0);gn(s,e.x,e.y,e.z),s.material.color.set(i),s.material.depthTest=r}static DrawSphere(e,t,i=Br,n=0,r=!0){let s=et.getSphere(t,n,!1);gn(s,e.x,e.y,e.z),s.material.color.set(i),s.material.depthTest=r}static DrawBox(e,t,i=Br,n=0,r=!0){let s=et.getBox(n);s.position.set(e.x,e.y,e.z),s.scale.set(t.x,t.y,t.z),s.material.color.set(i),s.material.depthTest=r,s.material.wireframe=!0}static DrawBox3(e,t=Br,i=0,n=!0){let r=et.getBox(i);r.position.copy(e.getCenter(_t)),r.scale.copy(e.getSize(_t)),r.material.color.set(t),r.material.depthTest=n,r.material.wireframe=!0}},mg=new ip(1,1,1);function Ma(o=null){let e=new cg(o??14540253),t=new lg(mg);return new ug(t,new dg({color:e}))}var tp=Symbol("GizmoCache"),et=class{static getBox(e){let t=this.boxesCache.pop();if(!t){let i=new ip(1,1,1);t=new $h(i)}return this.registerTimedObject(V.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new ag;let i=t.geometry.getAttribute("position");i||(i=new sg(new Float32Array(2*3),3),t.geometry.setAttribute("position",i))}return this.registerTimedObject(V.Current,t,e,this.linesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new $h(new hg(.5,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(V.Current,n,t,this.spheresCache),n}static registerTimedObject(e,t,i,n){if(!this.contextPostRenderCallbacks.get(e)){let r=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,r),e.post_render_callbacks.push(r)}t[tp]=n,this.timedObjectsBuffer.push(t),this.timesBuffer.push(V.Current.time.time+i),e.scene.add(t)}static onPostRender(e,t,i){let n=e.time.time;for(let r=0;r<t.length;r++)if(n>i[r]){let s=t[r];s[tp].push(s),e.scene.remove(s),t.splice(r,1),i.splice(r,1)}}};L(et,"linesCache",[]),L(et,"spheresCache",[]),L(et,"boxesCache",[]),L(et,"timedObjectsBuffer",new Array),L(et,"timesBuffer",new Array),L(et,"contextPostRenderCallbacks",new Map);var Ao=M("debugphysics"),Oc=M("debugphysicscolliders"),kc=M("debugcollisions"),Dg=M("showcolliders"),Lo=Symbol("needle component"),Ut=Symbol("physics body"),Ag=Symbol("rigidbody"),fe=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 Rg),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new Mc);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};L(fe,"AllLayers",4294967295);var Ic=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},Gr=class{raycaster=new Cg;defaultRaycastOptions=new fe;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new Mc;sphereOverlap(e,t,i=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let n=new Tg(e,t),r=this.sphereMask;r.enableAll(),r.disable(2);for(let s of this.context.scene.children)this.onSphereOverlap(s,n,r,this.sphereResults,i);return this.sphereResults.sort((s,a)=>s.distance-a.distance)}tempBoundingBox=new vg;onSphereOverlap(e,t,i,n,r){if(e.type==="Mesh"&&e.layers.test(i)){let s=e,a=s.geometry;if(a.boundingBox||a.computeBoundingBox(),a.boundingBox){s.matrixWorldNeedsUpdate&&s.updateMatrixWorld();let c=this.tempBoundingBox.copy(a.boundingBox).applyMatrix4(s.matrixWorld);if(t.intersectsBox(c)){let l=U(e).distanceTo(t.center),d=new Ic(e,l,t.center.clone());if(n.push(d),!r)return}}}if(e.children)for(let s of e.children){let a=n.length;if(this.onSphereOverlap(s,t,i,n,r),a!=n.length&&!r)return}}raycastFromRay(e,t=null){let i=t??this.defaultRaycastOptions;return i.ray=e,this.raycast(i)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold?i.params.Line={threshold:e.lineThreshold}:i.params.Line={threshold:0},e.ray)i.ray.copy(e.ray);else{let a=e.cam??this.context.mainCamera;if(!a)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];i.setFromCamera(t,a)}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 Mc?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 s=e.ignore;return s!==void 0&&s.length>0&&(r=r.filter(a=>!s.includes(a.object))),r}rapierRay=new yn.Ray({x:0,y:0,z:0},{x:0,y:0,z:1});raycastVectorsBuffer=new Wn(()=>new Sc,10);raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){let r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;let s=this.world?.castRay(r,i,n);if(s){let a=r.pointAt(s.toi),c=this.raycastVectorsBuffer.get();return c.set(a.x,a.y,a.z),{point:c,collider:s.collider[Lo]}}return null}getPhysicsRay(e,t,i=void 0){let n=this.context.mainCamera;if(t.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;let a=this.raycastVectorsBuffer.get();(t.x>1||t.y>1||t.y<-1||t.x<-1)&&this.context.input.convertScreenspaceToRaycastSpace(t),a.set(t.x,t.y,-1),a.unproject(n),t=a}let r=t;e.origin.x=r.x,e.origin.y=r.y,e.origin.z=r.z;let s=this.raycastVectorsBuffer.get();if(i)s.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;s.set(e.origin.x,e.origin.y,e.origin.z);let a=U(n);s.sub(a)}return s.normalize(),e.dir.x=s.x,e.dir.y=s.y,e.dir.z=s.z,e}_tempPosition=new Sc;_tempQuaternion=new Eg;_tempScale=new Sc;_tempMatrix=new wg;_isUpdatingPhysicsWorld=!1;get isUpdating(){return this._isUpdatingPhysicsWorld}context;world;_hasCreatedWorld=!1;eventQueue;collisionHandler;objects=[];bodies=[];_meshCache=new Map;constructor(e){this.context=e}async createWorld(){if(this._hasCreatedWorld){console.error("Invalid call to create physics world: world is already created");return}this._hasCreatedWorld=!0,Gr._didLoadPhysicsEngine||(await yn.init().then(()=>yn),Gr._didLoadPhysicsEngine=!0);let e={x:0,y:-9.81,z:0};this.world=new Ig(e)}clearCaches(){this._meshCache.clear()}addBoxCollider(e,t,i){let n=e.gameObject,r=Fe(n,this._tempPosition).multiply(i);r.multiplyScalar(.5);let s=Ps.cuboid(r.x,r.y,r.z);this.createCollider(e,s,t)}addSphereCollider(e,t,i){let n=e.gameObject,r=Fe(n,this._tempPosition).multiplyScalar(i),s=Ps.ball(r.x);this.createCollider(e,s,t)}addCapsuleCollider(e,t,i,n){let r=e.gameObject,s=Fe(r,this._tempPosition);Ao&&console.log("capsule scale",s,i,n);let a=Ps.capsule(i*.5*s.y-n,n*s.x);this.createCollider(e,a,t)}addMeshCollider(e,t,i){let n=t.geometry;if(!n){Ao&&console.warn("Missing mesh geometry",t.name);return}let r=n.getAttribute("position").array,s=n.index?.array,a=Fe(t,this._tempPosition);if(Math.abs(a.x-1)>1e-4||Math.abs(a.y-1)>1e-4||Math.abs(a.z-1)>1e-4){let u=n.uuid+"_"+a.x+"_"+a.y+"_"+a.z+"_"+i;if(this._meshCache.has(u))r=this._meshCache.get(u);else{console.warn("Your model is using scaled mesh colliders which is not optimal for performance",t.name,Object.assign({},a),t);let l=new Float32Array(r.length);for(let d=0;d<r.length;d+=3)l[d]=r[d]*a.x,l[d+1]=r[d+1]*a.y,l[d+2]=r[d+2]*a.z;r=l,this._meshCache.set(u,l)}}let c=i?Ps.convexMesh(r):Ps.trimesh(r,s);c&&this.createCollider(e,c)}createCollider(e,t,i){if(!this.world)throw new Error("Physics world not initialized");let n=this._tempMatrix,{rigidBody:r,useExplicitMassProperties:s}=this.getRigidbody(e,this._tempMatrix);n.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),Fe(e.gameObject,this._tempScale),i&&this._tempPosition.add(i).multiply(this._tempScale),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);let a=this.world.createCollider(t,r);return a[Lo]=e,e[Ut]=a,a.setActiveEvents(Sg.COLLISION_EVENTS),this.objects.push(e),this.bodies.push(a),a}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null,n=!1;if(e.attachedRigidbody){let r=e.attachedRigidbody;if(i=r[Ut],n=!0,!i){let s=r.isKinematic&&!Oc;Ao&&console.log("Create rigidbody",s);let a=s?yn.RigidBodyDesc.kinematicPositionBased():yn.RigidBodyDesc.dynamic(),c=U(e.attachedRigidbody.gameObject);a.setTranslation(c.x,c.y,c.z),a.setRotation(he(e.attachedRigidbody.gameObject)),i=this.world.createRigidBody(a),this.bodies.push(i),this.objects.push(r)}i[Lo]=r,r[Ut]=i,this.internalUpdateProperties(r,i),this.getRigidbodyRelativeMatrix(e.gameObject,r.gameObject,t)}else{let r=yn.RigidBodyDesc.kinematicPositionBased(),s=U(e.gameObject);r.setTranslation(s.x,s.y,s.z),r.setRotation(he(e.gameObject)),i=this.world.createRigidBody(r),t.identity(),i[Lo]=null}return e[Ag]=i,{rigidBody:i,useExplicitMassProperties:n}}removeBody(e){let t=e[Ut];if(e[Ut]=null,t&&this.world){let i=this.objects.findIndex(n=>n===e);if(i>=0){let n=this.bodies[i];if(this.bodies.splice(i,1),this.objects.splice(i,1),n instanceof Pg){let r=n;this.world?.removeCollider(r,!0);let s=r.parent();s&&s.numColliders()<=0&&this.world?.removeRigidBody(s)}else n instanceof Mg}}}updateBody(e,t,i){if(!(e.destroyed||!e.gameObject)&&!(!t&&!i))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{let n=e,r=n[Ut];r&&this.syncPhysicsBody(n.gameObject,r,t,i)}}updateProperties(e){let t=e[Ut];t&&this.internalUpdateProperties(e,t)}internal_getRigidbody(e){return e[Ut]}internalUpdateProperties(e,t){t.enableCcd(e.collisionDetectionMode!==0),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?1:0,!0),t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!0),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!0),e.isKinematic?t.setBodyType(yn.RigidBodyType.KinematicPositionBased):t.setBodyType(yn.RigidBodyType.Dynamic)}lines;step(e){!this.world||(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new Og(!1)),this.world.step(this.eventQueue),this._isUpdatingPhysicsWorld=!1,this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Ao||Oc||Dg){if(!this.lines){let i=new _g({color:16777215}),n=new yg;this.lines=new xg(n,i),this.context.scene.add(this.lines)}let t=e.debugRender();this.lines.geometry.setAttribute("position",new np(t.vertices,3)),this.lines.geometry.setAttribute("color",new np(t.colors,4))}}postStep(){!this.world||(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new Dc(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()))}syncObjects(){if(!Oc)for(let e=0;e<this.bodies.length;e++){let t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){let c=i.parent();c&&this.syncPhysicsBody(t.gameObject,c,!0,!0);continue}let r=i.translation(),s=i.rotation(),a=t.center;if(a&&a.isVector3){this._tempQuaternion.set(s.x,s.y,s.z,s.w);let c=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),u=Fe(t.gameObject);c.multiply(u),r.x-=c.x,r.y-=c.y,r.z-=c.z}gn(t.gameObject,r.x,r.y,r.z),wh(t.gameObject,s.x,s.y,s.z,s.w)}}syncPhysicsBody(e,t,i,n){let r=U(e,this._tempPosition),s=he(e,this._tempQuaternion);switch(t.bodyType()){case Pc.Fixed:case Pc.KinematicPositionBased:case Pc.KinematicVelocityBased:i&&t.setNextKinematicTranslation(r),n&&t.setNextKinematicRotation(s);break;default:i&&t.setTranslation(r,!1),n&&t.setRotation(s,!1);break}t.wakeUp()}getRigidbodyRelativeMatrix(e,t,i,n){if(n===void 0&&(n=Gr._matricesBuffer,n.length=0),e===t){let r=Fe(e,this._tempPosition);i.makeScale(r.x,r.y,r.z);for(let s=n.length-1;s>=0;s--)i.multiply(n[s]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}let i=e[Ut],n=t[Ut];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);let r=kg.fixed(Gr.centerConnectionPos,Gr.centerConnectionRot,this._tempPosition,this._tempQuaternion),s=this.world.createImpulseJoint(r,i,n,!0);Ao&&console.log("ADD FIXED JOINT",s)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}let r=e[Ut],s=t[Ut];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);let a=yn.JointData.revolute(i,this._tempPosition,n),c=this.world.createImpulseJoint(a,r,s,!0);Ao&&console.log("ADD HINGE JOINT",c)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);let n=e.matrixWorld,r=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,i.copy(r).premultiply(n.invert()).invert()}},Yn=Gr;L(Yn,"_didLoadPhysicsEngine",!1),L(Yn,"_matricesBuffer",[]),L(Yn,"centerConnectionPos",{x:0,y:0,z:0}),L(Yn,"centerConnectionRot",{x:0,y:0,z:0,w:1});var Dc=class{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){!this.eventQueue||!this.world||this.eventQueue.drainCollisionEvents((e,t,i)=>{let n=this.world.getCollider(e),r=this.world.getCollider(t),s=n[Lo],a=r[Lo];kc&&console.log("EVT",s.name,a.name,i,n,r),s&&a&&(i?(this.onCollisionStarted(s,n,a,r),this.onCollisionStarted(a,r,s,n)):(this.onCollisionEnded(s,a),this.onCollisionEnded(a,s)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let r=null;if(e.isTrigger||i.isTrigger)ci(e.gameObject,s=>{s.onTriggerEnter&&s.onTriggerEnter(i),this.activeTriggers.push({collider:e,component:s,otherCollider:i})});else{let s=e.gameObject;this.world.contactPair(t,n,(a,c)=>{ci(s,u=>{let l=u.onCollisionEnter||u.onCollisionStay||u.onCollisionExit;if(l||kc){if(!r){let d=[],h=a.normal();for(let b=0;b<a.numSolverContacts();b++){let _=a.solverContactPoint(b),v=a.contactImpulse(b);if(_){let y=a.contactDist(b),f=a.solverContactFriction(b),m=new va(_,y,h,v,f);d.push(m),kc&&Ur.DrawDirection(_,h,16711680,3,!0)}}r=new Cs(s,i,d)}if(l){let d={collider:e,component:u,collision:r};this.activeCollisions.push(d),u.onCollisionStay&&this.activeCollisionsStay.push(d),u.onCollisionEnter?.call(u,r)}}})})}}onHandleCollisionStay(){for(let e of this.activeCollisionsStay){let t=e.component;if(t.activeAndEnabled&&t.onCollisionStay){let i=e.collision;t.onCollisionStay(i)}}for(let e of this.activeTriggers){let t=e.component;if(t.activeAndEnabled&&t.onTriggerStay){let i=e.otherCollider;t.onTriggerStay(i)}}}onCollisionEnded(e,t){for(let i=0;i<this.activeCollisions.length;i++){let n=this.activeCollisions[i];if(n.collider===e&&n.collision.collider===t){let s=n.component;if(this.activeCollisions.splice(i,1),i--,s.activeAndEnabled&&s.onCollisionExit){let a=n.collision;s.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){let n=this.activeCollisionsStay[i];if(n.collider===e&&n.collision.collider===t){let s=n.component;if(this.activeCollisionsStay.splice(i,1),i--,s.activeAndEnabled&&s.onCollisionExit){let a=n.collision;s.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){let n=this.activeTriggers[i];if(n.collider===e&&n.otherCollider===t){let s=n.component;if(this.activeTriggers.splice(i,1),i--,s.activeAndEnabled&&s.onTriggerExit){let a=n.otherCollider;s.onTriggerExit(a)}}}}};import{Clock as Lg}from"three";var Ia=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 Lg;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.deltaTime<=0&&(this.deltaTime=1e-12),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 Hg}from"websocket-ts";var Ii=new Int32Array(2),Da=new Float32Array(Ii.buffer),Aa=new Float64Array(Ii.buffer),jo=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 Os;(function(o){o[o.UTF8_BYTES=1]="UTF8_BYTES",o[o.UTF16_STRING=2]="UTF16_STRING"})(Os||(Os={}));var Di=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new Di(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 Ii[0]=this.readInt32(e),Da[0]}readFloat64(e){return Ii[jo?0:1]=this.readInt32(e),Ii[jo?1:0]=this.readInt32(e+4),Aa[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){Da[0]=t,this.writeInt32(e,Ii[0])}writeFloat64(e,t){Aa[0]=t,this.writeInt32(e,Ii[jo?0:1]),this.writeInt32(e+4,Ii[jo?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===Os.UTF8_BYTES)return this.bytes_.subarray(e,e+i);for(;r<i;){let s,a=this.readUint8(e+r++);if(a<192)s=a;else{let c=this.readUint8(e+r++);if(a<224)s=(a&31)<<6|c&63;else{let u=this.readUint8(e+r++);if(a<240)s=(a&15)<<12|(c&63)<<6|u&63;else{let l=this.readUint8(e+r++);s=(a&7)<<18|(c&63)<<12|(u&63)<<6|l&63}}}s<65536?n+=String.fromCharCode(s):(s-=65536,n+=String.fromCharCode((s>>10)+55296,(s&(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 xt=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=Di.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=xt.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=Di.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 s=0,a=this.space;e:for(t=0;t<this.vtables.length;t++){let c=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(c)){for(let u=2;u<r;u+=2)if(this.bb.readInt16(a+u)!=this.bb.readInt16(c+u))continue e;s=this.vtables[t];break}}return s?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,s-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,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 s=4-1;s>=0;s--)this.writeInt8(r.charCodeAt(s))}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 s=e.charCodeAt(i++);n=(r<<10)+s+(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 rp={};function Fo(o,e){rp[o]=e}function op(o){let e=o.getBufferIdentifier(),t=rp[e];return t(o)}function sp(o){return typeof o.guid=="function"?o.guid():null}var Lc=ra(ja(),1);var Ha=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 Lc.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new Hc(t)})}trySetupClient(e){this._client=new Lc.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)})})}},jc=class{_peer;constructor(e){this._peer=e}};var Hc=class extends jc{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 Fa="wss://needle-tiny-starter.glitch.me/socket",ct=!!M("debugnet"),Ba=!!(ct||M("debugowner"));var Jn=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||(Ba&&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 Ba&&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?(Ba&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Ba&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}},Ua=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Ha),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return ct}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(),ct&&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]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){ct&&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&&ct&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}connect(){if(this.connected)return;ct&&console.log("connecting");let e=this.netWebSocketUrlProvider?.getWebsocketUrl();e?Fa=e:hh()&&(Fa="wss://"+window.location.host+"/socket"),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+Fa);let e=new Hg(Fa).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{ct&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new Di(i),r=n.getBufferIdentifier(),s=this._listenersBinary[r],a=op(n),c=sp(a);if(c&&typeof c=="string"&&(this._state[c]=a),!s)return;let u=a??n;for(let l of s)l(u)}handleIncomingStringMessage(e){if(ct&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let s=e.data;s&&(console.assert(s.id!==void 0&&s.id!==null&&s.id.length>0,"server did not send connection id",s.id),console.log("Your id is: "+s.id,this.context.alias??""),this._connectionId=s.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(ct&&console.log(e),e){this._isInRoom=!0;let s=e;this._currentRoomName=s.room,this._currentRoomViewId=s.viewId,this._currentRoomAllowEditing=s.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...s.inRoom),ct&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let s=e.data;this._currentInRoom.push(s.userId),ct&&console.log(s.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let s=e.data,a=this._currentInRoom.indexOf(s.userId);a>=0&&(console.log(s.userId+" left",this.context.alias??""),this._currentInRoom.splice(a,1)),s.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":ct&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),ct&&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));ct&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let i of t)i();t.length=0}}};import{EffectComposer as lb}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as cb}from"three/examples/jsm/postprocessing/RenderPass";import*as Zn from"three";var gp=ra(mp(),1),Ga=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(o,e){let t=await o.arrayBuffer(),i=vp(t),n=o.name.split(".").pop(),r=i+"."+n,s=o.name.split(".").shift();console.assert(s!==void 0);let a={alias:s,filename:r},u=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(u.success||console.warn("exists check did fail"),u.exists)return console.log("file already exists",i),new Ga(!0,r,i,o.size);console.log("begin uploading file",s,o.size);let l=new FormData;l.append("file",o);let d={};d.filesize=o.size,s&&(d.alias=s);let b=await(await fetch(e+"/upload/file",{method:"POST",body:l,headers:d})).json();if(b?.success===!1)return b.message!==void 0?console.error("Upload failed:",b.message):console.error("Upload failed"),null;console.assert(b.hash_sum===i,"hash sum did not match","received:",b.hash_sum,"expected:",i),b.success&&console.log("successfully uploaded",i,b.id);let _=new Ga(b.success,r,i,o.size);return _.url=e,_}function vp(o){return(0,gp.default)(new Uint8Array(o))}async function Va(o,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:o});if(r.status!==200)return console.error("download failed",r),null;let s=await r.blob(),a=await s.arrayBuffer();n||console.assert(s.size===t,"size mismatch","expected:",t,"got:",s.size);let c=vp(a);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),s.arrayBuffer()}catch(r){console.error(r)}return null}async function yp(o,e){let t=await fetch(o),i=t.body?.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let s=0,a=[];for(;;){let{done:l,value:d}=await i.read();if(d&&(a.push(d),s+=d.length,e.call(null,new ProgressEvent("progress",{loaded:s,total:r}))),l)break}let c=new Uint8Array(s),u=0;for(let l of a)c.set(l,u),u+=l.length;return c}function za(o,e,t){console.warn("Adding components on object has been temporarily disabled")}var xp,_p=null;function Qe(){return xp}function Wa(o){_p!==o&&(_p=o,xp=new o)}var Uc=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,i,n,r,s,a,c){this.seed=t,this.guid=i,this.file_name=n,this.file_hash=r,this.file_size=s,this.position=a,this.sender=e,this.serverUrl=c}};async function wp(o,e,t){let i=o.name;return i.endsWith(".gltf")||i.endsWith(".glb")?new Promise((n,r)=>{let s=new FileReader;s.readAsDataURL(o),s.onloadend=async a=>{let c=s.result,u=Ea(),l=new Ue(u),d=await Qe().loadSync(e,c,l,!0);if(d&&d.scene){let h=d.scene;if(!h.guid){let b=new Ue(u);h.guid=b.generateUUID()}t&&Gg(e.connection,o,u,h,t),za(h,l,d),n(d)}}}):(console.warn("Unsupported file type: "+i),console.log(o),null)}async function Ep(o,e){return new Promise(async(t,i)=>{let n=Ea(),r=new Ue(n),s=await Qe().loadSync(e,o.toString(),r,!0);if(s&&s.scene){let a=s.scene;za(a,r,s),t(s)}else console.warn("Unsupported file type: "+o.toString())})}function Cp(o){o.connection.beginListen("file-spawned",async e=>{if(e.sender!==o.connection.connectionId){console.log("received file event",e),Vg(e,o);let t=null;try{t=await Va(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{zg(e,o)}if(t){let i=new Ue(e.seed),n=await Qe().parseSync(o,t,null,i);if(n&&n.scene){let r=n.scene;if(za(r,i,n),e.parentGuid){let s=Ar(e.parentGuid,o.scene);"add"in s&&s.add(r)}r.parent||o.scene.add(r),e.position!==null&&r.position.copy(e.position)}}else console.error("download didnt return file")}})}async function Gg(o,e,t,i,n){if(!o.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 s=new Uc(o.connectionId,t,i.guid,r.filename,r.hash,e.size,i.position,r.url??n);i.parent&&(s.parentGuid=i.parent.guid),o.send("file-spawned",s)}var Gc={};function Vg(o,e){let t=new Zn.BoxGeometry,i=new Zn.Mesh(t,new Zn.MeshBasicMaterial({color:65280})),n=new Zn.BoxHelper(i,5592405);if(Gc[o.guid]=n,e.scene.add(n),o.parentGuid){let r=Ar(o.parentGuid,e.scene);r&&r.add(n)}o.position&&n.position.copy(o.position)}function zg(o,e){let t=o.guid,i=Gc[t];i&&(delete Gc[t],i.removeFromParent())}import*as Tp from"three";var iC=M("debugassets");var Na=class{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;let t=e?.reason?.path;if(t){let i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
|
|
150
|
-
`+i.src),e.preventDefault())}})}texturesLoader=new Tp.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 Ap from"three/examples/jsm/libs/stats.module";import{Vector4 as Jg,EquirectangularReflectionMapping as Qa,sRGBEncoding as qa,WebGLCubeRenderTarget as Zg}from"three";import{LightProbeGenerator as $g}from"three/examples/jsm/lights/LightProbeGenerator.js";import*as Rp from"three";var Ng=new Rp.FileLoader;async function Vc(o){return new Promise((e,t)=>{Ng.load(o,e,void 0,t)})}import{Vector4 as $n,FileLoader as Qg,DataTexture as Qc,RGBAFormat as qg,Color as Yg}from"three";var ks=new Uint8Array(4);ks[0]=255;ks[1]=255;ks[2]=255;ks[3]=255;var Op=new Qc(ks,1,1,qg);function Xa(o,e=1){let t="alpha"in o,i=e*e,n=new Uint8Array(4*i),r=Math.floor(o.r*255),s=Math.floor(o.g*255),a=Math.floor(o.b*255);for(let u=0;u<i;u++){let l=u*4;n[l+0]=r,n[l+1]=s,n[l+2]=a,t?n[l+3]=Math.floor(o.alpha*255):n[l+3]=255}let c=new Qc(n,e,e);return c.needsUpdate=!0,c}function kp(o,e,t,i=1,n=3){let a=i*n,c=[o,e,t],u=c.length,l=new Uint8Array(4*u*a),d=new Yg;for(let b=0;b<n;b++){let _=Math.floor(b/n*u),v=F.clamp(_+1,0,u-1),y=c[_],f=c[v],m=b/n*u%1;d.lerpColors(y,f,m);let p=Math.floor(d.r*255),g=Math.floor(d.g*255),x=Math.floor(d.b*255);for(let C=0;C<i;C++){let T=(b*i+C)*4;l[T+0]=p,l[T+1]=g,l[T+2]=x,l[T+3]=255}}let h=new Qc(l,i,n);return h.needsUpdate=!0,h}var Wc=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},Nc=class{loaded=new Map;async loadShader(e){let t=await Vc(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((r,s)=>{let a=this.loaded.get(t);a?r(a):s("Shader not found")});let i=await Vc(t),n=new Wc(e,i);return this.loaded.set(t,n),n}},aC=new Nc;function Ms(o,e){let t=o.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){let n=t[i],r=t[i+1],s=t[i+2],a=t[i+3],c=new $n(n,r,s,a);e.push(c)}return e}var zc=[],Sp=[];function qc(o,e){if(zc.length===0)for(let t=0;t<27;t++)zc.push(0);e||(e=zc);for(let t=0;t<27;t++)Sp[t]=e[t];e=Sp,o.unity_SHAr={value:new $n(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new $n(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new $n(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new $n(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new $n(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new $n(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new $n(e[24],e[25],e[26],1)}}var Xc=class{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}};async function Mp(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;let t=o.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){let r=o.shaders[i],s=o.shaders[n];if(r.uri&&s.uri||r.code&&s.code){if(!r.code&&r.uri&&await Pp(r),!s.code&&s.uri&&await Pp(s),!r.code||!s.code)return null;let a=o.techniques[e];return new Xc(r.code,s.code,a)}}return console.error("Shader technique not found",e),null}async function Pp(o){let e=o.uri;if(!!e)if(e.endsWith(".glsl")){let i=await new Qg().loadAsync(e);o.code=i.toString()}else o.code=Kg(o.uri)}function Kg(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}var Yc=M("debugenvlight"),Jc=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Jc||{});var Ya=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 Jg;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 Kc(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(Yc&&console.log(this.sceneLightSettings?Jc[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=qa,n.mapping=Qa,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=kp(t[0],t[1],t[2],64,64);i.encoding=qa,i.mapping=Qa,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=Xa(this.sceneLightSettings.ambientLight,64);t.encoding=qa,t.mapping=Qa,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 Yc&&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={}},Kc=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=Qa,t.encoding=qa}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){Yc&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new Zg(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=$g.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 s=e/(Math.PI*.5);for(let a=0;a<this._sphericalHarmonicsArray.length;a++)this._sphericalHarmonicsArray[a]*=s;if(n.sh.scale(r),this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:n}}}catch(t){console.error(t)}return null}};import{Object3D as eb}from"three";var Vr=M("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}},qe=class{static getOrCreate(e,t,i){let n=Oi(e,t);Vr&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,s=r.findAssetReference(n);if(s)return s;let a=new qe(n,i.hash);return r.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_hash;_hashedUri;_isLoadingRawBinary=!1;_rawBinary;constructor(e,t){this._uri=e,this._hash=t,e.includes("?v=")?this._hashedUri=e:this._hashedUri=t?e+"?v="+t:e,Fh(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?li(this.asset.scene):li(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._hashedUri);let e=await yp(this._hashedUri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=V.Current;this._rawBinary?(this._loading=Qe().parseSync(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=Qe().loadSync(t,this._hashedUri,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 vn(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=V.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 Ge?e:null;if(r||(r=new Ge),typeof e=="object"&&(e instanceof eb?r.parent=e:Object.assign(r,e)),t){r.context=n;let s=this.asset;s.guid=this.uri;let a=wa(s,r,void 0,i);if(a)return a}else{let s=Lr(this.asset,r);if(s)return s}}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}},Zc=class extends mn{constructor(){super([qe])}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?qe.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new Zc;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}}};import{FloatType as tb,HalfFloatType as ib,sRGBEncoding as nb}from"three";var Ip="NEEDLE_lightmaps",rb=M("debuglightmapsextension"),Is=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(Is||{}),Za=class{get name(){return Ip}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[Ip];if(i){let n=i.textures;return n?.length?(rb&&console.log(i),new Promise(async(r,s)=>{let a=[];for(let c of n)if(c.pointer){let u=To(this.parser,c.pointer).then(l=>{let d=l;d?.isTexture&&(this.registry?(c.type!==0&&(d.encoding=nb),(d.type==tb||d.type==ib)&&(d.flipY=!0),this.registry.registerTexture(this.source,c.type,d,c.index)):console.log(Is[c.type],c.pointer,d))});a.push(u)}await Promise.all(a),r()})):null}}return null}};import*as Ai from"three";var Dp=!!M("debuglightmaps"),$a=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){Dp&&console.log("Registering lightmap",e,Is[t],i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);let r=this._lightmaps.get(e),s=r?.get(t)??[];s.length<n&&(s.length=n+1),s[n]=i,r?.set(t,s)}tryGetLightmap(e,t=0){return this.tryGet(e,0,t)}tryGetSkybox(e){return this.tryGet(e,1,0)}tryGetReflection(e){return this.tryGet(e,2,0)}tryGet(e,t,i){if(!e)return Dp&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};Ai.ShaderChunk.lights_fragment_maps=Ai.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
|
|
149
|
+
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`))),Rc&&console.log("FIND",e),e!=null){for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i];if(e===null||n.constructor.name===e.name||n.constructor.name===e)if(Rc&&console.log("MATCH BY NAME",n),t)t.push(n);else return n}for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i],r=Object.getPrototypeOf(n.constructor);do{if(r===e)if(Rc&&console.log("MATCH BY PROTOYPE",r),t)t.push(n);else return n;r=Object.getPrototypeOf(r)}while(r)}return t}}}function jr(o,e){return Xh(o,e)}function Mo(o,e,t){return t||(t=[]),Xh(o,e,t)}function Hr(o,e,t){let i=jr(o,e);if(t===!1&&i.enabled===!1)return null;if(i)return i;for(let n=0;n<o?.children?.length;n++){let r=Hr(o.children[n],e);if(r)return r}return null}function Io(o,e,t){t||(t=[]),Mo(o,e,t);for(let i=0;i<o?.children?.length;i++)Io(o.children[i],e,t);return t}function ko(o,e){if(!o)return null;if(Array.isArray(o)){for(let i=0;i<o.length;i++){let n=ig(o[i]),r=ko(n,e);if(r)return r}return null}let t=jr(o,e);return t||(o.parent?ko(o.parent,e):null)}function Ss(o,e,t){return t||(t=[]),o?(Mo(o,e,t),o.parent?Ss(o.parent,e,t):t):t}function Qh(o,e,t){if(!o)return null;if(!e&&(e=V.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e;if(i.isScene||(i=e?.scene),!i)return null;for(let n in i.children){let r=i.children[n];if(t===!1&&r[Ii]===!1)continue;if(r.constructor==o)return r;let s=Hr(r,o);if(s)return s}return null}function qh(o,e,t){if(!o)return e;if(!t&&(t=V.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;let 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==o)return r;Io(r,o,e)}return e}function Do(o){o&&o.isObject3D===!0&&Gh(o,lt)}lt.prototype.SetActive=function(o){this.visible=o};lt.prototype.addNewComponent=function(o){return qn(this,new o)};lt.prototype.removeComponent=function(o){return Ca(this,o)};lt.prototype.getOrAddComponent=function(o){return Ta(this,o)};lt.prototype.getComponent=function(o){return jr(this,o)};lt.prototype.getComponents=function(o,e){return Mo(this,o,e)};lt.prototype.getComponentInChildren=function(o){return Hr(this,o)};lt.prototype.getComponentsInChildren=function(o,e){return Io(this,o,e)};lt.prototype.getComponentInParent=function(o){return ko(this,o)};lt.prototype.getComponentsInParent=function(o,e){return Ss(this,o,e)};Object.getOwnPropertyDescriptor(lt.prototype,"activeSelf")||Object.defineProperty(lt.prototype,"activeSelf",{get:function(){return this.visible},set:function(o){let e=typeof o=="number"?o>.5:o;this.visible=e}});Vh(lt);var Sa=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),oe=class{static isUsingInstancing(e){return e.__isUsingInstancing===!0}static markDirty(e,t=!0){if(!!e&&(this.isUsingInstancing(e)&&(e[Sa]=!0,e.matrixWorldNeedsUpdate=!0),t))for(let i of e.children)oe.markDirty(i,!0)}};var Fr=M("debuggetcomponent"),ng=(u=>(u[u.None=0]="None",u[u.HideInHierarchy=1]="HideInHierarchy",u[u.HideInInspector=2]="HideInInspector",u[u.DontSaveInEditor=4]="DontSaveInEditor",u[u.NotEditable=8]="NotEditable",u[u.DontSaveInBuild=16]="DontSaveInBuild",u[u.DontUnloadUnusedAsset=32]="DontUnloadUnusedAsset",u[u.DontSave=52]="DontSave",u[u.HideAndDontSave=61]="HideAndDontSave",u))(ng||{}),Ge=class{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context},Pa=Symbol("isActive");function Dr(o){let e=o.visible||ka(o);return o[Pa]===void 0&&(o[Pa]=e),o[Pa]&&e}function Oa(o,e,t=!0){o[Pa]=e,t&&(o.visible=e)}function Kh(o){return o[Ii]||ka(o)}function Jh(o,e){o.__isUsingInstancing=e}function ka(o){return oe.isUsingInstancing(o)}function Ar(o,e){return Nn(o,e,!0,!0)}function li(o,e=!0,t=!0){let i=o;if(i.isComponent){i.__internalDisable(),i.__internalDestroy();return}let n=o;if(Fr&&console.log(n),e&&n.children)for(let s of n.children)li(s,e,!1);let r=n.userData.components;if(r){let s=r.length;for(let a=0;a<r.length;a++){let c=r[a];c.__internalDisable(),c.__internalDestroy(),r.length<s&&(s=r.length,a--)}}t&&n.removeFromParent()}function ci(o,e,t=!0){if(!!o){if(o.isObject3D||new Error("Expected Object3D but got "+o),o.userData?.components)for(let i=0;i<o.userData.components.length;i++){let n=o.userData.components[i];if(n?.isComponent===!0){let r=e(n);if(r!==void 0)return r}}if(t&&o.children)for(let i=0;i<o.children.length;i++){let n=o.children[i];if(!n)continue;let r=ci(n,e,t);if(r!==void 0)return r}}}function Lr(o,e=null){if(o===null)return null;let t=null;e!==null&&(e.x!==void 0?(t=new Ge,t.position=e):t=e);let i=V.Current;t?.context&&(i=t.context),Fr&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new Ue(Date.now()));let n=[],r={},s={},a=Zh(i,o,t,n,r,s);a&&(og(r),rg(s,r)),Fr&&(Es(o,!0),Es(a,!0));let c={};for(let u in n){let l=n[u],d=l.guid;t&&t.idProvider&&(l.guid=t.idProvider.generateUUID(),c[d]=l.guid,Fr&&console.log(l.name,l.guid)),Ra(l,i),l.__internalNewInstanceCreated&&l.__internalNewInstanceCreated()}for(let u in n){let l=n[u];l.resolveGuids&&l.resolveGuids(c),l.enabled!==!1&&(l.enabled=!0)}return yn(i),a}function Zh(o,e,t,i,n,r){if(!e)return null;let s=e.userData;e.userData={};let a=e.children;e.children=[];let c;if(c=e.clone(!1),Do(c),e.userData=s,e.children=a,n[e.uuid]={original:e,clone:c},e.type==="SkinnedMesh"&&(r[e.uuid]={original:e,clone:c}),t?.visible!==void 0&&(c.visible=t.visible),t?.idProvider){c.uuid=t.idProvider.generateUUID();let l=c;l&&(l.guid=c.uuid)}e.animations&&e.animations.length>0&&(c.animations=[...e.animations]);let u=e.parent;if(u&&u.add(c),t?.position?te(c,t.position):c.position.copy(e.position),t?.rotation?$e(c,t.rotation):c.quaternion.copy(e.quaternion),t?.scale?c.scale.copy(t.scale):c.scale.copy(e.scale),t?.parent&&t.parent!=="scene"){let l=null;if(typeof t.parent=="string"?l=Nn(t.parent,o.scene,!0):l=t.parent,l){let d=t.keepWorldPosition===!0?l.attach:l.add;d?d.call(l,c):console.error("Invalid parent object",l,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(let[l,d]of Object.entries(e.userData))l!=="components"&&(c.userData[l]=d);if(e.userData?.components){let l=e.userData.components,d=[];c.userData.components=d;for(let h=0;h<l.length;h++){let b=l[h],_=Object.create(b);oi(_,b),d.push(_),_.gameObject=c,i.push(_)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0);for(let l in e.children){let d=e.children[l],h=Zh(o,d,t,i,n,r);h&&c.add(h)}return c}function rg(o,e){for(let t in o){let i=o[t],n=i.original,r=n.skeleton,s=i.clone;if(!r){console.warn("Skinned mesh has no skeleton?",i);continue}let a=r.bones,c=s.skeleton.clone();s.skeleton=c,s.bindMatrix.clone().copy(n.bindMatrix),s.bindMatrixInverse.copy(n.bindMatrixInverse);let u=[];c.bones=u;for(let l=0;l<a.length;l++){let d=a[l],b=e[d.uuid].clone;u.push(b)}}for(let t in o){let i=o[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function og(o){for(let e in o){let i=o[e].clone;if(i.userData?.components)for(let n=0;n<i.userData.components.length;n++){let r=i.userData.components[n],s=Object.entries(r);for(let[a,c]of s)if(Array.isArray(c)){let u=[];r[a]=u;for(let l=0;l<c.length;l++){let d=c[l];if(typeof d!="object"){u.push(d);continue}let h=Yh(r,a,d,o);h!==void 0?u.push(h):u.push(d)}}else if(typeof c=="object"){let u=Yh(r,a,c,o);u!==void 0&&(r[a]=u)}}}}function Yh(o,e,t,i){if(t!=null){if(t.isComponent===!0){let n=t.gameObject;if(n){let r=n.uuid,s=i[r]?.clone;if(!s){Fr&&console.log("reference did not change",e,o,t);return}let a=n.userData.components.indexOf(t);if(a>=0)return Fr&&console.log(e,r),s.userData.components[a];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;let n=t;if(n){let r=n.uuid,s=i[r]?.clone;if(s)return Fr&&console.log(e,"old",t,"new",s),s}}}}import _n,{ActiveEvents as Sg,Collider as Pg,ColliderDesc as Ps,EventQueue as Og,JointData as kg,RigidBody as Mg,RigidBodyType as Pc,World as Ig}from"@dimforge/rapier3d-compat";import{BufferAttribute as sg,Line as ag,BoxGeometry as ip,EdgesGeometry as lg,Color as cg,LineSegments as ug,LineBasicMaterial as dg,Mesh as $h,SphereGeometry as hg,Vector3 as pg,Quaternion as fg}from"three";var _t=new pg,ep=new fg,Br=8947848,Ur=class{static DrawRay(e,t,i=Br,n=0,r=!0){let s=et.getLine(n),a=s.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),_t.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+_t.x,e.y+_t.y,e.z+_t.z),a.needsUpdate=!0,s.material.color.set(i),s.material.depthTest=r}static DrawDirection(e,t,i=Br,n=0,r=!0,s=1){let a=et.getLine(n),c=a.geometry.getAttribute("position");c.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(_t.set(0,0,-s),ep.set(t.x,t.y,t.z,t.w),_t.applyQuaternion(ep)):(_t.set(t.x,t.y,t.z),_t.multiplyScalar(s)),c.setXYZ(1,e.x+_t.x,e.y+_t.y,e.z+_t.z),c.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=r}static DrawLine(e,t,i=Br,n=0,r=!0){let s=et.getLine(n),a=s.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,s.material.color.set(i),s.material.depthTest=r}static DrawWireSphere(e,t,i=Br,n=0,r=!0){let s=et.getSphere(t,n,!0);bn(s,e.x,e.y,e.z),s.material.color.set(i),s.material.depthTest=r}static DrawSphere(e,t,i=Br,n=0,r=!0){let s=et.getSphere(t,n,!1);bn(s,e.x,e.y,e.z),s.material.color.set(i),s.material.depthTest=r}static DrawBox(e,t,i=Br,n=0,r=!0){let s=et.getBox(n);s.position.set(e.x,e.y,e.z),s.scale.set(t.x,t.y,t.z),s.material.color.set(i),s.material.depthTest=r,s.material.wireframe=!0}static DrawBox3(e,t=Br,i=0,n=!0){let r=et.getBox(i);r.position.copy(e.getCenter(_t)),r.scale.copy(e.getSize(_t)),r.material.color.set(t),r.material.depthTest=n,r.material.wireframe=!0}},mg=new ip(1,1,1);function Ma(o=null){let e=new cg(o??14540253),t=new lg(mg);return new ug(t,new dg({color:e}))}var tp=Symbol("GizmoCache"),et=class{static getBox(e){let t=this.boxesCache.pop();if(!t){let i=new ip(1,1,1);t=new $h(i)}return this.registerTimedObject(V.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new ag;let i=t.geometry.getAttribute("position");i||(i=new sg(new Float32Array(2*3),3),t.geometry.setAttribute("position",i))}return this.registerTimedObject(V.Current,t,e,this.linesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new $h(new hg(.5,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(V.Current,n,t,this.spheresCache),n}static registerTimedObject(e,t,i,n){if(!this.contextPostRenderCallbacks.get(e)){let r=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,r),e.post_render_callbacks.push(r)}t[tp]=n,this.timedObjectsBuffer.push(t),this.timesBuffer.push(V.Current.time.time+i),e.scene.add(t)}static onPostRender(e,t,i){let n=e.time.time;for(let r=0;r<t.length;r++)if(n>i[r]){let s=t[r];s[tp].push(s),e.scene.remove(s),t.splice(r,1),i.splice(r,1)}}};L(et,"linesCache",[]),L(et,"spheresCache",[]),L(et,"boxesCache",[]),L(et,"timedObjectsBuffer",new Array),L(et,"timesBuffer",new Array),L(et,"contextPostRenderCallbacks",new Map);var Ao=M("debugphysics"),Oc=M("debugphysicscolliders"),kc=M("debugcollisions"),Dg=M("showcolliders"),Lo=Symbol("needle component"),Ut=Symbol("physics body"),Ag=Symbol("rigidbody"),fe=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 Rg),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setMask(e){this.layerMask||(this.layerMask=new Mc);let t=this.layerMask;t?t.mask=e:this.layerMask=e}};L(fe,"AllLayers",4294967295);var Ic=class{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}},Gr=class{raycaster=new Cg;defaultRaycastOptions=new fe;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:0},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new Mc;sphereOverlap(e,t,i=!0){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;let n=new Tg(e,t),r=this.sphereMask;r.enableAll(),r.disable(2);for(let s of this.context.scene.children)this.onSphereOverlap(s,n,r,this.sphereResults,i);return this.sphereResults.sort((s,a)=>s.distance-a.distance)}tempBoundingBox=new vg;onSphereOverlap(e,t,i,n,r){if(e.type==="Mesh"&&e.layers.test(i)){let s=e,a=s.geometry;if(a.boundingBox||a.computeBoundingBox(),a.boundingBox){s.matrixWorldNeedsUpdate&&s.updateMatrixWorld();let c=this.tempBoundingBox.copy(a.boundingBox).applyMatrix4(s.matrixWorld);if(t.intersectsBox(c)){let l=U(e).distanceTo(t.center),d=new Ic(e,l,t.center.clone());if(n.push(d),!r)return}}}if(e.children)for(let s of e.children){let a=n.length;if(this.onSphereOverlap(s,t,i,n,r),a!=n.length&&!r)return}}raycastFromRay(e,t=null){let i=t??this.defaultRaycastOptions;return i.ray=e,this.raycast(i)}raycast(e=null){e||(e=this.defaultRaycastOptions);let t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold?i.params.Line={threshold:e.lineThreshold}:i.params.Line={threshold:0},e.ray)i.ray.copy(e.ray);else{let a=e.cam??this.context.mainCamera;if(!a)return console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];i.setFromCamera(t,a)}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 Mc?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 s=e.ignore;return s!==void 0&&s.length>0&&(r=r.filter(a=>!s.includes(a.object))),r}rapierRay=new _n.Ray({x:0,y:0,z:0},{x:0,y:0,z:1});raycastVectorsBuffer=new Wn(()=>new Sc,10);raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){let r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;let s=this.world?.castRay(r,i,n);if(s){let a=r.pointAt(s.toi),c=this.raycastVectorsBuffer.get();return c.set(a.x,a.y,a.z),{point:c,collider:s.collider[Lo]}}return null}getPhysicsRay(e,t,i=void 0){let n=this.context.mainCamera;if(t.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;let a=this.raycastVectorsBuffer.get();(t.x>1||t.y>1||t.y<-1||t.x<-1)&&this.context.input.convertScreenspaceToRaycastSpace(t),a.set(t.x,t.y,-1),a.unproject(n),t=a}let r=t;e.origin.x=r.x,e.origin.y=r.y,e.origin.z=r.z;let s=this.raycastVectorsBuffer.get();if(i)s.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;s.set(e.origin.x,e.origin.y,e.origin.z);let a=U(n);s.sub(a)}return s.normalize(),e.dir.x=s.x,e.dir.y=s.y,e.dir.z=s.z,e}_tempPosition=new Sc;_tempQuaternion=new Eg;_tempScale=new Sc;_tempMatrix=new wg;_isUpdatingPhysicsWorld=!1;get isUpdating(){return this._isUpdatingPhysicsWorld}context;world;_hasCreatedWorld=!1;eventQueue;collisionHandler;objects=[];bodies=[];_meshCache=new Map;constructor(e){this.context=e}async createWorld(){if(this._hasCreatedWorld){console.error("Invalid call to create physics world: world is already created");return}this._hasCreatedWorld=!0,Gr._didLoadPhysicsEngine||(await _n.init().then(()=>_n),Gr._didLoadPhysicsEngine=!0);let e={x:0,y:-9.81,z:0};this.world=new Ig(e)}clearCaches(){this._meshCache.clear()}addBoxCollider(e,t,i){let n=e.gameObject,r=Fe(n,this._tempPosition).multiply(i);r.multiplyScalar(.5);let s=Ps.cuboid(r.x,r.y,r.z);this.createCollider(e,s,t)}addSphereCollider(e,t,i){let n=e.gameObject,r=Fe(n,this._tempPosition).multiplyScalar(i),s=Ps.ball(r.x);this.createCollider(e,s,t)}addCapsuleCollider(e,t,i,n){let r=e.gameObject,s=Fe(r,this._tempPosition);Ao&&console.log("capsule scale",s,i,n);let a=Ps.capsule(i*.5*s.y-n,n*s.x);this.createCollider(e,a,t)}addMeshCollider(e,t,i){let n=t.geometry;if(!n){Ao&&console.warn("Missing mesh geometry",t.name);return}let r=n.getAttribute("position").array,s=n.index?.array,a=Fe(t,this._tempPosition);if(Math.abs(a.x-1)>1e-4||Math.abs(a.y-1)>1e-4||Math.abs(a.z-1)>1e-4){let u=n.uuid+"_"+a.x+"_"+a.y+"_"+a.z+"_"+i;if(this._meshCache.has(u))r=this._meshCache.get(u);else{console.warn("Your model is using scaled mesh colliders which is not optimal for performance",t.name,Object.assign({},a),t);let l=new Float32Array(r.length);for(let d=0;d<r.length;d+=3)l[d]=r[d]*a.x,l[d+1]=r[d+1]*a.y,l[d+2]=r[d+2]*a.z;r=l,this._meshCache.set(u,l)}}let c=i?Ps.convexMesh(r):Ps.trimesh(r,s);c&&this.createCollider(e,c)}createCollider(e,t,i){if(!this.world)throw new Error("Physics world not initialized");let n=this._tempMatrix,{rigidBody:r,useExplicitMassProperties:s}=this.getRigidbody(e,this._tempMatrix);n.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),Fe(e.gameObject,this._tempScale),i&&this._tempPosition.add(i).multiply(this._tempScale),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);let a=this.world.createCollider(t,r);return a[Lo]=e,e[Ut]=a,a.setActiveEvents(Sg.COLLISION_EVENTS),this.objects.push(e),this.bodies.push(a),a}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null,n=!1;if(e.attachedRigidbody){let r=e.attachedRigidbody;if(i=r[Ut],n=!0,!i){let s=r.isKinematic&&!Oc;Ao&&console.log("Create rigidbody",s);let a=s?_n.RigidBodyDesc.kinematicPositionBased():_n.RigidBodyDesc.dynamic(),c=U(e.attachedRigidbody.gameObject);a.setTranslation(c.x,c.y,c.z),a.setRotation(he(e.attachedRigidbody.gameObject)),i=this.world.createRigidBody(a),this.bodies.push(i),this.objects.push(r)}i[Lo]=r,r[Ut]=i,this.internalUpdateProperties(r,i),this.getRigidbodyRelativeMatrix(e.gameObject,r.gameObject,t)}else{let r=_n.RigidBodyDesc.kinematicPositionBased(),s=U(e.gameObject);r.setTranslation(s.x,s.y,s.z),r.setRotation(he(e.gameObject)),i=this.world.createRigidBody(r),t.identity(),i[Lo]=null}return e[Ag]=i,{rigidBody:i,useExplicitMassProperties:n}}removeBody(e){let t=e[Ut];if(e[Ut]=null,t&&this.world){let i=this.objects.findIndex(n=>n===e);if(i>=0){let n=this.bodies[i];if(this.bodies.splice(i,1),this.objects.splice(i,1),n instanceof Pg){let r=n;this.world?.removeCollider(r,!0);let s=r.parent();s&&s.numColliders()<=0&&this.world?.removeRigidBody(s)}else n instanceof Mg}}}updateBody(e,t,i){if(!(e.destroyed||!e.gameObject)&&!(!t&&!i))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{let n=e,r=n[Ut];r&&this.syncPhysicsBody(n.gameObject,r,t,i)}}updateProperties(e){let t=e[Ut];t&&this.internalUpdateProperties(e,t)}internal_getRigidbody(e){return e[Ut]}internalUpdateProperties(e,t){t.enableCcd(e.collisionDetectionMode!==0),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?1:0,!0),t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!0),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!0),e.isKinematic?t.setBodyType(_n.RigidBodyType.KinematicPositionBased):t.setBodyType(_n.RigidBodyType.Dynamic)}lines;step(e){!this.world||(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new Og(!1)),this.world.step(this.eventQueue),this._isUpdatingPhysicsWorld=!1,this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Ao||Oc||Dg){if(!this.lines){let i=new _g({color:16777215}),n=new yg;this.lines=new xg(n,i),this.context.scene.add(this.lines)}let t=e.debugRender();this.lines.geometry.setAttribute("position",new np(t.vertices,3)),this.lines.geometry.setAttribute("color",new np(t.colors,4))}}postStep(){!this.world||(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new Dc(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()))}syncObjects(){if(!Oc)for(let e=0;e<this.bodies.length;e++){let t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){let c=i.parent();c&&this.syncPhysicsBody(t.gameObject,c,!0,!0);continue}let r=i.translation(),s=i.rotation(),a=t.center;if(a&&a.isVector3){this._tempQuaternion.set(s.x,s.y,s.z,s.w);let c=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),u=Fe(t.gameObject);c.multiply(u),r.x-=c.x,r.y-=c.y,r.z-=c.z}bn(t.gameObject,r.x,r.y,r.z),wh(t.gameObject,s.x,s.y,s.z,s.w)}}syncPhysicsBody(e,t,i,n){let r=U(e,this._tempPosition),s=he(e,this._tempQuaternion);switch(t.bodyType()){case Pc.Fixed:case Pc.KinematicPositionBased:case Pc.KinematicVelocityBased:i&&t.setNextKinematicTranslation(r),n&&t.setNextKinematicRotation(s);break;default:i&&t.setTranslation(r,!1),n&&t.setRotation(s,!1);break}t.wakeUp()}getRigidbodyRelativeMatrix(e,t,i,n){if(n===void 0&&(n=Gr._matricesBuffer,n.length=0),e===t){let r=Fe(e,this._tempPosition);i.makeScale(r.x,r.y,r.z);for(let s=n.length-1;s>=0;s--)i.multiply(n[s]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}let i=e[Ut],n=t[Ut];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);let r=kg.fixed(Gr.centerConnectionPos,Gr.centerConnectionRot,this._tempPosition,this._tempQuaternion),s=this.world.createImpulseJoint(r,i,n,!0);Ao&&console.log("ADD FIXED JOINT",s)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}let r=e[Ut],s=t[Ut];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);let a=_n.JointData.revolute(i,this._tempPosition,n),c=this.world.createImpulseJoint(a,r,s,!0);Ao&&console.log("ADD HINGE JOINT",c)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);let n=e.matrixWorld,r=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,i.copy(r).premultiply(n.invert()).invert()}},Yn=Gr;L(Yn,"_didLoadPhysicsEngine",!1),L(Yn,"_matricesBuffer",[]),L(Yn,"centerConnectionPos",{x:0,y:0,z:0}),L(Yn,"centerConnectionRot",{x:0,y:0,z:0,w:1});var Dc=class{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){!this.eventQueue||!this.world||this.eventQueue.drainCollisionEvents((e,t,i)=>{let n=this.world.getCollider(e),r=this.world.getCollider(t),s=n[Lo],a=r[Lo];kc&&console.log("EVT",s.name,a.name,i,n,r),s&&a&&(i?(this.onCollisionStarted(s,n,a,r),this.onCollisionStarted(a,r,s,n)):(this.onCollisionEnded(s,a),this.onCollisionEnded(a,s)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let r=null;if(e.isTrigger||i.isTrigger)ci(e.gameObject,s=>{s.onTriggerEnter&&s.onTriggerEnter(i),this.activeTriggers.push({collider:e,component:s,otherCollider:i})});else{let s=e.gameObject;this.world.contactPair(t,n,(a,c)=>{ci(s,u=>{let l=u.onCollisionEnter||u.onCollisionStay||u.onCollisionExit;if(l||kc){if(!r){let d=[],h=a.normal();for(let b=0;b<a.numSolverContacts();b++){let _=a.solverContactPoint(b),v=a.contactImpulse(b);if(_){let y=a.contactDist(b),f=a.solverContactFriction(b),m=new va(_,y,h,v,f);d.push(m),kc&&Ur.DrawDirection(_,h,16711680,3,!0)}}r=new Cs(s,i,d)}if(l){let d={collider:e,component:u,collision:r};this.activeCollisions.push(d),u.onCollisionStay&&this.activeCollisionsStay.push(d),u.onCollisionEnter?.call(u,r)}}})})}}onHandleCollisionStay(){for(let e of this.activeCollisionsStay){let t=e.component;if(t.activeAndEnabled&&t.onCollisionStay){let i=e.collision;t.onCollisionStay(i)}}for(let e of this.activeTriggers){let t=e.component;if(t.activeAndEnabled&&t.onTriggerStay){let i=e.otherCollider;t.onTriggerStay(i)}}}onCollisionEnded(e,t){for(let i=0;i<this.activeCollisions.length;i++){let n=this.activeCollisions[i];if(n.collider===e&&n.collision.collider===t){let s=n.component;if(this.activeCollisions.splice(i,1),i--,s.activeAndEnabled&&s.onCollisionExit){let a=n.collision;s.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){let n=this.activeCollisionsStay[i];if(n.collider===e&&n.collision.collider===t){let s=n.component;if(this.activeCollisionsStay.splice(i,1),i--,s.activeAndEnabled&&s.onCollisionExit){let a=n.collision;s.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){let n=this.activeTriggers[i];if(n.collider===e&&n.otherCollider===t){let s=n.component;if(this.activeTriggers.splice(i,1),i--,s.activeAndEnabled&&s.onTriggerExit){let a=n.otherCollider;s.onTriggerExit(a)}}}}};import{Clock as Lg}from"three";var Ia=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 Lg;_smoothedFps=0;_fpsSamples=[];_fpsSampleIndex=0;update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this.deltaTime<=0&&(this.deltaTime=1e-12),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 Hg}from"websocket-ts";var Di=new Int32Array(2),Da=new Float32Array(Di.buffer),Aa=new Float64Array(Di.buffer),jo=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 Os;(function(o){o[o.UTF8_BYTES=1]="UTF8_BYTES",o[o.UTF16_STRING=2]="UTF16_STRING"})(Os||(Os={}));var Ai=class{constructor(e){this.bytes_=e,this.position_=0}static allocate(e){return new Ai(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 Di[0]=this.readInt32(e),Da[0]}readFloat64(e){return Di[jo?0:1]=this.readInt32(e),Di[jo?1:0]=this.readInt32(e+4),Aa[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){Da[0]=t,this.writeInt32(e,Di[0])}writeFloat64(e,t){Aa[0]=t,this.writeInt32(e,Di[jo?0:1]),this.writeInt32(e+4,Di[jo?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===Os.UTF8_BYTES)return this.bytes_.subarray(e,e+i);for(;r<i;){let s,a=this.readUint8(e+r++);if(a<192)s=a;else{let c=this.readUint8(e+r++);if(a<224)s=(a&31)<<6|c&63;else{let u=this.readUint8(e+r++);if(a<240)s=(a&15)<<12|(c&63)<<6|u&63;else{let l=this.readUint8(e+r++);s=(a&7)<<18|(c&63)<<12|(u&63)<<6|l&63}}}s<65536?n+=String.fromCharCode(s):(s-=65536,n+=String.fromCharCode((s>>10)+55296,(s&(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 xt=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=Ai.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=xt.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=Ai.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 s=0,a=this.space;e:for(t=0;t<this.vtables.length;t++){let c=this.bb.capacity()-this.vtables[t];if(r==this.bb.readInt16(c)){for(let u=2;u<r;u+=2)if(this.bb.readInt16(a+u)!=this.bb.readInt16(c+u))continue e;s=this.vtables[t];break}}return s?(this.space=this.bb.capacity()-e,this.bb.writeInt32(this.space,s-e)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-e,this.offset()-e)),this.isNested=!1,e}finish(e,t,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 s=4-1;s>=0;s--)this.writeInt8(r.charCodeAt(s))}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 s=e.charCodeAt(i++);n=(r<<10)+s+(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 rp={};function Fo(o,e){rp[o]=e}function op(o){let e=o.getBufferIdentifier(),t=rp[e];return t(o)}function sp(o){return typeof o.guid=="function"?o.guid():null}var Lc=ra(ja(),1);var Ha=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 Lc.default(e);t.on("error",i=>{console.error(i),this._host=void 0,this.trySetupClient(e)}),t.on("open",i=>{this._host=new Hc(t)})}trySetupClient(e){this._client=new Lc.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)})})}},jc=class{_peer;constructor(e){this._peer=e}};var Hc=class extends jc{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 Fa="wss://needle-tiny-starter.glitch.me/socket",ct=!!M("debugnet"),Ba=!!(ct||M("debugowner"));var Jn=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||(Ba&&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 Ba&&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?(Ba&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Ba&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}},Ua=class{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Ha),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return ct}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(),ct&&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]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){ct&&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&&ct&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;let t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){if(!t||!this._listeners[e])return;let i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinrary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;let i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}connect(){if(this.connected)return;ct&&console.log("connecting");let e=this.netWebSocketUrlProvider?.getWebsocketUrl();e?Fa=e:hh()&&(Fa="wss://"+window.location.host+"/socket"),this.connectWebsocket()}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_isConnectingToWebsocket=!1;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;connectWebsocket(){if(this._isConnectingToWebsocket)return;this._isConnectingToWebsocket=!0,console.log("Connecting to "+Fa);let e=new Hg(Fa).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{ct&&i==="pong"&&console.log("<<",i)}}async handleIncomingBinaryMessage(e){let t=await e.arrayBuffer();var i=new Uint8Array(t);let n=new Ai(i),r=n.getBufferIdentifier(),s=this._listenersBinary[r],a=op(n),c=sp(a);if(c&&typeof c=="string"&&(this._state[c]=a),!s)return;let u=a??n;for(let l of s)l(u)}handleIncomingStringMessage(e){if(ct&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){let s=e.data;s&&(console.assert(s.id!==void 0&&s.id!==null&&s.id.length>0,"server did not send connection id",s.id),console.log("Your id is: "+s.id,this.context.alias??""),this._connectionId=s.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(ct&&console.log(e),e){this._isInRoom=!0;let s=e;this._currentRoomName=s.room,this._currentRoomViewId=s.viewId,this._currentRoomAllowEditing=s.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...s.inRoom),ct&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(1);break;case"left-room":e.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(e.data){let s=e.data;this._currentInRoom.push(s.userId),ct&&console.log(s.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){let s=e.data,a=this._currentInRoom.indexOf(s.userId);a>=0&&(console.log(s.userId+" left",this.context.alias??""),this._currentInRoom.splice(a,1)),s.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":ct&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":let r=e.data?.time;r&&(this._currentDelay=this.context.time.time-r),ct&&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));ct&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){let t=this._waitingForSocket[e];if(t){for(let i of t)i();t.length=0}}};import{EffectComposer as lb}from"three/examples/jsm/postprocessing/EffectComposer.js";import{RenderPass as cb}from"three/examples/jsm/postprocessing/RenderPass";import*as Zn from"three";var gp=ra(mp(),1),Ga=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(o,e){let t=await o.arrayBuffer(),i=vp(t),n=o.name.split(".").pop(),r=i+"."+n,s=o.name.split(".").shift();console.assert(s!==void 0);let a={alias:s,filename:r},u=await(await fetch(e+"/exists",{method:"POST",body:JSON.stringify(a)})).json();if(u.success||console.warn("exists check did fail"),u.exists)return console.log("file already exists",i),new Ga(!0,r,i,o.size);console.log("begin uploading file",s,o.size);let l=new FormData;l.append("file",o);let d={};d.filesize=o.size,s&&(d.alias=s);let b=await(await fetch(e+"/upload/file",{method:"POST",body:l,headers:d})).json();if(b?.success===!1)return b.message!==void 0?console.error("Upload failed:",b.message):console.error("Upload failed"),null;console.assert(b.hash_sum===i,"hash sum did not match","received:",b.hash_sum,"expected:",i),b.success&&console.log("successfully uploaded",i,b.id);let _=new Ga(b.success,r,i,o.size);return _.url=e,_}function vp(o){return(0,gp.default)(new Uint8Array(o))}async function Va(o,e,t,i,n=!1){try{let r=await fetch(i+"/download/file",{method:"POST",body:o});if(r.status!==200)return console.error("download failed",r),null;let s=await r.blob(),a=await s.arrayBuffer();n||console.assert(s.size===t,"size mismatch","expected:",t,"got:",s.size);let c=vp(a);return n||console.assert(c===e,"hash mismatch, downloaded file is invalid"),s.arrayBuffer()}catch(r){console.error(r)}return null}async function yp(o,e){let t=await fetch(o),i=t.body?.getReader(),n=t.headers.get("Content-Length"),r=n?parseInt(n):0;if(!i)return null;let s=0,a=[];for(;;){let{done:l,value:d}=await i.read();if(d&&(a.push(d),s+=d.length,e.call(null,new ProgressEvent("progress",{loaded:s,total:r}))),l)break}let c=new Uint8Array(s),u=0;for(let l of a)c.set(l,u),u+=l.length;return c}function za(o,e,t){console.warn("Adding components on object has been temporarily disabled")}var xp,_p=null;function Qe(){return xp}function Wa(o){_p!==o&&(_p=o,xp=new o)}var Uc=class{guid;file_name;file_hash;file_size;position;seed;sender;serverUrl;parentGuid;boundsSize;constructor(e,t,i,n,r,s,a,c){this.seed=t,this.guid=i,this.file_name=n,this.file_hash=r,this.file_size=s,this.position=a,this.sender=e,this.serverUrl=c}};async function wp(o,e,t){let i=o.name;return i.endsWith(".gltf")||i.endsWith(".glb")?new Promise((n,r)=>{let s=new FileReader;s.readAsDataURL(o),s.onloadend=async a=>{let c=s.result,u=Ea(),l=new Ue(u),d=await Qe().loadSync(e,c,l,!0);if(d&&d.scene){let h=d.scene;if(!h.guid){let b=new Ue(u);h.guid=b.generateUUID()}t&&Gg(e.connection,o,u,h,t),za(h,l,d),n(d)}}}):(console.warn("Unsupported file type: "+i),console.log(o),null)}async function Ep(o,e){return new Promise(async(t,i)=>{let n=Ea(),r=new Ue(n),s=await Qe().loadSync(e,o.toString(),r,!0);if(s&&s.scene){let a=s.scene;za(a,r,s),t(s)}else console.warn("Unsupported file type: "+o.toString())})}function Cp(o){o.connection.beginListen("file-spawned",async e=>{if(e.sender!==o.connection.connectionId){console.log("received file event",e),Vg(e,o);let t=null;try{t=await Va(e.file_name,e.file_hash,e.file_size,e.serverUrl)}finally{zg(e,o)}if(t){let i=new Ue(e.seed),n=await Qe().parseSync(o,t,null,i);if(n&&n.scene){let r=n.scene;if(za(r,i,n),e.parentGuid){let s=Ar(e.parentGuid,o.scene);"add"in s&&s.add(r)}r.parent||o.scene.add(r),e.position!==null&&r.position.copy(e.position)}}else console.error("download didnt return file")}})}async function Gg(o,e,t,i,n){if(!o.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 s=new Uc(o.connectionId,t,i.guid,r.filename,r.hash,e.size,i.position,r.url??n);i.parent&&(s.parentGuid=i.parent.guid),o.send("file-spawned",s)}var Gc={};function Vg(o,e){let t=new Zn.BoxGeometry,i=new Zn.Mesh(t,new Zn.MeshBasicMaterial({color:65280})),n=new Zn.BoxHelper(i,5592405);if(Gc[o.guid]=n,e.scene.add(n),o.parentGuid){let r=Ar(o.parentGuid,e.scene);r&&r.add(n)}o.position&&n.position.copy(o.position)}function zg(o,e){let t=o.guid,i=Gc[t];i&&(delete Gc[t],i.removeFromParent())}import*as Tp from"three";var iC=M("debugassets");var Na=class{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;let t=e?.reason?.path;if(t){let i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
|
|
150
|
+
`+i.src),e.preventDefault())}})}texturesLoader=new Tp.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 Ap from"three/examples/jsm/libs/stats.module";import{Vector4 as Jg,EquirectangularReflectionMapping as Qa,sRGBEncoding as qa,WebGLCubeRenderTarget as Zg}from"three";import{LightProbeGenerator as $g}from"three/examples/jsm/lights/LightProbeGenerator.js";import*as Rp from"three";var Ng=new Rp.FileLoader;async function Vc(o){return new Promise((e,t)=>{Ng.load(o,e,void 0,t)})}import{Vector4 as $n,FileLoader as Qg,DataTexture as Qc,RGBAFormat as qg,Color as Yg}from"three";var ks=new Uint8Array(4);ks[0]=255;ks[1]=255;ks[2]=255;ks[3]=255;var Op=new Qc(ks,1,1,qg);function Xa(o,e=1){let t="alpha"in o,i=e*e,n=new Uint8Array(4*i),r=Math.floor(o.r*255),s=Math.floor(o.g*255),a=Math.floor(o.b*255);for(let u=0;u<i;u++){let l=u*4;n[l+0]=r,n[l+1]=s,n[l+2]=a,t?n[l+3]=Math.floor(o.alpha*255):n[l+3]=255}let c=new Qc(n,e,e);return c.needsUpdate=!0,c}function kp(o,e,t,i=1,n=3){let a=i*n,c=[o,e,t],u=c.length,l=new Uint8Array(4*u*a),d=new Yg;for(let b=0;b<n;b++){let _=Math.floor(b/n*u),v=F.clamp(_+1,0,u-1),y=c[_],f=c[v],m=b/n*u%1;d.lerpColors(y,f,m);let p=Math.floor(d.r*255),g=Math.floor(d.g*255),w=Math.floor(d.b*255);for(let C=0;C<i;C++){let T=(b*i+C)*4;l[T+0]=p,l[T+1]=g,l[T+2]=w,l[T+3]=255}}let h=new Qc(l,i,n);return h.needsUpdate=!0,h}var Wc=class{stage;code;constructor(e,t){this.stage=e,this.code=t}},Nc=class{loaded=new Map;async loadShader(e){let t=await Vc(e);return JSON.parse(t)}async load(e,t){if(this.loaded.has(t))return new Promise((r,s)=>{let a=this.loaded.get(t);a?r(a):s("Shader not found")});let i=await Vc(t),n=new Wc(e,i);return this.loaded.set(t,n),n}},aC=new Nc;function Ms(o,e){let t=o.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){let n=t[i],r=t[i+1],s=t[i+2],a=t[i+3],c=new $n(n,r,s,a);e.push(c)}return e}var zc=[],Sp=[];function qc(o,e){if(zc.length===0)for(let t=0;t<27;t++)zc.push(0);e||(e=zc);for(let t=0;t<27;t++)Sp[t]=e[t];e=Sp,o.unity_SHAr={value:new $n(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new $n(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new $n(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new $n(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new $n(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new $n(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new $n(e[24],e[25],e[26],1)}}var Xc=class{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}};async function Mp(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;let t=o.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){let r=o.shaders[i],s=o.shaders[n];if(r.uri&&s.uri||r.code&&s.code){if(!r.code&&r.uri&&await Pp(r),!s.code&&s.uri&&await Pp(s),!r.code||!s.code)return null;let a=o.techniques[e];return new Xc(r.code,s.code,a)}}return console.error("Shader technique not found",e),null}async function Pp(o){let e=o.uri;if(!!e)if(e.endsWith(".glsl")){let i=await new Qg().loadAsync(e);o.code=i.toString()}else o.code=Kg(o.uri)}function Kg(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}var Yc=M("debugenvlight"),Jc=(n=>(n[n.Skybox=0]="Skybox",n[n.Trilight=1]="Trilight",n[n.Flat=3]="Flat",n[n.Custom=4]="Custom",n))(Jc||{});var Ya=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 Jg;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 Kc(this.context,t,1);this._lighting[e]=i}getReflection(e){return this._lighting[e]}enableReflection(e){switch(Yc&&console.log(this.sceneLightSettings?Jc[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=qa,n.mapping=Qa,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=kp(t[0],t[1],t[2],64,64);i.encoding=qa,i.mapping=Qa,this.context.scene.environment=i}else console.error("Missing ambient trilight",this.sceneLightSettings.sourceId);return;case 3:if(this.sceneLightSettings.ambientLight){let t=Xa(this.sceneLightSettings.ambientLight,64);t.encoding=qa,t.mapping=Qa,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 Yc&&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={}},Kc=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=Qa,t.encoding=qa}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){Yc&&console.log("GENERATING LIGHT PROBE",t);let n=Math.min(t.image.width,512);i=new Zg(n).fromEquirectangularTexture(this._context.renderer,t),this._source=i.texture}if(this._sphericalHarmonicsArray=[],i){let n=$g.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 s=e/(Math.PI*.5);for(let a=0;a<this._sphericalHarmonicsArray.length;a++)this._sphericalHarmonicsArray[a]*=s;if(n.sh.scale(r),this._source)return{array:this._sphericalHarmonicsArray,texture:this._source,lightProbe:n}}}catch(t){console.error(t)}return null}};import{Object3D as eb}from"three";var Vr=M("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}},qe=class{static getOrCreate(e,t,i){let n=ki(e,t);Vr&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);let r=i.addressables,s=r.findAssetReference(n);if(s)return s;let a=new qe(n,i.hash);return r.registerAssetReference(a),a}get asset(){return this._glbRoot??this._asset}set asset(e){this._asset=e}_loading;get uri(){return this._uri}get rawAsset(){return this._asset}_asset;_glbRoot;_uri;_progressListeners=[];_hash;_hashedUri;_isLoadingRawBinary=!1;_rawBinary;constructor(e,t){this._uri=e,this._hash=t,e.includes("?v=")?this._hashedUri=e:this._hashedUri=t?e+"?v="+t:e,Fh(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?li(this.asset.scene):li(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._hashedUri);let e=await yp(this._hashedUri,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(!this.mustLoad)return;if(e&&this._progressListeners.push(e),this._loading!==void 0)return this._loading;let t=V.Current;this._rawBinary?(this._loading=Qe().parseSync(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=Qe().loadSync(t,this._hashedUri,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 yn(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=V.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 Ge?e:null;if(r||(r=new Ge),typeof e=="object"&&(e instanceof eb?r.parent=e:Object.assign(r,e)),t){r.context=n;let s=this.asset;s.guid=this.uri;let a=wa(s,r,void 0,i);if(a)return a}else{let s=Lr(this.asset,r);if(s)return s}}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}},Zc=class extends gn{constructor(){super([qe])}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?qe.getOrCreate(t.gltfId,e,t.context):(console.error("Missing spurce id"),null):(console.error("Missing context"),null):null}};new Zc;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}}};import{FloatType as tb,HalfFloatType as ib,sRGBEncoding as nb}from"three";var Ip="NEEDLE_lightmaps",rb=M("debuglightmapsextension"),Is=(i=>(i[i.Lightmap=0]="Lightmap",i[i.Skybox=1]="Skybox",i[i.Reflection=2]="Reflection",i))(Is||{}),Za=class{get name(){return Ip}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[Ip];if(i){let n=i.textures;return n?.length?(rb&&console.log(i),new Promise(async(r,s)=>{let a=[];for(let c of n)if(c.pointer){let u=To(this.parser,c.pointer).then(l=>{let d=l;d?.isTexture&&(this.registry?(c.type!==0&&(d.encoding=nb),(d.type==tb||d.type==ib)&&(d.flipY=!0),this.registry.registerTexture(this.source,c.type,d,c.index)):console.log(Is[c.type],c.pointer,d))});a.push(u)}await Promise.all(a),r()})):null}}return null}};import*as Li from"three";var Dp=!!M("debuglightmaps"),$a=class{_context;_lightmaps=new Map;constructor(e){this._context=e}registerTexture(e,t,i,n){Dp&&console.log("Registering lightmap",e,Is[t],i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);let r=this._lightmaps.get(e),s=r?.get(t)??[];s.length<n&&(s.length=n+1),s[n]=i,r?.set(t,s)}tryGetLightmap(e,t=0){return this.tryGet(e,0,t)}tryGetSkybox(e){return this.tryGet(e,1,0)}tryGetReflection(e){return this.tryGet(e,2,0)}tryGet(e,t,i){if(!e)return Dp&&console.warn("Missing source id"),null;let n=this._lightmaps.get(e)?.get(t)??null;return!n?.length||n.length<=i?null:n[i]}};Li.ShaderChunk.lights_fragment_maps=Li.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vUv2 );",`
|
|
151
151
|
|
|
152
152
|
vec2 lUv = vUv2.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
|
|
153
153
|
vec4 lightMapTexel = texture2D( lightMap, lUv);
|
|
@@ -155,7 +155,7 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
|
|
|
155
155
|
lightMapTexel.rgb *= lightMapTexel.a * 8.; // no idea where that "8" comes from... heuristically derived
|
|
156
156
|
lightMapTexel.a = 1.;
|
|
157
157
|
lightMapTexel = conv_sRGBToLinear(lightMapTexel);
|
|
158
|
-
`);
|
|
158
|
+
`);Li.ShaderChunk.lightmap_pars_fragment=`
|
|
159
159
|
#ifdef USE_LIGHTMAP
|
|
160
160
|
uniform sampler2D lightMap;
|
|
161
161
|
uniform float lightMapIntensity;
|
|
@@ -166,14 +166,14 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
|
|
|
166
166
|
return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
|
|
167
167
|
}
|
|
168
168
|
#endif
|
|
169
|
-
`;
|
|
169
|
+
`;Li.ShaderChunk.lights_fragment_begin=Li.ShaderChunk.lights_fragment_begin.replace("irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );",`
|
|
170
170
|
#if defined(USE_LIGHTMAP)
|
|
171
171
|
irradiance += 0.;
|
|
172
172
|
#else
|
|
173
173
|
irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
|
|
174
|
-
#endif`);Ai.UniformsLib.lightmap.lightmapScaleOffset={value:new Ai.Vector4(1,1,0,0)};var ob=M("debugplayerview");var $c=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}},el=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new $c(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&&(ob&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}};var ub=M("debugSetup"),db=M("stats"),tl={};var Vt=(a=>(a[a.EarlyUpdate=0]="EarlyUpdate",a[a.Update=1]="Update",a[a.LateUpdate=2]="LateUpdate",a[a.OnBeforeRender=3]="OnBeforeRender",a[a.OnAfterRender=4]="OnAfterRender",a[a.PrePhysicsStep=9]="PrePhysicsStep",a[a.PostPhysicsStep=10]="PostPhysicsStep",a))(Vt||{});function Ra(o,e){if(!o)return;let t=e?.new_scripts??V.Current.new_scripts;t.includes(o)||t.push(o)}var wt=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;hash;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 isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get xrSession(){return this.renderer.xr?.getSession()}get arOverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=-1;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=db?Ap.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let i=M("postfx");this.renderer=new ab({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Re.NoToneMapping,this.renderer.setClearColor(new Re.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Re.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=Re.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=i?new lb(this.renderer):null}this.scene=new Re.Scene,this.application=new Ja(this),this.time=new Ia,this.input=new fa(this),this.physics=new Yn(this),this.connection=new Ua(this),this.assets=new Na,this.rendererData=new Ya(this),this.addressables=new Ka(this),this.lightmaps=new $a(this),this.players=new el(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,li(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,s,a,c,u)=>{let l=this._onBeforeRenderListeners[e.uuid];if(!!l)for(let d=0;d<l.length;d++){let h=l[d];h(n,r,s,a,c,u)}};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){await this.physics.createWorld();let i=!0;try{wt.Current=this,e&&await e(this,t)}catch(n){console.error(n),i=!1}if(!!i){this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),jh(this),Lh(this),Cp(this),wt._current=this;for(let n=0;n<this.new_scripts.length;n++){let r=this.new_scripts[n];if(r.gameObject!==void 0&&r.gameObject!==null){r.gameObject.userData===void 0&&(r.gameObject.userData={}),r.gameObject.userData.components===void 0&&(r.gameObject.userData.components=[]);let s=r.gameObject.userData.components;s.includes(r)||s.push(r)}}if(this.post_setup_callbacks)for(let n=0;n<this.post_setup_callbacks.length;n++)wt._current=this,await this.post_setup_callbacks[n](this);if(!this.mainCamera){wt._current=this;let n=null;ci(this.scene,r=>{let s=r;if(s?.isCamera){if(s.tag==="MainCamera")return n=s,!0;n=s}}),n?this.setCurrentCamera(n):console.error("MISSING camera",this)}if(wt._current=this,vn(this),!this.isManagedExternally&&this.composer&&this.mainCamera){let n=new cb(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(n),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),this.renderer.setAnimationLoop(this.render.bind(this)),ub&&Es(this.scene,!0)}}render(e,t){for(this._currentFrameEvent=-1,this._stats?.begin(),wt._current=this,this.time.update(),vn(this),Po(),ya(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]();this._currentFrameEvent=0;for(let i=0;i<this.scripts_earlyUpdate.length;i++){let n=this.scripts_earlyUpdate[i];!n.activeAndEnabled||n.earlyUpdate!==void 0&&(wt._current=this,n.earlyUpdate())}this.executeCoroutines(0),this._currentFrameEvent=1;for(let i=0;i<this.scripts_update.length;i++){let n=this.scripts_update[i];!n.activeAndEnabled||n.update!==void 0&&(wt._current=this,n.update())}this.executeCoroutines(1),this._currentFrameEvent=2;for(let i=0;i<this.scripts_lateUpdate.length;i++){let n=this.scripts_lateUpdate[i];!n.activeAndEnabled||n.lateUpdate!==void 0&&(wt._current=this,n.lateUpdate())}this.executeCoroutines(2);try{let n=this.time.deltaTime/1;for(let r=0;r<1;r++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.step(n),this._currentFrameEvent=10,this.executeCoroutines(10)}catch(i){console.error(i)}this.physics.postStep(),this._currentFrameEvent=3;for(let i=0;i<this.scripts_onBeforeRender.length;i++){let n=this.scripts_onBeforeRender[i];!n.activeAndEnabled||n.onBeforeRender!==void 0&&(wt._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._currentFrameEvent=-10,this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer&&!this.isInXR?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1,this._currentFrameEvent=4;for(let i=0;i<this.scripts_onAfterRender.length;i++){let n=this.scripts_onAfterRender[i];!n.activeAndEnabled||n.onAfterRender!==void 0&&(wt._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._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats?.end()}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new Re.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new sb(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Re.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Re.NearestFilter,this._renderTarget.texture.magFilter=Re.NearestFilter,this._renderTarget.texture.format=Re.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 a=r.chained;if(a&&a.length>0){let d=a[a.length-1].next();if(d.done&&a.pop(),t(d)&&(r.chained||(r.chained=[]),r.chained.push(d.value)),!d.done)continue}let c=r.main.next();if(c.done===!0){i.splice(n,1),--n;continue}let u=c.value;if(t(u)){if(u.next().done)continue;r.chained||(r.chained=[]),r.chained.push(u)}}}function t(i){return!!(i&&i.next&&i.return)}}},V=wt;L(V,"_current");var eu={};nh(eu,{Behaviour:()=>k,Component:()=>Et,GameObject:()=>R});import*as tt from"three";var R=class extends tt.Object3D{guid;static setActive(e,t,i=!0,n=!0){!e||(Oa(e,t,n),Po(e),t&&i&&ya(V.Current,e))}static isActiveSelf(e){return Dr(e)}static isActiveInHierarchy(e){return Kh(e)}static markAsInstancedRendered(e,t){Jh(e,t)}static isUsingInstancing(e){return ka(e)}static foreachComponent(e,t,i=!0){return ci(e,t,i)}static instantiateSynced(e,t){return e?wa(e,t):null}static instantiate(e,t=null){return Lr(e,t)}static destroySynced(e,t,i=!0){if(!e)return;let n=e;t=t??V.Current,Oo(n,t.connection,i)}static destroy(e,t=!0,i=!0){return li(e,t,i)}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=V.Current),t.add(e),Oa(e,!0),Po(e),i?R.foreachComponent(e,n=>{yc(n,i),!n.__internalDidAwakeAndStart&&i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){!e||(e.parent?.remove(e),Oa(e,!1),Po(e),R.foreachComponent(e,t=>{Rh(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 s=r[t];s&&typeof s=="function"&&s.bind(r)(...n)},i)}static addNewComponent(e,t,i=!0){let n=new t;return qn(e,n,i),n}static addComponent(e,t){if(t.gameObject==null)throw new Error("Did you mean to create a new component? Use addNewComponent");Wh(e,t)}static removeComponent(e){return Ca(e.gameObject,e),e}static getOrAddComponent(e,t){return Ta(e,t)}static getComponent(e,t){return e===null?null:jr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:Mo(e,t,i)}static findByGuid(e,t){return Ar(e,t)}static findObjectOfType(e,t,i=!0){return Qh(e,t??V.Current,i)}static findObjectsOfType(e,t){let i=[];return qh(e,i,t),i}static getComponentInChildren(e,t){return Hr(e,t)}static getComponentsInChildren(e,t,i=null){return Io(e,t,i??void 0)}static getComponentInParent(e,t){return ko(e,t)}static getComponentsInParent(e,t,i=null){return Ss(e,t,i)}static getAllComponents(e){return[...e.userData?.components]}static*iterateComponents(e){let t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}},di=class{get isComponent(){return!0}__context;get context(){return this.__context??V.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}get hideFlags(){return this.gameObject?.userData.hideFlags}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;let e=this.gameObject[Mi];return e===void 0?!0:e}set __isActiveInHierarchy(e){!this.gameObject||(this.gameObject[Mi]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=1){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=1){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(){this.__internalNewInstanceCreated()}__internalNewInstanceCreated(){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(){return this.__didEnable?!1:(this.__didEnable=!0,this.onEnable(),this.__isEnabled=!0,!0)}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this.onDisable(),this.__isEnabled=!1)}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.destroy?.call(this),Nh(this))}get enabled(){return this.__isEnabled??!0}set enabled(e){if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}_worldPosition=void 0;_worldQuaternion=void 0;_worldEuler=void 0;_worldRotation=void 0;get worldPosition(){return this._worldPosition||(this._worldPosition=new tt.Vector3),U(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){te(this.gameObject,e)}setWorldPosition(e,t,i){di._worldPositionBuffer.set(e,t,i),this.worldPosition=di._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new tt.Quaternion),he(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){$e(this.gameObject,e)}setWorldQuaternion(e,t,i,n){di._worldQuaternionBuffer.set(e,t,i,n),this.worldQuaternion=di._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new tt.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new tt.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new tt.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=F.toDegrees(t.x),t.y=F.toDegrees(t.y),t.z=F.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){n&&(e=F.toRadians(e),t=F.toRadians(t),i=F.toRadians(i)),di._worldEulerBuffer.set(e,t,i),di._worldQuaternionBuffer.setFromEuler(di._worldEulerBuffer),this.worldQuaternion=di._worldQuaternionBuffer}get forward(){return di._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}},Et=di;L(Et,"_worldPositionBuffer",new tt.Vector3),L(Et,"_worldQuaternionBuffer",new tt.Quaternion),L(Et,"_worldEulerBuffer",new tt.Euler),L(Et,"_tempQuaternionBuffer2",new tt.Quaternion),L(Et,"_forward",new tt.Vector3);var k=class extends Et{};var hi=function(o,e){return function(t,i,n){hb(t,i,n,o,e)}};function hb(o,e,t,i,n){if(!(!n&&!i&&!o.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Ze("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,2);return}if(o.__internalAwake){let r=Symbol(e),s=o.__internalAwake;o.__internalAwake=function(){this[r]===void 0&&(this[r]=this[e],Object.defineProperty(this,e,{set:function(a){if(this[pa]===!0)this[r]=a;else{i?.call(this,a);let c=this[r];this[r]=a,this.onValidate?.call(this,e,c)}},get:function(){return n?.call(this),this[r]}})),s.call(this)}}}}var Lp=M("debugloadingbar");var Ds=0,jp;function tu(o){Lp&&console.log(o.progress.loaded.toFixed(0)+"/"+o.progress.total.toFixed(0),o);let e=o.count,t=o.progress.total;t===0||t===void 0?(jp!==o.name&&(Ds=0),jp=o.name,Ds+=(1-Ds)*.001,Lp&&vs("Loading "+o.name+" did not report total size")):Ds=o.progress.loaded/t;let i=o.index/e+Ds/e;return F.clamp01(i)}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){console.warn("Custom loading container is not allowed"),this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement(i);return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let i=0;typeof e=="number"?i=e:("index"in e&&(i=tu(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,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=F.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}updateDisplay(){let e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){this._loadingElement=e||document.createElement("div"),e||(this._loadingElement.style.position="fixed",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",this._loadingElement.style.backgroundColor="#000000",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex="1000",this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let a of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(a);let i=document.createElement("div"),n=30;i.style.display="flex",i.style.width=n+"%",i.style.height="2px",i.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(i),this._loadingBar=document.createElement("div"),i.appendChild(this._loadingBar);let r=function(a){return F.lerp(n*.5,100-n*.5,a)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${r(0)}, #0BA398 ${r(.4)}, #99CC33 ${r(.5)}, #D7DB0A ${r(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let s=document.createElement("div");return this._messageContainer=s,s.style.display="flex",s.style.fontSize=".8em",s.style.paddingTop=".5em",s.style.color="rgba(255,255,255,.5)",s.style.justifyContent="center",this._loadingElement.appendChild(s),this._loadingElement}};import{DRACOLoader as iu}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Hp}from"three/examples/jsm/loaders/KTX2Loader.js";var As=M("debugdecoders"),pi,er;function nu(o){o!==void 0&&typeof o=="string"&&(pi||(pi=new iu),As&&console.log("Setting draco decoder path to",o),pi.setDecoderPath(o))}function ru(o){o!==void 0&&typeof o=="string"&&(pi||(pi=new iu),As&&console.log("Setting draco decoder type to",o),pi.setDecoderConfig({type:o}))}function ou(o){o!==void 0&&typeof o=="string"&&(er||(er=new Hp),As&&console.log("Setting ktx2 transcoder path to",o),er.setTranscoderPath(o))}function _n(o,e){pi||(pi=new iu,pi.setDecoderPath("./include/draco/"),pi.setDecoderConfig({type:"js"}),As&&console.log("Setting draco decoder path to","./include/draco/")),er||(er=new Hp,er.setTranscoderPath("./include/ktx2/"),As&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&er.detectSupport(e.renderer)),o.setDRACOLoader(pi),o.setKTX2Loader(er)}import{AnimationClip as pb,MathUtils as fb}from"three";var Bo=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 Bp(o,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??fb.generateUUID(),index:-1,clip:new pb(o,1,[])}}import{AnimationClip as mb,AnimationMixer as gb,AxesHelper as bb,Euler as Up,LoopOnce as vb,Quaternion as fi,Vector3 as Ls}from"three";import*as rl from"three";var tr=M("debuganimatorcontroller"),su=M("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 s=this.model.layers[t].stateMachine;for(let a of s.states)if(a.name===e||a.hash===e){tr&&console.log("transition to ",a),this.transitionTo(a,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){tr&&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 gb(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=gs(this.model,(i,n,r)=>r==null?!0:r.type==="Object3D"||r.isObject3D===!0?!1:Ch(r)?(console.log(r),!1):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,tr&&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()&&(tr&&console.debug("REMOVE",t.name,n.getEffectiveWeight(),n.isRunning(),n.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}let i=this._activeState,n=i.motion.action,r=0;for(let a of i.transitions){if(++r,!a.hasExitTime&&a.conditions.length<=0)continue;let c=!0;for(let u of a.conditions)if(!this.evaluateCondition(u)){c=!1;break}if(!!c){for(let u of a.conditions){let l=this.model.parameters.find(d=>d.name===u.parameter);l?.type===9&&(l.value=!1)}if(n){let u=i.motion.clip.duration,l=u<=0?1:n.time/u;if(a.hasExitTime?l>=a.exitTime:!0){n.clampWhenFinished=!0,tr&&console.log("transition to "+a.destinationState,a,l,a.exitTime,a.hasExitTime),this.transitionTo(a.destinationState,a.duration,a.offset);return}}else{this.transitionTo(a.destinationState,a.duration,a.offset);return}}}let s=!1;if(i.motion.isLooping&&n&&n.time>=n.getClip().duration&&(s=!0,n.reset(),n.time=0,n.play()),!s&&i&&!t&&n&&this.animator&&i.behaviours){let a=n?.getClip().duration,c=n.time/a,u=new Bo(this._activeState,c,a,this._speed);for(let l of i.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,u,0)}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(e=this.getState(e,n),!e?.motion||!e.motion.clip)return;let r=this._activeState===e;if(r){let u=e.motion;!u.action_loopback&&u.clip&&(this._mixer.uncacheAction(u.clip,this.animator.gameObject),u.action_loopback=this.createAction(u.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let u=this._activeState?.motion.clip.duration,l=this._activeState.motion.action.time/u,d=new Bo(this._activeState,l,u,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateExit?.call(h.instance,this.animator,d,n)}let s=this._activeState?.motion.action;s&&s.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=s);let a=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){i=Math.max(0,Math.min(1,i)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let u=e.motion.clip.duration;if(c.time=i*u,c.clampWhenFinished=!0,c.setLoop(vb,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 Bo(e,i,u,this._speed);for(let d of this._activeState.behaviours)d.instance?.onStateEnter?.call(d.instance,this.animator,l,n)}}else console.warn("No action",e.motion,this);tr&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,s,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new au(this));let i=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,i,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=Bp(r.name)),this.animator&&r.motion.clips){let s=r.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r.motion.clip=s?.clip}if(!r.motion.clip){let s=new mb;r.motion.clip=s}if(r.motion?.clip){let s=r.motion.clip,a=this.createAction(s);r.motion.action=a}if(r.behaviours&&Array.isArray(r.behaviours))for(let s of r.behaviours){if(!s?.typeName)continue;let a=O.get(s.typeName),c=new a;c.isStateMachineBehaviour&&(c._context=this.context??void 0,oi(c,s.properties),s.instance=c),tr&&console.log("Created animator controller behaviour",r.name,s.typeName,s.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let 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},nl=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 s=this.originalEvaluate(r);return t(r,s)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},we=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new Ls;rotationChange=new fi;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,we.firstKeyframeRotation[i.uuid]||(we.firstKeyframeRotation[i.uuid]=new rl.Quaternion),r){let s=r.values;we.firstKeyframeRotation[i.uuid].set(s[0],s[1],s[2],s[3])}we.spaceRotation[i.uuid]||(we.spaceRotation[i.uuid]=new fi),we.effectiveSpaceRotation[i.uuid]||(we.effectiveSpaceRotation[i.uuid]=new fi),we.clipOffsetRotation[i.uuid]=new fi,r&&we.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=we.lastObjRotation[this.root.uuid];we.spaceRotation[this.clip.uuid].copy(t);{let i=new rl.Euler().setFromQuaternion(t);console.log("START",this.clip.name,F.toDegrees(i.y))}}getClipRotationOffset(){return we.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;su&&i.add(new bb),we.lastObjPosition[i.uuid]||(we.lastObjPosition[i.uuid]=new Ls);let n=new Ls,r=new Ls,s=0;this.positionWrapper=new nl(t,(a,c)=>{let u=this.action.getEffectiveWeight();if(su&&i.position.length()>8&&i.position.set(0,i.position.y,0),a>s){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(u),n.applyQuaternion(this.getClipRotationOffset());let l=this.clip.uuid;n.applyQuaternion(we.spaceRotation[l]),this.positionChange.copy(n)}return r.fromArray(c),s=a,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(su){let a=t.values,c=new Up().setFromQuaternion(new fi(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",F.toDegrees(c.y));let u=t.values.length-4,l=new fi().set(a[u],a[u+1],a[u+2],a[u+3]),d=new Up().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",F.toDegrees(d.y))}let i=this.root;we.lastObjRotation[i.uuid]||(we.lastObjRotation[i.uuid]=new fi);let n=0,r=new fi,s=new fi;this.rotationWrapper=new nl(t,(a,c)=>(a>n&&(s.set(c[0],c[1],c[2],c[3]),r.invert(),s.multiply(r),this.rotationChange.copy(s)),r.fromArray(c),n=a,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(we.identityQuaternion,1-e)}},mi=we;L(mi,"lastObjPosition",{}),L(mi,"lastObjRotation",{}),L(mi,"firstKeyframeRotation",{}),L(mi,"spaceRotation",{}),L(mi,"effectiveSpaceRotation",{}),L(mi,"clipOffsetRotation",{}),L(mi,"identityQuaternion",new fi);var au=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"),s=this.findRootTrack(i,".quaternion"),a=new mi(this.controller.context,t,i,r,s);this.handler.push(a);let c=e.clipAction(i);return a.action=c,c}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new Ls;summedRotation=new fi;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),mi.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 w=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=Gp(o);else for(let e=0;e<o.length;e++){let t=o[e];o[e]=Gp(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=o}};function Gp(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}var yb=M("debuganimator"),Ye=class extends k{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=F.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=F.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}yb&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};E([w()],Ye.prototype,"applyRootMotion",2),E([w()],Ye.prototype,"hasRootMotion",2),E([w()],Ye.prototype,"keepAnimatorControllerStateOnDisable",2),E([w()],Ye.prototype,"runtimeAnimatorController",1);import*as zr from"three";var lu=M("debuganimation"),Wt=class extends k{playAutomatically=!0;randomStartTime=!0;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){lu&&console.log("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(lu&&console.log("Assign clip",e,Boolean(this.gameObject)),this.gameObject.animations||(this.gameObject.animations=[]),this.gameObject.animations.push(e))}set animations(e){lu&&console.log("assign 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&&oe.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}get isPlaying(){for(let e=0;e<this._currentActions.length;e++)if(this._currentActions[e].isRunning())return!0;return!1}play(e,t){if(this.init(),!this.mixer)return;e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length)return;i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(r=>r.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={}),t.minMaxOffsetNormalized||(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed||(t.minMaxSpeed=this.minMaxSpeed),t.loop||(t.loop=this.loop),t.clampWhenFinished||(t.clampWhenFinished=this.clampWhenFinished);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 a=this.tryFindHandle(e);if(a)return a.getPromise()}let n=t?.exclusive??!0;t?.fadeDuration?(n&&i?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):n&&i?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1;let r=e.getClip();t?.minMaxOffsetNormalized&&(e.time=F.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration),t?.minMaxSpeed&&(e.timeScale=F.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random())),t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0?e.loop=t.loop?zr.LoopRepeat:zr.LoopOnce:e.loop=zr.LoopOnce,e.play();let s=new cu(e,this.mixer,t,a=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){if(!this._didInit&&(this._didInit=!0,!!this.gameObject)){this.actions=[],this.mixer=new zr.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};E([w()],Wt.prototype,"playAutomatically",2),E([w()],Wt.prototype,"randomStartTime",2),E([w()],Wt.prototype,"loop",2),E([w()],Wt.prototype,"clampWhenFinished",2);var cu=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 om}from"three/examples/jsm/loaders/GLTFLoader.js";import*as Q from"three";import{RawShaderMaterial as xb}from"three";var xn=M("debugshaders"),Uo="NEEDLE_techniques_webgl";var uu=class{objectToWorldMatrix=new Q.Matrix4;worldToObjectMatrix=new Q.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Ms(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Ms(this.worldToObjectMatrix,this.worldToObject)}};var ce=class extends xb{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){let e=super.clone();return Vp(e),e}constructor(e,...t){super(...t),this.identifier=e,xn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName]&&this.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&V.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=V.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&V.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=V.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}xn&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},qc(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new Q.Vector4(r,r,r,r)},xn&&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 uu;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&V.Current.setRequireColor(!0),this.depthTextureUniform&&V.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,r,s){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=V.Current;e&&(ce.viewProjection&&this.uniforms[this._viewProjectionName]&&(ce.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Ms(ce.viewProjection,ce._viewProjectionValues)),ce.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ce.viewMatrix.copy(e.matrixWorldInverse),Ms(ce.viewMatrix,ce._viewMatrixValues)),this.uniforms[ce._worldSpaceCameraPosName]&&ce._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters?this.uniforms._TimeParameters.value=i.rendererData.timeVec4:this.uniforms._Time&&(this.uniforms._Time.value=i.rendererData.timeVec4);let n=i.mainLight;if(n){let a=U(n.gameObject,ce._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ce._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ce._mainLightColor};let c=n.intensity;ce._lightData.z=c,this.uniforms.unity_LightData={value:ce._lightData}}if(e&&(ce.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ce._viewProjectionValues),ce.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ce._viewMatrixValues),this.uniforms[ce._worldSpaceCameraPosName]&&(this.uniforms[ce._worldSpaceCameraPosName]={value:ce._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){let a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){let a=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;a.x=1-c.farClipPlane/c.nearClipPlane,a.y=c.farClipPlane/c.nearClipPlane,a.z=a.x/c.farClipPlane,a.w=a.y/c.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){let a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}}let r=this.depthTextureUniform;r&&(r.value=i.depthTexture);let s=this.opaqueTextureUniform;if(s&&(s.value=i.opaqueColorTexture),t){let a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}},Nt=ce;L(Nt,"viewProjection",new Q.Matrix4),L(Nt,"_viewProjectionValues",[]),L(Nt,"viewMatrix",new Q.Matrix4),L(Nt,"_viewMatrixValues",[]),L(Nt,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),L(Nt,"_worldSpaceCameraPos",new Q.Vector3),L(Nt,"_mainLightColor",new Q.Vector4),L(Nt,"_mainLightPosition",new Q.Vector3),L(Nt,"_lightData",new Q.Vector4);var ol=class{get name(){return Uo}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return xn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Uo])return xn&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[Uo].technique;if(i<0)return null;let n=this.parser.json.extensions[Uo];if(!n)return null;xn&&console.log(n);let r=n.techniques[i];return r?new Promise(async(s,a)=>{let c=await Mp(n,r.program),u=c?.fragmentShader,l=c?.vertexShader;if(!u||!l)return a();xn&&console.log("loadMaterial",t,c);let d={},h=r.uniforms;l.includes("_Time")&&(d._Time={value:new Q.Vector4(0,0,0,0)});for(let f in h){let m=f;switch(m){case"_TimeParameters":let p=new Q.Vector4;d[m]={value:p};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":d[m]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":d[m]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":d[m]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":d[m]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":d[m]={value:null};break}}let b=!1;if(t.extensions&&t.extensions[Uo]){let f=t.extensions[Uo];if(f.technique===i){xn&&console.log(t.name,"Material Properties",f);for(let m in f.values){let p=f.values[m];if(typeof p=="string"){if(p.startsWith("/textures/")){let g=p.substring(10),x=Number.parseInt(g);if(x>=0){let C=await this.parser.getDependency("texture",x);C&&(C.encoding=Q.LinearEncoding,C.needsUpdate=!0),d[m]={value:C};continue}}switch(m){case"alphaMode":p==="BLEND"&&(b=!0);continue}}if(Array.isArray(p)&&p.length===4){d[m]={value:new Q.Vector4(p[0],p[1],p[2],p[3])};continue}d[m]={value:p}}}}let _=new Nt(this.identifier,{name:t.name??"",uniforms:d,vertexShader:l,fragmentShader:u,lights:!1});switch(d._Cull?.value){case 0:_.side=Q.DoubleSide;break;case 1:_.side=Q.BackSide;break;case 2:_.side=Q.FrontSide;break;default:_.side=Q.FrontSide;break}switch(d._ZTest?.value){case 3:_.depthTest=!0,_.depthFunc=Q.EqualDepth;break;case 6:_.depthTest=!0,_.depthFunc=Q.NotEqualDepth;break;case 2:_.depthTest=!0,_.depthFunc=Q.LessDepth;break;case 4:_.depthTest=!0,_.depthFunc=Q.LessEqualDepth;break;case 5:_.depthTest=!0,_.depthFunc=Q.GreaterDepth;break;case 7:_.depthTest=!0,_.depthFunc=Q.GreaterEqualDepth;break;case 8:_.depthTest=!1,_.depthFunc=Q.AlwaysDepth;break}_.transparent=b,b&&(_.depthWrite=!1),qc(d),_.onUpdateUniforms();for(let f in h){let m=f,p=h[f].type;if(d[m]?.value===void 0)switch(p){case 35678:d[m]={value:Op},console.warn("Missing/unassigned texture, fallback to white: "+m);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+m,h[f]);break}}xn&&console.log(_.uuid,d),Vp(_),s(_)}):null}};function Vp(o){if(o.uniforms)for(let e in o.uniforms)Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{get:()=>o.uniforms[e].value,set:t=>{o.uniforms[e].value=t,o.needsUpdate=!0}})}var ir=Te,sl="$___Export_Components",wb="NEEDLE_components",du=class{[Ir]},hu=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},Go=class{get name(){return wb}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[sl]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&ir&&console.log("DONE",JSON.stringify(t)),e[sl]===void 0)return;let i=e[sl];delete e[sl],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 hu(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){ir&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,s=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;let c=new du;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=s,this.context.objectToNode=this.objectToNodeMap;let u=[];for(let l of a){this.context.target=l;let d=Qe().writeBuiltinComponentData(l,this.context);d!==null&&u.push(d)}u.length>0&&(c[Ir]=u,ir&&console.log("DID WRITE",n,"nodeIndex",s,u))}}beforeRoot(){return ir&&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];ir&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let s=t.json.nodes;for(let a=0;a<s.length;a++){let c=await t.getDependency("node",a);this.nodeToObjectMap[a]=c}for(let a=0;a<s.length;a++){let c=s[a],u=a,l=c.extensions;if(!l)continue;let d=l[this.name];if(!d)continue;ir&&console.log("NODE",c);let h=this.nodeToObjectMap[u];if(!h){console.error("Could not find object for node index: "+u,c,t);continue}Do(h),r.push(this.createComponents(h,d))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Ir];if(i){ir&&console.log(e.name,i);for(let n in i){let r=i[n];ir&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await To(this.parser,r),e.userData=e.userData||{},e.userData[Ir]=e.userData[Ir]||[],e.userData[Ir].push(r)}}}};import{EXRLoader as Eb}from"three/examples/jsm/loaders/EXRLoader";var pu=M("debugexr"),al=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",pu&&console.log(e)}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(pu&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],a=new Eb(i.options.manager);return pu&&console.log("EXT_texture_exr.loadTexture",s,a),i.loadTextureImage(e,s.source,a)}};var zp="NEEDLE_gameobject_data",ll=class{get name(){return zp}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[zp];if(r){let s=this.findAndApplyExtensionData(i,r);t.push(s)}}}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.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};import{AmbientLight as Cb,Color as Wp,HemisphereLight as Tb}from"three";var Np="NEEDLE_lighting_settings",Vo=M("debugenvlight"),cl=class{get name(){return Np}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[Np];if(i){Vo&&console.log(i);let n=R.addNewComponent(e.scene,fu,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new Wp().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new Wp().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},fu=class extends k{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)}Vo&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(Vo&&console.log("Enable scene lighting",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),e||Vo&&console.warn("This is no active?!",this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&!this._ambientLightObj&&(this._ambientLightObj=new Cb(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 Tb(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=>{Vo&&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(){Vo&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};import{NeverStencilFunc as Rb,LessStencilFunc as Sb,EqualStencilFunc as Pb,LessEqualStencilFunc as Ob,GreaterStencilFunc as kb,NotEqualStencilFunc as Mb,GreaterEqualStencilFunc as Ib,AlwaysStencilFunc as Db,ZeroStencilOp as Ab,KeepStencilOp as Lb,ReplaceStencilOp as jb,IncrementStencilOp as Hb,DecrementStencilOp as Fb,IncrementWrapStencilOp as Bb,DecrementWrapStencilOp as Ub,InvertStencilOp as Gb}from"three";var mu=M("debugstencil");function Vb(o,e){return(o&1<<e.layer)!=0}var Wr=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(mu&&console.log(t,Wr.stencils),!t)return;let i=Wr.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(Vb(r.layer,e)){mu&&console.log(r);let s=e.sharedMaterial?.clone();s&&(e.sharedMaterial=s,e.gameObject.renderOrder=r.event*1e3+r.index*50,s.stencilWrite=!0,s.stencilWriteMask=255,s.stencilFuncMask=255,s.stencilRef=r.value,s.stencilFunc=r.compareFunc,s.stencilZPass=r.passOp,s.stencilFail=r.failOp,s.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Wb];if(i){mu&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let s={...r};s.compareFunc=zb(s.compareFunc),s.passOp=gu(s.passOp),s.failOp=gu(s.failOp),s.zFailOp=gu(s.zFailOp),Wr.stencils[this.source]||(Wr.stencils[this.source]=[]),Wr.stencils[this.source].push(s)}}}return null}},Nr=Wr;L(Nr,"stencils",{});function gu(o){switch(o){case 0:return Lb;case 1:return Ab;case 2:return jb;case 3:return Hb;case 4:return Fb;case 6:return Bb;case 7:return Ub;case 5:return Gb}return 0}function zb(o){switch(o){case 1:return Rb;case 2:return Sb;case 3:return Pb;case 4:return Ob;case 5:return kb;case 6:return Mb;case 7:return Ib;case 8:return Db}return 0}var Wb="NEEDLE_render_objects";import{TextureLoader as Nb}from"three";import{GLTFLoader as Xb}from"three/examples/jsm/loaders/GLTFLoader";var bu="NEEDLE_deferred_texture",ut=M("debugprogressive"),yu=new Map,vu=!1;ut&&window.addEventListener("keyup",o=>{o.key==="p"&&(yu.forEach((e,t)=>{Object.entries(e).forEach(([i,n])=>{vu?t[i]=n.lod0:t[i]=n.original,t.needsUpdate=!0})}),vu=!vu)});var js=class{static assignTextureLOD(e,t,i,n=0){if(!!i)for(let r of Object.keys(i)){let s=i[r];s?.isTexture===!0&&(ut&&console.log(`-----------
|
|
174
|
+
#endif`);Li.UniformsLib.lightmap.lightmapScaleOffset={value:new Li.Vector4(1,1,0,0)};var ob=M("debugplayerview");var $c=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}},el=class{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new $c(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&&(ob&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}};var ub=M("debugSetup"),db=M("stats"),tl={};var Vt=(a=>(a[a.EarlyUpdate=0]="EarlyUpdate",a[a.Update=1]="Update",a[a.LateUpdate=2]="LateUpdate",a[a.OnBeforeRender=3]="OnBeforeRender",a[a.OnAfterRender=4]="OnAfterRender",a[a.PrePhysicsStep=9]="PrePhysicsStep",a[a.PostPhysicsStep=10]="PostPhysicsStep",a))(Vt||{});function Ra(o,e){if(!o)return;let t=e?.new_scripts??V.Current.new_scripts;t.includes(o)||t.push(o)}var wt=class{static get Current(){return this._current}static set Current(e){this._current=e}name;alias;isManagedExternally=!1;hash;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 isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get xrSession(){return this.renderer.xr?.getSession()}get arOverlayElement(){let e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=-1;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=db?Ap.default():null;constructor(e){if(this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer)this.renderer=e.renderer,this.isManagedExternally=!0;else{let i=M("postfx");this.renderer=new ab({antialias:!0}),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=Re.NoToneMapping,this.renderer.setClearColor(new Re.Color("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Re.PCFSoftShadowMap,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=Re.sRGBEncoding,this.renderer.physicallyCorrectLights=!0,this.composer=i?new lb(this.renderer):null}this.scene=new Re.Scene,this.application=new Ja(this),this.time=new Ia,this.input=new fa(this),this.physics=new Yn(this),this.connection=new Ua(this),this.assets=new Na,this.rendererData=new Ya(this),this.addressables=new Ka(this),this.lightmaps=new $a(this),this.players=new el(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,li(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,s,a,c,u)=>{let l=this._onBeforeRenderListeners[e.uuid];if(!!l)for(let d=0;d<l.length;d++){let h=l[d];h(n,r,s,a,c,u)}};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){await this.physics.createWorld();let i=!0;try{wt.Current=this,e&&await e(this,t)}catch(n){console.error(n),i=!1}if(!!i){this.isManagedExternally||this.domElement.prepend(this.renderer.domElement),jh(this),Lh(this),Cp(this),wt._current=this;for(let n=0;n<this.new_scripts.length;n++){let r=this.new_scripts[n];if(r.gameObject!==void 0&&r.gameObject!==null){r.gameObject.userData===void 0&&(r.gameObject.userData={}),r.gameObject.userData.components===void 0&&(r.gameObject.userData.components=[]);let s=r.gameObject.userData.components;s.includes(r)||s.push(r)}}if(this.post_setup_callbacks)for(let n=0;n<this.post_setup_callbacks.length;n++)wt._current=this,await this.post_setup_callbacks[n](this);if(!this.mainCamera){wt._current=this;let n=null;ci(this.scene,r=>{let s=r;if(s?.isCamera){if(s.tag==="MainCamera")return n=s,!0;n=s}}),n?this.setCurrentCamera(n):console.error("MISSING camera",this)}if(wt._current=this,yn(this),!this.isManagedExternally&&this.composer&&this.mainCamera){let n=new cb(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(n),this.composer.setSize(this.domWidth,this.domHeight)}this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),this.renderer.setAnimationLoop(this.render.bind(this)),ub&&Es(this.scene,!0)}}render(e,t){for(this._currentFrameEvent=-1,this._stats?.begin(),wt._current=this,this.time.update(),yn(this),Po(),ya(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]();this._currentFrameEvent=0;for(let i=0;i<this.scripts_earlyUpdate.length;i++){let n=this.scripts_earlyUpdate[i];!n.activeAndEnabled||n.earlyUpdate!==void 0&&(wt._current=this,n.earlyUpdate())}this.executeCoroutines(0),this._currentFrameEvent=1;for(let i=0;i<this.scripts_update.length;i++){let n=this.scripts_update[i];!n.activeAndEnabled||n.update!==void 0&&(wt._current=this,n.update())}this.executeCoroutines(1),this._currentFrameEvent=2;for(let i=0;i<this.scripts_lateUpdate.length;i++){let n=this.scripts_lateUpdate[i];!n.activeAndEnabled||n.lateUpdate!==void 0&&(wt._current=this,n.lateUpdate())}this.executeCoroutines(2);try{let n=this.time.deltaTime/1;for(let r=0;r<1;r++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.step(n),this._currentFrameEvent=10,this.executeCoroutines(10)}catch(i){console.error(i)}this.physics.postStep(),this._currentFrameEvent=3;for(let i=0;i<this.scripts_onBeforeRender.length;i++){let n=this.scripts_onBeforeRender[i];!n.activeAndEnabled||n.onBeforeRender!==void 0&&(wt._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._currentFrameEvent=-10,this._isRendering=!0,this.renderRequiredTextures(),this.isManagedExternally||(this.composer&&!this.isInXR?this.composer.render():this.mainCamera&&this.renderer.render(this.scene,this.mainCamera)),this._isRendering=!1,this._currentFrameEvent=4;for(let i=0;i<this.scripts_onAfterRender.length;i++){let n=this.scripts_onAfterRender[i];!n.activeAndEnabled||n.onAfterRender!==void 0&&(wt._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._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats?.end()}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new Re.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){let i=new sb(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new Re.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=Re.NearestFilter,this._renderTarget.texture.magFilter=Re.NearestFilter,this._renderTarget.texture.format=Re.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 a=r.chained;if(a&&a.length>0){let d=a[a.length-1].next();if(d.done&&a.pop(),t(d)&&(r.chained||(r.chained=[]),r.chained.push(d.value)),!d.done)continue}let c=r.main.next();if(c.done===!0){i.splice(n,1),--n;continue}let u=c.value;if(t(u)){if(u.next().done)continue;r.chained||(r.chained=[]),r.chained.push(u)}}}function t(i){return!!(i&&i.next&&i.return)}}},V=wt;L(V,"_current");var eu={};nh(eu,{Behaviour:()=>k,Component:()=>Et,GameObject:()=>R});import*as tt from"three";var R=class extends tt.Object3D{guid;static setActive(e,t,i=!0,n=!0){!e||(Oa(e,t,n),Po(e),t&&i&&ya(V.Current,e))}static isActiveSelf(e){return Dr(e)}static isActiveInHierarchy(e){return Kh(e)}static markAsInstancedRendered(e,t){Jh(e,t)}static isUsingInstancing(e){return ka(e)}static foreachComponent(e,t,i=!0){return ci(e,t,i)}static instantiateSynced(e,t){return e?wa(e,t):null}static instantiate(e,t=null){return Lr(e,t)}static destroySynced(e,t,i=!0){if(!e)return;let n=e;t=t??V.Current,Oo(n,t.connection,i)}static destroy(e,t=!0,i=!0){return li(e,t,i)}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=V.Current),t.add(e),Oa(e,!0),Po(e),i?R.foreachComponent(e,n=>{yc(n,i),!n.__internalDidAwakeAndStart&&i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){!e||(e.parent?.remove(e),Oa(e,!1),Po(e),R.foreachComponent(e,t=>{Rh(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 s=r[t];s&&typeof s=="function"&&s.bind(r)(...n)},i)}static addNewComponent(e,t,i=!0){let n=new t;return qn(e,n,i),n}static addComponent(e,t){if(t.gameObject==null)throw new Error("Did you mean to create a new component? Use addNewComponent");Wh(e,t)}static removeComponent(e){return Ca(e.gameObject,e),e}static getOrAddComponent(e,t){return Ta(e,t)}static getComponent(e,t){return e===null?null:jr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:Mo(e,t,i)}static findByGuid(e,t){return Ar(e,t)}static findObjectOfType(e,t,i=!0){return Qh(e,t??V.Current,i)}static findObjectsOfType(e,t){let i=[];return qh(e,i,t),i}static getComponentInChildren(e,t){return Hr(e,t)}static getComponentsInChildren(e,t,i=null){return Io(e,t,i??void 0)}static getComponentInParent(e,t){return ko(e,t)}static getComponentsInParent(e,t,i=null){return Ss(e,t,i)}static getAllComponents(e){return[...e.userData?.components]}static*iterateComponents(e){let t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}},di=class{get isComponent(){return!0}__context;get context(){return this.__context??V.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}get hideFlags(){return this.gameObject?.userData.hideFlags}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;let e=this.gameObject[Ii];return e===void 0?!0:e}set __isActiveInHierarchy(e){!this.gameObject||(this.gameObject[Ii]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=1){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=1){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(){this.__internalNewInstanceCreated()}__internalNewInstanceCreated(){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(){return this.__didEnable?!1:(this.__didEnable=!0,this.onEnable(),this.__isEnabled=!0,!0)}__internalDisable(){!this.__didEnable||(this.__didEnable=!1,this.onDisable(),this.__isEnabled=!1)}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.destroy?.call(this),Nh(this))}get enabled(){return this.__isEnabled??!0}set enabled(e){if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}_worldPosition=void 0;_worldQuaternion=void 0;_worldEuler=void 0;_worldRotation=void 0;get worldPosition(){return this._worldPosition||(this._worldPosition=new tt.Vector3),U(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(e){te(this.gameObject,e)}setWorldPosition(e,t,i){di._worldPositionBuffer.set(e,t,i),this.worldPosition=di._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new tt.Quaternion),he(this.gameObject,this._worldQuaternion)}set worldQuaternion(e){$e(this.gameObject,e)}setWorldQuaternion(e,t,i,n){di._worldQuaternionBuffer.set(e,t,i,n),this.worldQuaternion=di._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new tt.Euler),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(e){this._worldQuaternion||(this._worldQuaternion=new tt.Quaternion),this._worldQuaternion?.setFromEuler(e),this.worldQuaternion=this._worldQuaternion}get worldRotation(){let e=this.worldEuler;this._worldRotation||(this._worldRotation=new tt.Vector3);let t=this._worldRotation;return t.set(e.x,e.y,e.z),t.x=F.toDegrees(t.x),t.y=F.toDegrees(t.y),t.z=F.toDegrees(t.z),t}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){n&&(e=F.toRadians(e),t=F.toRadians(t),i=F.toRadians(i)),di._worldEulerBuffer.set(e,t,i),di._worldQuaternionBuffer.setFromEuler(di._worldEulerBuffer),this.worldQuaternion=di._worldQuaternionBuffer}get forward(){return di._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}},Et=di;L(Et,"_worldPositionBuffer",new tt.Vector3),L(Et,"_worldQuaternionBuffer",new tt.Quaternion),L(Et,"_worldEulerBuffer",new tt.Euler),L(Et,"_tempQuaternionBuffer2",new tt.Quaternion),L(Et,"_forward",new tt.Vector3);var k=class extends Et{};var hi=function(o,e){return function(t,i,n){hb(t,i,n,o,e)}};function hb(o,e,t,i,n){if(!(!n&&!i&&!o.onValidate)){if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Ze("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,2);return}if(o.__internalAwake){let r=Symbol(e),s=o.__internalAwake;o.__internalAwake=function(){this[r]===void 0&&(this[r]=this[e],Object.defineProperty(this,e,{set:function(a){if(this[pa]===!0)this[r]=a;else{i?.call(this,a);let c=this[r];this[r]=a,this.onValidate?.call(this,e,c)}},get:function(){return n?.call(this),this[r]}})),s.call(this)}}}}var Lp=M("debugloadingbar");var Ds=0,jp;function tu(o){Lp&&console.log(o.progress.loaded.toFixed(0)+"/"+o.progress.total.toFixed(0),o);let e=o.count,t=o.progress.total;t===0||t===void 0?(jp!==o.name&&(Ds=0),jp=o.name,Ds+=(1-Ds)*.001,Lp&&vs("Loading "+o.name+" did not report total size")):Ds=o.progress.loaded/t;let i=o.index/e+Ds/e;return F.clamp01(i)}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){console.warn("Custom loading container is not allowed"),this.container.removeChild(i);continue}this._loadingElement=this.createLoadingElement(i);return}}this._loadingElement=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",this.container.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){this._loadingElement?.parentElement||this.onLoadingBegin(t);let i=0;typeof e=="number"?i=e:("index"in e&&(i=tu(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,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=F.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}updateDisplay(){let e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){this._loadingElement=e||document.createElement("div"),e||(this._loadingElement.style.position="fixed",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",this._loadingElement.style.backgroundColor="#000000",this._loadingElement.style.display="flex",this._loadingElement.style.alignItems="center",this._loadingElement.style.justifyContent="center",this._loadingElement.style.zIndex="1000",this._loadingElement.style.flexDirection="column",this._loadingElement.style.pointerEvents="none",this._loadingElement.style.color="white");let t=this._loadingElementOptions?.className??"loading";if(this._loadingElement.classList.add(t),this._loadingElementOptions?.additionalClasses)for(let a of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(a);let i=document.createElement("div"),n=30;i.style.display="flex",i.style.width=n+"%",i.style.height="2px",i.style.background="rgba(255,255,255,.1)",this._loadingElement.appendChild(i),this._loadingBar=document.createElement("div"),i.appendChild(this._loadingBar);let r=function(a){return F.lerp(n*.5,100-n*.5,a)+"%"};this._loadingBar.style.background=`linear-gradient(90deg, #02022B ${r(0)}, #0BA398 ${r(.4)}, #99CC33 ${r(.5)}, #D7DB0A ${r(1)})`,this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",this._loadingTextContainer=document.createElement("div"),this._loadingTextContainer.style.display="flex",this._loadingTextContainer.style.justifyContent="center",this._loadingTextContainer.style.marginTop=".9em",this._loadingElement.appendChild(this._loadingTextContainer);let s=document.createElement("div");return this._messageContainer=s,s.style.display="flex",s.style.fontSize=".8em",s.style.paddingTop=".5em",s.style.color="rgba(255,255,255,.5)",s.style.justifyContent="center",this._loadingElement.appendChild(s),this._loadingElement}};import{DRACOLoader as iu}from"three/examples/jsm/loaders/DRACOLoader.js";import{KTX2Loader as Hp}from"three/examples/jsm/loaders/KTX2Loader.js";var As=M("debugdecoders"),pi,er;function nu(o){o!==void 0&&typeof o=="string"&&(pi||(pi=new iu),As&&console.log("Setting draco decoder path to",o),pi.setDecoderPath(o))}function ru(o){o!==void 0&&typeof o=="string"&&(pi||(pi=new iu),As&&console.log("Setting draco decoder type to",o),pi.setDecoderConfig({type:o}))}function ou(o){o!==void 0&&typeof o=="string"&&(er||(er=new Hp),As&&console.log("Setting ktx2 transcoder path to",o),er.setTranscoderPath(o))}function xn(o,e){pi||(pi=new iu,pi.setDecoderPath("./include/draco/"),pi.setDecoderConfig({type:"js"}),As&&console.log("Setting draco decoder path to","./include/draco/")),er||(er=new Hp,er.setTranscoderPath("./include/ktx2/"),As&&console.log("Setting ktx2 transcoder path to","./include/ktx2/"),e.renderer&&er.detectSupport(e.renderer)),o.setDRACOLoader(pi),o.setKTX2Loader(er)}import{AnimationClip as pb,MathUtils as fb}from"three";var Bo=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 Bp(o,e){return{name:"",isLooping:!1,guid:e?.generateUUID()??fb.generateUUID(),index:-1,clip:new pb(o,1,[])}}import{AnimationClip as mb,AnimationMixer as gb,AxesHelper as bb,Euler as Up,LoopOnce as vb,Quaternion as fi,Vector3 as Ls}from"three";import*as rl from"three";var tr=M("debuganimatorcontroller"),su=M("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 s=this.model.layers[t].stateMachine;for(let a of s.states)if(a.name===e||a.hash===e){tr&&console.log("transition to ",a),this.transitionTo(a,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){tr&&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 gb(this.animator.gameObject),this.createActions(this.animator)}clone(){let e=gs(this.model,(i,n,r)=>r==null?!0:r.type==="Object3D"||r.isObject3D===!0?!1:Ch(r)?(console.log(r),!1):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,tr&&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()&&(tr&&console.debug("REMOVE",t.name,n.getEffectiveWeight(),n.isRunning(),n.isScheduled()),this._activeStates.splice(e,1),e--)}}}setStartTransition(){for(let e of this.model.layers){let t=e.stateMachine,i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset)}}evaluateTransitions(){let t=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;t=!0}let i=this._activeState,n=i.motion.action,r=0;for(let a of i.transitions){if(++r,!a.hasExitTime&&a.conditions.length<=0)continue;let c=!0;for(let u of a.conditions)if(!this.evaluateCondition(u)){c=!1;break}if(!!c){for(let u of a.conditions){let l=this.model.parameters.find(d=>d.name===u.parameter);l?.type===9&&(l.value=!1)}if(n){let u=i.motion.clip.duration,l=u<=0?1:n.time/u;if(a.hasExitTime?l>=a.exitTime:!0){n.clampWhenFinished=!0,tr&&console.log("transition to "+a.destinationState,a,l,a.exitTime,a.hasExitTime),this.transitionTo(a.destinationState,a.duration,a.offset);return}}else{this.transitionTo(a.destinationState,a.duration,a.offset);return}}}let s=!1;if(i.motion.isLooping&&n&&n.time>=n.getClip().duration&&(s=!0,n.reset(),n.time=0,n.play()),!s&&i&&!t&&n&&this.animator&&i.behaviours){let a=n?.getClip().duration,c=n.time/a,u=new Bo(this._activeState,c,a,this._speed);for(let l of i.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,u,0)}}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState),e=this.model.layers[t].stateMachine.states[e]),e}transitionTo(e,t,i){if(!this.animator)return;let n=0;if(e=this.getState(e,n),!e?.motion||!e.motion.clip)return;let r=this._activeState===e;if(r){let u=e.motion;!u.action_loopback&&u.clip&&(this._mixer.uncacheAction(u.clip,this.animator.gameObject),u.action_loopback=this.createAction(u.clip))}if(this._activeState?.behaviours&&this._activeState.motion.action){let u=this._activeState?.motion.clip.duration,l=this._activeState.motion.action.time/u,d=new Bo(this._activeState,l,u,this._speed);for(let h of this._activeState.behaviours)h.instance?.onStateExit?.call(h.instance,this.animator,d,n)}let s=this._activeState?.motion.action;s&&s.fadeOut(t),r&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=s);let a=this._activeState;this._activeState=e;let c=e.motion?.action;if(c){i=Math.max(0,Math.min(1,i)),c.isRunning()&&c.stop(),c.reset(),c.timeScale=this._speed,c.enabled=!0;let u=e.motion.clip.duration;if(c.time=i*u,c.clampWhenFinished=!0,c.setLoop(vb,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 Bo(e,i,u,this._speed);for(let d of this._activeState.behaviours)d.instance?.onStateEnter?.call(d.instance,this.animator,l,n)}}else console.warn("No action",e.motion,this);tr&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,s,c,c?.getEffectiveTimeScale(),c?.getEffectiveWeight(),c?.isRunning(),c?.isScheduled(),c?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new au(this));let i=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,i,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=Bp(r.name)),this.animator&&r.motion.clips){let s=r.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r.motion.clip=s?.clip}if(!r.motion.clip){let s=new mb;r.motion.clip=s}if(r.motion?.clip){let s=r.motion.clip,a=this.createAction(s);r.motion.action=a}if(r.behaviours&&Array.isArray(r.behaviours))for(let s of r.behaviours){if(!s?.typeName)continue;let a=O.get(s.typeName),c=new a;c.isStateMachineBehaviour&&(c._context=this.context??void 0,oi(c,s.properties),s.instance=c),tr&&console.log("Created animator controller behaviour",r.name,s.typeName,s.properties,c)}}}}*enumerateActions(){for(let e of this.model.layers){let t=e.stateMachine;for(let 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},nl=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 s=this.originalEvaluate(r);return t(r,s)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}evaluate(e){this.customEvaluate&&this.customEvaluate(e)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}},we=class{set action(e){this._action=e}get action(){return this._action}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new Ls;rotationChange=new fi;constructor(e,t,i,n,r){if(this.context=e,this.root=t,this.clip=i,we.firstKeyframeRotation[i.uuid]||(we.firstKeyframeRotation[i.uuid]=new rl.Quaternion),r){let s=r.values;we.firstKeyframeRotation[i.uuid].set(s[0],s[1],s[2],s[3])}we.spaceRotation[i.uuid]||(we.spaceRotation[i.uuid]=new fi),we.effectiveSpaceRotation[i.uuid]||(we.effectiveSpaceRotation[i.uuid]=new fi),we.clipOffsetRotation[i.uuid]=new fi,r&&we.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=we.lastObjRotation[this.root.uuid];we.spaceRotation[this.clip.uuid].copy(t);{let i=new rl.Euler().setFromQuaternion(t);console.log("START",this.clip.name,F.toDegrees(i.y))}}getClipRotationOffset(){return we.clipOffsetRotation[this.clip.uuid]}handlePosition(e,t){if(t){let i=this.root;su&&i.add(new bb),we.lastObjPosition[i.uuid]||(we.lastObjPosition[i.uuid]=new Ls);let n=new Ls,r=new Ls,s=0;this.positionWrapper=new nl(t,(a,c)=>{let u=this.action.getEffectiveWeight();if(su&&i.position.length()>8&&i.position.set(0,i.position.y,0),a>s){n.set(c[0],c[1],c[2]),n.sub(r),n.multiplyScalar(u),n.applyQuaternion(this.getClipRotationOffset());let l=this.clip.uuid;n.applyQuaternion(we.spaceRotation[l]),this.positionChange.copy(n)}return r.fromArray(c),s=a,c[0]=0,c[1]=0,c[2]=0,c})}}handleRotation(e,t){if(t){if(su){let a=t.values,c=new Up().setFromQuaternion(new fi(a[0],a[1],a[2],a[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",F.toDegrees(c.y));let u=t.values.length-4,l=new fi().set(a[u],a[u+1],a[u+2],a[u+3]),d=new Up().setFromQuaternion(l);console.log(e.name,t.name,"LAST ROTATION IN TRACK",F.toDegrees(d.y))}let i=this.root;we.lastObjRotation[i.uuid]||(we.lastObjRotation[i.uuid]=new fi);let n=0,r=new fi,s=new fi;this.rotationWrapper=new nl(t,(a,c)=>(a>n&&(s.set(c[0],c[1],c[2],c[3]),r.invert(),s.multiply(r),this.rotationChange.copy(s)),r.fromArray(c),n=a,c[0]=0,c[1]=0,c[2]=0,c[3]=1,c))}}onBeforeUpdate(){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(){let e=this.action.getEffectiveWeight();this.positionChange.multiplyScalar(e),this.rotationChange.slerp(we.identityQuaternion,1-e)}},mi=we;L(mi,"lastObjPosition",{}),L(mi,"lastObjRotation",{}),L(mi,"firstKeyframeRotation",{}),L(mi,"spaceRotation",{}),L(mi,"effectiveSpaceRotation",{}),L(mi,"clipOffsetRotation",{}),L(mi,"identityQuaternion",new fi);var au=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"),s=this.findRootTrack(i,".quaternion"),a=new mi(this.controller.context,t,i,r,s);this.handler.push(a);let c=e.clipAction(i);return a.action=c,c}onStart(e){for(let t of this.handler)t.onStart(e)}onBeforeUpdate(){for(let e of this.handler)e.onBeforeUpdate()}summedPosition=new Ls;summedRotation=new fi;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),mi.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 x=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=Gp(o);else for(let e=0;e<o.length;e++){let t=o[e];o[e]=Gp(t)}return function(e,t){Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});let i=e.$serializedTypes=e.$serializedTypes||{};i[t]=o}};function Gp(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}var yb=M("debuganimator"),Ye=class extends k{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=F.lerp(e.x,e.y,Math.random())}set minMaxOffsetNormalized(e){this.normalizedStartOffset=F.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}yb&&console.log("ANIMATOR",this.name,this)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.Reset()}onBeforeRender(){this._animatorController&&this._animatorController.update()}};E([x()],Ye.prototype,"applyRootMotion",2),E([x()],Ye.prototype,"hasRootMotion",2),E([x()],Ye.prototype,"keepAnimatorControllerStateOnDisable",2),E([x()],Ye.prototype,"runtimeAnimatorController",1);import*as zr from"three";var lu=M("debuganimation"),Wt=class extends k{playAutomatically=!0;randomStartTime=!0;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){lu&&console.log("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}!e||(lu&&console.log("Assign clip",e,Boolean(this.gameObject)),this.gameObject.animations||(this.gameObject.animations=[]),this.gameObject.animations.push(e))}set animations(e){lu&&console.log("assign 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&&oe.markDirty(this.gameObject)}}getAction(e){return this.actions?.find(t=>t.getClip().name===e)}get isPlaying(){for(let e=0;e<this._currentActions.length;e++)if(this._currentActions[e].isRunning())return!0;return!1}play(e,t){if(this.init(),!this.mixer)return;e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length)return;i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(r=>r.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={}),t.minMaxOffsetNormalized||(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed||(t.minMaxSpeed=this.minMaxSpeed),t.loop||(t.loop=this.loop),t.clampWhenFinished||(t.clampWhenFinished=this.clampWhenFinished);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 a=this.tryFindHandle(e);if(a)return a.getPromise()}let n=t?.exclusive??!0;t?.fadeDuration?(n&&i?.fadeOut(t.fadeDuration),e.fadeIn(t.fadeDuration)):n&&i?.stop(),e.reset(),e.enabled=!0,e.time=0,e.timeScale=1;let r=e.getClip();t?.minMaxOffsetNormalized&&(e.time=F.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.duration),t?.minMaxSpeed&&(e.timeScale=F.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random())),t?.clampWhenFinished&&(e.clampWhenFinished=!0),t?.startTime!==void 0&&(e.time=t.startTime),t?.loop!==void 0?e.loop=t.loop?zr.LoopRepeat:zr.LoopOnce:e.loop=zr.LoopOnce,e.play();let s=new cu(e,this.mixer,t,a=>{this._handles.splice(this._handles.indexOf(s),1)});return this._handles.push(s),s.getPromise()}tryFindHandle(e){for(let t of this._handles)if(t.action===e)return t}_didInit=!1;init(){if(!this._didInit&&(this._didInit=!0,!!this.gameObject)){this.actions=[],this.mixer=new zr.AnimationMixer(this.gameObject);for(let e=0;e<this.animations.length;e++){let t=this.mixer.clipAction(this.animations[e]);this.actions.push(t)}}}};E([x()],Wt.prototype,"playAutomatically",2),E([x()],Wt.prototype,"randomStartTime",2),E([x()],Wt.prototype,"loop",2),E([x()],Wt.prototype,"clampWhenFinished",2);var cu=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 om}from"three/examples/jsm/loaders/GLTFLoader.js";import*as Q from"three";import{RawShaderMaterial as xb}from"three";var wn=M("debugshaders"),Uo="NEEDLE_techniques_webgl";var uu=class{objectToWorldMatrix=new Q.Matrix4;worldToObjectMatrix=new Q.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Ms(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Ms(this.worldToObjectMatrix,this.worldToObject)}};var ce=class extends xb{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){let e=super.clone();return Vp(e),e}constructor(e,...t){super(...t),this.identifier=e,wn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName]&&this.waitForLighting(),(this.depthTextureUniform||this.opaqueTextureUniform)&&V.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();let e=V.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&V.Current.pre_render_callbacks.splice(e,1)}async waitForLighting(){let e=V.Current;if(!e){console.error("Missing context");return}let t=await e.rendererData.getSceneLightingData(this.identifier);if(!t||!t.array){console.warn("Missing lighting data for custom shader, getSceneLightingData did not return anything");return}wn&&console.log(t);let i=t.array,n=t.texture;this.uniforms.unity_SpecCube0={value:n},qc(this.uniforms,i);let r=Math.sqrt(Math.PI*.5);this.uniforms.unity_SpecCube0_HDR={value:new Q.Vector4(r,r,r,r)},wn&&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 uu;get depthTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(!!this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&V.Current.setRequireColor(!0),this.depthTextureUniform&&V.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,r,s){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,r)}onUpdateUniforms(e,t){let i=V.Current;e&&(ce.viewProjection&&this.uniforms[this._viewProjectionName]&&(ce.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Ms(ce.viewProjection,ce._viewProjectionValues)),ce.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ce.viewMatrix.copy(e.matrixWorldInverse),Ms(ce.viewMatrix,ce._viewMatrixValues)),this.uniforms[ce._worldSpaceCameraPosName]&&ce._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters?this.uniforms._TimeParameters.value=i.rendererData.timeVec4:this.uniforms._Time&&(this.uniforms._Time.value=i.rendererData.timeVec4);let n=i.mainLight;if(n){let a=U(n.gameObject,ce._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ce._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ce._mainLightColor};let c=n.intensity;ce._lightData.z=c,this.uniforms.unity_LightData={value:ce._lightData}}if(e&&(ce.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ce._viewProjectionValues),ce.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ce._viewMatrixValues),this.uniforms[ce._worldSpaceCameraPosName]&&(this.uniforms[ce._worldSpaceCameraPosName]={value:ce._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){let a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){let a=this.uniforms._ZBufferParams.value,c=i.mainCameraComponent;a.x=1-c.farClipPlane/c.nearClipPlane,a.y=c.farClipPlane/c.nearClipPlane,a.z=a.x/c.farClipPlane,a.w=a.y/c.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){let a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}}let r=this.depthTextureUniform;r&&(r.value=i.depthTexture);let s=this.opaqueTextureUniform;if(s&&(s.value=i.opaqueColorTexture),t){let a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}},Nt=ce;L(Nt,"viewProjection",new Q.Matrix4),L(Nt,"_viewProjectionValues",[]),L(Nt,"viewMatrix",new Q.Matrix4),L(Nt,"_viewMatrixValues",[]),L(Nt,"_worldSpaceCameraPosName","_WorldSpaceCameraPos"),L(Nt,"_worldSpaceCameraPos",new Q.Vector3),L(Nt,"_mainLightColor",new Q.Vector4),L(Nt,"_mainLightPosition",new Q.Vector3),L(Nt,"_lightData",new Q.Vector4);var ol=class{get name(){return Uo}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){let t=this.parser.json.materials[e];if(!t)return wn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Uo])return wn&&console.log("material "+e+" does not use NEEDLE_techniques_webgl"),null;let i=t.extensions[Uo].technique;if(i<0)return null;let n=this.parser.json.extensions[Uo];if(!n)return null;wn&&console.log(n);let r=n.techniques[i];return r?new Promise(async(s,a)=>{let c=await Mp(n,r.program),u=c?.fragmentShader,l=c?.vertexShader;if(!u||!l)return a();wn&&console.log("loadMaterial",t,c);let d={},h=r.uniforms;l.includes("_Time")&&(d._Time={value:new Q.Vector4(0,0,0,0)});for(let f in h){let m=f;switch(m){case"_TimeParameters":let p=new Q.Vector4;d[m]={value:p};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":d[m]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":d[m]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":d[m]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":d[m]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":d[m]={value:null};break}}let b=!1;if(t.extensions&&t.extensions[Uo]){let f=t.extensions[Uo];if(f.technique===i){wn&&console.log(t.name,"Material Properties",f);for(let m in f.values){let p=f.values[m];if(typeof p=="string"){if(p.startsWith("/textures/")){let g=p.substring(10),w=Number.parseInt(g);if(w>=0){let C=await this.parser.getDependency("texture",w);C&&(C.encoding=Q.LinearEncoding,C.needsUpdate=!0),d[m]={value:C};continue}}switch(m){case"alphaMode":p==="BLEND"&&(b=!0);continue}}if(Array.isArray(p)&&p.length===4){d[m]={value:new Q.Vector4(p[0],p[1],p[2],p[3])};continue}d[m]={value:p}}}}let _=new Nt(this.identifier,{name:t.name??"",uniforms:d,vertexShader:l,fragmentShader:u,lights:!1});switch(d._Cull?.value){case 0:_.side=Q.DoubleSide;break;case 1:_.side=Q.BackSide;break;case 2:_.side=Q.FrontSide;break;default:_.side=Q.FrontSide;break}switch(d._ZTest?.value){case 3:_.depthTest=!0,_.depthFunc=Q.EqualDepth;break;case 6:_.depthTest=!0,_.depthFunc=Q.NotEqualDepth;break;case 2:_.depthTest=!0,_.depthFunc=Q.LessDepth;break;case 4:_.depthTest=!0,_.depthFunc=Q.LessEqualDepth;break;case 5:_.depthTest=!0,_.depthFunc=Q.GreaterDepth;break;case 7:_.depthTest=!0,_.depthFunc=Q.GreaterEqualDepth;break;case 8:_.depthTest=!1,_.depthFunc=Q.AlwaysDepth;break}_.transparent=b,b&&(_.depthWrite=!1),qc(d),_.onUpdateUniforms();for(let f in h){let m=f,p=h[f].type;if(d[m]?.value===void 0)switch(p){case 35678:d[m]={value:Op},console.warn("Missing/unassigned texture, fallback to white: "+m);break;default:console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+m,h[f]);break}}wn&&console.log(_.uuid,d),Vp(_),s(_)}):null}};function Vp(o){if(o.uniforms)for(let e in o.uniforms)Object.getOwnPropertyDescriptor(o,e)||Object.defineProperty(o,e,{get:()=>o.uniforms[e].value,set:t=>{o.uniforms[e].value=t,o.needsUpdate=!0}})}var ir=Te,sl="$___Export_Components",wb="NEEDLE_components",du=class{[Ir]},hu=class{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}},Go=class{get name(){return wb}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[sl]=i)}afterSerializeUserData(e,t){if(e.type==="Scene"&&ir&&console.log("DONE",JSON.stringify(t)),e[sl]===void 0)return;let i=e[sl];delete e[sl],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 hu(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){ir&&console.log("AFTER",e);for(let t in this.exportContext){let i=this.exportContext[t],n=i.node,r=i.nodeDef,s=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;let c=new du;r.extensions=r.extensions||{},r.extensions[this.name]=c,this.context.object=n,this.context.nodeId=s,this.context.objectToNode=this.objectToNodeMap;let u=[];for(let l of a){this.context.target=l;let d=Qe().writeBuiltinComponentData(l,this.context);d!==null&&u.push(d)}u.length>0&&(c[Ir]=u,ir&&console.log("DID WRITE",n,"nodeIndex",s,u))}}beforeRoot(){return ir&&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];ir&&console.log("After root",e,this.parser,i);let r=[];if(n===!0){let s=t.json.nodes;for(let a=0;a<s.length;a++){let c=await t.getDependency("node",a);this.nodeToObjectMap[a]=c}for(let a=0;a<s.length;a++){let c=s[a],u=a,l=c.extensions;if(!l)continue;let d=l[this.name];if(!d)continue;ir&&console.log("NODE",c);let h=this.nodeToObjectMap[u];if(!h){console.error("Could not find object for node index: "+u,c,t);continue}Do(h),r.push(this.createComponents(h,d))}}await Promise.all(r)}async createComponents(e,t){if(!t)return;let i=t[Ir];if(i){ir&&console.log(e.name,i);for(let n in i){let r=i[n];ir&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&await To(this.parser,r),e.userData=e.userData||{},e.userData[Ir]=e.userData[Ir]||[],e.userData[Ir].push(r)}}}};import{EXRLoader as Eb}from"three/examples/jsm/loaders/EXRLoader";var pu=M("debugexr"),al=class{constructor(e){this.parser=e,this.name="EXT_texture_exr",pu&&console.log(e)}loadTexture(e){let t=this.name,i=this.parser,r=i.json.textures[e];if(pu&&console.log("EXT_texture_exr.loadTexture",e,r),!r.extensions||!r.extensions[t])return null;let s=r.extensions[t],a=new Eb(i.options.manager);return pu&&console.log("EXT_texture_exr.loadTexture",s,a),i.loadTextureImage(e,s.source,a)}};var zp="NEEDLE_gameobject_data",ll=class{get name(){return zp}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[zp];if(r){let s=this.findAndApplyExtensionData(i,r);t.push(s)}}}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.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag,e.userData.hideFlags=t.hideFlags,e.userData.static=t.static,e.visible=t.activeSelf,e.guid=t.guid}};import{AmbientLight as Cb,Color as Wp,HemisphereLight as Tb}from"three";var Np="NEEDLE_lighting_settings",Vo=M("debugenvlight"),cl=class{get name(){return Np}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[Np];if(i){Vo&&console.log(i);let n=R.addNewComponent(e.scene,fu,!1);n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new Wp().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(r=>new Wp().fromArray(r))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource,this.context&&this.context.rendererData.registerSceneLightSettings(n)}}return null}},fu=class extends k{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)}Vo&&window.addEventListener("keydown",e=>{switch(e.key){case"l":this.enabled=!this.enabled;break}})}onEnable(){let e=this.context.mainCameraComponent?.sourceId===this.sourceId;if(Vo&&console.log("Enable scene lighting",this.sourceId,e,this,this.context.mainCameraComponent?.sourceId),e||Vo&&console.warn("This is no active?!",this.context.mainCameraComponent?.sourceId),this.ambientMode==3)this.ambientLight&&!this._ambientLightObj&&(this._ambientLightObj=new Cb(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 Tb(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=>{Vo&&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(){Vo&&console.log("disable",this.sourceId,this),this._lightProbeObj&&this._lightProbeObj.removeFromParent(),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this.sourceId&&this.context.rendererData.disableReflection()}};import{NeverStencilFunc as Rb,LessStencilFunc as Sb,EqualStencilFunc as Pb,LessEqualStencilFunc as Ob,GreaterStencilFunc as kb,NotEqualStencilFunc as Mb,GreaterEqualStencilFunc as Ib,AlwaysStencilFunc as Db,ZeroStencilOp as Ab,KeepStencilOp as Lb,ReplaceStencilOp as jb,IncrementStencilOp as Hb,DecrementStencilOp as Fb,IncrementWrapStencilOp as Bb,DecrementWrapStencilOp as Ub,InvertStencilOp as Gb}from"three";var mu=M("debugstencil");function Vb(o,e){return(o&1<<e.layer)!=0}var Wr=class{static applyStencil(e){if(!e)return;let t=e.sourceId;if(mu&&console.log(t,Wr.stencils),!t)return;let i=Wr.stencils[t];if(!!i)for(let n=i.length-1;n>=0;n--){let r=i[n];if(Vb(r.layer,e)){mu&&console.log(r);let s=e.sharedMaterial?.clone();s&&(e.sharedMaterial=s,e.gameObject.renderOrder=r.event*1e3+r.index*50,s.stencilWrite=!0,s.stencilWriteMask=255,s.stencilFuncMask=255,s.stencilRef=r.value,s.stencilFunc=r.compareFunc,s.stencilZPass=r.passOp,s.stencilFail=r.failOp,s.stencilZFail=r.zFailOp);break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){let t=this.parser.json.extensions;if(t){let i=t[Wb];if(i){mu&&console.log(i);let n=i.stencil;if(n&&Array.isArray(n))for(let r of n){let s={...r};s.compareFunc=zb(s.compareFunc),s.passOp=gu(s.passOp),s.failOp=gu(s.failOp),s.zFailOp=gu(s.zFailOp),Wr.stencils[this.source]||(Wr.stencils[this.source]=[]),Wr.stencils[this.source].push(s)}}}return null}},Nr=Wr;L(Nr,"stencils",{});function gu(o){switch(o){case 0:return Lb;case 1:return Ab;case 2:return jb;case 3:return Hb;case 4:return Fb;case 6:return Bb;case 7:return Ub;case 5:return Gb}return 0}function zb(o){switch(o){case 1:return Rb;case 2:return Sb;case 3:return Pb;case 4:return Ob;case 5:return kb;case 6:return Mb;case 7:return Ib;case 8:return Db}return 0}var Wb="NEEDLE_render_objects";import{TextureLoader as Nb}from"three";import{GLTFLoader as Xb}from"three/examples/jsm/loaders/GLTFLoader";var bu="NEEDLE_deferred_texture",ut=M("debugprogressive"),yu=new Map,vu=!1;ut&&window.addEventListener("keyup",o=>{o.key==="p"&&(yu.forEach((e,t)=>{Object.entries(e).forEach(([i,n])=>{vu?t[i]=n.lod0:t[i]=n.original,t.needsUpdate=!0})}),vu=!vu)});var js=class{static assignTextureLOD(e,t,i,n=0){if(!!i)for(let r of Object.keys(i)){let s=i[r];s?.isTexture===!0&&(ut&&console.log(`-----------
|
|
175
175
|
`,"FIND",i.name,r,s?.name,s?.userData,s),js.getOrLoadTexture(e,t,i,r,s,n).then(a=>{if(a?.isTexture===!0&&(a.needsUpdate=!0,ut&&console.log("Assign LOD",i.name,r,a.name,a.guid,i,"Prev:",s,"Now:",a,`
|
|
176
|
-
--------------`),i[r]=a,i.needsUpdate=!0,ut)){let c=yu.get(i);c||(c={},yu.set(i,c));let u=c[r];u||(u=c[r]={original:s,lod0:a}),u.lod0=a}}))}}get name(){return bu}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return ut&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[bu];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(s=>{ut&&console.log("register texture",s.name,s.uuid,n),s.userData.deferred=n,js.cache.set(s.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r,s){let a=r.uuid,c=js.cache.get(a);if(c){ut&&console.log(a,c.uri,c.guid);let u=Oi(t,c.uri);if(u.endsWith(".glb")||u.endsWith(".gltf")){if(!c.guid)return console.warn("missing pointer for glb/gltf texture",c),null;let l=u+"_"+c.guid;if(this.resolved[l])return ut&&console.log("Texture has already been loaded: "+l,i.name,n,r.name),this.resolved[l];let d=new Xb;_n(d,e),ut&&console.log("Load "+u,i.name,n,c.guid);let h=await d.loadAsync(u),b=h.parser;ut&&console.log("Loading finished "+u,i.name,n,c.guid);let _=-1,v=!1;for(let f of h.parser.json.textures)if(_++,f?.extensions){let m=f?.extensions[bu];if(m?.guid&&m.guid===c.guid){v=!0;break}}if(!v)return null;let y=await b.getDependency("texture",_);return y&&(y.guid=c.guid),this.resolved[l]=y,ut&&console.log(i.name,n,'change "'+r.name+'" \u2192 "'+y.name+'"',u,_,y,i,l),y}else{ut&&console.log("Load texture from uri: "+u);let d=await new Nb().loadAsync(u);return d&&ut?console.log(c,d):console.warn("failed loading",u),d}}else ut&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},wn=js;L(wn,"cache",new Map),L(wn,"resolved",{});function xu(o){let e=new Go;return o.register(t=>(e.parser=t,e)),e}var _u=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 wu(o,e,t){o.register(n=>new ll(n)),o.register(n=>new ca(n)),o.register(n=>new Za(n,e.lightmaps,t)),o.register(n=>new cl(n,t,e)),o.register(n=>new ol(n,t)),o.register(n=>new Nr(n,t)),o.register(n=>new wn(n,t,e)),o.register(n=>new al(n));let i=o.setAnimationPointerResolver;typeof i=="function"&&i.bind(o)(new _u)}import{Vector3 as Qb}from"three";var En=class extends k{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new Qb}update(){if(!this.from||!this.to)return;let e=U(this.from).clone(),t=U(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),te(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(U(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};E([w(R)],En.prototype,"from",2),E([w(R)],En.prototype,"to",2);var Li=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};E([w()],Li.prototype,"time",2),E([w()],Li.prototype,"value",2),E([w()],Li.prototype,"inTangent",2),E([w()],Li.prototype,"inWeight",2),E([w()],Li.prototype,"outTangent",2),E([w()],Li.prototype,"outWeight",2),E([w()],Li.prototype,"weightedMode",2);var Xt=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;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){let i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){let r=this.keys[t+1];if(r.time<e)continue;let s=F.remap(e,i.time,r.time,0,1);return F.lerp(i.value,r.value,s)}else return i.value}return this.keys[this.keys.length-1].value}};E([w(Li)],Xt.prototype,"keys",2);import*as Xp from"three";import*as Hs from"three";import{PositionalAudioHelper as qb}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var dt=M("debugaudio");var Oe=class extends k{static get userInteractionRegistered(){return Oe._didCallBeginWaitForUserInteraction||(Oe._didCallBeginWaitForUserInteraction=!0,Oe._beginWaitForUserInteraction()),Oe._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Oe._didCallBeginWaitForUserInteraction||(Oe._didCallBeginWaitForUserInteraction=!0,Oe._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Oe._userInteractionRegistered){Oe._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&&(dt&&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&&Oe._userInteractionRegistered){let e=R.getComponent(this.context.mainCamera,Qt)??R.findObjectOfType(Qt,this.context);e?.listener&&(this.sound=new Hs.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new Hs.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&&Oe._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Oe._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Oe._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){dt&&console.log("audio buffer loaded"),Oe.registerWaitForAllowAudio(()=>{dt&&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(),dt&&console.log(this.name,this.shouldPlay,Oe.userInteractionRegistered,this),this.shouldPlay&&Oe._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(dt&&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?dt&&!this.helper&&(this.helper=new qb(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(dt&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new Hs.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){dt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,dt&&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,dt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){dt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){dt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,dt&&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,dt&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},ie=Oe;L(ie,"_didCallBeginWaitForUserInteraction",!1),L(ie,"callbacks",[]),L(ie,"_userInteractionRegistered",!1),E([w()],ie.prototype,"clip",2),E([w()],ie.prototype,"playOnAwake",2),E([w()],ie.prototype,"loop",1),E([w()],ie.prototype,"spatialBlend",1),E([w()],ie.prototype,"minDistance",1),E([w()],ie.prototype,"maxDistance",1),E([w()],ie.prototype,"volume",1),E([w()],ie.prototype,"rollOffMode",2);import*as Cn from"three";import{Color as Yb}from"three";var $=class extends Yb{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=F.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){let n=e,r=t;return n.alpha&&r.alpha&&(this.alpha=F.lerp(n.alpha,r.alpha,i)),super.lerpColors(e,t,i)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as Jb}from"three";var ul=M("debugcam"),ae=class extends k{get isCamera(){return!0}get aspect(){return this._cam instanceof Jb?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 Cn.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;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;_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()}e.alpha===void 0&&(this._backgroundColor.alpha=1),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(){ul&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?(t=this.gameObject,t?.layers.enableAll()):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 Cn.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new Cn.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(ul&&Ze("apply Camera clear flags"),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;ul&&Ze("Environment blend mode: "+t+" on "+navigator.userAgent);let i=t==="additive"||t==="alpha-blend";if(this.context.xrSessionMode==="immersive-ar"&&t==="opaque"){if(navigator.userAgent?.includes("OculusBrowser"))return!0;if(navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))return!0}return i}enableSkybox(){this._skybox||(this._skybox=new Eu(this)),this._skybox.enable()}};E([w()],ae.prototype,"fieldOfView",1),E([w()],ae.prototype,"nearClipPlane",1),E([w()],ae.prototype,"farClipPlane",1),E([w()],ae.prototype,"clearFlags",1),E([w()],ae.prototype,"orthographic",2),E([w()],ae.prototype,"orthographicSize",2),E([w()],ae.prototype,"ARBackgroundAlpha",2),E([w()],ae.prototype,"cullingMask",1),E([w($)],ae.prototype,"backgroundColor",1);var Eu=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?(ul&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Cn.sRGBEncoding,this._skybox.mapping=Cn.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};var Qt=class extends k{get listener(){return this._listener==null&&(this._listener=new Xp.AudioListener),this._listener}_listener=null;awake(){ie.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=R.getComponentInParent(this.gameObject,ae);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as Zb}from"three/examples/jsm/loaders/GLTFLoader";import*as dl from"three";var Fs=M("debugavatar"),nr=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))}},Tn=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new Ge;i=R.instantiate(Nn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(Fs&&console.log("[Custom Avatar] valid config",t,Fs?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Fs?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(Fs&&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 a=await n.blob();a&&(r=await a.arrayBuffer())}return!r&&(r=await Va(t,t,0,"no url here go away",!0),!r)?null:(await Qe().parseSync(e,r,null,0))?.scene??null}let i=new Zb;return _n(i,e),new Promise((n,r)=>{let s=this.avatarRegistryUrl+"/"+t;i.load(s,async a=>{await Qe().createBuiltinComponents(e,s,a,null,void 0),n(a.scene)},a=>{Fs&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),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"]),s=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;let c=new dl.Vector3;new dl.Box3().setFromObject(n).getSize(c);let u=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+u+" meters! Should be < 0.3m"),u>.3&&n.scale.multiplyScalar(1/u*.3)}return new nr(t,n,r,s)}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 s=this.findAvatarPart(r,t);if(s)return s}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as $b}from"three";var ji=class extends k{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!ki)return;this._axes||(this._axes=new $b(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)}};E([w()],ji.prototype,"length",2),E([w()],ji.prototype,"depthTest",2),E([w()],ji.prototype,"isGizmo",2);import*as Qp from"three";var Xr=class extends k{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=U(this.to).clone(),t=U(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let s=U(this.hint).clone();s.sub(r);let a=new Qp.Vector3;a.crossVectors(s,n),a.crossVectors(n,a),a.normalize();let c=i*.5,u=Math.max(this.desiredDistance,c),l=Math.sqrt(u*u-c*c),d=a.clone();d.multiplyScalar(l),d.add(r),te(this.gameObject,d);let h=r.clone();h.sub(a),this.gameObject.lookAt(h)}};import*as Qr from"three";var ev=M("gizmos"),tv=M("debugboxhelper"),qt=class extends k{box=null;_lastMatrixUpdateFrame=-1;isInBox(e,t){if(!e)return;if(this.box||(this.box=new Qr.Box3),e.type==="Mesh")qt.testBox.setFromObject(e);else if(e.type==="Group"){if(qt.testBox.makeEmpty(),e.children.length>0)for(let n=0;n<e.children.length;n++)e.children[n].type==="Mesh"&&qt.testBox.expandByObject(e)}else{let n=U(e,qt._position),r=Fe(e,qt._size);t!==void 0&&r.multiplyScalar(t),qt.testBox.setFromCenterAndSize(n,r)}this.updateBox();let i=this.box?.intersectsBox(qt.testBox);return i&&tv&&Ur.DrawBox3(qt.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new Qr.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){let t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;let i=t,n=U(this.gameObject,qt._position,i),r=Fe(this.gameObject,qt._size);this.box.setFromCenterAndSize(n,r)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!ev&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Ma(e),this.gameObject.add(this._helper)}}},ke=qt;L(ke,"testBox",new Qr.Box3),L(ke,"_position",new Qr.Vector3),L(ke,"_size",new Qr.Vector3(.01,.01,.01));import{Quaternion as lv,Ray as cv,Vector3 as qr}from"three";import*as qp from"three";var gi=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)}}},iv=o=>/^[A-Z]*$/.test(o),rr=class extends Event{args},ye=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&&iv(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 rr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new gi(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}};import{Color as nv,Object3D as rv}from"three";var Tu=class extends mn{constructor(){super([nv,$])}onDeserialize(e){if(e!=null)return e.a!==void 0?new $(e.r,e.g,e.b,e.a):e.alpha!==void 0?new $(e.r,e.g,e.b,e.alpha):new qp.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}}},AS=new Tu,Ru=class extends mn{constructor(){super(rv)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return Te&&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 Te&&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=R.findByGuid(e.guid,n)),i||(i=R.findByGuid(e.guid,t.context.scene)),i?Te&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},ov=new Ru,Su=class extends mn{constructor(){super([Et,k])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Te&&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=R.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],s=this.findObjectForGuid(e,r);if(s)return s}}},Cu=new Su,Pu=class extends mn{constructor(){super([ye])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){Te&&console.log("DESERIALIZE EVENT",e);let i=new Array;if(e.calls&&Array.isArray(e.calls))for(let s of e.calls){Te&&console.log(s);let a=Cu.findObjectForGuid(s.target,t.root);!a&&t.context?.scene&&(a=Cu.findObjectForGuid(s.target,t.context?.scene));let c=s.method?.length>0;if(a&&c){let h=()=>console.warn(`Could not find method ${s.method} on object ${a.name}`,a,typeof a[s.method]);if(typeof a[s.method]!="function"){let b=!1;s.method.startsWith("set_")&&s.method.length>4&&(s.method=s.method.substring(4),a[s.method]!==void 0&&(b=!0)),b||h()}}let u,l=s.argument;s.argument!==void 0?(typeof l=="object"&&(l=ov.onDeserialize(s.argument,t),l||(l=Cu.onDeserialize(s.argument,t))),u=new gi(c?(...h)=>d(...h):void 0,s.enabled)):u=new gi(c?(...h)=>d(...h):void 0,s.enabled);let d=(...h)=>{let b=a[s.method];typeof b=="function"?l!==void 0?b?.call(a,l):b?.call(a,...h):a[s.method]=l};if(u.method||(u.__debuginfo=t.object?.name),!a||!u.method){let h=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;a?console.warn('EventList method not found: "'+s.method+'" on',a):console.warn("EventList is missing target - will be ignored",s.target,h,e)}else i.push(u)}let n=new ye(i);Te&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},LS=new Pu;import*as zo from"three";import{Vector3 as Yp}from"three";var Ou=class{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(let t of this._positionKeys)delete this.position[t];if(this.quaternion)for(let t of this._quaternionKeys)delete this.quaternion[t]}}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(let e of this._positionKeys){let t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(let e of this._quaternionKeys){let t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new pn(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((i,n)=>{if(this.context.physics.isUpdating||this.mute)return;let r=this.position[n];Math.abs(r-i)<1e-5||(this.position[n]=i,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new pn(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((i,n)=>{if(this.context.physics.isUpdating||this.mute)return;let r=this.quaternion[n];Math.abs(r-i)<1e-5||(this.quaternion[n]=i,this.rotationChanged=!0)}))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}},hl=class extends k{mass=1;useGravity=!0;constraints=0;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=0;get lockPositionX(){return(this.constraints&2)!==0}get lockPositionY(){return(this.constraints&4)!==0}get lockPositionZ(){return(this.constraints&8)!==0}get lockRotationX(){return(this.constraints&16)!==0}get lockRotationY(){return(this.constraints&32)!==0}get lockRotationZ(){return(this.constraints&64)!==0}set lockPositionX(e){e?this.constraints|=2:this.constraints&=-3}set lockPositionY(e){e?this.constraints|=4:this.constraints&=-5}set lockPositionZ(e){e?this.constraints|=8:this.constraints&=-9}set lockRotationX(e){e?this.constraints|=16:this.constraints&=-17}set lockRotationY(e){e?this.constraints|=32:this.constraints&=-33}set lockRotationZ(e){e?this.constraints|=64:this.constraints&=-65}_propertiesChanged=!1;_currentVelocity;_smoothedVelocity;_smoothedVelocityGetter;_lastPosition;_watch;awake(){this._watch=void 0,this._currentVelocity=new zo.Vector3,this._smoothedVelocity=new zo.Vector3,this._smoothedVelocityGetter=new zo.Vector3,this._lastPosition=new zo.Vector3}onEnable(){this._watch||(this._watch=new Ou(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),2)}onDisable(){this._watch?.stop(),this.context.physics.removeBody(this)}onDestroy(){this.context.physics.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.updateProperties(this)),this._watch?.isDirty&&(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()),this.captureVelocity(),yield}get body(){return this.context.physics.internal_getRigidbody(this)}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(){this.body?.resetForces(!0)}resetTorques(){this.body?.resetTorques(!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.addForce(e,!0)}applyImpulse(e){this.body?.applyImpulse(e,!0)}setForce(e,t,i){this.body?.resetForces(!0),this.body?.addForce({x:e,y:t,z:i},!0)}getVelocity(){let e=this.body?.linvel();return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i){if(e instanceof Yp){let n=e;this.body?.setLinvel(n,!0);return}t===void 0||i===void 0||this.body?.setLinvel({x:e,y:t,z:i},!0)}setAngularVelocity(e,t,i){if(e instanceof Yp){let n=e;this.body?.setAngvel(n,!0);return}t===void 0||i===void 0||this.body?.setAngvel({x:e,y:t,z:i},!0)}setTorque(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){this.gameObject&&this.destroyed}captureVelocity(){if(this.body){let e=U(this.gameObject);hl.tempPosition.copy(e);let t=e.sub(this._lastPosition);this._lastPosition.copy(hl.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}}},J=hl;L(J,"tempPosition",new zo.Vector3),E([hi(),w()],J.prototype,"mass",2),E([hi(),w()],J.prototype,"useGravity",2),E([hi(),w()],J.prototype,"constraints",2),E([hi(),w()],J.prototype,"isKinematic",2),E([hi(),w()],J.prototype,"drag",2),E([hi(),w()],J.prototype,"angularDrag",2),E([hi(),w()],J.prototype,"detectCollisions",2),E([hi(),w()],J.prototype,"sleepThreshold",2),E([hi(),w()],J.prototype,"collisionDetectionMode",2);import{Mesh as av,Vector3 as or}from"three";var Tt=class extends k{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}onDisable(){this.context.physics.removeBody(this)}};E([w(J)],Tt.prototype,"attachedRigidbody",2),E([w()],Tt.prototype,"isTrigger",2);var Rn=class extends Tt{radius=.5;center=new or(0,0,0);onEnable(){super.onEnable(),this.context.physics.addSphereCollider(this,this.center,this.radius)}};E([w()],Rn.prototype,"radius",2),E([w(or)],Rn.prototype,"center",2);var Sn=class extends Tt{size=new or(1,1,1);center=new or(0,0,0);onEnable(){super.onEnable(),this.context.physics.addBoxCollider(this,this.center,this.size)}};E([w(or)],Sn.prototype,"size",2),E([w(or)],Sn.prototype,"center",2);var sr=class extends Tt{sharedMesh;convex=!1;onEnable(){super.onEnable(),this.sharedMesh?.isMesh||this.gameObject instanceof av&&(this.sharedMesh=this.gameObject),this.sharedMesh?.isMesh&&this.context.physics.addMeshCollider(this,this.sharedMesh,this.convex)}};E([w()],sr.prototype,"convex",2);var Ct=class extends Tt{center=new or(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.addCapsuleCollider(this,this.center,this.height,this.radius)}};E([w(or)],Ct.prototype,"center",2),E([w()],Ct.prototype,"radius",2),E([w()],Ct.prototype,"height",2);var bi=class extends k{center=new qr(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(J),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(J)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(Ct);t||(t=this.gameObject.addNewComponent(Ct)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}_activeGroundCollisions=new Set;onCollisionEnter(e){for(let t of e.contacts)if(t.normal.y>.1){this._activeGroundCollisions.add(e);break}}onCollisionExit(e){this._activeGroundCollisions.delete(e)}get isGrounded(){return this._activeGroundCollisions.size>0}};E([w(qr)],bi.prototype,"center",2),E([w()],bi.prototype,"radius",2),E([w()],bi.prototype,"height",2);var Yt=class extends k{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;animator;lookForward=!0;_currentSpeed=new qr(0,0,0);_currentAngularSpeed=new qr(0,0,0);_temp=new qr(0,0,0);_jumpCount=0;_currentRotation;awake(){this._currentRotation=new lv}update(){this.controller?.isGrounded&&(this._jumpCount=0,this.animator?.SetBool("doubleJump",!1));let e=this.context.input.isKeyPressed("w"),t=this.context.input.isKeyPressed("s"),i=this.context.input.isKeyPressed("a"),n=this.context.input.isKeyPressed("d"),r=this.context.input.isKeyDown(" "),s=e?1:0+t?-1:0;this._currentSpeed.z+=s*this.movementSpeed*this.context.time.deltaTime,this.animator?.SetBool("running",s!=0),this.animator?.SetBool("jumping",this.controller?.isGrounded===!0&&r),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);let a=i?1:0+n?-1:0;if(this._currentAngularSpeed.y+=F.toRadians(a*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){let c=this.context.mainCameraComponent.forward;c.y=0,c.normalize(),this._currentRotation.setFromUnitVectors(new qr(0,0,1),c),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&r&&this.jumpForce>0){let c=this.controller?.isGrounded;if(!this.controller?.isGrounded&&this._jumpCount===1&&(c=!0,this.animator?.SetBool("doubleJump",!0)),c){this._jumpCount+=1;let u=this.controller.rigidbody,l=this._jumpCount===2?2:1;u.applyImpulse(new qr(0,1,0).multiplyScalar(this.jumpForce*l))}}if(this.controller){let c=this.controller?.rigidbody.getVelocity().y;if(c<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new cv),this._raycastOptions.ray.origin.copy(U(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);let u=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);let l=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(u),(l.length&&l[0].distance>2||c<-10)&&this.animator?.SetBool("falling",!0)}else this.animator?.SetBool("falling",!1)}}_raycastOptions=new fe};E([w(bi)],Yt.prototype,"controller",2),E([w()],Yt.prototype,"movementSpeed",2),E([w()],Yt.prototype,"rotationSpeed",2),E([w()],Yt.prototype,"jumpForce",2),E([w(Ye)],Yt.prototype,"animator",2);var Rt=class extends k{canGrab=!0;onPointerClick(e){}},St=class extends k{isUsed=!0;usedBy=null};var ar=class extends ke{},Yr=class extends k{deleteBoxes=[];awake(){this.deleteBoxes=R.findObjectsOfType(ar,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(R.getComponentInParent(this.gameObject,St)||Oo(this.gameObject,this.context.connection))}}};var lr=class extends k{visibleOn;onEnable(){this.apply()}apply(){this.test()||R.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:uv()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};E([w()],lr.prototype,"visibleOn",2);var pl;function uv(){if(pl===!0||pl===!1)return pl;let o=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),pl=o,o}import*as Pn from"three";var Ee=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 Wo=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Ee).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Ee).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Ee).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,s,a,c,u,l){return e.prep(4,36),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(u),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(s),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Kt=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 Kt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Kt).__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 Wo).__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 cr=M("debugsync"),No="STRS";Fo(No,Kt.getRootAsSyncedTransformModel);var Hi=new xt;function ku(o,e,t=!0){Hi.clear();let i=Hi.createString(o);Kt.startSyncedTransformModel(Hi),Kt.addGuid(Hi,i),Kt.addFast(Hi,t);let n=e.worldPosition,r=e.worldEuler,s=e.gameObject.scale;Kt.addTransform(Hi,Wo.createTransform(Hi,n.x,n.y,n.z,r.x,r.y,r.z,s.x,s.y,s.z));let a=Kt.endSyncedTransformModel(Hi);return Hi.finish(a,No),Hi.asUint8Array()}var ht=class extends k{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(){cr&&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(){cr&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new Pn.Vector3,this._targetRotation=new Pn.Quaternion,this.lastWorldPos=new Pn.Vector3,this.lastWorldRotation=new Pn.Quaternion,this.rb=R.getComponentInChildren(this.gameObject,J),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Jn(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(No,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Ah(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(No,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new Pn.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){cr&&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){oe.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)&&Eh(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){cr&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>a||s>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(cr&&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),oe.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let s=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,s),this.worldPosition=c,a=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,s),this.worldQuaternion=c,a=!0}a&&oe.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&&(cr&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new Pn.Vector3(0,0,0))>1e3&&(cr&&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)){cr&&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=ku(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as Y from"three";import{Euler as jv,EventDispatcher as Hv,Group as Fv,Matrix4 as af,Mesh as Bv,MeshBasicMaterial as Uv,Object3D as sf,Quaternion as Uu,RingGeometry as Gv,Vector3 as lf}from"three";var fl=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 u=document.createElementNS("http://www.w3.org/2000/svg","svg");u.setAttribute("width",38),u.setAttribute("height",38),u.style.position="absolute",u.style.right="20px",u.style.top="20px",u.addEventListener("click",function(){d.end()}),c.appendChild(u);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),u.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 d=null;async function h(_){_.addEventListener("end",b),await e.xr.setSession(_),i.textContent="STOP AR",t.domOverlay.root.style.display="",d=_}function b(){d.removeEventListener("end",b),i.textContent="START AR",t.domOverlay.root.style.display="none",d=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(){d===null?navigator.xr.requestSession("immersive-ar",t).then(h):d.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 s(){r(),i.textContent="AR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",a(i),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?n():s()}).catch(s),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",a(c),c}}};var ml=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 u(d){d.addEventListener("end",l),await e.xr.setSession(d),i.textContent="EXIT VR",c=d}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 d={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",d).then(u)}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 s(){r(),i.textContent="VR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",a(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():s(),ml.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",a(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),ml.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},Qo=ml;L(Qo,"xrSessionIsGranted",!1);Qo.registerSessionGrantedListener();import*as gl from"three";var Kp=ra(ja(),1);import{AudioAnalyser as dv}from"three";var qo="noVoip",pt=M("debugvoip"),hv=M("voip");var Mu=class{id;constructor(e){this.id=e}};var Iu=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,i,n){this.voip=e,this.peer=t,this.userId=i,this.peerId=n}close(){pt&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let i of t)i.enabled=!e}async startVoipCall(){if(!await Ke.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}pt&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),pt&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{pt&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(i){i.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){pt&&console.log("call closed",e)}},Du=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,ie.userInteractionRegistered||pt&&console.log("Incoming call, waiting for user interaction before opening audio"),ie.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){pt&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new gl.AudioListener;this.audio=new gl.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(n=>{if(!!i){console.log(n);for(let r of n)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),pt&&console.log("call is setup, you should hear something now"),this.analyzer=new dv(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},Ke=class extends k{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(M(qo)){console.log("VOIP is disabled by url parameter: "+qo);return}if(this.requireParam&&!hv){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Kp.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 Iu(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=i,i.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,i=this.connections[t];this.connections[t]=null,i&&i.close();let n=this.currentIncomingCalls[t];pt&&console.log("UserLeftRoom",e,t,n),n&&(n.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){pt&&console.log("Peer connection established and received id"),this.model=new Mu(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){pt&&console.log("CONNECTION",t),t.on("data",function(i){pt&&console.log("Received",i)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:i}=t,{peer:n}=e,r=this.currentIncomingCalls[i];if(r&&r.close(),pt&&console.log("received call"),await Ke.HasMicrophonePermissions()){let s=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(s)}else e.answer(null);this.currentIncomingCalls[i]=new Du(this,this.gameObject,e),e.on("stream",s=>{pt&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(s)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};import{Matrix4 as Bs}from"three";var Pt=class extends k{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 Bs;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=R.findObjectOfType(z);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 Bs().fromArray(i.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new Bs),this._placementPose.copy(t),e){if(this.invertForward){let i=new Bs().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)),oe.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 Bs().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};E([w()],Pt.prototype,"invertForward",2),E([w()],Pt.prototype,"arScale",1);import{BoxHelper as _v,BufferGeometry as xv,Color as nf,Euler as wv,Layers as Ev,Line as Cv,Mesh as Tv,MeshBasicMaterial as Rv,Quaternion as yl,Ray as Sv,SphereGeometry as Pv,Vector2 as Ov,Vector3 as _i}from"three";import{OculusHandModel as kv}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Mv}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import{XRControllerModelFactory as Iv}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{GLTFLoader as Dv}from"three/examples/jsm/loaders/GLTFLoader.js";import*as $p from"three";import{Quaternion as pv,Vector3 as bl}from"three";var Yo=M("debugflags");var Au=class{Mask=17;Has(e){let t=this.Mask&e;return Yo&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,_e.Apply()}Enable(e){this.Mask|=e,_e.Apply()}Disable(e){this.Mask&=~e,_e.Apply()}Toggle(e){this.Mask^=e,_e.Apply()}EnableAll(){this.Mask=-1,_e.Apply()}DisableAll(){this.Mask=0,_e.Apply()}},ft=Au;L(ft,"Global",new Au);var Fi=class extends k{static Apply(){for(let e of this.registry)e.UpdateVisible(ft.Global)}awake(){Fi.registry.push(this)}onEnable(){Fi.firstApply||(Fi.firstApply=!0,Fi.Apply())}onDestroy(){let e=Fi.registry.indexOf(this);e>=0&&Fi.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),Yo&&console.log(i),Fi.buffer.Mask=i,e=Fi.buffer);let n=e;if(n?(Yo&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(Yo&&console.log("use global mask"),ft.Global.Has(this.visibleIn)),t!==void 0)if(t)Yo&&console.trace("is visible",this.name,this.gameObject.uuid),R.setActive(this.gameObject,!0);else{if(Yo&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},_e=Fi;L(_e,"registry",[]),L(_e,"firstApply"),L(_e,"buffer",new ft);import{Object3D as Lu}from"three";var ur=M("debugavatar"),vi=class extends k{static getAvatar(e){return e>=0&&e<vi.instances.length?vi.instances[e]:null}static onAvatarMarkerCreated(e){return vi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return vi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){vi.instances.push(this),ur&&console.log(this);for(let e of vi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){vi.instances.splice(vi.instances.indexOf(this),1);for(let e of vi._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):R.setActive(this.avatar,e))}},se=vi;L(se,"instances",[]),L(se,"_onNewAvatarMarkerAdded",[]),L(se,"_onAvatarMarkerDestroyed",[]);var Us=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 bl(1,1,1);handLeftScale=new bl(1,1,1);handRightScale=new bl(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 Lu;_handLeftTarget=new Lu;_handRightTarget=new Lu;_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),oe.markDirty(this.head),this._canInterpolate=!0;let r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){let s=this.isLocalAvatar?this.handLeft:this._handLeftTarget;s.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),s.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),s.quaternion.multiply(Us.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handLeftScale),oe.markDirty(this.handLeft)}if(this.handRight){let s=this.isLocalAvatar?this.handRight:this._handRightTarget;s.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),s.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),s.quaternion.multiply(Us.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handRightScale),oe.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(){ur&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&me.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&R.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(ur&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&me.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;R.setActive(n,!1),e=R.instantiate(n),R.setActive(e,!0)}ur&&console.log(e);let i=await Us.loader.getOrCreateNewAvatarInstance(this.context,e);if(ur&&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=R.addNewComponent(this.root,se),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&&me.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(...R.getComponentsInChildren(this.root,_e)),this.flags.length<=0&&this.head){let n=R.addNewComponent(this.head,_e);n.visibleIn=20,this.flags.push(n),ur&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return ur&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return ur&&console.warn("build avatar failed"),!1}},Ot=Us;L(Ot,"loader",new Tn),L(Ot,"invertRotation",new pv().setFromAxisAngle(new bl(0,1,0),Math.PI));var me=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??V.Current?.time.time;return}}}};L(me,"Pois",[]),L(me,"LastChangeTime",0);var ju=class{guid;position=new $p.Vector3},Bi=class extends k{set controlledTarget(e){this.target=e;let t=O.get("MoveRandom");if(t&&this.target){let i=R.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new ju;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=R.getComponentInParent(this.gameObject,se),this.avatar){let e=R.getComponentInParent(this.gameObject,se);this._model=new Jn(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&&te(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(me.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=me.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=U(this._currentTargetObject);te(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=me.Pois;if(t.length>0){let i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}};import*as vl from"three-mesh-ui";import{OrbitControls as mv}from"three/examples/jsm/controls/OrbitControls";import{Object3D as fv}from"three";var Ui=class extends k{constraintActive=!0;locked=!1;sources=[]};E([w(fv)],Ui.prototype,"sources",2);import*as Gs from"three";var ef=M("nocamlimits"),Je=class extends k{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 Gs.Vector3,this._startedListeningToKeyEvents=!1}onEnable(){this._enableTime=this.context.time.time;let t=R.getComponent(this.gameObject,ae)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new mv(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"?ef||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):ef||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body)))}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}onDestroy(){this._controls?.dispose()}start(){if(this._controls){let e=R.getComponent(this.gameObject,ae);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");let t=new Gs.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new fe;e.screenPoint=new Gs.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.context.isInXR&&(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&&R.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=U(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};E([w(Ui)],Je.prototype,"lookAtConstraint",2);var Jt=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 bv}from"three";var vv=M("debugeventsystem"),Gi=class extends k{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Gi.systems.length<=0&&Gi.systems.push(...R.findObjectsOfType(Gi,e)));for(let i of Gi.systems)if(i.context===e)return;let t=new bv;R.addNewComponent(t,Gi),e.scene.add(t)}static ensureUpdateMeshUI(e,t){yi.update(e,t)}static markUIDirty(e){yi.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Gi.systems.push(this)}onDestroy(){Gi.systems.splice(Gi.systems.indexOf(this),1)}start(){}register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){let t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}_selectStartFn;_selectEndFn;_selectUpdateFn;onEnable(){let e=new Map;this._selectStartFn??=(i,n)=>{if(!n.grab)return;yi.resetLastSelected();let r=new Jt;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=!1,e.set(i,n.grab),n.grab&&!this.handleEvents(n.grab,r)&&(n.grab=null)},this._selectEndFn??=(i,n)=>{if(!n.grab)return;let r=new Jt;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=i.selectionClick,this.handleEvents(n.grab,r);let s=e.get(i);if(e.set(i,null),s)for(let a=0;a<this.raisedPointerDownEvents.length;a++){let c=this.raisedPointerDownEvents[a];this.raisedPointerDownObjects[a]===s&&c&&(c.onPointerUp?.call(c,r),this.raisedPointerDownEvents.splice(a,1),this.raisedPointerDownObjects.splice(a,1),a--)}};let t=new fe;this._selectUpdateFn??=i=>{t.ray=i.getRay();let n=this.performRaycast(t);if(!n)return;let r=new Jt;r.inputSource=i,this.handleIntersections(n,r)},Z.addEventListener("select-start",this._selectStartFn),Z.addEventListener("select-end",this._selectEndFn),Z.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){Z.removeEventListener("select-start",this._selectStartFn),Z.removeEventListener("select-end",this._selectEndFn),Z.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];raisedPointerDownObjects=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),z.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 Jt(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=R.getComponent(this.context.mainCameraComponent.gameObject,Je)??null,i&&(n=i.enabled,i.enabled=!1)),this.handleIntersections(e,t),i&&(this.orbitControl=i,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=R.getComponentsInParent(t,k,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 s=r;s.onPointerExit&&s.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let i=t.performRaycast(e);i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let i of e){let{object:n}=i;if(this.handleEvents(n,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&vv&&console.log("not allowed",e),!1;let i=e;t.object=e,this.lastPointerEvent=t;let n=e.parent,r=!1,s=t.isClicked??!1,a=null;if(n&&n.isUI){let c=(t.isPressed||t.isClicked)??!1;if(n[kt]){let u=n[kt].gameObject;if(u){if(!Zt.isInteractable(u,this.out))return this.out.canvasGroup?.interactable??!1;a=this.out.canvasGroup??null;let d=this.handleMeshUIIntersection(e,c);e=u,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(n,c))return!0}if(this.objectsHoveredThisFrame.push(e),a===null||a.interactable){let c=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let u=R.getComponentsInParent(e,k,this.handleEventsArray);for(let l=0;l<u.length;l++){if(t.used)return!0;if(u[l].destroyed)continue;let d=u[l];d.interactable!==!1&&(d.onPointerEnter&&(c||d.onPointerEnter(t)),t.isDown&&d.onPointerDown&&!this.raisedPointerDownEvents.includes(d)&&(d.onPointerDown(t),this.raisedPointerDownEvents.push(d),this.raisedPointerDownObjects.push(i)),t.isUp&&d.onPointerUp&&d.onPointerUp(t),t.isClicked&&d.onPointerClick&&d.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=yi.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&yi.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];yi.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?R.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},Ve=Gi;L(Ve,"didSearchEventSystem",!1),L(Ve,"systems",[]);var yi=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}};L(yi,"lastSelected",null),L(yi,"lastUpdateFrame",[]),L(yi,"needsUpdate",!1);import{AxesHelper as yv}from"three";var Ko="./include";vl.Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};var kt=Symbol("shadowDomOwner"),Me=class extends k{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Ve.markUIDirty(this.context)}shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=R.getComponentInParent(this.gameObject,Vi)),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=R.getComponentInParent(i,Me),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[kt]=this,e.traverse(r=>{r[kt]===void 0&&(r[kt]=this)});let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&(r?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),ki&&e.add(new yv(.5)),this.onAfterAddedToScene(),n&&vl.update()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e[kt]===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)}},Vi=class extends Me{awake(){super.awake()}};var Zt=class{static getObject(e){let t=e[kt];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;let i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;let n=ci(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),n?.raycastTarget!==!1}static tryFindCanvasGroup(e){if(!e)return null;let t=ci(e,i=>{let n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}};var Vs=M("debugwebxrcontroller");var dr=class extends k{},Ie=class extends k{static CreateRaycastLine(){let e=new Cv(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new Pv(.5,22,22),t=new Rv({color:this.raycastColor}),i=new Tv(e,t);return i.visible=!1,i.layers.set(2),i}static Create(e,t,i,n){let r=i?R.addNewComponent(i,Ie,!1):new Ie;r.webXR=e,r.index=t,r.type=n;let s=e.context;r.controller=s.renderer.xr.getController(t),r.controllerGrip=s.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=s.renderer.xr.getHand(t);let a=new Dv;_n(a,s),r.webXR.handModelPath&&r.webXR.handModelPath!==""&&a.setPath("/"+Oi(e.sourceId,r.webXR.handModelPath));let c=new kv(r.hand,a);return r.hand.add(c),r.hand.traverse(u=>u.layers.set(2)),r.handPointerModel=new Mv(r.hand,r.controller),r.controller.addEventListener("connected",u=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",u=>{if(u.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(h=>h.layers.set(2)),r.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let d=r.hand.joints;if(d)for(let h of Object.keys(d)){let b=d[h];b.parent||r.hand.add(b)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}static removeEventListener(e,t){if(!t)return;let i=this.eventSubs[e]??[],n=i.indexOf(t);n>=0&&i.splice(n,1),this.eventSubs[e]=i}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;showRaycastLine=!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 yl),he(e).multiply(this._wristQuaternion.setFromEuler(new wv(-Math.PI/4,0,0)))):null}movementVector=new _i;worldRot=new yl;joystick=new Ov;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=Ie.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Ie.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),Vs&&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 yl;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Ie.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(he(this.controller),this.useSmoothing?t:1);let i=U(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,te(this.raycastLine,i);let n=this.hand.joints;if(n&&n.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let s=this.getWristQuaternion();s&&this.rayRotation.copy(s)}$e(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=this.showRaycastLine,$e(this.raycastLine,this.rayRotation),te(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*Ie.MovementSpeedFactor,r=2,s=F.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=a,c*=s;let u=this.joystick.y>0?1:-1,l=Math.pow(this.joystick.y,r);l*=u,c*=s,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,l),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(n*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let d=this.joystick.x,h=Math.abs(d);if(h<.4)this.didRotate=!1;else if(h>.5&&!this.didRotate){let b=d>0?-1:1;t.rotateY(F.toRadians(30*b)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),a||(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,s=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let c=t[a];if(a===4)if(c.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;let u=this.webXR.Rig;if(u)if(r){r=!1,u.scale.set(1,1,1),s=1,Ie.MovementSpeedFactor=1;let l=this.context.mainCamera;Ie.PreviousCameraFarDistance&&(l.far=Ie.PreviousCameraFarDistance)}else{r=!0,n=!0,s=.1,Ie.MovementSpeedFactor=s*2;let l=this.context.mainCamera;Ie.PreviousCameraFarDistance=l.far,l.far/=s}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let c=a[0];if(r||this.isValidTeleportTarget(c.object)){let u=c.point;te(e,u)}}}}else i<.1&&(this.didTeleport=!1);s!==null&&(e.scale.set(s,s,s),e.updateMatrixWorld())}isValidTeleportTarget(e){return R.getComponentInParent(e,dr)!=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=Ie.raycastColor:n.color=Ie.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=F.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(),Vs&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(let i of e){let n=i.object;this.lastSelectStartObject=n;let r={selected:n,grab:n},s=Ie.eventSubs["select-start"];if(s&&s.length>0)for(let a of s)a(this,r);r.grab!==n&&Vs&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=nt.TryTake(this,r.grab,i,t));break}else{let i=Ie.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=Ie.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||R.isActiveInHierarchy(e)===!1||Zt.isInteractable(e)===!1)}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let i of e.children)this.grabbed?.selected===i||this.grabbed?.selectedMesh===i||this.setControllerLayers(i,t)}getRay(){let e=new Sv;return e.origin.copy(U(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}closeGrabBoundingBoxHelper;overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Vs&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new _v(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;let t=U(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new fe;e.layerMask=new Ev,e.layerMask.set(0),e.layerMask.disable(2),e.ray=this.getRay();let t=this.context.physics.raycast(e);for(let i=0;i<t.length;i++){let n=t[i],r=n.object;if(!this.testIsVisible(r)){t.splice(i,1),i--;continue}n.object=Zt.getObject(r);break}return t}},Z=Ie;L(Z,"Factory",new Iv),L(Z,"raycastColor",new nf(.9,.3,.3)),L(Z,"raycastNoHitColor",new nf(.6,.6,.6)),L(Z,"geometry",new xv().setFromPoints([new _i(0,0,0),new _i(0,0,-1)])),L(Z,"handModels",{}),L(Z,"eventSubs",{}),L(Z,"PreviousCameraFarDistance"),L(Z,"MovementSpeedFactor",1);var it=class{static AddEventListener(e,t){return it.Events[e]||(it.Events[e]=[]),it.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!it.Events[e])return;let i=it.Events[e].indexOf(t);i>=0&&it.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=R.getComponentInParent(t,Rt);if(r)t=r.gameObject;else return Vs&&console.warn("Prevented taking object that is not interactable",t),null;let s=t,a=R.getComponentInParent(t,ht);a&&(a.requestOwnership(),s=a.gameObject);for(let u of this.Current)if(u.selected===s)return u.controller===e||(u.free(),u.Take(e,s,t,a,r,i,n)),u;let c=new it;return c.Take(e,s,t,a,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,s,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};it.Events.WillTake?.forEach(b=>b(this,c));let u=i;u?.material&&(this.originalMaterial=u.material,Array.isArray(u.material)||(u.material=u.material.clone(),u.material&&u.material.emissive&&(u.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=u,this.controller=e,this.interactable=r,this.isCloseGrab=a,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=R.addNewComponent(this.selected,St),this.rigidbodies=R.getComponentsInChildren(this.selected,J),U(this.positionSource,this.lastControllerWorldPos);let l=()=>a?this.lastControllerWorldPos.clone():s.point.clone();this.grabDistance=l().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(l());let d=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();he(this.selected,this.localQuaternionToGrab).premultiply(d.invert());let h=this.controller.webXR.Rig;return h&&this.rigPositionLastFrame.copy(U(h)),me.Add(e.context,this.selected),it.Register(this),this.sync&&(this.sync.fastMode=!0),it.Events.DidTake?.forEach(b=>b(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};it.Events.WillFree?.forEach(n=>n(this,e)),me.Remove(this.controller.context,this.selected),it.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.setVelocity(n.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,it.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new _i;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new _i;localQuaternionToGrab=new yl(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new _i;controllerWorldPos=new _i;lastControllerWorldPos=new _i;controllerPosDelta=new _i;totalChangeAlongDirection=0;rigPositionLastFrame=new _i;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),U(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=U(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.rigidbodies)for(let e of this.rigidbodies)e.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new _i),this.targetDir.set(0,0,-this.grabDistance*t);let i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),n=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=n.clone()),this.quaternionLerp.slerp(n,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),$e(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(U(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),te(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});oe.markDirty(this.selected,!0)}}},nt=it;L(nt,"Events",{}),L(nt,"Current",[]);var On=class extends k{awake(){}};import{Quaternion as zs,Vector3 as _l,Vector4 as Av}from"three";var zi=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 Se=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 Se).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Se).__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 Ee).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new zi).__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 Ee).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Ee).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new zi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new zi).__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 rf=M("debugxr"),Ws=M("debugavatar");var Bu="VRUS";Fo(Bu,Se.getRootAsVrUserStateBuffer);function Fu(){return new Date().getTime()}function Lv(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return Xe.create(e,t)}var Ns=class{guid;time;avatarId;position=new _l;rotation=new Av;scale=1;posLeftHand=new _l;posRightHand=new _l;rotLeftHand=new zs;rotRightHand=new zs;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=Fu(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let s=Ns.quat0,a=Ns.quat1;s.set(i.x,i.y,i.z,i.w),s=s.multiplyQuaternions(s,Ns.invertRotation),e&&(e.getWorldQuaternion(a),s.multiplyQuaternions(a,s)),this.rotation.set(s.x,s.y,s.z,s.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let u=n.RightController?.controllerGrip;if(u&&(u.getWorldPosition(this.posRightHand),u.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);Se.startVrUserStateBuffer(e),Se.addGuid(e,i),Se.addTime(e,Lv(this.time)),Se.addAvatarId(e,n),Se.addPosition(e,Ee.createVec3(e,this.position.x,this.position.y,this.position.z)),Se.addRotation(e,zi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Se.addScale(e,this.scale),Se.addPosLeftHand(e,Ee.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Se.addPosRightHand(e,Ee.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Se.addRotLeftHand(e,zi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Se.addRotRightHand(e,zi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Se.endVrUserStateBuffer(e);e.finish(r,Bu);let s=e.asUint8Array();t.sendBinary(s)}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 s=t.posLeftHand();s&&this.posLeftHand.set(s.x(),s.y(),s.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let u=t.rotRightHand();u&&this.rotRightHand.set(u.x(),u.y(),u.z(),u.w()),this.scale=t.scale()}},Mt=Ns;L(Mt,"invertRotation",new zs().setFromAxisAngle(new _l(0,1,0),Math.PI)),L(Mt,"quat0",new zs),L(Mt,"quat1",new zs);var Wi=class extends k{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=R.getComponent(this.gameObject,z)),this.webXR||(this.webXR=R.findObjectOfType(z,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=R.findObjectOfType(z,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=R.findObjectOfType(Ke,this.context)),Ws){let e="debug-avatar-"+Ws,t=new Ot(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof Ws=="string"&&Ws.length>0)if(await t.setAvatarOverride(Ws)){let i=new Mt(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=R.getComponent(this.gameObject,z),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),z.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),z.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),z.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(Bu,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 Mt("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return rf&&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 Ot(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),z.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),z.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),z.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=Fu();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=Fu();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 Ot(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(){rf&&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 xt(1024);onXRSessionUpdate(e){this.xrState??=new Mt(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new Jn(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 s=r?.transform,a=s.position,c=s.orientation;this.xrState.update(n,a,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return M("avatar")??null}};async function Vv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function zv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var Gu=!1,Vu=!1;Vv().then(o=>Gu=o);zv().then(o=>Vu=o);var De=class extends k{enableVR=!0;enableAR=!0;defaultAvatar;handModelPath="";createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Gu||Vu)}static get IsARSupported(){return Gu}static get IsVRSupported(){return Vu}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){De.XRSupported?e.__internalAwake():console.warn("WebXR is not supported on this device");let i=Qo.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){e.__internalAwake();let i=e.webAR?.getAROverlayContainer(),n={};i?(n.domOverlay={root:i},n.optionalFeatures=["hit-test","dom-overlay"]):console.warn("No dom overlay root found, AR will not work");let r=fl.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),De.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=qe.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!R.findObjectOfType(Wi,this.context)){let e=R.addNewComponent(this.gameObject,Wi,!1);e.webXR=this}this.webAR=new kn(this)}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0;let e=De.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=De.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(i=De.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{De.resetButtonStyles(i),De.resetButtonStyles(t)},1e3)}_transformOrientation=new Uu;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)}De._isInXr===!1&&t&&this.onEnterXR(t,e),De.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++)Z.Create(this,e,this.gameObject,0);De.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(U(this.context.mainCamera)),this._originalCameraRotation.copy(he(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=R.findObjectOfType(On,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new Fv,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new lf;_originalCameraRotation=new Uu;onEnterXR(e,t){console.log("[XR] session begin",e),De._isInXr=!0,this.ensureRig();let i=this.context.renderer.xr.getReferenceSpace();if(i&&this.rig){let a=t.getViewerPose(i)?.transform.orientation;if(a){let c=new Uu(a.x,a.y,a.z,a.w),u=new jv().setFromQuaternion(c);this.rig.rotateY(u.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let s=n.getCamera(this.context.mainCamera);for(let a of s.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch(ft.Global.Set(r),r){case 2:this.context.xrSessionMode="immersive-ar",this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this.context.xrSessionMode="immersive-vr",this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),De._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),De.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),te(this.context.mainCamera,this._originalCameraPosition),$e(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),ft.Global.Set(17),De.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){!M("mirror")||setTimeout(()=>{if(!De.IsInWebXR)return;let t=new URL(window.location.href);Co(t.searchParams,qo,1),Co(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=()=>{De.IsInWebXR&&e.end()})})},1e3)}},z=De;L(z,"_isInXr",!1),L(z,"events",new Hv),E([w()],z.prototype,"enableVR",2),E([w()],z.prototype,"enableAR",2),E([w(qe)],z.prototype,"defaultAvatar",2),E([w()],z.prototype,"handModelPath",2),E([w()],z.prototype,"createVRButton",2),E([w()],z.prototype,"createARButton",2);var Jo=class{get webxr(){return this._webxr}_webxr;reticle=null;reticleParent=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this._webxr=e}arDomOverlay=null;arOverlayElement=null;noHitTestAvailable=!1;didPlaceARSessionRoot=!1;getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;let e=this.arDomOverlay;return e.getAROverlayContainer?this.arOverlayElement=e.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(e){this.reticleActive=e}async onBegin(e){let t=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();let i=navigator.userAgent?.includes("OculusBrowser")?0:1,n=i===1?4:2;for(let s=0;s<n;s++)Z.Create(this.webxr,s,this.webxr.gameObject,i);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=R.findObjectOfType(Pt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(s=>{e.requestHitTestSource({space:s}).then(a=>{this.hitTestSource=a}).catch(a=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",a)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new Bv(new Gv(.07,.09,32).rotateX(-Math.PI/2),new Uv),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new sf,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),this.reticleParent.matrix.copy(this.sessionRoot.gameObject.matrixWorld),this.webxr.scene?(this.context.scene.add(this.reticleParent),this.context.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,Jo.tempWebXRObject||(Jo.tempWebXRObject=new sf),this.context.scene.add(Jo.tempWebXRObject),R.addComponent(Jo.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene");let r=this.context.domElement;r?.onEnterAR?.call(r,e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),R.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;if(t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay){let i=this.arOverlayElement;i.onExitAR?.call(i,e)}this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;let n=this.webxr.Rig,r=Wv.clone();if(n){let s=new lf(0,0,0).add(n.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new af().makeTranslation(s.x,s.y,s.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 s=n.getPose(r);if(this.sessionRoot){let a=this.sessionRoot.onUpdate(this.webxr.Rig,e,s);this.didPlaceARSessionRoot=a}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){let a=s.transform.matrix;this.reticle.matrix.fromArray(a),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},kn=Jo;L(kn,"tempWebXRObject");var Wv=new af().identity().makeTranslation(0,-.5,0);var zu=!1;var Zo=class extends Rt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;orbit=null;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new Y.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){this.orbit=R.findObjectOfType(Je,this.context)}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||z.IsInWebXR)return;let t=R.getComponentInParent(e.object,Zo);!t||t!==this||(Zo.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||z.IsInWebXR||Zo.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||z.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(z.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!z.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&this._dragHelper?.hasSelected===!1&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new xl(this.context.mainCamera);else return;if(!e||!e.object)return;let t=R.getComponentInParent(e.object,Zo);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let c of this.selectStartEventListener)c(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context),this.orbit&&(this.orbit.enabled=!1);let r=R.getComponentInChildren(i,ht);zu&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=R.addNewComponent(i,St),this._draggingRigidbodies.length=0;let s=R.getComponentsInChildren(i,J);s&&this._draggingRigidbodies.push(...s);let a=nc();R.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(let n of this._draggingRigidbodies)n.setVelocity(n.smoothedVelocity);this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(zu&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e?.object){let n=R.getComponentInChildren(e.object,ht);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=nc();R.invokeOnChildren(t,i("onDragEnd"))}},xi=Zo;L(xi,"_active",null),L(xi,"lastHovered");var Wu=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new Y.Plane;_hasGroundPlane=!1;_groundPlane=new Y.Plane;_groundOffset=new Y.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new Y.Vector3;_raycaster=new Y.Raycaster;_cameraPlaneOffset=new Y.Vector3;_intersection=new Y.Vector3;_worldPosition=new Y.Vector3;_inverseMatrix=new Y.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new Y.Line(Wu.geometry),i=t.material;i.color=new Y.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new Y.SphereGeometry(.5,22,22),r=new Y.MeshBasicMaterial({color:i.color}),s=new Y.Mesh(n,r);s.visible=!1,s.layers.set(2),this._groundMarker=s}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&me.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}me.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new Y.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),s=this._context.input.getTouchesPressedCount()>=2||r;if(s){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){zu&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=U(this._camera).clone().sub(U(this._selected)).normalize(),u=Math.abs(c.dot(this._groundOffsetVector)),l=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),d=!s&&u>.2&&!l&&this._context.input.getPointerPressedCount()<=1,h=this._didDragOnGroundPlaneLastFrame!==d;if(this._didDragOnGroundPlaneLastFrame=d,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!d||h)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let b=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=b,d){this._groundOffsetVector.set(0,1,0);let _=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(_,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);h&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,i){if(!!this._selected){if(i){let n=U(this._selected);n.y=e.y,e=n}if(te(this._selected,e),te(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=U(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),te(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=U(this._selected),t=new Y.Ray(new Y.Vector3(0,.1,0).add(e),new Y.Vector3(0,-1,0)),i=new fe;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let s=n[r];if(!s.face||this.contains(this._selected,s.object))continue;let a=new Y.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,s.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){oe.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.resetForcesAndTorques(),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let i of e.children)if(this.contains(i,t))return!0}return!1}},xl=Wu;L(xl,"geometry",new Y.BufferGeometry().setFromPoints([new Y.Vector3(0,0,0),new Y.Vector3(0,-1,0)]));var $t=class extends k{url=null;urlParameterName=null;localhost=null;awake(){this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?$t.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=M(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=$t.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return Xn(e)}};var Mn=class extends k{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?$t.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 s=await wp(r,this.context,this.filesBackendUrl);s&&this.addObject(e,s)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let s=new URL(r);if(!s)return;let a=await Ep(s,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=new fe;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 s of n){r.position.copy(s.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};E([w()],Mn.prototype,"filesBackendUrl",2),E([w()],Mn.prototype,"localhost",2);import{Vector3 as Nv,Quaternion as Xv,Object3D as cf}from"three";var wi=class extends Rt{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 Nv(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Xv(0,0,0,1)}let e=R.getComponentInParent(this.gameObject,xi);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),Z.addEventListener("select-start",(t,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}let n=this.handleDuplication(i.selected);n&&(i.grab=n)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new Ge;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let i=R.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}};E([w(cf)],wi.prototype,"parent",2),E([w(cf)],wi.prototype,"object",2),E([w()],wi.prototype,"limitCount",2),E([w()],wi.prototype,"limitInterval",2);var Kr=class extends k{};import{FlyControls as Qv}from"three/examples/jsm/controls/FlyControls";var Jr=class extends k{_controls=null;onEnable(){let e=R.getComponent(this.gameObject,ae)?.cam;this._controls=new Qv(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 uf from"three";import{Color as qv}from"three";var Ni=class extends k{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!ki||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new uf.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Ma(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}};E([w()],Ni.prototype,"objectBounds",2),E([w(qv)],Ni.prototype,"color",2),E([w()],Ni.prototype,"isGizmo",2);import{GLTFExporter as ly}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as Nu,Matrix4 as Yv,Vector3 as df,Quaternion as Kv}from"three";var Xs=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 s=new Yv,a=new Array,c=new Array,u=new Array;for(let b=0;b<e.count;b++){e.getMatrixAt(b,s);let _=new df,v=new Kv,y=new df;s.decompose(_,v,y),a.push(_.x,_.y,_.z),c.push(v.x,v.y,v.z,v.w),u.push(y.x,y.y,y.z)}let l=new Float32Array(a),d=new Float32Array(c),h=new Float32Array(u);r.attributes={TRANSLATION:i.processAccessor(new Nu(l,3)),ROTATION:i.processAccessor(new Nu(d,4)),SCALE:i.processAccessor(new Nu(h,3))},n[this.name]=!0}};import*as qi from"three";import*as Qs from"three";var Xi=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new Qs.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new Qs.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,s){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(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 Qs.ShaderMaterial({vertexShader:`
|
|
176
|
+
--------------`),i[r]=a,i.needsUpdate=!0,ut)){let c=yu.get(i);c||(c={},yu.set(i,c));let u=c[r];u||(u=c[r]={original:s,lod0:a}),u.lod0=a}}))}}get name(){return bu}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}_loading=[];afterRoot(e){return ut&&console.log("AFTER",this.sourceId,e),this.parser.json.textures?.forEach((t,i)=>{if(t?.extensions){let n=t?.extensions[bu];if(n){let r=this.parser.getDependency("texture",i);this._loading.splice(this._loading.indexOf(i),1),r.then(s=>{ut&&console.log("register texture",s.name,s.uuid,n),s.userData.deferred=n,js.cache.set(s.uuid,n)})}}}),null}static async getOrLoadTexture(e,t,i,n,r,s){let a=r.uuid,c=js.cache.get(a);if(c){ut&&console.log(a,c.uri,c.guid);let u=ki(t,c.uri);if(u.endsWith(".glb")||u.endsWith(".gltf")){if(!c.guid)return console.warn("missing pointer for glb/gltf texture",c),null;let l=u+"_"+c.guid;if(this.resolved[l])return ut&&console.log("Texture has already been loaded: "+l,i.name,n,r.name),this.resolved[l];let d=new Xb;xn(d,e),ut&&console.log("Load "+u,i.name,n,c.guid);let h=await d.loadAsync(u),b=h.parser;ut&&console.log("Loading finished "+u,i.name,n,c.guid);let _=-1,v=!1;for(let f of h.parser.json.textures)if(_++,f?.extensions){let m=f?.extensions[bu];if(m?.guid&&m.guid===c.guid){v=!0;break}}if(!v)return null;let y=await b.getDependency("texture",_);return y&&(y.guid=c.guid),this.resolved[l]=y,ut&&console.log(i.name,n,'change "'+r.name+'" \u2192 "'+y.name+'"',u,_,y,i,l),y}else{ut&&console.log("Load texture from uri: "+u);let d=await new Nb().loadAsync(u);return d&&ut?console.log(c,d):console.warn("failed loading",u),d}}else ut&&console.warn("unknown uuid",r.name,r.uuid,r);return null}},En=js;L(En,"cache",new Map),L(En,"resolved",{});function xu(o){let e=new Go;return o.register(t=>(e.parser=t,e)),e}var _u=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 wu(o,e,t){o.register(n=>new ll(n)),o.register(n=>new ca(n)),o.register(n=>new Za(n,e.lightmaps,t)),o.register(n=>new cl(n,t,e)),o.register(n=>new ol(n,t)),o.register(n=>new Nr(n,t)),o.register(n=>new En(n,t,e)),o.register(n=>new al(n));let i=o.setAnimationPointerResolver;typeof i=="function"&&i.bind(o)(new _u)}import{Vector3 as Qb}from"three";var Cn=class extends k{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new Qb}update(){if(!this.from||!this.to)return;let e=U(this.from).clone(),t=U(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),te(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(U(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}};E([x(R)],Cn.prototype,"from",2),E([x(R)],Cn.prototype,"to",2);var ji=class{time;value;inTangent;inWeight;outTangent;outWeight;weightedMode};E([x()],ji.prototype,"time",2),E([x()],ji.prototype,"value",2),E([x()],ji.prototype,"inTangent",2),E([x()],ji.prototype,"inWeight",2),E([x()],ji.prototype,"outTangent",2),E([x()],ji.prototype,"outWeight",2),E([x()],ji.prototype,"weightedMode",2);var Xt=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;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){let i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){let r=this.keys[t+1];if(r.time<e)continue;let s=F.remap(e,i.time,r.time,0,1);return F.lerp(i.value,r.value,s)}else return i.value}return this.keys[this.keys.length-1].value}};E([x(ji)],Xt.prototype,"keys",2);import*as Xp from"three";import*as Hs from"three";import{PositionalAudioHelper as qb}from"three/examples/jsm/helpers/PositionalAudioHelper.js";var dt=M("debugaudio");var Oe=class extends k{static get userInteractionRegistered(){return Oe._didCallBeginWaitForUserInteraction||(Oe._didCallBeginWaitForUserInteraction=!0,Oe._beginWaitForUserInteraction()),Oe._userInteractionRegistered}static registerWaitForAllowAudio(e){if(e!==null){if(this._userInteractionRegistered){e();return}this.callbacks.indexOf(e)===-1&&this.callbacks.push(e),Oe._didCallBeginWaitForUserInteraction||(Oe._didCallBeginWaitForUserInteraction=!0,Oe._beginWaitForUserInteraction())}}static _beginWaitForUserInteraction(e=null){if(this._userInteractionRegistered){e&&e();return}e!==null&&this.registerWaitForAllowAudio(e);let i=(()=>{if(i!=null&&!Oe._userInteractionRegistered){Oe._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&&(dt&&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&&Oe._userInteractionRegistered){let e=R.getComponent(this.context.mainCamera,Qt)??R.findObjectOfType(Qt,this.context);e?.listener&&(this.sound=new Hs.PositionalAudio(e.listener),this.gameObject.add(this.sound))}return this.sound}get ShouldPlay(){return this.shouldPlay}_focusCallback;awake(){this.audioLoader=new Hs.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&&Oe._userInteractionRegistered&&this.play()},this.context.application.addEventListener("application-visible",this._focusCallback)}onDestroy(){this.context.application.removeEventListener("application-visible",this._focusCallback)}onEnable(){Oe._userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():Oe._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){dt&&console.log("audio buffer loaded"),Oe.registerWaitForAllowAudio(()=>{dt&&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(),dt&&console.log(this.name,this.shouldPlay,Oe.userInteractionRegistered,this),this.shouldPlay&&Oe._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(dt&&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?dt&&!this.helper&&(this.helper=new qb(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}loadAndPlay(e){if(e&&(this.clip=e),this.clip&&(dt&&console.log(this.clip),this.clip.endsWith(".mp3")||this.clip.endsWith(".wav"))){if(this.audioLoader||(this.audioLoader=new Hs.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===this.clip){dt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=this.clip,dt&&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,dt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying&&this.sound.play()}pause(){dt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause())}stop(){dt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,dt&&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,dt&&console.log("Audio clip ended",this.clip),this.sound.dispatchEvent({type:"ended",target:this}))}},ie=Oe;L(ie,"_didCallBeginWaitForUserInteraction",!1),L(ie,"callbacks",[]),L(ie,"_userInteractionRegistered",!1),E([x()],ie.prototype,"clip",2),E([x()],ie.prototype,"playOnAwake",2),E([x()],ie.prototype,"loop",1),E([x()],ie.prototype,"spatialBlend",1),E([x()],ie.prototype,"minDistance",1),E([x()],ie.prototype,"maxDistance",1),E([x()],ie.prototype,"volume",1),E([x()],ie.prototype,"rollOffMode",2);import*as Tn from"three";import{Color as Yb}from"three";var $=class extends Yb{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=F.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){let n=e,r=t;return n.alpha&&r.alpha&&(this.alpha=F.lerp(n.alpha,r.alpha,i)),super.lerpColors(e,t,i)}multiply(e){let t=e;return t.alpha&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}};import{PerspectiveCamera as Jb}from"three";var ul=M("debugcam"),ae=class extends k{get isCamera(){return!0}get aspect(){return this._cam instanceof Jb?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 Tn.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;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;_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()}e.alpha===void 0&&(this._backgroundColor.alpha=1),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(){ul&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&this.context.setCurrentCamera(this),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}buildCamera(){if(this._cam)return;let e=this.gameObject.isCamera,t=null;if(e?(t=this.gameObject,t?.layers.enableAll()):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 Tn.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),t.fov=this.fieldOfView;else{let i=this.orthographicSize*100;t=new Tn.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){if(ul&&Ze("apply Camera clear flags"),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;ul&&Ze("Environment blend mode: "+t+" on "+navigator.userAgent);let i=t==="additive"||t==="alpha-blend";if(this.context.xrSessionMode==="immersive-ar"&&t==="opaque"){if(navigator.userAgent?.includes("OculusBrowser"))return!0;if(navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))return!0}return i}enableSkybox(){this._skybox||(this._skybox=new Eu(this)),this._skybox.enable()}};E([x()],ae.prototype,"fieldOfView",1),E([x()],ae.prototype,"nearClipPlane",1),E([x()],ae.prototype,"farClipPlane",1),E([x()],ae.prototype,"clearFlags",1),E([x()],ae.prototype,"orthographic",2),E([x()],ae.prototype,"orthographicSize",2),E([x()],ae.prototype,"ARBackgroundAlpha",2),E([x()],ae.prototype,"cullingMask",1),E([x($)],ae.prototype,"backgroundColor",1);var Eu=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?(ul&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=Tn.sRGBEncoding,this._skybox.mapping=Tn.EquirectangularReflectionMapping,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this)}};var Qt=class extends k{get listener(){return this._listener==null&&(this._listener=new Xp.AudioListener),this._listener}_listener=null;awake(){ie.registerWaitForAllowAudio(()=>{let e=this.listener;if(e==null||e.parent)return;let t=R.getComponentInParent(this.gameObject,ae);t?t.cam.add(e):this.gameObject.add(e)})}};import{GLTFLoader as Zb}from"three/examples/jsm/loaders/GLTFLoader";import*as dl from"three";var Fs=M("debugavatar"),nr=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))}},Rn=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){let r=new Ge;i=R.instantiate(Nn(t,e.scene),r)}}else i=t;if(!i)return null;let n=this.findAvatar(i);return n.isValid?(Fs&&console.log("[Custom Avatar] valid config",t,Fs?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Fs?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(Fs&&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 a=await n.blob();a&&(r=await a.arrayBuffer())}return!r&&(r=await Va(t,t,0,"no url here go away",!0),!r)?null:(await Qe().parseSync(e,r,null,0))?.scene??null}let i=new Zb;return xn(i,e),new Promise((n,r)=>{let s=this.avatarRegistryUrl+"/"+t;i.load(s,async a=>{await Qe().createBuiltinComponents(e,s,a,null,void 0),n(a.scene)},a=>{Fs&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),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"]),s=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;let c=new dl.Vector3;new dl.Box3().setFromObject(n).getSize(c);let u=Math.max(c.x,c.y,c.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+u+" meters! Should be < 0.3m"),u>.3&&n.scale.multiplyScalar(1/u*.3)}return new nr(t,n,r,s)}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 s=this.findAvatarPart(r,t);if(s)return s}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}};import{AxesHelper as $b}from"three";var Hi=class extends k{length=1;depthTest=!0;isGizmo=!0;_axes=null;onEnable(){if(this.isGizmo&&!Mi)return;this._axes||(this._axes=new $b(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)}};E([x()],Hi.prototype,"length",2),E([x()],Hi.prototype,"depthTest",2),E([x()],Hi.prototype,"isGizmo",2);import*as Qp from"three";var Xr=class extends k{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let e=U(this.to).clone(),t=U(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);let r=t.clone();r.add(e),r.multiplyScalar(.5);let s=U(this.hint).clone();s.sub(r);let a=new Qp.Vector3;a.crossVectors(s,n),a.crossVectors(n,a),a.normalize();let c=i*.5,u=Math.max(this.desiredDistance,c),l=Math.sqrt(u*u-c*c),d=a.clone();d.multiplyScalar(l),d.add(r),te(this.gameObject,d);let h=r.clone();h.sub(a),this.gameObject.lookAt(h)}};import*as Qr from"three";var ev=M("gizmos"),tv=M("debugboxhelper"),qt=class extends k{box=null;_lastMatrixUpdateFrame=-1;isInBox(e,t){if(!e)return;if(this.box||(this.box=new Qr.Box3),e.type==="Mesh")qt.testBox.setFromObject(e);else if(e.type==="Group"){if(qt.testBox.makeEmpty(),e.children.length>0)for(let n=0;n<e.children.length;n++)e.children[n].type==="Mesh"&&qt.testBox.expandByObject(e)}else{let n=U(e,qt._position),r=Fe(e,qt._size);t!==void 0&&r.multiplyScalar(t),qt.testBox.setFromCenterAndSize(n,r)}this.updateBox();let i=this.box?.intersectsBox(qt.testBox);return i&&tv&&Ur.DrawBox3(qt.testBox,16711680,5),i}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new Qr.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){let t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;let i=t,n=U(this.gameObject,qt._position,i),r=Fe(this.gameObject,qt._size);this.box.setFromCenterAndSize(n,r)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!ev&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=Ma(e),this.gameObject.add(this._helper)}}},ke=qt;L(ke,"testBox",new Qr.Box3),L(ke,"_position",new Qr.Vector3),L(ke,"_size",new Qr.Vector3(.01,.01,.01));import{Quaternion as lv,Ray as cv,Vector3 as qr}from"three";import*as qp from"three";var gi=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)}}},iv=o=>/^[A-Z]*$/.test(o),rr=class extends Event{args},ye=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&&iv(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 rr(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1}}addEventListener(e){return this.methods.push(new gi(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}};import{Color as nv,Object3D as rv}from"three";var Tu=class extends gn{constructor(){super([nv,$])}onDeserialize(e){if(e!=null)return e.a!==void 0?new $(e.r,e.g,e.b,e.a):e.alpha!==void 0?new $(e.r,e.g,e.b,e.alpha):new qp.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}}},LS=new Tu,Ru=class extends gn{constructor(){super(rv)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let i=t.objectToNode[e.uuid];return Te&&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 Te&&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=R.findByGuid(e.guid,n)),i||(i=R.findByGuid(e.guid,t.context.scene)),i?Te&&console.log("Deserialized object reference?",e,i,t?.nodeToObject):console.warn("could not resolve reference",e,t.target,t.path,t.context.scene),i}}}},ov=new Ru,Su=class extends gn{constructor(){super([Et,k])}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){Te&&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=R.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],s=this.findObjectForGuid(e,r);if(s)return s}}},Cu=new Su,Pu=class extends gn{constructor(){super([ye])}onSerialize(e,t){console.log("TODO: SERIALIZE EVENT")}onDeserialize(e,t){if(e&&e.type==="EventList"){Te&&console.log("DESERIALIZE EVENT",e);let i=new Array;if(e.calls&&Array.isArray(e.calls))for(let s of e.calls){Te&&console.log(s);let a=Cu.findObjectForGuid(s.target,t.root);!a&&t.context?.scene&&(a=Cu.findObjectForGuid(s.target,t.context?.scene));let c=s.method?.length>0;if(a&&c){let h=()=>console.warn(`Could not find method ${s.method} on object ${a.name}`,a,typeof a[s.method]);if(typeof a[s.method]!="function"){let b=!1;s.method.startsWith("set_")&&s.method.length>4&&(s.method=s.method.substring(4),a[s.method]!==void 0&&(b=!0)),b||h()}}let u,l=s.argument;s.argument!==void 0?(typeof l=="object"&&(l=ov.onDeserialize(s.argument,t),l||(l=Cu.onDeserialize(s.argument,t))),u=new gi(c?(...h)=>d(...h):void 0,s.enabled)):u=new gi(c?(...h)=>d(...h):void 0,s.enabled);let d=(...h)=>{let b=a[s.method];typeof b=="function"?l!==void 0?b?.call(a,l):b?.call(a,...h):a[s.method]=l};if(u.method||(u.__debuginfo=t.object?.name),!a||!u.method){let h=t.object?"Current object: "+t.object.name+", "+t.object.guid:null;a?console.warn('EventList method not found: "'+s.method+'" on',a):console.warn("EventList is missing target - will be ignored",s.target,h,e)}else i.push(u)}let n=new ye(i);Te&&console.log(n);let r=t.target;return r!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,r),n}}},jS=new Pu;import*as zo from"three";import{Vector3 as Yp}from"three";var Ou=class{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(let t of this._positionKeys)delete this.position[t];if(this.quaternion)for(let t of this._quaternionKeys)delete this.quaternion[t]}}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(let e of this._positionKeys){let t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(let e of this._quaternionKeys){let t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new fn(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((i,n)=>{if(this.context.physics.isUpdating||this.mute)return;let r=this.position[n];Math.abs(r-i)<1e-5||(this.position[n]=i,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new fn(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((i,n)=>{if(this.context.physics.isUpdating||this.mute)return;let r=this.quaternion[n];Math.abs(r-i)<1e-5||(this.quaternion[n]=i,this.rotationChanged=!0)}))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}},hl=class extends k{mass=1;useGravity=!0;constraints=0;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=0;get lockPositionX(){return(this.constraints&2)!==0}get lockPositionY(){return(this.constraints&4)!==0}get lockPositionZ(){return(this.constraints&8)!==0}get lockRotationX(){return(this.constraints&16)!==0}get lockRotationY(){return(this.constraints&32)!==0}get lockRotationZ(){return(this.constraints&64)!==0}set lockPositionX(e){e?this.constraints|=2:this.constraints&=-3}set lockPositionY(e){e?this.constraints|=4:this.constraints&=-5}set lockPositionZ(e){e?this.constraints|=8:this.constraints&=-9}set lockRotationX(e){e?this.constraints|=16:this.constraints&=-17}set lockRotationY(e){e?this.constraints|=32:this.constraints&=-33}set lockRotationZ(e){e?this.constraints|=64:this.constraints&=-65}_propertiesChanged=!1;_currentVelocity;_smoothedVelocity;_smoothedVelocityGetter;_lastPosition;_watch;awake(){this._watch=void 0,this._currentVelocity=new zo.Vector3,this._smoothedVelocity=new zo.Vector3,this._smoothedVelocityGetter=new zo.Vector3,this._lastPosition=new zo.Vector3}onEnable(){this._watch||(this._watch=new Ou(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),2)}onDisable(){this._watch?.stop(),this.context.physics.removeBody(this)}onDestroy(){this.context.physics.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.updateProperties(this)),this._watch?.isDirty&&(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()),this.captureVelocity(),yield}get body(){return this.context.physics.internal_getRigidbody(this)}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(){this.body?.resetForces(!0)}resetTorques(){this.body?.resetTorques(!0)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.body?.wakeUp()}applyForce(e,t){this.body?.addForce(e,!0)}applyImpulse(e){this.body?.applyImpulse(e,!0)}setForce(e,t,i){this.body?.resetForces(!0),this.body?.addForce({x:e,y:t,z:i},!0)}getVelocity(){let e=this.body?.linvel();return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i){if(e instanceof Yp){let n=e;this.body?.setLinvel(n,!0);return}t===void 0||i===void 0||this.body?.setLinvel({x:e,y:t,z:i},!0)}setAngularVelocity(e,t,i){if(e instanceof Yp){let n=e;this.body?.setAngvel(n,!0);return}t===void 0||i===void 0||this.body?.setAngvel({x:e,y:t,z:i},!0)}setTorque(e,t,i){this.setAngularVelocity(e,t,i)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){this.gameObject&&this.destroyed}captureVelocity(){if(this.body){let e=U(this.gameObject);hl.tempPosition.copy(e);let t=e.sub(this._lastPosition);this._lastPosition.copy(hl.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}}},J=hl;L(J,"tempPosition",new zo.Vector3),E([hi(),x()],J.prototype,"mass",2),E([hi(),x()],J.prototype,"useGravity",2),E([hi(),x()],J.prototype,"constraints",2),E([hi(),x()],J.prototype,"isKinematic",2),E([hi(),x()],J.prototype,"drag",2),E([hi(),x()],J.prototype,"angularDrag",2),E([hi(),x()],J.prototype,"detectCollisions",2),E([hi(),x()],J.prototype,"sleepThreshold",2),E([hi(),x()],J.prototype,"collisionDetectionMode",2);import{Mesh as av,Vector3 as or}from"three";var Tt=class extends k{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(J))}onDisable(){this.context.physics.removeBody(this)}};E([x(J)],Tt.prototype,"attachedRigidbody",2),E([x()],Tt.prototype,"isTrigger",2);var Sn=class extends Tt{radius=.5;center=new or(0,0,0);onEnable(){super.onEnable(),this.context.physics.addSphereCollider(this,this.center,this.radius)}};E([x()],Sn.prototype,"radius",2),E([x(or)],Sn.prototype,"center",2);var Pn=class extends Tt{size=new or(1,1,1);center=new or(0,0,0);onEnable(){super.onEnable(),this.context.physics.addBoxCollider(this,this.center,this.size)}};E([x(or)],Pn.prototype,"size",2),E([x(or)],Pn.prototype,"center",2);var sr=class extends Tt{sharedMesh;convex=!1;onEnable(){super.onEnable(),this.sharedMesh?.isMesh||this.gameObject instanceof av&&(this.sharedMesh=this.gameObject),this.sharedMesh?.isMesh&&this.context.physics.addMeshCollider(this,this.sharedMesh,this.convex)}};E([x()],sr.prototype,"convex",2);var Ct=class extends Tt{center=new or(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.addCapsuleCollider(this,this.center,this.height,this.radius)}};E([x(or)],Ct.prototype,"center",2),E([x()],Ct.prototype,"radius",2),E([x()],Ct.prototype,"height",2);var bi=class extends k{center=new qr(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(J),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(J)),this.rigidbody)}onEnable(){let e=this.rigidbody,t=this.gameObject.getComponent(Ct);t||(t=this.gameObject.addNewComponent(Ct)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}_activeGroundCollisions=new Set;onCollisionEnter(e){for(let t of e.contacts)if(t.normal.y>.1){this._activeGroundCollisions.add(e);break}}onCollisionExit(e){this._activeGroundCollisions.delete(e)}get isGrounded(){return this._activeGroundCollisions.size>0}};E([x(qr)],bi.prototype,"center",2),E([x()],bi.prototype,"radius",2),E([x()],bi.prototype,"height",2);var Yt=class extends k{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;animator;lookForward=!0;_currentSpeed=new qr(0,0,0);_currentAngularSpeed=new qr(0,0,0);_temp=new qr(0,0,0);_jumpCount=0;_currentRotation;awake(){this._currentRotation=new lv}update(){this.controller?.isGrounded&&(this._jumpCount=0,this.animator?.SetBool("doubleJump",!1));let e=this.context.input.isKeyPressed("w"),t=this.context.input.isKeyPressed("s"),i=this.context.input.isKeyPressed("a"),n=this.context.input.isKeyPressed("d"),r=this.context.input.isKeyDown(" "),s=e?1:0+t?-1:0;this._currentSpeed.z+=s*this.movementSpeed*this.context.time.deltaTime,this.animator?.SetBool("running",s!=0),this.animator?.SetBool("jumping",this.controller?.isGrounded===!0&&r),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);let a=i?1:0+n?-1:0;if(this._currentAngularSpeed.y+=F.toRadians(a*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){let c=this.context.mainCameraComponent.forward;c.y=0,c.normalize(),this._currentRotation.setFromUnitVectors(new qr(0,0,1),c),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&r&&this.jumpForce>0){let c=this.controller?.isGrounded;if(!this.controller?.isGrounded&&this._jumpCount===1&&(c=!0,this.animator?.SetBool("doubleJump",!0)),c){this._jumpCount+=1;let u=this.controller.rigidbody,l=this._jumpCount===2?2:1;u.applyImpulse(new qr(0,1,0).multiplyScalar(this.jumpForce*l))}}if(this.controller){let c=this.controller?.rigidbody.getVelocity().y;if(c<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new cv),this._raycastOptions.ray.origin.copy(U(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);let u=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);let l=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(u),(l.length&&l[0].distance>2||c<-10)&&this.animator?.SetBool("falling",!0)}else this.animator?.SetBool("falling",!1)}}_raycastOptions=new fe};E([x(bi)],Yt.prototype,"controller",2),E([x()],Yt.prototype,"movementSpeed",2),E([x()],Yt.prototype,"rotationSpeed",2),E([x()],Yt.prototype,"jumpForce",2),E([x(Ye)],Yt.prototype,"animator",2);var Rt=class extends k{canGrab=!0;onPointerClick(e){}},St=class extends k{isUsed=!0;usedBy=null};var ar=class extends ke{},Yr=class extends k{deleteBoxes=[];awake(){this.deleteBoxes=R.findObjectsOfType(ar,this.context)}update(){for(let e of this.deleteBoxes){let t=this.gameObject;e.isInBox(t)===!0&&(R.getComponentInParent(this.gameObject,St)||Oo(this.gameObject,this.context.connection))}}};var lr=class extends k{visibleOn;onEnable(){this.apply()}apply(){this.test()||R.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:uv()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}};E([x()],lr.prototype,"visibleOn",2);var pl;function uv(){if(pl===!0||pl===!1)return pl;let o=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(o=!0)}(navigator.userAgent||navigator.vendor||window.opera),pl=o,o}import*as On from"three";var Ee=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 Wo=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Ee).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Ee).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Ee).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,r,s,a,c,u,l){return e.prep(4,36),e.prep(4,12),e.writeFloat32(l),e.writeFloat32(u),e.writeFloat32(c),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(s),e.writeFloat32(r),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};var Kt=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 Kt).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+4),(t||new Kt).__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 Wo).__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 cr=M("debugsync"),No="STRS";Fo(No,Kt.getRootAsSyncedTransformModel);var Fi=new xt;function ku(o,e,t=!0){Fi.clear();let i=Fi.createString(o);Kt.startSyncedTransformModel(Fi),Kt.addGuid(Fi,i),Kt.addFast(Fi,t);let n=e.worldPosition,r=e.worldEuler,s=e.gameObject.scale;Kt.addTransform(Fi,Wo.createTransform(Fi,n.x,n.y,n.z,r.x,r.y,r.z,s.x,s.y,s.z));let a=Kt.endSyncedTransformModel(Fi);return Fi.finish(a,No),Fi.asUint8Array()}var ht=class extends k{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(){cr&&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(){cr&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new On.Vector3,this._targetRotation=new On.Quaternion,this.lastWorldPos=new On.Vector3,this.lastWorldRotation=new On.Quaternion,this.rb=R.getComponentInChildren(this.gameObject,J),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Jn(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(No,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Ah(this.guid,this.context.connection),this._model=null,this.context.connection.stopListening("joined-room",this.joinedRoomCallback),this.context.connection.stopListenBinary(No,this.receivedDataCallback)}tryGetLastState(){let e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new On.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){cr&&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){oe.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)&&Eh(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){cr&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());let e=this.worldPosition,t=this.worldQuaternion;if(this._model.isOwned&&!this.receivedUpdate){let r=e.distanceTo(this.lastWorldPos),s=t.angleTo(this.lastWorldRotation),a=this._model.hasOwnership||this.fastMode?1e-4:.001;(r>a||s>a)&&(this._model.hasOwnership?this._needsUpdate=!0:(cr&&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),oe.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){let s=this._receivedFastUpdate||this.fastMode?.5:.3,a=!1;if(this.interpolatePosition&&this._targetPosition){let c=this.worldPosition;c.lerp(this._targetPosition,s),this.worldPosition=c,a=!0}if(this.interpolateRotation&&this._targetRotation){let c=this.worldQuaternion;c.slerp(this._targetRotation,s),this.worldQuaternion=c,a=!0}a&&oe.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&&(cr&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic),this.gameObject.position.distanceTo(new On.Vector3(0,0,0))>1e3&&(cr&&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)){cr&&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=ku(this.guid,this,!!n);this.context.connection.sendBinary(r)}}};import*as Y from"three";import{Euler as jv,EventDispatcher as Hv,Group as Fv,Matrix4 as af,Mesh as Bv,MeshBasicMaterial as Uv,Object3D as sf,Quaternion as Uu,RingGeometry as Gv,Vector3 as lf}from"three";var fl=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 u=document.createElementNS("http://www.w3.org/2000/svg","svg");u.setAttribute("width",38),u.setAttribute("height",38),u.style.position="absolute",u.style.right="20px",u.style.top="20px",u.addEventListener("click",function(){d.end()}),c.appendChild(u);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),u.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 d=null;async function h(_){_.addEventListener("end",b),await e.xr.setSession(_),i.textContent="STOP AR",t.domOverlay.root.style.display="",d=_}function b(){d.removeEventListener("end",b),i.textContent="START AR",t.domOverlay.root.style.display="none",d=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(){d===null?navigator.xr.requestSession("immersive-ar",t).then(h):d.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 s(){r(),i.textContent="AR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="ARButton",i.style.display="none",a(i),navigator.xr.isSessionSupported("immersive-ar").then(function(c){c?n():s()}).catch(s),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",a(c),c}}};var ml=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 u(d){d.addEventListener("end",l),await e.xr.setSession(d),i.textContent="EXIT VR",c=d}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 d={optionalFeatures:["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]};navigator.xr.requestSession("immersive-vr",d).then(u)}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 s(){r(),i.textContent="VR NOT SUPPORTED"}function a(c){c.style.position="absolute",c.style.bottom="20px",c.style.padding="12px 6px",c.style.border="1px solid #fff",c.style.borderRadius="4px",c.style.background="rgba(0,0,0,0.1)",c.style.color="#fff",c.style.font="normal 13px sans-serif",c.style.textAlign="center",c.style.opacity="0.5",c.style.outline="none",c.style.zIndex="999"}if("xr"in navigator)return i.id="VRButton",i.style.display="none",a(i),navigator.xr.isSessionSupported("immersive-vr").then(function(c){c?n():s(),ml.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",a(c),c}}static registerSessionGrantedListener(){if("xr"in navigator)try{navigator.xr.addEventListener("sessiongranted",()=>{console.log("Received session granted event"),ml.xrSessionIsGranted=!0})}catch(e){console.error(e)}}},Qo=ml;L(Qo,"xrSessionIsGranted",!1);Qo.registerSessionGrantedListener();import*as gl from"three";var Kp=ra(ja(),1);import{AudioAnalyser as dv}from"three";var qo="noVoip",pt=M("debugvoip"),hv=M("voip");var Mu=class{id;constructor(e){this.id=e}};var Iu=class{peer;voip;userId;peerId;call=null;callErrorListener=null;stream=null;constructor(e,t,i,n){this.voip=e,this.peer=t,this.userId=i,this.peerId=n}close(){pt&&console.log("close voip call"),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.open&&this.call.close(),this.stream?.getTracks().forEach(function(e){e.stop()})}updateMute(e){if(!this.stream)return;let t=this.stream?.getAudioTracks();for(let i of t)i.enabled=!e}async startVoipCall(){if(!await Ke.HasMicrophonePermissions()){console.warn("no permission to use microphone, can not start call");return}pt&&console.log("start voip call"),this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),this.updateMute(this.voip.muteOutput),pt&&console.log(this.stream),this.call=this.peer.call(this.peerId,this.stream,{metadata:{userId:this.userId}}),this.call.on("error",t=>{console.error(t)}),this.call.on("stream",t=>{pt&&console.log("received stream from remote again",t)}),this.peer.on("close",this.onCallClose.bind(this)),this.callErrorListener=t=>{t.message.includes(this.peerId)?(console.log("Could not connect to "+this.peerId),this.callErrorListener&&this.peer.off("error",this.callErrorListener),this.call&&this.call.close(),this.stream?.getTracks().forEach(function(i){i.stop()}),this.stream=null):console.error(t)},this.peer.on("error",this.callErrorListener)}onCallClose(e){pt&&console.log("call closed",e)}},Du=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,ie.userInteractionRegistered||pt&&console.log("Incoming call, waiting for user interaction before opening audio"),ie.registerWaitForAllowAudio(async()=>{if(this.call.open&&!this.closed){pt&&console.log("Setup audio and begin listening"),this.stream=new MediaStream([e]);let t=new gl.AudioListener;this.audio=new gl.Audio(t),this.audio.setVolume(this.voip.muteInput?0:1),this.audio.setMediaStreamSource(this.stream);let i=document.createElement("audio");this.audioElement=i,i.style.display="none",document.body.appendChild(i),i.srcObject=this.stream,i.sinkId!==void 0&&navigator.mediaDevices.enumerateDevices().then(n=>{if(!!i){console.log(n);for(let r of n)if(r.label==="Speakerphone"){i.sinkId=r.deviceId;break}}}),pt&&console.log("call is setup, you should hear something now"),this.analyzer=new dv(this.audio,32)}}))}close(){this.closed=!0,this.call?.open&&this.call.close(),this.audio?.disconnect(),this.stream?.getTracks().forEach(e=>{e.stop()}),this.stream=null,this.audioElement&&this.audioElement.remove()}},Ke=class extends k{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(M(qo)){console.log("VOIP is disabled by url parameter: "+qo);return}if(this.requireParam&&!hv){console.debug("VOIP must be enabled explicitly by url parameter");return}this.peer=new Kp.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 Iu(this,this.peer,this.context.connection.connectionId,e.peerId);this.connections[e.id]=i,i.startVoipCall()}}}),this.context.connection.beginListen("user-left-room",e=>{let{userId:t}=e,i=this.connections[t];this.connections[t]=null,i&&i.close();let n=this.currentIncomingCalls[t];pt&&console.log("UserLeftRoom",e,t,n),n&&(n.close(),this.currentIncomingCalls[t]=null)}),this.peer.on("open",this.onOpenPeerConnection.bind(this))}onEnable(){}onDisable(){console.log("TODO: close all");for(let e in this.currentIncomingCalls)this.currentIncomingCalls[e]?.close(),this.connections[e]?.close()}async onOpenPeerConnection(e){pt&&console.log("Peer connection established and received id"),this.model=new Mu(e),this.context.connection.send("peer-update-id",this.model,1),this.peer&&(this.peer.on("call",this.onReceiveCall.bind(this)),this.peer.on("connection",function(t){pt&&console.log("CONNECTION",t),t.on("data",function(i){pt&&console.log("Received",i)})}))}async onReceiveCall(e){let{metadata:t}=e;console.assert(t.userId);let{userId:i}=t,{peer:n}=e,r=this.currentIncomingCalls[i];if(r&&r.close(),pt&&console.log("received call"),await Ke.HasMicrophonePermissions()){let s=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});e.answer(s)}else e.answer(null);this.currentIncomingCalls[i]=new Du(this,this.gameObject,e),e.on("stream",s=>{pt&&console.log("receive caller stream, will setup audio now"),this.currentIncomingCalls[i]?.openAudioStream(s)}),e.on("error",console.error)}static async HasMicrophonePermissions(){return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}};import{Matrix4 as Bs}from"three";var Pt=class extends k{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 Bs;_selectStartFn=this.onSelectStart.bind(this);_selectEndFn=this.onSelectEnd.bind(this);start(){let e=R.findObjectOfType(z);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 Bs().fromArray(i.transform.matrix).invert()),!0):!1}placeAt(e,t){if(this._placementPose||(this._placementPose=new Bs),this._placementPose.copy(t),e){if(this.invertForward){let i=new Bs().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)),oe.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 Bs().makeScale(e,e,e),this._placementPose),t.matrix.decompose(t.position,t.quaternion,t.scale),t.updateMatrixWorld(),console.log("Place",t.position))}};E([x()],Pt.prototype,"invertForward",2),E([x()],Pt.prototype,"arScale",1);import{BoxHelper as _v,BufferGeometry as xv,Color as nf,Euler as wv,Layers as Ev,Line as Cv,Mesh as Tv,MeshBasicMaterial as Rv,Quaternion as yl,Ray as Sv,SphereGeometry as Pv,Vector2 as Ov,Vector3 as _i}from"three";import{OculusHandModel as kv}from"three/examples/jsm/webxr/OculusHandModel.js";import{OculusHandPointerModel as Mv}from"three/examples/jsm/webxr/OculusHandPointerModel.js";import{XRControllerModelFactory as Iv}from"three/examples/jsm/webxr/XRControllerModelFactory.js";import{GLTFLoader as Dv}from"three/examples/jsm/loaders/GLTFLoader.js";import*as $p from"three";import{Quaternion as pv,Vector3 as bl}from"three";var Yo=M("debugflags");var Au=class{Mask=17;Has(e){let t=this.Mask&e;return Yo&&console.log("HAS",e,this.Mask,"Result="+t),t!==0}Set(e){this.Mask=e,_e.Apply()}Enable(e){this.Mask|=e,_e.Apply()}Disable(e){this.Mask&=~e,_e.Apply()}Toggle(e){this.Mask^=e,_e.Apply()}EnableAll(){this.Mask=-1,_e.Apply()}DisableAll(){this.Mask=0,_e.Apply()}},ft=Au;L(ft,"Global",new Au);var Bi=class extends k{static Apply(){for(let e of this.registry)e.UpdateVisible(ft.Global)}awake(){Bi.registry.push(this)}onEnable(){Bi.firstApply||(Bi.firstApply=!0,Bi.Apply())}onDestroy(){let e=Bi.registry.indexOf(this);e>=0&&Bi.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),Yo&&console.log(i),Bi.buffer.Mask=i,e=Bi.buffer);let n=e;if(n?(Yo&&console.log("use passed in mask"),t=n.Has(this.visibleIn)):(Yo&&console.log("use global mask"),ft.Global.Has(this.visibleIn)),t!==void 0)if(t)Yo&&console.trace("is visible",this.name,this.gameObject.uuid),R.setActive(this.gameObject,!0);else{if(Yo&&console.trace("is not visible",this.name,this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}},_e=Bi;L(_e,"registry",[]),L(_e,"firstApply"),L(_e,"buffer",new ft);import{Object3D as Lu}from"three";var ur=M("debugavatar"),vi=class extends k{static getAvatar(e){return e>=0&&e<vi.instances.length?vi.instances[e]:null}static onAvatarMarkerCreated(e){return vi._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return vi._onAvatarMarkerDestroyed.push(e),e}connectionId;avatar;awake(){vi.instances.push(this),ur&&console.log(this);for(let e of vi._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){vi.instances.splice(vi.instances.indexOf(this),1);for(let e of vi._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}setVisible(e){this.avatar&&("setVisible"in this.avatar?this.avatar.setVisible(e):R.setActive(this.avatar,e))}},se=vi;L(se,"instances",[]),L(se,"_onNewAvatarMarkerAdded",[]),L(se,"_onAvatarMarkerDestroyed",[]);var Us=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 bl(1,1,1);handLeftScale=new bl(1,1,1);handRightScale=new bl(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 Lu;_handLeftTarget=new Lu;_handRightTarget=new Lu;_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),oe.markDirty(this.head),this._canInterpolate=!0;let r=this.isLocalAvatar?this.head:this._headTarget;if(r.position.set(e.position.x,e.position.y,e.position.z),r.quaternion.set(e.rotation.x,e.rotation.y,e.rotation.z,e.rotation.w),r.scale.set(e.scale,e.scale,e.scale),r.scale.multiply(this.headScale),this.handLeft){let s=this.isLocalAvatar?this.handLeft:this._handLeftTarget;s.position.set(e.posLeftHand.x,e.posLeftHand.y,e.posLeftHand.z),s.quaternion.set(e.rotLeftHand._x,e.rotLeftHand._y,e.rotLeftHand._z,e.rotLeftHand._w),s.quaternion.multiply(Us.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handLeftScale),oe.markDirty(this.handLeft)}if(this.handRight){let s=this.isLocalAvatar?this.handRight:this._handRightTarget;s.position.set(e.posRightHand.x,e.posRightHand.y,e.posRightHand.z),s.quaternion.set(e.rotRightHand._x,e.rotRightHand._y,e.rotRightHand._z,e.rotRightHand._w),s.quaternion.multiply(Us.invertRotation),s.scale.set(e.scale,e.scale,e.scale),s.scale.multiply(this.handRightScale),oe.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(){ur&&console.log("Destroy avatar",this.guid),this.root?.removeFromParent(),this.avatarMarker?.destroy(),this.lastAvatarId=null,this.head&&me.Remove(this.context,this.head)}updateVisibility(){let e=this.root;e&&R.setActive(e,this._isVisible)}async setupCustomAvatar(e){if(ur&&console.log("LOAD",e,this),!e||typeof e=="string"&&e.length<=0)return!1;this.head&&me.Remove(this.context,this.head);let t=e;if(t?.loadAssetAsync!==void 0){await t.loadAssetAsync();let n=t.asset;R.setActive(n,!1),e=R.instantiate(n),R.setActive(e,!0)}ur&&console.log(e);let i=await Us.loader.getOrCreateNewAvatarInstance(this.context,e);if(ur&&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=R.addNewComponent(this.root,se),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&&me.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(...R.getComponentsInChildren(this.root,_e)),this.flags.length<=0&&this.head){let n=R.addNewComponent(this.head,_e);n.visibleIn=20,this.flags.push(n),ur&&console.log("Added flag to head: "+n.visibleIn,this.head.name)}return ur&&console.log("[Avatar], is Local? ",this.isLocalAvatar,this.root),this.updateFlags(),this.updateVisibility(),!0}else return ur&&console.warn("build avatar failed"),!1}},Ot=Us;L(Ot,"loader",new Rn),L(Ot,"invertRotation",new pv().setFromAxisAngle(new bl(0,1,0),Math.PI));var me=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??V.Current?.time.time;return}}}};L(me,"Pois",[]),L(me,"LastChangeTime",0);var ju=class{guid;position=new $p.Vector3},Ui=class extends k{set controlledTarget(e){this.target=e;let t=O.get("MoveRandom");if(t&&this.target){let i=R.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new ju;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=R.getComponentInParent(this.gameObject,se),this.avatar){let e=R.getComponentInParent(this.gameObject,se);this._model=new Jn(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&&te(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(me.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=me.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){let t=U(this._currentTargetObject);te(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=me.Pois;if(t.length>0){let i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}};import*as vl from"three-mesh-ui";import{OrbitControls as mv}from"three/examples/jsm/controls/OrbitControls";import{Object3D as fv}from"three";var Gi=class extends k{constraintActive=!0;locked=!1;sources=[]};E([x(fv)],Gi.prototype,"sources",2);import*as Gs from"three";var ef=M("nocamlimits"),Je=class extends k{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 Gs.Vector3,this._startedListeningToKeyEvents=!1}onEnable(){this._enableTime=this.context.time.time;let t=R.getComponent(this.gameObject,ae)?.cam;this._controls||(console.assert(t!=null,"Missing camera",this),t&&(this._cameraObject=t),this._controls=new mv(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"?ef||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):ef||(this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom),this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._startedListeningToKeyEvents||(this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(window.document.body)))}onDisable(){this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}onDestroy(){this._controls?.dispose()}start(){if(this._controls){let e=R.getComponent(this.gameObject,ae);if(e&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");let t=new Gs.Vector3(0,0,-1).applyMatrix4(e.cam.matrixWorld);this.setTarget(t,!0)}}this.startCoroutine(this.startRaycastDelayed())}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){let e=new fe;e.screenPoint=new Gs.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.context.isInXR&&(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&&R.isActiveInHierarchy(t.object)){if(this._lookTargetPosition.copy(t.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;let i=U(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition)}break}}};E([x(Gi)],Je.prototype,"lookAtConstraint",2);var Jt=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 bv}from"three";var vv=M("debugeventsystem"),Vi=class extends k{static createIfNoneExists(e){this.didSearchEventSystem||(this.didSearchEventSystem=!0,Vi.systems.length<=0&&Vi.systems.push(...R.findObjectsOfType(Vi,e)));for(let i of Vi.systems)if(i.context===e)return;let t=new bv;R.addNewComponent(t,Vi),e.scene.add(t)}static ensureUpdateMeshUI(e,t){yi.update(e,t)}static markUIDirty(e){yi.markDirty()}static get instance(){return this.systems[0]}orbitControl=null;orbitControlWasEnabled=!1;raycaster=[];constructor(){super(),Vi.systems.push(this)}onDestroy(){Vi.systems.splice(Vi.systems.indexOf(this),1)}start(){}register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){let t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}_selectStartFn;_selectEndFn;_selectUpdateFn;onEnable(){let e=new Map;this._selectStartFn??=(i,n)=>{if(!n.grab)return;yi.resetLastSelected();let r=new Jt;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=!1,e.set(i,n.grab),n.grab&&!this.handleEvents(n.grab,r)&&(n.grab=null)},this._selectEndFn??=(i,n)=>{if(!n.grab)return;let r=new Jt;r.inputSource=i,r.isDown=i.selectionDown,r.isUp=i.selectionUp,r.isPressed=i.selectionPressed,r.isClicked=i.selectionClick,this.handleEvents(n.grab,r);let s=e.get(i);if(e.set(i,null),s)for(let a=0;a<this.raisedPointerDownEvents.length;a++){let c=this.raisedPointerDownEvents[a];this.raisedPointerDownObjects[a]===s&&c&&(c.onPointerUp?.call(c,r),this.raisedPointerDownEvents.splice(a,1),this.raisedPointerDownObjects.splice(a,1),a--)}};let t=new fe;this._selectUpdateFn??=i=>{t.ray=i.getRay();let n=this.performRaycast(t);if(!n)return;let r=new Jt;r.inputSource=i,this.handleIntersections(n,r)},Z.addEventListener("select-start",this._selectStartFn),Z.addEventListener("select-end",this._selectEndFn),Z.addEventListener("update",this._selectUpdateFn),this.context.pre_update_callbacks.push(this.onBeforeUpdate.bind(this)),this.context.input.addEventListener("pointerdown",this.onPointerDown.bind(this))}onDisable(){Z.removeEventListener("select-start",this._selectStartFn),Z.removeEventListener("select-end",this._selectEndFn),Z.removeEventListener("update",this._selectUpdateFn)}onPointerDown(){this.onBeforeUpdate()}lastPointerEvent=null;objectsHoveredThisFrame=[];objectsHoveredLastFrame=[];raisedPointerDownEvents=[];raisedPointerDownObjects=[];_didMove=!1;onBeforeUpdate(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),z.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 Jt(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=R.getComponent(this.context.mainCameraComponent.gameObject,Je)??null,i&&(n=i.enabled,i.enabled=!1)),this.handleIntersections(e,t),i&&(this.orbitControl=i,this.orbitControl?.enabled?(this.orbitControlWasEnabled=this.orbitControl.enabled,this.orbitControl.enabled=!1):this.orbitControl&&!this.context.input.mousePressed&&(this.orbitControl.enabled=this.orbitControlWasEnabled,this.orbitControl=null))}_tempComponentsArray=[];onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(let t of this.raisedPointerDownEvents)t.onPointerUp&&t.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(let t of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(t)<0){this._tempComponentsArray.length=0;let i=R.getComponentsInParent(t,k,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 s=r;s.onPointerExit&&s.onPointerExit(this.lastPointerEvent)}}let e=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=e}_sortedHits=[];performRaycast(e){if(!this.raycaster)return null;this._sortedHits.length=0;for(let t of this.raycaster){if(!t.activeAndEnabled)continue;let i=t.performRaycast(e);i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}handleIntersections(e,t){if(!e||e.length<=0)return!1;e=this.sortCandidates(e);for(let i of e){let{object:n}=i;if(this.handleEvents(n,t))return!0}return!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){let i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(let t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}handleEventsArray=[];out={};handleEvents(e,t){if(!this.testIsVisible(e))return t.isClicked&&vv&&console.log("not allowed",e),!1;let i=e;t.object=e,this.lastPointerEvent=t;let n=e.parent,r=!1,s=t.isClicked??!1,a=null;if(n&&n.isUI){let c=(t.isPressed||t.isClicked)??!1;if(n[kt]){let u=n[kt].gameObject;if(u){if(!Zt.isInteractable(u,this.out))return this.out.canvasGroup?.interactable??!1;a=this.out.canvasGroup??null;let d=this.handleMeshUIIntersection(e,c);e=u,r=!0}}if(!r&&this.handleMeshUiObjectWithoutShadowDom(n,c))return!0}if(this.objectsHoveredThisFrame.push(e),a===null||a.interactable){let c=this.objectsHoveredLastFrame.indexOf(e)>=0;this.handleEventsArray.length=0;let u=R.getComponentsInParent(e,k,this.handleEventsArray);for(let l=0;l<u.length;l++){if(t.used)return!0;if(u[l].destroyed)continue;let d=u[l];d.interactable!==!1&&(d.onPointerEnter&&(c||d.onPointerEnter(t)),t.isDown&&d.onPointerDown&&!this.raisedPointerDownEvents.includes(d)&&(d.onPointerDown(t),this.raisedPointerDownEvents.push(d),this.raisedPointerDownObjects.push(i)),t.isUp&&d.onPointerUp&&d.onPointerUp(t),t.isClicked&&d.onPointerClick&&d.onPointerClick(t))}}return!0}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){let i=yi.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&yi.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){let t=this.currentActiveMeshUIComponents[e];yi.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?R.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}},Ve=Vi;L(Ve,"didSearchEventSystem",!1),L(Ve,"systems",[]);var yi=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}};L(yi,"lastSelected",null),L(yi,"lastUpdateFrame",[]),L(yi,"needsUpdate",!1);import{AxesHelper as yv}from"three";var Ko="./include";vl.Block.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};var kt=Symbol("shadowDomOwner"),Me=class extends k{isRoot(){return this.Root?.gameObject===this.gameObject}markDirty(){Ve.markUIDirty(this.context)}shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=R.getComponentInParent(this.gameObject,zi)),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=R.getComponentInParent(i,Me),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have a UI element outside a Canvas?`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[kt]=this,e.traverse(r=>{r[kt]===void 0&&(r[kt]=this)});let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{let r=this._parentComponent.shadowComponent;r&&(r?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),Mi&&e.add(new yv(.5)),this.onAfterAddedToScene(),n&&vl.update()}set(e){}traverseOwnedShadowComponents(e,t,i){if(!!e&&e[kt]===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)}},zi=class extends Me{awake(){super.awake()}};var Zt=class{static getObject(e){let t=e[kt];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;let i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;let n=ci(e,r=>{if(r.isGraphic===!0)return r},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),n?.raycastTarget!==!1}static tryFindCanvasGroup(e){if(!e)return null;let t=ci(e,i=>{let n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}};var Vs=M("debugwebxrcontroller");var dr=class extends k{},Ie=class extends k{static CreateRaycastLine(){let e=new Cv(this.geometry),t=e.material;return t.color=this.raycastColor,e.layers.set(2),e.name="line",e.scale.z=1,e}static CreateRaycastHitPoint(){let e=new Pv(.5,22,22),t=new Rv({color:this.raycastColor}),i=new Tv(e,t);return i.visible=!1,i.layers.set(2),i}static Create(e,t,i,n){let r=i?R.addNewComponent(i,Ie,!1):new Ie;r.webXR=e,r.index=t,r.type=n;let s=e.context;r.controller=s.renderer.xr.getController(t),r.controllerGrip=s.renderer.xr.getControllerGrip(t),r.controllerModel=this.Factory.createControllerModel(r.controller),r.controllerGrip.add(r.controllerModel),r.hand=s.renderer.xr.getHand(t);let a=new Dv;xn(a,s),r.webXR.handModelPath&&r.webXR.handModelPath!==""&&a.setPath("/"+ki(e.sourceId,r.webXR.handModelPath));let c=new kv(r.hand,a);return r.hand.add(c),r.hand.traverse(u=>u.layers.set(2)),r.handPointerModel=new Mv(r.hand,r.controller),r.controller.addEventListener("connected",u=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2),setTimeout(()=>{r.setControllerLayers(r.controllerModel,2),r.setControllerLayers(r.controllerGrip,2),r.setControllerLayers(r.hand,2)},1e3)}),r.hand.addEventListener("connected",u=>{if(u.data.hand){e.Rig&&e.Rig.add(r.hand),r.type=0,r.handPointerModel.traverse(h=>h.layers.set(2)),r.handPointerModel.pointerObject?.traverse(h=>h.layers.set(2));let d=r.hand.joints;if(d)for(let h of Object.keys(d)){let b=d[h];b.parent||r.hand.add(b)}}}),r}static addEventListener(e,t){let i=this.eventSubs[e]??[];i.push(t),this.eventSubs[e]=i}static removeEventListener(e,t){if(!t)return;let i=this.eventSubs[e]??[],n=i.indexOf(t);n>=0&&i.splice(n,1),this.eventSubs[e]=i}webXR;index=-1;controllerModel;controller;controllerGrip;hand;handPointerModel;grabbed=null;input=null;type=0;showRaycastLine=!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 yl),he(e).multiply(this._wristQuaternion.setFromEuler(new wv(-Math.PI/4,0,0)))):null}movementVector=new _i;worldRot=new yl;joystick=new Ov;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=Ie.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=Ie.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),Vs&&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 yl;update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));let e=Ie.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(he(this.controller),this.useSmoothing?t:1);let i=U(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine)if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed,te(this.raycastLine,i);let n=this.hand.joints;if(n&&n.wrist&&this.grabbed&&this.grabbed.isCloseGrab){let s=this.getWristQuaternion();s&&this.rayRotation.copy(s)}$e(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=this.showRaycastLine,$e(this.raycastLine,this.rayRotation),te(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*Ie.MovementSpeedFactor,r=2,s=F.clamp01(this.joystick.length()*2),a=this.joystick.x>0?1:-1,c=Math.pow(this.joystick.x,r);c*=a,c*=s;let u=this.joystick.y>0?1:-1,l=Math.pow(this.joystick.y,r);l*=u,c*=s,t.getWorldQuaternion(this.worldRot),this.movementVector.set(c,0,l),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(n*this.context.time.deltaTime),t.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(t,i);break;case"right":let d=this.joystick.x,h=Math.abs(d);if(h<.4)this.didRotate=!1;else if(h>.5&&!this.didRotate){let b=d>0?-1:1;t.rotateY(F.toRadians(30*b)),this.didRotate=!0}this.runTeleport(t,i);break}}runTeleport(e,t){let i=-this.joystick.y;if(this.hand?.visible&&!this.grabbed){let a=this.handPointerModel.isPinched();a&&this._pinchStartTime===void 0&&(this._pinchStartTime=this.context.time.time),a&&this._pinchStartTime&&this.context.time.time-this._pinchStartTime>.8&&(i=this.handPointerModel.isPinched()?1:0),a||(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,s=null;if(t&&this.input&&!this.input.hand)for(let a=0;a<t.length;a++){let c=t[a];if(a===4)if(c.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;let u=this.webXR.Rig;if(u)if(r){r=!1,u.scale.set(1,1,1),s=1,Ie.MovementSpeedFactor=1;let l=this.context.mainCamera;Ie.PreviousCameraFarDistance&&(l.far=Ie.PreviousCameraFarDistance)}else{r=!0,n=!0,s=.1,Ie.MovementSpeedFactor=s*2;let l=this.context.mainCamera;Ie.PreviousCameraFarDistance=l.far,l.far/=s}}else c.pressed||(this.didChangeScale=!1)}if(n){if(!this.didTeleport){let a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){let c=a[0];if(r||this.isValidTeleportTarget(c.object)){let u=c.point;te(e,u)}}}}else i<.1&&(this.didTeleport=!1);s!==null&&(e.scale.set(s,s,s),e.updateMatrixWorld())}isValidTeleportTarget(e){return R.getComponentInParent(e,dr)!=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=Ie.raycastColor:n.color=Ie.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;let n=F.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(),Vs&&console.log("onHandleSelectStart","close grab? "+t,"intersections",e),e&&e.length>0)for(let i of e){let n=i.object;this.lastSelectStartObject=n;let r={selected:n,grab:n},s=Ie.eventSubs["select-start"];if(s&&s.length>0)for(let a of s)a(this,r);r.grab!==n&&Vs&&console.log("Grabbed object changed","original",n,"new",r.grab),r.grab&&(this.grabbed=nt.TryTake(this,r.grab,i,t));break}else{let i=Ie.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=Ie.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||R.isActiveInHierarchy(e)===!1||Zt.isInteractable(e)===!1)}setControllerLayers(e,t){if(!!e&&(e.layers.set(t),e.children))for(let i of e.children)this.grabbed?.selected===i||this.grabbed?.selectedMesh===i||this.setControllerLayers(i,t)}getRay(){let e=new Sv;return e.origin.copy(U(this.controller)),e.direction.set(0,0,-1).applyQuaternion(this.rayRotation),e}closeGrabBoundingBoxHelper;overlap(){let e=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Vs&&(!this.closeGrabBoundingBoxHelper&&e&&(this.closeGrabBoundingBoxHelper=new _v(e,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&e&&this.closeGrabBoundingBoxHelper.setFromObject(e)),!e)return new Array;let t=U(e).clone();return this.context.physics.sphereOverlap(t,.02)}raycast(){let e=new fe;e.layerMask=new Ev,e.layerMask.set(0),e.layerMask.disable(2),e.ray=this.getRay();let t=this.context.physics.raycast(e);for(let i=0;i<t.length;i++){let n=t[i],r=n.object;if(!this.testIsVisible(r)){t.splice(i,1),i--;continue}n.object=Zt.getObject(r);break}return t}},Z=Ie;L(Z,"Factory",new Iv),L(Z,"raycastColor",new nf(.9,.3,.3)),L(Z,"raycastNoHitColor",new nf(.6,.6,.6)),L(Z,"geometry",new xv().setFromPoints([new _i(0,0,0),new _i(0,0,-1)])),L(Z,"handModels",{}),L(Z,"eventSubs",{}),L(Z,"PreviousCameraFarDistance"),L(Z,"MovementSpeedFactor",1);var it=class{static AddEventListener(e,t){return it.Events[e]||(it.Events[e]=[]),it.Events[e].push(t),t}static RemoveEventListener(e,t){if(!t||!it.Events[e])return;let i=it.Events[e].indexOf(t);i>=0&&it.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=R.getComponentInParent(t,Rt);if(r)t=r.gameObject;else return Vs&&console.warn("Prevented taking object that is not interactable",t),null;let s=t,a=R.getComponentInParent(t,ht);a&&(a.requestOwnership(),s=a.gameObject);for(let u of this.Current)if(u.selected===s)return u.controller===e||(u.free(),u.Take(e,s,t,a,r,i,n)),u;let c=new it;return c.Take(e,s,t,a,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,s,a){if(console.assert(t!==null,"Expected object to be taken but was",t),e.isUsingHands?this.positionSource=a?e.wrist:e.controller:this.positionSource=e.controller,!this.positionSource)return console.warn("No position source"),this;let c={controller:e,take:t,hit:i,sync:n,interactable:r};it.Events.WillTake?.forEach(b=>b(this,c));let u=i;u?.material&&(this.originalMaterial=u.material,Array.isArray(u.material)||(u.material=u.material.clone(),u.material&&u.material.emissive&&(u.material.emissive.b=.2))),this.selected=t,this.selectedParent||(this.selectedParent=t.parent),this.selectedMesh=u,this.controller=e,this.interactable=r,this.isCloseGrab=a,this.didReparent=!1,this.sync=n,this.grabTime=e.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=R.addNewComponent(this.selected,St),this.rigidbodies=R.getComponentsInChildren(this.selected,J),U(this.positionSource,this.lastControllerWorldPos);let l=()=>a?this.lastControllerWorldPos.clone():s.point.clone();this.grabDistance=l().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(l());let d=e.isUsingHands&&a?this.controller.getWristQuaternion().clone():e.rayRotation.clone();he(this.selected,this.localQuaternionToGrab).premultiply(d.invert());let h=this.controller.webXR.Rig;return h&&this.rigPositionLastFrame.copy(U(h)),me.Add(e.context,this.selected),it.Register(this),this.sync&&(this.sync.fastMode=!0),it.Events.DidTake?.forEach(b=>b(this,c)),this}free(){if(!this.selected)return;let e={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};it.Events.WillFree?.forEach(n=>n(this,e)),me.Remove(this.controller.context,this.selected),it.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.setVelocity(n.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,it.Events.DidFree?.forEach(n=>n(this,e))}grabPoint=new _i;localPositionOffsetToGrab=null;localPositionOffsetToGrab_worldSpace=new _i;localQuaternionToGrab=new yl(0,0,0,1);targetDir=null;quaternionLerp=null;controllerDir=new _i;controllerWorldPos=new _i;lastControllerWorldPos=new _i;controllerPosDelta=new _i;totalChangeAlongDirection=0;rigPositionLastFrame=new _i;controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),U(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=U(e),n=this.rigPositionLastFrame.sub(i);this.controllerPosDelta.add(n),this.rigPositionLastFrame.copy(i)}return this.controllerDir.dot(this.controllerPosDelta)}update(){if(this.rigidbodies)for(let e of this.rigidbodies)e.resetVelocities();if(this.sync&&this.controller&&this.controller.context.connection.isInRoom&&this.controller.context.time.time-this.grabTime>3&&this.sync.hasOwnership()===!1&&(console.log("no ownership, will leave",this.sync.guid),this.free()),!(this.interactable&&!this.interactable.canGrab)){if(!this.didReparent&&this.selected&&this.controller){let e=this.controller.webXR.Rig?.scale.x??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let t=1;this.controller.type===0&&(t=Math.max(0,1+this.totalChangeAlongDirection*2/e),t=t*t*t),this.grabDistance/e<.8&&(t=1),this.targetDir||(this.targetDir=new _i),this.targetDir.set(0,0,-this.grabDistance*t);let i=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),n=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=n.clone()),this.quaternionLerp.slerp(n,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),$e(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(i),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(U(this.selected)),i.sub(this.localPositionOffsetToGrab_worldSpace)),te(this.selected,i)}if(this.rigidbodies!=null)for(let e of this.rigidbodies)e.wakeUp(),e.setBodyFromGameObject({x:0,y:0,z:0});oe.markDirty(this.selected,!0)}}},nt=it;L(nt,"Events",{}),L(nt,"Current",[]);var kn=class extends k{awake(){}};import{Quaternion as zs,Vector3 as _l,Vector4 as Av}from"three";var Wi=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 Se=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 Se).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsVrUserStateBuffer(e,t){return e.setPosition(e.position()+4),(t||new Se).__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 Ee).__init(this.bb_pos+t,this.bb):null}rotation(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Wi).__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 Ee).__init(this.bb_pos+t,this.bb):null}posRightHand(e){let t=this.bb.__offset(this.bb_pos,18);return t?(e||new Ee).__init(this.bb_pos+t,this.bb):null}rotLeftHand(e){let t=this.bb.__offset(this.bb_pos,20);return t?(e||new Wi).__init(this.bb_pos+t,this.bb):null}rotRightHand(e){let t=this.bb.__offset(this.bb_pos,22);return t?(e||new Wi).__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 rf=M("debugxr"),Ws=M("debugavatar");var Bu="VRUS";Fo(Bu,Se.getRootAsVrUserStateBuffer);function Fu(){return new Date().getTime()}function Lv(o){let e=o&4294967295,t=o/Math.pow(2,32)&1048575;return Xe.create(e,t)}var Ns=class{guid;time;avatarId;position=new _l;rotation=new Av;scale=1;posLeftHand=new _l;posRightHand=new _l;rotLeftHand=new zs;rotRightHand=new zs;constructor(e){this.guid=e}update(e,t,i,n,r){this.time=Fu(),this.avatarId=r,this.position.set(t.x,t.y,t.z),e&&this.position.applyMatrix4(e.matrixWorld);let s=Ns.quat0,a=Ns.quat1;s.set(i.x,i.y,i.z,i.w),s=s.multiplyQuaternions(s,Ns.invertRotation),e&&(e.getWorldQuaternion(a),s.multiplyQuaternions(a,s)),this.rotation.set(s.x,s.y,s.z,s.w),this.scale=e.scale.x;let c=n.LeftController?.controllerGrip;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand));let u=n.RightController?.controllerGrip;if(u&&(u.getWorldPosition(this.posRightHand),u.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);Se.startVrUserStateBuffer(e),Se.addGuid(e,i),Se.addTime(e,Lv(this.time)),Se.addAvatarId(e,n),Se.addPosition(e,Ee.createVec3(e,this.position.x,this.position.y,this.position.z)),Se.addRotation(e,Wi.createVec4(e,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),Se.addScale(e,this.scale),Se.addPosLeftHand(e,Ee.createVec3(e,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),Se.addPosRightHand(e,Ee.createVec3(e,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),Se.addRotLeftHand(e,Wi.createVec4(e,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),Se.addRotRightHand(e,Wi.createVec4(e,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));let r=Se.endVrUserStateBuffer(e);e.finish(r,Bu);let s=e.asUint8Array();t.sendBinary(s)}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 s=t.posLeftHand();s&&this.posLeftHand.set(s.x(),s.y(),s.z());let a=t.posRightHand();a&&this.posRightHand.set(a.x(),a.y(),a.z());let c=t.rotLeftHand();c&&this.rotLeftHand.set(c.x(),c.y(),c.z(),c.w());let u=t.rotRightHand();u&&this.rotRightHand.set(u.x(),u.y(),u.z(),u.w()),this.scale=t.scale()}},Mt=Ns;L(Mt,"invertRotation",new zs().setFromAxisAngle(new _l(0,1,0),Math.PI)),L(Mt,"quat0",new zs),L(Mt,"quat1",new zs);var Ni=class extends k{webXR=null;debugAvatarUser=null;voip=null;async awake(){if(this.webXR||(this.webXR=R.getComponent(this.gameObject,z)),this.webXR||(this.webXR=R.findObjectOfType(z,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=R.findObjectOfType(z,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=R.findObjectOfType(Ke,this.context)),Ws){let e="debug-avatar-"+Ws,t=new Ot(this.context,e,this.webXR);if(this.debugAvatarUser=t,typeof Ws=="string"&&Ws.length>0)if(await t.setAvatarOverride(Ws)){let i=new Mt(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=R.getComponent(this.gameObject,z),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),z.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),z.addEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),z.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(Bu,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 Mt("");onTryGetAvatar(e,t){if(e===this.context.connection.connectionId)return null;let i=new Date().getTime()-t;if(i>5e3)return rf&&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 Ot(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),z.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),z.removeEventListener("xrUpdate",this.eventSub_WebXRUpdateEvent),z.removeEventListener("xrStopped",this.eventSub_WebXREndEvent)}update(){let e=Fu();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=Fu();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 Ot(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(){rf&&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 xt(1024);onXRSessionUpdate(e){this.xrState??=new Mt(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid),this.ownership??=new Jn(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 s=r?.transform,a=s.position,c=s.orientation;this.xrState.update(n,a,c,this.webXR,this.getAvatarId()),this.localAvatar&&(this.context.connection.connectionId&&(this.localAvatar.guid=this.context.connection.connectionId),this.localAvatar.tryUpdate(this.xrState,0)),!(this.ownership&&!this.ownership.hasOwnership&&this.context.connection.isConnected&&(this.context.time.frameCount%120===0&&this.ownership.requestOwnership(),!this.ownership.hasOwnership))&&(!this.context.connection.isConnected||!this.context.connection.connectionId||this.xrState.sendAsBuffer(this.builder,this.context.connection))}getAvatarId(){return M("avatar")??null}};async function Vv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function zv(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}var Gu=!1,Vu=!1;Vv().then(o=>Gu=o);zv().then(o=>Vu=o);var De=class extends k{enableVR=!0;enableAR=!0;defaultAvatar;handModelPath="";createVRButton=!0;createARButton=!0;static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(Gu||Vu)}static get IsARSupported(){return Gu}static get IsVRSupported(){return Vu}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){De.XRSupported?e.__internalAwake():console.warn("WebXR is not supported on this device");let i=Qo.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){e.__internalAwake();let i=e.webAR?.getAROverlayContainer(),n={};i?(n.domOverlay={root:i},n.optionalFeatures=["hit-test","dom-overlay"]):console.warn("No dom overlay root found, AR will not work");let r=fl.createButton(e.context.renderer,n);return r.classList.add("webxr-ar-button"),r.classList.add("webxr-button"),De.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=qe.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!R.findObjectOfType(Ni,this.context)){let e=R.addNewComponent(this.gameObject,Ni,!1);e.webXR=this}this.webAR=new Mn(this)}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0;let e=De.XRSupported,t,i,n=document.createElement("div");n.classList.add("webxr-buttons"),this.context.domElement.append(n),this.enableAR&&this.createARButton&&(t=De.createARButton(this),this._arButton=t,n.appendChild(t)),this.createVRButton&&this.enableVR&&(i=De.createVRButton(this),this._vrButton=i,n.appendChild(i)),setTimeout(()=>{De.resetButtonStyles(i),De.resetButtonStyles(t)},1e3)}_transformOrientation=new Uu;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)}De._isInXr===!1&&t&&this.onEnterXR(t,e),De.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++)Z.Create(this,e,this.gameObject,0);De.events.dispatchEvent({type:"requestVRSession"})}}captureCameraState(){this.context.mainCamera&&(this._originalCameraPosition.copy(U(this.context.mainCamera)),this._originalCameraRotation.copy(he(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent)}ensureRig(){if(!this.rig){let e=R.findObjectOfType(kn,this.context);e?(this.rig=e.gameObject,this.rig.rotateY(Math.PI)):(this.rig=new Fv,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}_originalCameraParent=null;_originalCameraPosition=new lf;_originalCameraRotation=new Uu;onEnterXR(e,t){console.log("[XR] session begin",e),De._isInXr=!0,this.ensureRig();let i=this.context.renderer.xr.getReferenceSpace();if(i&&this.rig){let a=t.getViewerPose(i)?.transform.orientation;if(a){let c=new Uu(a.x,a.y,a.z,a.w),u=new jv().setFromQuaternion(c);this.rig.rotateY(u.y)}}let n=this.context.renderer.xr;if(this.context.mainCamera){let s=n.getCamera(this.context.mainCamera);for(let a of s.cameras)a.layers.enableAll();this.rig.add(this.context.mainCamera)}let r=this._requestedAR?2:4;switch(ft.Global.Set(r),r){case 2:this.context.xrSessionMode="immersive-ar",this._isInAR=!0,this.webAR?.onBegin(e);break;case 4:this.context.xrSessionMode="immersive-vr",this._isInVR=!0,this.onEnterVR(e);break}e.addEventListener("end",()=>{console.log("[XR] session end"),De._isInXr=!1,this.onExitXR(e)}),this.onEnterXR_HandleMirrorWindow(e),De.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),te(this.context.mainCamera,this._originalCameraPosition),$e(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),ft.Global.Set(17),De.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){!M("mirror")||setTimeout(()=>{if(!De.IsInWebXR)return;let t=new URL(window.location.href);Co(t.searchParams,qo,1),Co(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=()=>{De.IsInWebXR&&e.end()})})},1e3)}},z=De;L(z,"_isInXr",!1),L(z,"events",new Hv),E([x()],z.prototype,"enableVR",2),E([x()],z.prototype,"enableAR",2),E([x(qe)],z.prototype,"defaultAvatar",2),E([x()],z.prototype,"handModelPath",2),E([x()],z.prototype,"createVRButton",2),E([x()],z.prototype,"createARButton",2);var Jo=class{get webxr(){return this._webxr}_webxr;reticle=null;reticleParent=null;hitTestSource=null;reticleActive=!0;previousBackground=null;previousEnvironment=null;sessionRoot=null;_previousParent=null;get context(){return this.webxr.context}constructor(e){this._webxr=e}arDomOverlay=null;arOverlayElement=null;noHitTestAvailable=!1;didPlaceARSessionRoot=!1;getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;let e=this.arDomOverlay;return e.getAROverlayContainer?this.arOverlayElement=e.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(e){this.reticleActive=e}async onBegin(e){let t=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();let i=navigator.userAgent?.includes("OculusBrowser")?0:1,n=i===1?4:2;for(let s=0;s<n;s++)Z.Create(this.webxr,s,this.webxr.gameObject,i);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=R.findObjectOfType(Pt,t)),this.previousBackground=t.scene.background,this.previousEnvironment=t.scene.environment,t.scene.background=null,e.requestReferenceSpace("viewer").then(s=>{e.requestHitTestSource({space:s}).then(a=>{this.hitTestSource=a}).catch(a=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",a)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new Bv(new Gv(.07,.09,32).rotateX(-Math.PI/2),new Uv),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new sf,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),this.reticleParent.matrix.copy(this.sessionRoot.gameObject.matrixWorld),this.webxr.scene?(this.context.scene.add(this.reticleParent),this.context.scene.visible=!0):console.warn("Could not found WebXR Rig")),this._previousParent=this.webxr.gameObject,Jo.tempWebXRObject||(Jo.tempWebXRObject=new sf),this.context.scene.add(Jo.tempWebXRObject),R.addComponent(Jo.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,this.sessionRoot?.onBegin(e)):console.warn("No WebARSessionRoot found in scene");let r=this.context.domElement;r?.onEnterAR?.call(r,e,this.arOverlayElement),this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onEnd(e){this._previousParent&&(console.log("ADD",this._previousParent),R.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;let t=this.webxr.context;if(t.scene.background=this.previousBackground,t.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,e),this.arDomOverlay){let i=this.arOverlayElement;i.onExitAR?.call(i,e)}this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}onUpdate(e,t){if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;let n=this.webxr.Rig,r=Wv.clone();if(n){let s=new lf(0,0,0).add(n.position).divideScalar(this.sessionRoot?.arScale??1);r.multiply(new af().makeTranslation(s.x,s.y,s.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 s=n.getPose(r);if(this.sessionRoot){let a=this.sessionRoot.onUpdate(this.webxr.Rig,e,s);this.didPlaceARSessionRoot=a}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&s)){let a=s.transform.matrix;this.reticle.matrix.fromArray(a),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else this.sessionRoot?.onUpdate(this.webxr.Rig,e,null),this.reticle&&(this.reticle.visible=!1)}},Mn=Jo;L(Mn,"tempWebXRObject");var Wv=new af().identity().makeTranslation(0,-.5,0);var zu=!1;var Zo=class extends Rt{static get HasAnySelected(){return this._active!==null}transformSelf=!0;orbit=null;selectStartEventListener=[];selectEndEventListener=[];constructor(){super(),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new Y.Vector2}addDragEventListener(e,t){switch(e){case"selectstart":this.selectStartEventListener.push(t);break;case"selectend":this.selectEndEventListener.push(t);break}}_dragHelper=null;start(){this.orbit=R.findObjectOfType(Je,this.context)}_draggingRigidbodies=[];allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||z.IsInWebXR)return;let t=R.getComponentInParent(e.object,Zo);!t||t!==this||(Zo.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerExit(e){!this.allowEdit(this.gameObject)||z.IsInWebXR||Zo.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}_waitingForDragStart=null;onPointerDown(e){!this.allowEdit(this.gameObject)||z.IsInWebXR||(this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=e,e.StopPropagation())}onPointerUp(e){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(z.IsInWebXR||(this.onDragEnd(e),e.StopPropagation()))}update(){if(!z.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){let t=this.context.input.getPointerPositionDelta(0);if(t&&this._dragDelta.add(t),this._dragDelta.length()>2)this._didDrag=!0;else return}let e=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(e)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),this._isDragging&&this._dragHelper?.hasSelected===!1&&this.onDragEnd(null)}}_isDragging=!1;_marker=null;_dragDelta;_didDrag=!1;onDragStart(e){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new xl(this.context.mainCamera);else return;if(!e||!e.object)return;let t=R.getComponentInParent(e.object,Zo);if(!t||t!==this)return;let i=e.object;this.transformSelf&&(i=this.gameObject);let n={selected:i,attached:i};for(let c of this.selectStartEventListener)c(this,n);if(!n.attached)return;n.attached,i=n.attached,this._isDragging=!0,this._dragHelper.setSelected(i,this.context),this.orbit&&(this.orbit.enabled=!1);let r=R.getComponentInChildren(i,ht);zu&&console.log("DRAG START",r,i),r&&(r.fastMode=!0,r?.requestOwnership()),this._marker=R.addNewComponent(i,St),this._draggingRigidbodies.length=0;let s=R.getComponentsInChildren(i,J);s&&this._draggingRigidbodies.push(...s);let a=nc();R.invokeOnChildren(this._dragHelper.selected,a("onDragStart"))}onUpdateDrag(){if(!!this._dragHelper){this._dragHelper.onUpdate(this.context);for(let e of this._draggingRigidbodies)e.wakeUp(),e.resetVelocities()}}onDragEnd(e){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(let n of this._draggingRigidbodies)n.setVelocity(n.smoothedVelocity);this._draggingRigidbodies.length=0;let t=this._dragHelper.selected;if(zu&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),e?.object){let n=R.getComponentInChildren(e.object,ht);n&&(n.fastMode=!1),this._marker&&this._marker.destroy()}for(let n of this.selectEndEventListener)n(this);let i=nc();R.invokeOnChildren(t,i("onDragEnd"))}},xi=Zo;L(xi,"_active",null),L(xi,"lastHovered");var Wu=class{get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new Y.Plane;_hasGroundPlane=!1;_groundPlane=new Y.Plane;_groundOffset=new Y.Vector3;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new Y.Vector3;_raycaster=new Y.Raycaster;_cameraPlaneOffset=new Y.Vector3;_intersection=new Y.Vector3;_worldPosition=new Y.Vector3;_inverseMatrix=new Y.Matrix4;_rbs=[];_groundLine;_groundMarker;constructor(e){this._camera=e;let t=new Y.Line(Wu.geometry),i=t.material;i.color=new Y.Color(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;let n=new Y.SphereGeometry(.5,22,22),r=new Y.MeshBasicMaterial({color:i.color}),s=new Y.Mesh(n,r);s.visible=!1,s.layers.set(2),this._groundMarker=s}setSelected(e,t){if(this._selected&&t)for(let i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&me.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}me.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new Y.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),s=this._context.input.getTouchesPressedCount()>=2||r;if(s){let c=this._context.input.getPointerPositionDelta(0);c&&(this._groundOffsetVector.set(0,1,0),this._selected?.rotateOnWorldAxis(this._groundOffsetVector,c.x*this._context.time.deltaTime))}let a=this._context.input.getPointerPositionRC(0);if(!!a&&(this._raycaster.setFromCamera(a,this._camera),this._selected)){zu&&console.log("UPDATE DRAG",this._selected),this._groundOffsetVector.set(0,1,0);let c=U(this._camera).clone().sub(U(this._selected)).normalize(),u=Math.abs(c.dot(this._groundOffsetVector)),l=this._context?.input.isKeyPressed(t)||this._context?.input.isKeyPressed(i),d=!s&&u>.2&&!l&&this._context.input.getPointerPressedCount()<=1,h=this._didDragOnGroundPlaneLastFrame!==d;if(this._didDragOnGroundPlaneLastFrame=d,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!d||h)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){let b=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=b,d){this._groundOffsetVector.set(0,1,0);let _=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(_,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);h&&this.onUpdateScreenSpacePlane(),this._requireUpdateGroundPlane=!0,this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&(this.onUpdateWorldPosition(this._intersection.sub(this._cameraPlaneOffset),this._groundPlanePoint,!0),this.onDidUpdate())}}onUpdateWorldPosition(e,t,i){if(!!this._selected){if(i){let n=U(this._selected);n.y=e.y,e=n}if(te(this._selected,e),te(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=t!==null,t){let n=U(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),te(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=U(this._selected),t=new Y.Ray(new Y.Vector3(0,.1,0).add(e),new Y.Vector3(0,-1,0)),i=new fe;i.ignore=[this._selected];let n=this._context.physics.raycastFromRay(t,i);for(let r=0;r<n.length;r++){let s=n[r];if(!s.face||this.contains(this._selected,s.object))continue;let a=new Y.Vector3(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,s.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}onDidUpdate(){oe.markDirty(this._selected);for(let e of this._rbs)e.wakeUp(),e.resetForcesAndTorques(),e.setAngularVelocity(0,0,0)}contains(e,t){if(e===t)return!0;if(e.children){for(let i of e.children)if(this.contains(i,t))return!0}return!1}},xl=Wu;L(xl,"geometry",new Y.BufferGeometry().setFromPoints([new Y.Vector3(0,0,0),new Y.Vector3(0,-1,0)]));var $t=class extends k{url=null;urlParameterName=null;localhost=null;awake(){this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?$t.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){let r=M(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=$t.IsLocalNetwork()&&t;return n&&(i=t),e?.startsWith("/")&&(i=(n?i:window.location.origin)+e),i}static IsLocalNetwork(e=window.location.hostname){return Xn(e)}};var In=class extends k{filesBackendUrl;localhost;_dragOver;_drop;onEnable(){this.filesBackendUrl=this.filesBackendUrl?$t.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 s=await wp(r,this.context,this.filesBackendUrl);s&&this.addObject(e,s)}else n.kind==="string"&&n.type=="text/plain"&&n.getAsString(async r=>{console.log("dropped url",r);try{let s=new URL(r);if(!s)return;let a=await Ep(s,this.context);a&&this.addObject(e,a)}catch{console.log("dropped string is not a valid URL!",r)}})}}async addObject(e,t){console.log("Dropped",t);let i=new fe;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 s of n){r.position.copy(s.point);break}this.gameObject.add(r),this.dispatchEvent(new CustomEvent("object-added",{detail:t}))}};E([x()],In.prototype,"filesBackendUrl",2),E([x()],In.prototype,"localhost",2);import{Vector3 as Nv,Quaternion as Xv,Object3D as cf}from"three";var wi=class extends Rt{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 Nv(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new Xv(0,0,0,1)}let e=R.getComponentInParent(this.gameObject,xi);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),Z.addEventListener("select-start",(t,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}let n=this.handleDuplication(i.selected);n&&(i.grab=n)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(e){if(this._currentCount>=this.limitCount||!this.object)return null;if(e===this.gameObject||this.handleMultiObject(e)){if(this.object===this.gameObject)return null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);let t=new Ge;this.parent||(this.parent=this.gameObject.parent),this.parent&&(t.parent=this.parent.guid??this.parent.userData?.guid,t.keepWorldPosition=!0),t.position=this.worldPosition,t.rotation=this.worldQuaternion,t.context=this.context,this._currentCount+=1;let i=R.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}};E([x(cf)],wi.prototype,"parent",2),E([x(cf)],wi.prototype,"object",2),E([x()],wi.prototype,"limitCount",2),E([x()],wi.prototype,"limitInterval",2);var Kr=class extends k{};import{FlyControls as Qv}from"three/examples/jsm/controls/FlyControls";var Jr=class extends k{_controls=null;onEnable(){let e=R.getComponent(this.gameObject,ae)?.cam;this._controls=new Qv(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 uf from"three";import{Color as qv}from"three";var Xi=class extends k{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Mi||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new uf.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Ma(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}};E([x()],Xi.prototype,"objectBounds",2),E([x(qv)],Xi.prototype,"color",2),E([x()],Xi.prototype,"isGizmo",2);import{GLTFExporter as ly}from"three/examples/jsm/exporters/GLTFExporter.js";import{BufferAttribute as Nu,Matrix4 as Yv,Vector3 as df,Quaternion as Kv}from"three";var Xs=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 s=new Yv,a=new Array,c=new Array,u=new Array;for(let b=0;b<e.count;b++){e.getMatrixAt(b,s);let _=new df,v=new Kv,y=new df;s.decompose(_,v,y),a.push(_.x,_.y,_.z),c.push(v.x,v.y,v.z,v.w),u.push(y.x,y.y,y.z)}let l=new Float32Array(a),d=new Float32Array(c),h=new Float32Array(u);r.attributes={TRANSLATION:i.processAccessor(new Nu(l,3)),ROTATION:i.processAccessor(new Nu(d,4)),SCALE:i.processAccessor(new Nu(h,3))},n[this.name]=!0}};import*as Yi from"three";import*as Qs from"three";var Qi=class{get lightmap(){return this.lightmapTexture}set lightmap(e){e!==this.lightmapTexture&&(this.lightmapTexture=e,this.setupLightmap())}lightmapIndex=-1;lightmapScaleOffset=new Qs.Vector4(1,1,0,0);context;gameObject;lightmapTexture=null;lightmapScaleOffsetUniform={value:new Qs.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,s){this.onBeforeRenderThree(r)}setupLightmap(){if(this.gameObject.type==="Object3D")return;if(this.gameObject.type==="Group"){console.warn("Lightmap on multimaterial object is not supported yet... please ask kindly for implementation.");return}console.assert(this.gameObject.type==="Mesh","Lightmap only works on meshes",this);let e=this.gameObject;e.geometry.getAttribute("uv2")||e.geometry.setAttribute("uv2",e.geometry.getAttribute("uv"));let t=this.gameObject.material.clone();if(this.gameObject.material=t,this.gameObject.material.onBeforeCompile=(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 Qs.ShaderMaterial({vertexShader:`
|
|
177
177
|
attribute vec2 uv2;
|
|
178
178
|
varying vec2 vUv2;
|
|
179
179
|
void main()
|
|
@@ -205,7 +205,7 @@ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
|
|
|
205
205
|
// gl_FragColor = vec4(vUv2.xy, 0, 1);
|
|
206
206
|
gl_FragColor = lightMapTexel;
|
|
207
207
|
}
|
|
208
|
-
`,defines:{USE_LIGHTMAP:""}})}};import{AxesHelper as ty,Object3D as iy,Vector4 as ny}from"three";import{EquirectangularReflectionMapping as Jv,sRGBEncoding as Zv,Vector3 as hf}from"three";var $o=M("debugreflectionprobe"),pf=M("noreflectionprobe"),$v=Symbol("reflectionProbeKey"),ey=Symbol("original material"),Qi=class extends k{static get(e,t,i){if(!e||e.isObject3D!==!0||pf)return null;let n=Qi._probes.get(t);if(n){for(let r of n)if(r.__didAwake||r.__internalAwake(),r.enabled&&r.isInBox(e,i?1e-8:void 0))return $o&&console.log("Found reflection probe",e.name,r.name),r}return $o&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;set texture(e){this._texture=e}get texture(){return this._texture}center;size;_boxHelper;isInBox(e,t){return this._boxHelper?.isInBox(e,t)}constructor(){super(),Qi._probes.has(this.context)||Qi._probes.set(this.context,[]),Qi._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addNewComponent(ke),this._boxHelper.updateBox(!0),$o&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=Jv,this.texture.encoding=Zv,this.texture.needsUpdate=!0)}onDestroy(){let e=Qi._probes.get(this.context);if(e){let t=e.indexOf(this);t>=0&&e.splice(t,1)}}onSet(e){if(pf||e.sharedMaterials?.length<=0||!this.texture)return;let t=Qi._rendererMaterialsCache.get(e);t||(t=[],Qi._rendererMaterialsCache.set(e,t));for(let i=0;i<e.sharedMaterials.length;i++){let n=e.sharedMaterials[i];if(!n||n.envMap===void 0||n.envMap===this.texture)continue;let r=t[i];if(!r||r.material!==n||r.material.version!==n.version){let a=n.clone();r?(r.copy=a,r.material=n):(r={material:n,copy:a},t.push(r)),a[$v]=this,a[ey]=n,a.envMap=this.texture,$o&&console.log("Set reflection",e.name,e.guid)}let s=r?.copy;e.sharedMaterials[i]=s}}onUnset(e){let t=Qi._rendererMaterialsCache.get(e);if(t)for(let i=0;i<t.length;i++){let n=t[i];e.sharedMaterials[i]=n.material}}},It=Qi;L(It,"_probes",new Map),L(It,"_rendererMaterialsCache",new Map),E([w(hf)],It.prototype,"center",2),E([w(hf)],It.prototype,"size",2);var ff=M("noInstancing"),mf=!!M("debuglightmaps"),ry=M("debuginstancing"),oy=M("debugprogressive"),sy=M("noprogressive");var Zr=class{path=null;asset=null;default};var Xu=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"SkinnedMesh":case"Mesh":this._targets.push(n);break}return new Proxy(this,{get(r,s){if(typeof s=="string"){let a=parseInt(s);if(!isNaN(a))return i(a)}return r[s]},set(r,s,a){return typeof s=="string"&&t(a,Number.parseInt(s)),Reflect.set(r,s,a)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let i=this._targets[t];!i||i.material===void 0||(i.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let i=t[e];return i?i.material:null}},El=class extends k{receiveShadows=!1;shadowCastingMode=Qu.Off;lightmapIndex=-1;lightmapScaleOffset=new qi.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(e){this.sharedMaterials[0]=e}get material(){return this.sharedMaterials[0]}set material(e){this.sharedMaterials[0]=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new Xu(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return ff}_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}allowProgressiveLoading=!0;awake(){this.clearInstancingState(),this.probeAnchor&&$o&&this.probeAnchor.add(new ty(.2)),this._reflectionProbe=null;let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let i=0;i<this.gameObject.children.length;i++){let n=this.gameObject.children[i];if(!(n.type!=="Mesh"||R.getComponent(n,El))){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 Xi(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,mf)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new Xi(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,mf),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=ay.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return R.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return R.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(let t of this.handles)t.remove();return!0}return!1}start(){if(this.enableInstancing&&!ff&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.gameObject.type==="Group")for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&(this.gameObject.visible=!0,this.applyStencil()),this.updateReflectionProbe()}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){Nr.applyStencil(this)}onBeforeRender(){if(!this.gameObject)return;El.envmap=this.scene.environment;let e=this.gameObject[Sa]===!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[Sa],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&&R.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let i=this.handles[t];this.prevLayers||(this.prevLayers=[]);let n=i.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(n):this.prevLayers[t]=n,i.object.layers.disableAll()}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onSet(this)}onBeforeRenderThree(e,t,i,n,r,s){if(!sy&&r._didRequestTextureLOD===void 0&&this.allowProgressiveLoading&&(r._didRequestTextureLOD=0,oy?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{wn.assignTextureLOD(this.context,this.sourceId,r)},2e3)):wn.assignTextureLOD(this.context,this.sourceId,r)),r.envMapIntensity!==void 0){let a=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/a)}if(this._lightmaps)for(let a of this._lightmaps)a.onBeforeRenderThree(r)}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==Qu.On?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){if(this._reflectionProbe=null,this.reflectionProbeUsage!==0){if(!this.probeAnchor)return;let e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=It.get(e,this.context,t)}}},ne=El;L(ne,"envmap",null),E([w()],ne.prototype,"receiveShadows",2),E([w()],ne.prototype,"shadowCastingMode",2),E([w()],ne.prototype,"lightmapIndex",2),E([w(ny)],ne.prototype,"lightmapScaleOffset",2),E([w()],ne.prototype,"enableInstancing",2),E([w()],ne.prototype,"renderOrder",2),E([w()],ne.prototype,"allowOcclusionWhenDynamic",2),E([w(iy)],ne.prototype,"probeAnchor",2),E([w()],ne.prototype,"reflectionProbeUsage",2);var hr=class extends ne{},$r=class extends hr{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},Qu=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(Qu||{}),qu=class{objs=[];setup(e,t,i,n,r=0){let s=this.tryCreateOrAddInstance(e,t,n);if(s)return i===null&&(i=[]),i.push(s),i;if(r<=0&&e.type!=="Mesh"){let a=r+1;for(let c of e.children)i=this.setup(c,t,i,n,a)}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,s=r.geometry,a=r.material;for(let u of this.objs)if(!u.isFull()&&u.geo===s&&u.material===a)return u.addInstance(r);let c=new wl(e.name,s,a,200,t);return this.objs.push(c),c.addInstance(r)}return null}},ay=new qu,Yu=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,R.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},Ku=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,ry&&(i=new qi.MeshBasicMaterial({color:this.randomColor()})),this.inst=new qi.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 qi.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 Yu(-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,Ku.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}},wl=Ku;L(wl,"nullMatrix",new qi.Matrix4);import{Object3D as cy,Vector3 as uy}from"three";var eo=class extends ke{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},Dt=class extends k{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:Dt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Dt.saveArrayBuffer(i,e):Dt.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 ly,this.exporter.register(a=>new Xs(a)),this.ext=new Go,this.ext.registerExport(this.exporter)),Dt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:Dt.collectAnimations(e)},n=new cy;t?.pivot&&n.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(a=>{a&&(n.children.push(a),a.matrixAutoUpdate=!1,a.matrix.copy(a.matrixWorld),R.getComponentsInChildren(a,ne).forEach(c=>{R.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new Ro(n);return this.ext.context=r,new Promise((a,c)=>{try{this.exporter?.parse(n,u=>{s(),a(u)},u=>{s(),c(u)},i)}catch(u){console.error(u),c(u)}finally{console.log("FINALLY")}});function s(){e.forEach(a=>{!a||(a.matrixAutoUpdate=!0,R.getComponentsInChildren(a,ne).forEach(c=>{R.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){let 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 uy;return i.set(0,0,0),e.forEach(n=>{i.add(U(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 Cl,GridHelper as dy}from"three";var Yi=class extends k{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!ki)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new dy(e,t,this.color0??new Cl(.4,.4,.4),this.color1??new Cl(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};E([w()],Yi.prototype,"isGizmo",2),E([w(Cl)],Yi.prototype,"color0",2),E([w(Cl)],Yi.prototype,"color1",2);import{GroundProjectedEnv as hy}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Ki=class extends k{set scale(e){this._scale=e,this.env?.scale.setScalar(e)}get scale(){return this._scale}_scale=20;set radius(e){this._radius=e,this.env&&(this.env.height=e)}get radius(){return this._radius}_radius=100;set height(e){this._height=e,this.env&&(this.env.height=e)}get height(){return this._height}_height=100;_lastEnvironment;env;_watcher;onEnable(){this.context.time.frameCount>0&&this.updateAndCreate()}start(){this.updateAndCreate()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateAndCreate(){this.updateProjection(),this._watcher||(this._watcher=new pn(this.context.scene,"environment"),this._watcher.subscribeWrite(e=>{this.updateProjection()})),this._watcher.apply()}updateProjection(){if(!this.context.scene.environment){this.env?.removeFromParent();return}(!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new hy(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)}};E([w()],Ki.prototype,"scale",1),E([w()],Ki.prototype,"radius",1),E([w()],Ki.prototype,"height",1);import{Vector3 as gf}from"three";var qs=class extends k{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(J)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.createJoint(this.rigidBody,this.connectedBody)}};E([w(J)],qs.prototype,"connectedBody",2);var to=class extends qs{createJoint(e,t){this.context.physics.addFixedJoint(e,t)}},In=class extends qs{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.addHingeJoint(e,t,this.anchor,this.axis)}};E([w(gf)],In.prototype,"anchor",2),E([w(gf)],In.prototype,"axis",2);import*as ze from"three";import{Color as py}from"three";function Ju(o){return o*Math.PI/180}var bf=300,Zu=M("debuglights");var $u=class extends k{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new ze.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;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){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 ze.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=z.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=z.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){z.removeEventListener("xrStarted",this._webXRStartedListener),z.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=R.getComponentInParent(this.gameObject,Pt)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInAR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){let e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:let t=new ze.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-bf*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),gn(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Zu){let s=new ze.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(s)}break;case 0:let i=new ze.SpotLight(this.color,this.intensity*Math.PI,this.range,Ju(this.spotAngle/2),1-Ju(this.innerSpotAngle/2)/Ju(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 ze.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light){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),Zu&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this._overrideShadowBiasSettings===!0?(this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias):(this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4),this.updateShadowSoftHard();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=bf*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,Zu&&this.context.scene.add(new ze.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}}updateShadowSoftHard(){if(!!this.light)if(this.shadows===2){let e=this.light.shadow.mapSize.width/1024*5,t=F.clamp(Math.round(e),2,10);this.light.shadow.radius=e,this.light.shadow.blurSamples=t,dh()&&(this.light.shadow.radius*=.5,this.light.shadow.blurSamples=Math.floor(this.light.shadow.blurSamples*.5)),$u.allowChangingRendererShadowMapType&&(this.context.renderer.shadowMap.type=ze.VSMShadowMap)}else this.light.shadow.radius=1,this.light.shadow.blurSamples=1}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}},Ae=$u;L(Ae,"allowChangingRendererShadowMapType",!0),E([w()],Ae.prototype,"type",2),E([w(py)],Ae.prototype,"color",2),E([w()],Ae.prototype,"shadowNearPlane",1),E([w()],Ae.prototype,"shadowBias",1),E([w()],Ae.prototype,"shadowNormalBias",1),E([w()],Ae.prototype,"shadows",1),E([w()],Ae.prototype,"lightmapBakeType",2),E([w()],Ae.prototype,"intensity",1),E([w()],Ae.prototype,"shadowDistance",1),E([w()],Ae.prototype,"shadowResolution",1);var cA=new ze.Vector3(0,0,0);import*as Tl from"three";import{Vector3 as fy}from"three";var es=M("debugLODs"),my=M("noLODs");var Ei=class{screenRelativeTransitionHeight;distance;renderers};E([w()],Ei.prototype,"screenRelativeTransitionHeight",2),E([w()],Ei.prototype,"distance",2),E([w()],Ei.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):es&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=R.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 k{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!my&&!this._lodsHandler&&!!this.gameObject&&(es&&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 s of r.renderers)t.includes(s)||t.push(s)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){let r=new Tl.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new Tl.Object3D;es&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],s=this._lodsHandler[n],a=r.gameObject,c=0,u=0;es&&console.log(n,a.name);for(let d of this._lods){let h=null;d.renderers.includes(r)?h=a:h=i,es&&console.log("add",d.model.distance,h.name);let b=d.model.distance;u=b-c,c=Math.max(b,c),this.onAddLodLevel(s,h,b)}let l=c+u;es&&console.log("cull",l),this.onAddLodLevel(s,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}}}};E([w(fy)],Dn.prototype,"localReferencePoint",2),E([w(Ei)],Dn.prototype,"lodModels",2);var td=M("debugnestedgltf"),pr=class extends k{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;td&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new Ge;t.idProvider=new Ue(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;td&&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,n.layers.disableAll(),n.layers.set(this.layer)),this.destroy(),td&&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}};E([w(qe)],pr.prototype,"filePath",2);import{Quaternion as gy,Euler as by,Vector3 as io,Plane as vy}from"three";var Ci=class extends k{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new io(0,0,0);rotationOffset=new io(0,0,0);offset=new io(0,0,0);update(){if(!this.from)return;var e=U(this.from),t=he(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 a=new vy(this.gameObject.up,0),c=U(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,c);let u=new io(0,0,0);a.projectPoint(e,u),e.copy(u)}this.affectPosition&&te(this.gameObject,e);let n=new by(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new gy().setFromEuler(n);this.affectRotation&&$e(this.gameObject,t.multiply(r));let s=new io;this.from.getWorldDirection(s).multiplyScalar(50),this.levelLookDirection&&(s.y=0),this.alignLookDirection&&this.gameObject.lookAt(s)}};E([w(R)],Ci.prototype,"referenceSpace",2),E([w(R)],Ci.prototype,"from",2),E([w(io)],Ci.prototype,"positionOffset",2),E([w(io)],Ci.prototype,"rotationOffset",2);import*as is from"three";import{Matrix4 as vf,Vector3 as ti}from"three";import{createNoise4D as _y}from"simplex-noise";var ii=class{alphaKeys;colorKeys;get duration(){return 1}evaluate(e,t){let i,n=0,r=null,s=0;for(let a=0;a<this.alphaKeys.length;a++){let c=this.alphaKeys[a];(c.time<e||!i)&&(i=c,n=a)}for(let a=0;a<this.colorKeys.length;a++){let c=this.colorKeys[a];(c.time<e||!r)&&(r=c,s=a)}if(r)if(s+1<this.colorKeys.length){let c=this.colorKeys[s+1],u=F.remap(e,r.time,c.time,0,1);t.r=F.lerp(r.color.r,c.color.r,u),t.g=F.lerp(r.color.g,c.color.g,u),t.b=F.lerp(r.color.b,c.color.b,u)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(i)if(n+1<this.alphaKeys.length){let c=this.alphaKeys[n+1],u=F.remap(e,i.time,c.time,0,1);t.alpha=F.lerp(i.alpha,c.alpha,u)}else t.alpha=i.alpha;return t}};E([w()],ii.prototype,"alphaKeys",2),E([w()],ii.prototype,"colorKeys",2);var yf=(x=>(x[x.Sphere=0]="Sphere",x[x.SphereShell=1]="SphereShell",x[x.Hemisphere=2]="Hemisphere",x[x.HemisphereShell=3]="HemisphereShell",x[x.Cone=4]="Cone",x[x.Box=5]="Box",x[x.Mesh=6]="Mesh",x[x.ConeShell=7]="ConeShell",x[x.ConeVolume=8]="ConeVolume",x[x.ConeVolumeShell=9]="ConeVolumeShell",x[x.Circle=10]="Circle",x[x.CircleEdge=11]="CircleEdge",x[x.SingleSidedEdge=12]="SingleSidedEdge",x[x.MeshRenderer=13]="MeshRenderer",x[x.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",x[x.BoxShell=15]="BoxShell",x[x.BoxEdge=16]="BoxEdge",x[x.Donut=17]="Donut",x[x.Rectangle=18]="Rectangle",x[x.Sprite=19]="Sprite",x[x.SpriteRenderer=20]="SpriteRenderer",x))(yf||{}),G=class{mode;constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.constant;case 1:return e=F.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:let n=e*this.curveMin.duration,r=e*this.curveMax.duration;return F.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(r),i%1)*this.curveMultiplier;case 3:return F.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}};E([w()],G.prototype,"mode",2),E([w()],G.prototype,"constant",2),E([w()],G.prototype,"constantMin",2),E([w()],G.prototype,"constantMax",2),E([w(Xt)],G.prototype,"curve",2),E([w(Xt)],G.prototype,"curveMin",2),E([w(Xt)],G.prototype,"curveMax",2),E([w()],G.prototype,"curveMultiplier",2);var ei=class{mode;color;colorMin;colorMax;gradient;gradientMin;gradientMax;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(e,ei._temp),ei._temp;case 2:return ei._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:let r=Math.random();return this.gradientMin.evaluate(r,ei._temp),this.gradientMax.evaluate(r,ei._temp2),ei._temp.lerp(ei._temp2,i)}return ei._temp.set(16711935),ei._temp.alpha=1,ei._temp}},We=ei;L(We,"_temp",new $(0,0,0,1)),L(We,"_temp2",new $(0,0,0,1)),E([w($)],We.prototype,"color",2),E([w($)],We.prototype,"colorMin",2),E([w($)],We.prototype,"colorMax",2),E([w(ii)],We.prototype,"gradient",2),E([w(ii)],We.prototype,"gradientMin",2),E([w(ii)],We.prototype,"gradientMax",2);var ge=class{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime};E([w(G)],ge.prototype,"gravityModifier",2),E([w(We)],ge.prototype,"startColor",2),E([w(G)],ge.prototype,"startDelay",2),E([w(G)],ge.prototype,"startLifetime",2),E([w(G)],ge.prototype,"startRotation",2),E([w(G)],ge.prototype,"startRotationX",2),E([w(G)],ge.prototype,"startRotationY",2),E([w(G)],ge.prototype,"startRotationZ",2),E([w(G)],ge.prototype,"startSize",2),E([w(G)],ge.prototype,"startSizeX",2),E([w(G)],ge.prototype,"startSizeY",2),E([w(G)],ge.prototype,"startSizeZ",2),E([w(G)],ge.prototype,"startSpeed",2);var Zi=class{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return this.reset(),0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){let i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=F.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:let n=Math.random();t=F.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}},rt=class{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){let i=this.bursts[t];i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}};E([w()],rt.prototype,"enabled",2),E([w()],rt.prototype,"bursts",2),E([w(G)],rt.prototype,"rateOverTime",2),E([w()],rt.prototype,"rateOverTimeMultiplier",2),E([w(G)],rt.prototype,"rateOverDistance",2),E([w()],rt.prototype,"rateOverDistanceMultiplier",2);var Ji=class{enabled;color};E([w(We)],Ji.prototype,"color",2);var At=class{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new ti;evaluate(e,t){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e)*this.xMultiplier,t.y=this.y.evaluate(e)*this.yMultiplier,t.z=this.z.evaluate(e)*this.zMultiplier;else{let i=this.size.evaluate(e)*this.sizeMultiplier;t.x=i}return t}};E([w(G)],At.prototype,"size",2),E([w(G)],At.prototype,"x",2),E([w(G)],At.prototype,"y",2),E([w(G)],At.prototype,"z",2);var id=class{get type(){return yf[this.shapeType]}initialize(e){this.getPosition(),e.position.copy(this._vector)}toJSON(){return this}clone(){return new id}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;boxThickness;position;rotation;scale;radius;radiusThickness;sphericalDirectionAmount;system;_space;_worldSpaceMatrix=new vf;_worldSpaceMatrixInverse=new vf;update(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}_vector=new ti(0,0,0);_temp=new ti(0,0,0);get vector(){return this._vector}getPosition(){switch(this.shapeType){case 5:this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2;break;case 0:yy(this.position.x,this.position.y,this.position.z,this.radius*this.system.worldScale.x,this.radiusThickness,this.arc,this._vector);break;default:this._vector.set(0,0,0);break}this._space===1&&this._vector.applyMatrix4(this._worldSpaceMatrix)}_dir=new ti;getDirection(e){switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 0:let t=e.x,i=e.y,n=e.z;this._dir.set(t,i,n);break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyMatrix4(this._worldSpaceMatrixInverse),this._dir.normalize(),this._dir}},be=id;E([w()],be.prototype,"shapeType",2),E([w()],be.prototype,"enabled",2),E([w()],be.prototype,"alignToDirection",2),E([w()],be.prototype,"angle",2),E([w()],be.prototype,"arc",2),E([w()],be.prototype,"arcmode",2),E([w(ti)],be.prototype,"boxThickness",2),E([w(ti)],be.prototype,"position",2),E([w(ti)],be.prototype,"rotation",2),E([w(ti)],be.prototype,"scale",2),E([w()],be.prototype,"radius",2),E([w()],be.prototype,"radiusThickness",2),E([w()],be.prototype,"sphericalDirectionAmount",2);function yy(o,e,t,i,n,r,s){let a=Math.random(),c=Math.random(),u=2*Math.PI*a*(r/360),l=Math.acos(2*c-1),d=F.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,h=o+-d*Math.sin(l)*Math.cos(u),b=e+d*Math.sin(l)*Math.sin(u),_=t+d*Math.cos(l);s.x=h,s.y=b,s.z=_}var K=class{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new ti;apply(e,t,i,n,r,s){if(!this.enabled)return;this._noise||(this._noise=_y(()=>0));let a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),c=this._noise(a.x,a.y,a.z,this._time),u=this._noise(a.x,a.y,a.z,this._time+.3),l=this._noise(a.x,a.y,a.z,this._time+1);this._temp.set(c,u,l).normalize();let d=r/s,h=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=h*this.strengthXMultiplier,this._temp.y*=h*this.strengthYMultiplier,this._temp.z*=h*this.strengthZMultiplier):(this.strengthX&&(h*=this.strengthX.evaluate(d)*Math.PI),this._temp.multiplyScalar(h)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}};E([w()],K.prototype,"damping",2),E([w()],K.prototype,"enabled",2),E([w()],K.prototype,"frequency",2),E([w()],K.prototype,"octaveCount",2),E([w()],K.prototype,"octaveMultiplier",2),E([w()],K.prototype,"octaveScale",2),E([w(G)],K.prototype,"positionAmount",2),E([w()],K.prototype,"quality",2),E([w(G)],K.prototype,"remap",2),E([w()],K.prototype,"remapEnabled",2),E([w()],K.prototype,"remapMultiplier",2),E([w(G)],K.prototype,"remapX",2),E([w()],K.prototype,"remapXMultiplier",2),E([w(G)],K.prototype,"remapY",2),E([w()],K.prototype,"remapYMultiplier",2),E([w(G)],K.prototype,"remapZ",2),E([w()],K.prototype,"remapZMultiplier",2),E([w()],K.prototype,"scrollSpeedMultiplier",2),E([w()],K.prototype,"separateAxes",2),E([w()],K.prototype,"strengthMultiplier",2),E([w(G)],K.prototype,"strengthX",2),E([w()],K.prototype,"strengthXMultiplier",2),E([w(G)],K.prototype,"strengthY",2),E([w()],K.prototype,"strengthYMultiplier",2),E([w(G)],K.prototype,"strengthZ",2),E([w()],K.prototype,"strengthZMultiplier",2);var fr=class{enabled};E([w()],fr.prototype,"enabled",2);var Pe=class{enabled;space=0;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new ti;apply(e,t,i,n,r,s){if(!this.enabled)return;let a=r/s,c=this.speedModifier.evaluate(a)*this.speedModifierMultiplier,u=this.x.evaluate(a)*c,l=this.y.evaluate(a)*c,d=this.z.evaluate(a)*c;this._temp.set(-u,l,d),this._system&&(this.space===1&&this._temp.applyQuaternion(this._system.worldQuaternionInverted),this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}};E([w()],Pe.prototype,"enabled",2),E([w()],Pe.prototype,"space",2),E([w(G)],Pe.prototype,"speedModifier",2),E([w()],Pe.prototype,"speedModifierMultiplier",2),E([w(G)],Pe.prototype,"x",2),E([w()],Pe.prototype,"xMultiplier",2),E([w(G)],Pe.prototype,"y",2),E([w()],Pe.prototype,"yMultiplier",2),E([w(G)],Pe.prototype,"z",2),E([w()],Pe.prototype,"zMultiplier",2);var ve=class{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?this.frameOverTime.evaluate(Math.random()):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){let t=this.numTilesX*this.numTilesY,i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}};E([w()],ve.prototype,"animation",2),E([w()],ve.prototype,"enabled",2),E([w()],ve.prototype,"cycleCount",2),E([w(G)],ve.prototype,"frameOverTime",2),E([w()],ve.prototype,"frameOverTimeMultiplier",2),E([w()],ve.prototype,"numTilesX",2),E([w()],ve.prototype,"numTilesY",2),E([w(G)],ve.prototype,"startFrame",2),E([w()],ve.prototype,"startFrameMultiplier",2),E([w()],ve.prototype,"rowMode",2),E([w()],ve.prototype,"rowIndex",2),E([w()],ve.prototype,"spriteCount",2),E([w()],ve.prototype,"timeMode",2);var Ne=class{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e){return this.enabled?this.separateAxes?0:this.z.evaluate(e)*-1:0}};E([w()],Ne.prototype,"enabled",2),E([w()],Ne.prototype,"separateAxes",2),E([w(G)],Ne.prototype,"x",2),E([w()],Ne.prototype,"xMultiplier",2),E([w(G)],Ne.prototype,"y",2),E([w()],Ne.prototype,"yMultiplier",2),E([w(G)],Ne.prototype,"z",2),E([w()],Ne.prototype,"zMultiplier",2);var Le=class{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){let i=F.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}};E([w()],Le.prototype,"enabled",2),E([w()],Le.prototype,"range",2),E([w()],Le.prototype,"separateAxes",2),E([w(G)],Le.prototype,"x",2),E([w()],Le.prototype,"xMultiplier",2),E([w(G)],Le.prototype,"y",2),E([w()],Le.prototype,"yMultiplier",2),E([w(G)],Le.prototype,"z",2),E([w()],Le.prototype,"zMultiplier",2);var le=class{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new ti;_temp2=new ti;apply(e,t,i,n,r,s,a){if(!!this.enabled){let c=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>c){this._temp.copy(t).normalize().multiplyScalar(c);let l=this.dampen*.5;t.x=F.lerp(t.x,this._temp.x,l),t.y=F.lerp(t.y,this._temp.y,l),t.z=F.lerp(t.z,this._temp.z,l),i.x=F.lerp(i.x,this._temp.x,l),i.y=F.lerp(i.y,this._temp.y,l),i.z=F.lerp(i.z,this._temp.z,l)}}}};E([w()],le.prototype,"enabled",2),E([w()],le.prototype,"dampen",2),E([w(G)],le.prototype,"drag",2),E([w()],le.prototype,"dragMultiplier",2),E([w(G)],le.prototype,"limit",2),E([w()],le.prototype,"limitMultiplier",2),E([w()],le.prototype,"separateAxes",2),E([w(G)],le.prototype,"limitX",2),E([w()],le.prototype,"limitXMultiplier",2),E([w(G)],le.prototype,"limitY",2),E([w()],le.prototype,"limitYMultiplier",2),E([w(G)],le.prototype,"limitZ",2),E([w()],le.prototype,"limitZMultiplier",2),E([w()],le.prototype,"multiplyDragByParticleSize",2),E([w()],le.prototype,"multiplyDragByParticleVelocity",2),E([w()],le.prototype,"space",2);import{AxesHelper as xy,Material as wy,Mesh as _f,Object3D as Ey,Quaternion as Pl,Vector3 as Ol,Vector4 as Cy}from"three";import{BatchedParticleRenderer as Ty,ConstantColor as Ry,ConstantValue as Sy,ParticleSystem as Py,RenderMode as Rl}from"three.quarks";var Oy=M("debugparticles"),$i=class extends k{renderMode;particleMaterial;particleMesh;get transparent(){return this.particleMaterial?.transparent??!1}getMesh(){let e=null;return this.particleMesh instanceof _f&&(e=this.particleMesh.geometry),e===null&&(e=new is.BoxGeometry(1,1,1)),new _f(e,this.particleMaterial)}};E([w()],$i.prototype,"renderMode",2),E([w(wy)],$i.prototype,"particleMaterial",2);var ts=class{_curve;constructor(e){this._curve=e}type="function";genValue(e){return this._curve.evaluate(e,Math.random())}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}};var Ys=class{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}system;constructor(e){this.system=e}},nd=class extends Ys{genValue(){return this.system.textureSheetAnimation.getStartIndex()}},rd=class extends Ys{_lastPosition=new Ol;_lastDistance=0;update(){let e=U(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){let n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random()),s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}let t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);let i=this.system.maxParticles-this.system.currentParticles;return F.clamp(e,0,i/this.system.deltaTime)}},od=class extends Ys{genValue(){return 0}},no=class{system;get scaleFactorDiff(){return this.system.worldScale.x-this.system.scale}constructor(e){this.system=e}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}},sd=class extends no{type="NeedleTextureSheet";update(e,t){let i=this.system.textureSheetAnimation;if(i.enabled){let n=e.age/e.life,r=i.evaluate(n);r!==void 0&&(e.uvTile=r)}}},ad=class extends no{type="NeedleRotation";update(e,t){if(e.rotation!==void 0&&!(e.rotation instanceof Pl)){if(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(e.age/e.life)*t:e.rotation=Math.PI,this.system.rotationBySpeed.enabled){let i=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(e.age/e.life,i)*t}}}},ld=class extends no{type="NeedleSize";update(e,t){let i=e.age/e.life,n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i).x);let r=this.system.worldScale.x/this.system.cameraScale;e.size=e.startSize*n*r}},Sl=Symbol("startVelocity"),xf=Symbol("gravityModifier"),wf=new Ol,A1=new Pl,cd=class extends no{type="NeedleVelocity";_gravityDirection=new Ol;initialize(e){let t=1+this.scaleFactorDiff;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random())*t,e.velocity.copy(this.system.shape.getDirection(e.position)).multiplyScalar(e.startSpeed),e[Sl]?e[Sl].copy(e.velocity):e[Sl]=e.velocity.clone();let i=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[xf]=i,this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===0&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted)}update(e,t){let i=e[Sl],n=e[xf];n!==0&&(wf.copy(this._gravityDirection).multiplyScalar(n*t*Math.PI),i.add(wf)),e.velocity.copy(i);let r=e.age/e.life,s=this.system.noise;s.enabled&&s.apply(0,e.position,e.velocity,t,e.age,e.life);let a=this.system.velocityOverLifetime;a.enabled&&a.apply(0,e.position,e.velocity,t,e.age,e.life);let c=this.system.limitVelocityOverLifetime;c.enabled&&c.apply(e.position,i,e.velocity,e.size,r,t,1)}},ud=class extends no{type="NeedleColor";initialize(e){let t=this.system.main.startColor.evaluate(e.age/e.life,Math.random());e.startColor.set(t.r,t.g,t.b,t.alpha),e.color.copy(e.startColor)}update(e,t){if(this.system.colorOverLifetime.enabled){let i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i);e.color.set(n.r,n.g,n.b,n.alpha).multiply(e.startColor)}}},dd=class{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new rd(this.system)}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new ts(this.system.main.startLifetime)}get startSpeed(){return new ts(this.system.main.startSpeed)}get startRotation(){return new ts(this.system.main.startRotation)}get startSize(){return new ts(this.system.main.startSize)}startLength;get startColor(){return new Ry(new Cy(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new od(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh().geometry}get renderMode(){if(this.system.trails.enabled===!0)return Rl.Trail;switch(this.system.renderer.renderMode){case 0:return Rl.BillBoard;case 4:return Rl.LocalSpace}return Rl.BillBoard}rendererEmitterSettings={startLength:new Sy(220),followLocalOrigin:!1};get speedFactor(){return this.system.main.simulationSpeed}get texture(){let e=this.system.renderer.particleMaterial;if(e&&e.map){let t=e.map;return t.premultiplyAlpha=!1,t.encoding=is.LinearEncoding,t}return Xa(new $(1,1,1,1),1)}get startTileIndex(){return new nd(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??is.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===1}},hd=class{burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0},pd=class extends k{play(e=!1){e&&R.foreachComponent(this.gameObject,t=>{t instanceof pd&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._time=0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(){this._isPlaying=!1}stop(){this._isPlaying=!1,this._time=0}_state;emit(e){if(this._particleSystem){e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new hd),this._state.waitEmiting=e,this._state.time=0;let t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;get renderer(){return this._renderer}get isPlaying(){return this.isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===1}__worldQuaternion=new Pl;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new Pl;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new Ol;get worldScale(){return this._worldScale}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;set bursts(e){for(let t=0;t<e.length;t++){let i=e[t];if(!(i instanceof Zi)){let n=new Zi;oi(n,i),e[t]=n}}this._bursts=e}_bursts;awake(){this._renderer=this.gameObject.getComponent($i),this._container=new Ey,this._container.matrixAutoUpdate=!1,this.main.simulationSpace==0?this.gameObject.add(this._container):this.context.scene.add(this._container),this._batchSystem=new Ty,this._container.add(this._batchSystem),this._interface=new dd(this),this._particleSystem=new Py(this._batchSystem,this._interface),this._particleSystem.addBehavior(new ld(this)),this._particleSystem.addBehavior(new cd(this)),this._particleSystem.addBehavior(new ud(this)),this._particleSystem.addBehavior(new sd(this)),this._particleSystem.addBehavior(new ad(this));let e=this._particleSystem.emitter;this.context.scene.add(e),Oy&&(console.log(this),this.gameObject.add(new xy(1)))}onEnable(){this.play()}onDisable(){}onBeforeRender(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;let e=this.context.mainCamera;if(e){let n=Fe(e);this._cameraScale=n.x}let t=this._container;if(this.worldspace&&(t=this.gameObject),he(t,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Fe(this.gameObject,this._worldScale),!this.worldspace&&this._container&&this.gameObject?.parent){let n=Fe(this.gameObject.parent);n.x=1/n.x,n.y=1/n.y,n.z=1/n.z,this._container.matrix.identity(),this._container.matrix.scale(n)}this.emission.system=this;let i=this.deltaTime;this._interface.update(),this.shape.update(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.velocityOverLifetime.update(this),this._batchSystem?.update(i),this._time+=i,this._time>this.duration&&(this._time=0)}},je=pd;E([w(Ji)],je.prototype,"colorOverLifetime",2),E([w(ge)],je.prototype,"main",2),E([w(rt)],je.prototype,"emission",2),E([w(At)],je.prototype,"sizeOverLifetime",2),E([w(be)],je.prototype,"shape",2),E([w(K)],je.prototype,"noise",2),E([w(Pe)],je.prototype,"velocityOverLifetime",2),E([w(le)],je.prototype,"limitVelocityOverLifetime",2),E([w(ve)],je.prototype,"textureSheetAnimation",2),E([w(Ne)],je.prototype,"rotationOverLifetime",2),E([w(Le)],je.prototype,"rotationBySpeed",2);import*as Cf from"three";function*Ef(o,e=null){let t=e?e.time:V.Current.time,i=t.time;for(;t.time-i<o;)yield}var ot=class extends k{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 Ef(.2),!this.tryAssignColor()););}tryAssignColor(){let e=R.getComponentInParent(this.gameObject,se);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ot.hashCode(e),i=ot.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 Cf.Color(t/255,i/255,n/255)}};import*as Ml from"three";import{Object3D as Ay,ShaderMaterial as Ly,Texture as jy,Vector2 as md,Vector4 as Hy}from"three";function ky(){return new Promise((o,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),o())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function Tf(o){await ky(),o()}import{PlaneGeometry as My,MeshBasicMaterial as Iy,Mesh as Dy}from"three";var kl=class{static createPrimitive(e,t){let i;switch(e){case 0:let n=new My(1,1,1,1),r=t?.material??new Iy({color:16777215});i=new Dy(n,r)}return t?.name&&(i.name=t.name),i}};var fd=M("debugvideo");var Rf=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(Rf||{}),xe=class extends k{renderer=null;playOnAwake=!0;playOnEnable;aspectMode=0;renderMode;targetMaterialProperty;targetMaterialRenderer;targetTexture;time=0;_playbackSpeed=1;get playbackSpeed(){return this.videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this.videoElement&&(this.videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this.videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this.videoElement&&(this.videoElement.loop=e)}get currentTime(){return this.videoElement?.currentTime??this.time}set currentTime(e){this.videoElement?this.videoElement.currentTime=e:this.time=e}get isPlaying(){let e=this.videoElement;return e?e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA:!1}get crossOrigin(){return this.videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this.videoElement&&(e!==null?this.videoElement.setAttribute("crossorigin",e):this.videoElement.removeAttribute("crossorigin"))}get videoTexture(){return this._videoTexture}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;_videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setVideo(e){this.clip=e,this.source=0,this.videoElement?(this.videoElement.srcObject=e,this._isPlaying&&this.videoElement.play(),this.updateAspect()):this.create(!0)}setClipURL(e){this.url!==e&&(this.url=e,this.source=1,fd&&console.log("set url",e),this.videoElement?(this.videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(!0))}awake(){this.create(this.playOnAwake),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this._isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}})}onEnable(){this.playOnEnable===!0&&this.handleBeginPlaying(!0),this.screenspace?this._overlay?.start():this._overlay?.stop()}onDisable(){this.pause()}onDestroy(){this.videoElement&&(this.videoElement.parentElement?.removeChild(this.videoElement),this.videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}_receivedInput=!1;constructor(){super(),Tf(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],M("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}play(){!this.videoElement||this._isPlaying&&!this.videoElement?.ended&&!this.videoElement?.paused||(this._isPlaying=!0,this._receivedInput||(this.videoElement.muted=!0),this.updateVideoElementSettings(),this.videoElement?.play().catch(e=>{console.warn(e)}),fd&&console.log("play",this.videoElement))}stop(){this._isPlaying=!1,this.videoElement&&(this.videoElement.currentTime=0,this.videoElement.pause())}pause(){this._isPlaying=!1,this.videoElement?.pause()}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url;break}if(!!t){if(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"){this.videoElement.src=t;let i=this.videoElement.captureStream?.call(this.videoElement);this.clip=i}else this.videoElement.srcObject=t;this._videoTexture||(this._videoTexture=new Ml.VideoTexture(this.videoElement)),this._videoTexture.flipY=!1,this._videoTexture.encoding=Ml.sRGBEncoding,this.handleBeginPlaying(e),console.log(this)}}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new gd(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),fd&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=R.getComponent(this.gameObject,ne)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,Rf[this.renderMode],this);return}let i=t.material;if(i)if(this._targetObjects.push(t),i!==this.videoMaterial&&(this.videoMaterial=i.clone(),t.material=this.videoMaterial),!this.targetMaterialProperty)this.videoMaterial.map=this._videoTexture;else switch(this.targetMaterialProperty){default:this.videoMaterial.map=this._videoTexture;break}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&this.play()}updateVideoElementSettings(){!this.videoElement||(this.videoElement.loop=this._isLooping,this.videoElement.currentTime=this.currentTime,this.videoElement.playbackRate=this._playbackSpeed,this.videoElement.playsInline=!0,this.videoElement.muted=!this._receivedInput&&this.audioOutputMode!==0,(this.playOnAwake||this.playOnEnable)&&(this.videoElement.autoplay=!0))}updateVideoElementStyles(){!this.videoElement||(this.videoElement.style.userSelect="none",this.videoElement.style.visibility="hidden",this.videoElement.style.display="none",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){let e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let n;for(let r of i.getVideoTracks()){let s=r.getSettings();if(s&&s.width&&s.height){n=s.width/s.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(let r of this._targetObjects){let s=1;if(r.parent){let a=Fe(r.parent);s=a.x/a.y}switch(this.aspectMode){case 1:r.scale.y=1/n*r.scale.x*s;break;case 2:r.scale.x=n*r.scale.y*s;break}}for(let r=0;r<3;r++)yield}}};E([w(Ay)],xe.prototype,"renderer",2),E([w()],xe.prototype,"playOnAwake",2),E([w()],xe.prototype,"playOnEnable",2),E([w()],xe.prototype,"aspectMode",2),E([w()],xe.prototype,"renderMode",2),E([w()],xe.prototype,"targetMaterialProperty",2),E([w(ne)],xe.prototype,"targetMaterialRenderer",2),E([w(jy)],xe.prototype,"targetTexture",2),E([w()],xe.prototype,"time",2),E([w()],xe.prototype,"playbackSpeed",1),E([w()],xe.prototype,"isLooping",1);var gd=class{context;constructor(e){this.context=e,this._input=new bd(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;let t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;let e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=kl.createPrimitive(0,{material:new vd(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}let t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();let i=t.material;i?.reset(),this._input?.enable(i)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){let e=this._screenspaceModeQuad?.material;!e||(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input},bd=class{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});let t=new md;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){let r=new md(n.movementX,n.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;let r=n.touches[0],s=n.touches[1],a=r.clientX-s.clientX,c=r.clientY-s.clientY,u=Math.sqrt(a*a+c*c);if(this._lastPinch!==0){let l=u-this._lastPinch;this._material.zoom-=l*.004}this._lastPinch=u}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}},vd=class extends Ly{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){let t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new md;get offset(){let e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){let t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new Hy(0,0,1,1)}},this.vertexShader=`
|
|
208
|
+
`,defines:{USE_LIGHTMAP:""}})}};import{AxesHelper as ty,Object3D as iy,Vector4 as ny}from"three";import{EquirectangularReflectionMapping as Jv,sRGBEncoding as Zv,Vector3 as hf}from"three";var $o=M("debugreflectionprobe"),pf=M("noreflectionprobe"),$v=Symbol("reflectionProbeKey"),ey=Symbol("original material"),qi=class extends k{static get(e,t,i){if(!e||e.isObject3D!==!0||pf)return null;let n=qi._probes.get(t);if(n){for(let r of n)if(r.__didAwake||r.__internalAwake(),r.enabled&&r.isInBox(e,i?1e-8:void 0))return $o&&console.log("Found reflection probe",e.name,r.name),r}return $o&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;set texture(e){this._texture=e}get texture(){return this._texture}center;size;_boxHelper;isInBox(e,t){return this._boxHelper?.isInBox(e,t)}constructor(){super(),qi._probes.has(this.context)||qi._probes.set(this.context,[]),qi._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addNewComponent(ke),this._boxHelper.updateBox(!0),$o&&this._boxHelper.showHelper(5592320,!0),this.texture&&(this.texture.mapping=Jv,this.texture.encoding=Zv,this.texture.needsUpdate=!0)}onDestroy(){let e=qi._probes.get(this.context);if(e){let t=e.indexOf(this);t>=0&&e.splice(t,1)}}onSet(e){if(pf||e.sharedMaterials?.length<=0||!this.texture)return;let t=qi._rendererMaterialsCache.get(e);t||(t=[],qi._rendererMaterialsCache.set(e,t));for(let i=0;i<e.sharedMaterials.length;i++){let n=e.sharedMaterials[i];if(!n||n.envMap===void 0||n.envMap===this.texture)continue;let r=t[i];if(!r||r.material!==n||r.material.version!==n.version){let a=n.clone();r?(r.copy=a,r.material=n):(r={material:n,copy:a},t.push(r)),a[$v]=this,a[ey]=n,a.envMap=this.texture,$o&&console.log("Set reflection",e.name,e.guid)}let s=r?.copy;e.sharedMaterials[i]=s}}onUnset(e){let t=qi._rendererMaterialsCache.get(e);if(t)for(let i=0;i<t.length;i++){let n=t[i];e.sharedMaterials[i]=n.material}}},It=qi;L(It,"_probes",new Map),L(It,"_rendererMaterialsCache",new Map),E([x(hf)],It.prototype,"center",2),E([x(hf)],It.prototype,"size",2);var ff=M("noInstancing"),mf=!!M("debuglightmaps"),ry=M("debuginstancing"),oy=M("debugprogressive"),sy=M("noprogressive");var Zr=class{path=null;asset=null;default};var Xu=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"SkinnedMesh":case"Mesh":this._targets.push(n);break}return new Proxy(this,{get(r,s){if(typeof s=="string"){let a=parseInt(s);if(!isNaN(a))return i(a)}return r[s]},set(r,s,a){return typeof s=="string"&&t(a,Number.parseInt(s)),Reflect.set(r,s,a)}})}get length(){return this._targets.length}setMaterial(e,t){if(t<0||t>=this._targets.length)return;let i=this._targets[t];!i||i.material===void 0||(i.material=e)}getMaterial(e){if(e<0)return null;let t=this._targets;if(e>=t.length)return null;let i=t[e];return i?i.material:null}},El=class extends k{receiveShadows=!1;shadowCastingMode=Qu.Off;lightmapIndex=-1;lightmapScaleOffset=new Yi.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(e){this.sharedMaterials[0]=e}get material(){return this.sharedMaterials[0]}set material(e){this.sharedMaterials[0]=e}_sharedMaterials;get sharedMaterials(){return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._sharedMaterials=new Xu(this)),this._sharedMaterials}static get shouldSuppressInstancing(){return ff}_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}allowProgressiveLoading=!0;awake(){this.clearInstancingState(),this.probeAnchor&&$o&&this.probeAnchor.add(new ty(.2)),this._reflectionProbe=null;let e=this.gameObject.type;if(e==="Group"){for(let t of this.gameObject.children)this.context.addBeforeRenderListener(t,this.onBeforeRenderThree.bind(this)),t.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let t=0;for(let i=0;i<this.gameObject.children.length;i++){let n=this.gameObject.children[i];if(!(n.type!=="Mesh"||R.getComponent(n,El))){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 Qi(this.gameObject,this.context);this._lightmaps.push(i),i.init(this.lightmapIndex,this.lightmapScaleOffset,t,mf)}}else if(e==="Group"){for(let i of this.gameObject.children)if(!i.material?.isMeshBasicMaterial){let n=new Qi(i,this.context);this._lightmaps.push(n),n.init(this.lightmapIndex,this.lightmapScaleOffset,t,mf),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=ay.setup(this.gameObject,this.context,null,{rend:this,foundMeshes:0}),this.handles)return R.markAsInstancedRendered(this.gameObject,!0),!0}else if(this.handles!==null){for(let t of this.handles)t.updateInstanceMatrix(!0),t.add();return R.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this.handles)for(let t of this.handles)t.remove();return!0}return!1}start(){if(this.enableInstancing&&!ff&&this.setInstancingEnabled(!0),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.gameObject.type==="Group")for(let e=0;e<this.gameObject.children.length;e++){let t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this._isInstancingEnabled?this.setInstancingEnabled(!0):this.enabled&&(this.gameObject.visible=!0,this.applyStencil()),this.updateReflectionProbe()}onDisable(){this.handles&&this.handles.length>0?this.setInstancingEnabled(!1):this.enabled||(this.gameObject.visible=!1)}onDestroy(){this.handles=null}applyStencil(){Nr.applyStencil(this)}onBeforeRender(){if(!this.gameObject)return;El.envmap=this.scene.environment;let e=this.gameObject[Sa]===!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[Sa],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&&R.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this.handles)for(let t=0;t<this.handles.length;t++){let i=this.handles[t];this.prevLayers||(this.prevLayers=[]);let n=i.object.layers.mask;t>=this.prevLayers.length?this.prevLayers.push(n):this.prevLayers[t]=n,i.object.layers.disableAll()}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onSet(this)}onBeforeRenderThree(e,t,i,n,r,s){if(!sy&&r._didRequestTextureLOD===void 0&&this.allowProgressiveLoading&&(r._didRequestTextureLOD=0,oy?(console.log("Load material LOD (with delay)",r.name),setTimeout(()=>{En.assignTextureLOD(this.context,this.sourceId,r)},2e3)):En.assignTextureLOD(this.context,this.sourceId,r)),r.envMapIntensity!==void 0){let a=this.hasLightmap?Math.PI:1;r.envMapIntensity=Math.max(0,this.context.rendererData.environmentIntensity/a)}if(this._lightmaps)for(let a of this._lightmaps)a.onBeforeRenderThree(r)}onAfterRender(){if(this._isInstancingEnabled&&this.handles&&this.prevLayers&&this.prevLayers.length>=this.handles.length)for(let e=0;e<this.handles.length;e++){let t=this.handles[e];t.object.layers.mask=this.prevLayers[e]}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==Qu.On?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){if(this._reflectionProbe=null,this.reflectionProbeUsage!==0){if(!this.probeAnchor)return;let e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=It.get(e,this.context,t)}}},ne=El;L(ne,"envmap",null),E([x()],ne.prototype,"receiveShadows",2),E([x()],ne.prototype,"shadowCastingMode",2),E([x()],ne.prototype,"lightmapIndex",2),E([x(ny)],ne.prototype,"lightmapScaleOffset",2),E([x()],ne.prototype,"enableInstancing",2),E([x()],ne.prototype,"renderOrder",2),E([x()],ne.prototype,"allowOcclusionWhenDynamic",2),E([x(iy)],ne.prototype,"probeAnchor",2),E([x()],ne.prototype,"reflectionProbeUsage",2);var hr=class extends ne{},$r=class extends hr{awake(){super.awake(),this.allowOcclusionWhenDynamic=!1}},Qu=(n=>(n[n.Off=0]="Off",n[n.On=1]="On",n[n.TwoSided=2]="TwoSided",n[n.ShadowsOnly=3]="ShadowsOnly",n))(Qu||{}),qu=class{objs=[];setup(e,t,i,n,r=0){let s=this.tryCreateOrAddInstance(e,t,n);if(s)return i===null&&(i=[]),i.push(s),i;if(r<=0&&e.type!=="Mesh"){let a=r+1;for(let c of e.children)i=this.setup(c,t,i,n,a)}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,s=r.geometry,a=r.material;for(let u of this.objs)if(!u.isFull()&&u.geo===s&&u.material===a)return u.addInstance(r);let c=new wl(e.name,s,a,200,t);return this.objs.push(c),c.addInstance(r)}return null}},ay=new qu,Yu=class{get name(){return this.object.name}instanceIndex=-1;object;instancer;constructor(e,t,i){this.instanceIndex=e,this.object=t,this.instancer=i,R.markAsInstancedRendered(t,!0)}updateInstanceMatrix(e=!1){this.instanceIndex<0||(this.object.updateWorldMatrix(!0,e),this.instancer.updateInstance(this.object.matrixWorld,this.instanceIndex))}add(){this.instanceIndex>=0||this.instancer.add(this)}remove(){this.instanceIndex<0||this.instancer.remove(this)}},Ku=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,ry&&(i=new Yi.MeshBasicMaterial({color:this.randomColor()})),this.inst=new Yi.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 Yi.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 Yu(-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,Ku.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}},wl=Ku;L(wl,"nullMatrix",new Yi.Matrix4);import{Object3D as cy,Vector3 as uy}from"three";var eo=class extends ke{sceneRoot;start(){this.startCoroutine(this.updateGltfBox())}*updateGltfBox(){for(;;)for(let e=0;e<10;e++)yield}},Dt=class extends k{binary=!0;objects=[];exporter;ext;async exportNow(e){console.log("DO EXPORT",this.objects);let t={binary:this.binary,pivot:Dt.calculateCenter(this.objects)},i=await this.export(this.objects,t);this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Dt.saveArrayBuffer(i,e):Dt.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 ly,this.exporter.register(a=>new Xs(a)),this.ext=new Go,this.ext.registerExport(this.exporter)),Dt.filterTopmostParent(e);let i={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:t?.binary??!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:Dt.collectAnimations(e)},n=new cy;t?.pivot&&n.position.sub(t.pivot),console.log("EXPORT",e),e.forEach(a=>{a&&(n.children.push(a),a.matrixAutoUpdate=!1,a.matrix.copy(a.matrixWorld),R.getComponentsInChildren(a,ne).forEach(c=>{R.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))});let r=new Ro(n);return this.ext.context=r,new Promise((a,c)=>{try{this.exporter?.parse(n,u=>{s(),a(u)},u=>{s(),c(u)},i)}catch(u){console.error(u),c(u)}finally{console.log("FINALLY")}});function s(){e.forEach(a=>{!a||(a.matrixAutoUpdate=!0,R.getComponentsInChildren(a,ne).forEach(c=>{R.isActiveInHierarchy(c.gameObject)&&c.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){let 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 uy;return i.set(0,0,0),e.forEach(n=>{i.add(U(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 Cl,GridHelper as dy}from"three";var Ki=class extends k{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Mi)return;let e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new dy(e,t,this.color0??new Cl(.4,.4,.4),this.color1??new Cl(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset),this.gameObject.add(this.gridHelper))}};E([x()],Ki.prototype,"isGizmo",2),E([x(Cl)],Ki.prototype,"color0",2),E([x(Cl)],Ki.prototype,"color1",2);import{GroundProjectedEnv as hy}from"three/examples/jsm/objects/GroundProjectedEnv.js";var Ji=class extends k{set scale(e){this._scale=e,this.env?.scale.setScalar(e)}get scale(){return this._scale}_scale=20;set radius(e){this._radius=e,this.env&&(this.env.height=e)}get radius(){return this._radius}_radius=100;set height(e){this._height=e,this.env&&(this.env.height=e)}get height(){return this._height}_height=100;_lastEnvironment;env;_watcher;onEnable(){this.context.time.frameCount>0&&this.updateAndCreate()}start(){this.updateAndCreate()}onDisable(){this._watcher?.revoke(),this.env?.removeFromParent()}updateAndCreate(){this.updateProjection(),this._watcher||(this._watcher=new fn(this.context.scene,"environment"),this._watcher.subscribeWrite(e=>{this.updateProjection()})),this._watcher.apply()}updateProjection(){if(!this.context.scene.environment){this.env?.removeFromParent();return}(!this.env||this.context.scene.environment!==this._lastEnvironment)&&(console.log("Create/Update Ground Projection",this.context.scene.environment.name),this.env=new hy(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)}};E([x()],Ji.prototype,"scale",1),E([x()],Ji.prototype,"radius",1),E([x()],Ji.prototype,"height",1);import{Vector3 as gf}from"three";var qs=class extends k{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(J)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.createJoint(this.rigidBody,this.connectedBody)}};E([x(J)],qs.prototype,"connectedBody",2);var to=class extends qs{createJoint(e,t){this.context.physics.addFixedJoint(e,t)}},Dn=class extends qs{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.addHingeJoint(e,t,this.anchor,this.axis)}};E([x(gf)],Dn.prototype,"anchor",2),E([x(gf)],Dn.prototype,"axis",2);import*as ze from"three";import{Color as py}from"three";function Ju(o){return o*Math.PI/180}var bf=300,Zu=M("debuglights");var $u=class extends k{type=0;range=1;spotAngle=1;innerSpotAngle=1;color=new ze.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;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){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 ze.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=z.addEventListener("xrStarted",this.onWebXRStarted.bind(this)),this._webXREndedListener=z.addEventListener("xrStopped",this.onWebXREnded.bind(this)))}onDisable(){z.removeEventListener("xrStarted",this._webXRStartedListener),z.removeEventListener("xrStopped",this._webXREndedListener)}_webXRStartedListener;_webXREndedListener;_webARRoot;onWebXRStarted(){this._webARRoot=R.getComponentInParent(this.gameObject,Pt)??void 0,this.startCoroutine(this._updateLightIntensityInARRoutine())}*_updateLightIntensityInARRoutine(){for(;this.context.isInAR;){yield,this.updateIntensity();for(let e=0;e<30;e++)yield}}onWebXREnded(){this.updateIntensity()}createLight(){let e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:let t=new ze.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-bf*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),bn(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Zu){let s=new ze.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(s)}break;case 0:let i=new ze.SpotLight(this.color,this.intensity*Math.PI,this.range,Ju(this.spotAngle/2),1-Ju(this.innerSpotAngle/2)/Ju(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 ze.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=r;break}if(this.light){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),Zu&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this._overrideShadowBiasSettings===!0?(this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias):(this.light.shadow.bias=this.shadowBias*1e-5,this.light.shadow.normalBias=this.shadowNormalBias*1e-4),this.updateShadowSoftHard();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=bf*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,Zu&&this.context.scene.add(new ze.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}}updateShadowSoftHard(){if(!!this.light)if(this.shadows===2){let e=this.light.shadow.mapSize.width/1024*5,t=F.clamp(Math.round(e),2,10);this.light.shadow.radius=e,this.light.shadow.blurSamples=t,dh()&&(this.light.shadow.radius*=.5,this.light.shadow.blurSamples=Math.floor(this.light.shadow.blurSamples*.5)),$u.allowChangingRendererShadowMapType&&(this.context.renderer.shadowMap.type=ze.VSMShadowMap)}else this.light.shadow.radius=1,this.light.shadow.blurSamples=1}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}},Ae=$u;L(Ae,"allowChangingRendererShadowMapType",!0),E([x()],Ae.prototype,"type",2),E([x(py)],Ae.prototype,"color",2),E([x()],Ae.prototype,"shadowNearPlane",1),E([x()],Ae.prototype,"shadowBias",1),E([x()],Ae.prototype,"shadowNormalBias",1),E([x()],Ae.prototype,"shadows",1),E([x()],Ae.prototype,"lightmapBakeType",2),E([x()],Ae.prototype,"intensity",1),E([x()],Ae.prototype,"shadowDistance",1),E([x()],Ae.prototype,"shadowResolution",1);var uA=new ze.Vector3(0,0,0);import*as Tl from"three";import{Vector3 as fy}from"three";var es=M("debugLODs"),my=M("noLODs");var Ei=class{screenRelativeTransitionHeight;distance;renderers};E([x()],Ei.prototype,"screenRelativeTransitionHeight",2),E([x()],Ei.prototype,"distance",2),E([x()],Ei.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):es&&console.warn("Renderer not found: "+i,e.gameObject)}}findRenderer(e,t){let i=R.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}},An=class extends k{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(!my&&!this._lodsHandler&&!!this.gameObject&&(es&&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 s of r.renderers)t.includes(s)||t.push(s)}this._lodsHandler=new Array;for(let n=0;n<t.length;n++){let r=new Tl.LOD;this._lodsHandler.push(r),this.gameObject.add(r)}let i=new Tl.Object3D;es&&console.log(t);for(let n=0;n<t.length;n++){let r=t[n],s=this._lodsHandler[n],a=r.gameObject,c=0,u=0;es&&console.log(n,a.name);for(let d of this._lods){let h=null;d.renderers.includes(r)?h=a:h=i,es&&console.log("add",d.model.distance,h.name);let b=d.model.distance;u=b-c,c=Math.max(b,c),this.onAddLodLevel(s,h,b)}let l=c+u;es&&console.log("cull",l),this.onAddLodLevel(s,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}}}};E([x(fy)],An.prototype,"localReferencePoint",2),E([x(Ei)],An.prototype,"lodModels",2);var td=M("debugnestedgltf"),pr=class extends k{filePath;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){this.filePath?.preload()}async start(){if(this._isLoadingOrDoneLoading)return;td&&console.log(this,this.guid);let e=this.gameObject.parent;if(e){this._isLoadingOrDoneLoading=!0;let t=new Ge;t.idProvider=new Ue(this.hash(this.guid)),t.parent=e,this.gameObject.updateMatrix();let i=this.gameObject.matrix;td&&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,n.layers.disableAll(),n.layers.set(this.layer)),this.destroy(),td&&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}};E([x(qe)],pr.prototype,"filePath",2);import{Quaternion as gy,Euler as by,Vector3 as io,Plane as vy}from"three";var Ci=class extends k{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new io(0,0,0);rotationOffset=new io(0,0,0);offset=new io(0,0,0);update(){if(!this.from)return;var e=U(this.from),t=he(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 a=new vy(this.gameObject.up,0),c=U(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,c);let u=new io(0,0,0);a.projectPoint(e,u),e.copy(u)}this.affectPosition&&te(this.gameObject,e);let n=new by(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),r=new gy().setFromEuler(n);this.affectRotation&&$e(this.gameObject,t.multiply(r));let s=new io;this.from.getWorldDirection(s).multiplyScalar(50),this.levelLookDirection&&(s.y=0),this.alignLookDirection&&this.gameObject.lookAt(s)}};E([x(R)],Ci.prototype,"referenceSpace",2),E([x(R)],Ci.prototype,"from",2),E([x(io)],Ci.prototype,"positionOffset",2),E([x(io)],Ci.prototype,"rotationOffset",2);import*as is from"three";import{Matrix4 as vf,Vector3 as ti}from"three";import{createNoise4D as _y}from"simplex-noise";var ii=class{alphaKeys;colorKeys;get duration(){return 1}evaluate(e,t){let i,n=0,r=null,s=0;for(let a=0;a<this.alphaKeys.length;a++){let c=this.alphaKeys[a];(c.time<e||!i)&&(i=c,n=a)}for(let a=0;a<this.colorKeys.length;a++){let c=this.colorKeys[a];(c.time<e||!r)&&(r=c,s=a)}if(r)if(s+1<this.colorKeys.length){let c=this.colorKeys[s+1],u=F.remap(e,r.time,c.time,0,1);t.r=F.lerp(r.color.r,c.color.r,u),t.g=F.lerp(r.color.g,c.color.g,u),t.b=F.lerp(r.color.b,c.color.b,u)}else t.r=r.color.r,t.g=r.color.g,t.b=r.color.b;if(i)if(n+1<this.alphaKeys.length){let c=this.alphaKeys[n+1],u=F.remap(e,i.time,c.time,0,1);t.alpha=F.lerp(i.alpha,c.alpha,u)}else t.alpha=i.alpha;return t}};E([x()],ii.prototype,"alphaKeys",2),E([x()],ii.prototype,"colorKeys",2);var yf=(w=>(w[w.Sphere=0]="Sphere",w[w.SphereShell=1]="SphereShell",w[w.Hemisphere=2]="Hemisphere",w[w.HemisphereShell=3]="HemisphereShell",w[w.Cone=4]="Cone",w[w.Box=5]="Box",w[w.Mesh=6]="Mesh",w[w.ConeShell=7]="ConeShell",w[w.ConeVolume=8]="ConeVolume",w[w.ConeVolumeShell=9]="ConeVolumeShell",w[w.Circle=10]="Circle",w[w.CircleEdge=11]="CircleEdge",w[w.SingleSidedEdge=12]="SingleSidedEdge",w[w.MeshRenderer=13]="MeshRenderer",w[w.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",w[w.BoxShell=15]="BoxShell",w[w.BoxEdge=16]="BoxEdge",w[w.Donut=17]="Donut",w[w.Rectangle=18]="Rectangle",w[w.Sprite=19]="Sprite",w[w.SpriteRenderer=20]="SpriteRenderer",w))(yf||{}),G=class{mode;constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.constant;case 1:return e=F.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:let n=e*this.curveMin.duration,r=e*this.curveMax.duration;return F.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(r),i%1)*this.curveMultiplier;case 3:return F.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}};E([x()],G.prototype,"mode",2),E([x()],G.prototype,"constant",2),E([x()],G.prototype,"constantMin",2),E([x()],G.prototype,"constantMax",2),E([x(Xt)],G.prototype,"curve",2),E([x(Xt)],G.prototype,"curveMin",2),E([x(Xt)],G.prototype,"curveMax",2),E([x()],G.prototype,"curveMultiplier",2);var ei=class{mode;color;colorMin;colorMax;gradient;gradientMin;gradientMax;evaluate(e,t){let i=t===void 0?Math.random():t;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(e,ei._temp),ei._temp;case 2:return ei._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:let r=Math.random();return this.gradientMin.evaluate(r,ei._temp),this.gradientMax.evaluate(r,ei._temp2),ei._temp.lerp(ei._temp2,i)}return ei._temp.set(16711935),ei._temp.alpha=1,ei._temp}},We=ei;L(We,"_temp",new $(0,0,0,1)),L(We,"_temp2",new $(0,0,0,1)),E([x($)],We.prototype,"color",2),E([x($)],We.prototype,"colorMin",2),E([x($)],We.prototype,"colorMax",2),E([x(ii)],We.prototype,"gradient",2),E([x(ii)],We.prototype,"gradientMin",2),E([x(ii)],We.prototype,"gradientMax",2);var ge=class{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime};E([x(G)],ge.prototype,"gravityModifier",2),E([x(We)],ge.prototype,"startColor",2),E([x(G)],ge.prototype,"startDelay",2),E([x(G)],ge.prototype,"startLifetime",2),E([x(G)],ge.prototype,"startRotation",2),E([x(G)],ge.prototype,"startRotationX",2),E([x(G)],ge.prototype,"startRotationY",2),E([x(G)],ge.prototype,"startRotationZ",2),E([x(G)],ge.prototype,"startSize",2),E([x(G)],ge.prototype,"startSizeX",2),E([x(G)],ge.prototype,"startSizeY",2),E([x(G)],ge.prototype,"startSizeZ",2),E([x(G)],ge.prototype,"startSpeed",2);var $i=class{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return this.reset(),0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){let i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=F.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:let n=Math.random();t=F.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}},rt=class{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){let i=this.bursts[t];i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}};E([x()],rt.prototype,"enabled",2),E([x()],rt.prototype,"bursts",2),E([x(G)],rt.prototype,"rateOverTime",2),E([x()],rt.prototype,"rateOverTimeMultiplier",2),E([x(G)],rt.prototype,"rateOverDistance",2),E([x()],rt.prototype,"rateOverDistanceMultiplier",2);var Zi=class{enabled;color};E([x(We)],Zi.prototype,"color",2);var At=class{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new ti;evaluate(e,t){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e)*this.xMultiplier,t.y=this.y.evaluate(e)*this.yMultiplier,t.z=this.z.evaluate(e)*this.zMultiplier;else{let i=this.size.evaluate(e)*this.sizeMultiplier;t.x=i}return t}};E([x(G)],At.prototype,"size",2),E([x(G)],At.prototype,"x",2),E([x(G)],At.prototype,"y",2),E([x(G)],At.prototype,"z",2);var id=class{get type(){return yf[this.shapeType]}initialize(e){this.getPosition(),e.position.copy(this._vector)}toJSON(){return this}clone(){return new id}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcmode=0;boxThickness;position;rotation;scale;radius;radiusThickness;sphericalDirectionAmount;system;_space;_worldSpaceMatrix=new vf;_worldSpaceMatrixInverse=new vf;update(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}_vector=new ti(0,0,0);_temp=new ti(0,0,0);get vector(){return this._vector}getPosition(){switch(this.shapeType){case 5:this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2;break;case 0:yy(this.position.x,this.position.y,this.position.z,this.radius*this.system.worldScale.x,this.radiusThickness,this.arc,this._vector);break;default:this._vector.set(0,0,0);break}this._space===1&&this._vector.applyMatrix4(this._worldSpaceMatrix)}_dir=new ti;getDirection(e){switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 0:let t=e.x,i=e.y,n=e.z;this._dir.set(t,i,n);break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyMatrix4(this._worldSpaceMatrixInverse),this._dir.normalize(),this._dir}},be=id;E([x()],be.prototype,"shapeType",2),E([x()],be.prototype,"enabled",2),E([x()],be.prototype,"alignToDirection",2),E([x()],be.prototype,"angle",2),E([x()],be.prototype,"arc",2),E([x()],be.prototype,"arcmode",2),E([x(ti)],be.prototype,"boxThickness",2),E([x(ti)],be.prototype,"position",2),E([x(ti)],be.prototype,"rotation",2),E([x(ti)],be.prototype,"scale",2),E([x()],be.prototype,"radius",2),E([x()],be.prototype,"radiusThickness",2),E([x()],be.prototype,"sphericalDirectionAmount",2);function yy(o,e,t,i,n,r,s){let a=Math.random(),c=Math.random(),u=2*Math.PI*a*(r/360),l=Math.acos(2*c-1),d=F.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,h=o+-d*Math.sin(l)*Math.cos(u),b=e+d*Math.sin(l)*Math.sin(u),_=t+d*Math.cos(l);s.x=h,s.y=b,s.z=_}var K=class{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new ti;apply(e,t,i,n,r,s){if(!this.enabled)return;this._noise||(this._noise=_y(()=>0));let a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),c=this._noise(a.x,a.y,a.z,this._time),u=this._noise(a.x,a.y,a.z,this._time+.3),l=this._noise(a.x,a.y,a.z,this._time+1);this._temp.set(c,u,l).normalize();let d=r/s,h=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=h*this.strengthXMultiplier,this._temp.y*=h*this.strengthYMultiplier,this._temp.z*=h*this.strengthZMultiplier):(this.strengthX&&(h*=this.strengthX.evaluate(d)*Math.PI),this._temp.multiplyScalar(h)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}};E([x()],K.prototype,"damping",2),E([x()],K.prototype,"enabled",2),E([x()],K.prototype,"frequency",2),E([x()],K.prototype,"octaveCount",2),E([x()],K.prototype,"octaveMultiplier",2),E([x()],K.prototype,"octaveScale",2),E([x(G)],K.prototype,"positionAmount",2),E([x()],K.prototype,"quality",2),E([x(G)],K.prototype,"remap",2),E([x()],K.prototype,"remapEnabled",2),E([x()],K.prototype,"remapMultiplier",2),E([x(G)],K.prototype,"remapX",2),E([x()],K.prototype,"remapXMultiplier",2),E([x(G)],K.prototype,"remapY",2),E([x()],K.prototype,"remapYMultiplier",2),E([x(G)],K.prototype,"remapZ",2),E([x()],K.prototype,"remapZMultiplier",2),E([x()],K.prototype,"scrollSpeedMultiplier",2),E([x()],K.prototype,"separateAxes",2),E([x()],K.prototype,"strengthMultiplier",2),E([x(G)],K.prototype,"strengthX",2),E([x()],K.prototype,"strengthXMultiplier",2),E([x(G)],K.prototype,"strengthY",2),E([x()],K.prototype,"strengthYMultiplier",2),E([x(G)],K.prototype,"strengthZ",2),E([x()],K.prototype,"strengthZMultiplier",2);var fr=class{enabled};E([x()],fr.prototype,"enabled",2);var Pe=class{enabled;space=0;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new ti;apply(e,t,i,n,r,s){if(!this.enabled)return;let a=r/s,c=this.speedModifier.evaluate(a)*this.speedModifierMultiplier,u=this.x.evaluate(a)*c,l=this.y.evaluate(a)*c,d=this.z.evaluate(a)*c;this._temp.set(-u,l,d),this._system&&(this.space===1&&this._temp.applyQuaternion(this._system.worldQuaternionInverted),this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}};E([x()],Pe.prototype,"enabled",2),E([x()],Pe.prototype,"space",2),E([x(G)],Pe.prototype,"speedModifier",2),E([x()],Pe.prototype,"speedModifierMultiplier",2),E([x(G)],Pe.prototype,"x",2),E([x()],Pe.prototype,"xMultiplier",2),E([x(G)],Pe.prototype,"y",2),E([x()],Pe.prototype,"yMultiplier",2),E([x(G)],Pe.prototype,"z",2),E([x()],Pe.prototype,"zMultiplier",2);var ve=class{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?this.frameOverTime.evaluate(Math.random()):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){let t=this.numTilesX*this.numTilesY,i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}};E([x()],ve.prototype,"animation",2),E([x()],ve.prototype,"enabled",2),E([x()],ve.prototype,"cycleCount",2),E([x(G)],ve.prototype,"frameOverTime",2),E([x()],ve.prototype,"frameOverTimeMultiplier",2),E([x()],ve.prototype,"numTilesX",2),E([x()],ve.prototype,"numTilesY",2),E([x(G)],ve.prototype,"startFrame",2),E([x()],ve.prototype,"startFrameMultiplier",2),E([x()],ve.prototype,"rowMode",2),E([x()],ve.prototype,"rowIndex",2),E([x()],ve.prototype,"spriteCount",2),E([x()],ve.prototype,"timeMode",2);var Ne=class{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e){return this.enabled?this.separateAxes?0:this.z.evaluate(e)*-1:0}};E([x()],Ne.prototype,"enabled",2),E([x()],Ne.prototype,"separateAxes",2),E([x(G)],Ne.prototype,"x",2),E([x()],Ne.prototype,"xMultiplier",2),E([x(G)],Ne.prototype,"y",2),E([x()],Ne.prototype,"yMultiplier",2),E([x(G)],Ne.prototype,"z",2),E([x()],Ne.prototype,"zMultiplier",2);var Le=class{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){let i=F.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}};E([x()],Le.prototype,"enabled",2),E([x()],Le.prototype,"range",2),E([x()],Le.prototype,"separateAxes",2),E([x(G)],Le.prototype,"x",2),E([x()],Le.prototype,"xMultiplier",2),E([x(G)],Le.prototype,"y",2),E([x()],Le.prototype,"yMultiplier",2),E([x(G)],Le.prototype,"z",2),E([x()],Le.prototype,"zMultiplier",2);var le=class{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new ti;_temp2=new ti;apply(e,t,i,n,r,s,a){if(!!this.enabled){let c=this.limit.evaluate(r)*this.limitMultiplier;if(t.length()>c){this._temp.copy(t).normalize().multiplyScalar(c);let l=this.dampen*.5;t.x=F.lerp(t.x,this._temp.x,l),t.y=F.lerp(t.y,this._temp.y,l),t.z=F.lerp(t.z,this._temp.z,l),i.x=F.lerp(i.x,this._temp.x,l),i.y=F.lerp(i.y,this._temp.y,l),i.z=F.lerp(i.z,this._temp.z,l)}}}};E([x()],le.prototype,"enabled",2),E([x()],le.prototype,"dampen",2),E([x(G)],le.prototype,"drag",2),E([x()],le.prototype,"dragMultiplier",2),E([x(G)],le.prototype,"limit",2),E([x()],le.prototype,"limitMultiplier",2),E([x()],le.prototype,"separateAxes",2),E([x(G)],le.prototype,"limitX",2),E([x()],le.prototype,"limitXMultiplier",2),E([x(G)],le.prototype,"limitY",2),E([x()],le.prototype,"limitYMultiplier",2),E([x(G)],le.prototype,"limitZ",2),E([x()],le.prototype,"limitZMultiplier",2),E([x()],le.prototype,"multiplyDragByParticleSize",2),E([x()],le.prototype,"multiplyDragByParticleVelocity",2),E([x()],le.prototype,"space",2);import{AxesHelper as xy,Material as wy,Mesh as _f,Object3D as Ey,Quaternion as Pl,Vector3 as Ol,Vector4 as Cy}from"three";import{BatchedParticleRenderer as Ty,ConstantColor as Ry,ConstantValue as Sy,ParticleSystem as Py,RenderMode as Rl}from"three.quarks";var Oy=M("debugparticles"),en=class extends k{renderMode;particleMaterial;particleMesh;get transparent(){return this.particleMaterial?.transparent??!1}getMesh(){let e=null;return this.particleMesh instanceof _f&&(e=this.particleMesh.geometry),e===null&&(e=new is.BoxGeometry(1,1,1)),new _f(e,this.particleMaterial)}};E([x()],en.prototype,"renderMode",2),E([x(wy)],en.prototype,"particleMaterial",2);var ts=class{_curve;constructor(e){this._curve=e}type="function";genValue(e){return this._curve.evaluate(e,Math.random())}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}};var Ys=class{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}system;constructor(e){this.system=e}},nd=class extends Ys{genValue(){return this.system.textureSheetAnimation.getStartIndex()}},rd=class extends Ys{_lastPosition=new Ol;_lastDistance=0;update(){let e=U(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){let n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random()),s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}let t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);let i=this.system.maxParticles-this.system.currentParticles;return F.clamp(e,0,i/this.system.deltaTime)}},od=class extends Ys{genValue(){return 0}},no=class{system;get scaleFactorDiff(){return this.system.worldScale.x-this.system.scale}constructor(e){this.system=e}initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}},sd=class extends no{type="NeedleTextureSheet";update(e,t){let i=this.system.textureSheetAnimation;if(i.enabled){let n=e.age/e.life,r=i.evaluate(n);r!==void 0&&(e.uvTile=r)}}},ad=class extends no{type="NeedleRotation";update(e,t){if(e.rotation!==void 0&&!(e.rotation instanceof Pl)){if(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(e.age/e.life)*t:e.rotation=Math.PI,this.system.rotationBySpeed.enabled){let i=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(e.age/e.life,i)*t}}}},ld=class extends no{type="NeedleSize";update(e,t){let i=e.age/e.life,n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i).x);let r=this.system.worldScale.x/this.system.cameraScale;e.size=e.startSize*n*r}},Sl=Symbol("startVelocity"),xf=Symbol("gravityModifier"),wf=new Ol,L1=new Pl,cd=class extends no{type="NeedleVelocity";_gravityDirection=new Ol;initialize(e){let t=1+this.scaleFactorDiff;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random())*t,e.velocity.copy(this.system.shape.getDirection(e.position)).multiplyScalar(e.startSpeed),e[Sl]?e[Sl].copy(e.velocity):e[Sl]=e.velocity.clone();let i=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[xf]=i,this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===0&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted)}update(e,t){let i=e[Sl],n=e[xf];n!==0&&(wf.copy(this._gravityDirection).multiplyScalar(n*t*Math.PI),i.add(wf)),e.velocity.copy(i);let r=e.age/e.life,s=this.system.noise;s.enabled&&s.apply(0,e.position,e.velocity,t,e.age,e.life);let a=this.system.velocityOverLifetime;a.enabled&&a.apply(0,e.position,e.velocity,t,e.age,e.life);let c=this.system.limitVelocityOverLifetime;c.enabled&&c.apply(e.position,i,e.velocity,e.size,r,t,1)}},ud=class extends no{type="NeedleColor";initialize(e){let t=this.system.main.startColor.evaluate(e.age/e.life,Math.random());e.startColor.set(t.r,t.g,t.b,t.alpha),e.color.copy(e.startColor)}update(e,t){if(this.system.colorOverLifetime.enabled){let i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i);e.color.set(n.r,n.g,n.b,n.alpha).multiply(e.startColor)}}},dd=class{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new rd(this.system)}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new ts(this.system.main.startLifetime)}get startSpeed(){return new ts(this.system.main.startSpeed)}get startRotation(){return new ts(this.system.main.startRotation)}get startSize(){return new ts(this.system.main.startSize)}startLength;get startColor(){return new Ry(new Cy(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new od(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh().geometry}get renderMode(){if(this.system.trails.enabled===!0)return Rl.Trail;switch(this.system.renderer.renderMode){case 0:return Rl.BillBoard;case 4:return Rl.LocalSpace}return Rl.BillBoard}rendererEmitterSettings={startLength:new Sy(220),followLocalOrigin:!1};get speedFactor(){return this.system.main.simulationSpeed}get texture(){let e=this.system.renderer.particleMaterial;if(e&&e.map){let t=e.map;return t.premultiplyAlpha=!1,t.encoding=is.LinearEncoding,t}return Xa(new $(1,1,1,1),1)}get startTileIndex(){return new nd(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??is.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===1}},hd=class{burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0},pd=class extends k{play(e=!1){e&&R.foreachComponent(this.gameObject,t=>{t instanceof pd&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._time=0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(){this._isPlaying=!1}stop(){this._isPlaying=!1,this._time=0}_state;emit(e){if(this._particleSystem){e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new hd),this._state.waitEmiting=e,this._state.time=0;let t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;get renderer(){return this._renderer}get isPlaying(){return this.isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===1}__worldQuaternion=new Pl;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new Pl;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new Ol;get worldScale(){return this._worldScale}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;set bursts(e){for(let t=0;t<e.length;t++){let i=e[t];if(!(i instanceof $i)){let n=new $i;oi(n,i),e[t]=n}}this._bursts=e}_bursts;awake(){this._renderer=this.gameObject.getComponent(en),this._container=new Ey,this._container.matrixAutoUpdate=!1,this.main.simulationSpace==0?this.gameObject.add(this._container):this.context.scene.add(this._container),this._batchSystem=new Ty,this._container.add(this._batchSystem),this._interface=new dd(this),this._particleSystem=new Py(this._batchSystem,this._interface),this._particleSystem.addBehavior(new ld(this)),this._particleSystem.addBehavior(new cd(this)),this._particleSystem.addBehavior(new ud(this)),this._particleSystem.addBehavior(new sd(this)),this._particleSystem.addBehavior(new ad(this));let e=this._particleSystem.emitter;this.context.scene.add(e),Oy&&(console.log(this),this.gameObject.add(new xy(1)))}onEnable(){this.play()}onDisable(){}onBeforeRender(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;let e=this.context.mainCamera;if(e){let n=Fe(e);this._cameraScale=n.x}let t=this._container;if(this.worldspace&&(t=this.gameObject),he(t,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Fe(this.gameObject,this._worldScale),!this.worldspace&&this._container&&this.gameObject?.parent){let n=Fe(this.gameObject.parent);n.x=1/n.x,n.y=1/n.y,n.z=1/n.z,this._container.matrix.identity(),this._container.matrix.scale(n)}this.emission.system=this;let i=this.deltaTime;this._interface.update(),this.shape.update(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.velocityOverLifetime.update(this),this._batchSystem?.update(i),this._time+=i,this._time>this.duration&&(this._time=0)}},je=pd;E([x(Zi)],je.prototype,"colorOverLifetime",2),E([x(ge)],je.prototype,"main",2),E([x(rt)],je.prototype,"emission",2),E([x(At)],je.prototype,"sizeOverLifetime",2),E([x(be)],je.prototype,"shape",2),E([x(K)],je.prototype,"noise",2),E([x(Pe)],je.prototype,"velocityOverLifetime",2),E([x(le)],je.prototype,"limitVelocityOverLifetime",2),E([x(ve)],je.prototype,"textureSheetAnimation",2),E([x(Ne)],je.prototype,"rotationOverLifetime",2),E([x(Le)],je.prototype,"rotationBySpeed",2);import*as Cf from"three";function*Ef(o,e=null){let t=e?e.time:V.Current.time,i=t.time;for(;t.time-i<o;)yield}var ot=class extends k{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 Ef(.2),!this.tryAssignColor()););}tryAssignColor(){let e=R.getComponentInParent(this.gameObject,se);return e&&e.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(e.connectionId),!0):!1}assignUserColor(e){let t=ot.hashCode(e),i=ot.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 Cf.Color(t/255,i/255,n/255)}};import*as Ml from"three";import{Object3D as Ay,ShaderMaterial as Ly,Texture as jy,Vector2 as md,Vector4 as Hy}from"three";function ky(){return new Promise((o,e)=>{let i=()=>{i!=null&&(document.removeEventListener("pointerdown",i),document.removeEventListener("click",i),document.removeEventListener("dragstart",i),document.removeEventListener("touchstart",i),o())};document.addEventListener("pointerdown",i),document.addEventListener("click",i),document.addEventListener("dragstart",i),document.addEventListener("touchstart",i)})}async function Tf(o){await ky(),o()}import{PlaneGeometry as My,MeshBasicMaterial as Iy,Mesh as Dy}from"three";var kl=class{static createPrimitive(e,t){let i;switch(e){case 0:let n=new My(1,1,1,1),r=t?.material??new Iy({color:16777215});i=new Dy(n,r)}return t?.name&&(i.name=t.name),i}};var fd=M("debugvideo");var Rf=(n=>(n[n.CameraFarPlane=0]="CameraFarPlane",n[n.CameraNearPlane=1]="CameraNearPlane",n[n.RenderTexture=2]="RenderTexture",n[n.MaterialOverride=3]="MaterialOverride",n))(Rf||{}),xe=class extends k{renderer=null;playOnAwake=!0;playOnEnable;aspectMode=0;renderMode;targetMaterialProperty;targetMaterialRenderer;targetTexture;time=0;_playbackSpeed=1;get playbackSpeed(){return this.videoElement?.playbackRate??this._playbackSpeed}set playbackSpeed(e){this._playbackSpeed=e,this.videoElement&&(this.videoElement.playbackRate=e)}_isLooping=!1;get isLooping(){return this.videoElement?.loop??this._isLooping}set isLooping(e){this._isLooping=e,this.videoElement&&(this.videoElement.loop=e)}get currentTime(){return this.videoElement?.currentTime??this.time}set currentTime(e){this.videoElement?this.videoElement.currentTime=e:this.time=e}get isPlaying(){let e=this.videoElement;return e?e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>e.HAVE_CURRENT_DATA:!1}get crossOrigin(){return this.videoElement?.crossOrigin??this._crossOrigin}set crossOrigin(e){this._crossOrigin=e,this.videoElement&&(e!==null?this.videoElement.setAttribute("crossorigin",e):this.videoElement.removeAttribute("crossorigin"))}get videoTexture(){return this._videoTexture}_crossOrigin="anonymous";audioOutputMode=1;source;clip=null;url=null;videoElement=null;_videoTexture=null;videoMaterial=null;_isPlaying=!1;wasPlaying=!1;setVideo(e){this.clip=e,this.source=0,this.videoElement?(this.videoElement.srcObject=e,this._isPlaying&&this.videoElement.play(),this.updateAspect()):this.create(!0)}setClipURL(e){this.url!==e&&(this.url=e,this.source=1,fd&&console.log("set url",e),this.videoElement?(this.videoElement.src=e,this._isPlaying&&(this.stop(),this.play())):this.create(!0))}awake(){this.create(this.playOnAwake),window.addEventListener("visibilitychange",e=>{switch(document.visibilityState){case"hidden":this.wasPlaying=this._isPlaying,this.pause();break;case"visible":this.wasPlaying&&this.play();break}})}onEnable(){this.playOnEnable===!0&&this.handleBeginPlaying(!0),this.screenspace?this._overlay?.start():this._overlay?.stop()}onDisable(){this.pause()}onDestroy(){this.videoElement&&(this.videoElement.parentElement?.removeChild(this.videoElement),this.videoElement=null),this._videoTexture&&(this._videoTexture.dispose(),this._videoTexture=null)}_receivedInput=!1;constructor(){super(),Tf(()=>{this._receivedInput=!0,this.updateVideoElementSettings()}),this._targetObjects=[],M("videoscreenspace")&&window.addEventListener("keydown",e=>{e.key==="f"&&(this.screenspace=!this.screenspace)})}play(){!this.videoElement||this._isPlaying&&!this.videoElement?.ended&&!this.videoElement?.paused||(this._isPlaying=!0,this._receivedInput||(this.videoElement.muted=!0),this.updateVideoElementSettings(),this.videoElement?.play().catch(e=>{console.warn(e)}),fd&&console.log("play",this.videoElement))}stop(){this._isPlaying=!1,this.videoElement&&(this.videoElement.currentTime=0,this.videoElement.pause())}pause(){this._isPlaying=!1,this.videoElement?.pause()}create(e){let t;switch(this.source){case 0:t=this.clip;break;case 1:t=this.url;break}if(!!t){if(this.videoElement||(this.videoElement=this.createVideoElement(),this.context.domElement?.prepend(this.videoElement),this.updateVideoElementStyles()),typeof t=="string"){this.videoElement.src=t;let i=this.videoElement.captureStream?.call(this.videoElement);this.clip=i}else this.videoElement.srcObject=t;this._videoTexture||(this._videoTexture=new Ml.VideoTexture(this.videoElement)),this._videoTexture.flipY=!1,this._videoTexture.encoding=Ml.sRGBEncoding,this.handleBeginPlaying(e),console.log(this)}}updateAspect(){this.aspectMode!==0&&this.startCoroutine(this.updateAspectImpl())}_overlay=null;get screenspace(){return this._overlay?.enabled??!1}set screenspace(e){if(e){if(!this._videoTexture)return;this._overlay||(this._overlay=new gd(this.context)),this._overlay.add(this._videoTexture)}else this._overlay?.remove(this._videoTexture);this._overlay&&(this._overlay.enabled=e)}_targetObjects;createVideoElement(){let e=document.createElement("video");return this._crossOrigin&&e.setAttribute("crossorigin",this._crossOrigin),fd&&console.log("create video elment",e),e}handleBeginPlaying(e){if(!this.enabled||!this.videoElement)return;this._targetObjects.length=0;let t=this.gameObject;switch(this.renderMode){case 3:t=this.targetMaterialRenderer?.gameObject,t||(t=R.getComponent(this.gameObject,ne)?.gameObject);break;case 2:console.error("VideoPlayer renderTexture not implemented yet. Please use material override instead");return}if(!t){console.error("Missing target for video material renderer",this.name,Rf[this.renderMode],this);return}let i=t.material;if(i)if(this._targetObjects.push(t),i!==this.videoMaterial&&(this.videoMaterial=i.clone(),t.material=this.videoMaterial),!this.targetMaterialProperty)this.videoMaterial.map=this._videoTexture;else switch(this.targetMaterialProperty){default:this.videoMaterial.map=this._videoTexture;break}else{console.warn("Can not play video, no material found, this might be a multimaterial case which is not supported yet");return}this.updateVideoElementSettings(),this.updateVideoElementStyles(),e&&this.play()}updateVideoElementSettings(){!this.videoElement||(this.videoElement.loop=this._isLooping,this.videoElement.currentTime=this.currentTime,this.videoElement.playbackRate=this._playbackSpeed,this.videoElement.playsInline=!0,this.videoElement.muted=!this._receivedInput&&this.audioOutputMode!==0,(this.playOnAwake||this.playOnEnable)&&(this.videoElement.autoplay=!0))}updateVideoElementStyles(){!this.videoElement||(this.videoElement.style.userSelect="none",this.videoElement.style.visibility="hidden",this.videoElement.style.display="none",this.updateAspect())}_updateAspectRoutineId=-1;*updateAspectImpl(){let e=++this._updateAspectRoutineId,t=void 0,i=this.clip;for(;e===this._updateAspectRoutineId&&this.aspectMode!==0&&this.clip&&i===this.clip&&this._isPlaying;){if(!i||typeof i=="string")return;let n;for(let r of i.getVideoTracks()){let s=r.getSettings();if(s&&s.width&&s.height){n=s.width/s.height;break}else n=this.context.renderer.domElement.clientWidth/this.context.renderer.domElement.clientHeight}if(n===void 0){for(let r=0;r<10;r++)yield;if(!this.isPlaying)break;continue}if(t===n){yield;continue}for(let r of this._targetObjects){let s=1;if(r.parent){let a=Fe(r.parent);s=a.x/a.y}switch(this.aspectMode){case 1:r.scale.y=1/n*r.scale.x*s;break;case 2:r.scale.x=n*r.scale.y*s;break}}for(let r=0;r<3;r++)yield}}};E([x(Ay)],xe.prototype,"renderer",2),E([x()],xe.prototype,"playOnAwake",2),E([x()],xe.prototype,"playOnEnable",2),E([x()],xe.prototype,"aspectMode",2),E([x()],xe.prototype,"renderMode",2),E([x()],xe.prototype,"targetMaterialProperty",2),E([x(ne)],xe.prototype,"targetMaterialRenderer",2),E([x(jy)],xe.prototype,"targetTexture",2),E([x()],xe.prototype,"time",2),E([x()],xe.prototype,"playbackSpeed",1),E([x()],xe.prototype,"isLooping",1);var gd=class{context;constructor(e){this.context=e,this._input=new bd(this)}get enabled(){return this._isInScreenspaceMode}set enabled(e){e?this.start():this.stop()}add(e){this._videos.indexOf(e)===-1&&this._videos.push(e)}remove(e){if(!e)return;let t=this._videos.indexOf(e);t>=0&&this._videos.splice(t,1)}start(){if(this._isInScreenspaceMode||this._videos.length<0)return;let e=this._videos[this._videos.length-1];if(!e)return;if(this._isInScreenspaceMode=!0,!this._screenspaceModeQuad){if(this._screenspaceModeQuad=kl.createPrimitive(0,{material:new vd(e)}),!this._screenspaceModeQuad)return;this._screenspaceModeQuad.geometry.scale(2,2,2)}let t=this._screenspaceModeQuad;this.context.scene.add(t),this.updateScreenspaceMaterialUniforms();let i=t.material;i?.reset(),this._input?.enable(i)}stop(){this._isInScreenspaceMode=!1,this._screenspaceModeQuad&&(this._input?.disable(),this._screenspaceModeQuad.removeFromParent())}updateScreenspaceMaterialUniforms(){let e=this._screenspaceModeQuad?.material;!e||(e.screenAspect=this.context.domElement.clientWidth/this.context.domElement.clientHeight)}_videos=[];_screenspaceModeQuad;_isInScreenspaceMode=!1;_input},bd=class{_onResizeScreenFn;_onKeyUpFn;_onMouseWheelFn;context;overlay;constructor(e){this.overlay=e,this.context=e.context}_material;enable(e){this._material=e,window.addEventListener("resize",this._onResizeScreenFn=()=>{this.overlay.updateScreenspaceMaterialUniforms()}),window.addEventListener("keyup",this._onKeyUpFn=n=>{n.key==="Escape"&&this.overlay.stop()}),window.addEventListener("wheel",this._onMouseWheelFn=n=>{this.overlay.enabled&&(e.zoom+=n.deltaY*5e-4,n.preventDefault())},{passive:!1});let t=new md;window.addEventListener("mousemove",n=>{if(this.overlay.enabled&&this.context.input.getPointerPressed(0)){let r=new md(n.movementX,n.movementY);r.x/=this.context.domElement.clientWidth,r.y/=this.context.domElement.clientHeight,t.set(r.x,r.y),t.multiplyScalar(e.zoom/-this.context.time.deltaTime*.01),e.offset=e.offset.add(t)}}),window.addEventListener("pointermove",n=>{this.overlay.enabled&&this.context.input.getPointerPressed(0)&&this.context.input.getTouchesPressedCount()===1&&(t.set(n.movementX,n.movementY),t.multiplyScalar(e.zoom*-this.context.time.deltaTime*.05),e.offset=e.offset.add(t))});let i=0;window.addEventListener("touchstart",n=>{if(n.touches.length<2){this.context.time.time-i<.3&&this.overlay.stop(),i=this.context.time.time;return}this._isPinching=!0,this._lastPinch=0}),window.addEventListener("touchmove",n=>{if(!this._isPinching||!this._material)return;let r=n.touches[0],s=n.touches[1],a=r.clientX-s.clientX,c=r.clientY-s.clientY,u=Math.sqrt(a*a+c*c);if(this._lastPinch!==0){let l=u-this._lastPinch;this._material.zoom-=l*.004}this._lastPinch=u}),window.addEventListener("touchend",()=>{this._isPinching=!1})}_isPinching=!1;_lastPinch=0;disable(){this._onResizeScreenFn&&(window.removeEventListener("resize",this._onResizeScreenFn),this._onResizeScreenFn=void 0),this._onKeyUpFn&&(window.removeEventListener("keyup",this._onKeyUpFn),this._onKeyUpFn=void 0),this._onMouseWheelFn&&(window.removeEventListener("wheel",this._onMouseWheelFn),this._onMouseWheelFn=void 0)}},vd=class extends Ly{set screenAspect(e){this.uniforms.screenAspect.value=e,this.needsUpdate=!0}set offset(e){let t=this.uniforms.offsetScale.value;t.x=e.x,t.y=e.y,this.uniforms.offsetScale.value=t,this.needsUpdate=!0}_offset=new md;get offset(){let e=this.uniforms.offsetScale.value;return this._offset.set(e.x,e.y),this._offset}set zoom(e){let t=this.uniforms.offsetScale.value;e<.001&&(e=.001),t.z=e,this.needsUpdate=!0}get zoom(){return this.uniforms.offsetScale.value.z}reset(){this.offset=this.offset.set(0,0),this.zoom=1,this.needsUpdate=!0}constructor(e){super(),this.uniforms={map:{value:e},screenAspect:{value:1},offsetScale:{value:new Hy(0,0,1,1)}},this.vertexShader=`
|
|
209
209
|
uniform sampler2D map;
|
|
210
210
|
uniform float screenAspect;
|
|
211
211
|
uniform vec4 offsetScale;
|
|
@@ -255,7 +255,7 @@ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
|
|
|
255
255
|
else
|
|
256
256
|
gl_FragColor = texture2D(map, vUv);
|
|
257
257
|
}
|
|
258
|
-
`}};var Sf=ra(ja(),1);import{EventDispatcher as Ed}from"three";var Pf=M("debugscreenshare");function Il(o){if(!!o)for(let e of o.getTracks())e.stop()}var
|
|
258
|
+
`}};var Sf=ra(ja(),1);import{EventDispatcher as Ed}from"three";var Pf=M("debugscreenshare");function Il(o){if(!!o)for(let e of o.getTracks())e.stop()}var Ln=class extends k{onPointerClick(){if(this.isReceiving){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}videoPlayer;device=0;get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){return this._currentStream?.active&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;let e=this._currentStream.getTracks();for(let t of e)if(t.readyState==="live")return!0}return!1}_net;_requestOpen=!1;_currentStream=null;_currentMode=0;awake(){Pf&&console.log(this),ie.registerWaitForAllowAudio(()=>{this.videoPlayer&&this._currentStream&&this._currentMode===2&&this.videoPlayer.setVideo(this._currentStream)})}start(){if(this.videoPlayer||(this.videoPlayer=R.getComponent(this.gameObject,xe)??void 0),!this.videoPlayer){console.error("Screencapture did not find a VideoPlayer component");return}let e=Dl.getOrCreate(this.context,this.guid);this._net=new wd(this.context,e),this._net.enable(),this._net.addEventListener(Of.ReceiveVideo,this.onReceiveVideo.bind(this))}async share(e){e?.device&&(this.device=e.device),this._requestOpen=!0;try{if(this.videoPlayer){let t=e?.constraints??{echoCancellation:!0,autoGainControl:!1},i={video:t,audio:t};switch(this.device){case 1:this.tryShareUserCamera(i,e);break;case 0:if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}let n=await navigator.mediaDevices.getDisplayMedia(i);this._requestOpen?this.setVideo(n,1):Il(n);break;case 2:let r=0,s=this.context.renderer.domElement.captureStream(r);this.setVideo(s,1);break}}}catch(t){if(t.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",t)}}close(){this._requestOpen=!1,this._currentStream&&(console.warn("Close current stream / disposing resources"),this._net?.stopSendingVideo(this._currentStream),Il(this._currentStream),this._currentMode=0,this._currentStream=null)}setVideo(e,t){if(e===this._currentStream||(this.close(),!e||!this.videoPlayer))return;this._currentStream=e,this._requestOpen=!0,this._currentMode=t,this.videoPlayer.setVideo(e),t===1&&this._net?.startSendingVideo(e),e.addEventListener("ended",()=>{this.close()})}onReceiveVideo(e){this.setVideo(e.stream,2)}async tryShareUserCamera(e,t){let i=(await navigator.mediaDevices.enumerateDevices()).filter(n=>n.kind==="videoinput");console.log("Request camera",i);for(let n of i)try{if(!this._requestOpen)break;if(n.kind!=="videoinput")continue;let r=n.deviceId;if(t?.deviceId!==void 0&&r!==t.deviceId)continue;e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=r);let s=await navigator.mediaDevices.getUserMedia(e);this._requestOpen?this.setVideo(s,1):Il(s),console.log("Selected camera",n);break}catch(r){console.warn(r)}}};E([x(xe)],Ln.prototype,"videoPlayer",2),E([x()],Ln.prototype,"device",2);var Of=(i=>(i.Connected="peer-user-connected",i.ReceiveVideo="receive-video",i.Disconnected="peer-user-disconnected",i))(Of||{}),yd=class{type="receive-video";stream;target;constructor(e,t){this.stream=e,this.target=t}},_d=class{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}};var xd=class extends Ed{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 yd(n,this);this.dispatchEvent(r)}})}},ns=class extends Ed{static getOrCreate(e,t){if(ns.instances.has(t))return ns.instances.get(t);let i=new ns(e,t);return ns.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 Sf.default(e)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){!this._peer||(this._peer.on("open",this.onPeerConnectFn),this._peer.on("call",this.onPeerReceiveCallFn))}unsubscribePeerEvents(){}onPeerConnect(e){Pf&&console.log("Peer connected as",e),this.context.connection.send("peer-user-connected",new _d(this,e))}onPeerReceivingCall(e){e.answer(),this.registerCall(e,"incoming")}registerCall(e,t){let 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,s=new xd(n,e,t);return r.push(s),e.on("error",a=>{console.error("Call error",a)}),e.on("close",()=>{console.log("Call ended",e.metadata),e.close();let a=r.indexOf(s);a!==-1&&r.splice(a,1)}),t==="incoming"&&(s.addEventListener("receive-video",a=>{this.dispatchEvent(a)}),e.on("stream",()=>{let a=setInterval(()=>{s.isOpen||(clearInterval(a),s.close())},2e3)})),s}},Dl=ns;L(Dl,"instances",new Map);var wd=class extends Ed{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(s=>s.userId===n)){let s=this.peer.makeCall(this.peer.getPeerIdFromUserId(n),t);s&&(e=!0,i.push(s))}}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 Fy,AdditiveBlending as By}from"three";var jn=class extends k{mode=0;shadowColor=new $(0,0,0,1);awake(){switch(this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break}}applyLightBlendMaterial(){let e=R.getComponent(this.gameObject,ne);if(e){let t=e.material;t.blending=By,this.applyMaterialOptions(t),t.onBeforeCompile=i=>{i.fragmentShader=i.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
|
|
259
259
|
|
|
260
260
|
// diffuse-only lighting with overdrive to somewhat compensate
|
|
261
261
|
// for the loss of indirect lighting and to make it more visible.
|
|
@@ -266,13 +266,13 @@ irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
|
|
|
266
266
|
// be blended onto the scene.
|
|
267
267
|
gl_FragColor = vec4(direct, max);
|
|
268
268
|
return;
|
|
269
|
-
`)}}}applyShadowMaterial(){let e=R.getComponent(this.gameObject,ne);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new Fy;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)}};E([w()],Ln.prototype,"mode",2),E([w($)],Ln.prototype,"shadowColor",2);import{RGBELoader as Vy}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as zy}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as Wy}from"three";var kf=M("debugautosync"),Cd=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new Td(e);return this._syncers[e.guid]=t,t}},Mf=new Cd,Td=class{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};data={};_boundEvent;get networkingKey(){return this.comp.constructor.name}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving.bind(this));let t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}notifyChanged(e,t){this._isReceiving||(this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;let e=this.comp.context.connection;if(!e||!e.isConnected){for(let t in this.changedProperties)delete this.changedProperties[t];return}for(let t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(let t in this.changedProperties){let 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)){kf&&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 Uy(o,e){let t=e!==o;if(!t&&o&&e){if(Array.isArray(o)&&Array.isArray(e))t=!0;else if(typeof o=="object"&&typeof e=="object"){for(let i of Object.keys(o))if(o[i]!==e[i]){t=!0;break}}}return t}function Gy(o){if(o.__autoPropertySyncHandler)return o.__autoPropertySyncHandler;let e=Mf.getOrCreateSyncer(o);return e?.init(o),o.__autoPropertySyncHandler=e,e}var Al=function(o){return function(e,t){let i=null,n=o?e[o]:void 0,r=e,s=r.__internalAwake;kf&&console.log(t);let a=t+"k__BackingField";r.__internalAwake=function(){if(this[a]!==void 0)return;this[a]=this[t],s.call(this),i=Mf.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(u){let l=this[a];this[a]=u,Uy(u,l)&&n?.call(this,u,l)!==!1&&Gy(this)?.notifyChanged(t,u)},get:function(){return this[a]},configurable:!0,enumerable:!0}),i?.init(this)}}};var jn=class extends k{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 zy:new Vy}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=Wy,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))}};E([Al("setSkybox"),w()],jn.prototype,"url",2),E([w()],jn.prototype,"allowDrop",2);import*as Ll from"three";import{Object3D as Ny}from"three";var Rd=class extends k{target=null;followFactor=.1;rotateFactor=.1;positionAxes=-1;flipForward=!1;_firstUpdate=!0;onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){let t=U(this.target),i=this._firstUpdate||e?1:F.clamp01(this.context.time.deltaTime*this.followFactor),n=this.worldPosition;this.positionAxes&2&&(n.x=F.lerp(n.x,t.x,i)),this.positionAxes&4&&(n.y=F.lerp(n.y,t.y,i)),this.positionAxes&8&&(n.z=F.lerp(n.z,t.z,i)),this.worldPosition=n}if(this.rotateFactor>0){let t=he(this.target);this.flipForward&&t.premultiply(Rd._invertForward);let i=this._firstUpdate||e?1:F.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},mt=Rd;L(mt,"_invertForward",new Ll.Quaternion().setFromAxisAngle(new Ll.Vector3(0,1,0),Math.PI)),E([w(Ny)],mt.prototype,"target",2),E([w()],mt.prototype,"followFactor",2),E([w()],mt.prototype,"rotateFactor",2),E([w()],mt.prototype,"positionAxes",2);import{Layers as Af}from"three";var Ks=M("debugspatialtrigger"),If=new Af,Df=new Af;function Xy(o,e){return If.mask=o,Df.mask=e,If.test(Df)}var gt=class extends k{triggerMask=0;onEnter;onStay;onExit;start(){Ks&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of en.triggers)Xy(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){Ks&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){Ks&&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)}};E([w()],gt.prototype,"triggerMask",2),E([w(ye)],gt.prototype,"onEnter",2),E([w(ye)],gt.prototype,"onStay",2),E([w(ye)],gt.prototype,"onExit",2);var Js=class extends k{triggerMask;boxHelper;start(){Ks&&console.log(this.name,this.triggerMask,this)}onEnable(){Js.triggers.push(this),this.boxHelper||(this.boxHelper=R.addNewComponent(this.gameObject,ke),this.boxHelper?.showHelper(null,Ks))}onDisable(){Js.triggers.splice(Js.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof gt&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof gt&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof gt&&t.onExitTrigger(this)},!1)}},en=Js;L(en,"triggers",[]),E([w()],en.prototype,"triggerMask",2);import*as mr from"three";var Lt=M("debugspectator"),ro=class extends k{cam=null;_mode=0;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){if(this._handler){let t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),R.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),R.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.localId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new Pd(this.context,this),this._networking=new Md(this.context,this),this._networking.awake(),R.setActive(this.gameObject,!1),this.cam=R.getComponent(this.gameObject,ae),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Sd(this.context,this.cam,this)),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),z.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),z.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),z.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.orbit=R.getComponent(this.context.mainCamera,Je)}onDestroy(){this.stopSpectating(),z.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),z.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),z.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()||R.setActive(this.gameObject,!0)}onXRSessionStart(e){!this.isSupportedPlatform()||(Lt&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){this.context.removeCamera(this.cam),R.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,"headset"),this.target=this.context.players.getPlayerView(this.localId)),Lt&&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 mr.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;let s=this.cam?.cam;this.context.updateAspect(s);let a=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,s),e.xr.isPresenting=a,e.xr.enabled=t,i?e.setRenderTarget(i):e.state.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){let e=this._mode===0;for(let t of se.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 se.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)}}},Sd=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=R.addNewComponent(this.cam.gameObject,mt)),this.target||(this.target=new mr.Object3D),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Lt&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Lt&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){this.target?.removeFromParent(),this.follow&&R.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){Lt&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(Lt&&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(Qy):i.quaternion.identity()}}},Qy=new mr.Quaternion().setFromAxisAngle(new mr.Vector3(0,1,0),Math.PI),Pd=class{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),window.addEventListener("keydown",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 fe;e.setMask(16777215);let t=this.context.physics.raycast(e);if(Lt&&console.log(...t),t?.length)for(let i of t){if(i.distance<.2)continue;let n=i.object,r=R.getComponentInParent(n,se),s=r?.connectionId;if(s){let a=this.context.players.getPlayerView(s);this.spectator.target=a,Lt&&console.log("spectate",s,r);break}}}},Od=class{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}},kd=class{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}},Md=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(Lt&&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 Od(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Lt&&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 kd(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){M("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){let t=e.targetUserId,i=e.guid;if(Lt&&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 Lt&&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):(Lt&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}};import*as jt from"three";import{Material as qy,Texture as Yy}from"three";var gr=class{texture;triangles;uv;vertices;_geometry};E([w(Yy)],gr.prototype,"texture",2);var jl=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new jt.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 s=e.triangles[r];i[r*3]=-e.vertices[s].x,i[r*3+1]=e.vertices[s].y,i[r*3+2]=0;let a=e.uv[s];n[r*2]=a.x,n[r*2+1]=1-a.y}return t.setAttribute("position",new jt.BufferAttribute(i,3)),t.setAttribute("uv",new jt.BufferAttribute(n,2)),t}},tn=class extends k{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=jl.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new jt.MeshBasicMaterial({color:16777215,side:jt.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new jt.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 jt.Mesh(jl.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))}}};E([w()],tn.prototype,"drawMode",2),E([w($)],tn.prototype,"color",2),E([w(qy)],tn.prototype,"sharedMaterial",2);var Ht=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 Ht).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new Ht).__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 Ee).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ee).__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 Ky}from"three";var Hl="SCAM";Fo(Hl,Ht.getRootAsSyncedCameraModel);var Ft=new xt,Id=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){Ft.clear();let i=Ft.createString(this.guid),n=Ft.createString(this.userId);Ht.startSyncedCameraModel(Ft),Ht.addGuid(Ft,i),Ht.addUserId(Ft,n);let r=U(e),s=ga(e);Ht.addPos(Ft,Ee.createVec3(Ft,r.x,r.y,r.z)),Ht.addRot(Ft,Ee.createVec3(Ft,s.x,s.y,s.z));let a=Ht.endSyncedCameraModel(Ft);Ft.finish(a,Hl),t.sendBinary(Ft.asUint8Array())}}},Fl=class extends k{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(Hl,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Hl,this._receiveCallback)}update(){for(let n in this.remoteCams){let r=this.remoteCams[n],s=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||s>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,s),r?.obj&&R.destroy(r.obj),delete this.remoteCams[n],r&&delete this.userToCamMap[r.userId],Fl.instances.push(r),this.context.players.removePlayerView(r.userId,"browser");continue}}if(z.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 Id(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let t=U(e),i=he(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,"browser"))}onReceivedRemoteCameraInfoBin(e){let t=e.guid();if(!t)return;let i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){let c=new Ge;c.context=this.context;let u=R.instantiate(this.cameraPrefab,c);n=this.remoteCams[t]={obj:u,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(u),this.userToCamMap[i]=t,Fl.instances.push(n);let l=R.getOrAddComponent(u,se);l.connectionId=i,l.avatar=u}else return;let r=n.obj;this.context.players.setPlayerView(i,r,"browser"),n.lastUpdate=this.context.time.realtimeSinceStartup,oe.markDirty(r);let s=e.pos();s&&gn(r,s.x(),s.y(),s.z());let a=e.rot();a&&ba(r,a.x(),a.y(),a.z())}},Hn=Fl;L(Hn,"instances",[]),E([w([Ky,qe])],Hn.prototype,"cameraPrefab",2);var Dd="view",Lf=M("debugsyncedroom"),ni=class extends k{roomName;urlParameterName;joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=M(Dd);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){let i=M(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=ch(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?(Lf&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(Lf&&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=M(Dd);return e||M(this.urlParameterName)}setRandomRoomUrlParameter(){let e=oc(),t=this.generateRoomName();M(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),sh(t,e)}generateRoomName(){return lh()+"_"+ah(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){let e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Dd,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};E([w()],ni.prototype,"roomName",2),E([w()],ni.prototype,"urlParameterName",2),E([w()],ni.prototype,"joinRandomRoom",2),E([w()],ni.prototype,"requireRoomParameter",2),E([w()],ni.prototype,"autoRejoin",2);function jf(){let o=M("testwindowcount")||0;o&&o>0&&Jy(o)}function Jy(o){if(M("testwindow"))return null;let e=new URL(window.location.href);Co(e.searchParams,qo,1),Co(e.searchParams,"testwindow",1);let t=e.toString(),i=[];window.onbeforeunload=()=>{for(let c of i)c.close()};let n=.05,r=128,s=0,a=0;for(let c=0;c<o;c++){s*r+r*.01>=window.innerWidth&&(a+=1,s=0);let u=s*(r*(1+n))+window.screenLeft,l=a*(r*(1+n))+window.screenTop+90+60*a;s+=1;let d=window.open(t,"test window "+c,`popup=yes width=${r} height=${r} top=${l} left=${u}`);if(!d){console.warn("Failed to open window");continue}i.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let h=0;h<i.length;h++){let b=i[h];b!==d&&b.close()}i.length=0}}}return i}import{Vector3 as $y}from"three";var oo=class extends k{awake(){jf()}},so=class extends k{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(No,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new Bl(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 xt(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=ku(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)}}}},Bl=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}}};L(Bl,"temp",new $y);import{MathUtils as e_}from"three";import{TransformControls as t_}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as i_}from"three/examples/jsm/controls/OrbitControls";var br=class extends k{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!ki||!this.context.mainCamera||(this.control=new t_(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=R.getComponentInParent(this.context.mainCamera,i_)??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=R.getComponentInParent(this.gameObject,ht);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(e_.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))}};E([w()],br.prototype,"isGizmo",2);import{LinearToneMapping as Hf,ACESFilmicToneMapping as n_,ReinhardToneMapping as r_}from"three";var Ul=M("debugvolume"),Bf=(i=>(i[i.None=0]="None",i[i.Neutral=1]="Neutral",i[i.ACES=2]="ACES",i))(Bf||{}),ao=class{overrideState=!1;value=0},Ti=class{active=!1;parameters},Bn=class extends Ti{mode;get isToneMapping(){return!0}},Un=class extends Ti{postExposure};function o_(o){return"mode"in o?Bn:"postExposure"in o?Un:Ti}var Ff=Symbol("volumeprofile"),Fn=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 s of this.components)if(s instanceof Bn){let a=s;if(!s.active||t){e.renderer.toneMapping=Hf;continue}switch(Ul&&console.log("VOLUME:",Bf[a.mode?.value??0]),a.mode?.value??0){case 0:e.renderer.toneMapping=Hf;break;case 1:e.renderer.toneMapping=r_;break;case 2:e.renderer.toneMapping=n_;break}}else if(s instanceof Un){let a=s;Ul&&console.log(a.postExposure);let c=Math.pow(2,a.postExposure?.value??0),u=a.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=u?c:1}}};E([w([o=>o_(o),Ti])],Fn.prototype,"components",2);var vr=class extends k{sharedProfile;awake(){Ul&&(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(){Ul&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};E([w(Fn)],vr.prototype,"sharedProfile",2);import{Vector3 as s_}from"three";var yr=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 k{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=nt.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),nt.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=R.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=R.getComponentsInChildren(i,ot);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]&&(R.destroy(this._instances[t].instance),delete this._instances[t])}onAttachedObjectFree(e){if(this._grabModels.length<=0)return;let t=this._grabModels[0];this.updateModel(t,e),this.endGrab(t)}onBeforeRender(){if(this.updateRendering(),!!this.prefab&&(this.prefab.visible=!1,this.context.time.frameCount%10===0))for(let e=0;e<nt.Current.length;e++){let t=nt.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new yr),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 s_;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,s=U(i);this.temp.set(r.x,r.y,r.z),s.lerp(this.temp,e),te(i,s)}}};import{Object3D as a_}from"three";var Ri=class extends k{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=R.getComponentInParent(this.gameObject,_e)}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)}}};E([w(a_)],Ri.prototype,"eyes",2),E([w()],Ri.prototype,"lastBlinkTime",2),E([w()],Ri.prototype,"blinkLength",2),E([w()],Ri.prototype,"eyesOpen",2);import*as Gl from"three";import{Object3D as Ad}from"three";var Ld=class extends k{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=R.getComponentInParent(this.gameObject,Bi)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=R.addNewComponent(this.gameObject,Bi)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new Gl.Vector3;currentTargetPoint=new Gl.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=U(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=U(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let s=Ld.forward;if(s.set(0,0,1),s.applyQuaternion(he(this.head)),s.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},Si=Ld;L(Si,"forward",new Gl.Vector3(0,0,1)),E([w(Ad)],Si.prototype,"head",2),E([w(Ad)],Si.prototype,"eyes",2),E([w(Ad)],Si.prototype,"target",2);import{Object3D as Uf}from"three";var l_=M("debugmouth"),Gn=class extends k{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=R.findObjectOfType(Ke,this.context),this.marker||(this.marker=R.getComponentInParent(this.gameObject,se))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){l_&&(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)}}}};E([w(Uf)],Gn.prototype,"idle",2),E([w(Uf)],Gn.prototype,"talking",2);var co=class extends k{voip=null;marker=null;_startPosition=null;awake(){this.voip=R.findObjectOfType(Ke,this.context),this.marker=R.getComponentInParent(this.gameObject,se)}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 Ud={};nh(Ud,{AlignmentConstraint:()=>En,Animation:()=>Wt,AnimationCurve:()=>Xt,AnimationTrackHandler:()=>Vn,Animator:()=>Ye,AnimatorController:()=>zt,AttachedObject:()=>nt,AudioListener:()=>Qt,AudioSource:()=>ie,AudioTrackHandler:()=>zn,AvatarBlink_Simple:()=>Ri,AvatarEyeLook_Rotation:()=>Si,AvatarLoader:()=>Tn,AvatarMarker:()=>se,AvatarModel:()=>nr,Avatar_Brain_LookAt:()=>Bi,Avatar_MouthShapes:()=>Gn,Avatar_MustacheShake:()=>co,Avatar_POI:()=>me,AxesHelper:()=>ji,BaseUIComponent:()=>Me,BasicIKConstraint:()=>Xr,BoxCollider:()=>Sn,BoxGizmo:()=>Ni,BoxHelperComponent:()=>ke,Button:()=>Bt,CallInfo:()=>gi,Camera:()=>ae,Canvas:()=>He,CanvasGroup:()=>cn,CapsuleCollider:()=>Ct,CharacterController:()=>bi,CharacterControllerInput:()=>Yt,Collider:()=>Tt,ColorAdjustments:()=>Un,ColorOverLifetimeModule:()=>Ji,ControlTrackHandler:()=>rn,Deletable:()=>Yr,DeleteBox:()=>ar,DeviceFlag:()=>lr,DragControls:()=>xi,DropListener:()=>Mn,Duplicatable:()=>wi,EmissionModule:()=>rt,EventList:()=>ye,EventListEvent:()=>rr,EventSystem:()=>Ve,EventTrigger:()=>Kr,FieldWithDefault:()=>Zr,FixedJoint:()=>to,FlyControls:()=>Jr,GltfExport:()=>Dt,GltfExportBox:()=>eo,Gradient:()=>ii,Graphic:()=>bt,GraphicRaycaster:()=>vo,GridHelper:()=>Yi,GridLayoutGroup:()=>bo,GroundProjectedEnv:()=>Ki,HingeJoint:()=>In,HorizontalLayoutGroup:()=>go,Image:()=>ln,InputField:()=>vt,Interactable:()=>Rt,Keyboard:()=>fo,LODGroup:()=>Dn,LODModel:()=>Ei,LayoutGroup:()=>un,Light:()=>Ae,LimitVelocityOverLifetimeModule:()=>le,LogStats:()=>uo,LookAtConstraint:()=>Ui,MainModule:()=>ge,MaskableGraphic:()=>an,MeshCollider:()=>sr,MeshRenderer:()=>hr,MinMaxCurve:()=>G,MinMaxGradient:()=>We,NestedGltf:()=>pr,Networking:()=>$t,NoiseModule:()=>K,ObjectRaycaster:()=>Tr,OffsetConstraint:()=>Ci,OrbitControls:()=>Je,ParticleBurst:()=>Zi,ParticleSystem:()=>je,ParticleSystemRenderer:()=>$i,PlayableDirector:()=>sn,PlayerColor:()=>ot,PointerEventData:()=>Jt,RGBAColor:()=>$,RawImage:()=>Er,Raycaster:()=>Cr,Rect:()=>wr,RectTransform:()=>st,ReflectionProbe:()=>It,RemoteSkybox:()=>jn,Renderer:()=>ne,RendererLightmap:()=>Xi,Rigidbody:()=>J,RotationBySpeedModule:()=>Le,RotationOverLifetimeModule:()=>Ne,ScreenCapture:()=>An,ShadowCatcher:()=>Ln,ShapeModule:()=>be,SignalAsset:()=>_r,SignalReceiver:()=>nn,SignalReceiverEvent:()=>xr,SignalTrackHandler:()=>on,Size:()=>ho,SizeOverLifetimeModule:()=>At,SkinnedMeshRenderer:()=>$r,SmoothFollow:()=>mt,SpatialHtml:()=>yo,SpatialTrigger:()=>en,SpatialTriggerReceiver:()=>gt,SpectatorCamera:()=>ro,SphereCollider:()=>Rn,Sprite:()=>gr,SpriteRenderer:()=>tn,SyncedCamera:()=>Hn,SyncedRoom:()=>ni,SyncedTransform:()=>ht,TeleportTarget:()=>dr,TestRunner:()=>oo,TestSimulateUserData:()=>so,Text:()=>Ce,TextureSheetAnimationModule:()=>ve,ToneMapping:()=>Bn,TrailModule:()=>fr,TransformGizmo:()=>br,UIRaycastUtils:()=>Zt,UIRootComponent:()=>Vi,UsageMarker:()=>St,VRUserState:()=>Mt,VelocityOverLifetimeModule:()=>Pe,VerticalLayoutGroup:()=>mo,VideoPlayer:()=>xe,Voip:()=>Ke,Volume:()=>vr,VolumeComponent:()=>Ti,VolumeParameter:()=>ao,VolumeProfile:()=>Fn,WebAR:()=>kn,WebARSessionRoot:()=>Pt,WebXR:()=>z,WebXRAvatar:()=>Ot,WebXRController:()=>Z,WebXRSync:()=>Wi,XRFlag:()=>_e,XRGrabModel:()=>yr,XRGrabRendering:()=>lo,XRRig:()=>On,XRState:()=>ft,__Ignore:()=>ls});var c_=M("logstats"),uo=class extends k{onEnable(){console.log(this),c_&&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 zf from"three";var _r=class{guid},xr=class{signal;reaction;$serializedTypes={signal:_r,reaction:ye}},nn=class extends k{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)}}};E([w(xr)],nn.prototype,"events",2);import*as ee from"three";import{Quaternion as u_,Vector3 as d_}from"three";var rs=M("debugtimeline"),os=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 s=1,a=!1;return r.easeInDuration>0&&(s*=Math.min((e-r.start)/r.easeInDuration,1)),r.easeOutDuration>0&&!a&&(s*=Math.min((r.end-e)/r.easeOutDuration,1)),s}return 0}},jd=class{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){let t=e.getClip();this.clip=t;let i=e.getRoot(),n=i.name+".position",r=i.name+".quaternion";rs&&console.log(t.name,t.tracks,n);for(let s of t.tracks)if(!(s.times.length<=0)){if(s.name.endsWith(n))this.rootStartPosition=new ee.Vector3().fromArray(s.values,0),this.rootEndPosition=new ee.Vector3().fromArray(s.values,s.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),rs&&console.log(this.rootPositionOffset);else if(s.name.endsWith(r)&&(this.rootStartQuaternion=new ee.Quaternion().fromArray(s.values,0),this.rootEndQuaternion=new ee.Quaternion().fromArray(s.values,s.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),rs)){let a=new ee.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}},Vn=class extends os{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",s=n+".quaternion",a=!1,c=!1;for(let u of t.tracks)u.name.endsWith(r)?(a=!0,this.createPositionInterpolant(t,e,u)):u.name.endsWith(s)&&(c=!0,this.createRotationInterpolant(t,e,u));if(!a||!c){let u=this.mixer?.getRoot(),l=t.tracks[0],d=l.name.lastIndexOf("."),h=l.name.substring(0,d),b=h.substring(h.lastIndexOf(".")+1),_=u.getObjectByName(b);if(_)if(a){if(!c){let v=t.tracks[0].name.substring(0,d)+".quaternion";rs&&console.warn("Create quaternion track",b,_);let y=_.quaternion,f=new ee.QuaternionKeyframeTrack(v,[0,t.duration],[y.x,y.y,y.z,y.w,y.x,y.y,y.z,y.w]);t.tracks.push(f),this.createRotationInterpolant(t,e,f)}}else{let v=h+".position";rs&&console.warn("Create position track",b,_);let y=_.position,f=new ee.VectorKeyframeTrack(v,[0,t.duration],[y.x,y.y,y.z,y.x,y.y,y.z]);t.tracks.push(f),this.createPositionInterpolant(t,e,f)}}}bind(){if(!this._didBind){this._didBind=!0,rs&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(let e of this.actions){let t=new jd(e);this._actionOffsets.push(t)}for(let e of this.models){let t=e.asset,i=t.position,n=t.rotation;i.x!==void 0&&(i.isVector3||(t.position=new d_(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new u_(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 ee.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new ee.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new ee.Vector3;_totalOffsetRotation=new ee.Quaternion;_totalOffsetPosition2=new ee.Vector3;_totalOffsetRotation2=new ee.Quaternion;_summedPos=new ee.Vector3;_tempPos=new ee.Vector3;_summedRot=new ee.Quaternion;_tempRot=new ee.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 s=this.models[r],a=this.actions[r],c=s.asset;a.weight=0;let u=e>=s.start&&e<=s.end,l=s.postExtrapolationMode,d=u;if(!d&&!n&&s.end<e&&s.postExtrapolationMode!==0){let h=r<this.clips.length-1?this.models[r+1]:null;(!h||h.start>e)&&(d=!0,n=!0)}if(d){let h=1;h*=this.evaluateWeight(e,r,this.models,d);let b=this.getClipTime(e,s),_=0,v=c.duration;if(u){if(c.loop)for(_+=Math.floor(b/(v+1e-6));b>v;)b-=v}else if(!u)switch(l){case 2:b%=v;break;case 3:let m=Math.floor(b/v)%2!==0;b%=v,m&&(b=v-b);break}a.time=b,a.timeScale=0;let y=h*this.director.weight;if(a.weight=y,a.clampWhenFinished=!0,a.isRunning()||a.play(),this._useclipOffsets){let f=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,m=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-h),t+=1;let p=this._summedPos.set(0,0,0),g=this._tempPos.set(0,0,0),x=this._summedRot.identity(),C=this._tempRot.identity(),T=c.rotation,S=new ee.Quaternion;S.slerp(T,h);let D=this._actionOffsets[r];if(D.hasOffsets)for(let A=0;A<_;A++)D.rootPositionOffset?g.copy(D.rootPositionOffset):g.set(0,0,0),g.applyQuaternion(x).applyQuaternion(S),D.rootQuaternionOffset&&(C.copy(D.rootQuaternionOffset),x.multiply(C)),p.add(g);m.multiply(S),m.multiply(x),p.add(c.position),f.add(p)}}}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 ee.Quaternion;this.ensureTrackOffsets();let s=this.trackOffset?.rotation;i.createInterpolant=()=>{let a=n(),c=a.evaluate.bind(a);return a.evaluate=u=>{let l=c(u);return r.set(l[0],l[1],l[2],l[3]),r.premultiply(this._totalOffsetRotation),s&&r.premultiply(s),l[0]=r.x,l[1]=r.y,l[2]=r.z,l[3]=r.w,l},a}}createPositionInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new ee.Vector3;this.ensureTrackOffsets();let s=this.trackOffset?.rotation,a=this.trackOffset?.position,c;i.createInterpolant=()=>{let u=n(),l=u.evaluate.bind(u);return u.evaluate=d=>{let h=l(d);return r.set(h[0],h[1],h[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(b=>b.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),s&&r.applyQuaternion(s),a&&(r.x-=a.x,r.y+=a.y,r.z+=a.z),h[0]=r.x,h[1]=r.y,h[2]=r.z,h},u}}},zn=class extends os{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return Oi(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 ee.Audio(this.listener);i.setVolume(e.asset.volume);let n=new ee.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}}},on=class extends os{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 a of this.receivers)!a||a.invoke(i.asset)}}else i.emitOnce||(this.didTrigger[t]=!1)}}},Zs=class extends os{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;Zs.resolved[r]?n.sourceObject=Zs.resolved[r]:(n.sourceObject=R.findByGuid(r,e.scene),Zs.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=R.getComponent(n.sourceObject,sn);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 s=n.sourceObject;s.visible=!0}if(n.updateDirector){let s=this.timelines[t];s&&(s.isPlaying&&s.pause(),s.time=r,s.evaluate())}}else{let r=this._previousActiveModel?.asset;if(n.controlActivation){let s=n.sourceObject;r?.sourceObject!==s&&(s.visible=!1)}}}}},rn=Zs;L(rn,"resolved",{});var Vf=M("debugtimeline");var Vl=class extends k{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(){Vf&&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 a of t.clips)a.start<=e&&e<=a.end&&(r=!0);let s=n;s.visible!==void 0&&(s.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=gs(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=R.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Vf&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),Vl.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=Vl.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 s=t.outputs[r];typeof s.enabled=="boolean"&&(s.enabled=!1);let a=s?.gameObject?.animations;if(a){let c=new Vn;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let u=0;u<t.clips.length;u++){let l=t.clips[u],d=l.asset;if(!d){console.error("MISSING anim model?","clip#"+u,l,t,this.playableAsset,this.name);continue}let h=d.clip,b=h;if((typeof b=="string"||typeof b=="number")&&(b=a.find(v=>v.name===h)),!b){console.warn("Could not find animationClip for model",l,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new zf.AnimationMixer(s.gameObject)),c.clips.push(b),c.mixer.uncacheAction(b),c.createHooks(l.asset,b);let _=c.mixer.clipAction(b);c.actions.push(_),c.models.push(l)}this._animationTracks.push(c)}}}else if(t.type==="AudioTrack"){if(t.clips.length<=0)continue;e.push(t)}else if(t.type==="MarkerTrack"){let r=new on;r.director=this,r.track=t;for(let s of t.markers)switch(s.type){case"SignalEmitter":r.models.push(s),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let s=R.getComponent(this.gameObject,nn);s&&(r.receivers.push(s),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new on;r.director=this,r.track=t;for(let s of t.markers)r.models.push(s),r.didTrigger.push(!1);for(let s of t.outputs)r.receivers.push(s);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new rn;r.director=this,r.track=t;for(let s of t.clips)r.models.push(s);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}ie.registerWaitForAllowAudio(()=>{let t=R.findObjectOfType(Qt,this.context);if(!!t)for(let i of e){let n=new zn;n.director=this,n.track=i,n.listener=t.listener;for(let r=0;r<i.clips.length;r++){let s=i.clips[r];n.addModel(s)}this._audioTracks.push(n)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},sn=Vl;L(sn,"createTrackFunctions",{});import{Color as m_,Texture as Yf}from"three";import*as Fd from"three-mesh-ui";import{Matrix4 as p_,Object3D as f_,Vector2 as Qf,Vector3 as Hd}from"three";import{FrontSide as Wf,DoubleSide as Nf}from"three";function ss(o,e){if(!o)return;let t=o.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?Nf:Wf,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?Nf:Wf,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of o.children)ss(i,e)}function zl(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);let i=Proxy.revocable(o[e],{set(s,a,c,u){let l=s[a],d=Reflect.set(s,a,c,u);return t(c,l),d}}),n=i.revoke,r=o[e];return i.revoke=()=>{o[e]=r,n()},o[e]=i.proxy,i}function Xf(o,e,t=3){let i=o.__scheduledActions;i||(i=o.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*a(){e?.call(o),r[n]=null}let c=o.startCoroutine(a(),t);r[n]=c}var qf=M("debugui"),ho=class{width;height},wr=class{x;y;width;height},st=class extends Me{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new Hd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new p_,this.rectBlock=new f_,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new Hd),zl(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)&&(qf&&console.log("updating",this.name),this.applyTransform()),Ve.ensureUpdateMeshUI(Fd,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},qf&&console.log(this.name,e);let t=new Fd.Block(e);return this._createdBlocks.push(t),t}};E([w(wr)],st.prototype,"rect",2),E([w(Qf)],st.prototype,"sizeDelta",2),E([w(Hd)],st.prototype,"anchoredPosition3D",2),E([w(Qf)],st.prototype,"pivot",2);var bt=class extends Me{get isGraphic(){return!0}get color(){return this._color||(this._color=new $(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 $(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=R.getComponent(this.gameObject,st)),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(),zl(this,"_color",()=>Xf(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)}};E([w($)],bt.prototype,"color",1),E([w()],bt.prototype,"raycastTarget",2);var an=class extends bt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var Wl=class{texture;rect};E([w(Yf)],Wl.prototype,"texture",2);var ln=class extends an{sprite;isBuiltinSprite(){switch(this.sprite?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":return!0}return this.sprite?.texture?.image?.width===32&&this.sprite?.texture?.image?.height===32}onBeforeCreate(e){this.isBuiltinSprite()&&(e.borderRadius=5,e.borderColor=new m_(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};E([w(Wl)],ln.prototype,"sprite",2);var Er=class extends an{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};E([w(Yf)],Er.prototype,"mainTexture",2);var as=M("debugbutton");var Bt=class extends k{onClick;_isHovered=!1;onPointerEnter(e){as&&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(){as&&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){as&&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){as&&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){as&&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(),as&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.SetTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=R.getComponent(this.gameObject,ln),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);let t=this.getFinalColor(e.color,this.colors?.normalColor),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 s=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(a);let c=this.getFinalColor(e.color,this.colors?.selectedColor),u={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(u);let l=this.getFinalColor(e.color,this.colors?.disabledColor),d={state:"disabled",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(d)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};E([w(ye)],Bt.prototype,"onClick",2),E([w()],Bt.prototype,"colors",2),E([w()],Bt.prototype,"transition",2),E([w()],Bt.prototype,"animationTriggers",2),E([w(Ye)],Bt.prototype,"animator",2),E([w()],Bt.prototype,"interactable",1);var Bd=class extends Vi{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof Bd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),ss(this.shadowComponent,this);for(let e of R.getComponentsInChildren(this.gameObject,Me))ss(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(F.toRadians(e.fieldOfView)*n)*(e.aspect*1.333333),s=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=s;break;case 2:break}}},He=Bd;E([w()],He.prototype,"renderOnTop",1),E([w()],He.prototype,"depthWrite",1),E([w()],He.prototype,"doubleSided",1),E([w()],He.prototype,"castShadows",1),E([w()],He.prototype,"receiveShadows",1),E([w()],He.prototype,"renderMode",1),E([w(He)],He.prototype,"rootCanvas",1),E([w()],He.prototype,"scaleFactor",1);var cn=class extends k{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of R.getComponentsInChildren(this.gameObject,bt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};E([w()],cn.prototype,"alpha",1),E([w()],cn.prototype,"interactable",2),E([w()],cn.prototype,"blocksRaycasts",2);import*as Kf from"three-mesh-ui";import{Color as j}from"three";var g_=M("debugtext");var Ce=class extends bt{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){g_&&console.log(this);let t=this.verticalOverflow==0&&this.horizontalOverflow==0;t&&(this.context.renderer.localClippingEnabled=!0);let i=this.rectTransform;this._textContainer=this.uiObject=this.createBlock(i,t,null,!0),this.createText(this.text,this.getTextOpts(),this.supportRichText),this.uiObject,this.uiObject=this.createBlock(i,t,this.uiObject,!1)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;_textContainer=null;getTextOpts(){let e=this.fontSize,t={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&(this.uiObject.onAfterUpdate=this.updateWidth.bind(this))}createBlock(e,t,i,n=!1){let r={};r.hiddenOverflow=t,r.interLine=(this.lineSpacing-1)*this.fontSize*1.333,this.getAlignment(r,n);let s=e.createNewBlock(r);return i&&(Array.isArray(i)?s.add(...i):s.add(i)),s}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((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[kt]===void 0&&(e[kt]=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 s=this.getNextTag(e,n.endIndex);if(s){let a=this.getText(e,n,s);this.handleTag(n,t,r),this.createText(a,t,!1)}else{let a=e.substring(n.endIndex);this.handleTag(n,t,r),this.createText(a,t,!1)}n=s}}else{let n={...t};n.content=e;let r=new Kf.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 s=this._textMeshUi[r];!s.textContent||(ss(s,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 s=n.previousValues[r];t[r]=s}}}else if(e.type.includes("color")){let n=new $s(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=b_(r)}else t.fontColor=new j(1,1,1)}else if(e.type=="b"){let n=new $s(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new $s(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=Oi(this.sourceId,this.font),this.font):null}};E([w(He)],Ce.prototype,"canvas",2),E([w()],Ce.prototype,"alignment",2),E([w()],Ce.prototype,"verticalOverflow",2),E([w()],Ce.prototype,"horizontalOverflow",2),E([w()],Ce.prototype,"lineSpacing",2),E([w()],Ce.prototype,"supportRichText",2),E([w()],Ce.prototype,"font",2),E([w()],Ce.prototype,"fontStyle",2),E([w()],Ce.prototype,"text",1),E([w()],Ce.prototype,"fontSize",1);var $s=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function b_(o){if(o.startsWith("#")){let t=o.substring(1);var e=parseInt(t,16);let i=e>>16&255,n=e>>8&255,r=e&255;return new j(i/255,n/255,r/255)}switch(o){case"black":return new j(0,0,0);case"white":return new j(1,1,1);case"red":return new j(1,0,0);case"lime":return new j(0,1,0);case"blue":return new j(0,0,1);case"yellow":return new j(1,1,0);case"cyan":return new j(0,1,1);case"magenta":return new j(1,0,1);case"silver":return new j(.75,.75,.75);case"gray":return new j(.5,.5,.5);case"maroon":return new j(.5,0,0);case"olive":return new j(.5,.5,0);case"green":return new j(0,.5,0);case"purple":return new j(.5,0,.5);case"teal":return new j(0,.5,.5);case"navy":return new j(0,0,.5);case"darkred":return new j(.54,0,0);case"brown":return new j(.55,.27,0);case"firebrick":return new j(.69,.13,.13);case"crimson":return new j(.86,.08,.24);case"tomato":return new j(1,.39,.28);case"coral":return new j(1,.49,.31);case"indianred":return new j(.6,.31,.51);case"lightcoral":return new j(.94,.5,.5);case"darkorange":return new j(1,.55,0);case"orange":return new j(1,.65,0);case"gold":return new j(1,.84,0);case"darkgoldenrod":return new j(.72,.53,.04);case"goldenrod":return new j(.85,.65,.13);case"palegoldenrod":return new j(.93,.87,.67);case"darkkhaki":return new j(.74,.7,.42);case"khaki":return new j(.94,.9,.55);case"yellowgreen":return new j(.6,.8,.19);case"darkolivegreen":return new j(.33,.42,.18);case"olivedrab":return new j(.42,.56,.14);case"lawngreen":return new j(.49,.99,0);case"chartreuse":return new j(.5,1,0);case"greenyellow":return new j(.68,1,.18);case"darkgreen":return new j(0,.39,0);case"forestgreen":return new j(.13,.55,.13);case"limegreen":return new j(.19,.8,.19);case"lightgreen":return new j(.56,.93,.56);case"palegreen":return new j(.59,.98,.59);case"darkseagreen":return new j(.56,.74,.56);case"mediumspringgreen":return new j(0,.98,.6);case"springgreen":return new j(0,1,.5);case"seagreen":return new j(.18,.31,.31);case"mediumaquamarine":return new j(.4,.8,.66);case"mediumseagreen":return new j(.24,.7,.44);case"lightseagreen":return new j(.13,.7,.67);case"darkslategray":return new j(.18,.31,.31);case"darkcyan":return new j(0,.55,.55);case"aqua":return new j(0,1,1);case"lightcyan":return new j(.8,1,1);case"darkturquoise":return new j(0,.81,.82);case"turquoise":return new j(0,.82,.82);case"mediumturquoise":return new j(.28,.82,.8);case"paleturquoise":return new j(.68,1,.93);case"aquamarine":return new j(.5,1,.83);case"powderblue":return new j(.69,.88,.9);case"cadetblue":return new j(.37,.62,.63);case"steelblue":return new j(.27,.51,.71);case"cornflowerblue":return new j(.39,.58,.93);case"deepskyblue":return new j(0,.7,1);case"dodgerblue":return new j(.12,.56,1);case"lightblue":return new j(.68,.85,.9);case"skyblue":return new j(.53,.81,.92);case"lightskyblue":return new j(.53,.81,.98);case"midnightblue":return new j(.18,.18,.31);case"darkblue":return new j(0,0,.55);case"mediumblue":return new j(0,0,.82);case"royalblue":return new j(.25,.41,.88);case"blueviolet":return new j(.54,.17,.89);case"indigo":return new j(.29,0,.51);case"darkslateblue":return new j(.28,.24,.55);case"slateblue":return new j(.42,.35,.8);case"mediumslateblue":return new j(.48,.41,.9);case"mediumpurple":return new j(.58,.44,.86);case"darkmagenta":return new j(.55,0,.55);case"darkviolet":return new j(.58,0,.83);case"darkorchid":return new j(.6,.2,.8);case"mediumorchid":return new j(.73,.33,.83);case"thistle":return new j(.84,.75,.85);case"plum":return new j(.87,.63,.87);case"violet":return new j(.93,.51,.93);case"fuchsia":return new j(1,0,1);case"orchid":return new j(.85,.44,.84);case"mediumvioletred":return new j(.78,.08,.52);case"palevioletred":return new j(.86,.44,.58);case"hotpink":return new j(1,.4,.71);case"deeppink":return new j(1,.08,.58);case"lightpink":return new j(1,.71,.76);case"pink":return new j(1,.75,.78);case"antiquewhite":return new j(.98,.92,.84);case"beige":return new j(.96,.96,.86);case"bisque":return new j(1,.89,.77);case"blanchedalmond":return new j(1,.92,.82);case"wheat":return new j(.96,.87,.87);case"cornsilk":return new j(1,.97,.86);case"lemonchiffon":return new j(1,.98,.8);case"lightgoldenrodyellow":return new j(.98,.98,.82);case"lightyellow":return new j(1,1,.8);case"saddlebrown":return new j(.55,.27,.07);case"sienna":return new j(.63,.32,.18);case"chocolate":return new j(.82,.41,.12);case"peru":return new j(.82,.52,.25);case"sandybrown":return new j(.96,.64,.38);case"burlywood":return new j(.87,.72,.53);case"tan":return new j(.82,.71,.55);case"rosybrown":return new j(.74,.56,.56);case"moccasin":return new j(1,.89,.71);case"navajowhite":return new j(1,.87,.68);case"peachpuff":return new j(1,.85,.73);case"mistyrose":return new j(1,.89,.88);case"lavenderblush":return new j(1,.94,.93);case"linen":return new j(.98,.94,.9);case"oldlace":return new j(.99,.96,.9);case"papayawhip":return new j(1,.94,.84);case"seashell":return new j(1,.96,.93);case"mintcream":return new j(.98,1,.98);case"slategray":return new j(.44,.5,.56);case"lightslategray":return new j(.47,.53,.6);case"lightsteelblue":return new j(.69,.77,.87);case"lavender":return new j(.9,.9,.98);case"floralwhite":return new j(1,.98,.98);case"aliceblue":return new j(.94,.97,1);case"ghostwhite":return new j(.97,.97,1);case"honeydew":return new j(.94,1,.94);case"ivory":return new j(1,1,.94);case"azure":return new j(.94,1,1);case"snow":return new j(1,.98,.98);case"dimgray":return new j(.4,.4,.4);case"darkgray":return new j(.66,.66,.66);case"lightgray":return new j(.83,.83,.83);case"gainsboro":return new j(.86,.86,.86);case"whitesmoke":return new j(.96,.96,.96)}return new j(1,1,1)}var po=M("debuginputfield"),X=class extends k{get text(){return this.textComponent?.text??""}get isFocused(){return X.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){po&&console.log(this.name,this)}onEnable(){X.htmlField||(X.htmlField=document.createElement("input"),X.htmlField.classList.add("ar"),document.body.appendChild(X.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),X.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&R.setActive(this.placeholder.gameObject,!1)}onDisable(){X.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){po&&console.log("CLICK",e,X.active),X.activeTime=this.context.time.time,X.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();X.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-X.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(X.active!==this&&(po&&console.log("Select",this.name,this,X.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,X.htmlField?.value),X.active?.onDeselected(),X.active=this,this.placeholder&&R.setActive(this.placeholder.gameObject,!1),X.htmlField)){if(X.htmlField.value=this.textComponent?.text||"",po&&console.log("set input field value",X.htmlField.value),this.context.isInXR){let e=this.context.arOverlayElement;e&&(X.htmlField.style.width="0px",X.htmlField.style.height="0px",e.append(X.htmlField))}this.selectInputField()}}onDeselected(){X.active===this&&(X.active=null,po&&console.log("Deselect",this.name,this),X.htmlField&&(X.htmlField.blur(),document.body.append(X.htmlField),X.htmlField.style.width="",X.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&R.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(X.active===this){if(po&&console.log(e.code,e,X.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}X.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&R.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&X.htmlField){if(this.textComponent.text!==X.htmlField.value){po&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=X.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=X.htmlField.value}}selectInputField(){X.htmlField&&(X.htmlField.setSelectionRange(X.htmlField.value.length,X.htmlField.value.length),X.htmlField.focus())}},vt=X;L(vt,"active",null),L(vt,"activeTime",-1),L(vt,"htmlField",null),E([w(Ce)],vt.prototype,"textComponent",2),E([w(Ce)],vt.prototype,"placeholder",2),E([w(ye)],vt.prototype,"onValueChanged",2),E([w(ye)],vt.prototype,"onEndEdit",2);import*as Jf from"three-mesh-ui";import*as ea from"three";var Zf=(a=>(a[a.fr=0]="fr",a[a.ru=1]="ru",a[a.de=2]="de",a[a.es=3]="es",a[a.el=4]="el",a[a.nord=5]="nord",a[a.eng=6]="eng",a))(Zf||{}),fo=class extends Me{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=Zf[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=R.getComponent(this.gameObject,st);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:Ko+"/"+t+"-msdf.json",fontTexture:Ko+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new ea.Color(this.colors.keyboardBack),backspaceTexture:Ko+"/backspace.png",shiftTexture:Ko+"/shift.png",enterTexture:Ko+"/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 Jf.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(s=>{s.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new ea.Color(this.colors.button),backgroundOpacity:1}}),s.setState("normal"),s.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new ea.Color(this.colors.hovered),backgroundOpacity:1}}),s.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new ea.Color(this.colors.selected),backgroundOpacity:1},onSet:()=>{let a=s.info.input,c=s.info.command;if(this._lastKeyPressed!==a)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedTime>.05)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedStartTime<.5||c=="switch"||c=="shift"||c=="switch-set"){this._lastKeyPressedTime=this.context.time.time;return}if(this._lastKeyPressedTime=this.context.time.time,this._lastKeyPressed=a,c)switch(c){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
|
|
270
|
-
`);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else s.info.input!==void 0&&this.tryAppend(s.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var un=class extends k{reverseArrangement=!1},mo=class extends un{},go=class extends un{},bo=class extends un{};var Cr=class extends k{awake(){Ve.createIfNoneExists(this.context)}onEnable(){Ve.instance?.register(this)}onDisable(){Ve.instance?.unregister(this)}performRaycast(e=null){return null}},Tr=class extends Cr{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new fe,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},vo=class extends Tr{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as $f from"three";import{HTMLMesh as v_}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as y_}from"three/examples/jsm/interactive/InteractiveGroup.js";var yo=class extends k{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 y_(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new v_(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=ga(this.gameObject).clone();ba(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let s=new $f.Box3;s.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);let a=s.max.x-s.min.x,c=s.max.y-s.min.y;if(this.keepAspect){let l=a/c;a>c?i.scale.set(1/a,1/c/l,1):i.scale.set(1/a*l,1/c,1)}else i.scale.set(1/a,1/c,1);let u=this.gameObject.scale;i.scale.multiply(u)},1)}};var ls=class{};var ta=class extends k{toggleKey="p";update(){this.context.input.isKeyDown("p")&&this.context.domElement.classList.toggle("presentation-mode")}};import*as em from"three";import{Raycaster as w_,Vector3 as E_}from"three";import*as Nl from"three";import{MeshLine as __,MeshLineMaterial as x_}from"three.meshline";var Gd=class{id=0;points=[];line=new __;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 Nl.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=Gd.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 x_({color:10066329,lineWidth:.01})},_o=Gd;L(_o,"wp",new Nl.Vector3);var Rr=class extends k{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=R.findByGuid(t,this.context.scene);if(!!i)return this.internalStartLine(i,e,!1),this.inFlight[e]}internalStartLine(e,t,i=!0,n){let r=new _o(e??this.context.scene,n);r.id=t,this.inFlight[t]=r,i&&this.sendLineStart(r);let s;return this.freeBuffer.length<=0?s=new Array:s=this.freeBuffer.pop(),this.buffer[t]=s,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,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 C_}from"three.meshline";var Xl=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new E_,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},Ql=class extends k{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=R.getComponent(this.gameObject,Rr),this.lines||(this.lines=R.addNewComponent(this.gameObject,Rr))),this.orbit=R.findObjectOfType(Je,this.context)??void 0,this._states.mouse=new Xl;let e={};Z.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),Z.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),Z.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);Ql._raycaster.setFromCamera(t,this.context.mainCamera);let i=Ql._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 s=this._states[e];if(s||(this._states[e]=new Xl,s=this._states[e]),n)s.isDrawing=!1,s.currentHandle&&(this.lines.endLine(s.currentHandle),s.currentHandle=null);else if(i){if(r)return s;let a=this.getHit(t),c=null,u=s.prevDistance;if(a)s.currentHandle||(s.maxDistance=a.distance),c=a.point,c.add(a.face.normal.multiplyScalar(.01)),s.prevDistance=a.distance;else if(s.maxDistance>0){let l=s.maxDistance;if(!s.currentHandle&&s.lastHit){let d=U(this.context.mainCamera);l=s.lastHit.distanceTo(d)}c=t.origin.add(t.direction.multiplyScalar(s.maxDistance)),s.prevDistance=s.maxDistance}if(c){if(!s.currentHandle){let l=s.lastParent??this.gameObject;this.addToPaintedObject&&a&&(l=a.object),s.lastParent=l,s.currentHandle=this.lines.startLine(l,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(s.prevDistance>s.maxDistance||Math.abs(u-s.prevDistance)>.2)){let l=s.maxDistance;c=t.origin.add(t.direction.multiplyScalar(l)),s.prevDistance=l}if(s.lastHit&&s.lastHit.distanceTo(c)<s.prevDistance*.01)return s;this.lines.updateLine(s.currentHandle,{point:c}),s.lastHit.copy(c)}s.isDrawing=s.currentHandle!==null}return s}_raycastOptions=new fe;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(!!R.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=ot.colorFromHashCode(ot.hashCode(this.context.connection.connectionId)):e=new em.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new C_({color:e,lineWidth:F.lerp(.005,.01,Math.random())})}},cs=Ql;L(cs,"_raycaster",new w_);import{Object3D as T_}from"three";var us=class extends k{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=R.getComponent(t,Pi);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Pi.all.length-1;t>=0;t--){let i=Pi.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};E([w(qe)],us.prototype,"asset",2);var ri=class extends k{static get all(){return ri._all}static get local(){return ri._local}static isLocalPlayer(e){return e instanceof T_?R.getComponentInParent(e,ri)?.isLocalPlayer??!1:e instanceof Et?R.getComponentInParent(e.gameObject,ri)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&ri.local.push(this),ri.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(){Oo(this.gameObject,this.context.connection)}onDestroy(){if(ri.all.splice(ri.all.indexOf(this),1),this.isLocalPlayer){let e=ri._local.indexOf(this);e>=0&&ri._local.splice(e,1)}}},Pi=ri;L(Pi,"_all",[]),L(Pi,"_local",[]),E([Al(),w()],Pi.prototype,"owner",2);En[I]=!0;Wt[I]=!0;Xt[I]=!0;Ye[I]=!0;zt[I]=!0;Qt[I]=!0;ie[I]=!0;nr[I]=!0;Tn[I]=!0;ji[I]=!0;Xr[I]=!0;ke[I]=!0;ae[I]=!0;bi[I]=!0;Yt[I]=!0;Tt[I]=!0;Rn[I]=!0;Sn[I]=!0;sr[I]=!0;Ct[I]=!0;ar[I]=!0;Yr[I]=!0;lr[I]=!0;xi[I]=!0;Mn[I]=!0;wi[I]=!0;gi[I]=!0;rr[I]=!0;ye[I]=!0;Kr[I]=!0;Jr[I]=!0;Ni[I]=!0;eo[I]=!0;Dt[I]=!0;Yi[I]=!0;Ki[I]=!0;Rt[I]=!0;St[I]=!0;to[I]=!0;In[I]=!0;Ae[I]=!0;Ei[I]=!0;Dn[I]=!0;Ui[I]=!0;pr[I]=!0;$t[I]=!0;Ci[I]=!0;Je[I]=!0;$i[I]=!0;je[I]=!0;ii[I]=!0;G[I]=!0;We[I]=!0;ge[I]=!0;Zi[I]=!0;rt[I]=!0;Ji[I]=!0;At[I]=!0;be[I]=!0;K[I]=!0;fr[I]=!0;Pe[I]=!0;ve[I]=!0;Ne[I]=!0;Le[I]=!0;le[I]=!0;ot[I]=!0;It[I]=!0;Zr[I]=!0;ne[I]=!0;hr[I]=!0;$r[I]=!0;Xi[I]=!0;J[I]=!0;An[I]=!0;Ln[I]=!0;jn[I]=!0;mt[I]=!0;gt[I]=!0;en[I]=!0;ro[I]=!0;gr[I]=!0;tn[I]=!0;Hn[I]=!0;ni[I]=!0;ht[I]=!0;oo[I]=!0;so[I]=!0;br[I]=!0;xe[I]=!0;Ke[I]=!0;ao[I]=!0;Ti[I]=!0;Bn[I]=!0;Un[I]=!0;Fn[I]=!0;vr[I]=!0;Pt[I]=!0;z[I]=!0;kn[I]=!0;se[I]=!0;Ot[I]=!0;dr[I]=!0;Z[I]=!0;nt[I]=!0;yr[I]=!0;lo[I]=!0;On[I]=!0;Mt[I]=!0;Wi[I]=!0;ft[I]=!0;_e[I]=!0;Ri[I]=!0;Si[I]=!0;me[I]=!0;Bi[I]=!0;Gn[I]=!0;co[I]=!0;ls[I]=!0;uo[I]=!0;$[I]=!0;sn[I]=!0;_r[I]=!0;xr[I]=!0;nn[I]=!0;Vn[I]=!0;zn[I]=!0;on[I]=!0;rn[I]=!0;Me[I]=!0;Vi[I]=!0;Bt[I]=!0;He[I]=!0;cn[I]=!0;Ve[I]=!0;bt[I]=!0;an[I]=!0;ln[I]=!0;Er[I]=!0;vt[I]=!0;fo[I]=!0;un[I]=!0;mo[I]=!0;go[I]=!0;bo[I]=!0;Jt[I]=!0;Cr[I]=!0;Tr[I]=!0;vo[I]=!0;Zt[I]=!0;ho[I]=!0;wr[I]=!0;st[I]=!0;yo[I]=!0;Ce[I]=!0;ta[I]=!0;cs[I]=!0;_o[I]=!0;Rr[I]=!0;us[I]=!0;Pi[I]=!0;O.add("AlignmentConstraint",En);O.add("Animation",Wt);O.add("AnimationCurve",Xt);O.add("Animator",Ye);O.add("AnimatorController",zt);O.add("AudioListener",Qt);O.add("AudioSource",ie);O.add("AvatarModel",nr);O.add("AvatarLoader",Tn);O.add("AxesHelper",ji);O.add("BasicIKConstraint",Xr);O.add("BoxHelperComponent",ke);O.add("Camera",ae);O.add("CharacterController",bi);O.add("CharacterControllerInput",Yt);O.add("Collider",Tt);O.add("SphereCollider",Rn);O.add("BoxCollider",Sn);O.add("MeshCollider",sr);O.add("CapsuleCollider",Ct);O.add("DeleteBox",ar);O.add("Deletable",Yr);O.add("DeviceFlag",lr);O.add("DragControls",xi);O.add("DropListener",Mn);O.add("Duplicatable",wi);O.add("CallInfo",gi);O.add("EventListEvent",rr);O.add("EventList",ye);O.add("EventTrigger",Kr);O.add("FlyControls",Jr);O.add("BoxGizmo",Ni);O.add("GltfExportBox",eo);O.add("GltfExport",Dt);O.add("GridHelper",Yi);O.add("GroundProjectedEnv",Ki);O.add("Interactable",Rt);O.add("UsageMarker",St);O.add("FixedJoint",to);O.add("HingeJoint",In);O.add("Light",Ae);O.add("LODModel",Ei);O.add("LODGroup",Dn);O.add("LookAtConstraint",Ui);O.add("NestedGltf",pr);O.add("Networking",$t);O.add("OffsetConstraint",Ci);O.add("OrbitControls",Je);O.add("ParticleSystemRenderer",$i);O.add("ParticleSystem",je);O.add("Gradient",ii);O.add("MinMaxCurve",G);O.add("MinMaxGradient",We);O.add("MainModule",ge);O.add("ParticleBurst",Zi);O.add("EmissionModule",rt);O.add("ColorOverLifetimeModule",Ji);O.add("SizeOverLifetimeModule",At);O.add("ShapeModule",be);O.add("NoiseModule",K);O.add("TrailModule",fr);O.add("VelocityOverLifetimeModule",Pe);O.add("TextureSheetAnimationModule",ve);O.add("RotationOverLifetimeModule",Ne);O.add("RotationBySpeedModule",Le);O.add("LimitVelocityOverLifetimeModule",le);O.add("PlayerColor",ot);O.add("ReflectionProbe",It);O.add("FieldWithDefault",Zr);O.add("Renderer",ne);O.add("MeshRenderer",hr);O.add("SkinnedMeshRenderer",$r);O.add("RendererLightmap",Xi);O.add("Rigidbody",J);O.add("ScreenCapture",An);O.add("ShadowCatcher",Ln);O.add("RemoteSkybox",jn);O.add("SmoothFollow",mt);O.add("SpatialTriggerReceiver",gt);O.add("SpatialTrigger",en);O.add("SpectatorCamera",ro);O.add("Sprite",gr);O.add("SpriteRenderer",tn);O.add("SyncedCamera",Hn);O.add("SyncedRoom",ni);O.add("SyncedTransform",ht);O.add("TestRunner",oo);O.add("TestSimulateUserData",so);O.add("TransformGizmo",br);O.add("VideoPlayer",xe);O.add("Voip",Ke);O.add("VolumeParameter",ao);O.add("VolumeComponent",Ti);O.add("ToneMapping",Bn);O.add("ColorAdjustments",Un);O.add("VolumeProfile",Fn);O.add("Volume",vr);O.add("WebARSessionRoot",Pt);O.add("WebXR",z);O.add("WebAR",kn);O.add("AvatarMarker",se);O.add("WebXRAvatar",Ot);O.add("TeleportTarget",dr);O.add("WebXRController",Z);O.add("AttachedObject",nt);O.add("XRGrabModel",yr);O.add("XRGrabRendering",lo);O.add("XRRig",On);O.add("VRUserState",Mt);O.add("WebXRSync",Wi);O.add("XRState",ft);O.add("XRFlag",_e);O.add("AvatarBlink_Simple",Ri);O.add("AvatarEyeLook_Rotation",Si);O.add("Avatar_POI",me);O.add("Avatar_Brain_LookAt",Bi);O.add("Avatar_MouthShapes",Gn);O.add("Avatar_MustacheShake",co);O.add("__Ignore",ls);O.add("LogStats",uo);O.add("RGBAColor",$);O.add("PlayableDirector",sn);O.add("SignalAsset",_r);O.add("SignalReceiverEvent",xr);O.add("SignalReceiver",nn);O.add("AnimationTrackHandler",Vn);O.add("AudioTrackHandler",zn);O.add("SignalTrackHandler",on);O.add("ControlTrackHandler",rn);O.add("BaseUIComponent",Me);O.add("UIRootComponent",Vi);O.add("Button",Bt);O.add("Canvas",He);O.add("CanvasGroup",cn);O.add("EventSystem",Ve);O.add("Graphic",bt);O.add("MaskableGraphic",an);O.add("Image",ln);O.add("RawImage",Er);O.add("InputField",vt);O.add("Keyboard",fo);O.add("LayoutGroup",un);O.add("VerticalLayoutGroup",mo);O.add("HorizontalLayoutGroup",go);O.add("GridLayoutGroup",bo);O.add("PointerEventData",Jt);O.add("Raycaster",Cr);O.add("ObjectRaycaster",Tr);O.add("GraphicRaycaster",vo);O.add("UIRaycastUtils",Zt);O.add("Size",ho);O.add("Rect",wr);O.add("RectTransform",st);O.add("SpatialHtml",yo);O.add("Text",Ce);O.add("PresentationMode",ta);O.add("LinesDrawer",cs);O.add("LineInstanceHandler",_o);O.add("LinesManager",Rr);O.add("PlayerSync",us);O.add("PlayerState",Pi);var tm=Te,R_=M("debugtypestore");R_&&console.log(O);function im(o,e){let i=fc(o,e);return i!==void 0?i:null}var S_=new ha;async function nm(o,e,t,i=null,n){if(!t)return;let r=[],s=i;typeof s=="number"&&(s=new Ue(i));let a=new Ro(t.scene);a.gltfId=e,a.context=o,a.gltf=t,a.nodeToObject=n?.nodeToObjectMap,a.implementationInformation=S_;let c=[];if(t.scenes)for(let u of t.scenes)await zd(a,u,c,r);if(t.children)for(let u of t.children)await zd(a,u,c,r);o.new_scripts_pre_setup_callbacks.push(()=>{for(let u of c)P_(u,a);if(s){Vd(t,s);for(let u of t.scenes)Vd(u,s)}})}function Vd(o,e){if(e!==null&&!!o){if(o.guid=e.generateUUID(),o&&o.userData&&o.userData.components)for(let t of o.userData.components)t!==null&&(t.guid=e.generateUUID());if(o.children)for(let t of o.children)Vd(t,e)}}var ia=[];async function zd(o,e,t,i){if(!e)return;let n=e.userData;if(n){let r=n.builtin_components;if(r&&r.length>0)for(let s of r)try{if(s===null)continue;let a=O.get(s.name);if(a!=null){let c=new a;c.sourceId=o.gltfId,oi(c,s,o.implementationInformation),qn(e,c,!1),t.push({instance:c,compData:s,obj:e})}else tm&&console.debug("unknown component: "+s.name),ia.includes(s.name)||ia.push(s.name)}catch(a){console.error(s.name+" - "+a.message,a)}if(ia.length>0){let s=ia.join(", ");console.warn("unknown components: "+s),ia.length=0,Xn()&&Ze(`<strong>Unknown components in scene</strong>:
|
|
269
|
+
`)}}}applyShadowMaterial(){let e=R.getComponent(this.gameObject,ne);if(e)if(e.material?.type!=="ShadowMaterial"){let t=new Fy;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)}};E([x()],jn.prototype,"mode",2),E([x($)],jn.prototype,"shadowColor",2);import{RGBELoader as Vy}from"three/examples/jsm/loaders/RGBELoader.js";import{EXRLoader as zy}from"three/examples/jsm/loaders/EXRLoader";import{EquirectangularRefractionMapping as Wy}from"three";var kf=M("debugautosync"),Cd=class{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];let t=new Td(e);return this._syncers[e.guid]=t,t}},Mf=new Cd,Td=class{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};data={};_boundEvent;get networkingKey(){return this.comp.constructor.name}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this._boundEvent=this.onHandleSending.bind(this),this.comp.context.post_render_callbacks.push(this._boundEvent),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving.bind(this));let t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}notifyChanged(e,t){this._isReceiving||(this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending(){if(!this.hasChanges)return;this.hasChanges=!1;let e=this.comp.context.connection;if(!e||!e.isConnected){for(let t in this.changedProperties)delete this.changedProperties[t];return}for(let t in this.data)delete this.data[t];this.data.guid=this.comp.guid;for(let t in this.changedProperties){let 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)){kf&&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 Uy(o,e){let t=e!==o;if(!t&&o&&e){if(Array.isArray(o)&&Array.isArray(e))t=!0;else if(typeof o=="object"&&typeof e=="object"){for(let i of Object.keys(o))if(o[i]!==e[i]){t=!0;break}}}return t}function Gy(o){if(o.__autoPropertySyncHandler)return o.__autoPropertySyncHandler;let e=Mf.getOrCreateSyncer(o);return e?.init(o),o.__autoPropertySyncHandler=e,e}var Al=function(o){return function(e,t){let i=null,n=o?e[o]:void 0,r=e,s=r.__internalAwake;kf&&console.log(t);let a=t+"k__BackingField";r.__internalAwake=function(){if(this[a]!==void 0)return;this[a]=this[t],s.call(this),i=Mf.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,t)?.set===void 0&&Object.defineProperty(this,t,{set:function(u){let l=this[a];this[a]=u,Uy(u,l)&&n?.call(this,u,l)!==!1&&Gy(this)?.notifyChanged(t,u)},get:function(){return this[a]},configurable:!0,enumerable:!0}),i?.init(this)}}};var Ti=class extends k{url;allowDrop=!0;background=!0;environment=!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 zy:new Vy}let t=await this._loader.loadAsync(e);if(!t||!this.enabled)return;this.url=e,t.mapping=Wy,this._prevBackground=this.context.scene.background,this._prevEnvironment=this.context.scene.environment,console.log("Set skybox",this.url),this.environment&&(this.context.scene.environment=t),this.background&&(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))}};E([Al("setSkybox"),x()],Ti.prototype,"url",2),E([x()],Ti.prototype,"allowDrop",2),E([x()],Ti.prototype,"background",2),E([x()],Ti.prototype,"environment",2);import*as Ll from"three";import{Object3D as Ny}from"three";var Rd=class extends k{target=null;followFactor=.1;rotateFactor=.1;positionAxes=-1;flipForward=!1;_firstUpdate=!0;onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){let t=U(this.target),i=this._firstUpdate||e?1:F.clamp01(this.context.time.deltaTime*this.followFactor),n=this.worldPosition;this.positionAxes&2&&(n.x=F.lerp(n.x,t.x,i)),this.positionAxes&4&&(n.y=F.lerp(n.y,t.y,i)),this.positionAxes&8&&(n.z=F.lerp(n.z,t.z,i)),this.worldPosition=n}if(this.rotateFactor>0){let t=he(this.target);this.flipForward&&t.premultiply(Rd._invertForward);let i=this._firstUpdate||e?1:F.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}},mt=Rd;L(mt,"_invertForward",new Ll.Quaternion().setFromAxisAngle(new Ll.Vector3(0,1,0),Math.PI)),E([x(Ny)],mt.prototype,"target",2),E([x()],mt.prototype,"followFactor",2),E([x()],mt.prototype,"rotateFactor",2),E([x()],mt.prototype,"positionAxes",2);import{Layers as Af}from"three";var Ks=M("debugspatialtrigger"),If=new Af,Df=new Af;function Xy(o,e){return If.mask=o,Df.mask=e,If.test(Df)}var gt=class extends k{triggerMask=0;onEnter;onStay;onExit;start(){Ks&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(let e of tn.triggers)Xy(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){Ks&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke(this,e)}onExitTrigger(e){Ks&&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)}};E([x()],gt.prototype,"triggerMask",2),E([x(ye)],gt.prototype,"onEnter",2),E([x(ye)],gt.prototype,"onStay",2),E([x(ye)],gt.prototype,"onExit",2);var Js=class extends k{triggerMask;boxHelper;start(){Ks&&console.log(this.name,this.triggerMask,this)}onEnable(){Js.triggers.push(this),this.boxHelper||(this.boxHelper=R.addNewComponent(this.gameObject,ke),this.boxHelper?.showHelper(null,Ks))}onDisable(){Js.triggers.splice(Js.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof gt&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof gt&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){R.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof gt&&t.onExitTrigger(this)},!1)}},tn=Js;L(tn,"triggers",[]),E([x()],tn.prototype,"triggerMask",2);import*as mr from"three";var Lt=M("debugspectator"),ro=class extends k{cam=null;_mode=0;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){if(this._handler){let t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),R.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),R.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.localId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new Pd(this.context,this),this._networking=new Md(this.context,this),this._networking.awake(),R.setActive(this.gameObject,!1),this.cam=R.getComponent(this.gameObject,ae),!this.cam){console.error("Spectator camera needs camera component",this);return}!this._handler&&this.cam&&(this._handler=new Sd(this.context,this.cam,this)),this.eventSub_WebXRRequestStartEvent=this.onXRSessionRequestStart.bind(this),this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),z.addEventListener("requestVRSession",this.eventSub_WebXRRequestStartEvent),z.addEventListener("xrStarted",this.eventSub_WebXRStartEvent),z.addEventListener("xrStopped",this.eventSub_WebXREndEvent),this.orbit=R.getComponent(this.context.mainCamera,Je)}onDestroy(){this.stopSpectating(),z.removeEventListener("requestVRSession",this.eventSub_WebXRStartEvent),z.removeEventListener("xrStarted",this.eventSub_WebXRStartEvent),z.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()||R.setActive(this.gameObject,!0)}onXRSessionStart(e){!this.isSupportedPlatform()||(Lt&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onXRSessionEnded(e){this.context.removeCamera(this.cam),R.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating()}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,"headset"),this.target=this.context.players.getPlayerView(this.localId)),Lt&&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 mr.Color(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;let s=this.cam?.cam;this.context.updateAspect(s);let a=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,s),e.xr.isPresenting=a,e.xr.enabled=t,i?e.setRenderTarget(i):e.state.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){let e=this._mode===0;for(let t of se.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 se.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)}}},Sd=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=R.addNewComponent(this.cam.gameObject,mt)),this.target||(this.target=new mr.Object3D),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Lt&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Lt&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){this.target?.removeFromParent(),this.follow&&R.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){Lt&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(Lt&&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(Qy):i.quaternion.identity()}}},Qy=new mr.Quaternion().setFromAxisAngle(new mr.Vector3(0,1,0),Math.PI),Pd=class{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log("Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),window.addEventListener("keydown",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 fe;e.setMask(16777215);let t=this.context.physics.raycast(e);if(Lt&&console.log(...t),t?.length)for(let i of t){if(i.distance<.2)continue;let n=i.object,r=R.getComponentInParent(n,se),s=r?.connectionId;if(s){let a=this.context.players.getPlayerView(s);this.spectator.target=a,Lt&&console.log("spectate",s,r);break}}}},Od=class{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}},kd=class{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}},Md=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(Lt&&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 Od(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",r)}}onRequestFollowMe(e=!1){if(Lt&&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 kd(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){M("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){let t=e.targetUserId,i=e.guid;if(Lt&&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 Lt&&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):(Lt&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}};import*as jt from"three";import{Material as qy,Texture as Yy}from"three";var gr=class{texture;triangles;uv;vertices;_geometry};E([x(Yy)],gr.prototype,"texture",2);var jl=class{static getOrCreateGeometry(e){if(e._geometry)return e._geometry;let t=new jt.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 s=e.triangles[r];i[r*3]=-e.vertices[s].x,i[r*3+1]=e.vertices[s].y,i[r*3+2]=0;let a=e.uv[s];n[r*2]=a.x,n[r*2+1]=1-a.y}return t.setAttribute("position",new jt.BufferAttribute(i,3)),t.setAttribute("uv",new jt.BufferAttribute(n,2)),t}},nn=class extends k{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=jl.getOrCreateGeometry(this.sprite),this._currentSprite.material.map=this.sprite.texture;else{let e=new jt.MeshBasicMaterial({color:16777215,side:jt.DoubleSide});if(!e)return;if(this.color&&(e.color||(e.color=new jt.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 jt.Mesh(jl.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))}}};E([x()],nn.prototype,"drawMode",2),E([x($)],nn.prototype,"color",2),E([x(qy)],nn.prototype,"sharedMaterial",2);var Ht=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 Ht).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+4),(t||new Ht).__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 Ee).__init(this.bb_pos+t,this.bb):null}rot(e){let t=this.bb.__offset(this.bb_pos,12);return t?(e||new Ee).__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 Ky}from"three";var Hl="SCAM";Fo(Hl,Ht.getRootAsSyncedCameraModel);var Ft=new xt,Id=class{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){Ft.clear();let i=Ft.createString(this.guid),n=Ft.createString(this.userId);Ht.startSyncedCameraModel(Ft),Ht.addGuid(Ft,i),Ht.addUserId(Ft,n);let r=U(e),s=ga(e);Ht.addPos(Ft,Ee.createVec3(Ft,r.x,r.y,r.z)),Ht.addRot(Ft,Ee.createVec3(Ft,s.x,s.y,s.z));let a=Ht.endSyncedCameraModel(Ft);Ft.finish(a,Hl),t.sendBinary(Ft.asUint8Array())}}},Fl=class extends k{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(Hl,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(Hl,this._receiveCallback)}update(){for(let n in this.remoteCams){let r=this.remoteCams[n],s=this.context.time.realtimeSinceStartup-r.lastUpdate;if(!r||s>this._camTimeoutInSeconds){console.log("Remote cam timeout",r,s),r?.obj&&R.destroy(r.obj),delete this.remoteCams[n],r&&delete this.userToCamMap[r.userId],Fl.instances.push(r),this.context.players.removePlayerView(r.userId,"browser");continue}}if(z.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 Id(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));let t=U(e),i=he(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,"browser"))}onReceivedRemoteCameraInfoBin(e){let t=e.guid();if(!t)return;let i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){let c=new Ge;c.context=this.context;let u=R.instantiate(this.cameraPrefab,c);n=this.remoteCams[t]={obj:u,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(u),this.userToCamMap[i]=t,Fl.instances.push(n);let l=R.getOrAddComponent(u,se);l.connectionId=i,l.avatar=u}else return;let r=n.obj;this.context.players.setPlayerView(i,r,"browser"),n.lastUpdate=this.context.time.realtimeSinceStartup,oe.markDirty(r);let s=e.pos();s&&bn(r,s.x(),s.y(),s.z());let a=e.rot();a&&ba(r,a.x(),a.y(),a.z())}},Hn=Fl;L(Hn,"instances",[]),E([x([Ky,qe])],Hn.prototype,"cameraPrefab",2);var Dd="view",Lf=M("debugsyncedroom"),ni=class extends k{roomName;urlParameterName;joinRandomRoom=!0;requireRoomParameter=!1;autoRejoin=!0;_roomPrefix;awake(){this._roomPrefix===void 0&&(this._roomPrefix=this.roomName,this.roomName="")}onEnable(){let e=M(Dd);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}this.tryJoinRoom()}onDisable(){this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName){let i=M(this.urlParameterName);if(i&&typeof i=="string"){t=!0;let n=ch(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?(Lf&&console.log('No required room parameter "'+this.urlParameterName+'" in url - will not connect to networking backend.'),!1):!this.roomName||this.roomName.length<=0?(Lf&&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=M(Dd);return e||M(this.urlParameterName)}setRandomRoomUrlParameter(){let e=oc(),t=this.generateRoomName();M(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),sh(t,e)}generateRoomName(){return lh()+"_"+ah(100,999)}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){let e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Dd,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}};E([x()],ni.prototype,"roomName",2),E([x()],ni.prototype,"urlParameterName",2),E([x()],ni.prototype,"joinRandomRoom",2),E([x()],ni.prototype,"requireRoomParameter",2),E([x()],ni.prototype,"autoRejoin",2);function jf(){let o=M("testwindowcount")||0;o&&o>0&&Jy(o)}function Jy(o){if(M("testwindow"))return null;let e=new URL(window.location.href);Co(e.searchParams,qo,1),Co(e.searchParams,"testwindow",1);let t=e.toString(),i=[];window.onbeforeunload=()=>{for(let c of i)c.close()};let n=.05,r=128,s=0,a=0;for(let c=0;c<o;c++){s*r+r*.01>=window.innerWidth&&(a+=1,s=0);let u=s*(r*(1+n))+window.screenLeft,l=a*(r*(1+n))+window.screenTop+90+60*a;s+=1;let d=window.open(t,"test window "+c,`popup=yes width=${r} height=${r} top=${l} left=${u}`);if(!d){console.warn("Failed to open window");continue}i.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let h=0;h<i.length;h++){let b=i[h];b!==d&&b.close()}i.length=0}}}return i}import{Vector3 as $y}from"three";var oo=class extends k{awake(){jf()}},so=class extends k{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinrary(No,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new Bl(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 xt(1024));let e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();let i=ku(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)}}}},Bl=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}}};L(Bl,"temp",new $y);import{MathUtils as e_}from"three";import{TransformControls as t_}from"three/examples/jsm/controls/TransformControls";import{OrbitControls as i_}from"three/examples/jsm/controls/OrbitControls";var br=class extends k{isGizmo=!0;control;orbit;awake(){this.isGizmo&&!Mi||!this.context.mainCamera||(this.control=new t_(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=R.getComponentInParent(this.context.mainCamera,i_)??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=R.getComponentInParent(this.gameObject,ht);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(e_.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))}};E([x()],br.prototype,"isGizmo",2);import{LinearToneMapping as Hf,ACESFilmicToneMapping as n_,ReinhardToneMapping as r_}from"three";var Ul=M("debugvolume"),Bf=(i=>(i[i.None=0]="None",i[i.Neutral=1]="Neutral",i[i.ACES=2]="ACES",i))(Bf||{}),ao=class{overrideState=!1;value=0},Ri=class{active=!1;parameters},Bn=class extends Ri{mode;get isToneMapping(){return!0}},Un=class extends Ri{postExposure};function o_(o){return"mode"in o?Bn:"postExposure"in o?Un:Ri}var Ff=Symbol("volumeprofile"),Fn=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 s of this.components)if(s instanceof Bn){let a=s;if(!s.active||t){e.renderer.toneMapping=Hf;continue}switch(Ul&&console.log("VOLUME:",Bf[a.mode?.value??0]),a.mode?.value??0){case 0:e.renderer.toneMapping=Hf;break;case 1:e.renderer.toneMapping=r_;break;case 2:e.renderer.toneMapping=n_;break}}else if(s instanceof Un){let a=s;Ul&&console.log(a.postExposure);let c=Math.pow(2,a.postExposure?.value??0),u=a.postExposure?.overrideState&&!t;e.renderer.toneMappingExposure=u?c:1}}};E([x([o=>o_(o),Ri])],Fn.prototype,"components",2);var vr=class extends k{sharedProfile;awake(){Ul&&(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(){Ul&&console.log("APPLY VOLUME",this),this.sharedProfile?.apply(this.context)}onDisable(){this.sharedProfile?.unapply(this.context)}};E([x(Fn)],vr.prototype,"sharedProfile",2);import{Vector3 as s_}from"three";var yr=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 k{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=nt.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),nt.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=R.instantiate(this.prefab);if(i.visible=!0,this._instances[e.guid]={instance:i,model:e},e.userId){let n=R.getComponentsInChildren(i,ot);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]&&(R.destroy(this._instances[t].instance),delete this._instances[t])}onAttachedObjectFree(e){if(this._grabModels.length<=0)return;let t=this._grabModels[0];this.updateModel(t,e),this.endGrab(t)}onBeforeRender(){if(this.updateRendering(),!!this.prefab&&(this.prefab.visible=!1,this.context.time.frameCount%10===0))for(let e=0;e<nt.Current.length;e++){let t=nt.Current[e];if(!t.controller||!t.selected)continue;this._grabModels.length<=e&&(this._grabModels.push(new yr),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 s_;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,s=U(i);this.temp.set(r.x,r.y,r.z),s.lerp(this.temp,e),te(i,s)}}};import{Object3D as a_}from"three";var Si=class extends k{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=R.getComponentInParent(this.gameObject,_e)}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)}}};E([x(a_)],Si.prototype,"eyes",2),E([x()],Si.prototype,"lastBlinkTime",2),E([x()],Si.prototype,"blinkLength",2),E([x()],Si.prototype,"eyesOpen",2);import*as Gl from"three";import{Object3D as Ad}from"three";var Ld=class extends k{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=R.getComponentInParent(this.gameObject,Ui)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=R.addNewComponent(this.gameObject,Ui)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new Gl.Vector3;currentTargetPoint=new Gl.Vector3;update(){let e=this.target;if(e&&this.head){let t=this.eyes;if(t){let i=U(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);let n=U(this.head),r=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(r.length()<.1)return;let s=Ld.forward;if(s.set(0,0,1),s.applyQuaternion(he(this.head)),s.dot(r)>.45)for(let c=0;c<t.length;c++)t[c].lookAt(this.currentTargetPoint)}}}},Pi=Ld;L(Pi,"forward",new Gl.Vector3(0,0,1)),E([x(Ad)],Pi.prototype,"head",2),E([x(Ad)],Pi.prototype,"eyes",2),E([x(Ad)],Pi.prototype,"target",2);import{Object3D as Uf}from"three";var l_=M("debugmouth"),Gn=class extends k{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=R.findObjectOfType(Ke,this.context),this.marker||(this.marker=R.getComponentInParent(this.gameObject,se))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){l_&&(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)}}}};E([x(Uf)],Gn.prototype,"idle",2),E([x(Uf)],Gn.prototype,"talking",2);var co=class extends k{voip=null;marker=null;_startPosition=null;awake(){this.voip=R.findObjectOfType(Ke,this.context),this.marker=R.getComponentInParent(this.gameObject,se)}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 Ud={};nh(Ud,{AlignmentConstraint:()=>Cn,Animation:()=>Wt,AnimationCurve:()=>Xt,AnimationTrackHandler:()=>Vn,Animator:()=>Ye,AnimatorController:()=>zt,AttachedObject:()=>nt,AudioListener:()=>Qt,AudioSource:()=>ie,AudioTrackHandler:()=>zn,AvatarBlink_Simple:()=>Si,AvatarEyeLook_Rotation:()=>Pi,AvatarLoader:()=>Rn,AvatarMarker:()=>se,AvatarModel:()=>nr,Avatar_Brain_LookAt:()=>Ui,Avatar_MouthShapes:()=>Gn,Avatar_MustacheShake:()=>co,Avatar_POI:()=>me,AxesHelper:()=>Hi,BaseUIComponent:()=>Me,BasicIKConstraint:()=>Xr,BoxCollider:()=>Pn,BoxGizmo:()=>Xi,BoxHelperComponent:()=>ke,Button:()=>Bt,CallInfo:()=>gi,Camera:()=>ae,Canvas:()=>He,CanvasGroup:()=>un,CapsuleCollider:()=>Ct,CharacterController:()=>bi,CharacterControllerInput:()=>Yt,Collider:()=>Tt,ColorAdjustments:()=>Un,ColorOverLifetimeModule:()=>Zi,ControlTrackHandler:()=>on,Deletable:()=>Yr,DeleteBox:()=>ar,DeviceFlag:()=>lr,DragControls:()=>xi,DropListener:()=>In,Duplicatable:()=>wi,EmissionModule:()=>rt,EventList:()=>ye,EventListEvent:()=>rr,EventSystem:()=>Ve,EventTrigger:()=>Kr,FieldWithDefault:()=>Zr,FixedJoint:()=>to,FlyControls:()=>Jr,GltfExport:()=>Dt,GltfExportBox:()=>eo,Gradient:()=>ii,Graphic:()=>bt,GraphicRaycaster:()=>vo,GridHelper:()=>Ki,GridLayoutGroup:()=>bo,GroundProjectedEnv:()=>Ji,HingeJoint:()=>Dn,HorizontalLayoutGroup:()=>go,Image:()=>cn,InputField:()=>vt,Interactable:()=>Rt,Keyboard:()=>fo,LODGroup:()=>An,LODModel:()=>Ei,LayoutGroup:()=>dn,Light:()=>Ae,LimitVelocityOverLifetimeModule:()=>le,LogStats:()=>uo,LookAtConstraint:()=>Gi,MainModule:()=>ge,MaskableGraphic:()=>ln,MeshCollider:()=>sr,MeshRenderer:()=>hr,MinMaxCurve:()=>G,MinMaxGradient:()=>We,NestedGltf:()=>pr,Networking:()=>$t,NoiseModule:()=>K,ObjectRaycaster:()=>Tr,OffsetConstraint:()=>Ci,OrbitControls:()=>Je,ParticleBurst:()=>$i,ParticleSystem:()=>je,ParticleSystemRenderer:()=>en,PlayableDirector:()=>an,PlayerColor:()=>ot,PointerEventData:()=>Jt,RGBAColor:()=>$,RawImage:()=>Er,Raycaster:()=>Cr,Rect:()=>wr,RectTransform:()=>st,ReflectionProbe:()=>It,RemoteSkybox:()=>Ti,Renderer:()=>ne,RendererLightmap:()=>Qi,Rigidbody:()=>J,RotationBySpeedModule:()=>Le,RotationOverLifetimeModule:()=>Ne,ScreenCapture:()=>Ln,ShadowCatcher:()=>jn,ShapeModule:()=>be,SignalAsset:()=>_r,SignalReceiver:()=>rn,SignalReceiverEvent:()=>xr,SignalTrackHandler:()=>sn,Size:()=>ho,SizeOverLifetimeModule:()=>At,SkinnedMeshRenderer:()=>$r,SmoothFollow:()=>mt,SpatialHtml:()=>yo,SpatialTrigger:()=>tn,SpatialTriggerReceiver:()=>gt,SpectatorCamera:()=>ro,SphereCollider:()=>Sn,Sprite:()=>gr,SpriteRenderer:()=>nn,SyncedCamera:()=>Hn,SyncedRoom:()=>ni,SyncedTransform:()=>ht,TeleportTarget:()=>dr,TestRunner:()=>oo,TestSimulateUserData:()=>so,Text:()=>Ce,TextureSheetAnimationModule:()=>ve,ToneMapping:()=>Bn,TrailModule:()=>fr,TransformGizmo:()=>br,UIRaycastUtils:()=>Zt,UIRootComponent:()=>zi,UsageMarker:()=>St,VRUserState:()=>Mt,VelocityOverLifetimeModule:()=>Pe,VerticalLayoutGroup:()=>mo,VideoPlayer:()=>xe,Voip:()=>Ke,Volume:()=>vr,VolumeComponent:()=>Ri,VolumeParameter:()=>ao,VolumeProfile:()=>Fn,WebAR:()=>Mn,WebARSessionRoot:()=>Pt,WebXR:()=>z,WebXRAvatar:()=>Ot,WebXRController:()=>Z,WebXRSync:()=>Ni,XRFlag:()=>_e,XRGrabModel:()=>yr,XRGrabRendering:()=>lo,XRRig:()=>kn,XRState:()=>ft,__Ignore:()=>ls});var c_=M("logstats"),uo=class extends k{onEnable(){console.log(this),c_&&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 zf from"three";var _r=class{guid},xr=class{signal;reaction;$serializedTypes={signal:_r,reaction:ye}},rn=class extends k{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)}}};E([x(xr)],rn.prototype,"events",2);import*as ee from"three";import{Quaternion as u_,Vector3 as d_}from"three";var rs=M("debugtimeline"),os=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 s=1,a=!1;return r.easeInDuration>0&&(s*=Math.min((e-r.start)/r.easeInDuration,1)),r.easeOutDuration>0&&!a&&(s*=Math.min((r.end-e)/r.easeOutDuration,1)),s}return 0}},jd=class{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){let t=e.getClip();this.clip=t;let i=e.getRoot(),n=i.name+".position",r=i.name+".quaternion";rs&&console.log(t.name,t.tracks,n);for(let s of t.tracks)if(!(s.times.length<=0)){if(s.name.endsWith(n))this.rootStartPosition=new ee.Vector3().fromArray(s.values,0),this.rootEndPosition=new ee.Vector3().fromArray(s.values,s.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),rs&&console.log(this.rootPositionOffset);else if(s.name.endsWith(r)&&(this.rootStartQuaternion=new ee.Quaternion().fromArray(s.values,0),this.rootEndQuaternion=new ee.Quaternion().fromArray(s.values,s.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),rs)){let a=new ee.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}},Vn=class extends os{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",s=n+".quaternion",a=!1,c=!1;for(let u of t.tracks)u.name.endsWith(r)?(a=!0,this.createPositionInterpolant(t,e,u)):u.name.endsWith(s)&&(c=!0,this.createRotationInterpolant(t,e,u));if(!a||!c){let u=this.mixer?.getRoot(),l=t.tracks[0],d=l.name.lastIndexOf("."),h=l.name.substring(0,d),b=h.substring(h.lastIndexOf(".")+1),_=u.getObjectByName(b);if(_)if(a){if(!c){let v=t.tracks[0].name.substring(0,d)+".quaternion";rs&&console.warn("Create quaternion track",b,_);let y=_.quaternion,f=new ee.QuaternionKeyframeTrack(v,[0,t.duration],[y.x,y.y,y.z,y.w,y.x,y.y,y.z,y.w]);t.tracks.push(f),this.createRotationInterpolant(t,e,f)}}else{let v=h+".position";rs&&console.warn("Create position track",b,_);let y=_.position,f=new ee.VectorKeyframeTrack(v,[0,t.duration],[y.x,y.y,y.z,y.x,y.y,y.z]);t.tracks.push(f),this.createPositionInterpolant(t,e,f)}}}bind(){if(!this._didBind){this._didBind=!0,rs&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(let e of this.actions){let t=new jd(e);this._actionOffsets.push(t)}for(let e of this.models){let t=e.asset,i=t.position,n=t.rotation;i.x!==void 0&&(i.isVector3||(t.position=new d_(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new u_(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 ee.Vector3(e.x,e.y,e.z)));let t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new ee.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new ee.Vector3;_totalOffsetRotation=new ee.Quaternion;_totalOffsetPosition2=new ee.Vector3;_totalOffsetRotation2=new ee.Quaternion;_summedPos=new ee.Vector3;_tempPos=new ee.Vector3;_summedRot=new ee.Quaternion;_tempRot=new ee.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 s=this.models[r],a=this.actions[r],c=s.asset;a.weight=0;let u=e>=s.start&&e<=s.end,l=s.postExtrapolationMode,d=u;if(!d&&!n&&s.end<e&&s.postExtrapolationMode!==0){let h=r<this.clips.length-1?this.models[r+1]:null;(!h||h.start>e)&&(d=!0,n=!0)}if(d){let h=1;h*=this.evaluateWeight(e,r,this.models,d);let b=this.getClipTime(e,s),_=0,v=c.duration;if(u){if(c.loop)for(_+=Math.floor(b/(v+1e-6));b>v;)b-=v}else if(!u)switch(l){case 2:b%=v;break;case 3:let m=Math.floor(b/v)%2!==0;b%=v,m&&(b=v-b);break}a.time=b,a.timeScale=0;let y=h*this.director.weight;if(a.weight=y,a.clampWhenFinished=!0,a.isRunning()||a.play(),this._useclipOffsets){let f=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,m=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-h),t+=1;let p=this._summedPos.set(0,0,0),g=this._tempPos.set(0,0,0),w=this._summedRot.identity(),C=this._tempRot.identity(),T=c.rotation,S=new ee.Quaternion;S.slerp(T,h);let D=this._actionOffsets[r];if(D.hasOffsets)for(let A=0;A<_;A++)D.rootPositionOffset?g.copy(D.rootPositionOffset):g.set(0,0,0),g.applyQuaternion(w).applyQuaternion(S),D.rootQuaternionOffset&&(C.copy(D.rootQuaternionOffset),w.multiply(C)),p.add(g);m.multiply(S),m.multiply(w),p.add(c.position),f.add(p)}}}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 ee.Quaternion;this.ensureTrackOffsets();let s=this.trackOffset?.rotation;i.createInterpolant=()=>{let a=n(),c=a.evaluate.bind(a);return a.evaluate=u=>{let l=c(u);return r.set(l[0],l[1],l[2],l[3]),r.premultiply(this._totalOffsetRotation),s&&r.premultiply(s),l[0]=r.x,l[1]=r.y,l[2]=r.z,l[3]=r.w,l},a}}createPositionInterpolant(e,t,i){let n=i.createInterpolant.bind(i),r=new ee.Vector3;this.ensureTrackOffsets();let s=this.trackOffset?.rotation,a=this.trackOffset?.position,c;i.createInterpolant=()=>{let u=n(),l=u.evaluate.bind(u);return u.evaluate=d=>{let h=l(d);return r.set(h[0],h[1],h[2]),t.removeStartOffset&&(c===void 0?(c=null,c=this._actionOffsets.find(b=>b.clip===e)?.rootStartPosition?.clone()):c?.isVector3&&r.sub(c)),r.applyQuaternion(this._totalOffsetRotation),r.add(this._totalOffsetPosition),s&&r.applyQuaternion(s),a&&(r.x-=a.x,r.y+=a.y,r.z+=a.z),h[0]=r.x,h[1]=r.y,h[2]=r.z,h},u}}},zn=class extends os{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;getAudioFilePath(e){let t=this.director.sourceId;return ki(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 ee.Audio(this.listener);i.setVolume(e.asset.volume);let n=new ee.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}}},sn=class extends os{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 a of this.receivers)!a||a.invoke(i.asset)}}else i.emitOnce||(this.didTrigger[t]=!1)}}},Zs=class extends os{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;Zs.resolved[r]?n.sourceObject=Zs.resolved[r]:(n.sourceObject=R.findByGuid(r,e.scene),Zs.resolved[r]=n.sourceObject)}if(n.sourceObject){let r=R.getComponent(n.sourceObject,an);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 s=n.sourceObject;s.visible=!0}if(n.updateDirector){let s=this.timelines[t];s&&(s.isPlaying&&s.pause(),s.time=r,s.evaluate())}}else{let r=this._previousActiveModel?.asset;if(n.controlActivation){let s=n.sourceObject;r?.sourceObject!==s&&(s.visible=!1)}}}}},on=Zs;L(on,"resolved",{});var Vf=M("debugtimeline");var Vl=class extends k{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(){Vf&&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 a of t.clips)a.start<=e&&e<=a.end&&(r=!0);let s=n;s.visible!==void 0&&(s.visible=r)}}break}for(let t of this._animationTracks)t.evaluate(e);for(let t of this._audioTracks)t.evaluate(e);for(let t of this._signalTracks)t.evaluate(e);for(let t of this._controlTracks)t.evaluate(e);for(let t of this._customTracks)t.evaluate(e)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=gs(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=R.findByGuid(n,e);r===null||typeof r!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Vf&&console.log("Resolved binding",n,"to",r),t.outputs[i]=r)}else if(n===null){if(t.outputs.splice(i,1),Vl.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=Vl.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 s=t.outputs[r];typeof s.enabled=="boolean"&&(s.enabled=!1);let a=s?.gameObject?.animations;if(a){let c=new Vn;c.trackOffset=t.trackOffset,c.director=this,c.track=t;for(let u=0;u<t.clips.length;u++){let l=t.clips[u],d=l.asset;if(!d){console.error("MISSING anim model?","clip#"+u,l,t,this.playableAsset,this.name);continue}let h=d.clip,b=h;if((typeof b=="string"||typeof b=="number")&&(b=a.find(v=>v.name===h)),!b){console.warn("Could not find animationClip for model",l,t.name,this.name,this.playableAsset?.name);continue}c.mixer||(c.mixer=new zf.AnimationMixer(s.gameObject)),c.clips.push(b),c.mixer.uncacheAction(b),c.createHooks(l.asset,b);let _=c.mixer.clipAction(b);c.actions.push(_),c.models.push(l)}this._animationTracks.push(c)}}}else if(t.type==="AudioTrack"){if(t.clips.length<=0)continue;e.push(t)}else if(t.type==="MarkerTrack"){let r=new sn;r.director=this,r.track=t;for(let s of t.markers)switch(s.type){case"SignalEmitter":r.models.push(s),r.didTrigger.push(!1);break}if(r!==null&&r.models.length>0){let s=R.getComponent(this.gameObject,rn);s&&(r.receivers.push(s),this._signalTracks.push(r))}}else if(t.type==="SignalTrack"){let r=new sn;r.director=this,r.track=t;for(let s of t.markers)r.models.push(s),r.didTrigger.push(!1);for(let s of t.outputs)r.receivers.push(s);this._signalTracks.push(r)}else if(t.type==="ControlTrack"){let r=new on;r.director=this,r.track=t;for(let s of t.clips)r.models.push(s);r.resolveSourceObjects(this.context),this._controlTracks.push(r)}}ie.registerWaitForAllowAudio(()=>{let t=R.findObjectOfType(Qt,this.context);if(!!t)for(let i of e){let n=new zn;n.director=this,n.track=i,n.listener=t.listener;for(let r=0;r<i.clips.length;r++){let s=i.clips[r];n.addModel(s)}this._audioTracks.push(n)}})}setAudioTracksAllowPlaying(e){for(let t of this._audioTracks)t.onAllowAudioChanged(e)}},an=Vl;L(an,"createTrackFunctions",{});import{Color as m_,Texture as Yf}from"three";import*as Fd from"three-mesh-ui";import{Matrix4 as p_,Object3D as f_,Vector2 as Qf,Vector3 as Hd}from"three";import{FrontSide as Wf,DoubleSide as Nf}from"three";function ss(o,e){if(!o)return;let t=o.material;t?.isMaterial===!0&&(t.depthTest=!e.renderOnTop,t.side=e.doubleSided??!0?Nf:Wf,t.depthWrite=e.depthWrite??!1,t.shadowSide=e.doubleSided?Nf:Wf,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1);for(let i of o.children)ss(i,e)}function zl(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);let i=Proxy.revocable(o[e],{set(s,a,c,u){let l=s[a],d=Reflect.set(s,a,c,u);return t(c,l),d}}),n=i.revoke,r=o[e];return i.revoke=()=>{o[e]=r,n()},o[e]=i.proxy,i}function Xf(o,e,t=3){let i=o.__scheduledActions;i||(i=o.__scheduledActions={});let n=e.name;i[t]||(i[t]={});let r=i[t];if(r[n])return;function*a(){e?.call(o),r[n]=null}let c=o.startCoroutine(a(),t);r[n]=c}var qf=M("debugui"),ho=class{width;height},wr=class{x;y;width;height},st=class extends Me{offset=.01;get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new Hd),this._anchoredPosition}rect;sizeDelta;anchoredPosition3D;pivot;lastMatrix;rectBlock;_transformNeedsUpdate=!1;awake(){super.awake(),this.lastMatrix=new p_,this.rectBlock=new f_,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._anchoredPosition||(this._anchoredPosition=new Hd),zl(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)&&(qf&&console.log("updating",this.name),this.applyTransform()),Ve.ensureUpdateMeshUI(Fd,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},qf&&console.log(this.name,e);let t=new Fd.Block(e);return this._createdBlocks.push(t),t}};E([x(wr)],st.prototype,"rect",2),E([x(Qf)],st.prototype,"sizeDelta",2),E([x(Hd)],st.prototype,"anchoredPosition3D",2),E([x(Qf)],st.prototype,"pivot",2);var bt=class extends Me{get isGraphic(){return!0}get color(){return this._color||(this._color=new $(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 $(1,1,1,1)),this._color.copy(e))}onColorChanged(){let e=this.color;this.setOptions({backgroundColor:e,backgroundOpacity:e.alpha,borderOpacity:e.alpha})}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;get rectTransform(){return this._rect||(this._rect=R.getComponent(this.gameObject,st)),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(),zl(this,"_color",()=>Xf(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)}};E([x($)],bt.prototype,"color",1),E([x()],bt.prototype,"raycastTarget",2);var ln=class extends bt{onAfterCreated(){this.uiObject&&(this.uiObject.scale.y*=-1)}};var Wl=class{texture;rect};E([x(Yf)],Wl.prototype,"texture",2);var cn=class extends ln{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 m_(.4,.4,.4),e.borderOpacity=this.color.alpha,e.borderWidth=.3)}onAfterCreated(){super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture)}};E([x(Wl)],cn.prototype,"sprite",2);var Er=class extends ln{mainTexture;onAfterCreated(){super.onAfterCreated(),this.setTexture(this.mainTexture)}};E([x(Yf)],Er.prototype,"mainTexture",2);var as=M("debugbutton");var Bt=class extends k{onClick;_isHovered=!1;onPointerEnter(e){as&&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(){as&&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){as&&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){as&&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){as&&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(),as&&console.log(this),this.init()}start(){this._image?.setInteractable(this.interactable)}onEnable(){super.onEnable()}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.SetTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=R.getComponent(this.gameObject,cn),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 s=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:s,backgroundOpacity:s.alpha}};e.setupState(a);let c=this.getFinalColor(e.color,this.colors?.selectedColor),u={state:"selected",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};e.setupState(u);let l=this.getFinalColor(e.color,this.colors?.disabledColor),d={state:"disabled",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(d)}getFinalColor(e,t){return t?e.clone().multiply(t):e.clone()}};E([x(ye)],Bt.prototype,"onClick",2),E([x()],Bt.prototype,"colors",2),E([x()],Bt.prototype,"transition",2),E([x()],Bt.prototype,"animationTriggers",2),E([x(Ye)],Bt.prototype,"animator",2),E([x()],Bt.prototype,"interactable",1);var Bd=class extends zi{set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop}_renderOnTop=!1;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!0;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!0;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof Bd||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}awake(){this.shadowComponent=this.gameObject,super.awake()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this.onRenderSettingsChanged()}previousAspect=-1;onBeforeRender(){this.isScreenSpace&&this.context.mainCameraComponent&&this.context.mainCameraComponent.aspect!==this.previousAspect&&(this.previousAspect=this.context.mainCameraComponent.aspect,this.updateRenderMode())}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),3))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.updateRenderMode(),ss(this.shadowComponent,this);for(let e of R.getComponentsInChildren(this.gameObject,Me))ss(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(F.toRadians(e.fieldOfView)*n)*(e.aspect*1.333333),s=r*(this.context.domHeight/this.context.domWidth);t.scale.x=-r,t.scale.y=s;break;case 2:break}}},He=Bd;E([x()],He.prototype,"renderOnTop",1),E([x()],He.prototype,"depthWrite",1),E([x()],He.prototype,"doubleSided",1),E([x()],He.prototype,"castShadows",1),E([x()],He.prototype,"receiveShadows",1),E([x()],He.prototype,"renderMode",1),E([x(He)],He.prototype,"rootCanvas",1),E([x()],He.prototype,"scaleFactor",1);var un=class extends k{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),3))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){for(let e of R.getComponentsInChildren(this.gameObject,bt,this._buffer)){let t=e.color;t.alpha=this._alpha,e.color=t}}};E([x()],un.prototype,"alpha",1),E([x()],un.prototype,"interactable",2),E([x()],un.prototype,"blocksRaycasts",2);import*as Kf from"three-mesh-ui";import{Color as j}from"three";var g_=M("debugtext");var Ce=class extends bt{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){g_&&console.log(this);let t=this.verticalOverflow==0&&this.horizontalOverflow==0;t&&(this.context.renderer.localClippingEnabled=!0);let i=this.rectTransform;this._textContainer=this.uiObject=this.createBlock(i,t,null,!0),this.createText(this.text,this.getTextOpts(),this.supportRichText),this.uiObject,this.uiObject=this.createBlock(i,t,this.uiObject,!1)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;_textContainer=null;getTextOpts(){let e=this.fontSize,t={content:this.text,fontColor:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.font=this.font?.toLocaleLowerCase(),this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&(this.uiObject.onAfterUpdate=this.updateWidth.bind(this))}createBlock(e,t,i,n=!1){let r={};r.hiddenOverflow=t,r.interLine=(this.lineSpacing-1)*this.fontSize*1.333,this.getAlignment(r,n);let s=e.createNewBlock(r);return i&&(Array.isArray(i)?s.add(...i):s.add(i)),s}getAlignment(e,t=!1){switch(t||(e.contentDirection="row"),this.alignment){default:case 0:case 1:case 2:e.justifyContent="start";break;case 3:case 4:case 5:e.justifyContent="center";break;case 6:case 7:case 8:e.justifyContent="end";break}switch(this.alignment){case 0:case 3:case 6:e.alignContent=t?"left":"top";break;case 1:case 4:case 7:e.alignContent="center";break;case 2:case 5:case 8:e.alignContent=t?"right":"bottom";break}return e}updateWidth(){this.horizontalOverflow===1&&setTimeout(()=>{if(!this._textMeshUi)return;let e=this._textMeshUi[0].parent;if(!!e&&e.lines){let t=e.lines.reduce((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[kt]===void 0&&(e[kt]=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 s=this.getNextTag(e,n.endIndex);if(s){let a=this.getText(e,n,s);this.handleTag(n,t,r),this.createText(a,t,!1)}else{let a=e.substring(n.endIndex);this.handleTag(n,t,r),this.createText(a,t,!1)}n=s}}else{let n={...t};n.content=e;let r=new Kf.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 s=this._textMeshUi[r];!s.textContent||(ss(s,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 s=n.previousValues[r];t[r]=s}}}else if(e.type.includes("color")){let n=new $s(e,{fontColor:t.fontColor});if(i.push(n),e.type.length>6){let r=e.type.substring(6);t.fontColor=b_(r)}else t.fontColor=new j(1,1,1)}else if(e.type=="b"){let n=new $s(e,{fontFamily:t.fontFamily,fontTexture:t.fontTexture});i.push(n),this.setFont(t,1)}else if(e.type=="i"){let n=new $s(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=ki(this.sourceId,this.font),this.font):null}};E([x(He)],Ce.prototype,"canvas",2),E([x()],Ce.prototype,"alignment",2),E([x()],Ce.prototype,"verticalOverflow",2),E([x()],Ce.prototype,"horizontalOverflow",2),E([x()],Ce.prototype,"lineSpacing",2),E([x()],Ce.prototype,"supportRichText",2),E([x()],Ce.prototype,"font",2),E([x()],Ce.prototype,"fontStyle",2),E([x()],Ce.prototype,"text",1),E([x()],Ce.prototype,"fontSize",1);var $s=class{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}};function b_(o){if(o.startsWith("#")){let t=o.substring(1);var e=parseInt(t,16);let i=e>>16&255,n=e>>8&255,r=e&255;return new j(i/255,n/255,r/255)}switch(o){case"black":return new j(0,0,0);case"white":return new j(1,1,1);case"red":return new j(1,0,0);case"lime":return new j(0,1,0);case"blue":return new j(0,0,1);case"yellow":return new j(1,1,0);case"cyan":return new j(0,1,1);case"magenta":return new j(1,0,1);case"silver":return new j(.75,.75,.75);case"gray":return new j(.5,.5,.5);case"maroon":return new j(.5,0,0);case"olive":return new j(.5,.5,0);case"green":return new j(0,.5,0);case"purple":return new j(.5,0,.5);case"teal":return new j(0,.5,.5);case"navy":return new j(0,0,.5);case"darkred":return new j(.54,0,0);case"brown":return new j(.55,.27,0);case"firebrick":return new j(.69,.13,.13);case"crimson":return new j(.86,.08,.24);case"tomato":return new j(1,.39,.28);case"coral":return new j(1,.49,.31);case"indianred":return new j(.6,.31,.51);case"lightcoral":return new j(.94,.5,.5);case"darkorange":return new j(1,.55,0);case"orange":return new j(1,.65,0);case"gold":return new j(1,.84,0);case"darkgoldenrod":return new j(.72,.53,.04);case"goldenrod":return new j(.85,.65,.13);case"palegoldenrod":return new j(.93,.87,.67);case"darkkhaki":return new j(.74,.7,.42);case"khaki":return new j(.94,.9,.55);case"yellowgreen":return new j(.6,.8,.19);case"darkolivegreen":return new j(.33,.42,.18);case"olivedrab":return new j(.42,.56,.14);case"lawngreen":return new j(.49,.99,0);case"chartreuse":return new j(.5,1,0);case"greenyellow":return new j(.68,1,.18);case"darkgreen":return new j(0,.39,0);case"forestgreen":return new j(.13,.55,.13);case"limegreen":return new j(.19,.8,.19);case"lightgreen":return new j(.56,.93,.56);case"palegreen":return new j(.59,.98,.59);case"darkseagreen":return new j(.56,.74,.56);case"mediumspringgreen":return new j(0,.98,.6);case"springgreen":return new j(0,1,.5);case"seagreen":return new j(.18,.31,.31);case"mediumaquamarine":return new j(.4,.8,.66);case"mediumseagreen":return new j(.24,.7,.44);case"lightseagreen":return new j(.13,.7,.67);case"darkslategray":return new j(.18,.31,.31);case"darkcyan":return new j(0,.55,.55);case"aqua":return new j(0,1,1);case"lightcyan":return new j(.8,1,1);case"darkturquoise":return new j(0,.81,.82);case"turquoise":return new j(0,.82,.82);case"mediumturquoise":return new j(.28,.82,.8);case"paleturquoise":return new j(.68,1,.93);case"aquamarine":return new j(.5,1,.83);case"powderblue":return new j(.69,.88,.9);case"cadetblue":return new j(.37,.62,.63);case"steelblue":return new j(.27,.51,.71);case"cornflowerblue":return new j(.39,.58,.93);case"deepskyblue":return new j(0,.7,1);case"dodgerblue":return new j(.12,.56,1);case"lightblue":return new j(.68,.85,.9);case"skyblue":return new j(.53,.81,.92);case"lightskyblue":return new j(.53,.81,.98);case"midnightblue":return new j(.18,.18,.31);case"darkblue":return new j(0,0,.55);case"mediumblue":return new j(0,0,.82);case"royalblue":return new j(.25,.41,.88);case"blueviolet":return new j(.54,.17,.89);case"indigo":return new j(.29,0,.51);case"darkslateblue":return new j(.28,.24,.55);case"slateblue":return new j(.42,.35,.8);case"mediumslateblue":return new j(.48,.41,.9);case"mediumpurple":return new j(.58,.44,.86);case"darkmagenta":return new j(.55,0,.55);case"darkviolet":return new j(.58,0,.83);case"darkorchid":return new j(.6,.2,.8);case"mediumorchid":return new j(.73,.33,.83);case"thistle":return new j(.84,.75,.85);case"plum":return new j(.87,.63,.87);case"violet":return new j(.93,.51,.93);case"fuchsia":return new j(1,0,1);case"orchid":return new j(.85,.44,.84);case"mediumvioletred":return new j(.78,.08,.52);case"palevioletred":return new j(.86,.44,.58);case"hotpink":return new j(1,.4,.71);case"deeppink":return new j(1,.08,.58);case"lightpink":return new j(1,.71,.76);case"pink":return new j(1,.75,.78);case"antiquewhite":return new j(.98,.92,.84);case"beige":return new j(.96,.96,.86);case"bisque":return new j(1,.89,.77);case"blanchedalmond":return new j(1,.92,.82);case"wheat":return new j(.96,.87,.87);case"cornsilk":return new j(1,.97,.86);case"lemonchiffon":return new j(1,.98,.8);case"lightgoldenrodyellow":return new j(.98,.98,.82);case"lightyellow":return new j(1,1,.8);case"saddlebrown":return new j(.55,.27,.07);case"sienna":return new j(.63,.32,.18);case"chocolate":return new j(.82,.41,.12);case"peru":return new j(.82,.52,.25);case"sandybrown":return new j(.96,.64,.38);case"burlywood":return new j(.87,.72,.53);case"tan":return new j(.82,.71,.55);case"rosybrown":return new j(.74,.56,.56);case"moccasin":return new j(1,.89,.71);case"navajowhite":return new j(1,.87,.68);case"peachpuff":return new j(1,.85,.73);case"mistyrose":return new j(1,.89,.88);case"lavenderblush":return new j(1,.94,.93);case"linen":return new j(.98,.94,.9);case"oldlace":return new j(.99,.96,.9);case"papayawhip":return new j(1,.94,.84);case"seashell":return new j(1,.96,.93);case"mintcream":return new j(.98,1,.98);case"slategray":return new j(.44,.5,.56);case"lightslategray":return new j(.47,.53,.6);case"lightsteelblue":return new j(.69,.77,.87);case"lavender":return new j(.9,.9,.98);case"floralwhite":return new j(1,.98,.98);case"aliceblue":return new j(.94,.97,1);case"ghostwhite":return new j(.97,.97,1);case"honeydew":return new j(.94,1,.94);case"ivory":return new j(1,1,.94);case"azure":return new j(.94,1,1);case"snow":return new j(1,.98,.98);case"dimgray":return new j(.4,.4,.4);case"darkgray":return new j(.66,.66,.66);case"lightgray":return new j(.83,.83,.83);case"gainsboro":return new j(.86,.86,.86);case"whitesmoke":return new j(.96,.96,.96)}return new j(1,1,1)}var po=M("debuginputfield"),X=class extends k{get text(){return this.textComponent?.text??""}get isFocused(){return X.active===this}textComponent;placeholder;onValueChanged;onEndEdit;inputEventFn;start(){po&&console.log(this.name,this)}onEnable(){X.htmlField||(X.htmlField=document.createElement("input"),X.htmlField.classList.add("ar"),document.body.appendChild(X.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),X.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&R.setActive(this.placeholder.gameObject,!1)}onDisable(){X.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected()}onPointerClick(e){po&&console.log("CLICK",e,X.active),X.activeTime=this.context.time.time,X.active!==this&&this.startCoroutine(this.activeLoop(),2),this.selectInputField()}*activeLoop(){for(this.onSelected();X.active===this&&!(this.context.input.getPointerUp(0)&&this.context.time.time-X.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(X.active!==this&&(po&&console.log("Select",this.name,this,X.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,X.htmlField?.value),X.active?.onDeselected(),X.active=this,this.placeholder&&R.setActive(this.placeholder.gameObject,!1),X.htmlField)){if(X.htmlField.value=this.textComponent?.text||"",po&&console.log("set input field value",X.htmlField.value),this.context.isInXR){let e=this.context.arOverlayElement;e&&(X.htmlField.style.width="0px",X.htmlField.style.height="0px",e.append(X.htmlField))}this.selectInputField()}}onDeselected(){X.active===this&&(X.active=null,po&&console.log("Deselect",this.name,this),X.htmlField&&(X.htmlField.blur(),document.body.append(X.htmlField),X.htmlField.style.width="",X.htmlField.style.height=""),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&R.setActive(this.placeholder.gameObject,!0),this.onEndEdit?.invoke())}onInput(e){if(X.active===this){if(po&&console.log(e.code,e,X.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}X.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&R.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&X.htmlField){if(this.textComponent.text!==X.htmlField.value){po&&console.log("VALUE CHANGED");let e=this.textComponent.text,t=X.htmlField.value;this.onValueChanged?.invoke(t,e)}this.textComponent.text=X.htmlField.value}}selectInputField(){X.htmlField&&(X.htmlField.setSelectionRange(X.htmlField.value.length,X.htmlField.value.length),X.htmlField.focus())}},vt=X;L(vt,"active",null),L(vt,"activeTime",-1),L(vt,"htmlField",null),E([x(Ce)],vt.prototype,"textComponent",2),E([x(Ce)],vt.prototype,"placeholder",2),E([x(ye)],vt.prototype,"onValueChanged",2),E([x(ye)],vt.prototype,"onEndEdit",2);import*as Jf from"three-mesh-ui";import*as ea from"three";var Zf=(a=>(a[a.fr=0]="fr",a[a.ru=1]="ru",a[a.de=2]="de",a[a.es=3]="es",a[a.el=4]="el",a[a.nord=5]="nord",a[a.eng=6]="eng",a))(Zf||{}),fo=class extends Me{font;text;keymap;padding;margin;fontSize;borderRadius;colors={keyboardBack:8750469,panelBack:2500134,button:3552822,hovered:1842204,selected:1088605};awake(){super.awake();let e=Zf[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=R.getComponent(this.gameObject,st);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:Ko+"/"+t+"-msdf.json",fontTexture:Ko+"/"+t+".png",fontSize:this.fontSize||6,backgroundColor:new ea.Color(this.colors.keyboardBack),backspaceTexture:Ko+"/backspace.png",shiftTexture:Ko+"/shift.png",enterTexture:Ko+"/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 Jf.Keyboard(n),this.gameObject.scale.set(1,1,1),this.keyboard.keys.forEach(s=>{s.setupState({state:"normal",attributes:{offset:.003,backgroundColor:new ea.Color(this.colors.button),backgroundOpacity:1}}),s.setState("normal"),s.setupState({state:"hovered",attributes:{offset:.3,backgroundColor:new ea.Color(this.colors.hovered),backgroundOpacity:1}}),s.setupState({state:"pressed",attributes:{offset:.1,backgroundColor:new ea.Color(this.colors.selected),backgroundOpacity:1},onSet:()=>{let a=s.info.input,c=s.info.command;if(this._lastKeyPressed!==a)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedTime>.05)this._lastKeyPressedStartTime=this.context.time.time;else if(this.context.time.time-this._lastKeyPressedStartTime<.5||c=="switch"||c=="shift"||c=="switch-set"){this._lastKeyPressedTime=this.context.time.time;return}if(this._lastKeyPressedTime=this.context.time.time,this._lastKeyPressed=a,c)switch(c){case"switch":this.keyboard.setNextPanel();break;case"switch-set":this.keyboard.setNextCharset();break;case"enter":this.tryAppend(`
|
|
270
|
+
`);break;case"space":this.tryAppend(" ");break;case"backspace":if(!this.text?.text?.length)break;this.text?.text&&(this.text.text=this.text.text.substring(0,this.text.text.length-1)||"");break;case"shift":this.keyboard.toggleCase();break}else s.info.input!==void 0&&this.tryAppend(s.info.input)}})})}tryAppend(e){this.text&&(this.text.text+=e,this.markDirty())}};var dn=class extends k{reverseArrangement=!1},mo=class extends dn{},go=class extends dn{},bo=class extends dn{};var Cr=class extends k{awake(){Ve.createIfNoneExists(this.context)}onEnable(){Ve.instance?.register(this)}onDisable(){Ve.instance?.unregister(this)}performRaycast(e=null){return null}},Tr=class extends Cr{targets=null;raycastHits=[];start(){this.targets=[this.gameObject]}performRaycast(e=null){return this.targets?(e??=new fe,e.targets=this.targets,e.results=this.raycastHits,this.context.physics.raycast(e)):null}},vo=class extends Tr{eventCamera=null;ignoreReversedGraphics=!1;rootRaycaster=null};import*as $f from"three";import{HTMLMesh as v_}from"three/examples/jsm/interactive/HTMLMesh.js";import{InteractiveGroup as y_}from"three/examples/jsm/interactive/InteractiveGroup.js";var yo=class extends k{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 y_(this.context.renderer,this.context.mainCamera);this.gameObject.add(t);let i=new v_(e);t.add(i),i.visible=!1,console.log(i);let n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;let r=ga(this.gameObject).clone();ba(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();let s=new $f.Box3;s.setFromObject(t),this.setWorldRotation(r.x,r.y,r.z);let a=s.max.x-s.min.x,c=s.max.y-s.min.y;if(this.keepAspect){let l=a/c;a>c?i.scale.set(1/a,1/c/l,1):i.scale.set(1/a*l,1/c,1)}else i.scale.set(1/a,1/c,1);let u=this.gameObject.scale;i.scale.multiply(u)},1)}};var ls=class{};var ta=class extends k{toggleKey="p";update(){this.context.input.isKeyDown("p")&&this.context.domElement.classList.toggle("presentation-mode")}};import*as em from"three";import{Raycaster as w_,Vector3 as E_}from"three";import*as Nl from"three";import{MeshLine as __,MeshLineMaterial as x_}from"three.meshline";var Gd=class{id=0;points=[];line=new __;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 Nl.Mesh(this.line,this.material),e.add(this.mesh)}appendPoint(e){let t=Gd.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 x_({color:10066329,lineWidth:.01})},_o=Gd;L(_o,"wp",new Nl.Vector3);var Rr=class extends k{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=R.findByGuid(t,this.context.scene);if(!!i)return this.internalStartLine(i,e,!1),this.inFlight[e]}internalStartLine(e,t,i=!0,n){let r=new _o(e??this.context.scene,n);r.id=t,this.inFlight[t]=r,i&&this.sendLineStart(r);let s;return this.freeBuffer.length<=0?s=new Array:s=this.freeBuffer.pop(),this.buffer[t]=s,{id:t}}sendLineStart(e){let t=e.mesh.parent;this.context.connection.send("line-start",{id:e.id,parentGuid:t?t.guid:void 0})}sendLineUpdate(e,t,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 C_}from"three.meshline";var Xl=class{isDrawing;lastHit;currentHandle;maxDistance;prevDistance;lastParent;constructor(){this.isDrawing=!1,this.lastHit=new E_,this.currentHandle=null,this.maxDistance=0,this.prevDistance=0,this.lastParent=null}},Ql=class extends k{lines;colliders;alignToSurface=!0;addToPaintedObject=!0;orbit;start(){this.lines||(this.lines=R.getComponent(this.gameObject,Rr),this.lines||(this.lines=R.addNewComponent(this.gameObject,Rr))),this.orbit=R.findObjectOfType(Je,this.context)??void 0,this._states.mouse=new Xl;let e={};Z.addEventListener("select-start",(t,i)=>{e[t.controller.uuid]=!0}),Z.addEventListener("update",(t,i)=>{if(e[t.controller.uuid]===!0){let n=t.getRay();this.updateLine(t.controller.uuid,n,!0,!1,!1)}}),Z.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);Ql._raycaster.setFromCamera(t,this.context.mainCamera);let i=Ql._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 s=this._states[e];if(s||(this._states[e]=new Xl,s=this._states[e]),n)s.isDrawing=!1,s.currentHandle&&(this.lines.endLine(s.currentHandle),s.currentHandle=null);else if(i){if(r)return s;let a=this.getHit(t),c=null,u=s.prevDistance;if(a)s.currentHandle||(s.maxDistance=a.distance),c=a.point,c.add(a.face.normal.multiplyScalar(.01)),s.prevDistance=a.distance;else if(s.maxDistance>0){let l=s.maxDistance;if(!s.currentHandle&&s.lastHit){let d=U(this.context.mainCamera);l=s.lastHit.distanceTo(d)}c=t.origin.add(t.direction.multiplyScalar(s.maxDistance)),s.prevDistance=s.maxDistance}if(c){if(!s.currentHandle){let l=s.lastParent??this.gameObject;this.addToPaintedObject&&a&&(l=a.object),s.lastParent=l,s.currentHandle=this.lines.startLine(l,{material:this.createRandomMaterial()})}if(this.alignToSurface&&(s.prevDistance>s.maxDistance||Math.abs(u-s.prevDistance)>.2)){let l=s.maxDistance;c=t.origin.add(t.direction.multiplyScalar(l)),s.prevDistance=l}if(s.lastHit&&s.lastHit.distanceTo(c)<s.prevDistance*.01)return s;this.lines.updateLine(s.currentHandle,{point:c}),s.lastHit.copy(c)}s.isDrawing=s.currentHandle!==null}return s}_raycastOptions=new fe;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(!!R.isActiveInHierarchy(i.object))return i}return null}createRandomMaterial(){let e;return this.context.connection.connectionId?e=ot.colorFromHashCode(ot.hashCode(this.context.connection.connectionId)):e=new em.Color("hsl("+(Math.random()*100).toFixed(0)+", 80%, 30%)"),new C_({color:e,lineWidth:F.lerp(.005,.01,Math.random())})}},cs=Ql;L(cs,"_raycaster",new w_);import{Object3D as T_}from"three";var us=class extends k{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=R.getComponent(t,Oi);i&&(i.owner=this.context.connection.connectionId)}}watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Oi.all.length-1;t>=0;t--){let i=Oi.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};E([x(qe)],us.prototype,"asset",2);var ri=class extends k{static get all(){return ri._all}static get local(){return ri._local}static isLocalPlayer(e){return e instanceof T_?R.getComponentInParent(e,ri)?.isLocalPlayer??!1:e instanceof Et?R.getComponentInParent(e.gameObject,ri)?.isLocalPlayer??!1:!1}owner;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}awake(){this.isLocalPlayer&&ri.local.push(this),ri.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(){Oo(this.gameObject,this.context.connection)}onDestroy(){if(ri.all.splice(ri.all.indexOf(this),1),this.isLocalPlayer){let e=ri._local.indexOf(this);e>=0&&ri._local.splice(e,1)}}},Oi=ri;L(Oi,"_all",[]),L(Oi,"_local",[]),E([Al(),x()],Oi.prototype,"owner",2);Cn[I]=!0;Wt[I]=!0;Xt[I]=!0;Ye[I]=!0;zt[I]=!0;Qt[I]=!0;ie[I]=!0;nr[I]=!0;Rn[I]=!0;Hi[I]=!0;Xr[I]=!0;ke[I]=!0;ae[I]=!0;bi[I]=!0;Yt[I]=!0;Tt[I]=!0;Sn[I]=!0;Pn[I]=!0;sr[I]=!0;Ct[I]=!0;ar[I]=!0;Yr[I]=!0;lr[I]=!0;xi[I]=!0;In[I]=!0;wi[I]=!0;gi[I]=!0;rr[I]=!0;ye[I]=!0;Kr[I]=!0;Jr[I]=!0;Xi[I]=!0;eo[I]=!0;Dt[I]=!0;Ki[I]=!0;Ji[I]=!0;Rt[I]=!0;St[I]=!0;to[I]=!0;Dn[I]=!0;Ae[I]=!0;Ei[I]=!0;An[I]=!0;Gi[I]=!0;pr[I]=!0;$t[I]=!0;Ci[I]=!0;Je[I]=!0;en[I]=!0;je[I]=!0;ii[I]=!0;G[I]=!0;We[I]=!0;ge[I]=!0;$i[I]=!0;rt[I]=!0;Zi[I]=!0;At[I]=!0;be[I]=!0;K[I]=!0;fr[I]=!0;Pe[I]=!0;ve[I]=!0;Ne[I]=!0;Le[I]=!0;le[I]=!0;ot[I]=!0;It[I]=!0;Zr[I]=!0;ne[I]=!0;hr[I]=!0;$r[I]=!0;Qi[I]=!0;J[I]=!0;Ln[I]=!0;jn[I]=!0;Ti[I]=!0;mt[I]=!0;gt[I]=!0;tn[I]=!0;ro[I]=!0;gr[I]=!0;nn[I]=!0;Hn[I]=!0;ni[I]=!0;ht[I]=!0;oo[I]=!0;so[I]=!0;br[I]=!0;xe[I]=!0;Ke[I]=!0;ao[I]=!0;Ri[I]=!0;Bn[I]=!0;Un[I]=!0;Fn[I]=!0;vr[I]=!0;Pt[I]=!0;z[I]=!0;Mn[I]=!0;se[I]=!0;Ot[I]=!0;dr[I]=!0;Z[I]=!0;nt[I]=!0;yr[I]=!0;lo[I]=!0;kn[I]=!0;Mt[I]=!0;Ni[I]=!0;ft[I]=!0;_e[I]=!0;Si[I]=!0;Pi[I]=!0;me[I]=!0;Ui[I]=!0;Gn[I]=!0;co[I]=!0;ls[I]=!0;uo[I]=!0;$[I]=!0;an[I]=!0;_r[I]=!0;xr[I]=!0;rn[I]=!0;Vn[I]=!0;zn[I]=!0;sn[I]=!0;on[I]=!0;Me[I]=!0;zi[I]=!0;Bt[I]=!0;He[I]=!0;un[I]=!0;Ve[I]=!0;bt[I]=!0;ln[I]=!0;cn[I]=!0;Er[I]=!0;vt[I]=!0;fo[I]=!0;dn[I]=!0;mo[I]=!0;go[I]=!0;bo[I]=!0;Jt[I]=!0;Cr[I]=!0;Tr[I]=!0;vo[I]=!0;Zt[I]=!0;ho[I]=!0;wr[I]=!0;st[I]=!0;yo[I]=!0;Ce[I]=!0;ta[I]=!0;cs[I]=!0;_o[I]=!0;Rr[I]=!0;us[I]=!0;Oi[I]=!0;O.add("AlignmentConstraint",Cn);O.add("Animation",Wt);O.add("AnimationCurve",Xt);O.add("Animator",Ye);O.add("AnimatorController",zt);O.add("AudioListener",Qt);O.add("AudioSource",ie);O.add("AvatarModel",nr);O.add("AvatarLoader",Rn);O.add("AxesHelper",Hi);O.add("BasicIKConstraint",Xr);O.add("BoxHelperComponent",ke);O.add("Camera",ae);O.add("CharacterController",bi);O.add("CharacterControllerInput",Yt);O.add("Collider",Tt);O.add("SphereCollider",Sn);O.add("BoxCollider",Pn);O.add("MeshCollider",sr);O.add("CapsuleCollider",Ct);O.add("DeleteBox",ar);O.add("Deletable",Yr);O.add("DeviceFlag",lr);O.add("DragControls",xi);O.add("DropListener",In);O.add("Duplicatable",wi);O.add("CallInfo",gi);O.add("EventListEvent",rr);O.add("EventList",ye);O.add("EventTrigger",Kr);O.add("FlyControls",Jr);O.add("BoxGizmo",Xi);O.add("GltfExportBox",eo);O.add("GltfExport",Dt);O.add("GridHelper",Ki);O.add("GroundProjectedEnv",Ji);O.add("Interactable",Rt);O.add("UsageMarker",St);O.add("FixedJoint",to);O.add("HingeJoint",Dn);O.add("Light",Ae);O.add("LODModel",Ei);O.add("LODGroup",An);O.add("LookAtConstraint",Gi);O.add("NestedGltf",pr);O.add("Networking",$t);O.add("OffsetConstraint",Ci);O.add("OrbitControls",Je);O.add("ParticleSystemRenderer",en);O.add("ParticleSystem",je);O.add("Gradient",ii);O.add("MinMaxCurve",G);O.add("MinMaxGradient",We);O.add("MainModule",ge);O.add("ParticleBurst",$i);O.add("EmissionModule",rt);O.add("ColorOverLifetimeModule",Zi);O.add("SizeOverLifetimeModule",At);O.add("ShapeModule",be);O.add("NoiseModule",K);O.add("TrailModule",fr);O.add("VelocityOverLifetimeModule",Pe);O.add("TextureSheetAnimationModule",ve);O.add("RotationOverLifetimeModule",Ne);O.add("RotationBySpeedModule",Le);O.add("LimitVelocityOverLifetimeModule",le);O.add("PlayerColor",ot);O.add("ReflectionProbe",It);O.add("FieldWithDefault",Zr);O.add("Renderer",ne);O.add("MeshRenderer",hr);O.add("SkinnedMeshRenderer",$r);O.add("RendererLightmap",Qi);O.add("Rigidbody",J);O.add("ScreenCapture",Ln);O.add("ShadowCatcher",jn);O.add("RemoteSkybox",Ti);O.add("SmoothFollow",mt);O.add("SpatialTriggerReceiver",gt);O.add("SpatialTrigger",tn);O.add("SpectatorCamera",ro);O.add("Sprite",gr);O.add("SpriteRenderer",nn);O.add("SyncedCamera",Hn);O.add("SyncedRoom",ni);O.add("SyncedTransform",ht);O.add("TestRunner",oo);O.add("TestSimulateUserData",so);O.add("TransformGizmo",br);O.add("VideoPlayer",xe);O.add("Voip",Ke);O.add("VolumeParameter",ao);O.add("VolumeComponent",Ri);O.add("ToneMapping",Bn);O.add("ColorAdjustments",Un);O.add("VolumeProfile",Fn);O.add("Volume",vr);O.add("WebARSessionRoot",Pt);O.add("WebXR",z);O.add("WebAR",Mn);O.add("AvatarMarker",se);O.add("WebXRAvatar",Ot);O.add("TeleportTarget",dr);O.add("WebXRController",Z);O.add("AttachedObject",nt);O.add("XRGrabModel",yr);O.add("XRGrabRendering",lo);O.add("XRRig",kn);O.add("VRUserState",Mt);O.add("WebXRSync",Ni);O.add("XRState",ft);O.add("XRFlag",_e);O.add("AvatarBlink_Simple",Si);O.add("AvatarEyeLook_Rotation",Pi);O.add("Avatar_POI",me);O.add("Avatar_Brain_LookAt",Ui);O.add("Avatar_MouthShapes",Gn);O.add("Avatar_MustacheShake",co);O.add("__Ignore",ls);O.add("LogStats",uo);O.add("RGBAColor",$);O.add("PlayableDirector",an);O.add("SignalAsset",_r);O.add("SignalReceiverEvent",xr);O.add("SignalReceiver",rn);O.add("AnimationTrackHandler",Vn);O.add("AudioTrackHandler",zn);O.add("SignalTrackHandler",sn);O.add("ControlTrackHandler",on);O.add("BaseUIComponent",Me);O.add("UIRootComponent",zi);O.add("Button",Bt);O.add("Canvas",He);O.add("CanvasGroup",un);O.add("EventSystem",Ve);O.add("Graphic",bt);O.add("MaskableGraphic",ln);O.add("Image",cn);O.add("RawImage",Er);O.add("InputField",vt);O.add("Keyboard",fo);O.add("LayoutGroup",dn);O.add("VerticalLayoutGroup",mo);O.add("HorizontalLayoutGroup",go);O.add("GridLayoutGroup",bo);O.add("PointerEventData",Jt);O.add("Raycaster",Cr);O.add("ObjectRaycaster",Tr);O.add("GraphicRaycaster",vo);O.add("UIRaycastUtils",Zt);O.add("Size",ho);O.add("Rect",wr);O.add("RectTransform",st);O.add("SpatialHtml",yo);O.add("Text",Ce);O.add("PresentationMode",ta);O.add("LinesDrawer",cs);O.add("LineInstanceHandler",_o);O.add("LinesManager",Rr);O.add("PlayerSync",us);O.add("PlayerState",Oi);var tm=Te,R_=M("debugtypestore");R_&&console.log(O);function im(o,e){let i=fc(o,e);return i!==void 0?i:null}var S_=new ha;async function nm(o,e,t,i=null,n){if(!t)return;let r=[],s=i;typeof s=="number"&&(s=new Ue(i));let a=new Ro(t.scene);a.gltfId=e,a.context=o,a.gltf=t,a.nodeToObject=n?.nodeToObjectMap,a.implementationInformation=S_;let c=[];if(t.scenes)for(let u of t.scenes)await zd(a,u,c,r);if(t.children)for(let u of t.children)await zd(a,u,c,r);o.new_scripts_pre_setup_callbacks.push(()=>{for(let u of c)P_(u,a);if(s){Vd(t,s);for(let u of t.scenes)Vd(u,s)}})}function Vd(o,e){if(e!==null&&!!o){if(o.guid=e.generateUUID(),o&&o.userData&&o.userData.components)for(let t of o.userData.components)t!==null&&(t.guid=e.generateUUID());if(o.children)for(let t of o.children)Vd(t,e)}}var ia=[];async function zd(o,e,t,i){if(!e)return;let n=e.userData;if(n){let r=n.builtin_components;if(r&&r.length>0)for(let s of r)try{if(s===null)continue;let a=O.get(s.name);if(a!=null){let c=new a;c.sourceId=o.gltfId,oi(c,s,o.implementationInformation),qn(e,c,!1),t.push({instance:c,compData:s,obj:e})}else tm&&console.debug("unknown component: "+s.name),ia.includes(s.name)||ia.push(s.name)}catch(a){console.error(s.name+" - "+a.message,a)}if(ia.length>0){let s=ia.join(", ");console.warn("unknown components: "+s),ia.length=0,Xn()&&Ze(`<strong>Unknown components in scene</strong>:
|
|
271
271
|
|
|
272
272
|
${s}
|
|
273
273
|
|
|
274
274
|
This could mean you forgot to add a npmdef to your ExportInfo
|
|
275
|
-
<a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,1)}}if(e.children)for(let r of e.children)await zd(o,r,t,i)}function P_(o,e){let{instance:t,compData:i,obj:n}=o;e.object=n,e.target=t;let r=!0;r=ys(t,i,e)===!0,tm&&console.debug("add "+i.name,i,t)}var na=class{createBuiltinComponents(e,t,i,n,r){return nm(e,t,i,n,r)}writeBuiltinComponentData(e,t){return im(e,t)}parseSync(e,t,i,n){return k_(e,t,i,n)}loadSync(e,t,i,n,r){return M_(e,t,i,n,r)}};Wa(na);var O_=M("printGltf");var Sr=class{context;loader;path;gltf;constructor(e,t,i,n){this.context=e,this.path=t,this.loader=i,this.gltf=n}},rm={};function ds(o,e){if(rm[o])for(let t of rm[o])t(e)}async function sm(o,e,t,i,n){O_&&console.log(t),await o.assets.registerGltf(t),await Qe().createBuiltinComponents(o,e,t,i,n)}function k_(o,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 om;wu(n,o,t);let s=xu(n);return new Promise((a,c)=>{try{_n(n,o),ds(0,new Sr(o,t,n)),n.parse(e,t,async u=>{ds(1,new Sr(o,t,n,u)),await sm(o,t,u,i,s),ds(10,new Sr(o,t,n,u)),a(u)},u=>{console.error("failed loading "+t,u),a(void 0)})}catch(u){console.error(u),c(u)}})}function M_(o,e,t,i=!1,n){let r=new om;wu(r,o,e);let a=xu(r);return new Promise((c,u)=>{try{_n(r,o),ds(0,new Sr(o,e,r)),r.load(e,async l=>{ds(1,new Sr(o,e,r,l)),await sm(o,e,l,t,a),ds(10,new Sr(o,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),u(l)}})}Wa(na);var xo=M("debugwebcomponent"),Wd=class{id;context;previouslyAdded;previousSource;networkEvent;constructor(e,t){this.id=e,this.context=t,this.networkEvent="needle-engine-source-changed",this.id&&(this.networkEvent+="-"+this.id),this.context.connection.beginListen(this.networkEvent,i=>{this.onSourceChanged(i,!0)})}async onSourceChanged(e,t=!1,i=!1){this.previouslyAdded&&(t&&e===this.previousSource||R.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,V.Current=this.context;let n=await Qe().loadSync(this.context,e,this.getHashFromString(e),!1);i||vn(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}},I_="needle-engine",D_="vr",A_="desktop",L_=[fn,D_,A_],Nd=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=R;GameObject=R;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new oa}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let a=this.getAttribute("src");return a?.endsWith(".glb")||a?.endsWith(".gltf")?a:null},i="loadScene",n=t();n&&(i=n);let r=this.getAttribute("alias"),s=this.getAttribute("hash");if(this._context=new V({name:i,domElement:this,alias:r,hash:s??void 0}),this._watcher=new Wd(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(tl).length<=0;){if(!this.isConnected)return;await uh(10)}let a=tl[i]??window[i],c=null;if((!a||n)&&(n&&(i=n),a=async u=>{let l=t();l&&this._watcher&&(c=l,await this._watcher.onSourceChanged(l,!0,!0))}),a){this.classList.add("loading"),console.log("Needle Engine: Begin loading",r??"");let u=!0,l=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:u}));!this._loadingView&&l&&(this._loadingView=new il(this)),l&&this._loadingView?.onLoadingBegin("begin load");let d=(b,_)=>{this._loadingProgress01=tu(b),l&&this._loadingView?.onLoadingUpdate(b,_),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:b.name,progress:b.progress,index:b.index,count:b.count,totalProgress01:this._loadingProgress01}}))};this.onBeforeBeginLoading(),await this._context.onCreate(a,{progress:d});let h=t();h&&h!==c&&await this._watcher.onSourceChanged(h,!0,!0),this._loadingProgress01=1,l&&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',tl)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this._context&&this._context.onDestroy()}static get observedAttributes(){return["hash","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&&(xo&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":xo&&console.log("dracoDecoderPath",i),nu(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(xo&&console.log("dracoDecoderType",i),ru(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":xo&&console.log("ktx2DecoderPath",i),ou(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,fn))}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 L_)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&&(xo&&console.log("using custom draco decoder path",e),nu(e));let t=this.getAttribute("dracoDecoderType");t&&(xo&&console.log("using custom draco decoder type",t),ru(t));let i=this.getAttribute("ktx2DecoderPath");i&&(xo&&console.log("using custom ktx2 decoder path",i),ou(i))}};window.customElements.define(I_,Nd);import*as j_ from"three";var Xd={Context:V};globalThis.Needle=Xd;function am(o){for(let e in o)Xd[e]=o[e]}am(eu);am(Ud);for(let o of Object.getOwnPropertyNames(R))switch(o){case"prototype":case"constructor":case"length":case"name":continue;default:Xd[o]=R[o];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=j_;export{En as AlignmentConstraint,Wt as Animation,Xt as AnimationCurve,Vn as AnimationTrackHandler,Ye as Animator,zt as AnimatorController,qe as AssetReference,nt as AttachedObject,Qt as AudioListener,ie as AudioSource,zn as AudioTrackHandler,Ri as AvatarBlink_Simple,Si as AvatarEyeLook_Rotation,Tn as AvatarLoader,se as AvatarMarker,nr as AvatarModel,Bi as Avatar_Brain_LookAt,Gn as Avatar_MouthShapes,co as Avatar_MustacheShake,me as Avatar_POI,ji as AxesHelper,Me as BaseUIComponent,Xr as BasicIKConstraint,k as Behaviour,Sn as BoxCollider,Ni as BoxGizmo,ke as BoxHelperComponent,Bt as Button,gi as CallInfo,ae as Camera,He as Canvas,cn as CanvasGroup,Ct as CapsuleCollider,bi as CharacterController,Yt as CharacterControllerInput,Tt as Collider,Cs as Collision,Un as ColorAdjustments,Ji as ColorOverLifetimeModule,rn as ControlTrackHandler,Yr as Deletable,ar as DeleteBox,lr as DeviceFlag,xi as DragControls,Mn as DropListener,wi as Duplicatable,rt as EmissionModule,ye as EventList,rr as EventListEvent,Ve as EventSystem,Kr as EventTrigger,Zr as FieldWithDefault,to as FixedJoint,Jr as FlyControls,Vt as FrameEvent,R as GameObject,Ur as Gizmos,Dt as GltfExport,eo as GltfExportBox,ii as Gradient,bt as Graphic,vo as GraphicRaycaster,Yi as GridHelper,bo as GridLayoutGroup,Ki as GroundProjectedEnv,ng as HideFlags,In as HingeJoint,go as HorizontalLayoutGroup,ln as Image,vt as InputField,oe as InstancingUtil,Ge as InstantiateOptions,Rt as Interactable,fo as Keyboard,Dn as LODGroup,Ei as LODModel,un as LayoutGroup,Ae as Light,le as LimitVelocityOverLifetimeModule,uo as LogStats,bs as LogType,Ui as LookAtConstraint,ge as MainModule,an as MaskableGraphic,sr as MeshCollider,hr as MeshRenderer,G as MinMaxCurve,We as MinMaxGradient,pr as NestedGltf,$t as Networking,K as NoiseModule,Tr as ObjectRaycaster,Ci as OffsetConstraint,Je as OrbitControls,Zi as ParticleBurst,je as ParticleSystem,$i as ParticleSystemRenderer,sn as PlayableDirector,ot as PlayerColor,Jt as PointerEventData,$ as RGBAColor,Er as RawImage,Cr as Raycaster,wr as Rect,st as RectTransform,It as ReflectionProbe,jn as RemoteSkybox,ne as Renderer,Xi as RendererLightmap,J as Rigidbody,Le as RotationBySpeedModule,Ne as RotationOverLifetimeModule,An as ScreenCapture,Ln as ShadowCatcher,be as ShapeModule,_r as SignalAsset,nn as SignalReceiver,xr as SignalReceiverEvent,on as SignalTrackHandler,ho as Size,At as SizeOverLifetimeModule,$r as SkinnedMeshRenderer,mt as SmoothFollow,yo as SpatialHtml,en as SpatialTrigger,gt as SpatialTriggerReceiver,ro as SpectatorCamera,Rn as SphereCollider,gr as Sprite,tn as SpriteRenderer,Hn as SyncedCamera,ni as SyncedRoom,ht as SyncedTransform,dr as TeleportTarget,oo as TestRunner,so as TestSimulateUserData,Ce as Text,ve as TextureSheetAnimationModule,Bn as ToneMapping,fr as TrailModule,br as TransformGizmo,Zt as UIRaycastUtils,Vi as UIRootComponent,St as UsageMarker,Mt as VRUserState,Pe as VelocityOverLifetimeModule,mo as VerticalLayoutGroup,xe as VideoPlayer,Ke as Voip,vr as Volume,Ti as VolumeComponent,ao as VolumeParameter,Fn as VolumeProfile,kn as WebAR,Pt as WebARSessionRoot,z as WebXR,Ot as WebXRAvatar,Z as WebXRController,Wi as WebXRSync,_e as XRFlag,yr as XRGrabModel,lo as XRGrabRendering,On as XRRig,ft as XRState,ls as __Ignore,qn as addNewComponentInstance,Do as apply,li as destroy,Nh as destroyComponentInstance,Ar as findByGuid,Qh as findObjectOfType,qh as findObjectsOfType,ci as foreachComponent,jr as getComponent,Hr as getComponentInChildren,ko as getComponentInParent,Mo as getComponents,Io as getComponentsInChildren,Ss as getComponentsInParent,Ta as getOrAddComponent,Lr as instantiate,Kh as isActiveInHierarchy,Dr as isActiveSelf,ka as isUsingInstancing,Jh as markAsInstancedRendered,Wh as moveComponentInstance,Ca as removeComponent,w as serializeable,Oa as setActive,Ze as showBalloonMessage,vs as showBalloonWarning,hi as validate};
|
|
275
|
+
<a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,1)}}if(e.children)for(let r of e.children)await zd(o,r,t,i)}function P_(o,e){let{instance:t,compData:i,obj:n}=o;e.object=n,e.target=t;let r=!0;r=ys(t,i,e)===!0,tm&&console.debug("add "+i.name,i,t)}var na=class{createBuiltinComponents(e,t,i,n,r){return nm(e,t,i,n,r)}writeBuiltinComponentData(e,t){return im(e,t)}parseSync(e,t,i,n){return k_(e,t,i,n)}loadSync(e,t,i,n,r){return M_(e,t,i,n,r)}};Wa(na);var O_=M("printGltf");var Sr=class{context;loader;path;gltf;constructor(e,t,i,n){this.context=e,this.path=t,this.loader=i,this.gltf=n}},rm={};function ds(o,e){if(rm[o])for(let t of rm[o])t(e)}async function sm(o,e,t,i,n){O_&&console.log(t),await o.assets.registerGltf(t),await Qe().createBuiltinComponents(o,e,t,i,n)}function k_(o,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 om;wu(n,o,t);let s=xu(n);return new Promise((a,c)=>{try{xn(n,o),ds(0,new Sr(o,t,n)),n.parse(e,t,async u=>{ds(1,new Sr(o,t,n,u)),await sm(o,t,u,i,s),ds(10,new Sr(o,t,n,u)),a(u)},u=>{console.error("failed loading "+t,u),a(void 0)})}catch(u){console.error(u),c(u)}})}function M_(o,e,t,i=!1,n){let r=new om;wu(r,o,e);let a=xu(r);return new Promise((c,u)=>{try{xn(r,o),ds(0,new Sr(o,e,r)),r.load(e,async l=>{ds(1,new Sr(o,e,r,l)),await sm(o,e,l,t,a),ds(10,new Sr(o,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),u(l)}})}Wa(na);var xo=M("debugwebcomponent"),Wd=class{id;context;previouslyAdded;previousSource;networkEvent;constructor(e,t){this.id=e,this.context=t,this.networkEvent="needle-engine-source-changed",this.id&&(this.networkEvent+="-"+this.id),this.context.connection.beginListen(this.networkEvent,i=>{this.onSourceChanged(i,!0)})}async onSourceChanged(e,t=!1,i=!1){this.previouslyAdded&&(t&&e===this.previousSource||R.destroySynced(this.previouslyAdded)),this.previouslyAdded=null,t||this.context.connection.send(this.networkEvent,e),this.previousSource=e,V.Current=this.context;let n=await Qe().loadSync(this.context,e,this.getHashFromString(e),!1);i||yn(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}},I_="needle-engine",D_="vr",A_="desktop",L_=[mn,D_,A_],Nd=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=R;GameObject=R;_context=null;_overlay_ar;_loadingProgress01=0;_watcher;_loadingView;constructor(){super(),this._overlay_ar=new oa}async connectedCallback(){this.onSetupDesktop();var e=new MutationObserver(this.onElementsChanged.bind(this));e.observe(this,{childList:!0});let t=()=>{let a=this.getAttribute("src");return a?.endsWith(".glb")||a?.endsWith(".gltf")?a:null},i="loadScene",n=t();n&&(i=n);let r=this.getAttribute("alias"),s=this.getAttribute("hash");if(this._context=new V({name:i,domElement:this,alias:r,hash:s??void 0}),this._watcher=new Wd(this.getAttribute("id")??r??"",this._context),i&&i.length>0){if(!n)for(;Object.keys(tl).length<=0;){if(!this.isConnected)return;await uh(10)}let a=tl[i]??window[i],c=null;if((!a||n)&&(n&&(i=n),a=async u=>{let l=t();l&&this._watcher&&(c=l,await this._watcher.onSourceChanged(l,!0,!0))}),a){this.classList.add("loading"),console.log("Needle Engine: Begin loading",r??"");let u=!0,l=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:r},cancelable:u}));!this._loadingView&&l&&(this._loadingView=new il(this)),l&&this._loadingView?.onLoadingBegin("begin load");let d=(b,_)=>{this._loadingProgress01=tu(b),l&&this._loadingView?.onLoadingUpdate(b,_),this.dispatchEvent(new CustomEvent("progress",{detail:{context:this._context,name:b.name,progress:b.progress,index:b.index,count:b.count,totalProgress01:this._loadingProgress01}}))};this.onBeforeBeginLoading(),await this._context.onCreate(a,{progress:d});let h=t();h&&h!==c&&await this._watcher.onSourceChanged(h,!0,!0),this._loadingProgress01=1,l&&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',tl)}else console.error("Missing src attribute - please provide a function name",this)}disconnectedCallback(){this._context&&this._context.onDestroy()}static get observedAttributes(){return["hash","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&&(xo&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":xo&&console.log("dracoDecoderPath",i),nu(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(xo&&console.log("dracoDecoderType",i),ru(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":xo&&console.log("ktx2DecoderPath",i),ou(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,mn))}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 L_)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&&(xo&&console.log("using custom draco decoder path",e),nu(e));let t=this.getAttribute("dracoDecoderType");t&&(xo&&console.log("using custom draco decoder type",t),ru(t));let i=this.getAttribute("ktx2DecoderPath");i&&(xo&&console.log("using custom ktx2 decoder path",i),ou(i))}};window.customElements.define(I_,Nd);import*as j_ from"three";var Xd={Context:V};globalThis.Needle=Xd;function am(o){for(let e in o)Xd[e]=o[e]}am(eu);am(Ud);for(let o of Object.getOwnPropertyNames(R))switch(o){case"prototype":case"constructor":case"length":case"name":continue;default:Xd[o]=R[o];break}globalThis.THREE?console.warn("Threejs is already imported"):globalThis.THREE=j_;export{Cn as AlignmentConstraint,Wt as Animation,Xt as AnimationCurve,Vn as AnimationTrackHandler,Ye as Animator,zt as AnimatorController,qe as AssetReference,nt as AttachedObject,Qt as AudioListener,ie as AudioSource,zn as AudioTrackHandler,Si as AvatarBlink_Simple,Pi as AvatarEyeLook_Rotation,Rn as AvatarLoader,se as AvatarMarker,nr as AvatarModel,Ui as Avatar_Brain_LookAt,Gn as Avatar_MouthShapes,co as Avatar_MustacheShake,me as Avatar_POI,Hi as AxesHelper,Me as BaseUIComponent,Xr as BasicIKConstraint,k as Behaviour,Pn as BoxCollider,Xi as BoxGizmo,ke as BoxHelperComponent,Bt as Button,gi as CallInfo,ae as Camera,He as Canvas,un as CanvasGroup,Ct as CapsuleCollider,bi as CharacterController,Yt as CharacterControllerInput,Tt as Collider,Cs as Collision,Un as ColorAdjustments,Zi as ColorOverLifetimeModule,on as ControlTrackHandler,Yr as Deletable,ar as DeleteBox,lr as DeviceFlag,xi as DragControls,In as DropListener,wi as Duplicatable,rt as EmissionModule,ye as EventList,rr as EventListEvent,Ve as EventSystem,Kr as EventTrigger,Zr as FieldWithDefault,to as FixedJoint,Jr as FlyControls,Vt as FrameEvent,R as GameObject,Ur as Gizmos,Dt as GltfExport,eo as GltfExportBox,ii as Gradient,bt as Graphic,vo as GraphicRaycaster,Ki as GridHelper,bo as GridLayoutGroup,Ji as GroundProjectedEnv,ng as HideFlags,Dn as HingeJoint,go as HorizontalLayoutGroup,cn as Image,vt as InputField,oe as InstancingUtil,Ge as InstantiateOptions,Rt as Interactable,fo as Keyboard,An as LODGroup,Ei as LODModel,dn as LayoutGroup,Ae as Light,le as LimitVelocityOverLifetimeModule,uo as LogStats,bs as LogType,Gi as LookAtConstraint,ge as MainModule,ln as MaskableGraphic,sr as MeshCollider,hr as MeshRenderer,G as MinMaxCurve,We as MinMaxGradient,pr as NestedGltf,$t as Networking,K as NoiseModule,Tr as ObjectRaycaster,Ci as OffsetConstraint,Je as OrbitControls,$i as ParticleBurst,je as ParticleSystem,en as ParticleSystemRenderer,an as PlayableDirector,ot as PlayerColor,Jt as PointerEventData,$ as RGBAColor,Er as RawImage,Cr as Raycaster,wr as Rect,st as RectTransform,It as ReflectionProbe,Ti as RemoteSkybox,ne as Renderer,Qi as RendererLightmap,J as Rigidbody,Le as RotationBySpeedModule,Ne as RotationOverLifetimeModule,Ln as ScreenCapture,jn as ShadowCatcher,be as ShapeModule,_r as SignalAsset,rn as SignalReceiver,xr as SignalReceiverEvent,sn as SignalTrackHandler,ho as Size,At as SizeOverLifetimeModule,$r as SkinnedMeshRenderer,mt as SmoothFollow,yo as SpatialHtml,tn as SpatialTrigger,gt as SpatialTriggerReceiver,ro as SpectatorCamera,Sn as SphereCollider,gr as Sprite,nn as SpriteRenderer,Hn as SyncedCamera,ni as SyncedRoom,ht as SyncedTransform,dr as TeleportTarget,oo as TestRunner,so as TestSimulateUserData,Ce as Text,ve as TextureSheetAnimationModule,Bn as ToneMapping,fr as TrailModule,br as TransformGizmo,O as TypeStore,Zt as UIRaycastUtils,zi as UIRootComponent,St as UsageMarker,Mt as VRUserState,Pe as VelocityOverLifetimeModule,mo as VerticalLayoutGroup,xe as VideoPlayer,Ke as Voip,vr as Volume,Ri as VolumeComponent,ao as VolumeParameter,Fn as VolumeProfile,Mn as WebAR,Pt as WebARSessionRoot,z as WebXR,Ot as WebXRAvatar,Z as WebXRController,Ni as WebXRSync,_e as XRFlag,yr as XRGrabModel,lo as XRGrabRendering,kn as XRRig,ft as XRState,ls as __Ignore,qn as addNewComponentInstance,Do as apply,li as destroy,Nh as destroyComponentInstance,Ar as findByGuid,Qh as findObjectOfType,qh as findObjectsOfType,ci as foreachComponent,jr as getComponent,Hr as getComponentInChildren,ko as getComponentInParent,Mo as getComponents,Io as getComponentsInChildren,Ss as getComponentsInParent,Ta as getOrAddComponent,Lr as instantiate,Kh as isActiveInHierarchy,Dr as isActiveSelf,ka as isUsingInstancing,Jh as markAsInstancedRendered,Wh as moveComponentInstance,Ca as removeComponent,x as serializeable,Oa as setActive,Ze as showBalloonMessage,vs as showBalloonWarning,hi as validate};
|
|
276
276
|
/*!
|
|
277
277
|
* Determine if an object is a Buffer
|
|
278
278
|
*
|