@needle-tools/engine 3.6.0-alpha → 3.6.0-alpha.2
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.js +12 -12
- package/dist/needle-engine.light.js +4965 -4965
- package/dist/needle-engine.light.min.js +5 -5
- package/dist/needle-engine.light.umd.cjs +5 -5
- package/dist/needle-engine.min.js +5 -5
- package/dist/needle-engine.umd.cjs +5 -5
- package/lib/engine/engine_context.js +2 -2
- package/lib/engine/engine_context.js.map +1 -1
- package/lib/engine-components/Camera.js +0 -3
- package/lib/engine-components/Camera.js.map +1 -1
- package/lib/engine-components/OrbitControls.js +7 -3
- package/lib/engine-components/OrbitControls.js.map +1 -1
- package/package.json +1 -1
- package/plugins/vite/defines.js +5 -2
- package/src/engine/engine_context.ts +2 -2
- package/src/engine-components/Camera.ts +0 -4
- package/src/engine-components/OrbitControls.ts +6 -2
|
@@ -3333,11 +3333,11 @@ a=extmap-allow-mixed`)!==-1){const I=g.sdp.split(`
|
|
|
3333
3333
|
isUnifiedPlanSupported:`).concat(this.isUnifiedPlanSupported())},t}()),kq={iceServers:[{urls:"stun:stun.l.google.com:19302"},{urls:["turn:eu-0.turn.peerjs.com:3478","turn:us-0.turn.peerjs.com:3478"],username:"peerjs",credential:"peerjsp"}],sdpSemantics:"unified-plan"},_W=function(){function t(){this.CLOUD_HOST="0.peerjs.com",this.CLOUD_PORT=443,this.chunkedBrowsers={Chrome:1,chrome:1},this.chunkedMTU=16300,this.defaultConfig=kq,this.browser=Kh.getBrowser(),this.browserVersion=Kh.getVersion(),this.supports=function(){var A={browser:Kh.isBrowserSupported(),webRTC:Kh.isWebRTCSupported(),audioVideo:!1,data:!1,binaryBlob:!1,reliable:!1};if(!A.webRTC)return A;var e;try{e=new RTCPeerConnection(kq),A.audioVideo=!0;var g=void 0;try{g=e.createDataChannel("_PEERJSTEST",{ordered:!0}),A.data=!0,A.reliable=!!g.ordered;try{g.binaryType="blob",A.binaryBlob=!Kh.isIOS}catch{}}catch{}finally{g&&g.close()}}catch{}finally{e&&e.close()}return A}(),this.pack=NJ.pack,this.unpack=NJ.unpack,this._dataCount=1}return t.prototype.noop=function(){},t.prototype.validateId=function(A){return!A||/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.test(A)},t.prototype.chunk=function(A){for(var e=[],g=A.size,I=Math.ceil(g/nt.chunkedMTU),i=0,o=0;o<g;){var C=Math.min(g,o+nt.chunkedMTU),s=A.slice(o,C),a={__peerData:this._dataCount,n:i,data:s,total:I};e.push(a),o=C,i++}return this._dataCount++,e},t.prototype.blobToArrayBuffer=function(A,e){var g=new FileReader;return g.onload=function(I){I.target&&e(I.target.result)},g.readAsArrayBuffer(A),g},t.prototype.binaryStringToArrayBuffer=function(A){for(var e=new Uint8Array(A.length),g=0;g<A.length;g++)e[g]=A.charCodeAt(g)&255;return e.buffer},t.prototype.randomToken=function(){return Math.random().toString(36).slice(2)},t.prototype.isSecure=function(){return location.protocol==="https:"},t}(),nt=new _W,Gq={};tC(Gq,"Peer",()=>Hq,t=>Hq=t);var Jh={},OW=Object.prototype.hasOwnProperty,FI="~";function qh(){}Object.create&&(qh.prototype=Object.create(null),new qh().__proto__||(FI=!1));function PW(t,A,e){this.fn=t,this.context=A,this.once=e||!1}function mq(t,A,e,g,I){if(typeof e!="function")throw new TypeError("The listener must be a function");var i=new PW(e,g||t,I),o=FI?FI+A:A;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],i]:t._events[o].push(i):(t._events[o]=i,t._eventsCount++),t}function Su(t,A){--t._eventsCount===0?t._events=new qh:delete t._events[A]}function cI(){this._events=new qh,this._eventsCount=0}cI.prototype.eventNames=function(){var t=[],A,e;if(this._eventsCount===0)return t;for(e in A=this._events)OW.call(A,e)&&t.push(FI?e.slice(1):e);return Object.getOwnPropertySymbols?t.concat(Object.getOwnPropertySymbols(A)):t},cI.prototype.listeners=function(t){var A=FI?FI+t:t,e=this._events[A];if(!e)return[];if(e.fn)return[e.fn];for(var g=0,I=e.length,i=new Array(I);g<I;g++)i[g]=e[g].fn;return i},cI.prototype.listenerCount=function(t){var A=FI?FI+t:t,e=this._events[A];return e?e.fn?1:e.length:0},cI.prototype.emit=function(t,A,e,g,I,i){var o=FI?FI+t:t;if(!this._events[o])return!1;var C=this._events[o],s=arguments.length,a,n;if(C.fn){switch(C.once&&this.removeListener(t,C.fn,void 0,!0),s){case 1:return C.fn.call(C.context),!0;case 2:return C.fn.call(C.context,A),!0;case 3:return C.fn.call(C.context,A,e),!0;case 4:return C.fn.call(C.context,A,e,g),!0;case 5:return C.fn.call(C.context,A,e,g,I),!0;case 6:return C.fn.call(C.context,A,e,g,I,i),!0}for(n=1,a=new Array(s-1);n<s;n++)a[n-1]=arguments[n];C.fn.apply(C.context,a)}else{var B=C.length,Q;for(n=0;n<B;n++)switch(C[n].once&&this.removeListener(t,C[n].fn,void 0,!0),s){case 1:C[n].fn.call(C[n].context);break;case 2:C[n].fn.call(C[n].context,A);break;case 3:C[n].fn.call(C[n].context,A,e);break;case 4:C[n].fn.call(C[n].context,A,e,g);break;default:if(!a)for(Q=1,a=new Array(s-1);Q<s;Q++)a[Q-1]=arguments[Q];C[n].fn.apply(C[n].context,a)}}return!0},cI.prototype.on=function(t,A,e){return mq(this,t,A,e,!1)},cI.prototype.once=function(t,A,e){return mq(this,t,A,e,!0)},cI.prototype.removeListener=function(t,A,e,g){var I=FI?FI+t:t;if(!this._events[I])return this;if(!A)return Su(this,I),this;var i=this._events[I];if(i.fn)i.fn===A&&(!g||i.once)&&(!e||i.context===e)&&Su(this,I);else{for(var o=0,C=[],s=i.length;o<s;o++)(i[o].fn!==A||g&&!i[o].once||e&&i[o].context!==e)&&C.push(i[o]);C.length?this._events[I]=C.length===1?C[0]:C:Su(this,I)}return this},cI.prototype.removeAllListeners=function(t){var A;return t?(A=FI?FI+t:t,this._events[A]&&Su(this,A)):(this._events=new qh,this._eventsCount=0),this},cI.prototype.off=cI.prototype.removeListener,cI.prototype.addListener=cI.prototype.on,cI.prefixed=FI,cI.EventEmitter=cI,Jh=cI;var te={};tC(te,"LogLevel",()=>ZI,t=>ZI=t),tC(te,"default",()=>Mq,t=>Mq=t);var ar=function(t,A){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var g=e.call(t),I,i=[],o;try{for(;(A===void 0||A-- >0)&&!(I=g.next()).done;)i.push(I.value)}catch(C){o={error:C}}finally{try{I&&!I.done&&(e=g.return)&&e.call(g)}finally{if(o)throw o.error}}return i},nr=function(t,A,e){if(e||arguments.length===2)for(var g=0,I=A.length,i;g<I;g++)(i||!(g in A))&&(i||(i=Array.prototype.slice.call(A,0,g)),i[g]=A[g]);return t.concat(i||Array.prototype.slice.call(A))},jW="PeerJS: ",ZI;(function(t){t[t.Disabled=0]="Disabled",t[t.Errors=1]="Errors",t[t.Warnings=2]="Warnings",t[t.All=3]="All"})(ZI||(ZI={}));var WW=function(){function t(){this._logLevel=ZI.Disabled}return Object.defineProperty(t.prototype,"logLevel",{get:function(){return this._logLevel},set:function(A){this._logLevel=A},enumerable:!1,configurable:!0}),t.prototype.log=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=ZI.All&&this._print.apply(this,nr([ZI.All],ar(A),!1))},t.prototype.warn=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=ZI.Warnings&&this._print.apply(this,nr([ZI.Warnings],ar(A),!1))},t.prototype.error=function(){for(var A=[],e=0;e<arguments.length;e++)A[e]=arguments[e];this._logLevel>=ZI.Errors&&this._print.apply(this,nr([ZI.Errors],ar(A),!1))},t.prototype.setLogFunction=function(A){this._print=A},t.prototype._print=function(A){for(var e=[],g=1;g<arguments.length;g++)e[g-1]=arguments[g];var I=nr([jW],ar(e),!1);for(var i in I)I[i]instanceof Error&&(I[i]="("+I[i].name+") "+I[i].message);A>=ZI.All?console.log.apply(console,nr([],ar(I),!1)):A>=ZI.Warnings?console.warn.apply(console,nr(["WARNING"],ar(I),!1)):A>=ZI.Errors&&console.error.apply(console,nr(["ERROR"],ar(I),!1))},t}(),Mq=new WW,Rq={};tC(Rq,"Socket",()=>Uq,t=>Uq=t);var mo;(function(t){t.Data="data",t.Media="media"})(mo||(mo={}));var gg;(function(t){t.BrowserIncompatible="browser-incompatible",t.Disconnected="disconnected",t.InvalidID="invalid-id",t.InvalidKey="invalid-key",t.Network="network",t.PeerUnavailable="peer-unavailable",t.SslUnavailable="ssl-unavailable",t.ServerError="server-error",t.SocketError="socket-error",t.SocketClosed="socket-closed",t.UnavailableID="unavailable-id",t.WebRTC="webrtc"})(gg||(gg={}));var ns;(function(t){t.Binary="binary",t.BinaryUTF8="binary-utf8",t.JSON="json"})(ns||(ns={}));var rs;(function(t){t.Message="message",t.Disconnected="disconnected",t.Error="error",t.Close="close"})(rs||(rs={}));var $g;(function(t){t.Heartbeat="HEARTBEAT",t.Candidate="CANDIDATE",t.Offer="OFFER",t.Answer="ANSWER",t.Open="OPEN",t.Error="ERROR",t.IdTaken="ID-TAKEN",t.InvalidKey="INVALID-KEY",t.Leave="LEAVE",t.Expire="EXPIRE"})($g||($g={}));var sk={};sk=JSON.parse('{"name":"peerjs","version":"1.4.7","keywords":["peerjs","webrtc","p2p","rtc"],"description":"PeerJS client","homepage":"https://peerjs.com","bugs":{"url":"https://github.com/peers/peerjs/issues"},"repository":{"type":"git","url":"https://github.com/peers/peerjs"},"license":"MIT","contributors":["Michelle Bu <michelle@michellebu.com>","afrokick <devbyru@gmail.com>","ericz <really.ez@gmail.com>","Jairo <kidandcat@gmail.com>","Jonas Gloning <34194370+jonasgloning@users.noreply.github.com>","Jairo Caro-Accino Viciana <jairo@galax.be>","Carlos Caballero <carlos.caballero.gonzalez@gmail.com>","hc <hheennrryy@gmail.com>","Muhammad Asif <capripio@gmail.com>","PrashoonB <prashoonbhattacharjee@gmail.com>","Harsh Bardhan Mishra <47351025+HarshCasper@users.noreply.github.com>","akotynski <aleksanderkotbury@gmail.com>","lmb <i@lmb.io>","Jairooo <jairocaro@msn.com>","Moritz St\xFCckler <moritz.stueckler@gmail.com>","Simon <crydotsnakegithub@gmail.com>","Denis Lukov <denismassters@gmail.com>","Philipp Hancke <fippo@andyet.net>","Hans Oksendahl <hansoksendahl@gmail.com>","Jess <jessachandler@gmail.com>","khankuan <khankuan@gmail.com>","DUODVK <kurmanov.work@gmail.com>","XiZhao <kwang1imsa@gmail.com>","Matthias Lohr <matthias@lohr.me>","=frank tree <=frnktrb@googlemail.com>","Andre Eckardt <aeckardt@outlook.com>","Chris Cowan <agentme49@gmail.com>","Alex Chuev <alex@chuev.com>","alxnull <alxnull@e.mail.de>","Yemel Jardi <angel.jardi@gmail.com>","Ben Parnell <benjaminparnell.94@gmail.com>","Benny Lichtner <bennlich@gmail.com>","fresheneesz <bitetrudpublic@gmail.com>","bob.barstead@exaptive.com <bob.barstead@exaptive.com>","chandika <chandika@gmail.com>","emersion <contact@emersion.fr>","Christopher Van <cvan@users.noreply.github.com>","eddieherm <edhermoso@gmail.com>","Eduardo Pinho <enet4mikeenet@gmail.com>","Evandro Zanatta <ezanatta@tray.net.br>","Gardner Bickford <gardner@users.noreply.github.com>","Gian Luca <gianluca.cecchi@cynny.com>","PatrickJS <github@gdi2290.com>","jonnyf <github@jonathanfoss.co.uk>","Hizkia Felix <hizkifw@gmail.com>","Hristo Oskov <hristo.oskov@gmail.com>","Isaac Madwed <i.madwed@gmail.com>","Ilya Konanykhin <ilya.konanykhin@gmail.com>","jasonbarry <jasbarry@me.com>","Jonathan Burke <jonathan.burke.1311@googlemail.com>","Josh Hamit <josh.hamit@gmail.com>","Jordan Austin <jrax86@gmail.com>","Joel Wetzell <jwetzell@yahoo.com>","xizhao <kevin.wang@cloudera.com>","Alberto Torres <kungfoobar@gmail.com>","Jonathan Mayol <mayoljonathan@gmail.com>","Jefferson Felix <me@jsfelix.dev>","Rolf Erik Lekang <me@rolflekang.com>","Kevin Mai-Husan Chia <mhchia@users.noreply.github.com>","Pepijn de Vos <pepijndevos@gmail.com>","JooYoung <qkdlql@naver.com>","Tobias Speicher <rootcommander@gmail.com>","Steve Blaurock <sblaurock@gmail.com>","Kyrylo Shegeda <shegeda@ualberta.ca>","Diwank Singh Tomer <singh@diwank.name>","So\u0308ren Balko <Soeren.Balko@gmail.com>","Arpit Solanki <solankiarpit1997@gmail.com>","Yuki Ito <yuki@gnnk.net>","Artur Zayats <zag2art@gmail.com>"],"funding":{"type":"opencollective","url":"https://opencollective.com/peer"},"collective":{"type":"opencollective","url":"https://opencollective.com/peer"},"files":["dist/*"],"sideEffects":["lib/global.ts","lib/supports.ts"],"main":"dist/bundler.cjs","module":"dist/bundler.mjs","browser-minified":"dist/peerjs.min.js","browser-unminified":"dist/peerjs.js","types":"dist/types.d.ts","engines":{"node":">= 10"},"targets":{"types":{"source":"lib/exports.ts"},"main":{"source":"lib/exports.ts","sourceMap":{"inlineSources":true}},"module":{"source":"lib/exports.ts","includeNodeModules":["eventemitter3"],"sourceMap":{"inlineSources":true}},"browser-minified":{"context":"browser","outputFormat":"global","optimize":true,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"},"browser-unminified":{"context":"browser","outputFormat":"global","optimize":false,"engines":{"browsers":"cover 99%, not dead"},"source":"lib/global.ts"}},"scripts":{"contributors":"git-authors-cli --print=false && prettier --write package.json && git add package.json package-lock.json && git commit -m \\"chore(contributors): update and sort contributors list\\"","check":"tsc --noEmit","watch":"parcel watch","build":"rm -rf dist && parcel build","prepublishOnly":"npm run build","test":"mocha -r ts-node/register -r jsdom-global/register test/**/*.ts","format":"prettier --write .","semantic-release":"semantic-release"},"devDependencies":{"@parcel/config-default":"^2.5.0","@parcel/packager-ts":"^2.5.0","@parcel/transformer-typescript-tsc":"^2.5.0","@parcel/transformer-typescript-types":"^2.5.0","@semantic-release/changelog":"^6.0.1","@semantic-release/git":"^10.0.1","@types/chai":"^4.3.0","@types/mocha":"^9.1.0","@types/node":"^17.0.18","chai":"^4.3.6","git-authors-cli":"^1.0.40","jsdom":"^19.0.0","jsdom-global":"^3.0.2","mocha":"^9.2.0","mock-socket":"8.0.5","parcel":"^2.5.0","parcel-transformer-tsc-sourcemaps":"^1.0.2","prettier":"^2.6.2","semantic-release":"^19.0.2","standard":"^16.0.4","ts-node":"^10.5.0","typescript":"^4.5.5"},"dependencies":{"@swc/helpers":"^0.3.13","eventemitter3":"^4.0.7","peerjs-js-binarypack":"1.0.1","webrtc-adapter":"^7.7.1"}}');var VW=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),zW=function(t,A){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var g=e.call(t),I,i=[],o;try{for(;(A===void 0||A-- >0)&&!(I=g.next()).done;)i.push(I.value)}catch(C){o={error:C}}finally{try{I&&!I.done&&(e=g.return)&&e.call(g)}finally{if(o)throw o.error}}return i},ZW=function(t,A,e){if(e||arguments.length===2)for(var g=0,I=A.length,i;g<I;g++)(i||!(g in A))&&(i||(i=Array.prototype.slice.call(A,0,g)),i[g]=A[g]);return t.concat(i||Array.prototype.slice.call(A))},XW=function(t){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&t[A],g=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&g>=t.length&&(t=void 0),{value:t&&t[g++],done:!t}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},Uq=function(t){VW(A,t);function A(e,g,I,i,o,C){C===void 0&&(C=5e3);var s=t.call(this)||this;s.pingInterval=C,s._disconnected=!0,s._messagesQueue=[];var a=e?"wss://":"ws://";return s._baseUrl=a+g+":"+I+i+"peerjs?key="+o,s}return A.prototype.start=function(e,g){var I=this;this._id=e;var i="".concat(this._baseUrl,"&id=").concat(e,"&token=").concat(g);this._socket||!this._disconnected||(this._socket=new WebSocket(i+"&version="+sk.version),this._disconnected=!1,this._socket.onmessage=function(o){var C;try{C=JSON.parse(o.data),te.default.log("Server message received:",C)}catch{te.default.log("Invalid server message",o.data);return}I.emit(rs.Message,C)},this._socket.onclose=function(o){I._disconnected||(te.default.log("Socket closed.",o),I._cleanup(),I._disconnected=!0,I.emit(rs.Disconnected))},this._socket.onopen=function(){I._disconnected||(I._sendQueuedMessages(),te.default.log("Socket open"),I._scheduleHeartbeat())})},A.prototype._scheduleHeartbeat=function(){var e=this;this._wsPingTimer=setTimeout(function(){e._sendHeartbeat()},this.pingInterval)},A.prototype._sendHeartbeat=function(){if(!this._wsOpen()){te.default.log("Cannot send heartbeat, because socket closed");return}var e=JSON.stringify({type:$g.Heartbeat});this._socket.send(e),this._scheduleHeartbeat()},A.prototype._wsOpen=function(){return!!this._socket&&this._socket.readyState===1},A.prototype._sendQueuedMessages=function(){var e,g,I=ZW([],zW(this._messagesQueue),!1);this._messagesQueue=[];try{for(var i=XW(I),o=i.next();!o.done;o=i.next()){var C=o.value;this.send(C)}}catch(s){e={error:s}}finally{try{o&&!o.done&&(g=i.return)&&g.call(i)}finally{if(e)throw e.error}}},A.prototype.send=function(e){if(!this._disconnected){if(!this._id){this._messagesQueue.push(e);return}if(!e.type){this.emit(rs.Error,"Invalid message");return}if(this._wsOpen()){var g=JSON.stringify(e);this._socket.send(g)}}},A.prototype.close=function(){this._disconnected||(this._cleanup(),this._disconnected=!0)},A.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)},A}(Jh.EventEmitter),ak={};tC(ak,"MediaConnection",()=>Kq,t=>Kq=t);var nk={};tC(nk,"Negotiator",()=>Fq,t=>Fq=t);var fu=function(){return fu=Object.assign||function(t){for(var A,e=1,g=arguments.length;e<g;e++){A=arguments[e];for(var I in A)Object.prototype.hasOwnProperty.call(A,I)&&(t[I]=A[I])}return t},fu.apply(this,arguments)},ku=function(t,A,e,g){function I(i){return i instanceof e?i:new e(function(o){o(i)})}return new(e||(e=Promise))(function(i,o){function C(n){try{a(g.next(n))}catch(B){o(B)}}function s(n){try{a(g.throw(n))}catch(B){o(B)}}function a(n){n.done?i(n.value):I(n.value).then(C,s)}a((g=g.apply(t,A||[])).next())})},Gu=function(t,A){var e={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},g,I,i,o;return o={next:C(0),throw:C(1),return:C(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function C(a){return function(n){return s([a,n])}}function s(a){if(g)throw new TypeError("Generator is already executing.");for(;e;)try{if(g=1,I&&(i=a[0]&2?I.return:a[0]?I.throw||((i=I.return)&&i.call(I),0):I.next)&&!(i=i.call(I,a[1])).done)return i;switch(I=0,i&&(a=[a[0]&2,i.value]),a[0]){case 0:case 1:i=a;break;case 4:return e.label++,{value:a[1],done:!1};case 5:e.label++,I=a[1],a=[0];continue;case 7:a=e.ops.pop(),e.trys.pop();continue;default:if(i=e.trys,!(i=i.length>0&&i[i.length-1])&&(a[0]===6||a[0]===2)){e=0;continue}if(a[0]===3&&(!i||a[1]>i[0]&&a[1]<i[3])){e.label=a[1];break}if(a[0]===6&&e.label<i[1]){e.label=i[1],i=a;break}if(i&&e.label<i[2]){e.label=i[2],e.ops.push(a);break}i[2]&&e.ops.pop(),e.trys.pop();continue}a=A.call(t,e)}catch(n){a=[6,n],I=0}finally{g=i=0}if(a[0]&5)throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},Fq=function(){function t(A){this.connection=A}return t.prototype.startConnection=function(A){var e=this._startPeerConnection();if(this.connection.peerConnection=e,this.connection.type===mo.Media&&A._stream&&this._addTracksToConnection(A._stream,e),A.originator){if(this.connection.type===mo.Data){var g=this.connection,I={ordered:!!A.reliable},i=e.createDataChannel(g.label,I);g.initialize(i)}this._makeOffer()}else this.handleSDP("OFFER",A.sdp)},t.prototype._startPeerConnection=function(){te.default.log("Creating RTCPeerConnection.");var A=new RTCPeerConnection(this.connection.provider.options.config);return this._setupListeners(A),A},t.prototype._setupListeners=function(A){var e=this,g=this.connection.peer,I=this.connection.connectionId,i=this.connection.type,o=this.connection.provider;te.default.log("Listening for ICE candidates."),A.onicecandidate=function(C){!C.candidate||!C.candidate.candidate||(te.default.log("Received ICE candidates for ".concat(g,":"),C.candidate),o.socket.send({type:$g.Candidate,payload:{candidate:C.candidate,type:i,connectionId:I},dst:g}))},A.oniceconnectionstatechange=function(){switch(A.iceConnectionState){case"failed":te.default.log("iceConnectionState is failed, closing connections to "+g),e.connection.emit("error",new Error("Negotiation of connection to "+g+" failed.")),e.connection.close();break;case"closed":te.default.log("iceConnectionState is closed, closing connections to "+g),e.connection.emit("error",new Error("Connection to "+g+" closed.")),e.connection.close();break;case"disconnected":te.default.log("iceConnectionState changed to disconnected on the connection with "+g);break;case"completed":A.onicecandidate=nt.noop;break}e.connection.emit("iceStateChanged",A.iceConnectionState)},te.default.log("Listening for data channel"),A.ondatachannel=function(C){te.default.log("Received data channel");var s=C.channel,a=o.getConnection(g,I);a.initialize(s)},te.default.log("Listening for remote stream"),A.ontrack=function(C){te.default.log("Received remote stream");var s=C.streams[0],a=o.getConnection(g,I);if(a.type===mo.Media){var n=a;e._addStreamToMediaConnection(s,n)}}},t.prototype.cleanup=function(){te.default.log("Cleaning up PeerConnection to "+this.connection.peer);var A=this.connection.peerConnection;if(A){this.connection.peerConnection=null,A.onicecandidate=A.oniceconnectionstatechange=A.ondatachannel=A.ontrack=function(){};var e=A.signalingState!=="closed",g=!1;if(this.connection.type===mo.Data){var I=this.connection,i=I.dataChannel;i&&(g=!!i.readyState&&i.readyState!=="closed")}(e||g)&&A.close()}},t.prototype._makeOffer=function(){return ku(this,void 0,Promise,function(){var A,e,g,I,i,o,C;return Gu(this,function(s){switch(s.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,s.label=1;case 1:return s.trys.push([1,7,,8]),[4,A.createOffer(this.connection.options.constraints)];case 2:g=s.sent(),te.default.log("Created offer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(g.sdp=this.connection.options.sdpTransform(g.sdp)||g.sdp),s.label=3;case 3:return s.trys.push([3,5,,6]),[4,A.setLocalDescription(g)];case 4:return s.sent(),te.default.log("Set localDescription:",g,"for:".concat(this.connection.peer)),I={sdp:g,type:this.connection.type,connectionId:this.connection.connectionId,metadata:this.connection.metadata,browser:nt.browser},this.connection.type===mo.Data&&(i=this.connection,I=fu(fu({},I),{label:i.label,reliable:i.reliable,serialization:i.serialization})),e.socket.send({type:$g.Offer,payload:I,dst:this.connection.peer}),[3,6];case 5:return o=s.sent(),o!="OperationError: Failed to set local offer sdp: Called in wrong state: kHaveRemoteOffer"&&(e.emitError(gg.WebRTC,o),te.default.log("Failed to setLocalDescription, ",o)),[3,6];case 6:return[3,8];case 7:return C=s.sent(),e.emitError(gg.WebRTC,C),te.default.log("Failed to createOffer, ",C),[3,8];case 8:return[2]}})})},t.prototype._makeAnswer=function(){return ku(this,void 0,Promise,function(){var A,e,g,I,i;return Gu(this,function(o){switch(o.label){case 0:A=this.connection.peerConnection,e=this.connection.provider,o.label=1;case 1:return o.trys.push([1,7,,8]),[4,A.createAnswer()];case 2:g=o.sent(),te.default.log("Created answer."),this.connection.options.sdpTransform&&typeof this.connection.options.sdpTransform=="function"&&(g.sdp=this.connection.options.sdpTransform(g.sdp)||g.sdp),o.label=3;case 3:return o.trys.push([3,5,,6]),[4,A.setLocalDescription(g)];case 4:return o.sent(),te.default.log("Set localDescription:",g,"for:".concat(this.connection.peer)),e.socket.send({type:$g.Answer,payload:{sdp:g,type:this.connection.type,connectionId:this.connection.connectionId,browser:nt.browser},dst:this.connection.peer}),[3,6];case 5:return I=o.sent(),e.emitError(gg.WebRTC,I),te.default.log("Failed to setLocalDescription, ",I),[3,6];case 6:return[3,8];case 7:return i=o.sent(),e.emitError(gg.WebRTC,i),te.default.log("Failed to create answer, ",i),[3,8];case 8:return[2]}})})},t.prototype.handleSDP=function(A,e){return ku(this,void 0,Promise,function(){var g,I,i,o;return Gu(this,function(C){switch(C.label){case 0:e=new RTCSessionDescription(e),g=this.connection.peerConnection,I=this.connection.provider,te.default.log("Setting remote description",e),i=this,C.label=1;case 1:return C.trys.push([1,5,,6]),[4,g.setRemoteDescription(e)];case 2:return C.sent(),te.default.log("Set remoteDescription:".concat(A," for:").concat(this.connection.peer)),A!=="OFFER"?[3,4]:[4,i._makeAnswer()];case 3:C.sent(),C.label=4;case 4:return[3,6];case 5:return o=C.sent(),I.emitError(gg.WebRTC,o),te.default.log("Failed to setRemoteDescription, ",o),[3,6];case 6:return[2]}})})},t.prototype.handleCandidate=function(A){return ku(this,void 0,Promise,function(){var e,g,I,i,o,C;return Gu(this,function(s){switch(s.label){case 0:te.default.log("handleCandidate:",A),e=A.candidate,g=A.sdpMLineIndex,I=A.sdpMid,i=this.connection.peerConnection,o=this.connection.provider,s.label=1;case 1:return s.trys.push([1,3,,4]),[4,i.addIceCandidate(new RTCIceCandidate({sdpMid:I,sdpMLineIndex:g,candidate:e}))];case 2:return s.sent(),te.default.log("Added ICE candidate for:".concat(this.connection.peer)),[3,4];case 3:return C=s.sent(),o.emitError(gg.WebRTC,C),te.default.log("Failed to handleCandidate, ",C),[3,4];case 4:return[2]}})})},t.prototype._addTracksToConnection=function(A,e){if(te.default.log("add tracks from stream ".concat(A.id," to peer connection")),!e.addTrack)return te.default.error("Your browser does't support RTCPeerConnection#addTrack. Ignored.");A.getTracks().forEach(function(g){e.addTrack(g,A)})},t.prototype._addStreamToMediaConnection=function(A,e){te.default.log("add stream ".concat(A.id," to media connection ").concat(e.connectionId)),e.addStream(A)},t}(),rk={};tC(rk,"BaseConnection",()=>Nq,t=>Nq=t);var $W=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),Nq=function(t){$W(A,t);function A(e,g,I){var i=t.call(this)||this;return i.peer=e,i.provider=g,i.options=I,i._open=!1,i.metadata=I.metadata,i}return Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),A}(Jh.EventEmitter),AV=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),mu=function(){return mu=Object.assign||function(t){for(var A,e=1,g=arguments.length;e<g;e++){A=arguments[e];for(var I in A)Object.prototype.hasOwnProperty.call(A,I)&&(t[I]=A[I])}return t},mu.apply(this,arguments)},eV=function(t){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&t[A],g=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&g>=t.length&&(t=void 0),{value:t&&t[g++],done:!t}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},Kq=function(t){AV(A,t);function A(e,g,I){var i=t.call(this,e,g,I)||this;return i._localStream=i.options._stream,i.connectionId=i.options.connectionId||A.ID_PREFIX+nt.randomToken(),i._negotiator=new nk.Negotiator(i),i._localStream&&i._negotiator.startConnection({_stream:i._localStream,originator:!0}),i}return Object.defineProperty(A.prototype,"type",{get:function(){return mo.Media},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"localStream",{get:function(){return this._localStream},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"remoteStream",{get:function(){return this._remoteStream},enumerable:!1,configurable:!0}),A.prototype.addStream=function(e){te.default.log("Receiving stream",e),this._remoteStream=e,t.prototype.emit.call(this,"stream",e)},A.prototype.handleMessage=function(e){var g=e.type,I=e.payload;switch(e.type){case $g.Answer:this._negotiator.handleSDP(g,I.sdp),this._open=!0;break;case $g.Candidate:this._negotiator.handleCandidate(I.candidate);break;default:te.default.warn("Unrecognized message type:".concat(g," from peer:").concat(this.peer));break}},A.prototype.answer=function(e,g){var I,i;if(g===void 0&&(g={}),this._localStream){te.default.warn("Local stream already exists on this MediaConnection. Are you answering a call twice?");return}this._localStream=e,g&&g.sdpTransform&&(this.options.sdpTransform=g.sdpTransform),this._negotiator.startConnection(mu(mu({},this.options._payload),{_stream:e}));var o=this.provider._getMessages(this.connectionId);try{for(var C=eV(o),s=C.next();!s.done;s=C.next()){var a=s.value;this.handleMessage(a)}}catch(n){I={error:n}}finally{try{s&&!s.done&&(i=C.return)&&i.call(C)}finally{if(I)throw I.error}}this._open=!0},A.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,t.prototype.emit.call(this,"close"))},A.ID_PREFIX="mc_",A}(rk.BaseConnection),Bk={};tC(Bk,"DataConnection",()=>bq,t=>bq=t);var Jq={};tC(Jq,"EncodingQueue",()=>qq,t=>qq=t);var tV=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),qq=function(t){tV(A,t);function A(){var e=t.call(this)||this;return e.fileReader=new FileReader,e._queue=[],e._processing=!1,e.fileReader.onload=function(g){e._processing=!1,g.target&&e.emit("done",g.target.result),e.doNextTask()},e.fileReader.onerror=function(g){te.default.error("EncodingQueue error:",g),e._processing=!1,e.destroy(),e.emit("error",g)},e}return Object.defineProperty(A.prototype,"queue",{get:function(){return this._queue},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"size",{get:function(){return this.queue.length},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"processing",{get:function(){return this._processing},enumerable:!1,configurable:!0}),A.prototype.enque=function(e){this.queue.push(e),!this.processing&&this.doNextTask()},A.prototype.destroy=function(){this.fileReader.abort(),this._queue=[]},A.prototype.doNextTask=function(){this.size!==0&&(this.processing||(this._processing=!0,this.fileReader.readAsArrayBuffer(this.queue.shift())))},A}(Jh.EventEmitter),gV=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),IV=function(t){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&t[A],g=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&g>=t.length&&(t=void 0),{value:t&&t[g++],done:!t}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},bq=function(t){gV(A,t);function A(e,g,I){var i=t.call(this,e,g,I)||this;return i.stringify=JSON.stringify,i.parse=JSON.parse,i._buffer=[],i._bufferSize=0,i._buffering=!1,i._chunkedData={},i._encodingQueue=new Jq.EncodingQueue,i.connectionId=i.options.connectionId||A.ID_PREFIX+nt.randomToken(),i.label=i.options.label||i.connectionId,i.serialization=i.options.serialization||ns.Binary,i.reliable=!!i.options.reliable,i._encodingQueue.on("done",function(o){i._bufferedSend(o)}),i._encodingQueue.on("error",function(){te.default.error("DC#".concat(i.connectionId,": Error occured in encoding from blob to arraybuffer, close DC")),i.close()}),i._negotiator=new nk.Negotiator(i),i._negotiator.startConnection(i.options._payload||{originator:!0}),i}return Object.defineProperty(A.prototype,"type",{get:function(){return mo.Data},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"dataChannel",{get:function(){return this._dc},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"bufferSize",{get:function(){return this._bufferSize},enumerable:!1,configurable:!0}),A.prototype.initialize=function(e){this._dc=e,this._configureDataChannel()},A.prototype._configureDataChannel=function(){var e=this;(!nt.supports.binaryBlob||nt.supports.reliable)&&(this.dataChannel.binaryType="arraybuffer"),this.dataChannel.onopen=function(){te.default.log("DC#".concat(e.connectionId," dc connection success")),e._open=!0,e.emit("open")},this.dataChannel.onmessage=function(g){te.default.log("DC#".concat(e.connectionId," dc onmessage:"),g.data),e._handleDataMessage(g)},this.dataChannel.onclose=function(){te.default.log("DC#".concat(e.connectionId," dc closed for:"),e.peer),e.close()}},A.prototype._handleDataMessage=function(e){var g=this,I=e.data,i=I.constructor,o=this.serialization===ns.Binary||this.serialization===ns.BinaryUTF8,C=I;if(o){if(i===Blob){nt.blobToArrayBuffer(I,function(a){var n=nt.unpack(a);g.emit("data",n)});return}else if(i===ArrayBuffer)C=nt.unpack(I);else if(i===String){var s=nt.binaryStringToArrayBuffer(I);C=nt.unpack(s)}}else this.serialization===ns.JSON&&(C=this.parse(I));if(C.__peerData){this._handleChunk(C);return}t.prototype.emit.call(this,"data",C)},A.prototype._handleChunk=function(e){var g=e.__peerData,I=this._chunkedData[g]||{data:[],count:0,total:e.total};if(I.data[e.n]=e.data,I.count++,this._chunkedData[g]=I,I.total===I.count){delete this._chunkedData[g];var i=new Blob(I.data);this._handleDataMessage({data:i})}},A.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,t.prototype.emit.call(this,"close"))},A.prototype.send=function(e,g){if(!this.open){t.prototype.emit.call(this,"error",new Error("Connection is not open. You should listen for the `open` event before sending messages."));return}if(this.serialization===ns.JSON)this._bufferedSend(this.stringify(e));else if(this.serialization===ns.Binary||this.serialization===ns.BinaryUTF8){var I=nt.pack(e);if(!g&&I.size>nt.chunkedMTU){this._sendChunks(I);return}nt.supports.binaryBlob?this._bufferedSend(I):this._encodingQueue.enque(I)}else this._bufferedSend(e)},A.prototype._bufferedSend=function(e){(this._buffering||!this._trySend(e))&&(this._buffer.push(e),this._bufferSize=this._buffer.length)},A.prototype._trySend=function(e){var g=this;if(!this.open)return!1;if(this.dataChannel.bufferedAmount>A.MAX_BUFFERED_AMOUNT)return this._buffering=!0,setTimeout(function(){g._buffering=!1,g._tryBuffer()},50),!1;try{this.dataChannel.send(e)}catch(I){return te.default.error("DC#:".concat(this.connectionId," Error when sending:"),I),this._buffering=!0,this.close(),!1}return!0},A.prototype._tryBuffer=function(){if(this.open&&this._buffer.length!==0){var e=this._buffer[0];this._trySend(e)&&(this._buffer.shift(),this._bufferSize=this._buffer.length,this._tryBuffer())}},A.prototype._sendChunks=function(e){var g,I,i=nt.chunk(e);te.default.log("DC#".concat(this.connectionId," Try to send ").concat(i.length," chunks..."));try{for(var o=IV(i),C=o.next();!C.done;C=o.next()){var s=C.value;this.send(s,!0)}}catch(a){g={error:a}}finally{try{C&&!C.done&&(I=o.return)&&I.call(o)}finally{if(g)throw g.error}}},A.prototype.handleMessage=function(e){var g=e.payload;switch(e.type){case $g.Answer:this._negotiator.handleSDP(e.type,g.sdp);break;case $g.Candidate:this._negotiator.handleCandidate(g.candidate);break;default:te.default.warn("Unrecognized message type:",e.type,"from peer:",this.peer);break}},A.ID_PREFIX="dc_",A.MAX_BUFFERED_AMOUNT=8388608,A}(rk.BaseConnection),vq={};tC(vq,"API",()=>Yq,t=>Yq=t);var Lq=function(t,A,e,g){function I(i){return i instanceof e?i:new e(function(o){o(i)})}return new(e||(e=Promise))(function(i,o){function C(n){try{a(g.next(n))}catch(B){o(B)}}function s(n){try{a(g.throw(n))}catch(B){o(B)}}function a(n){n.done?i(n.value):I(n.value).then(C,s)}a((g=g.apply(t,A||[])).next())})},xq=function(t,A){var e={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},g,I,i,o;return o={next:C(0),throw:C(1),return:C(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function C(a){return function(n){return s([a,n])}}function s(a){if(g)throw new TypeError("Generator is already executing.");for(;e;)try{if(g=1,I&&(i=a[0]&2?I.return:a[0]?I.throw||((i=I.return)&&i.call(I),0):I.next)&&!(i=i.call(I,a[1])).done)return i;switch(I=0,i&&(a=[a[0]&2,i.value]),a[0]){case 0:case 1:i=a;break;case 4:return e.label++,{value:a[1],done:!1};case 5:e.label++,I=a[1],a=[0];continue;case 7:a=e.ops.pop(),e.trys.pop();continue;default:if(i=e.trys,!(i=i.length>0&&i[i.length-1])&&(a[0]===6||a[0]===2)){e=0;continue}if(a[0]===3&&(!i||a[1]>i[0]&&a[1]<i[3])){e.label=a[1];break}if(a[0]===6&&e.label<i[1]){e.label=i[1],i=a;break}if(i&&e.label<i[2]){e.label=i[2],e.ops.push(a);break}i[2]&&e.ops.pop(),e.trys.pop();continue}a=A.call(t,e)}catch(n){a=[6,n],I=0}finally{g=i=0}if(a[0]&5)throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}},Yq=function(){function t(A){this._options=A}return t.prototype._buildRequest=function(A){var e=this._options.secure?"https":"http",g=this._options,I=g.host,i=g.port,o=g.path,C=g.key,s=new URL("".concat(e,"://").concat(I,":").concat(i).concat(o).concat(C,"/").concat(A));return s.searchParams.set("ts","".concat(Date.now()).concat(Math.random())),s.searchParams.set("version",sk.version),fetch(s.href,{referrerPolicy:this._options.referrerPolicy})},t.prototype.retrieveId=function(){return Lq(this,void 0,Promise,function(){var A,e,g;return xq(this,function(I){switch(I.label){case 0:return I.trys.push([0,2,,3]),[4,this._buildRequest("id")];case 1:if(A=I.sent(),A.status!==200)throw new Error("Error. Status:".concat(A.status));return[2,A.text()];case 2:throw e=I.sent(),te.default.error("Error retrieving ID",e),g="",this._options.path==="/"&&this._options.host!==nt.CLOUD_HOST&&(g=" 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."+g);case 3:return[2]}})})},t.prototype.listAllPeers=function(){return Lq(this,void 0,Promise,function(){var A,e,g;return xq(this,function(I){switch(I.label){case 0:return I.trys.push([0,2,,3]),[4,this._buildRequest("peers")];case 1:if(A=I.sent(),A.status!==200)throw A.status===401?(e="",this._options.host===nt.CLOUD_HOST?e="It looks like you're using the cloud server. You can email team@peerjs.com to enable peer listing for your API key.":e="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. "+e)):new Error("Error. Status:".concat(A.status));return[2,A.json()];case 2:throw g=I.sent(),te.default.error("Error retrieving list peers",g),new Error("Could not get list peers from the server."+g);case 3:return[2]}})})},t}(),iV=function(){var t=function(A,e){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,I){g.__proto__=I}||function(g,I){for(var i in I)Object.prototype.hasOwnProperty.call(I,i)&&(g[i]=I[i])},t(A,e)};return function(A,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");t(A,e);function g(){this.constructor=A}A.prototype=e===null?Object.create(e):(g.prototype=e.prototype,new g)}}(),bh=function(){return bh=Object.assign||function(t){for(var A,e=1,g=arguments.length;e<g;e++){A=arguments[e];for(var I in A)Object.prototype.hasOwnProperty.call(A,I)&&(t[I]=A[I])}return t},bh.apply(this,arguments)},vh=function(t){var A=typeof Symbol=="function"&&Symbol.iterator,e=A&&t[A],g=0;if(e)return e.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&g>=t.length&&(t=void 0),{value:t&&t[g++],done:!t}}};throw new TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")},oV=function(t,A){var e=typeof Symbol=="function"&&t[Symbol.iterator];if(!e)return t;var g=e.call(t),I,i=[],o;try{for(;(A===void 0||A-- >0)&&!(I=g.next()).done;)i.push(I.value)}catch(C){o={error:C}}finally{try{I&&!I.done&&(e=g.return)&&e.call(g)}finally{if(o)throw o.error}}return i},Hq=function(t){iV(A,t);function A(e,g){var I=t.call(this)||this;I._id=null,I._lastServerId=null,I._destroyed=!1,I._disconnected=!1,I._open=!1,I._connections=new Map,I._lostMessages=new Map;var i;return e&&e.constructor==Object?g=e:e&&(i=e.toString()),g=bh({debug:0,host:nt.CLOUD_HOST,port:nt.CLOUD_PORT,path:"/",key:A.DEFAULT_KEY,token:nt.randomToken(),config:nt.defaultConfig,referrerPolicy:"strict-origin-when-cross-origin"},g),I._options=g,I._options.host==="/"&&(I._options.host=window.location.hostname),I._options.path&&(I._options.path[0]!=="/"&&(I._options.path="/"+I._options.path),I._options.path[I._options.path.length-1]!=="/"&&(I._options.path+="/")),I._options.secure===void 0&&I._options.host!==nt.CLOUD_HOST?I._options.secure=nt.isSecure():I._options.host==nt.CLOUD_HOST&&(I._options.secure=!0),I._options.logFunction&&te.default.setLogFunction(I._options.logFunction),te.default.logLevel=I._options.debug||0,I._api=new vq.API(g),I._socket=I._createServerConnection(),!nt.supports.audioVideo&&!nt.supports.data?(I._delayedAbort(gg.BrowserIncompatible,"The current browser does not support WebRTC"),I):i&&!nt.validateId(i)?(I._delayedAbort(gg.InvalidID,'ID "'.concat(i,'" is invalid')),I):(i?I._initialize(i):I._api.retrieveId().then(function(o){return I._initialize(o)}).catch(function(o){return I._abort(gg.ServerError,o)}),I)}return Object.defineProperty(A.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"options",{get:function(){return this._options},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"open",{get:function(){return this._open},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"socket",{get:function(){return this._socket},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"connections",{get:function(){var e,g,I=Object.create(null);try{for(var i=vh(this._connections),o=i.next();!o.done;o=i.next()){var C=oV(o.value,2),s=C[0],a=C[1];I[s]=a}}catch(n){e={error:n}}finally{try{o&&!o.done&&(g=i.return)&&g.call(i)}finally{if(e)throw e.error}}return I},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"destroyed",{get:function(){return this._destroyed},enumerable:!1,configurable:!0}),Object.defineProperty(A.prototype,"disconnected",{get:function(){return this._disconnected},enumerable:!1,configurable:!0}),A.prototype._createServerConnection=function(){var e=this,g=new Rq.Socket(this._options.secure,this._options.host,this._options.port,this._options.path,this._options.key,this._options.pingInterval);return g.on(rs.Message,function(I){e._handleMessage(I)}),g.on(rs.Error,function(I){e._abort(gg.SocketError,I)}),g.on(rs.Disconnected,function(){e.disconnected||(e.emitError(gg.Network,"Lost connection to server."),e.disconnect())}),g.on(rs.Close,function(){e.disconnected||e._abort(gg.SocketClosed,"Underlying socket is already closed.")}),g},A.prototype._initialize=function(e){this._id=e,this.socket.start(e,this._options.token)},A.prototype._handleMessage=function(e){var g,I,i=e.type,o=e.payload,C=e.src;switch(i){case $g.Open:this._lastServerId=this.id,this._open=!0,this.emit("open",this.id);break;case $g.Error:this._abort(gg.ServerError,o.msg);break;case $g.IdTaken:this._abort(gg.UnavailableID,'ID "'.concat(this.id,'" is taken'));break;case $g.InvalidKey:this._abort(gg.InvalidKey,'API KEY "'.concat(this._options.key,'" is invalid'));break;case $g.Leave:te.default.log("Received leave message from ".concat(C)),this._cleanupPeer(C),this._connections.delete(C);break;case $g.Expire:this.emitError(gg.PeerUnavailable,"Could not connect to peer ".concat(C));break;case $g.Offer:var h=o.connectionId,c=this.getConnection(C,h);if(c&&(c.close(),te.default.warn("Offer received for existing Connection ID:".concat(h))),o.type===mo.Media){var s=new ak.MediaConnection(C,this,{connectionId:h,_payload:o,metadata:o.metadata});c=s,this._addConnection(C,c),this.emit("call",s)}else if(o.type===mo.Data){var a=new Bk.DataConnection(C,this,{connectionId:h,_payload:o,metadata:o.metadata,label:o.label,serialization:o.serialization,reliable:o.reliable});c=a,this._addConnection(C,c),this.emit("connection",a)}else{te.default.warn("Received malformed connection type:".concat(o.type));return}var n=this._getMessages(h);try{for(var B=vh(n),Q=B.next();!Q.done;Q=B.next()){var E=Q.value;c.handleMessage(E)}}catch(l){g={error:l}}finally{try{Q&&!Q.done&&(I=B.return)&&I.call(B)}finally{if(g)throw g.error}}break;default:if(!o){te.default.warn("You received a malformed message from ".concat(C," of type ").concat(i));return}var h=o.connectionId,c=this.getConnection(C,h);c&&c.peerConnection?c.handleMessage(e):h?this._storeMessage(h,e):te.default.warn("You received an unrecognized message:",e);break}},A.prototype._storeMessage=function(e,g){this._lostMessages.has(e)||this._lostMessages.set(e,[]),this._lostMessages.get(e).push(g)},A.prototype._getMessages=function(e){var g=this._lostMessages.get(e);return g?(this._lostMessages.delete(e),g):[]},A.prototype.connect=function(e,g){if(g===void 0&&(g={}),this.disconnected){te.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."),this.emitError(gg.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}var I=new Bk.DataConnection(e,this,g);return this._addConnection(e,I),I},A.prototype.call=function(e,g,I){if(I===void 0&&(I={}),this.disconnected){te.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."),this.emitError(gg.Disconnected,"Cannot connect to new Peer after disconnecting from server.");return}if(!g){te.default.error("To call a peer, you must provide a stream from your browser's `getUserMedia`.");return}var i=new ak.MediaConnection(e,this,bh(bh({},I),{_stream:g}));return this._addConnection(e,i),i},A.prototype._addConnection=function(e,g){te.default.log("add connection ".concat(g.type,":").concat(g.connectionId," to peerId:").concat(e)),this._connections.has(e)||this._connections.set(e,[]),this._connections.get(e).push(g)},A.prototype._removeConnection=function(e){var g=this._connections.get(e.peer);if(g){var I=g.indexOf(e);I!==-1&&g.splice(I,1)}this._lostMessages.delete(e.connectionId)},A.prototype.getConnection=function(e,g){var I,i,o=this._connections.get(e);if(!o)return null;try{for(var C=vh(o),s=C.next();!s.done;s=C.next()){var a=s.value;if(a.connectionId===g)return a}}catch(n){I={error:n}}finally{try{s&&!s.done&&(i=C.return)&&i.call(C)}finally{if(I)throw I.error}}return null},A.prototype._delayedAbort=function(e,g){var I=this;setTimeout(function(){I._abort(e,g)},0)},A.prototype._abort=function(e,g){te.default.error("Aborting!"),this.emitError(e,g),this._lastServerId?this.disconnect():this.destroy()},A.prototype.emitError=function(e,g){te.default.error("Error:",g);var I;typeof g=="string"?I=new Error(g):I=g,I.type=e,this.emit("error",I)},A.prototype.destroy=function(){this.destroyed||(te.default.log("Destroy peer with ID:".concat(this.id)),this.disconnect(),this._cleanup(),this._destroyed=!0,this.emit("close"))},A.prototype._cleanup=function(){var e,g;try{for(var I=vh(this._connections.keys()),i=I.next();!i.done;i=I.next()){var o=i.value;this._cleanupPeer(o),this._connections.delete(o)}}catch(C){e={error:C}}finally{try{i&&!i.done&&(g=I.return)&&g.call(I)}finally{if(e)throw e.error}}this.socket.removeAllListeners()},A.prototype._cleanupPeer=function(e){var g,I,i=this._connections.get(e);if(i)try{for(var o=vh(i),C=o.next();!C.done;C=o.next()){var s=C.value;s.close()}}catch(a){g={error:a}}finally{try{C&&!C.done&&(I=o.return)&&I.call(o)}finally{if(g)throw g.error}}},A.prototype.disconnect=function(){if(!this.disconnected){var e=this.id;te.default.log("Disconnect peer with ID:".concat(e)),this._disconnected=!0,this._open=!1,this.socket.close(),this._lastServerId=e,this._id=null,this.emit("disconnected",e)}},A.prototype.reconnect=function(){if(this.disconnected&&!this.destroyed)te.default.log("Attempting reconnection to server with ID ".concat(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)te.default.error("In a hurry? We're still trying to make the initial connection!");else throw new Error("Peer ".concat(this.id," cannot reconnect because it is not disconnected from the server!"))}},A.prototype.listAllPeers=function(e){var g=this;e===void 0&&(e=function(I){}),this._api.listAllPeers().then(function(I){return e(I)}).catch(function(I){return g._abort(gg.ServerError,I)})},A.DEFAULT_KEY="peerjs",A}(Jh.EventEmitter),Mu=Gq.Peer;class CV{constructor(){r(this,"_host"),r(this,"_client"),r(this,"_clientData"),this.onEnable()}get isHost(){return this._host!==void 0}onEnable(){const A="HOST-5980e65c-8438-453e-8b35-f13c736dcd81";this.trySetupHost(A)}trySetupHost(A){let e=new Mu(A);e.on("error",g=>{console.error(g),this._host=void 0,this.trySetupClient(A)}),e.on("open",g=>{this._host=new aV(e)})}trySetupClient(A){this._client=new Mu,this._client.on("error",e=>{console.error("Client error",e)}),this._client.on("open",e=>{console.log("client connected",e),this._clientData=this._client.connect(A,{metadata:{id:e}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",g=>{console.log("<<",g)})})}}class sV{constructor(A){r(this,"_peer"),this._peer=A}}class aV extends sV{constructor(A){var e;super(A),r(this,"_connections",[]),console.log("I AM THE HOST"),(e=this._peer)==null||e.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}get isHost(){return!0}onConnection(A){console.log("host connection",A),A.on("open",()=>{this._connections.push(A),this.broadcastConnection(A)})}broadcastConnection(A){const e=this._connections.map(g=>{var I;return(I=g.metadata)==null?void 0:I.id}).filter(g=>g!==void 0);this.broadcast({type:"connection-list",connections:e})}broadcast(A){if(A!=null){console.log(">>",A);for(const e in this._peer.connections){const g=this._peer.connections[e];if(g)if(Array.isArray(g))for(const I of g)I&&I.send(A);else console.warn(g)}}}}var XI=(t=>(t[t.OnConnection=0]="OnConnection",t[t.OnRoomJoin=1]="OnRoomJoin",t[t.Queued=2]="Queued",t[t.Immediate=3]="Immediate",t))(XI||{});const Tq="https://urls.needle.tools/default-networking-backend/index";let Ra="wss://needle-tiny-starter.glitch.me/socket";const NI=!!aA("debugnet"),Lh=!!(NI||aA("debugowner"));var _q=(t=>(t.ConnectionInfo="connection-start-info",t))(_q||{}),Pt=(t=>(t.Join="join-room",t.Leave="leave-room",t.JoinedRoom="joined-room",t.LeftRoom="left-room",t.UserJoinedRoom="user-joined-room",t.UserLeftRoom="user-left-room",t))(Pt||{});class nV{constructor(){r(this,"room"),r(this,"viewId"),r(this,"allowEditing"),r(this,"inRoom")}}class rV{constructor(){r(this,"room")}}class BV{constructor(){r(this,"userId")}}var Oq=(t=>(t.RequestHasOwner="request-has-owner",t.ResponseHasOwner="response-has-owner",t.RequestIsOwner="request-is-owner",t.ResponseIsOwner="response-is-owner",t.RequestOwnership="request-ownership",t.GainedOwnership="gained-ownership",t.RemoveOwnership="remove-ownership",t.LostOwnership="lost-ownership",t.GainedOwnershipBroadcast="gained-ownership-broadcast",t.LostOwnershipBroadcast="lost-ownership-broadcast",t))(Oq||{});class Ru{constructor(A,e){r(this,"guid"),r(this,"connection"),r(this,"_hasOwnership",!1),r(this,"_isOwned"),r(this,"_gainSubscription"),r(this,"_lostSubscription"),r(this,"_hasOwnerResponse"),r(this,"_isWaitingForOwnershipResponseCallback",null),this.connection=A,this.guid=e,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),A.beginListen("lost-ownership",this._lostSubscription),A.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),A.beginListen("response-has-owner",this._hasOwnerResponse)}get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(A){A.guid===this.guid&&(this._isOwned=A.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(A){A.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=A.value,A.value||(Lh&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((A,e)=>{this.requestOwnership();let g=0;const I=()=>{if(g++>10)return e("Timeout");setTimeout(()=>{this.hasOwnership?A(this):I()},100)};I()})}requestOwnership(){return Lh&&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.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(A){A.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===A.owner?(Lh&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(A){A===this.guid&&(Lh&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class Pq{constructor(A){r(this,"context"),r(this,"_peer",null),r(this,"_usersInRoomCopy",[]),r(this,"_defaultMessagesBuffer",[]),r(this,"_defaultMessagesBufferArray",[]),r(this,"netWebSocketUrlProvider"),r(this,"_listeners",{}),r(this,"_listenersBinary",{}),r(this,"connected",!1),r(this,"channelId"),r(this,"_connectionId",null),r(this,"_ws"),r(this,"_waitingForSocket",{}),r(this,"_isInRoom",!1),r(this,"_currentRoomName",null),r(this,"_currentRoomViewId",null),r(this,"_currentRoomAllowEditing",!0),r(this,"_currentInRoom",[]),r(this,"_state",{}),r(this,"_currentDelay",-1),r(this,"_connectingToWebsocketPromise",null),this.context=A}get peer(){return this._peer||(this._peer=new CV),this._peer}tryGetState(A){return A==="invalid"?null:this._state[A]}get connectionId(){return this._connectionId}get isDebugEnabled(){return NI}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}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(A){return this._currentInRoom.indexOf(A)!==-1}usersInRoom(A=null){A||(A=this._usersInRoomCopy),A.length=0;for(const e of this._currentInRoom)A.push(e);return A}joinRoom(A,e=!1){this.connect(),NI&&console.log("join: "+A),this.send("join-room",{room:A,viewOnly:e},XI.OnConnection)}leaveRoom(A=null){if(A||(A=this.currentRoomName),!A){console.error("Can not leave unknown room");return}this.send("leave-room",{room:A})}send(A,e=null,g=XI.Queued){if(e===null&&(e={}),g===XI.Queued){this._defaultMessagesBuffer.push({key:A,value:e});return}return this.sendWithWebsocket(A,e,g)}sendDeleteRemoteState(A){this.send("delete-state",{guid:A,dontSave:!0}),delete this._state[A]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(A){var e;NI&&console.log("<< bin",A.length),(e=this._ws)==null||e.send(A)}sendBufferedMessagesNow(){var A;if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const I in this._defaultMessagesBuffer){const i=this._defaultMessagesBuffer[I];if(e<=1){this.sendWithWebsocket(i.key,i.value,XI.Immediate);break}const o=this.toMessage(i.key,i.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&NI&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const g=JSON.stringify(this._defaultMessagesBufferArray);(A=this._ws)==null||A.send(g)}beginListen(A,e){return this._listeners[A]||(this._listeners[A]=[]),this._listeners[A].push(e),e}stopListening(A,e){return this.stopListen(A,e)}stopListen(A,e){if(!e||!this._listeners[A])return;const g=this._listeners[A].indexOf(e);g>=0&&this._listeners[A].splice(g,1)}beginListenBinary(A,e){return this._listenersBinary[A]||(this._listenersBinary[A]=[]),this._listenersBinary[A].push(e),e}stopListenBinary(A,e){if(!this._listenersBinary[A])return;const g=this._listenersBinary[A].indexOf(e);g>=0&&this._listenersBinary[A].splice(g,1)}registerProvider(A){this.netWebSocketUrlProvider=A}async connect(){var A;if(this.connected)return Promise.resolve(!0);NI&&console.log("connecting");const e=(A=this.netWebSocketUrlProvider)==null?void 0:A.getWebsocketUrl();return e?Ra=e:qU()&&(Ra="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){var A;(A=this._ws)==null||A.close(),this._ws=void 0}connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(A,e)=>{let g=!1;const I=o=>{g||(g=!0,A(o))};if(Ra===void 0&&(console.log("Fetch default backend url: "+Tq),Ra=await(await fetch(Tq)).text()),Ra===void 0){I(!1);return}console.log(`\u22A1 Connecting to networking backend on
|
|
3334
3334
|
`+Ra);const i=new SJ.WebsocketBuilder(Ra).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=i,this.connected=!0,console.log(`\u229E Connected to networking backend
|
|
3335
3335
|
`+Ra),I(!0),this.onSendQueued(XI.OnConnection)}).onClose(o=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,I(!1)}).onError((o,C)=>{console.error("\u22A0 Websocket error",o,C),I(!1)}).onMessage(this.onMessage.bind(this)).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build()})}onMessage(A,e){const g=e.data;try{if(typeof g!="string"){g.size&&this.handleIncomingBinaryMessage(g);return}const I=JSON.parse(g);if(Array.isArray(I))for(const i of I)this.handleIncomingStringMessage(i);else this.handleIncomingStringMessage(I);return}catch{NI&&g==="pong"&&console.log("<<",g)}}async handleIncomingBinaryMessage(A){const e=await A.arrayBuffer();var g=new Uint8Array(e);const I=new hd(g),i=I.getBufferIdentifier(),o=this._listenersBinary[i],C=fW(I),s=kW(C);if(s&&typeof s=="string"&&(this._state[s]=C),!o)return;const a=C??I;for(const n of o)n(a)}handleIncomingStringMessage(A){var e,g;if(NI&&console.log("<<",A.key??A),A.key)switch(A.key){case"connection-start-info":if(A.data){const C=A.data;C&&(console.assert(C.id!==void 0&&C.id!==null&&C.id.length>0,"server did not send connection id",C.id),console.log("Your id is: "+C.id,this.context.alias??""),this._connectionId=C.id)}else console.warn("Expected connection id in "+A.key);break;case"joined-room":if(NI&&console.log(A),A){this._isInRoom=!0;const C=A;this._currentRoomName=C.room,this._currentRoomViewId=C.viewId,this._currentRoomAllowEditing=C.allowEditing??!0,console.log("Room view id",this._currentRoomViewId),this._currentInRoom.length=0,this._currentInRoom.push(...C.inRoom),NI&&console.log("joined room with",this._currentInRoom,this.context.alias??"")}this.onSendQueued(XI.OnRoomJoin);break;case"left-room":A.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentInRoom.length=0);break;case"user-joined-room":if(A.data){const C=A.data;this._currentInRoom.push(C.userId),NI&&console.log(C.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(A.data){const C=A.data,s=this._currentInRoom.indexOf(C.userId);s>=0&&(console.log(C.userId+" left",this.context.alias??""),this._currentInRoom.splice(s,1)),C.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":NI&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=(e=A.data)==null?void 0:e.time;o&&(this._currentDelay=this.context.time.time-o),NI&&console.log("Current latency: "+this._currentDelay.toFixed(1)+" sec","Clients in room: "+((g=this._currentInRoom)==null?void 0:g.length));break}const I=this._listeners[A.key];if(I)for(const o of I)o(A.data);const i=A.data;i&&(this._state[i.guid]=i)}toMessage(A,e){return{key:A,data:e}}sendWithWebsocket(A,e,g=XI.OnRoomJoin){if(!this._ws){const i=this._waitingForSocket[g]||[];i.push(()=>this.sendWithWebsocket(A,e,g)),this._waitingForSocket[g]=i;return}const I=JSON.stringify(this.toMessage(A,e));NI&&console.log(">>",A),this._ws.send(I)}onSendQueued(A){const e=this._waitingForSocket[A];if(e){for(const g of e)g();e.length=0}}}function WB(t,A){try{A?t(A):t()}catch(e){return console.error(e),!1}return!0}(0,eval)(`
|
|
3336
|
-
if(!globalThis[""
|
|
3337
|
-
globalThis[""
|
|
3336
|
+
if(!globalThis["NEEDLE_ENGINE_VERSION"])
|
|
3337
|
+
globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";
|
|
3338
3338
|
if(!globalThis[""undefined""])
|
|
3339
3339
|
globalThis[""undefined""] = "unknown";
|
|
3340
|
-
`);const jq="null",QV="undefined",Bs="needle_isActiveInHierarchy",rr="builtin_components",xh="needle_editor_guid",EV=/^(?:[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 hV(t){return typeof t=="string"&&EV.test(t)}const AI=[];for(let t=0;t<256;++t)AI.push((t+256).toString(16).slice(1));function cV(t,A=0){return(AI[t[A+0]]+AI[t[A+1]]+AI[t[A+2]]+AI[t[A+3]]+"-"+AI[t[A+4]]+AI[t[A+5]]+"-"+AI[t[A+6]]+AI[t[A+7]]+"-"+AI[t[A+8]]+AI[t[A+9]]+"-"+AI[t[A+10]]+AI[t[A+11]]+AI[t[A+12]]+AI[t[A+13]]+AI[t[A+14]]+AI[t[A+15]]).toLowerCase()}function lV(t){if(!hV(t))throw TypeError("Invalid UUID");let A;const e=new Uint8Array(16);return e[0]=(A=parseInt(t.slice(0,8),16))>>>24,e[1]=A>>>16&255,e[2]=A>>>8&255,e[3]=A&255,e[4]=(A=parseInt(t.slice(9,13),16))>>>8,e[5]=A&255,e[6]=(A=parseInt(t.slice(14,18),16))>>>8,e[7]=A&255,e[8]=(A=parseInt(t.slice(19,23),16))>>>8,e[9]=A&255,e[10]=(A=parseInt(t.slice(24,36),16))/1099511627776&255,e[11]=A/4294967296&255,e[12]=A>>>24&255,e[13]=A>>>16&255,e[14]=A>>>8&255,e[15]=A&255,e}function dV(t){t=unescape(encodeURIComponent(t));const A=[];for(let e=0;e<t.length;++e)A.push(t.charCodeAt(e));return A}const pV="6ba7b810-9dad-11d1-80b4-00c04fd430c8",uV="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function DV(t,A,e){function g(I,i,o,C){var s;if(typeof I=="string"&&(I=dV(I)),typeof i=="string"&&(i=lV(i)),((s=i)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+I.length);if(a.set(i),a.set(I,i.length),a=e(a),a[6]=a[6]&15|A,a[8]=a[8]&63|128,o){C=C||0;for(let n=0;n<16;++n)o[C+n]=a[n];return o}return cV(a)}try{g.name=t}catch{}return g.DNS=pV,g.URL=uV,g}function wV(t,A,e,g){switch(t){case 0:return A&e^~A&g;case 1:return A^e^g;case 2:return A&e^A&g^e&g;case 3:return A^e^g}}function Qk(t,A){return t<<A|t>>>32-A}function yV(t){const A=[1518500249,1859775393,2400959708,3395469782],e=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){const o=unescape(encodeURIComponent(t));t=[];for(let C=0;C<o.length;++C)t.push(o.charCodeAt(C))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);const g=t.length/4+2,I=Math.ceil(g/16),i=new Array(I);for(let o=0;o<I;++o){const C=new Uint32Array(16);for(let s=0;s<16;++s)C[s]=t[o*64+s*4]<<24|t[o*64+s*4+1]<<16|t[o*64+s*4+2]<<8|t[o*64+s*4+3];i[o]=C}i[I-1][14]=(t.length-1)*8/Math.pow(2,32),i[I-1][14]=Math.floor(i[I-1][14]),i[I-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<I;++o){const C=new Uint32Array(80);for(let E=0;E<16;++E)C[E]=i[o][E];for(let E=16;E<80;++E)C[E]=Qk(C[E-3]^C[E-8]^C[E-14]^C[E-16],1);let s=e[0],a=e[1],n=e[2],B=e[3],Q=e[4];for(let E=0;E<80;++E){const h=Math.floor(E/20),c=Qk(s,5)+wV(h,a,n,B)+Q+A[h]+C[E]>>>0;Q=B,B=n,n=Qk(a,30)>>>0,a=s,s=c}e[0]=e[0]+s>>>0,e[1]=e[1]+a>>>0,e[2]=e[2]+n>>>0,e[3]=e[3]+B>>>0,e[4]=e[4]+Q>>>0}return[e[0]>>24&255,e[0]>>16&255,e[0]>>8&255,e[0]&255,e[1]>>24&255,e[1]>>16&255,e[1]>>8&255,e[1]&255,e[2]>>24&255,e[2]>>16&255,e[2]>>8&255,e[2]&255,e[3]>>24&255,e[3]>>16&255,e[3]>>8&255,e[3]&255,e[4]>>24&255,e[4]>>16&255,e[4]>>8&255,e[4]&255]}const SV=DV("v5",80,yV),Wq=SV;_t.registerCallback(ci.ContextCreated,t=>{const A=t.context;Ab(A),$q(A)});const Uu=aA("debugcomponents"),Vq="eff8ba80-635d-11ec-90d6-0242ac120003";class VI{constructor(A){r(this,"_originalSeed"),r(this,"_seed"),typeof A=="string"&&(A=VI.hash(A)),this._originalSeed=A,this._seed=A}get seed(){return this._seed}set seed(A){this._seed=A}reset(){this._seed=this._originalSeed}generateUUID(A){if(typeof A=="string")return Wq(A,Vq);const e=this._seed;return this._seed-=1,Wq(e.toString(),Vq)}initialize(A){typeof A=="string"?this._seed=VI.hash(A):this._seed=A}static createFromString(A){return new VI(this.hash(A))}static hash(A){let e=0;for(let g=0;g<A.length;g++)e=A.charCodeAt(g)+((e<<5)-e);return e}}var zq=(t=>(t.NewInstanceCreated="new-instance-created",t.InstanceDestroyed="instance-destroyed",t))(zq||{});class Zq{constructor(A){r(this,"guid"),this.guid=A}}function Fu(t,A,e=!0){if(!t)return;const g=t;if(Qs(t,e),!A){console.warn("Can not send destroy: No networking connection provided",t.guid);return}if(!A.isConnected){console.warn("Can not send destroy: not connected",t.guid);return}let I=t.guid;if(!I&&g.uuid&&(I=g.uuid),!I){console.warn("Can not send destroy: failed to find guid",t);return}const i=new Zq(I);A.send("instance-destroyed",i,XI.Queued)}function Xq(t,A){const e=new Zq(t);A.send("instance-destroyed",e,XI.Queued)}function $q(t){t.connection.beginListen("instance-destroyed",A=>{Uu&&console.log("[Remote] Destroyed",t.scene,A);const e=zh(A.guid,t.scene);e&&Qs(e)})}class fV{constructor(A,e,g){r(this,"filename"),r(this,"hash"),r(this,"size"),this.filename=A,this.hash=e,this.size=g}}class kV{constructor(A,e){r(this,"guid"),r(this,"originalGuid"),r(this,"seed"),r(this,"visible"),r(this,"hostData"),r(this,"dontSave"),r(this,"parent"),r(this,"position"),r(this,"rotation"),r(this,"scale"),this.originalGuid=A,this.guid=e}}function Ek(t,A,e,g){var I;const i=t;if(!i.guid)return console.warn("Can not instantiate: No guid",i),null;if(A.context||(A.context=we.Current),!A.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const o=A?{...A}:null,{instance:C,seed:s}=GV(i,A);if(C){const a=C;if(a.guid){Uu&&console.log("[Local] new instance","gameobject:",C?.guid);const n=new kV(i.guid,a.guid);n.seed=s,o&&(o.position&&(n.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(n.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(n.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),n.position||(n.position={x:a.position.x,y:a.position.y,z:a.position.z}),n.rotation||(n.rotation={x:a.quaternion.x,y:a.quaternion.y,z:a.quaternion.z,w:a.quaternion.w}),n.scale||(n.scale={x:a.scale.x,y:a.scale.y,z:a.scale.z}),n.visible=i.visible,o!=null&&o.parent&&(typeof o.parent=="string"?n.parent=o.parent:n.parent=o.parent.guid),n.hostData=e,g===!1&&(n.dontSave=!0),(I=A?.context)==null||I.connection.send("new-instance-created",n)}else console.warn("Missing guid, can not send new instance event",a)}return C}function Nu(){return Math.random()*9999999}function Ab(t){t.connection.beginListen("new-instance-created",async A=>{const e=await mV(A.originalGuid,t.scene);if(!e){console.warn("could not find object that was instantiated: "+A.guid);return}const g=new gC;A.position&&(g.position=new f(A.position.x,A.position.y,A.position.z)),A.rotation&&(g.rotation=new GA(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w)),A.scale&&(g.scale=new f(A.scale.x,A.scale.y,A.scale.z)),g.parent=A.parent,A.seed&&(g.idProvider=new VI(A.seed)),g.visible=A.visible,g.context=t,Uu&&t.alias&&console.log("[Remote] instantiate in: "+t.alias);const I=Zh(e,g);I&&(A.parent==="scene"&&t.scene.add(I),Uu&&console.log("[Remote] new instance","gameobject:",I?.guid,e))})}function GV(t,A){const e=Nu(),g=A??new gC;g.idProvider=new VI(e);const I=Zh(t,g);return{seed:e,instance:I}}const eb={};function tb(t,A){eb[t]=A}async function mV(t,A){const e=eb[t];if(e!=null){const g=await e(t);if(g)return g}return gb(t,A)}function gb(t,A){if(A===null||!t)return null;if(A.guid===t)return A;if(A.children)for(const e of A.children){const g=gb(t,e);if(g)return g}return null}const Ib=new Map;function MV(t,A){if(!t)return;if(!A){console.warn("No prototype found",t,t.prototype,t.constructor);return}let e=Ib.get(A);e&&e.apply(t)}function RV(t){const A=UV(t.prototype);Ib.set(t,A)}function UV(t){return new FV(t)}class FV{constructor(A){r(this,"$symbol"),r(this,"extensions"),r(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(A),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const g=this.extensions[e],I=Object.getOwnPropertyDescriptor(A,g);I&&this.descriptors.push(I)}}apply(A){if(!A[this.$symbol]){A[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const g=this.extensions[e],I=this.descriptors[e];I&&Object.defineProperty(A,g,I)}}}}var Yh=(t=>(t.Added="component-added",t.Removing="removing-component",t))(Yh||{});const ib=aA("debugcomponentevents");class Hh{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let g=this.eventListeners.get(A);g||(g=[]),g.push(e),this.eventListeners.set(A,g),ib&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const g=this.eventListeners.get(A);if(!g)return;const I=g.indexOf(e);I<0||g.splice(I,1)}static dispatchComponentLifecycleEvent(A,e){const g=this.eventListeners.get(A);if(ib&&console.log("Dispatching event "+A,g),!!g)for(const I of g)I(e)}}r(Hh,"eventListeners",new Map);const hk=aA("debuggetcomponent");function NV(t){return t==null||t.isObject3D?t:t.object&&t.object.isObject3D?t.object:t}function ck(t,A){if(!t||!t.userData.components)return;const e=t.userData.components.indexOf(A);e<0||(Hh.dispatchComponentLifecycleEvent(Yh.Removing,A),A.gameObject=null,t.userData.components.splice(e,1))}function Ku(t,A){const e=VB(t,A);if(e)return e;const g=new A;return Br(t,g)}const ob=new VI("addComponentIdProvider");function Br(t,A,e=!0){t.userData||(t.userData={}),t.userData.components||(t.userData.components=[]),t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ob.generateUUID()),qu(t),tD(A);try{e&&A.__internalAwake&&(Xh(t),A.__internalAwake()),Hh.dispatchComponentLifecycleEvent(Yh.Added,A)}catch(g){console.error(g)}return A}function lk(t,A){if(A.gameObject===t)return A;if(A.gameObject&&A.gameObject.userData.components){const e=A.gameObject.userData.components.indexOf(A);A.gameObject.userData.components.splice(e,1)}if(!t.userData.components)t.userData.components=[];else if(t.userData.components.includes(A))return A;return t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ob.generateUUID()),tD(A),A}function Cb(t){if(t.gameObject&&t.gameObject.userData.components){const A=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(A,1)}t.__internalDisable&&t.__internalDisable(),t.onDestroy&&t.onDestroy(),Es(t,t.context??we.Current),t.__internalDestroy(),t.gameObject=null}let sb=!1;function ab(t,A,e){var g;if(t!=null){if(!t.isObject3D){console.error("Object is not object3D");return}if(!((g=t?.userData)!=null&&g.components))return null;if(typeof A=="string"&&(sb||(sb=!0,console.warn(`Accessing components by name is not supported.
|
|
3340
|
+
`);const jq=NEEDLE_ENGINE_VERSION,QV="undefined",Bs="needle_isActiveInHierarchy",rr="builtin_components",xh="needle_editor_guid",EV=/^(?:[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 hV(t){return typeof t=="string"&&EV.test(t)}const AI=[];for(let t=0;t<256;++t)AI.push((t+256).toString(16).slice(1));function cV(t,A=0){return(AI[t[A+0]]+AI[t[A+1]]+AI[t[A+2]]+AI[t[A+3]]+"-"+AI[t[A+4]]+AI[t[A+5]]+"-"+AI[t[A+6]]+AI[t[A+7]]+"-"+AI[t[A+8]]+AI[t[A+9]]+"-"+AI[t[A+10]]+AI[t[A+11]]+AI[t[A+12]]+AI[t[A+13]]+AI[t[A+14]]+AI[t[A+15]]).toLowerCase()}function lV(t){if(!hV(t))throw TypeError("Invalid UUID");let A;const e=new Uint8Array(16);return e[0]=(A=parseInt(t.slice(0,8),16))>>>24,e[1]=A>>>16&255,e[2]=A>>>8&255,e[3]=A&255,e[4]=(A=parseInt(t.slice(9,13),16))>>>8,e[5]=A&255,e[6]=(A=parseInt(t.slice(14,18),16))>>>8,e[7]=A&255,e[8]=(A=parseInt(t.slice(19,23),16))>>>8,e[9]=A&255,e[10]=(A=parseInt(t.slice(24,36),16))/1099511627776&255,e[11]=A/4294967296&255,e[12]=A>>>24&255,e[13]=A>>>16&255,e[14]=A>>>8&255,e[15]=A&255,e}function dV(t){t=unescape(encodeURIComponent(t));const A=[];for(let e=0;e<t.length;++e)A.push(t.charCodeAt(e));return A}const pV="6ba7b810-9dad-11d1-80b4-00c04fd430c8",uV="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function DV(t,A,e){function g(I,i,o,C){var s;if(typeof I=="string"&&(I=dV(I)),typeof i=="string"&&(i=lV(i)),((s=i)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+I.length);if(a.set(i),a.set(I,i.length),a=e(a),a[6]=a[6]&15|A,a[8]=a[8]&63|128,o){C=C||0;for(let n=0;n<16;++n)o[C+n]=a[n];return o}return cV(a)}try{g.name=t}catch{}return g.DNS=pV,g.URL=uV,g}function wV(t,A,e,g){switch(t){case 0:return A&e^~A&g;case 1:return A^e^g;case 2:return A&e^A&g^e&g;case 3:return A^e^g}}function Qk(t,A){return t<<A|t>>>32-A}function yV(t){const A=[1518500249,1859775393,2400959708,3395469782],e=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){const o=unescape(encodeURIComponent(t));t=[];for(let C=0;C<o.length;++C)t.push(o.charCodeAt(C))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);const g=t.length/4+2,I=Math.ceil(g/16),i=new Array(I);for(let o=0;o<I;++o){const C=new Uint32Array(16);for(let s=0;s<16;++s)C[s]=t[o*64+s*4]<<24|t[o*64+s*4+1]<<16|t[o*64+s*4+2]<<8|t[o*64+s*4+3];i[o]=C}i[I-1][14]=(t.length-1)*8/Math.pow(2,32),i[I-1][14]=Math.floor(i[I-1][14]),i[I-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<I;++o){const C=new Uint32Array(80);for(let E=0;E<16;++E)C[E]=i[o][E];for(let E=16;E<80;++E)C[E]=Qk(C[E-3]^C[E-8]^C[E-14]^C[E-16],1);let s=e[0],a=e[1],n=e[2],B=e[3],Q=e[4];for(let E=0;E<80;++E){const h=Math.floor(E/20),c=Qk(s,5)+wV(h,a,n,B)+Q+A[h]+C[E]>>>0;Q=B,B=n,n=Qk(a,30)>>>0,a=s,s=c}e[0]=e[0]+s>>>0,e[1]=e[1]+a>>>0,e[2]=e[2]+n>>>0,e[3]=e[3]+B>>>0,e[4]=e[4]+Q>>>0}return[e[0]>>24&255,e[0]>>16&255,e[0]>>8&255,e[0]&255,e[1]>>24&255,e[1]>>16&255,e[1]>>8&255,e[1]&255,e[2]>>24&255,e[2]>>16&255,e[2]>>8&255,e[2]&255,e[3]>>24&255,e[3]>>16&255,e[3]>>8&255,e[3]&255,e[4]>>24&255,e[4]>>16&255,e[4]>>8&255,e[4]&255]}const SV=DV("v5",80,yV),Wq=SV;_t.registerCallback(ci.ContextCreated,t=>{const A=t.context;Ab(A),$q(A)});const Uu=aA("debugcomponents"),Vq="eff8ba80-635d-11ec-90d6-0242ac120003";class VI{constructor(A){r(this,"_originalSeed"),r(this,"_seed"),typeof A=="string"&&(A=VI.hash(A)),this._originalSeed=A,this._seed=A}get seed(){return this._seed}set seed(A){this._seed=A}reset(){this._seed=this._originalSeed}generateUUID(A){if(typeof A=="string")return Wq(A,Vq);const e=this._seed;return this._seed-=1,Wq(e.toString(),Vq)}initialize(A){typeof A=="string"?this._seed=VI.hash(A):this._seed=A}static createFromString(A){return new VI(this.hash(A))}static hash(A){let e=0;for(let g=0;g<A.length;g++)e=A.charCodeAt(g)+((e<<5)-e);return e}}var zq=(t=>(t.NewInstanceCreated="new-instance-created",t.InstanceDestroyed="instance-destroyed",t))(zq||{});class Zq{constructor(A){r(this,"guid"),this.guid=A}}function Fu(t,A,e=!0){if(!t)return;const g=t;if(Qs(t,e),!A){console.warn("Can not send destroy: No networking connection provided",t.guid);return}if(!A.isConnected){console.warn("Can not send destroy: not connected",t.guid);return}let I=t.guid;if(!I&&g.uuid&&(I=g.uuid),!I){console.warn("Can not send destroy: failed to find guid",t);return}const i=new Zq(I);A.send("instance-destroyed",i,XI.Queued)}function Xq(t,A){const e=new Zq(t);A.send("instance-destroyed",e,XI.Queued)}function $q(t){t.connection.beginListen("instance-destroyed",A=>{Uu&&console.log("[Remote] Destroyed",t.scene,A);const e=zh(A.guid,t.scene);e&&Qs(e)})}class fV{constructor(A,e,g){r(this,"filename"),r(this,"hash"),r(this,"size"),this.filename=A,this.hash=e,this.size=g}}class kV{constructor(A,e){r(this,"guid"),r(this,"originalGuid"),r(this,"seed"),r(this,"visible"),r(this,"hostData"),r(this,"dontSave"),r(this,"parent"),r(this,"position"),r(this,"rotation"),r(this,"scale"),this.originalGuid=A,this.guid=e}}function Ek(t,A,e,g){var I;const i=t;if(!i.guid)return console.warn("Can not instantiate: No guid",i),null;if(A.context||(A.context=we.Current),!A.context)return console.error("Missing network instantiate options / reference to network connection in sync instantiate"),null;const o=A?{...A}:null,{instance:C,seed:s}=GV(i,A);if(C){const a=C;if(a.guid){Uu&&console.log("[Local] new instance","gameobject:",C?.guid);const n=new kV(i.guid,a.guid);n.seed=s,o&&(o.position&&(n.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(n.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(n.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),n.position||(n.position={x:a.position.x,y:a.position.y,z:a.position.z}),n.rotation||(n.rotation={x:a.quaternion.x,y:a.quaternion.y,z:a.quaternion.z,w:a.quaternion.w}),n.scale||(n.scale={x:a.scale.x,y:a.scale.y,z:a.scale.z}),n.visible=i.visible,o!=null&&o.parent&&(typeof o.parent=="string"?n.parent=o.parent:n.parent=o.parent.guid),n.hostData=e,g===!1&&(n.dontSave=!0),(I=A?.context)==null||I.connection.send("new-instance-created",n)}else console.warn("Missing guid, can not send new instance event",a)}return C}function Nu(){return Math.random()*9999999}function Ab(t){t.connection.beginListen("new-instance-created",async A=>{const e=await mV(A.originalGuid,t.scene);if(!e){console.warn("could not find object that was instantiated: "+A.guid);return}const g=new gC;A.position&&(g.position=new f(A.position.x,A.position.y,A.position.z)),A.rotation&&(g.rotation=new GA(A.rotation.x,A.rotation.y,A.rotation.z,A.rotation.w)),A.scale&&(g.scale=new f(A.scale.x,A.scale.y,A.scale.z)),g.parent=A.parent,A.seed&&(g.idProvider=new VI(A.seed)),g.visible=A.visible,g.context=t,Uu&&t.alias&&console.log("[Remote] instantiate in: "+t.alias);const I=Zh(e,g);I&&(A.parent==="scene"&&t.scene.add(I),Uu&&console.log("[Remote] new instance","gameobject:",I?.guid,e))})}function GV(t,A){const e=Nu(),g=A??new gC;g.idProvider=new VI(e);const I=Zh(t,g);return{seed:e,instance:I}}const eb={};function tb(t,A){eb[t]=A}async function mV(t,A){const e=eb[t];if(e!=null){const g=await e(t);if(g)return g}return gb(t,A)}function gb(t,A){if(A===null||!t)return null;if(A.guid===t)return A;if(A.children)for(const e of A.children){const g=gb(t,e);if(g)return g}return null}const Ib=new Map;function MV(t,A){if(!t)return;if(!A){console.warn("No prototype found",t,t.prototype,t.constructor);return}let e=Ib.get(A);e&&e.apply(t)}function RV(t){const A=UV(t.prototype);Ib.set(t,A)}function UV(t){return new FV(t)}class FV{constructor(A){r(this,"$symbol"),r(this,"extensions"),r(this,"descriptors"),this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(A),this.descriptors=new Array;for(let e=0;e<this.extensions.length;e++){const g=this.extensions[e],I=Object.getOwnPropertyDescriptor(A,g);I&&this.descriptors.push(I)}}apply(A){if(!A[this.$symbol]){A[this.$symbol]=!0;for(let e=0;e<this.extensions.length;e++){const g=this.extensions[e],I=this.descriptors[e];I&&Object.defineProperty(A,g,I)}}}}var Yh=(t=>(t.Added="component-added",t.Removing="removing-component",t))(Yh||{});const ib=aA("debugcomponentevents");class Hh{static addComponentLifecylceEventListener(A,e){this.eventListeners.has(A)&&this.eventListeners.set(A,[]);let g=this.eventListeners.get(A);g||(g=[]),g.push(e),this.eventListeners.set(A,g),ib&&console.log("Added event listener for "+A,this.eventListeners)}static removeComponentLifecylceEventListener(A,e){const g=this.eventListeners.get(A);if(!g)return;const I=g.indexOf(e);I<0||g.splice(I,1)}static dispatchComponentLifecycleEvent(A,e){const g=this.eventListeners.get(A);if(ib&&console.log("Dispatching event "+A,g),!!g)for(const I of g)I(e)}}r(Hh,"eventListeners",new Map);const hk=aA("debuggetcomponent");function NV(t){return t==null||t.isObject3D?t:t.object&&t.object.isObject3D?t.object:t}function ck(t,A){if(!t||!t.userData.components)return;const e=t.userData.components.indexOf(A);e<0||(Hh.dispatchComponentLifecycleEvent(Yh.Removing,A),A.gameObject=null,t.userData.components.splice(e,1))}function Ku(t,A){const e=VB(t,A);if(e)return e;const g=new A;return Br(t,g)}const ob=new VI("addComponentIdProvider");function Br(t,A,e=!0){t.userData||(t.userData={}),t.userData.components||(t.userData.components=[]),t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ob.generateUUID()),qu(t),tD(A);try{e&&A.__internalAwake&&(Xh(t),A.__internalAwake()),Hh.dispatchComponentLifecycleEvent(Yh.Added,A)}catch(g){console.error(g)}return A}function lk(t,A){if(A.gameObject===t)return A;if(A.gameObject&&A.gameObject.userData.components){const e=A.gameObject.userData.components.indexOf(A);A.gameObject.userData.components.splice(e,1)}if(!t.userData.components)t.userData.components=[];else if(t.userData.components.includes(A))return A;return t.userData.components.push(A),A.gameObject=t,(A.guid===void 0||A.guid==="invalid")&&(A.guid=ob.generateUUID()),tD(A),A}function Cb(t){if(t.gameObject&&t.gameObject.userData.components){const A=t.gameObject.userData.components.indexOf(t);t.gameObject.userData.components.splice(A,1)}t.__internalDisable&&t.__internalDisable(),t.onDestroy&&t.onDestroy(),Es(t,t.context??we.Current),t.__internalDestroy(),t.gameObject=null}let sb=!1;function ab(t,A,e){var g;if(t!=null){if(!t.isObject3D){console.error("Object is not object3D");return}if(!((g=t?.userData)!=null&&g.components))return null;if(typeof A=="string"&&(sb||(sb=!0,console.warn(`Accessing components by name is not supported.
|
|
3341
3341
|
Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
|
|
3342
3342
|
|
|
3343
3343
|
You can import other modules your main module to get access to types
|
|
@@ -3833,7 +3833,7 @@ outputColor=vec4(color,inputColor.a);}`,$b=class extends Ro{constructor({blendFu
|
|
|
3833
3833
|
irradiance += 0.;
|
|
3834
3834
|
#else
|
|
3835
3835
|
irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
|
|
3836
|
-
#endif`),zA.lightmap.lightmapScaleOffset={value:new Ie(1,1,0,0)};const EZ=aA("debugplayerview");var iC=(t=>(t.Browser="browser",t.Headset="headset",t.Handheld="handheld",t))(iC||{});class uv{constructor(A,e){r(this,"userId"),r(this,"context"),r(this,"viewDevice","browser"),r(this,"removed",!1),r(this,"_object"),this.userId=A,this.context=e}get currentObject(){return this._object}set currentObject(A){this._object=A}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class Dv{constructor(A){r(this,"context"),r(this,"playerViews",new Map),this.context=A}setPlayerView(A,e,g){let I=this.playerViews.get(A);I||(I=new uv(A,this.context),this.playerViews.set(A,I)),I.viewDevice=g,I.currentObject=e,I.removed=!1}getPlayerView(A){if(!!A){if(!this.context.connection.userIsInRoom(A)){this.playerViews.delete(A);return}return this.playerViews.get(A)}}removePlayerView(A,e){const g=this.playerViews.get(A);g?.viewDevice===e&&(EZ&&console.log("REMOVE",A),g.removed=!0,this.playerViews.delete(A))}}const Lk=aA("debugSetup"),hZ=aA("stats"),cZ=aA("debugactive"),lZ=aA("debugframerate"),dZ=aA("debugcoroutine"),pZ={};class uZ{constructor(A){r(this,"name"),r(this,"alias"),r(this,"domElement"),r(this,"renderer"),r(this,"hash"),this.domElement=A??document.body}}var ki=(t=>(t[t.EarlyUpdate=0]="EarlyUpdate",t[t.Update=1]="Update",t[t.LateUpdate=2]="LateUpdate",t[t.OnBeforeRender=3]="OnBeforeRender",t[t.OnAfterRender=4]="OnAfterRender",t[t.PrePhysicsStep=9]="PrePhysicsStep",t[t.PostPhysicsStep=10]="PostPhysicsStep",t[t.Undefined=-1]="Undefined",t))(ki||{}),gc=(t=>(t.ImmersiveVR="immersive-vr",t.ImmersiveAR="immersive-ar",t))(gc||{});function tD(t,A){if(!t)return;const e=A?.new_scripts??we.Current.new_scripts;e.includes(t)||e.push(t)}class we{constructor(A){r(this,"name"),r(this,"alias"),r(this,"isManagedExternally",!1),r(this,"isPaused",!1),r(this,"runInBackground",!1),r(this,"targetFrameRate"),r(this,"hash"),r(this,"domElement"),r(this,"_resolutionScaleFactor",1),r(this,"_boundingClientRectFrame",-1),r(this,"_boundingClientRect",null),r(this,"_domX"),r(this,"_domY"),r(this,"xrSessionMode"),r(this,"_xrFrame",null),r(this,"_currentFrameEvent",-1),r(this,"scene"),r(this,"renderer"),r(this,"composer",null),r(this,"scripts",[]),r(this,"scripts_pausedChanged",[]),r(this,"scripts_earlyUpdate",[]),r(this,"scripts_update",[]),r(this,"scripts_lateUpdate",[]),r(this,"scripts_onBeforeRender",[]),r(this,"scripts_onAfterRender",[]),r(this,"scripts_WithCorroutines",[]),r(this,"coroutines",{}),r(this,"mainCameraComponent"),r(this,"post_setup_callbacks",[]),r(this,"pre_update_callbacks",[]),r(this,"pre_render_callbacks",[]),r(this,"post_render_callbacks",[]),r(this,"new_scripts",[]),r(this,"new_script_start",[]),r(this,"new_scripts_pre_setup_callbacks",[]),r(this,"new_scripts_post_setup_callbacks",[]),r(this,"application"),r(this,"time"),r(this,"input"),r(this,"physics"),r(this,"connection"),r(this,"assets"),r(this,"mainLight",null),r(this,"sceneLighting"),r(this,"addressables"),r(this,"lightmaps"),r(this,"players"),r(this,"_sizeChanged",!1),r(this,"_isCreated",!1),r(this,"_isCreating",!1),r(this,"_isVisible",!1),r(this,"_stats",hZ?Zz():null),r(this,"_intersectionObserver",null),r(this,"_disposeCallbacks",[]),r(this,"_cameraStack",[]),r(this,"_onBeforeRenderListeners",new Map),r(this,"_onAfterRenderListeners",new Map),r(this,"_requireDepthTexture",!1),r(this,"_requireColorTexture",!1),r(this,"_renderTarget"),r(this,"_isRendering",!1),r(this,"_accumulatedTime",0),r(this,"_framerateClock",new _p),r(this,"_dispatchReadyAfterFrame",!1),r(this,"_wasPaused",!1);var e,g;if(this.name=A?.name||"",this.alias=A?.alias,this.domElement=A?.domElement||document.body,this.hash=A?.hash,A!=null&&A.renderer)this.renderer=A.renderer,this.isManagedExternally=!0;else{const o={antialias:!0},C=(g=(e=A?.domElement)==null?void 0:e.shadowRoot)==null?void 0:g.querySelector("canvas");C&&(o.canvas=C),this.renderer=new NB(o),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=GI,this.renderer.setClearColor(new fA("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=RS,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=ue,this.renderer.physicallyCorrectLights=!0}this.scene=new Di,_t.register(this),this.application=new lv(this),this.time=new yJ,this.input=new CJ(this),this.physics=new DJ(this),this.connection=new Pq(this),this.assets=new hb,this.sceneLighting=new hv(this),this.addressables=new Qv(this),this.lightmaps=new QZ(this),this.players=new Dv(this);const I=()=>this._sizeChanged=!0;window.addEventListener("resize",I),this._disposeCallbacks.push(()=>window.removeEventListener("resize",I));const i=new ResizeObserver(o=>this._sizeChanged=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(o=>{this._isVisible=o[0].isIntersecting}),this._disposeCallbacks.push(()=>{var o;return(o=this._intersectionObserver)==null?void 0:o.disconnect()})}get version(){return jq}static get Current(){return _t.Current}static set Current(A){_t.Current=A}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(A){if(A!==this._resolutionScaleFactor&&typeof A=="number"){if(A<=0){console.error("Invalid resolution scale factor",A);return}this._resolutionScaleFactor=A,this.updateSize()}}calculateBoundingClientRect(){if(this.isInAR){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var A;return((A=this.renderer.xr)==null?void 0:A.isPresenting)||!1}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get xrSession(){var A;return(A=this.renderer.xr)==null?void 0:A.getSession()}get xrFrame(){return this._xrFrame}get arOverlayElement(){const A=this.domElement;return typeof A.getAROverlayContainer=="function"?A.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this.mainCameraComponent){const A=this.mainCameraComponent;return A.cam||A.buildCamera(),A.cam}return null}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}internalOnUpdateVisible(){var A,e;(A=this._intersectionObserver)==null||A.disconnect(),(e=this._intersectionObserver)==null||e.observe(this.domElement)}updateSize(){var A,e,g;if(!this.isManagedExternally&&((A=this.renderer.xr)==null?void 0:A.isPresenting)===!1){this._sizeChanged=!1;const I=this.resolutionScaleFactor,i=this.domWidth*I,o=this.domHeight*I,C=this.mainCamera;this.updateAspect(C),this.renderer.setSize(i,o),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((e=this.composer.setSize)==null||e.call(this.composer,i,o),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((g=this.composer.setPixelRatio)==null||g.call(this.composer,window.devicePixelRatio)))}}updateAspect(A,e,g){if(!A)return;e===void 0&&(e=this.domWidth),g===void 0&&(g=this.domHeight);const I=A.aspect;A.aspect=e/g,I!==A.aspect&&A.updateProjectionMatrix()}async onCreate(A,e){try{return this._isCreating=!0,await this.internalOnCreate(A,e)}finally{this._isCreating=!1}}clear(){var A;(A=this.scene)!=null&&A.children.length&&(Qs(this.scene,!0,!0),this.scene=new Di),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear())}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var A,e,g;this.clear(),(A=this.renderer)==null||A.setAnimationLoop(null),this.isManagedExternally||(e=this.renderer)==null||e.dispose();for(const I of this._disposeCallbacks)try{I()}catch(i){console.error("Error in on dispose callback:",i,I)}(g=this.domElement)!=null&&g.parentElement&&this.domElement.parentElement.removeChild(this.domElement),_t.dispatchCallback(ci.ContextDestroyed,this),_t.unregister(this)}registerCoroutineUpdate(A,e,g){return this.coroutines[g]||(this.coroutines[g]=[]),this.coroutines[g].push({comp:A,main:e}),e}unregisterCoroutineUpdate(A,e){if(!this.coroutines[e])return;const g=this.coroutines[e].findIndex(I=>I.main===A);g>=0&&this.coroutines[e].splice(g,1)}stopAllCoroutinesFrom(A){for(const e in this.coroutines){const g=this.coroutines[e];for(let I=g.length-1;I>=0;I--)g[I].comp===A&&g.splice(I,1)}}setCurrentCamera(A){var e;if(!A)return;if(A.cam||A.buildCamera(),!A.cam){console.warn("Camera component is missing camera",A);return}const g=this._cameraStack.indexOf(A);g>=0&&this._cameraStack.splice(g,1),this._cameraStack.push(A),this.mainCameraComponent=A;const I=A.cam;I.isPerspectiveCamera&&this.updateAspect(I),(e=this.mainCameraComponent)==null||e.applyClearFlagsIfIsActiveCamera()}removeCamera(A){if(!A)return;const e=this._cameraStack.indexOf(A);if(e>=0&&this._cameraStack.splice(e,1),this.mainCameraComponent===A&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const g=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(g)}}addBeforeRenderListener(A,e){var g;this._onBeforeRenderListeners.has(A.uuid)||(this._onBeforeRenderListeners.set(A.uuid,[]),A.onBeforeRender=this._createRenderCallbackWrapper(A,this._onBeforeRenderListeners)),(g=this._onBeforeRenderListeners.get(A.uuid))==null||g.push(e)}removeBeforeRenderListener(A,e){if(this._onBeforeRenderListeners.has(A.uuid)){const g=this._onBeforeRenderListeners.get(A.uuid),I=g.indexOf(e);I>=0&&g.splice(I,1)}}addAfterRenderListener(A,e){var g;this._onAfterRenderListeners.has(A.uuid)||(this._onAfterRenderListeners.set(A.uuid,[]),A.onAfterRender=this._createRenderCallbackWrapper(A,this._onAfterRenderListeners)),(g=this._onAfterRenderListeners.get(A.uuid))==null||g.push(e)}removeAfterRenderListener(A,e){if(this._onAfterRenderListeners.has(A.uuid)){const g=this._onAfterRenderListeners.get(A.uuid),I=g.indexOf(e);I>=0&&g.splice(I,1)}}_createRenderCallbackWrapper(A,e){return(g,I,i,o,C,s)=>{const a=e.get(A.uuid);if(a)for(let n=0;n<a.length;n++){const B=a[n];B(g,I,i,o,C,s)}}}get isRendering(){return this._isRendering}setRequireDepth(A){this._requireDepthTexture=A}setRequireColor(A){this._requireColorTexture=A}get depthTexture(){var A;return((A=this._renderTarget)==null?void 0:A.depthTexture)||null}get opaqueColorTexture(){var A;return((A=this._renderTarget)==null?void 0:A.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const A=getComputedStyle(this.domElement);return A.visibility!=="hidden"&&A.display!=="none"&&A.opacity!=="0"}async internalOnCreate(A,e){var g;this.clear(),(g=this.renderer)==null||g.setAnimationLoop(null),await _E(1),we.Current=this,await _t.dispatchCallback(ci.ContextCreationStart,this);let I=!0;try{we.Current=this,A&&await A(this,e)}catch(i){console.error(i),I=!1}if(!I)return!1;this.internalOnUpdateVisible(),!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),we.Current=this,we.Current=this;for(let i=0;i<this.new_scripts.length;i++){const o=this.new_scripts[i];if(o.gameObject!==void 0&&o.gameObject!==null){o.gameObject.userData===void 0&&(o.gameObject.userData={}),o.gameObject.userData.components===void 0&&(o.gameObject.userData.components=[]);const C=o.gameObject.userData.components;C.includes(o)||C.push(o)}}if(this.post_setup_callbacks)for(let i=0;i<this.post_setup_callbacks.length;i++)we.Current=this,await this.post_setup_callbacks[i](this);if(!this.mainCamera){we.Current=this;let i=null;Qr(this.scene,o=>{const C=o;if(C!=null&&C.isCamera){if(Xh(C.gameObject),!C.activeAndEnabled)return;if(C.tag==="MainCamera")return i=C,!0;i=C}}),i?this.setCurrentCamera(i):(_t.dispatchCallback(ci.MissingCamera,this),!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this))}if(we.Current=this,Hu(this),!this.isManagedExternally&&this.composer&&this.mainCamera){const i=new zu(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(i),this.composer.setSize(this.domWidth,this.domHeight)}return this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),Lk&&su(this.scene,!0),this._isCreating=!1,this.restartRenderLoop(),this._dispatchReadyAfterFrame=!0,_t.dispatchCallback(ci.ContextCreated,this)}restartRenderLoop(){if(!this.renderer)return console.error("Can not start render loop without renderer"),!1;if(this._isCreating)return console.warn("Can not start render loop while creating context"),!1;const A=this.render.bind(this);return this.renderer.setAnimationLoop(A),!0}render(A,e){if(UI()||Lk||VV())try{this.internalRender(A,e)}catch(g){(UI()||Lk)&&g instanceof Error&&Hg("Exception during render-loop.<br/>See console for details.",co.Error),console.error(g),console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),this.domElement.dispatchEvent(new CustomEvent("error",{detail:g}))}else this.internalRender(A,e)}internalRender(A,e){var g,I;if(this._xrFrame=e,this._currentFrameEvent=-1,this.isInXR===!1&&this.targetFrameRate!==void 0){if(this._accumulatedTime+=this._framerateClock.getDelta(),this._accumulatedTime<1/this.targetFrameRate)return;this._accumulatedTime=0}if((g=this._stats)==null||g.begin(),we.Current=this,!this.onHandlePaused()){for(we.Current=this,this.time.update(),lZ&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Hu(this),Tu(this.scene),Mb(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}if(this.pre_update_callbacks)for(const i in this.pre_update_callbacks)this.pre_update_callbacks[i]();this._currentFrameEvent=0;for(let i=0;i<this.scripts_earlyUpdate.length;i++){const o=this.scripts_earlyUpdate[i];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(we.Current=this,o.earlyUpdate())}if(this.executeCoroutines(0),!this.onHandlePaused()){this._currentFrameEvent=1;for(let i=0;i<this.scripts_update.length;i++){const o=this.scripts_update[i];o.activeAndEnabled&&o.update!==void 0&&(we.Current=this,o.update())}if(this.executeCoroutines(1),!this.onHandlePaused()){this._currentFrameEvent=2;for(let i=0;i<this.scripts_lateUpdate.length;i++){const o=this.scripts_lateUpdate[i];o.activeAndEnabled&&o.lateUpdate!==void 0&&(we.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),!this.onHandlePaused()){if(this.physics.engine){const i=this.time.deltaTime/1;for(let o=0;o<1;o++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);this.physics.engine.postStep()}if(!this.onHandlePaused()){if(this.isVisibleToUser){this._currentFrameEvent=3;for(let i=0;i<this.scripts_onBeforeRender.length;i++){const o=this.scripts_onBeforeRender[i];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(we.Current=this,o.onBeforeRender(e))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const i in this.pre_render_callbacks)this.pre_render_callbacks[i]();this.isManagedExternally||(XV(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4);for(let i=0;i<this.scripts_onAfterRender.length;i++){const o=this.scripts_onAfterRender[i];o.activeAndEnabled&&o.onAfterRender!==void 0&&(we.Current=this,o.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(const i in this.post_render_callbacks)this.post_render_callbacks[i]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),(I=this._stats)==null||I.end(),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")))}}}}}}renderNow(A){return!A&&(A=this.mainCamera,!A)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):A&&this.renderer.render(this.scene,A),this._isRendering=!1,!0)}onHandlePaused(){const A=this.evaluatePaused();if(this._wasPaused!==A){cZ&&console.log("Paused?",A,"context:"+this.alias);for(let e=0;e<this.scripts_pausedChanged.length;e++){const g=this.scripts_pausedChanged[e];g.activeAndEnabled&&g.onPausedChanged!==void 0&&(we.Current=this,g.onPausedChanged(A,this._wasPaused))}}return this._wasPaused=A,A}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new st(this.domWidth,this.domHeight),this._requireDepthTexture){const g=new lp(this.domWidth,this.domHeight);this._renderTarget.depthTexture=g}this._requireColorTexture&&(this._renderTarget.texture=new Ye,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=tt,this._renderTarget.texture.magFilter=tt,this._renderTarget.texture.format=mt)}const A=this._renderTarget;A.texture&&(A.texture.encoding=this.renderer.outputEncoding);const e=this.renderer.getRenderTarget();this.renderer.setRenderTarget(A),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(e)}executeCoroutines(A){if(this.coroutines[A]){const g=this.coroutines[A];for(let I=0;I<g.length;I++)try{const i=g[I];if(!i.comp||i.comp.destroyed||!i.main||i.comp.enabled===!1){dZ&&console.log("Removing coroutine",i.comp,i.comp.enabled),g.splice(I,1),--I;continue}const o=i.chained;if(o&&o.length>0){const a=o[o.length-1].next();if(a.done&&o.pop(),e(a)&&(i.chained||(i.chained=[]),i.chained.push(a.value)),!a.done)continue}const C=i.main.next();if(C.done===!0){g.splice(I,1),--I;continue}const s=C.value;if(e(s)){if(s.next().done)continue;i.chained||(i.chained=[]),i.chained.push(s)}}catch(i){console.error(i)}}function e(g){return!!(g&&g.next&&g.return)}}}const DZ=aA("debugaroverlay"),hr="ar",wv="quit-ar";class wZ{constructor(){r(this,"arContainer",null),r(this,"closeARCallback"),r(this,"currentSession",null),r(this,"registeredCloseEventElements",[]),r(this,"_createdAROnlyElements",[]),r(this,"_reparentedObjects",[]),this.closeARCallback=this.onRequestedEndAR.bind(this)}get ARContainer(){return this.arContainer}requestEndAR(){this.onRequestedEndAR()}onBegin(A,e,g){this.currentSession=g,this.arContainer=e,A.domElement.querySelectorAll(`.${hr}`).forEach(i=>{var o;i&&i!==this.arContainer&&(this._reparentedObjects.push({el:i,previousParent:i.parentElement}),(o=this.arContainer)==null||o.appendChild(i))});const I=e.getElementsByClassName(wv);if(!I||I.length<=0)console.warn(`Missing quit AR elements, creating fallback X button. Use class name '${wv}' to override.`),this.createFallbackCloseARButton(this.arContainer);else for(let i=0;i<I.length;i++){const o=I[i];o&&(o.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(o))}}onEnd(A){var e;for(const g of this._createdAROnlyElements)g.remove&&g.remove();for(const g of this._reparentedObjects){const I=g.el;(e=g.previousParent)==null||e.appendChild(I)}this._reparentedObjects.length=0,yS()&&setTimeout(()=>{const g=A.renderer.domElement;g&&A.domElement.insertBefore(g,A.domElement.firstChild);const I=document.querySelectorAll("*");for(var i=0;i<I.length;i++){const o=I[i];o&&o._displayChanged!==void 0&&o._displayWas!==void 0&&(o.style.display=o._displayWas)}},10)}findOrCreateARContainer(A){if(A.classList.contains(hr))return A;if(A.children)for(let I=0;I<A.children.length;I++){const i=A.children[I];if(!(!i||!i.classList)&&i.classList.contains(hr))return i}const e=document.getElementsByClassName(hr);if(e&&e.length>0)return e[0];DZ&&console.log("No overlay container found in document - generating new ony");const g=document.createElement("div");return g.classList.add(hr),g.style.position="absolute",g.style.width="100%",g.style.height="100%",g.style.display="flex",g.style.visibility="visible",A.appendChild(g)}onRequestedEndAR(){if(this.currentSession){this.currentSession.end(),this.currentSession=null;for(const A of this.registeredCloseEventElements)A.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(A){var e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","38px"),e.setAttribute("height","38px"),e.style.position="absolute",e.style.right="20px",e.style.top="40px",e.style.zIndex="9999",e.style.pointerEvents="auto",e.addEventListener("click",this.closeARCallback),A.appendChild(e),this._createdAROnlyElements.push(e);var g=document.createElementNS("http://www.w3.org/2000/svg","path");g.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),g.setAttribute("stroke","#ddd"),g.setAttribute("stroke-width","3px"),e.appendChild(g),this._createdAROnlyElements.push(g)}}class eA extends UA{constructor(){super(...arguments),r(this,"guid")}static isDestroyed(A){return pk(A)}static setActive(A,e,g=!0){A&&(Vh(A,e),Tu(A),e&&g&&Mb(we.Current,A))}static isActiveSelf(A){return ZB(A)}static isActiveInHierarchy(A){return Db(A)}static markAsInstancedRendered(A,e){wb(A,e)}static isUsingInstancing(A){return Yu(A)}static foreachComponent(A,e,g=!0){return Qr(A,e,g)}static instantiateSynced(A,e){return A?Ek(A,e):null}static instantiate(A,e=null){return Zh(A,e)}static destroySynced(A,e,g=!0){if(!A)return;const I=A;e=e??we.Current,Fu(I,e.connection,g)}static destroy(A,e=!0,g=!0){return Qs(A,e,g)}static add(A,e,g){if(!(!A||!e)){if(A===e){console.warn("Can not add object to self",A);return}g||(g=we.Current),e.add(A),Vh(A,!0),Tu(A),g?eA.foreachComponent(A,I=>{Dk(I,g),!I.__internalDidAwakeAndStart&&g.new_script_start.includes(I)===!1&&g.new_script_start.push(I)},!0):console.warn("Missing context")}}static remove(A){var e;A&&((e=A.parent)==null||e.remove(A),Vh(A,!1),Tu(A),eA.foreachComponent(A,g=>{zV(g)},!0))}static invokeOnChildren(A,e,...g){this.invoke(A,e,!0,g)}static invoke(A,e,g=!1,...I){A&&this.foreachComponent(A,i=>{const o=i[e];o&&typeof o=="function"&&o?.call(i,...I)},g)}static addNewComponent(A,e,g=!0){const I=new e;return Br(A,I,g),I}static addComponent(A,e){return this.moveComponent(A,e)}static moveComponent(A,e){return lk(A,e)}static removeComponent(A){return ck(A.gameObject,A),A}static getOrAddComponent(A,e){return Ku(A,e)}static getComponent(A,e){return A===null?null:VB(A,e)}static getComponents(A,e,g=null){return A===null?g??[]:Th(A,e,g)}static findByGuid(A,e){return zh(A,e)}static findObjectOfType(A,e,g=!0){return nb(A,e??we.Current,g)}static findObjectsOfType(A,e){const g=[];return rb(A,g,e),g}static getComponentInChildren(A,e){return zB(A,e)}static getComponentsInChildren(A,e,g=null){return _h(A,e,g??void 0)}static getComponentInParent(A,e){return Oh(A,e)}static getComponentsInParent(A,e,g=null){return Ju(A,e,g)}static getAllComponents(A){var e;return[...(e=A.userData)==null?void 0:e.components]}static*iterateComponents(A){var e;const g=(e=A?.userData)==null?void 0:e.components;if(g&&Array.isArray(g))for(let I=0;I<g.length;I++)yield g[I]}}var Eg;let Ja=(Eg=class{constructor(){r(this,"__context"),r(this,"__name"),r(this,"gameObject"),r(this,"guid","invalid"),r(this,"sourceId"),r(this,"__didAwake",!1),r(this,"__didStart",!1),r(this,"__didEnable",!1),r(this,"__isEnabled"),r(this,"__destroyed",!1),r(this,"_worldPosition"),r(this,"_worldQuaternion"),r(this,"_worldEuler"),r(this,"_worldRotation"),r(this,"_eventListeners",new Map),this.__internalNewInstanceCreated()}get isComponent(){return!0}get context(){return this.__context??we.Current}set context(t){this.__context=t}get scene(){return this.context.scene}get layer(){var t,A;return(A=(t=this.gameObject)==null?void 0:t.userData)==null?void 0:A.layer}get name(){var t,A;return(t=this.gameObject)!=null&&t.name?this.gameObject.name:(A=this.gameObject)==null?void 0:A.userData.name}set name(t){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=t,this.__name=t):this.__name=t}get tag(){var t;return(t=this.gameObject)==null?void 0:t.userData.tag}set tag(t){this.gameObject&&(this.gameObject.userData.tag=t)}get static(){var t;return(t=this.gameObject)==null?void 0:t.userData.static}get hideFlags(){var t;return(t=this.gameObject)==null?void 0:t.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;const t=this.gameObject[Bs];return t===void 0?!0:t}set __isActiveInHierarchy(t){this.gameObject&&(this.gameObject[Bs]=t)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(t,A=ki.Update){return this.context.registerCoroutineUpdate(this,t,A)}stopCoroutine(t,A=ki.Update){this.context.unregisterCoroutineUpdate(t,A)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__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(t){return this.__destroyed?(UI()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(t!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(t){if(this.__didAwake){if(!this.__didEnable){t!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var t;this.__destroyed||(this.__destroyed=!0,(t=this.destroy)==null||t.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this})),Cb(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(t){if(this.__destroyed){UI()&&console.warn(`[Needle Engine Dev] Trying to ${t?"enable":"disable"} destroyed component`);return}if(typeof t=="number"&&(t>=.5?t=!0:t=!1),!this.__didAwake){this.__isEnabled=t;return}t?this.__internalEnable():this.__internalDisable()}get worldPosition(){return this._worldPosition||(this._worldPosition=new f),ye(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(t){tg(this.gameObject,t)}setWorldPosition(t,A,e){Eg._worldPositionBuffer.set(t,A,e),this.worldPosition=Eg._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new GA),Ng(this.gameObject,this._worldQuaternion)}set worldQuaternion(t){zI(this.gameObject,t)}setWorldQuaternion(t,A,e,g){Eg._worldQuaternionBuffer.set(t,A,e,g),this.worldQuaternion=Eg._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new fg),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(t){var A;this._worldQuaternion||(this._worldQuaternion=new GA),(A=this._worldQuaternion)==null||A.setFromEuler(t),this.worldQuaternion=this._worldQuaternion}get worldRotation(){const t=this.worldEuler;this._worldRotation||(this._worldRotation=new f);const A=this._worldRotation;return A.set(t.x,t.y,t.z),A.x=XA.toDegrees(A.x),A.y=XA.toDegrees(A.y),A.z=XA.toDegrees(A.z),A}set worldRotation(t){this.setWorldRotation(t.x,t.y,t.z,!0)}setWorldRotation(t,A,e,g=!0){g&&(t=XA.toRadians(t),A=XA.toRadians(A),e=XA.toRadians(e)),Eg._worldEulerBuffer.set(t,A,e),Eg._worldQuaternionBuffer.setFromEuler(Eg._worldEulerBuffer),this.worldQuaternion=Eg._worldQuaternionBuffer}get forward(){return Eg._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return Eg._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return Eg._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(t,A){this._eventListeners[t]=this._eventListeners[t]||[],this._eventListeners[t].push(A)}removeEventListener(t,A){if(!this._eventListeners[t])return;const e=this._eventListeners[t].indexOf(A);e>=0&&this._eventListeners[t].splice(e,1)}dispatchEvent(t){if(!this._eventListeners[t.type])return!1;const A=this._eventListeners[t.type];for(let e=0;e<A.length;e++)A[e](t);return!1}},r(Eg,"_worldPositionBuffer",new f),r(Eg,"_worldQuaternionBuffer",new GA),r(Eg,"_worldEulerBuffer",new fg),r(Eg,"_tempQuaternionBuffer2",new GA),r(Eg,"_forward",new f),r(Eg,"_right",new f),r(Eg,"_up",new f),Eg);class RA extends Ja{}const yZ=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:RA,Component:Ja,GameObject:eA},Symbol.toStringTag,{value:"Module"})),SZ='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',fZ=new Blob([SZ],{type:"image/svg+xml;charset=utf-8"}),kZ=URL.createObjectURL(fZ),yv=kZ,cr=aA("debuglicense"),xk="basic";cr&&console.log("License Type: "+xk);function qa(){switch(xk){case"pro":case"enterprise":return!0}return!1}function Sv(){switch(xk){case"indie":return!0}return!1}function fv(){return qa()||Sv()}_t.registerCallback(ci.ContextRegistered,t=>{GZ(t.context)});async function GZ(t){try{if(qa()!==!0)return Tk(t)}catch(A){return cr&&console.log("License check failed",A),Tk(t)}cr&&Tk(t)}const kv="needle-license-element",Yk=5e3,Hk=200;function Tk(t){MZ(),t.domElement.addEventListener("ready",()=>{setTimeout(()=>{mZ(t)},1e3)}),FZ()}function mZ(t){const A=RZ(),e=UZ(),g=setInterval(()=>{if(!A)return;const s=t.domElement.shadowRoot||t.domElement;A.parentNode!==s&&(s.appendChild(A),e&&s.appendChild(e))},100);let I=`<img class="logo" src="${yv}" style="width: 40px; height: 40px; margin-right: 2px; vertical-align: middle; margin-bottom: 2px;"/>`;const i=document.createElement("div");i.innerHTML=I,i.classList.add("logo"),A.appendChild(i);const o=document.createElement("div");o.classList.add("text"),A.appendChild(o),A.title="Needle Engine",fv()||(A.title+=" non commercial version"),A.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});const C=Yk+Hk;setTimeout(()=>{clearInterval(g),A?.remove(),e?.remove()},C)}let Gv=0;async function MZ(t){const A=Date.now();if(A-Gv<2e3)return;Gv=A,console.log("%c Needle Engine \u2014 non commercial version",`
|
|
3836
|
+
#endif`),zA.lightmap.lightmapScaleOffset={value:new Ie(1,1,0,0)};const EZ=aA("debugplayerview");var iC=(t=>(t.Browser="browser",t.Headset="headset",t.Handheld="handheld",t))(iC||{});class uv{constructor(A,e){r(this,"userId"),r(this,"context"),r(this,"viewDevice","browser"),r(this,"removed",!1),r(this,"_object"),this.userId=A,this.context=e}get currentObject(){return this._object}set currentObject(A){this._object=A}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}}class Dv{constructor(A){r(this,"context"),r(this,"playerViews",new Map),this.context=A}setPlayerView(A,e,g){let I=this.playerViews.get(A);I||(I=new uv(A,this.context),this.playerViews.set(A,I)),I.viewDevice=g,I.currentObject=e,I.removed=!1}getPlayerView(A){if(!!A){if(!this.context.connection.userIsInRoom(A)){this.playerViews.delete(A);return}return this.playerViews.get(A)}}removePlayerView(A,e){const g=this.playerViews.get(A);g?.viewDevice===e&&(EZ&&console.log("REMOVE",A),g.removed=!0,this.playerViews.delete(A))}}const Lk=aA("debugSetup"),hZ=aA("stats"),cZ=aA("debugactive"),lZ=aA("debugframerate"),dZ=aA("debugcoroutine"),pZ={};class uZ{constructor(A){r(this,"name"),r(this,"alias"),r(this,"domElement"),r(this,"renderer"),r(this,"hash"),this.domElement=A??document.body}}var ki=(t=>(t[t.EarlyUpdate=0]="EarlyUpdate",t[t.Update=1]="Update",t[t.LateUpdate=2]="LateUpdate",t[t.OnBeforeRender=3]="OnBeforeRender",t[t.OnAfterRender=4]="OnAfterRender",t[t.PrePhysicsStep=9]="PrePhysicsStep",t[t.PostPhysicsStep=10]="PostPhysicsStep",t[t.Undefined=-1]="Undefined",t))(ki||{}),gc=(t=>(t.ImmersiveVR="immersive-vr",t.ImmersiveAR="immersive-ar",t))(gc||{});function tD(t,A){if(!t)return;const e=A?.new_scripts??we.Current.new_scripts;e.includes(t)||e.push(t)}class we{constructor(A){r(this,"name"),r(this,"alias"),r(this,"isManagedExternally",!1),r(this,"isPaused",!1),r(this,"runInBackground",!1),r(this,"targetFrameRate"),r(this,"hash"),r(this,"domElement"),r(this,"_resolutionScaleFactor",1),r(this,"_boundingClientRectFrame",-1),r(this,"_boundingClientRect",null),r(this,"_domX"),r(this,"_domY"),r(this,"xrSessionMode"),r(this,"_xrFrame",null),r(this,"_currentFrameEvent",-1),r(this,"scene"),r(this,"renderer"),r(this,"composer",null),r(this,"scripts",[]),r(this,"scripts_pausedChanged",[]),r(this,"scripts_earlyUpdate",[]),r(this,"scripts_update",[]),r(this,"scripts_lateUpdate",[]),r(this,"scripts_onBeforeRender",[]),r(this,"scripts_onAfterRender",[]),r(this,"scripts_WithCorroutines",[]),r(this,"coroutines",{}),r(this,"mainCameraComponent"),r(this,"post_setup_callbacks",[]),r(this,"pre_update_callbacks",[]),r(this,"pre_render_callbacks",[]),r(this,"post_render_callbacks",[]),r(this,"new_scripts",[]),r(this,"new_script_start",[]),r(this,"new_scripts_pre_setup_callbacks",[]),r(this,"new_scripts_post_setup_callbacks",[]),r(this,"application"),r(this,"time"),r(this,"input"),r(this,"physics"),r(this,"connection"),r(this,"assets"),r(this,"mainLight",null),r(this,"sceneLighting"),r(this,"addressables"),r(this,"lightmaps"),r(this,"players"),r(this,"_sizeChanged",!1),r(this,"_isCreated",!1),r(this,"_isCreating",!1),r(this,"_isVisible",!1),r(this,"_stats",hZ?Zz():null),r(this,"_intersectionObserver",null),r(this,"_disposeCallbacks",[]),r(this,"_cameraStack",[]),r(this,"_onBeforeRenderListeners",new Map),r(this,"_onAfterRenderListeners",new Map),r(this,"_requireDepthTexture",!1),r(this,"_requireColorTexture",!1),r(this,"_renderTarget"),r(this,"_isRendering",!1),r(this,"_accumulatedTime",0),r(this,"_framerateClock",new _p),r(this,"_dispatchReadyAfterFrame",!1),r(this,"_wasPaused",!1);var e,g;if(this.name=A?.name||"",this.alias=A?.alias,this.domElement=A?.domElement||document.body,this.hash=A?.hash,A!=null&&A.renderer)this.renderer=A.renderer,this.isManagedExternally=!0;else{const o={antialias:!0},C=(g=(e=A?.domElement)==null?void 0:e.shadowRoot)==null?void 0:g.querySelector("canvas");C&&(o.canvas=C),this.renderer=new NB(o),this.renderer.toneMappingExposure=1,this.renderer.toneMapping=GI,this.renderer.setClearColor(new fA("lightgrey"),0),this.renderer.antialias=!0,this.renderer.alpha=!1,this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=RS,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputEncoding=ue,this.renderer.physicallyCorrectLights=!0}this.scene=new Di,_t.register(this),this.application=new lv(this),this.time=new yJ,this.input=new CJ(this),this.physics=new DJ(this),this.connection=new Pq(this),this.assets=new hb,this.sceneLighting=new hv(this),this.addressables=new Qv(this),this.lightmaps=new QZ(this),this.players=new Dv(this);const I=()=>this._sizeChanged=!0;window.addEventListener("resize",I),this._disposeCallbacks.push(()=>window.removeEventListener("resize",I));const i=new ResizeObserver(o=>this._sizeChanged=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(o=>{this._isVisible=o[0].isIntersecting}),this._disposeCallbacks.push(()=>{var o;return(o=this._intersectionObserver)==null?void 0:o.disconnect()})}get version(){return jq}static get Current(){return _t.Current}static set Current(A){_t.Current=A}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(A){if(A!==this._resolutionScaleFactor&&typeof A=="number"){if(A<=0){console.error("Invalid resolution scale factor",A);return}this._resolutionScaleFactor=A,this.updateSize()}}calculateBoundingClientRect(){if(this.isInAR){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){var A;return((A=this.renderer.xr)==null?void 0:A.isPresenting)||!1}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get xrSession(){var A;return(A=this.renderer.xr)==null?void 0:A.getSession()}get xrFrame(){return this._xrFrame}get arOverlayElement(){const A=this.domElement;return typeof A.getAROverlayContainer=="function"?A.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}get mainCamera(){if(this.mainCameraComponent){const A=this.mainCameraComponent;return A.cam||A.buildCamera(),A.cam}return null}get rendererData(){return this.sceneLighting}get isCreated(){return this._isCreated}internalOnUpdateVisible(){var A,e;(A=this._intersectionObserver)==null||A.disconnect(),(e=this._intersectionObserver)==null||e.observe(this.domElement)}updateSize(){var A,e,g;if(!this.isManagedExternally&&((A=this.renderer.xr)==null?void 0:A.isPresenting)===!1){this._sizeChanged=!1;const I=this.resolutionScaleFactor,i=this.domWidth*I,o=this.domHeight*I,C=this.mainCamera;this.updateAspect(C),this.renderer.setSize(i,o),this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.composer&&((e=this.composer.setSize)==null||e.call(this.composer,i,o),"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&((g=this.composer.setPixelRatio)==null||g.call(this.composer,window.devicePixelRatio)))}}updateAspect(A,e,g){if(!A)return;e===void 0&&(e=this.domWidth),g===void 0&&(g=this.domHeight);const I=A.aspect;A.aspect=e/g,I!==A.aspect&&A.updateProjectionMatrix()}async onCreate(A,e){try{return this._isCreating=!0,await this.internalOnCreate(A,e)}finally{this._isCreating=!1}}clear(){var A;(A=this.scene)!=null&&A.children.length&&(Qs(this.scene,!0,!0),this.scene=new Di),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear())}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){var A,e,g;this.clear(),(A=this.renderer)==null||A.setAnimationLoop(null),this.isManagedExternally||(e=this.renderer)==null||e.dispose();for(const I of this._disposeCallbacks)try{I()}catch(i){console.error("Error in on dispose callback:",i,I)}(g=this.domElement)!=null&&g.parentElement&&this.domElement.parentElement.removeChild(this.domElement),_t.dispatchCallback(ci.ContextDestroyed,this),_t.unregister(this)}registerCoroutineUpdate(A,e,g){return this.coroutines[g]||(this.coroutines[g]=[]),this.coroutines[g].push({comp:A,main:e}),e}unregisterCoroutineUpdate(A,e){if(!this.coroutines[e])return;const g=this.coroutines[e].findIndex(I=>I.main===A);g>=0&&this.coroutines[e].splice(g,1)}stopAllCoroutinesFrom(A){for(const e in this.coroutines){const g=this.coroutines[e];for(let I=g.length-1;I>=0;I--)g[I].comp===A&&g.splice(I,1)}}setCurrentCamera(A){var e;if(!A)return;if(A.cam||A.buildCamera(),!A.cam){console.warn("Camera component is missing camera",A);return}const g=this._cameraStack.indexOf(A);g>=0&&this._cameraStack.splice(g,1),this._cameraStack.push(A),this.mainCameraComponent=A;const I=A.cam;I.isPerspectiveCamera&&this.updateAspect(I),(e=this.mainCameraComponent)==null||e.applyClearFlagsIfIsActiveCamera()}removeCamera(A){if(!A)return;const e=this._cameraStack.indexOf(A);if(e>=0&&this._cameraStack.splice(e,1),this.mainCameraComponent===A&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const g=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(g)}}addBeforeRenderListener(A,e){var g;this._onBeforeRenderListeners.has(A.uuid)||(this._onBeforeRenderListeners.set(A.uuid,[]),A.onBeforeRender=this._createRenderCallbackWrapper(A,this._onBeforeRenderListeners)),(g=this._onBeforeRenderListeners.get(A.uuid))==null||g.push(e)}removeBeforeRenderListener(A,e){if(this._onBeforeRenderListeners.has(A.uuid)){const g=this._onBeforeRenderListeners.get(A.uuid),I=g.indexOf(e);I>=0&&g.splice(I,1)}}addAfterRenderListener(A,e){var g;this._onAfterRenderListeners.has(A.uuid)||(this._onAfterRenderListeners.set(A.uuid,[]),A.onAfterRender=this._createRenderCallbackWrapper(A,this._onAfterRenderListeners)),(g=this._onAfterRenderListeners.get(A.uuid))==null||g.push(e)}removeAfterRenderListener(A,e){if(this._onAfterRenderListeners.has(A.uuid)){const g=this._onAfterRenderListeners.get(A.uuid),I=g.indexOf(e);I>=0&&g.splice(I,1)}}_createRenderCallbackWrapper(A,e){return(g,I,i,o,C,s)=>{const a=e.get(A.uuid);if(a)for(let n=0;n<a.length;n++){const B=a[n];B(g,I,i,o,C,s)}}}get isRendering(){return this._isRendering}setRequireDepth(A){this._requireDepthTexture=A}setRequireColor(A){this._requireColorTexture=A}get depthTexture(){var A;return((A=this._renderTarget)==null?void 0:A.depthTexture)||null}get opaqueColorTexture(){var A;return((A=this._renderTarget)==null?void 0:A.texture)||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;const A=getComputedStyle(this.domElement);return A.visibility!=="hidden"&&A.display!=="none"&&A.opacity!=="0"}async internalOnCreate(A,e){var g;this.clear(),(g=this.renderer)==null||g.setAnimationLoop(null),await _E(1),we.Current=this,await _t.dispatchCallback(ci.ContextCreationStart,this);let I=!0;try{we.Current=this,A&&await A(this,e)}catch(i){console.error(i),I=!1}if(!I)return!1;this.internalOnUpdateVisible(),!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),we.Current=this,we.Current=this;for(let i=0;i<this.new_scripts.length;i++){const o=this.new_scripts[i];if(o.gameObject!==void 0&&o.gameObject!==null){o.gameObject.userData===void 0&&(o.gameObject.userData={}),o.gameObject.userData.components===void 0&&(o.gameObject.userData.components=[]);const C=o.gameObject.userData.components;C.includes(o)||C.push(o)}}if(this.post_setup_callbacks)for(let i=0;i<this.post_setup_callbacks.length;i++)we.Current=this,await this.post_setup_callbacks[i](this);if(!this.mainCamera){we.Current=this;let i=null;Qr(this.scene,o=>{const C=o;if(C!=null&&C.isCamera){if(Xh(C.gameObject),!C.activeAndEnabled)return;if(C.tag==="MainCamera")return i=C,!0;i=C}}),i?this.setCurrentCamera(i):!_t.dispatchCallback(ci.MissingCamera,this)&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}if(we.Current=this,Hu(this),!this.isManagedExternally&&this.composer&&this.mainCamera){const i=new zu(this.scene,this.mainCamera);this.renderer.setSize(this.domWidth,this.domHeight),this.composer.addPass(i),this.composer.setSize(this.domWidth,this.domHeight)}return this._sizeChanged=!0,this._stats&&(this._stats.showPanel(1),this.domElement.appendChild(this._stats.dom)),Lk&&su(this.scene,!0),this._isCreating=!1,this.restartRenderLoop(),this._dispatchReadyAfterFrame=!0,_t.dispatchCallback(ci.ContextCreated,this)}restartRenderLoop(){if(!this.renderer)return console.error("Can not start render loop without renderer"),!1;if(this._isCreating)return console.warn("Can not start render loop while creating context"),!1;const A=this.render.bind(this);return this.renderer.setAnimationLoop(A),!0}render(A,e){if(UI()||Lk||VV())try{this.internalRender(A,e)}catch(g){(UI()||Lk)&&g instanceof Error&&Hg("Exception during render-loop.<br/>See console for details.",co.Error),console.error(g),console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null),this.domElement.dispatchEvent(new CustomEvent("error",{detail:g}))}else this.internalRender(A,e)}internalRender(A,e){var g,I;if(this._xrFrame=e,this._currentFrameEvent=-1,this.isInXR===!1&&this.targetFrameRate!==void 0){if(this._accumulatedTime+=this._framerateClock.getDelta(),this._accumulatedTime<1/this.targetFrameRate)return;this._accumulatedTime=0}if((g=this._stats)==null||g.begin(),we.Current=this,!this.onHandlePaused()){for(we.Current=this,this.time.update(),lZ&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Hu(this),Tu(this.scene),Mb(this);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}if(this.pre_update_callbacks)for(const i in this.pre_update_callbacks)this.pre_update_callbacks[i]();this._currentFrameEvent=0;for(let i=0;i<this.scripts_earlyUpdate.length;i++){const o=this.scripts_earlyUpdate[i];o.activeAndEnabled&&o.earlyUpdate!==void 0&&(we.Current=this,o.earlyUpdate())}if(this.executeCoroutines(0),!this.onHandlePaused()){this._currentFrameEvent=1;for(let i=0;i<this.scripts_update.length;i++){const o=this.scripts_update[i];o.activeAndEnabled&&o.update!==void 0&&(we.Current=this,o.update())}if(this.executeCoroutines(1),!this.onHandlePaused()){this._currentFrameEvent=2;for(let i=0;i<this.scripts_lateUpdate.length;i++){const o=this.scripts_lateUpdate[i];o.activeAndEnabled&&o.lateUpdate!==void 0&&(we.Current=this,o.lateUpdate())}if(this.executeCoroutines(2),!this.onHandlePaused()){if(this.physics.engine){const i=this.time.deltaTime/1;for(let o=0;o<1;o++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);this.physics.engine.postStep()}if(!this.onHandlePaused()){if(this.isVisibleToUser){this._currentFrameEvent=3;for(let i=0;i<this.scripts_onBeforeRender.length;i++){const o=this.scripts_onBeforeRender[i];o.activeAndEnabled&&o.onBeforeRender!==void 0&&(we.Current=this,o.onBeforeRender(e))}if(this.executeCoroutines(3),this._sizeChanged&&this.updateSize(),this.pre_render_callbacks)for(const i in this.pre_render_callbacks)this.pre_render_callbacks[i]();this.isManagedExternally||(XV(this),this._currentFrameEvent=-1,this.renderNow(),this._currentFrameEvent=4);for(let i=0;i<this.scripts_onAfterRender.length;i++){const o=this.scripts_onAfterRender[i];o.activeAndEnabled&&o.onAfterRender!==void 0&&(we.Current=this,o.onAfterRender())}if(this.executeCoroutines(4),this.post_render_callbacks)for(const i in this.post_render_callbacks)this.post_render_callbacks[i]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),(I=this._stats)==null||I.end(),this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")))}}}}}}renderNow(A){return!A&&(A=this.mainCamera,!A)?!1:(this._isRendering=!0,this.renderRequiredTextures(),this.composer&&!this.isInXR?this.composer.render(this.time.deltaTime):A&&this.renderer.render(this.scene,A),this._isRendering=!1,!0)}onHandlePaused(){const A=this.evaluatePaused();if(this._wasPaused!==A){cZ&&console.log("Paused?",A,"context:"+this.alias);for(let e=0;e<this.scripts_pausedChanged.length;e++){const g=this.scripts_pausedChanged[e];g.activeAndEnabled&&g.onPausedChanged!==void 0&&(we.Current=this,g.onPausedChanged(A,this._wasPaused))}}return this._wasPaused=A,A}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new st(this.domWidth,this.domHeight),this._requireDepthTexture){const g=new lp(this.domWidth,this.domHeight);this._renderTarget.depthTexture=g}this._requireColorTexture&&(this._renderTarget.texture=new Ye,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=tt,this._renderTarget.texture.magFilter=tt,this._renderTarget.texture.format=mt)}const A=this._renderTarget;A.texture&&(A.texture.encoding=this.renderer.outputEncoding);const e=this.renderer.getRenderTarget();this.renderer.setRenderTarget(A),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(e)}executeCoroutines(A){if(this.coroutines[A]){const g=this.coroutines[A];for(let I=0;I<g.length;I++)try{const i=g[I];if(!i.comp||i.comp.destroyed||!i.main||i.comp.enabled===!1){dZ&&console.log("Removing coroutine",i.comp,i.comp.enabled),g.splice(I,1),--I;continue}const o=i.chained;if(o&&o.length>0){const a=o[o.length-1].next();if(a.done&&o.pop(),e(a)&&(i.chained||(i.chained=[]),i.chained.push(a.value)),!a.done)continue}const C=i.main.next();if(C.done===!0){g.splice(I,1),--I;continue}const s=C.value;if(e(s)){if(s.next().done)continue;i.chained||(i.chained=[]),i.chained.push(s)}}catch(i){console.error(i)}}function e(g){return!!(g&&g.next&&g.return)}}}const DZ=aA("debugaroverlay"),hr="ar",wv="quit-ar";class wZ{constructor(){r(this,"arContainer",null),r(this,"closeARCallback"),r(this,"currentSession",null),r(this,"registeredCloseEventElements",[]),r(this,"_createdAROnlyElements",[]),r(this,"_reparentedObjects",[]),this.closeARCallback=this.onRequestedEndAR.bind(this)}get ARContainer(){return this.arContainer}requestEndAR(){this.onRequestedEndAR()}onBegin(A,e,g){this.currentSession=g,this.arContainer=e,A.domElement.querySelectorAll(`.${hr}`).forEach(i=>{var o;i&&i!==this.arContainer&&(this._reparentedObjects.push({el:i,previousParent:i.parentElement}),(o=this.arContainer)==null||o.appendChild(i))});const I=e.getElementsByClassName(wv);if(!I||I.length<=0)console.warn(`Missing quit AR elements, creating fallback X button. Use class name '${wv}' to override.`),this.createFallbackCloseARButton(this.arContainer);else for(let i=0;i<I.length;i++){const o=I[i];o&&(o.addEventListener("click",this.closeARCallback),this.registeredCloseEventElements.push(o))}}onEnd(A){var e;for(const g of this._createdAROnlyElements)g.remove&&g.remove();for(const g of this._reparentedObjects){const I=g.el;(e=g.previousParent)==null||e.appendChild(I)}this._reparentedObjects.length=0,yS()&&setTimeout(()=>{const g=A.renderer.domElement;g&&A.domElement.insertBefore(g,A.domElement.firstChild);const I=document.querySelectorAll("*");for(var i=0;i<I.length;i++){const o=I[i];o&&o._displayChanged!==void 0&&o._displayWas!==void 0&&(o.style.display=o._displayWas)}},10)}findOrCreateARContainer(A){if(A.classList.contains(hr))return A;if(A.children)for(let I=0;I<A.children.length;I++){const i=A.children[I];if(!(!i||!i.classList)&&i.classList.contains(hr))return i}const e=document.getElementsByClassName(hr);if(e&&e.length>0)return e[0];DZ&&console.log("No overlay container found in document - generating new ony");const g=document.createElement("div");return g.classList.add(hr),g.style.position="absolute",g.style.width="100%",g.style.height="100%",g.style.display="flex",g.style.visibility="visible",A.appendChild(g)}onRequestedEndAR(){if(this.currentSession){this.currentSession.end(),this.currentSession=null;for(const A of this.registeredCloseEventElements)A.removeEventListener("click",this.closeARCallback);this.registeredCloseEventElements.length=0}}createFallbackCloseARButton(A){var e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","38px"),e.setAttribute("height","38px"),e.style.position="absolute",e.style.right="20px",e.style.top="40px",e.style.zIndex="9999",e.style.pointerEvents="auto",e.addEventListener("click",this.closeARCallback),A.appendChild(e),this._createdAROnlyElements.push(e);var g=document.createElementNS("http://www.w3.org/2000/svg","path");g.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),g.setAttribute("stroke","#ddd"),g.setAttribute("stroke-width","3px"),e.appendChild(g),this._createdAROnlyElements.push(g)}}class eA extends UA{constructor(){super(...arguments),r(this,"guid")}static isDestroyed(A){return pk(A)}static setActive(A,e,g=!0){A&&(Vh(A,e),Tu(A),e&&g&&Mb(we.Current,A))}static isActiveSelf(A){return ZB(A)}static isActiveInHierarchy(A){return Db(A)}static markAsInstancedRendered(A,e){wb(A,e)}static isUsingInstancing(A){return Yu(A)}static foreachComponent(A,e,g=!0){return Qr(A,e,g)}static instantiateSynced(A,e){return A?Ek(A,e):null}static instantiate(A,e=null){return Zh(A,e)}static destroySynced(A,e,g=!0){if(!A)return;const I=A;e=e??we.Current,Fu(I,e.connection,g)}static destroy(A,e=!0,g=!0){return Qs(A,e,g)}static add(A,e,g){if(!(!A||!e)){if(A===e){console.warn("Can not add object to self",A);return}g||(g=we.Current),e.add(A),Vh(A,!0),Tu(A),g?eA.foreachComponent(A,I=>{Dk(I,g),!I.__internalDidAwakeAndStart&&g.new_script_start.includes(I)===!1&&g.new_script_start.push(I)},!0):console.warn("Missing context")}}static remove(A){var e;A&&((e=A.parent)==null||e.remove(A),Vh(A,!1),Tu(A),eA.foreachComponent(A,g=>{zV(g)},!0))}static invokeOnChildren(A,e,...g){this.invoke(A,e,!0,g)}static invoke(A,e,g=!1,...I){A&&this.foreachComponent(A,i=>{const o=i[e];o&&typeof o=="function"&&o?.call(i,...I)},g)}static addNewComponent(A,e,g=!0){const I=new e;return Br(A,I,g),I}static addComponent(A,e){return this.moveComponent(A,e)}static moveComponent(A,e){return lk(A,e)}static removeComponent(A){return ck(A.gameObject,A),A}static getOrAddComponent(A,e){return Ku(A,e)}static getComponent(A,e){return A===null?null:VB(A,e)}static getComponents(A,e,g=null){return A===null?g??[]:Th(A,e,g)}static findByGuid(A,e){return zh(A,e)}static findObjectOfType(A,e,g=!0){return nb(A,e??we.Current,g)}static findObjectsOfType(A,e){const g=[];return rb(A,g,e),g}static getComponentInChildren(A,e){return zB(A,e)}static getComponentsInChildren(A,e,g=null){return _h(A,e,g??void 0)}static getComponentInParent(A,e){return Oh(A,e)}static getComponentsInParent(A,e,g=null){return Ju(A,e,g)}static getAllComponents(A){var e;return[...(e=A.userData)==null?void 0:e.components]}static*iterateComponents(A){var e;const g=(e=A?.userData)==null?void 0:e.components;if(g&&Array.isArray(g))for(let I=0;I<g.length;I++)yield g[I]}}var Eg;let Ja=(Eg=class{constructor(){r(this,"__context"),r(this,"__name"),r(this,"gameObject"),r(this,"guid","invalid"),r(this,"sourceId"),r(this,"__didAwake",!1),r(this,"__didStart",!1),r(this,"__didEnable",!1),r(this,"__isEnabled"),r(this,"__destroyed",!1),r(this,"_worldPosition"),r(this,"_worldQuaternion"),r(this,"_worldEuler"),r(this,"_worldRotation"),r(this,"_eventListeners",new Map),this.__internalNewInstanceCreated()}get isComponent(){return!0}get context(){return this.__context??we.Current}set context(t){this.__context=t}get scene(){return this.context.scene}get layer(){var t,A;return(A=(t=this.gameObject)==null?void 0:t.userData)==null?void 0:A.layer}get name(){var t,A;return(t=this.gameObject)!=null&&t.name?this.gameObject.name:(A=this.gameObject)==null?void 0:A.userData.name}set name(t){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=t,this.__name=t):this.__name=t}get tag(){var t;return(t=this.gameObject)==null?void 0:t.userData.tag}set tag(t){this.gameObject&&(this.gameObject.userData.tag=t)}get static(){var t;return(t=this.gameObject)==null?void 0:t.userData.static}get hideFlags(){var t;return(t=this.gameObject)==null?void 0:t.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;const t=this.gameObject[Bs];return t===void 0?!0:t}set __isActiveInHierarchy(t){this.gameObject&&(this.gameObject[Bs]=t)}awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(t,A=ki.Update){return this.context.registerCoroutineUpdate(this,t,A)}stopCoroutine(t,A=ki.Update){this.context.unregisterCoroutineUpdate(t,A)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}__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(t){return this.__destroyed?(UI()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(t!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(t){if(this.__didAwake){if(!this.__didEnable){t!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){var t;this.__destroyed||(this.__destroyed=!0,(t=this.destroy)==null||t.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this})),Cb(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(t){if(this.__destroyed){UI()&&console.warn(`[Needle Engine Dev] Trying to ${t?"enable":"disable"} destroyed component`);return}if(typeof t=="number"&&(t>=.5?t=!0:t=!1),!this.__didAwake){this.__isEnabled=t;return}t?this.__internalEnable():this.__internalDisable()}get worldPosition(){return this._worldPosition||(this._worldPosition=new f),ye(this.gameObject,this._worldPosition),this._worldPosition}set worldPosition(t){tg(this.gameObject,t)}setWorldPosition(t,A,e){Eg._worldPositionBuffer.set(t,A,e),this.worldPosition=Eg._worldPositionBuffer}get worldQuaternion(){return this._worldQuaternion||(this._worldQuaternion=new GA),Ng(this.gameObject,this._worldQuaternion)}set worldQuaternion(t){zI(this.gameObject,t)}setWorldQuaternion(t,A,e,g){Eg._worldQuaternionBuffer.set(t,A,e,g),this.worldQuaternion=Eg._worldQuaternionBuffer}get worldEuler(){return this._worldEuler||(this._worldEuler=new fg),this._worldEuler.setFromQuaternion(this.worldQuaternion),this._worldEuler}set worldEuler(t){var A;this._worldQuaternion||(this._worldQuaternion=new GA),(A=this._worldQuaternion)==null||A.setFromEuler(t),this.worldQuaternion=this._worldQuaternion}get worldRotation(){const t=this.worldEuler;this._worldRotation||(this._worldRotation=new f);const A=this._worldRotation;return A.set(t.x,t.y,t.z),A.x=XA.toDegrees(A.x),A.y=XA.toDegrees(A.y),A.z=XA.toDegrees(A.z),A}set worldRotation(t){this.setWorldRotation(t.x,t.y,t.z,!0)}setWorldRotation(t,A,e,g=!0){g&&(t=XA.toRadians(t),A=XA.toRadians(A),e=XA.toRadians(e)),Eg._worldEulerBuffer.set(t,A,e),Eg._worldQuaternionBuffer.setFromEuler(Eg._worldEulerBuffer),this.worldQuaternion=Eg._worldQuaternionBuffer}get forward(){return Eg._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}get right(){return Eg._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}get up(){return Eg._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}addEventListener(t,A){this._eventListeners[t]=this._eventListeners[t]||[],this._eventListeners[t].push(A)}removeEventListener(t,A){if(!this._eventListeners[t])return;const e=this._eventListeners[t].indexOf(A);e>=0&&this._eventListeners[t].splice(e,1)}dispatchEvent(t){if(!this._eventListeners[t.type])return!1;const A=this._eventListeners[t.type];for(let e=0;e<A.length;e++)A[e](t);return!1}},r(Eg,"_worldPositionBuffer",new f),r(Eg,"_worldQuaternionBuffer",new GA),r(Eg,"_worldEulerBuffer",new fg),r(Eg,"_tempQuaternionBuffer2",new GA),r(Eg,"_forward",new f),r(Eg,"_right",new f),r(Eg,"_up",new f),Eg);class RA extends Ja{}const yZ=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:RA,Component:Ja,GameObject:eA},Symbol.toStringTag,{value:"Module"})),SZ='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',fZ=new Blob([SZ],{type:"image/svg+xml;charset=utf-8"}),kZ=URL.createObjectURL(fZ),yv=kZ,cr=aA("debuglicense"),xk="basic";cr&&console.log("License Type: "+xk);function qa(){switch(xk){case"pro":case"enterprise":return!0}return!1}function Sv(){switch(xk){case"indie":return!0}return!1}function fv(){return qa()||Sv()}_t.registerCallback(ci.ContextRegistered,t=>{GZ(t.context)});async function GZ(t){try{if(qa()!==!0)return Tk(t)}catch(A){return cr&&console.log("License check failed",A),Tk(t)}cr&&Tk(t)}const kv="needle-license-element",Yk=5e3,Hk=200;function Tk(t){MZ(),t.domElement.addEventListener("ready",()=>{setTimeout(()=>{mZ(t)},1e3)}),FZ()}function mZ(t){const A=RZ(),e=UZ(),g=setInterval(()=>{if(!A)return;const s=t.domElement.shadowRoot||t.domElement;A.parentNode!==s&&(s.appendChild(A),e&&s.appendChild(e))},100);let I=`<img class="logo" src="${yv}" style="width: 40px; height: 40px; margin-right: 2px; vertical-align: middle; margin-bottom: 2px;"/>`;const i=document.createElement("div");i.innerHTML=I,i.classList.add("logo"),A.appendChild(i);const o=document.createElement("div");o.classList.add("text"),A.appendChild(o),A.title="Needle Engine",fv()||(A.title+=" non commercial version"),A.addEventListener("click",()=>{globalThis.open("https://needle.tools","_blank")});const C=Yk+Hk;setTimeout(()=>{clearInterval(g),A?.remove(),e?.remove()},C)}let Gv=0;async function MZ(t){const A=Date.now();if(A-Gv<2e3)return;Gv=A,console.log("%c Needle Engine \u2014 non commercial version",`
|
|
3837
3837
|
font-size: 18px;
|
|
3838
3838
|
background-size: 20px;
|
|
3839
3839
|
background-position: left top;
|
|
@@ -4558,7 +4558,7 @@ void main() {
|
|
|
4558
4558
|
`){super("lineBreak",A,!0),this._newLineBreakability=null}update(A,e){this._needsProcess=!0}process(A){const e=A._whiteSpace._newLineBreakability;if(A._inlines._value)for(let g=0;g<A._inlines._value.length;g++){const I=A._inlines._value[g],i=I.char;let o=null;i!==void 0&&(e!=="nowrap"&&(this._value.includes(i)||i.match(/\s/g))&&(o="possible"),i.match(/\n/g)&&(o=e)),I.lineBreak=o}}get value(){return this._value}}class sH extends Qt{constructor(){super("layouter",null,!1),this._value=null}update(A,e){this._value=A._parent.find(g=>g.isUI&&g.isText),this._needsProcess=!0}process(A){this._value&&(this._value._layouter._needsProcess=!0)}}class ZAA extends Rc{constructor(A){super("backgroundColor",A,!1),this._allowsInherit=!1,this._input=0}computeOutputValue(A){this._input==="inherit"?this._value.set(this.getInheritedInput(A)):this._value.set(this._input)}}class aH extends gY{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class nH extends IY{constructor(){super()}computeOutputValue(A){const e=this.getInheritedInput(A),g=XAA[e];g?this._value=g:this._value=e}}const XAA={light:"100",normal:"400",bold:"700",bolder:"900"};class rH extends rY{constructor(){super("fontFamily","inherit",!0),this._input="inherit",this._needsUpdate=!0,this._allowsInherit=!1}computeOutputValue(A){let e=this._inheritedInput;if(e==="inherit"&&(e=this.getInheritedInput(A)),e instanceof _D)this._value=e,A._font._needsUpdate=!0;else if(typeof e=="string"){const g=Sr.getFontFamily(e);g?(this._value=g,A._font._needsUpdate=!0):console.warn(`(.style) fontFamily, the font '${e}' is not registered. Aborted.`)}else console.warn("(.style) fontFamily requires a registered fontFamily instance, or the id of a registered fontFamily."),console.warn("If you want to set a specific font, please use .font property instead.")}get value(){return this._value}}class Om extends QY{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited,this._whiteSpacedContent="",this._stringCollapser=this.emptyStrategyLogic,this._inlineCollapser=this.emptyStrategyLogic,this._inlineWrapper=this.emptyStrategyLogic}_computeFromInherited(A){switch(super._computeFromInherited(A),this._newLineBreakability=$AA(this._value),this._value){case"nowrap":case"normal":this._stringCollapser=AeA;break;case"pre-line":this._stringCollapser=QH;break;default:this._stringCollapser=eeA}switch(this._value){case"pre-line":case"nowrap":case"normal":this._inlineCollapser=oeA;break;case"pre-wrap":this._inlineCollapser=ieA;break;default:this._inlineCollapser=CeA}switch(this._value){case"pre-line":case"pre-wrap":case"normal":this._inlineWrapper=teA;break;case"pre":this._inlineWrapper=geA;break;default:this._inlineWrapper=IeA}this._needsProcess=!0}process(A){A.isInline&&!A.isInlineBlock&&(this._whiteSpacedContent=this._stringCollapser(A._textContent._value),A._glyphs._needsProcess=!0)}}const BH={" ":" ","\n":`
|
|
4559
4559
|
`,"\r":"\r"," ":" "},$AA=function(t){switch(t){case"pre":case"pre-wrap":case"pre-line":return"mandatory"}return null};function AeA(t){return QH(t.replace(/\n/g," "))}function QH(t){return t.replace(/[ ]{2,}/g," ")}function eeA(t){return t}function teA(t,A,e,g){const I=t[A];if(I.lineBreak==="mandatory"||e+I.xadvance+I.xoffset+I.kerning>g.INNER_WIDTH)return!0;const i=cH(t,A,g);return seA(t[A-1],e,i,g)}function geA(t,A,e,g){return t[A].lineBreak==="mandatory"}function IeA(){return!1}function ieA(t){if(!t[0])return 0;const A=t[0],e=t[t.length-1];return A.char&&A.char===`
|
|
4560
4560
|
`&&t.length>1&&hH([A],t[1]),e.char&&e.char===`
|
|
4561
|
-
`&&t.length>1&&EH([e],t[t.length-2]),A.offsetX}function oeA(t){if(!t[0])return 0;let A=[],e;for(let g=0;g<t.length;g++){const I=t[g];if(I.char&&BH[I.char]&&t.length>g){A.push(I),e=t[g+1];continue}break}hH(A,e),A=[],e=null;for(let g=t.length-1;g>0;g--){const I=t[g];if(I.char&&BH[I.char]&&g>0){A.push(I),e=t[g-1];continue}break}return EH(A,e),t[0].offsetX}function CeA(t){return t[0]?t[0].offsetX:0}function EH(t,A){if(A)for(let e=0;e<t.length;e++){const g=t[e];g.fontFactor=0,g.offsetX=A.offsetX+A.cumulativeWidth,g.cumulativeWidth=0}}function hH(t,A){if(A)for(let e=0;e<t.length;e++){const g=t[e];g.fontFactor=0,g.offsetX=A.offsetX,g.cumulativeWidth=0}}function cH(t,A,e,g){if(g=g||0,!t[A])return g;const I=t[A];return I.lineBreak?g+I.xadvance:cH(t,A+1,e,g+I.xadvance+I.xoffset+I.kerning+e.LETTERSPACING)}function seA(t,A,e,g){return!t||!t.char||A+e<g.INNER_WIDTH?!1:g.BREAKON.indexOf(t.char)>-1}class lH extends EY{constructor(){super(),this._input="inherit",this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A),A._fontSize._needsProcess=!0,A._layouter._needsProcess=!0}}class dH extends Ft{constructor(){super("fontSize","inherit",!0),this._allowsInherit=!1}computeOutputValue(A){this._value=this._inheritedInput,A._font._fontVariant&&(A._bounds._needsProcess=!0,A._layouter._needsProcess=!0)}process(A){if(!A._font._fontVariant||!A._font._fontVariant.isReady)return;const e=this._value/A._font._fontVariant.typographic.size,g=A._inlines._value;for(let I=0;I<g.length;I++){const i=g[I];i.resetOffsets(),i.fontSize=this._value,i.fontFactor=e}}get value(){return this._value}}class pH extends hY{constructor(){super("segments",1,!1),this._notInheritedValue=void 0}update(A,e){this._notInheritedValue=this._value,this._notInheritedValue==="inherit"&&(this._notInheritedValue=this.getInheritedInput(A)),A._layouter._needsUpdate=!0}set value(A){this._value!==A&&(this._value=A,this._needsUpdate=!0)}get value(){return this._value==="inherit"?this._notInheritedValue:this._value}}class aeA extends pH{constructor(){super(),this._value="inherit"}}class neA extends PD{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A),A._parent._value._layouter._needsProcess=!1}process(A){if(this._value!=="none"){const e=A._whiteSpace._whiteSpacedContent,g=A._inlines._value;for(let I=1;I<g.length;I++){const i=e[I-1]+e[I];g[I].kerning=A._font._fontVariant.getKerningAmount(i)}}}}class uH extends Qt{constructor(){super("children",null,!1),this._uis=[]}update(A,e){}process(A){}_compute(A){}dispose(){}}function reA(t,A=!1){const e=t[0].index!==null,g=new Set(Object.keys(t[0].attributes)),I=new Set(Object.keys(t[0].morphAttributes)),i={},o={},C=t[0].morphTargetsRelative,s=new $A.BufferGeometry;let a=0;for(let n=0;n<t.length;++n){const B=t[n];let Q=0;if(e!==(B.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const E in B.attributes){if(!g.has(E))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+'. All geometries must have compatible attributes; make sure "'+E+'" attribute exists among all geometries, or in none of them.'),null;i[E]===void 0&&(i[E]=[]),i[E].push(B.attributes[E]),Q++}if(Q!==g.size)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+". Make sure all geometries have the same number of attributes."),null;if(C!==B.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const E in B.morphAttributes){if(!I.has(E))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+". .morphAttributes must be consistent throughout all geometries."),null;o[E]===void 0&&(o[E]=[]),o[E].push(B.morphAttributes[E])}if(s.userData.mergedUserData=s.userData.mergedUserData||[],s.userData.mergedUserData.push(B.userData),A){let E;if(e)E=B.index.count;else if(B.attributes.position!==void 0)E=B.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+". The geometry must have either an index or a position attribute"),null;s.addGroup(a,E,n),a+=E}}if(e){let n=0;const B=[];for(let Q=0;Q<t.length;++Q){const E=t[Q].index;for(let h=0;h<E.count;++h)B.push(E.getX(h)+n);n+=t[Q].attributes.position.count}s.setIndex(B)}for(const n in i){const B=DH(i[n]);if(!B)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+n+" attribute."),null;s.setAttribute(n,B)}for(const n in o){const B=o[n][0].length;if(B===0)break;s.morphAttributes=s.morphAttributes||{},s.morphAttributes[n]=[];for(let Q=0;Q<B;++Q){const E=[];for(let c=0;c<o[n].length;++c)E.push(o[n][c][Q]);const h=DH(E);if(!h)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+n+" morphAttribute."),null;s.morphAttributes[n].push(h)}}return s}function DH(t){let A,e,g,I=0;for(let C=0;C<t.length;++C){const s=t[C];if(s.isInterleavedBufferAttribute)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported."),null;if(A===void 0&&(A=s.array.constructor),A!==s.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(e===void 0&&(e=s.itemSize),e!==s.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(g===void 0&&(g=s.normalized),g!==s.normalized)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;I+=s.array.length}const i=new A(I);let o=0;for(let C=0;C<t.length;++C)i.set(t[C].array,o),o+=t[C].array.length;return new $A.BufferAttribute(i,e,g)}class BeA extends Qt{constructor(){super("renderer")}render(A){if(!A._inlines._value||!A._inlines._value.length)return;const e=A._inlines._value.map(I=>A._font._fontVariant.getGeometricGlyph(I,A).translate(I.offsetX,I.offsetY,0)),g=reA(e);A.setFontMesh(new $A.Mesh(g,A.fontMaterial)),A._fontMesh.renderOrder=1/0}}class QeA extends Bm{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!1}computeOutputValue(A){this._value=this._inheritedInput,A._layouter._needsProcess=!0}}class LE extends bc{constructor(A={}){const e={};LE.definePropertiesValues(e,A),super(e,A),r(this,"_rebuildParentUI",()=>{super._rebuildParentUI(),this._layouter._needsUpdate=!0}),LE.init(this)}add(A){const e=[];for(let g=0;g<arguments.length;g++){const I=arguments[g];!I.isUI||I.isInline?(e.push(I),I.position.z=.005):console.warn("Block element can only contain Box elements.",I)}return super.add(...e)}set textContent(A){this._textContent.value=A}get textContent(){return this._textContent._value}set invertAlpha(A){this._invertAlpha.value=A}get invertAlpha(){return this._invertAlpha._value}static definePropertiesValues(A,e){A.children||(A.children=uH),A.textContent||(A.textContent=jAA),A.glyphs||(A.glyphs=VAA),A.inlines||(A.inlines=WAA),A.layouter||(A.layouter=sH),A.renderer||(A.renderer=BeA),A.fontFamily||(A.fontFamily=rH),A.fontWeight||(A.fontWeight=nH),A.fontStyle||(A.fontStyle=aH),A.fontSize||(A.fontSize=dH),A.color||(A.color=zAA),A.backgroundColor||(A.backgroundColor=ZAA),A.lineBreak||(A.lineBreak=CH),A.letterSpacing||(A.letterSpacing=lH),A.whiteSpace||(A.whiteSpace=Om),A.segments||(A.segments=aeA),A.textAlign||(A.textAlign=QeA),A.fontKerning||(A.fontKerning=neA)}static init(A){Object.defineProperties(A,{isInline:{configurable:!1,enumerable:!0,value:!0}})}}class EeA extends tY{constructor(){super("textContent",null,!1),this._needsUpdate=!1}set value(A){this._value!==A&&(this._value=A,this._needsUpdate=!0)}update(A,e){this._needsUpdate=!1;for(let g=A.children.length-1;g>=0;g--){const I=A.children[g];I.isUI&&(A.remove(I),I.clear())}A._children._uis=[],this._value&&A.add(new LE({name:"anonymousInline",textContent:this._value}))}}class heA extends Array{constructor(...A){super(...A),this.width=0,this.height=0}}class ceA extends Qt{constructor(){super("layouter",null,!1),this._value=null}update(A,e){}process(A){let e=A._width._value;A._width._auto?e=1/0:e=A._bounds._innerWidth;const g=A._lineHeight._value,I=new heA(new oH);let i=0;A._children._inlines.forEach(B=>{if(!B._inlines.value)return;this._resetInlines(B);const Q=B._fontSize._value,E=B._letterSpacing._value*Q,h=B._whiteSpace._value,c=B._lineBreak._value,l={WHITESPACE:h,LETTERSPACING:E,BREAKON:c,INNER_WIDTH:e},d=B._whiteSpace._inlineWrapper;i+=B._margin._value.w+B._padding._value.w,B._inlines.value.forEach((u,p,D)=>{const y=I[I.length-1];if(d(D,p,i,l)){if(I.push(new oH(u)),u.offsetX=u.xoffset,u.width===0){i=0;return}u.cumulativeWidth=u.xadvance+E,i=u.cumulativeWidth;return}I[I.length-1].push(u),u.offsetX=i+u.xoffset+u.kerning,u.cumulativeWidth=u.xadvance+u.kerning+E,i+=u.cumulativeWidth,y.length-1===1&&y[y.length-2].width===0&&(u.offsetX-=u.xoffset,i-=u.xoffset)}),i+=B._margin._value.y+B._padding._value.y});const o=A._whiteSpace._inlineCollapser;let C=0,s=0,a=0;I.forEach((B,Q)=>{const E=o(B);let h=0,c=0;if(B.forEach(l=>{h=Math.max(h,l.lineHeight),c=Math.max(c,l.lineBase),l.offsetX-=E}),B.lineHeight=h,B.lineBase=c,Q===0?a=-(h*g-h)*.5:a-=I[Q-1].lineHeight*g,B.y=a,B.x=0,B.forEach(l=>{l.offsetY=a-l.anchor,l.lineHeight<B.lineHeight&&(l.offsetY-=B.lineBase-l.lineBase)}),s+=B.lineHeight*g,B.width=0,B[0]){const l=B[B.length-1];B.width=l.offsetX+l.cumulativeWidth+l.paddingRight+l.marginRight+B[0].offsetX,C=Math.max(C,B.width)}}),I.height=s,I.width=C,this._value=I,e===1/0&&A._bounds.setChildrenWidth(A,I.width),A._height._auto&&A._bounds.setChildrenHeight(A,I.height);const n=A._parent._value;n&&(n._autoSize._needsProcess=!0,n._flexDirection._needsProcess=!0),A._inlineJustificator._needsProcess=!0,A._textAlign._needsProcess=!0,A._overflow._needsUpdate=!0}_resetInlines(A){A._fontSize.process(A)}}class leA extends Bm{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(A){this._value=this._inheritedInput,this._needsProcess=!0}process(A){deA(A),A._renderer._needsRender=!0}}function deA(t){const A=t._layouter._value,e=t._textAlign._value,g=t._bounds._innerWidth;for(let I=0;I<A.length;I++){const i=A[I],o=peA(t,i,I===A.length-1),C=t._padding._value,s=t._borderWidth._value,a=(-C.w+C.y)/2+(-s.w+s.y)/2;i.x+=o;for(let n=0;n<i.length;n++)i[n].offsetX+=o-a}if(e.indexOf("justify")===0)for(let I=0;I<A.length;I++){const i=A[I];if(e.indexOf("-")!==-1&&I===A.length-1)return;const o=g-i.width;if(o<=0)return;let C=0;for(let B=1;B<i.length-1;B++)C+=i[B].char===" "?1:0;const s=o/C;let a=1;e==="justify-right"&&(i.reverse(),a=-1);let n=0;for(let B=1;B<=i.length-1;B++){const Q=i[B];Q.offsetX+=n*a,n+=Q.char===" "?s:0}e==="justify-right"&&i.reverse()}}function peA(t,A,e){switch(t._textAlign._value){case"justify-left":case"justify":case"left":return-t._bounds._innerWidth/2;case"justify-right":case"right":return-A.width+t._bounds._innerWidth/2;case"center":return-A.width/2;case"justify-center":return e?-A.width/2:-t._bounds._innerWidth/2;default:console.warn(`textAlign: '${t._textAlign._value}' is not valid`)}}class ueA extends Qm{constructor(){super(),this._value=this._input="column",this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(A){this._value=this._inheritedInput}}class DeA extends BY{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class weA extends PD{constructor(){super(),this._value=this._input=this.getDefaultValue(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A)}}class yeA extends tH{constructor(){super(),this._innerWidth=1/0,this._innerHeight=0}}class SeA extends Qt{constructor(){super("children",null,!1),r(this,"_sortOrder",(A,e)=>A._order._value<e._order._value?-1:A._order._value>e._order._value?1:this._uis.indexOf(A)<this._uis.indexOf(e)?-1:1),this._uis=[],this._inlines=[],this._boxes=[]}update(A,e){this._compute(A),this._needsProcess=!0}process(A){this._compute(A),A._overflow._needsRender=!0}_compute(A){this._uis=A.children.filter(e=>e.visible&&e.isUI),this._inlines=this._uis.filter(e=>e.isInline).sort(this._sortOrder)}dispose(){this._inlines=null}}class feA extends Qt{constructor(){super("autosize")}process(A){if(A._layouter._value&&A._layouter._value.length){const e=A._layouter._value,g=A._padding._value,I=A._borderWidth._value;A._width._auto&&A._bounds.setOffsetWidth(A,e.width+g.w+g.y+I.w+I.y),A._height._auto&&A._bounds.setOffsetHeight(A,e.height+g.x+g.z+I.x+I.z)}}}class keA extends iH{constructor(){super("renderer"),this._needsUpdate=!1}render(A){super.render(A);for(const e of A._children._inlines)e._renderer.render(e);A.performAfterUpdate()}}class ud extends dd{constructor(A={},e={}){ud.definePropertiesValues(e,A),super(e,A),ud.init(this)}add(A){const e=[];let g=!1;for(let I=0;I<arguments.length;I++){const i=arguments[I];!i.isUI||i.isInline?(i.isInline&&(g=!0),e.push(i)):console.warn("Block element can only contain Box elements.",i)}return e.length>0&&super.add(...e),g&&(this._children._needsUpdate=!0,this._layouter._needsProcess=!0),this}set textContent(A){this._textContent.value=A}get textContent(){return super.textContent}set invertAlpha(A){this._invertAlpha.value=A}get invertAlpha(){return this._invertAlpha._value}get lines(){return this._layouter._value}static definePropertiesValues(A,e){A.flexDirection=ueA,A.justifyContent=Em,A.alignItems=rm,A.bounds=yeA,A.autoSize=feA,A.renderer=keA,A.children||(A.children=SeA),A.textContent||(A.textContent=EeA),A.layouter||(A.layouter=ceA),A.lineHeight||(A.lineHeight=DeA),A.textAlign||(A.textAlign=leA),A.whiteSpace||(A.whiteSpace=Om),A.fontKerning||(A.fontKerning=weA),A.segments||(A.segments=pH),e.width||(e.width="100%"),e.fontSide||(e.fontSide=0)}static init(A){Object.defineProperties(A,{isText:{configurable:!1,enumerable:!0,value:!0}})}}class GeA extends Qt{constructor(){super("inlines",null,!1),this._value=[]}process(A){this._value[0].paddingLeft=A._padding._value.w,this._value[0].marginLeft=A._margin._value.w;const e=this._value.length-1;this._value[e].paddingRight=A._padding._value.y,this._value[e].marginRight=A._margin._value.y}}class meA extends Qt{constructor(){super("renderer")}render(A){A._backgroundMesh||A.setBackgroundMesh(new IH(A)),A._backgroundMesh.position.x=A._inlines._value[0].offsetX+A._inlines._value[0].width/2,A._backgroundMesh.position.y=A._inlines._value[0].offsetY+A._inlines._value[0].lineBase/2,A._bounds.render(A)}}class MeA extends Qt{constructor(){super("bounds",null,!1),this._size=new $A.Vector3(1,1,1),this._offsetWidth=0,this._offsetHeight=0,this._innerWidth=0,this._innerHeight=0}update(A,e){this.output(e),this._needsProcess=!0}process(A){this._offsetWidth=this._innerWidth=A._inlines._value[0].width,this._offsetHeight=this._innerHeight=A._inlines._value[0].height,this._needsRender=!0,A._borderWidth._needsRender=!0,A._borderRadius._needsRender=!0}render(A){this._size.x=this._offsetWidth,this._size.y=this._offsetHeight}output(A){A.size=this._size}}class Dd extends bc{constructor(A={}){const e={};Dd.definePropertiesValues(e,A),super(e,A),Dd.init(this)}clear(){for(const A of this._inlines._value)A.clear();return super.clear()}bindBackgroundMeshProperties(){this._backgroundMesh.raycast=()=>{},this._bounds._size=this._backgroundMesh.scale,this._bounds._needsUpdate=!0}unbindBackgroundMeshProperties(){this._bounds._size=new $A.Vector3(1,1,1),this._bounds._needsUpdate=!0}add(A){const e=[];for(let g=0;g<arguments.length;g++){const I=arguments[g];I.isUI?console.warn("ThreeMeshUI::InlineBlockElement cannot contains UI Elements.",I):(e.push(I),I.position.z=.005)}return super.add(...e)}static definePropertiesValues(A,e){A.children||(A.children=uH),A.bounds||(A.bounds=MeA),A.inlines||(A.inlines=GeA),A.layouter||(A.layouter=sH),A.renderer||(A.renderer=meA),A.fontFamily||(A.fontFamily=rH),A.fontWeight||(A.fontWeight=nH),A.fontStyle||(A.fontStyle=aH),A.fontSize||(A.fontSize=dH),A.backgroundColor||(A.backgroundColor=$x),A.lineBreak||(A.lineBreak=CH),A.letterSpacing||(A.letterSpacing=lH),A.whiteSpace||(A.whiteSpace=Om),A.fontKerning||(A.fontKerning=PD),e.backgroundSize||(e.backgroundSize="cover"),e.width||(e.width="100%"),e.height||(e.height="100%"),e.boxSizing||(e.boxSizing="border-box")}static init(A){Object.defineProperties(A,{isInline:{configurable:!1,enumerable:!0,value:!0},isInlineBlock:{configurable:!1,enumerable:!0,value:!0}}),A._inlines._value=[new ReA(A)],A.backgroundMaterial=new eH,A._renderer.render(A)}}class ReA extends CY{constructor(A){super(),this._uiElement=A}get xadvance(){const A=this._uiElement._padding._value,e=this._uiElement._width;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.w+A.y+e.value}get width(){const A=this._uiElement._width;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get height(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get anchor(){return this.height}get lineHeight(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get lineBase(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}clear(){this._uiElement=null}}class wH{constructor(A){this._subject=A}attach(){console.error(`Behavior::attach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}act(){throw new Error(`Behavior::act() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}detach(){console.error(`Behavior::detach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}clear(){}}const yH=()=>ew.update(),SH={BaseProperty:Qt,Block:pd,Text:ud,Inline:LE,InlineBlock:Dd,MeshUIBaseElement:bc,FontLibrary:Sr,update:yH,MSDFFontMaterialUtils:Eo,ShaderChunkUI:AH,Behavior:wH,FontVariant:Mc};typeof global<"u"&&(global.ThreeMeshUI=SH);const UeA=SH;var FeA=lg.w8,fH=lg.cg,Pm=lg.gO,NeA=lg.wb,jm=lg.zV,KeA=lg.HS,JeA=lg.Ec,gw=lg.gF,qeA=lg.ol,beA=lg.pz,veA=lg.tx,LeA=lg.hj,xeA=lg.FV,YeA=lg.sV,kH=lg.xv,HeA=lg.mx,TeA=lg.gE,_eA=lg.ZP,GH=lg.Vx;const mH=Object.freeze(Object.defineProperty({__proto__:null,BaseProperty:FeA,Behavior:fH,Block:Pm,DefaultValues:NeA,FontLibrary:jm,FontVariant:KeA,InheritableProperty:JeA,Inline:gw,InlineBlock:qeA,InlineGlyph:beA,MSDFFontMaterialUtils:veA,MaterialTransformers:LeA,MeshUIBaseElement:xeA,ShaderChunkUI:YeA,Text:kH,TypographicFont:HeA,TypographicGlyph:TeA,default:_eA,update:GH},Symbol.toStringTag,{value:"Module"}));Pm.prototype.interactable={get(){return this.interactive},set(t){this.interactable=t}};const Ns=Symbol("shadowDomOwner");class _o extends RA{constructor(){super(...arguments),r(this,"shadowComponent",null),r(this,"_controlsChildLayout",!0),r(this,"_root"),r(this,"_parentComponent")}isRoot(){var A;return((A=this.Root)==null?void 0:A.gameObject)===this.gameObject}get canvas(){const A=this.Root;return A!=null&&A.isCanvas?A:null}markDirty(){io.markUIDirty(this.context)}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(A){this._controlsChildLayout=A,this.shadowComponent&&(this.shadowComponent.autoLayout=A)}get Root(){return this._root===void 0&&(this._root=eA.getComponentInParent(this.gameObject,vc)),this._root}get Canvas(){return this.canvas}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(A,e){var g;this.removeShadowComponent();const I=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=eA.getComponentInParent(I,_o),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}A.name=this.name+" ("+(this.constructor.name??"UI")+")",A.autoLayout=this._parentComponent.controlsChildLayout,A[Ns]=this,this.setShadowComponentOwner(A);let i=!1;if(((g=this.Root)==null?void 0:g.gameObject)===this.gameObject)this.gameObject.add(A);else{let o=this._parentComponent.shadowComponent;o&&(o?.add(A),i=!0)}this.shadowComponent=A,e&&e.shadowComponent&&this.shadowComponent&&e.shadowComponent.add(this.shadowComponent),Mh&&A.add(new _B(.5)),this.onAfterAddedToScene(),i&&GH()}set(A){}setShadowComponentOwner(A){if(A&&(A[Ns]===void 0||A[Ns]===this)&&(A[Ns]=this,A.children))for(const e of A.children)this.setShadowComponentOwner(e)}traverseOwnedShadowComponents(A,e,g){if(A&&A[Ns]===e){g(A);for(const I of A.children)this.traverseOwnedShadowComponents(I,e,g)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(A){this.shadowComponent&&(this.shadowComponent.interactable=A)}}class vc extends _o{awake(){super.awake()}}class bQ{static getObject(A){const e=A[Ns];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const g=this.tryFindCanvasGroup(A);if(g?.isCanvasGroup===!0&&(e&&(e.canvasGroup=g),g.blocksRaycasts===!1||g.interactable===!1))return!1;const I=Qr(A,i=>{if(i.isGraphic===!0)return i},!1);return e&&I?.isGraphic===!0&&(e.graphic=I),!(I?.raycastTarget===!1||I?.layer===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=Qr(A,g=>{const I=g;if(I.blocksRaycasts!==void 0&&I.interactable!==void 0)return I},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}const Lc=aA("debugwebxrcontroller");var vQ=(t=>(t[t.PhysicalDevice=0]="PhysicalDevice",t[t.Touch=1]="Touch",t))(vQ||{}),Ks=(t=>(t.SelectStart="select-start",t.SelectEnd="select-end",t.Update="update",t))(Ks||{});class Iw extends RA{}const eI=class extends RA{constructor(){super(...arguments),r(this,"webXR"),r(this,"index",-1),r(this,"controllerModel"),r(this,"controller"),r(this,"controllerGrip"),r(this,"hand"),r(this,"handPointerModel"),r(this,"grabbed",null),r(this,"input",null),r(this,"type",0),r(this,"showRaycastLine",!0),r(this,"_wristQuaternion",null),r(this,"movementVector",new f),r(this,"worldRot",new GA),r(this,"joystick",new W),r(this,"didRotate",!1),r(this,"didTeleport",!1),r(this,"didChangeScale",!1),r(this,"lastHit",null),r(this,"raycastLine",null),r(this,"_raycastHitPoint",null),r(this,"_connnectedCallback",null),r(this,"_disconnectedCallback",null),r(this,"_selectStartEvt",null),r(this,"_selectEndEvt",null),r(this,"_selectionPressed",!1),r(this,"_selectionPressedLastFrame",!1),r(this,"_selectionStartTime",0),r(this,"_selectionEndTime",0),r(this,"_useSmoothing",!0),r(this,"_isConnected",!1),r(this,"rayRotation",new GA),r(this,"_pinchStartTime"),r(this,"selectStartCallback",null),r(this,"lastSelectStartObject",null),r(this,"_didNotEndSelection",!1),r(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const t=new Ag(this.geometry),A=t.material;return A.color=this.raycastColor,t.layers.set(2),t.name="line",t.scale.z=1,t}static CreateRaycastHitPoint(){const t=new Qo(.5,22,22),A=new lt({color:this.raycastColor}),e=new yA(t,A);return e.visible=!1,e.layers.set(2),e}static Create(t,A,e,g){const I=e?eA.addNewComponent(e,eI,!1):new eI;I.webXR=t,I.index=A,I.type=g;const i=t.context;I.controller=i.renderer.xr.getController(A),I.controllerGrip=i.renderer.xr.getControllerGrip(A),I.controllerModel=this.Factory.createControllerModel(I.controller),I.controllerGrip.add(I.controllerModel),I.hand=i.renderer.xr.getHand(A);const o=new IQ;Cc(o,i),I.webXR.handModelPath&&I.webXR.handModelPath!==""?o.setPath(Ia(t.sourceId,I.webXR.handModelPath)):o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const C=new l6(I.hand,o);return I.hand.add(C),I.hand.traverse(s=>s.layers.set(2)),I.handPointerModel=new S6(I.hand,I.controller),I.controller.addEventListener("connected",s=>{I.setControllerLayers(I.controllerModel,2),I.setControllerLayers(I.controllerGrip,2),I.setControllerLayers(I.hand,2),setTimeout(()=>{I.setControllerLayers(I.controllerModel,2),I.setControllerLayers(I.controllerGrip,2),I.setControllerLayers(I.hand,2)},1e3)}),I.hand.addEventListener("connected",s=>{var a;if(s.data.hand){t.Rig&&t.Rig.add(I.hand),I.type=0,I.handPointerModel.traverse(B=>B.layers.set(2)),(a=I.handPointerModel.pointerObject)==null||a.traverse(B=>B.layers.set(2));const n=I.hand.joints;if(n)for(const B of Object.keys(n)){const Q=n[B];Q.parent||I.hand.add(Q)}}}),I}static addEventListener(t,A){const e=this.eventSubs[t]??[];e.push(A),this.eventSubs[t]=e}static removeEventListener(t,A){if(!A)return;const e=this.eventSubs[t]??[],g=e.indexOf(A);g>=0&&e.splice(g,1),this.eventSubs[t]=e}get isUsingHands(){var t;return((t=this.input)==null?void 0:t.hand)!=null}get wrist(){if(!this.hand)return null;const t=this.hand.joints;return t?t.wrist:null}getWristQuaternion(){const t=this.wrist;return t?(this._wristQuaternion||(this._wristQuaternion=new GA),Ng(t).multiply(this._wristQuaternion.setFromEuler(new fg(-Math.PI/4,0,0)))):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}get useSmoothing(){return this._useSmoothing}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(){var t,A,e;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)),(t=this.hand)==null||t.clear(),(A=this.controllerGrip)==null||A.clear(),(e=this.controller)==null||e.clear()}onEnable(){var t,A,e,g,I;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=eI.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=eI.CreateRaycastHitPoint()),(t=this.webXR.Rig)==null||t.add(this.hand),(A=this.webXR.Rig)==null||A.add(this.controllerGrip),(e=this.webXR.Rig)==null||e.add(this.controller),(g=this.webXR.Rig)==null||g.add(this.raycastLine),(I=this.raycastLine)==null||I.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),Lc&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var t,A,e,g,I;(t=this.hand)==null||t.removeFromParent(),(A=this.controllerGrip)==null||A.removeFromParent(),(e=this.controller)==null||e.removeFromParent(),(g=this.raycastLine)==null||g.removeFromParent(),(I=this._raycastHitPoint)==null||I.removeFromParent();const i=this.webXR.Controllers.indexOf(this);i>=0&&this.webXR.Controllers.splice(i,1)}onSourceConnected(t){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,t);return}this._isConnected=!0,this.input=t.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(t){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",t);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(t){switch(t){case"down":this.context.input.createPointerDown({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));const t=eI.eventSubs.update;if(t&&t.length>0)for(const g of t)g(this);let A=1;this.type===0?A=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(A=this.context.time.deltaTime/.3),this.rayRotation.slerp(Ng(this.controller),this.useSmoothing?A:1);const e=ye(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine){const g=this.showRaycastLine&&this.type!==1;if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed&&g,tg(this.raycastLine,e);const I=this.hand.joints;if(I&&I.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const i=this.getWristQuaternion();i&&this.rayRotation.copy(i)}zI(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=g,zI(this.raycastLine,this.rayRotation),tg(this.raycastLine,e)}this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(t){var A,e;if(this.lastHit=null,!t||t.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=t.inputSources[this.index]),!this.input)return;const g=this.webXR.Rig;if(!g)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const I=(e=(A=this.input)==null?void 0:A.gamepad)==null?void 0:e.buttons;switch(this.input.handedness){case"left":const i=3*eI.MovementSpeedFactor,o=2,C=XA.clamp01(this.joystick.length()*2),s=this.joystick.x>0?1:-1;let a=Math.pow(this.joystick.x,o);a*=s,a*=C;const n=this.joystick.y>0?1:-1;let B=Math.pow(this.joystick.y,o);B*=n,a*=C,g.getWorldQuaternion(this.worldRot),this.movementVector.set(a,0,B),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(i*this.context.time.deltaTime),g.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(g,I);break;case"right":const Q=this.joystick.x,E=Math.abs(Q);if(E<.4)this.didRotate=!1;else if(E>.5&&!this.didRotate){const h=Q>0?-1:1;g.rotateY(XA.toRadians(30*h)),this.didRotate=!0}this.runTeleport(g,I);break}}runTeleport(t,A){var e,g,I;let i=-this.joystick.y;if((e=this.hand)!=null&&e.visible&&!this.grabbed){const 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 o=i>.5&&this.webXR.IsInVR,C=this.webXR.Rig?((I=(g=this.webXR.Rig)==null?void 0:g.scale)==null?void 0:I.x)<.999:!1,s=null;if(A&&this.input&&!this.input.hand)for(let a=0;a<A.length;a++){const n=A[a];if(a===4)if(n.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;const B=this.webXR.Rig;if(B)if(C){C=!1,B.scale.set(1,1,1),s=1,eI.MovementSpeedFactor=1;const Q=this.context.mainCamera;eI.PreviousCameraFarDistance&&(Q.far=eI.PreviousCameraFarDistance)}else{C=!0,o=!0,s=.1,eI.MovementSpeedFactor=s*2;const Q=this.context.mainCamera;eI.PreviousCameraFarDistance=Q.far,Q.far/=s}}else n.pressed||(this.didChangeScale=!1)}if(o){if(!this.didTeleport){const a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){const n=a[0];if(C||this.isValidTeleportTarget(n.object)){const B=n.point;tg(t,B)}}}}else i<.1&&(this.didTeleport=!1);s!==null&&(t.scale.set(s,s,s),t.updateMatrixWorld())}isValidTeleportTarget(t){return eA.getComponentInParent(t,Iw)!=null}updateStick(t){var A;!t||!t.gamepad||((A=t.gamepad.axes)==null?void 0:A.length)<4||(this.joystick.x=t.gamepad.axes[2],this.joystick.y=t.gamepad.axes[3])}updateLastHit(){var t;const A=this.raycast(),e=A?A[0]:null;this.lastHit=e;let g=1;if(this.webXR.Rig&&(g/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=g*(((t=this.lastHit)==null?void 0:t.distance)??9999);const I=this.raycastLine.material;e!=null?I.color=eI.raycastColor:I.color=eI.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const I=XA.clamp(this.lastHit.distance*.01*g,.015,.1);this._raycastHitPoint.scale.set(I,I,I)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return e}onSelectStart(){this.context.connection.allowEditing&&(this.selectStartCallback=()=>this.onHandleSelectStart())}onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let t=null,A=!1;if(this.isUsingHands?(t=this.overlap(),t.length<=0?(t=this.raycast(),A=!1):A=!0):t=this.raycast(),Lc&&console.log("onHandleSelectStart","close grab? "+A,"intersections",t),t&&t.length>0)for(const e of t){const g=e.object;this.lastSelectStartObject=g;const I={selected:g,grab:g},i=eI.eventSubs["select-start"];if(i&&i.length>0)for(const o of i)o(this,I);I.grab!==g&&Lc&&console.log("Grabbed object changed","original",g,"new",I.grab),I.grab&&(this.grabbed=pC.TryTake(this,I.grab,e,A));break}else{const e=eI.eventSubs["select-start"],g={selected:null,grab:null};if(e&&e.length>0)for(const I of e)I(this,g)}}onSelectEnd(){var t;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;const A={grab:((t=this.grabbed)==null?void 0:t.selected)??this.lastSelectStartObject},e=eI.eventSubs["select-end"];if(e&&e.length>0)for(const g of e)g(this,A);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(t){return!(!t||eA.isActiveInHierarchy(t)===!1||bQ.isInteractable(t)===!1)}setControllerLayers(t,A){var e,g;if(t&&(t.layers.set(A),t.children))for(const I of t.children)((e=this.grabbed)==null?void 0:e.selected)===I||((g=this.grabbed)==null?void 0:g.selectedMesh)===I||this.setControllerLayers(I,A)}getRay(){const t=new As;return t.origin.copy(ye(this.controller)),t.direction.set(0,0,-1).applyQuaternion(this.rayRotation),t}overlap(){const t=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Lc&&(!this.closeGrabBoundingBoxHelper&&t&&(this.closeGrabBoundingBoxHelper=new Xp(t,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&t&&this.closeGrabBoundingBoxHelper.setFromObject(t)),!t)return new Array;const A=ye(t).clone();return this.context.physics.sphereOverlap(A,.02)}raycast(){const t=new Go;t.layerMask=new xi,t.layerMask.enableAll(),t.layerMask.disable(2),t.ray=this.getRay();const A=this.context.physics.raycast(t);for(let e=0;e<A.length;e++){const g=A[e],I=g.object;if(!this.testIsVisible(I)){A.splice(e,1),e--;continue}g.object=bQ.getObject(I);break}return A}};let dg=eI;r(dg,"Factory",new q6),r(dg,"raycastColor",new fA(.9,.3,.3)),r(dg,"raycastNoHitColor",new fA(.6,.6,.6)),r(dg,"geometry",new pe().setFromPoints([new f(0,0,0),new f(0,0,-1)])),r(dg,"handModels",{}),r(dg,"eventSubs",{}),r(dg,"PreviousCameraFarDistance"),r(dg,"MovementSpeedFactor",1);var iw=(t=>(t.WillTake="WillTake",t.DidTake="DidTake",t.WillFree="WillFree",t.DidFree="DidFree",t))(iw||{});const oi=class{constructor(){r(this,"sync",null),r(this,"selected",null),r(this,"selectedParent",null),r(this,"selectedMesh",null),r(this,"controller",null),r(this,"grabTime",0),r(this,"grabUUID",""),r(this,"isCloseGrab",!1),r(this,"originalMaterial",null),r(this,"usageMarker",null),r(this,"rigidbodies",null),r(this,"didReparent",!1),r(this,"grabDistance",0),r(this,"interactable",null),r(this,"positionSource",null),r(this,"grabPoint",new f),r(this,"localPositionOffsetToGrab",null),r(this,"localPositionOffsetToGrab_worldSpace",new f),r(this,"localQuaternionToGrab",new GA(0,0,0,1)),r(this,"targetDir",null),r(this,"quaternionLerp",null),r(this,"controllerDir",new f),r(this,"controllerWorldPos",new f),r(this,"lastControllerWorldPos",new f),r(this,"controllerPosDelta",new f),r(this,"totalChangeAlongDirection",0),r(this,"rigPositionLastFrame",new f)}static AddEventListener(t,A){return oi.Events[t]||(oi.Events[t]=[]),oi.Events[t].push(A),A}static RemoveEventListener(t,A){if(!A||!oi.Events[t])return;const e=oi.Events[t].indexOf(A);e>=0&&oi.Events[t].splice(e,1)}static Register(t){this.Current.find(A=>A===t)||this.Current.push(t)}static Remove(t){const A=this.Current.indexOf(t);A>=0&&this.Current.splice(A,1)}static TryTake(t,A,e,g){const I=eA.getComponentInParent(A,MQ);if(I)A=I.gameObject;else return Lc&&console.warn("Prevented taking object that is not interactable",A),null;let i=A;const o=eA.getComponentInParent(A,tn);o&&(o.requestOwnership(),i=o.gameObject);for(const s of this.Current)if(s.selected===i)return s.controller===t||(s.free(),s.Take(t,i,A,o,I,e,g)),s;const C=new oi;return C.Take(t,i,A,o,I,e,g),C}Take(t,A,e,g,I,i,o){var C,s;if(console.assert(A!==null,"Expected object to be taken but was",A),t.isUsingHands?this.positionSource=o?t.wrist:t.controller:this.positionSource=t.controller,!this.positionSource)return console.warn("No position source"),this;const a={controller:t,take:A,hit:e,sync:g,interactable:I};(C=oi.Events.WillTake)==null||C.forEach(h=>h(this,a));const n=e;n!=null&&n.material&&(this.originalMaterial=n.material,Array.isArray(n.material)||(n.material=n.material.clone(),n.material&&n.material.emissive&&(n.material.emissive.b=.2))),this.selected=A,this.selectedParent||(this.selectedParent=A.parent),this.selectedMesh=n,this.controller=t,this.interactable=I,this.isCloseGrab=o,this.didReparent=!1,this.sync=g,this.grabTime=t.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=eA.addNewComponent(this.selected,RQ),this.rigidbodies=eA.getComponentsInChildren(this.selected,Ht),ye(this.positionSource,this.lastControllerWorldPos);const B=()=>o?this.lastControllerWorldPos.clone():i.point.clone();this.grabDistance=B().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(B());const Q=t.isUsingHands&&o?this.controller.getWristQuaternion().clone():t.rayRotation.clone();Ng(this.selected,this.localQuaternionToGrab).premultiply(Q.invert());const E=this.controller.webXR.Rig;return E&&this.rigPositionLastFrame.copy(ye(E)),YI.Add(t.context,this.selected),oi.Register(this),this.sync&&(this.sync.fastMode=!0),(s=oi.Events.DidTake)==null||s.forEach(h=>h(this,a)),this}free(){var t,A,e,g;if(!this.selected)return;const I={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(t=oi.Events.WillFree)==null||t.forEach(C=>C(this,I)),YI.Remove(this.controller.context,this.selected),oi.Remove(this),this.sync&&(this.sync.fastMode=!1);const i=this.selectedMesh;i&&this.originalMaterial&&i.material&&(i.material=this.originalMaterial);const o=this.selected;if(this.didReparent&&o.parent){const C=this.selectedParent;C?C.attach(o):(A=this.controller)==null||A.context.scene.attach(o)}if((e=this.usageMarker)==null||e.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const C of this.rigidbodies)C.wakeUp(),C.setVelocity(C.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(g=oi.Events.DidFree)==null||g.forEach(C=>C(this,I))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),ye(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const t=this.controller.webXR.Rig;if(t){const A=ye(t),e=this.rigPositionLastFrame.sub(A);this.controllerPosDelta.add(e),this.rigPositionLastFrame.copy(A)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var t;if(this.rigidbodies)for(const A of this.rigidbodies)A.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){const A=((t=this.controller.webXR.Rig)==null?void 0:t.scale.x)??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let e=1;this.controller.type===0&&(e=Math.max(0,1+this.totalChangeAlongDirection*2/A),e=e*e*e),this.grabDistance/A<.8&&(e=1),this.targetDir||(this.targetDir=new f),this.targetDir.set(0,0,-this.grabDistance*e);const g=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),I=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=I.clone()),this.quaternionLerp.slerp(I,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),zI(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(g),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(ye(this.selected)),g.sub(this.localPositionOffsetToGrab_worldSpace)),tg(this.selected,g)}if(this.rigidbodies!=null)for(const A of this.rigidbodies)A.wakeUp();Ei.markDirty(this.selected,!0)}}};let pC=oi;r(pC,"Events",{}),r(pC,"Current",[]);var OeA=Object.defineProperty,PeA=Object.getOwnPropertyDescriptor,Wm=(t,A,e,g)=>{for(var I=g>1?void 0:g?PeA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&OeA(A,e,I),I};class kr extends RA{constructor(){super(...arguments),r(this,"objectBounds",!1),r(this,"color"),r(this,"isGizmo",!0),r(this,"_gizmoObject",null),r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!Mh||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Xp(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Cx(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),ki.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var A;this._boxHelper;)(A=this._boxHelper)==null||A.update(),yield}}Wm([w()],kr.prototype,"objectBounds",2),Wm([w(fA)],kr.prototype,"color",2),Wm([w()],kr.prototype,"isGizmo",2);const jeA=aA("debugrig");class ow extends RA{awake(){if(jeA){const A=new UA;A.position.y+=.5,this.gameObject.add(A);const e=A.addNewComponent(kr);e&&(e.isGizmo=!1)}}}class LQ{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,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(A,e,g,I,i){return A.prep(4,16),A.writeFloat32(i),A.writeFloat32(I),A.writeFloat32(g),A.writeFloat32(e),A.offset()}}class yI{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsVrUserStateBuffer(A,e){return(e||new yI).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsVrUserStateBuffer(A,e){return A.setPosition(A.position()+lu),(e||new yI).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}time(){const A=this.bb.__offset(this.bb_pos,6);return A?this.bb.readInt64(this.bb_pos+A):this.bb.createLong(0,0)}avatarId(A){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,A):null}position(A){const e=this.bb.__offset(this.bb_pos,10);return e?(A||new Gi).__init(this.bb_pos+e,this.bb):null}rotation(A){const e=this.bb.__offset(this.bb_pos,12);return e?(A||new LQ).__init(this.bb_pos+e,this.bb):null}scale(){const A=this.bb.__offset(this.bb_pos,14);return A?this.bb.readFloat32(this.bb_pos+A):0}posLeftHand(A){const e=this.bb.__offset(this.bb_pos,16);return e?(A||new Gi).__init(this.bb_pos+e,this.bb):null}posRightHand(A){const e=this.bb.__offset(this.bb_pos,18);return e?(A||new Gi).__init(this.bb_pos+e,this.bb):null}rotLeftHand(A){const e=this.bb.__offset(this.bb_pos,20);return e?(A||new LQ).__init(this.bb_pos+e,this.bb):null}rotRightHand(A){const e=this.bb.__offset(this.bb_pos,22);return e?(A||new LQ).__init(this.bb_pos+e,this.bb):null}static startVrUserStateBuffer(A){A.startObject(10)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addTime(A,e){A.addFieldInt64(1,e,A.createLong(0,0))}static addAvatarId(A,e){A.addFieldOffset(2,e,0)}static addPosition(A,e){A.addFieldStruct(3,e,0)}static addRotation(A,e){A.addFieldStruct(4,e,0)}static addScale(A,e){A.addFieldFloat32(5,e,0)}static addPosLeftHand(A,e){A.addFieldStruct(6,e,0)}static addPosRightHand(A,e){A.addFieldStruct(7,e,0)}static addRotLeftHand(A,e){A.addFieldStruct(8,e,0)}static addRotRightHand(A,e){A.addFieldStruct(9,e,0)}static endVrUserStateBuffer(A){return A.endObject()}static finishVrUserStateBufferBuffer(A,e){A.finish(e)}static finishSizePrefixedVrUserStateBufferBuffer(A,e){A.finish(e,void 0,!0)}}const MH=aA("debugxr"),xc=aA("debugavatar"),Vm="VRUS";Xf(Vm,yI.getRootAsVrUserStateBuffer);function zm(){return new Date().getTime()}function WeA(t){let A=t&4294967295,e=t/Math.pow(2,32)&1048575;return xC.create(A,e)}const Cw=class{constructor(t){r(this,"guid"),r(this,"time"),r(this,"avatarId"),r(this,"position",new f),r(this,"rotation",new Ie),r(this,"scale",1),r(this,"posLeftHand",new f),r(this,"posRightHand",new f),r(this,"rotLeftHand",new GA),r(this,"rotRightHand",new GA),this.guid=t}update(t,A,e,g,I){var i,o,C,s,a,n;this.time=zm(),this.avatarId=I,this.position.set(A.x,A.y,A.z),t&&this.position.applyMatrix4(t.matrixWorld);let B=Cw.quat0;const Q=Cw.quat1;B.set(e.x,e.y,e.z,e.w),B=B.multiplyQuaternions(B,Cw.invertRotation),t&&(t.getWorldQuaternion(Q),B.multiplyQuaternions(Q,B)),this.rotation.set(B.x,B.y,B.z,B.w),this.scale=t.scale.x;const E=(i=g.LeftController)==null?void 0:i.controllerGrip;E&&(E.getWorldPosition(this.posLeftHand),E.getWorldQuaternion(this.rotLeftHand));const h=(o=g.RightController)==null?void 0:o.controllerGrip;if(h&&(h.getWorldPosition(this.posRightHand),h.getWorldQuaternion(this.rotRightHand)),(s=(C=g.LeftController)==null?void 0:C.hand)!=null&&s.visible){const c=g.LeftController.wrist;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand))}if((n=(a=g.RightController)==null?void 0:a.hand)!=null&&n.visible){const c=g.RightController.wrist;c&&(c.getWorldPosition(this.posRightHand),c.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(t,A){t.clear();const e=t.createString(this.guid),g=t.createString(this.avatarId);yI.startVrUserStateBuffer(t),yI.addGuid(t,e),yI.addTime(t,WeA(this.time)),yI.addAvatarId(t,g),yI.addPosition(t,Gi.createVec3(t,this.position.x,this.position.y,this.position.z)),yI.addRotation(t,LQ.createVec4(t,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),yI.addScale(t,this.scale),yI.addPosLeftHand(t,Gi.createVec3(t,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),yI.addPosRightHand(t,Gi.createVec3(t,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),yI.addRotLeftHand(t,LQ.createVec4(t,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),yI.addRotRightHand(t,LQ.createVec4(t,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));const I=yI.endVrUserStateBuffer(t);t.finish(I,Vm);const i=t.asUint8Array();A.sendBinary(i)}setFromBuffer(t,A){if(!t)return;this.guid=t,this.time=A.time().toFloat64();const e=A.avatarId();e&&(this.avatarId=e);const g=A.position();g&&this.position.set(g.x(),g.y(),g.z());const I=A.rotation();I&&this.rotation.set(I.x(),I.y(),I.z(),I.w());const i=A.posLeftHand();i&&this.posLeftHand.set(i.x(),i.y(),i.z());const o=A.posRightHand();o&&this.posRightHand.set(o.x(),o.y(),o.z());const C=A.rotLeftHand();C&&this.rotLeftHand.set(C.x(),C.y(),C.z(),C.w());const s=A.rotRightHand();s&&this.rotRightHand.set(s.x(),s.y(),s.z(),s.w()),this.scale=A.scale()}};let Js=Cw;r(Js,"invertRotation",new GA().setFromAxisAngle(new f(0,1,0),Math.PI)),r(Js,"quat0",new GA),r(Js,"quat1",new GA);class Yc extends RA{constructor(){super(...arguments),r(this,"webXR",null),r(this,"debugAvatarUser",null),r(this,"voip",null),r(this,"tempState",new Js("")),r(this,"_removeAvatarsList",[]),r(this,"eventSub_ConnectionEvent",null),r(this,"eventSub_WebXRStartEvent",null),r(this,"eventSub_WebXREndEvent",null),r(this,"eventSub_WebXRUpdateEvent",null),r(this,"avatars",{}),r(this,"localAvatar",null),r(this,"k_LocalAvatarNoNetworkingGuid","local"),r(this,"ownership",null),r(this,"xrState",null),r(this,"builder",new FE(1024))}async awake(){if(this.webXR||(this.webXR=eA.getComponent(this.gameObject,Se)),this.webXR||(this.webXR=eA.findObjectOfType(Se,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=eA.findObjectOfType(Se,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=eA.findObjectOfType(Xs,this.context)),xc){const A="debug-avatar-"+xc,e=new An(this.context,A,this.webXR);if(this.debugAvatarUser=e,typeof xc=="string"&&xc.length>0)if(await e.setAvatarOverride(xc)){const g=new Js(A);g.position.y+=1;const I=.5;g.posLeftHand.y+=I,g.posLeftHand.x+=I,g.posRightHand.y+=I,g.posRightHand.x-=I,e.tryUpdate(g,0)}else e.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=eA.getComponent(this.gameObject,Se),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),Se.addEventListener(kt.XRStarted,this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),Se.addEventListener(kt.XRUpdate,this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Se.addEventListener(kt.XRStopped,this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen(Pt.JoinedRoom,this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",A=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",A=>{const e=A.id!==null&&A.id!==void 0;if(e&&(console.log("webxr user left evt"),e)){const g=this.avatars[A.id];g?.destroy(),this.avatars[A.id]=void 0}}),this.context.connection.beginListenBinary(Vm,A=>{const e=A.guid();if(!e)return;const g=A.time().toFloat64(),I=this.tempState;I.setFromBuffer(e,A);const i=this.onTryGetAvatar(e,g);i?.tryUpdate(I,g)}),this.context.connection.beginListen("vr-session-update",A=>{const e=A.guid,g=A.time,I=this.onTryGetAvatar(e,g);I?.tryUpdate(A,g)})}onTryGetAvatar(A,e){if(A===this.context.connection.connectionId)return null;const g=new Date().getTime()-e;if(g>5e3)return MH&&console.log("old data",g,A),null;let I=this.avatars[A];if(I===void 0)try{console.log("create new avatar");const i=new An(this.context,A,this.webXR);I=i,this.avatars[A]=i}catch(i){this.avatars[A]=null,console.error(i)}return I}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListen(Pt.JoinedRoom,this.eventSub_ConnectionEvent),Se.removeEventListener(kt.XRStarted,this.eventSub_WebXRStartEvent),Se.removeEventListener(kt.XRUpdate,this.eventSub_WebXRUpdateEvent),Se.removeEventListener(kt.XRStopped,this.eventSub_WebXREndEvent)}update(){const A=zm();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=A),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(const e in this.avatars){const g=this.avatars[e];g&&g.update()}}detectPotentiallyDisconnectedAvatarsAndRemove(){const A=zm();for(const e in this.avatars){const g=this.avatars[e];if(!g){this._removeAvatarsList.push(e);continue}A-g.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),g.destroy(),this.avatars[e]=void 0)}for(const e of this._removeAvatarsList)delete this.avatars[e];this._removeAvatarsList.length=0}buildLocalAvatar(){var A;if(this.localAvatar)return;const e=((A=this.context.connection)==null?void 0:A.connectionId)??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new An(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}onConnected(){var A,e,g;MH&&console.log("Hey you are connected as "+this.context.connection.connectionId),((A=this.localAvatar)==null?void 0:A.guid)===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&((e=this.localAvatar)==null||e.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,(g=this.ownership)==null||g.freeOwnership(),this.ownership=null)}onXRSessionStart(A){var e,g,I;if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((e=this.localAvatar)==null||e.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,(g=this.ownership)==null||g.freeOwnership(),this.ownership=null,this.avatars)for(const i in this.avatars)(I=this.avatars[i])==null||I.updateFlags()}onXRSessionEnded(A){var e;console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((e=this.localAvatar)==null||e.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null)}onXRSessionUpdate(A){this.xrState??(this.xrState=new Js(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership??(this.ownership=new Ru(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();const{frame:e,xr:g,rig:I}=A,i=e.getViewerPose(g.getReferenceSpace());if(!i)return;const o=i?.transform,C=o.position,s=o.orientation;this.xrState.update(I,C,s,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 aA("avatar")??null}}var VeA=Object.defineProperty,zeA=Object.getOwnPropertyDescriptor,xQ=(t,A,e,g)=>{for(var I=g>1?void 0:g?zeA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&VeA(A,e,I),I};async function RH(){return yS()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function UH(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}let sw=!1,aw=!1;RH().then(t=>sw=t),UH().then(t=>aw=t);var kt=(t=>(t.XRStarted="xrStarted",t.XRStopped="xrStopped",t.XRUpdate="xrUpdate",t.RequestVRSession="requestVRSession",t.ModifyAROptions="modify-ar-options",t))(kt||{}),YQ;const qg=(YQ=class extends RA{constructor(){super(...arguments),r(this,"enableVR",!0),r(this,"enableAR",!0),r(this,"defaultAvatar"),r(this,"handModelPath",""),r(this,"createVRButton",!0),r(this,"createARButton",!0),r(this,"controllers",[]),r(this,"rig"),r(this,"isInit",!1),r(this,"_requestedAR",!1),r(this,"_requestedVR",!1),r(this,"_isInAR",!1),r(this,"_isInVR",!1),r(this,"_arButton"),r(this,"_vrButton"),r(this,"webAR",null),r(this,"_transformOrientation",new GA),r(this,"_currentHeadPose",null),r(this,"_originalCameraParent",null),r(this,"_originalCameraPosition",new f),r(this,"_originalCameraRotation",new GA),r(this,"_originalXRRigParent",null),r(this,"_originalXRRigPosition",new f),r(this,"_originalXRRigRotation",new GA),r(this,"xrMirrorWindow",null)}static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(sw||aw)}static get IsARSupported(){return sw}static get IsVRSupported(){return aw}static get OptionalFeatures_VR(){return this._optionalFeatures_VR}static get OptionalFeatures_AR(){return this._optionalFeatures_AR}static addEventListener(t,A){return this.events.addEventListener(t,A),A}static removeEventListener(t,A){return this.events.removeEventListener(t,A),A}static dispatchEvent(t,A){this.events.dispatchEvent({type:t,detail:A})}static createVRButton(t,A){qg.XRSupported?t.__internalAwake():console.warn("WebXR is not supported on this device");const e={optionalFeatures:qg.OptionalFeatures_VR},g=tm.createButton(t.context.renderer,e);return g.classList.add("webxr-ar-button"),g.classList.add("webxr-button"),this.resetButtonStyles(g),(A?.registerClick??!0)&&g.addEventListener("click",t.onClickedVRButton.bind(t)),g}static createARButton(t,A){var e;t.__internalAwake();const g=(e=t.webAR)==null?void 0:e.getAROverlayContainer(),I={optionalFeatures:[...this.OptionalFeatures_AR]};g?(I.domOverlay={root:g},I.optionalFeatures.push("dom-overlay"),I.optionalFeatures.push("hit-test")):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work.");const i=o6.createButton(t.context.renderer,I,this.onModifyAROptions.bind(this));return i.classList.add("webxr-ar-button"),i.classList.add("webxr-button"),qg.resetButtonStyles(i),(A?.registerClick??!0)&&i.addEventListener("click",t.onClickedARButton.bind(t)),i}static onModifyAROptions(t){qg.dispatchEvent("modify-ar-options",t)}static resetButtonStyles(t){t&&(t.style.position="",t.style.bottom="",t.style.left="")}endSession(){const t=this.context.renderer.xr.getSession();t&&t.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}get Controllers(){return this.controllers}get LeftController(){var t,A;return this.controllers.length>0&&((t=this.controllers[0].input)==null?void 0:t.handedness)==="left"?this.controllers[0]:this.controllers.length>1&&((A=this.controllers[1].input)==null?void 0:A.handedness)==="left"?this.controllers[1]:null}get RightController(){var t,A;return this.controllers.length>0&&((t=this.controllers[0].input)==null?void 0:t.handedness)==="right"?this.controllers[0]:this.controllers.length>1&&((A=this.controllers[1].input)==null?void 0:A.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}awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=dI.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!eA.findObjectOfType(Yc,this.context)){const t=eA.addNewComponent(this.gameObject,Yc,!1);t.webXR=this}this.webAR=new Tc(this)}start(){location.protocol=="http:"&&location.host.indexOf("localhost")<0&&(fo("WebXR only works on https"),console.warn("WebXR only works on https. https://engine.needle.tools/docs/xr.html"))}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,qg.XRSupported;let t,A;const e=document.createElement("div");e.classList.add("webxr-buttons"),this.context.domElement.append(e),this.enableAR&&this.createARButton&&sw&&(t=qg.createARButton(this),this._arButton=t,e.appendChild(t)),this.createVRButton&&this.enableVR&&aw&&(A=qg.createVRButton(this),this._vrButton=A,e.appendChild(A)),setTimeout(()=>{qg.resetButtonStyles(A),qg.resetButtonStyles(t)},1e3)}get TransformOrientation(){return this._transformOrientation}get HeadPose(){return this._currentHeadPose}onBeforeRender(t){var A;if(!t)return;const e=this.context.renderer.xr.getSession();if(e){const g=t.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(!g)return;this._currentHeadPose=g;const I=g?.transform;I&&this._transformOrientation.set(I.orientation.x,I.orientation.y,I.orientation.z,I.orientation.w),qg._isInXr===!1&&e&&this.onEnterXR(e,t);for(const i of this.controllers)i.onUpdate(e);this._isInAR&&((A=this.webAR)==null||A.onUpdate(e,t))}qg.events.dispatchEvent({type:"xrUpdate",frame:t,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureStateBeforeXR())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureStateBeforeXR(),this.ensureRig();for(let t=0;t<2;t++)dg.Create(this,t,this.gameObject,vQ.PhysicalDevice);qg.events.dispatchEvent({type:"requestVRSession"})}}captureStateBeforeXR(){this.context.mainCamera&&(this._originalCameraPosition.copy(ye(this.context.mainCamera)),this._originalCameraRotation.copy(Ng(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent),this.Rig&&(this._originalXRRigParent=this.Rig.parent,this._originalXRRigPosition.copy(this.Rig.position),this._originalXRRigRotation.copy(this.Rig.quaternion))}ensureRig(){if(!this.rig){const t=eA.findObjectOfType(ow,this.context);t?this.rig=t.gameObject:(this.rig=new Ti,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}onEnterXR(t,A){var e,g;console.log("[XR] session begin",t),qg._isInXr=!0,this.ensureRig();const I=this.context.renderer.xr.getReferenceSpace();if(I&&this.rig){const C=A.getViewerPose(I),s=C?.transform.orientation;if(s){const a=new GA(s.x,s.y,s.z,s.w),n=new fg().setFromQuaternion(a);this.rig.rotateY(n.y)}}const i=this.context.renderer.xr;if(this.context.mainCamera){const C=i.getCamera(this.context.mainCamera),s=(e=this.context.mainCameraComponent)==null?void 0:e.cullingMask;if(s!==void 0){for(const a of C.cameras)a.layers.mask=s;C.layers.mask=s}else{for(const a of C.cameras)a.layers.enableAll();C.layers.enableAll()}this.rig.add(this.context.mainCamera),this._requestedAR&&this.context.scene.add(this.rig)}const o=this._requestedAR?cg.AR:cg.VR;switch(QC.Global.Set(o),o){case cg.AR:this.context.xrSessionMode=gc.ImmersiveAR,this._isInAR=!0,(g=this.webAR)==null||g.onBegin(t);break;case cg.VR:this.context.xrSessionMode=gc.ImmersiveVR,this._isInVR=!0,this.onEnterVR(t);break}t.addEventListener("end",()=>{console.log("[XR] session end"),qg._isInXr=!1,this.onExitXR(t)}),this.onEnterXR_HandleMirrorWindow(t),qg.events.dispatchEvent({type:"xrStarted",session:t})}onExitXR(t){var A,e,g;const I=this._isInAR;this._isInAR&&t&&((A=this.webAR)==null||A.onEnd(t)),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&&((e=this._originalCameraParent)==null||e.add(this.context.mainCamera),tg(this.context.mainCamera,this._originalCameraPosition),zI(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),I&&((g=this._originalXRRigParent)==null||g.add(this.rig),this.rig.position.copy(this._originalXRRigPosition),this.rig.quaternion.copy(this._originalXRRigRotation)),QC.Global.Set(cg.Browser|cg.ThirdPerson),qg.events.dispatchEvent({type:"xrStopped",session:t})}onEnterVR(t){}destroyControllers(){var t;for(let A=this.controllers.length-1;A>=0;A-=1)(t=this.controllers[A])==null||t.destroy();this.controllers.length=0}onEnterXR_HandleMirrorWindow(t){aA("mirror")&&setTimeout(()=>{if(!qg.IsInWebXR)return;const A=new URL(window.location.href);TE(A.searchParams,FD,1),TE(A.searchParams,"isMirror",1);const e=A.toString();this.xrMirrorWindow=window.open(e,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{qg.IsInWebXR&&t.end()})})},1e3)}},r(YQ,"_isInXr",!1),r(YQ,"events",new mg),r(YQ,"_optionalFeatures_VR",["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]),r(YQ,"_optionalFeatures_AR",["anchors","local-floor","hand-tracking","layers"]),YQ);let Se=qg;xQ([w()],Se.prototype,"enableVR",2),xQ([w()],Se.prototype,"enableAR",2),xQ([w(dI)],Se.prototype,"defaultAvatar",2),xQ([w()],Se.prototype,"handModelPath",2),xQ([w()],Se.prototype,"createVRButton",2),xQ([w()],Se.prototype,"createARButton",2);const Hc=class{constructor(t){r(this,"_webxr"),r(this,"reticle",null),r(this,"reticleParent",null),r(this,"hitTestSource",null),r(this,"reticleActive",!0),r(this,"previousBackground",null),r(this,"previousEnvironment",null),r(this,"sessionRoot",null),r(this,"_previousParent",null),r(this,"arDomOverlay",null),r(this,"arOverlayElement",null),r(this,"noHitTestAvailable",!1),r(this,"didPlaceARSessionRoot",!1),this._webxr=t}get webxr(){return this._webxr}get context(){return this.webxr.context}getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;const t=this.arDomOverlay;return t.getAROverlayContainer?this.arOverlayElement=t.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(t){this.reticleActive=t}async onBegin(t){var A,e,g,I;const i=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();const o=(A=navigator.userAgent)!=null&&A.includes("OculusBrowser")?vQ.PhysicalDevice:vQ.Touch,C=o===vQ.Touch?4:2;for(let a=0;a<C;a++)dg.Create(this.webxr,a,this.webxr.gameObject,o);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=eA.findObjectOfType(Xa,i)),this.previousBackground=i.scene.background,this.previousEnvironment=i.scene.environment,i.scene.background=null,t.requestReferenceSpace("viewer").then(a=>{var n,B;(B=(n=t.requestHitTestSource)==null?void 0:n.call(t,{space:a}))==null||B.then(Q=>{this.hitTestSource=Q}).catch(Q=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",Q)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new yA(new UE(.07,.09,32).rotateX(-Math.PI/2),new lt),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new UA,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),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,Hc.tempWebXRObject||(Hc.tempWebXRObject=new UA),this.context.scene.add(Hc.tempWebXRObject),eA.addComponent(Hc.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,(e=this.sessionRoot)==null||e.onBegin(t)):console.warn("No WebARSessionRoot found in scene");const s=this.context.domElement;(g=s?.onEnterAR)==null||g.call(s,t,this.arOverlayElement),(I=this.context.mainCameraComponent)==null||I.applyClearFlagsIfIsActiveCamera()}onEnd(t){var A,e;this._previousParent&&(eA.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;const g=this.webxr.context;g.scene.background=this.previousBackground,g.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,t);const I=this.context.domElement;(A=I.onExitAR)==null||A.call(I,t),(e=this.context.mainCameraComponent)==null||e.applyClearFlagsIfIsActiveCamera()}onUpdate(t,A){var e,g;if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;const i=this.webxr.Rig,o=ZeA.clone();(e=this.sessionRoot)==null||e.placeAt(i,o)}return}if(!this.hitTestSource)return;const I=A.getHitTestResults(this.hitTestSource);if(I.length){const i=I[0],o=this.webxr.context.renderer.xr.getReferenceSpace();if(o){const C=i.getPose(o);if(this.sessionRoot){const s=this.sessionRoot.onUpdate(this.webxr.Rig,t,C);this.didPlaceARSessionRoot=s}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&C)){const s=C.transform.matrix;this.reticle.matrix.fromArray(s),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else(g=this.sessionRoot)==null||g.onUpdate(this.webxr.Rig,t,null),this.reticle&&(this.reticle.visible=!1)}};let Tc=Hc;r(Tc,"tempWebXRObject");const ZeA=new TA().identity().makeTranslation(0,0,0);class Gr{constructor(A,e){r(this,"used",!1),r(this,"inputSource"),r(this,"object"),r(this,"pointerId"),r(this,"isDown"),r(this,"isUp"),r(this,"isPressed"),r(this,"isClicked"),r(this,"input"),r(this,"event"),this.event=e,this.input=A}use(){this.used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId)}stopPropagation(){var A;(A=this.event)==null||A.stopImmediatePropagation()}Use(){this.use()}StopPropagation(){var A;(A=this.event)==null||A.stopImmediatePropagation()}}class HQ extends RA{awake(){io.createIfNoneExists(this.context)}onEnable(){var A;(A=io.get(this.context))==null||A.register(this)}onDisable(){var A;(A=io.get(this.context))==null||A.unregister(this)}performRaycast(A=null){return null}}class mr extends HQ{constructor(){super(...arguments),r(this,"targets",null),r(this,"raycastHits",[])}start(){this.targets=[this.gameObject]}performRaycast(A=null){return this.targets?(A??(A=new Go),A.targets=this.targets,A.results=this.raycastHits,this.context.physics.raycast(A)):null}}class Zm extends mr{}const _c=aA("debugeventsystem");var Xm=(t=>(t.BeforeHandleInput="BeforeHandleInput",t.AfterHandleInput="AfterHandleInput",t))(Xm||{});const qs=class extends RA{constructor(){super(),r(this,"raycaster",[]),r(this,"_selectStartFn"),r(this,"_selectEndFn"),r(this,"_selectUpdateFn"),r(this,"_handleEventFn"),r(this,"lastPointerEvent",null),r(this,"objectsHoveredThisFrame",[]),r(this,"objectsHoveredLastFrame",[]),r(this,"raisedPointerDownEvents",[]),r(this,"raisedPointerDownObjects",[]),r(this,"_didMove",!1),r(this,"_tempComponentsArray",[]),r(this,"_sortedHits",[]),r(this,"_sortingBuffer",[]),r(this,"_noDepthTestingResults",[]),r(this,"handleEventsArray",[]),r(this,"out",{}),r(this,"currentActiveMeshUIComponents",[]),qs.systems.push(this)}static createIfNoneExists(t){this.didSearchEventSystem||(this.didSearchEventSystem=!0,qs.systems.length<=0&&qs.systems.push(...eA.findObjectsOfType(qs,t)));for(const e of qs.systems)if(e.context===t)return;const A=new UA;eA.addNewComponent(A,qs),t.scene.add(A)}static get systems(){const t=we.Current;return this._eventSystemMap.has(t)||this._eventSystemMap.set(t,[]),this._eventSystemMap.get(t)}static get(t){const A=this._eventSystemMap.get(t);return A&&A.length>0?A[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(t,A){bs.update(t,A)}static markUIDirty(t){bs.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.objectsHoveredThisFrame.length>0}onDestroy(){qs.systems.splice(qs.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!eA.findObjectOfType(HQ,this.context)){const t=eA.addNewComponent(this.context.scene,mr);this.raycaster.push(t),UI()&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found",this)}}register(t){var A;t&&this.raycaster&&!this.raycaster.includes(t)&&((A=this.raycaster)==null||A.push(t))}unregister(t){var A,e;const g=(A=this.raycaster)==null?void 0:A.indexOf(t);g!==void 0&&g!==-1&&((e=this.raycaster)==null||e.splice(g,1))}onEnable(){const t=new Map;this._selectStartFn??(this._selectStartFn=(e,g)=>{if(!g.grab)return;bs.resetLastSelected();const I=new Gr(this.context.input);I.inputSource=e,I.isDown=e.selectionDown,I.isUp=e.selectionUp,I.isPressed=e.selectionPressed,I.isClicked=!1,t.set(e,g.grab),g.grab&&!this.handleEvents(g.grab,I)&&(g.grab=null)}),this._selectEndFn??(this._selectEndFn=(e,g)=>{var I;if(!g.grab)return;const i=new Gr(this.context.input);i.inputSource=e,i.isDown=e.selectionDown,i.isUp=e.selectionUp,i.isPressed=e.selectionPressed,i.isClicked=e.selectionClick,this.handleEvents(g.grab,i);const o=t.get(e);if(t.set(e,null),o)for(let C=0;C<this.raisedPointerDownEvents.length;C++){const s=this.raisedPointerDownEvents[C];this.raisedPointerDownObjects[C]===o&&s&&((I=s.onPointerUp)==null||I.call(s,i),this.raisedPointerDownEvents.splice(C,1),this.raisedPointerDownObjects.splice(C,1),C--)}});const A=new Go;this._selectUpdateFn??(this._selectUpdateFn=e=>{A.ray=e.getRay();const g=this.performRaycast(A);if(!g)return;const I=new Gr(this.context.input);I.inputSource=e,this.handleIntersections(g,I)}),dg.addEventListener(Ks.SelectStart,this._selectStartFn),dg.addEventListener(Ks.SelectEnd,this._selectEndFn),dg.addEventListener(Ks.Update,this._selectUpdateFn),this._handleEventFn??(this._handleEventFn=this.onHandleEvents.bind(this)),this.context.pre_update_callbacks.push(this._handleEventFn)}onDisable(){dg.removeEventListener(Ks.SelectStart,this._selectStartFn),dg.removeEventListener(Ks.SelectEnd,this._selectEndFn),dg.removeEventListener(Ks.Update,this._selectUpdateFn),this.context.pre_update_callbacks.splice(this.context.pre_update_callbacks.indexOf(this._handleEventFn),1)}onHandleEvents(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),Se.IsInWebXR||this.context.input.isKeyPressed("AltLeft")||this.context.input.isKeyPressed("AltRight"))return;if(!this._didMove){const i=this.context.input.getPointerPositionRC(0);if(i&&i.x===0&&i.y===0)return;this._didMove=!0}let t=0;for(const i of this.context.input.foreachPointerId()){const o=this.context.input.getPointerDown(i),C=this.context.input.getPointerUp(i);if(o||C){t=i;break}}const A=this.context.input.getPointerEvent(t),e=new Gr(this.context.input,A);e.inputSource=this.context.input,e.pointerId=t,e.isClicked=this.context.input.getPointerClicked(t),e.isDown=this.context.input.getPointerDown(t),e.isUp=this.context.input.getPointerUp(t),e.isPressed=this.context.input.getPointerPressed(t),_c&&e.isClicked&&console.log("CLICK",t);const g=this.performRaycast(null);if(!g)return;this.lastPointerEvent=e;const I={sender:this,args:e,hasActiveUI:this.currentActiveMeshUIComponents.length>0};_c&&e.isClicked&&Hg("EventSystem: "+e.pointerId+" - "+this.context.time.frame+" - Up:"+e.isUp+", Down:"+e.isDown),this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:I})),this.handleIntersections(g,e),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:I}))}onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(const A of this.raisedPointerDownEvents)A.onPointerUp&&A.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(const A of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(A)<0){this._tempComponentsArray.length=0;const e=eA.getComponentsInParent(A,RA,this._tempComponentsArray);this.lastPointerEvent.object=A;for(let g=0;g<e.length;g++){const I=e[g];if(!I.gameObject||I.destroyed)continue;const i=I;i.onPointerExit&&i.onPointerExit(this.lastPointerEvent)}}const t=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=t}performRaycast(t){if(!this.raycaster)return null;this._sortedHits.length=0;for(const A of this.raycaster){if(!A.activeAndEnabled)continue;const e=A.performRaycast(t);e&&e.length>0&&this._sortedHits.push(...e)}return this._sortedHits.sort((A,e)=>A.distance-e.distance),this._sortedHits}handleIntersections(t,A){if(!t||t.length<=0)return!1;t=this.sortCandidates(t);for(const e of t){const{object:g}=e;if(this.handleEvents(g,A))return!0}return!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let A=0;A<t.length;A++){const e=t[A],g=e.object;if(g.material&&g.material.depthTest===!1){this._noDepthTestingResults.push(e);continue}this._sortingBuffer.push(e)}for(const A of this._sortingBuffer)this._noDepthTestingResults.push(A);return this._noDepthTestingResults}handleEvents(t,A){if(!this.testIsVisible(t))return A.isClicked&&_c&&console.log("not allowed",t),!1;const e=t;A.object=t,this.lastPointerEvent=A;const g=t.parent;let I=!1;const i=A.isClicked??!1;let o=null;if(g&&g.isUI){const C=(A.isPressed||A.isClicked)??!1;if(g[Ns]){const s=g[Ns].gameObject;if(s){if(!bQ.isInteractable(s,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,C),t=s,I=!0}}if(!I&&this.handleMeshUiObjectWithoutShadowDom(g,C))return!0}if(i&&_c&&console.log(this.context.time.frame,t),this.objectsHoveredThisFrame.push(t),o===null||o.interactable){const C=this.objectsHoveredLastFrame.indexOf(t)>=0;this.handleEventsArray.length=0;const s=eA.getComponentsInParent(t,RA,this.handleEventsArray);for(let a=0;a<s.length;a++){if(A.used)return!0;if(s[a].destroyed)continue;const n=s[a];if(n.interactable!==!1){if(n.onPointerEnter&&(C||n.onPointerEnter(A)),n.onPointerMove&&n.onPointerMove(A),A.isDown&&n.onPointerDown&&!this.raisedPointerDownEvents.includes(n)&&(n.onPointerDown(A),this.raisedPointerDownEvents.push(n),this.raisedPointerDownObjects.push(e)),A.isUp&&n.onPointerUp){const B=this.raisedPointerDownEvents.indexOf(n);B!==-1&&this.raisedPointerDownEvents.splice(B,1),n.onPointerUp(A)}A.isClicked&&n.onPointerClick&&n.onPointerClick(A)}}}return!0}handleMeshUiObjectWithoutShadowDom(t,A){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,A)}handleMeshUIIntersection(t,A){const e=bs.updateState(t,A);return e&&this.currentActiveMeshUIComponents.push(e),e!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&bs.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const A=this.currentActiveMeshUIComponents[t];bs.resetState(A)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?eA.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}};let io=qs;r(io,"_eventSystemMap",new Map),r(io,"didSearchEventSystem",!1);class bs{static markDirty(){this.needsUpdate=!0}static update(A,e){const g=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(g===I.frame)return;I.frame=g;let i=this.needsUpdate||g<1;I.nextUpdate===e.time.frameCount&&(i=!0),i&&(_c&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:g,nextUpdate:g}],A.update()}static updateState(A,e){let g=null;if(A&&(g=this.findBlockInParent(A),g&&g!==this.lastSelected)){if(g.interactable===!1)return null;this.needsUpdate=!0}return g}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}r(bs,"lastSelected",null),r(bs,"lastUpdateFrame",[]),r(bs,"needsUpdate",!1);const nw=Symbol("cameraController");function XeA(t){return t[nw]}function FH(t,A,e){e?t[nw]=A:t[nw]===A&&(t[nw]=null)}var $eA=Object.defineProperty,AtA=Object.getOwnPropertyDescriptor,etA=(t,A,e,g)=>{for(var I=g>1?void 0:g?AtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&$eA(A,e,I),I};const rw=aA("freecam"),NH=aA("debugcamerafit"),ttA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let $m;class vs extends RA{constructor(){super(...arguments),r(this,"autoRotate",!1),r(this,"autoRotateSpeed",1),r(this,"enableKeys",!0),r(this,"enableDamping",!0),r(this,"dampingFactor",.1),r(this,"enableZoom",!0),r(this,"minZoom",0),r(this,"maxZoom",1/0),r(this,"enablePan",!0),r(this,"lookAtConstraint",null),r(this,"lookAtConstraint01",1),r(this,"middleClickToFocus",!0),r(this,"doubleClickToFocus",!0),r(this,"useSlerp",!0),r(this,"debugLog",!1),r(this,"targetLerpSpeed",5),r(this,"_lookTargetPosition"),r(this,"_controls",null),r(this,"_cameraObject",null),r(this,"_lerpToTargetPosition",!1),r(this,"_lerpCameraToTarget",!1),r(this,"_cameraTargetPosition",null),r(this,"_inputs",0),r(this,"_enableTime",0),r(this,"_startedListeningToKeyEvents",!1),r(this,"_eventSystem"),r(this,"_afterHandleInputFn"),r(this,"_camera",null),r(this,"_syncedTransform"),r(this,"targetElement",null),r(this,"_shouldDisable",!1),r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(A){var e;(e=this.controls)==null||e.addEventListener("start",A)}awake(){this._lookTargetPosition=new f,this._startedListeningToKeyEvents=!1}start(){if(this._controls){const A=eA.getComponent(this.gameObject,Kt);if(A&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");const e=ye(A.cam).length(),g=new f(0,0,-e).applyMatrix4(A.cam.matrixWorld);this.setTarget(g,!0)}}this.startCoroutine(this.startRaycastDelayed()),this._eventSystem=io.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Xm.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var A,e;(A=this._controls)==null||A.dispose(),(e=this._eventSystem)==null||e.removeEventListener(Xm.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const A=eA.getComponent(this.gameObject,Kt);this._camera=A;const e=A?.cam;if(e&&FH(e,this,!0),!this._controls){console.assert(e!=null,"Missing camera",this),e&&(this._cameraObject=e);const g=this.targetElement??this.context.domElement;this._controls=new i6(e,g),$m===void 0&&($m={...this._controls.keys})}this._controls&&(rw&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,Un()&&(this.doubleClickToFocus=!0)),this._controls.enableDamping=this.enableDamping,this._controls.keys=this.enableKeys?$m:ttA,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.addEventListener("start",this.onControlsChangeStarted.bind(this)),e?.type==="PerspectiveCamera"?rw||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):rw||(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))),this._syncedTransform=eA.getComponent(this.gameObject,tn)??void 0}onDisable(){var A;(A=this._camera)!=null&&A.cam&&FH(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1)}onControlsChangeStarted(){this._syncedTransform&&this._syncedTransform.requestOwnership()}afterHandleInput(A){A.detail.args.pointerId===0&&(A.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!A.detail.args.isPressed||A.detail.args.isUp)&&(this._shouldDisable=!1))}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){const A=new Go;A.screenPoint=new W(0,0),A.lineThreshold=.1;const e=this.context.physics.raycast(A);e.length>0&&this.setTarget(e[0].point,!0)}}onBeforeRender(){var A,e,g;if(!this._controls||this._cameraObject!==this.context.mainCamera)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this.autoRotate=!1,this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let I=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(I||(I=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),I?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){const i=this.context.time.deltaTime*this.targetLerpSpeed;if(this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject){if(this.useSlerp){const o=(A=this._cameraObject)==null?void 0:A.position;sJ(o,this._cameraTargetPosition,i)}else(e=this._cameraObject)==null||e.position.lerp(this._cameraTargetPosition,i);this._cameraObject.position.distanceTo(this._cameraTargetPosition)<1e-4&&(this._lerpCameraToTarget=!1)}this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,i),this._lookTargetPosition.distanceTo(this._controls.target)<1e-5&&(this._lerpToTargetPosition=!1))}!rw&&(g=this.lookAtConstraint)!=null&&g.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&!this.context.isInXR&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent,this._controls.update())}setCameraTarget(A,e=!1){var g;A?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=A.clone(),e&&this._cameraTargetPosition&&((g=this.controllerObject)==null||g.position.copy(this._cameraTargetPosition))):this._lerpCameraToTarget=!1}setFromTargetPosition(A=0,e=1){var g;if(!this._controls)return!1;const I=(g=this.lookAtConstraint)==null?void 0:g.sources;if(I&&I.length>0){const i=I[A];if(i)return i.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,e),!0}return!1}setTarget(A=null,e=!1){this._controls&&(A!==null&&this._lookTargetPosition.copy(A),e?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(A,e){this._controls&&this._controls.target.lerp(A,e)}distanceToTarget(A){return this._controls?this._controls.target.distanceTo(A):-1}setTargetFromRaycast(){var A,e;if(!this.controls)return;const g=this.context.physics.raycast();for(const I of g)if(I.distance>0&&eA.isActiveInHierarchy(I.object)){if(this._lookTargetPosition.copy(I.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;const i=ye(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition),(e=(A=this._cameraObject)==null?void 0:A.parent)==null||e.worldToLocal(this._cameraTargetPosition)}break}}fitCamera(A,e=1.1){const g=this._cameraObject,I=this._controls;if(A!=null&&A.length||(A=this.context.scene.children),!g||!I)return;const i=new f,o=new f,C=new BI;C.makeEmpty();for(const c of A)c instanceof Nf||C.expandByObject(c,!0);g.updateMatrixWorld(),g.updateProjectionMatrix(),C.getCenter(o),C.applyMatrix4(g.matrixWorldInverse),C.getSize(i),C.setFromCenterAndSize(o,i);const s=g.fov,a=2*Math.atan(Math.tan(s*Math.PI/360/2)*g.aspect)/Math.PI*360,n=i.y/(2*Math.atan(Math.PI*s/360)),B=i.x/(2*Math.atan(Math.PI*a/360)),Q=e*Math.max(n,B)+i.z/2;NH&&console.log("Fit camera to objects",n,B,"distance",Q);const E=ye(g),h=I.target.clone().sub(E).normalize().multiplyScalar(Q);if(I.maxDistance=Q*10,I.minDistance=Q*.01,I.target.copy(o),g.near=Q/100,g.far=Q*100,g.updateMatrixWorld(),g.updateProjectionMatrix(),tg(g,I.target.clone().sub(h)),NH){const c=new Nf(C);this.context.scene.add(c),cJ(c,ou(g)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",l=>{l.code==="KeyF"&&this.fitCamera(A)}))}I.update()}}etA([w(Sc)],vs.prototype,"lookAtConstraint",2);var gtA=Object.defineProperty,ItA=Object.getOwnPropertyDescriptor,oo=(t,A,e,g)=>{for(var I=g>1?void 0:g?ItA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&>A(A,e,I),I},KH=(t=>(t[t.Skybox=1]="Skybox",t[t.SolidColor=2]="SolidColor",t[t.Uninitialized=4]="Uninitialized",t))(KH||{});const Oc=aA("debugcam"),JH=aA("debugscreenpointtoray");var Bw;const Pc=(Bw=class extends RA{constructor(){super(...arguments),r(this,"_nearClipPlane",.1),r(this,"_farClipPlane",1e3),r(this,"orthographic",!1),r(this,"orthographicSize",5),r(this,"ARBackgroundAlpha",0),r(this,"_cullingMask",4294967295),r(this,"_backgroundBlurriness"),r(this,"_backgroundIntensity"),r(this,"_targetTexture",null),r(this,"_backgroundColor"),r(this,"_fov"),r(this,"_cam",null),r(this,"_clearFlags",2),r(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof Xe?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof Xe?this._cam.fov:this._fov}set fieldOfView(t){const A=this._fov!=t;if(this._fov=t,A&&this._cam&&this._cam instanceof Xe){if(this._fov===void 0){console.error("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(t){const A=this._nearClipPlane!=t;this._nearClipPlane=t,this._cam&&A&&(this._cam.near=t,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(t){const A=this._farClipPlane!=t;this._farClipPlane=t,this._cam&&A&&(this._cam.far=t,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(t){t!==this._clearFlags&&(this._clearFlags=t,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(t){this._cullingMask=t,this._cam&&(this._cam.layers.mask=t)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set backgroundBlurriness(t){t!==this._backgroundBlurriness&&(t===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(t,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(t){t!==this._backgroundIntensity&&(t===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(t,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(t){if(t){if(this._backgroundColor)this._backgroundColor.copy(t);else{if(!t.clone)return;this._backgroundColor=t.clone()}t.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(t){this._targetTexture=t}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(t,A,e){let g=this.cam;const I=Pc._origin;I.set(t,A,-1),this.context.input.convertScreenspaceToRaycastSpace(I),JH&&console.log("screenPointToRay",t.toFixed(2),A.toFixed(2),"now:",I.x.toFixed(2),I.y.toFixed(2),"isInXR:"+this.context.isInXR),I.z=-1,I.unproject(g);const i=Pc._direction.set(I.x,I.y,I.z),o=ye(g);return i.sub(o),i.normalize(),e?(e.set(o,i),e):new As(o.clone(),i.clone())}awake(){this.sourceId||console.warn("Camera has no source - the camera should be exported inside a gltf",this.name),JH&&window.addEventListener("pointerdown",t=>{const A=t.clientX,e=t.clientY;console.log("touch",A.toFixed(2),e.toFixed(2));const g=this.screenPointToRay(A,e),I="#"+Math.floor(Math.random()*16777215).toString(16);nC.DrawRay(g.origin,g.direction,I,10)})}onEnable(){Oc&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),otA(this)),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&this._targetTexture){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const t=this.context.renderer;t&&this._targetTexture.render(this.context.scene,this._cam,t)}}buildCamera(){if(this._cam)return;const t=this.gameObject.isCamera;let A=null;if(t?(A=this.gameObject,A?.layers.enableAll(),A instanceof Xe&&(this._fov=A.fov)):A=this.gameObject.children[0],A&&A.isCamera)A.type==="PerspectiveCamera"&&(this._fov&&(A.fov=this._fov),A.near=this._nearClipPlane,A.far=this._farClipPlane,A.updateProjectionMatrix());else if(!this.orthographic)A=new Xe(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(A.fov=this.fieldOfView),this.gameObject.add(A);else{const e=this.orthographicSize*100;A=new MB(window.innerWidth/-e,window.innerWidth/e,window.innerHeight/e,window.innerHeight/-e,this._nearClipPlane,this._farClipPlane),this.gameObject.add(A)}this._cam=A,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){Oc&&console.log("Camera does not exist (apply clear flags)");return}switch(Oc&&Hg("apply Camera clear flags: "+this._clearFlags),this._clearFlags){case 1:if(Pc.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox(),this._backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this._backgroundBlurriness),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity);break;case 2:if(this._backgroundColor){let t=this._backgroundColor.alpha;Pc.backgroundShouldBeTransparent(this.context)&&(t=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,t)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}enableSkybox(){this._skybox||(this._skybox=new itA(this)),this._skybox.enable()}static backgroundShouldBeTransparent(t){var A,e,g,I;const i=(A=t.renderer.xr)==null?void 0:A.getSession();if(!i)return!1;const o=i.environmentBlendMode;Oc&&Hg("Environment blend mode: "+o+" on "+navigator.userAgent);const C=o==="additive"||o==="alpha-blend";return t.xrSessionMode===gc.ImmersiveAR&&o==="opaque"&&((e=navigator.userAgent)!=null&&e.includes("OculusBrowser")||(g=navigator.userAgent)!=null&&g.includes("Mozilla")&&(I=navigator.userAgent)!=null&&I.includes("Mobile WebXRViewer/v2"))?!0:C}},r(Bw,"_origin",new f),r(Bw,"_direction",new f),Bw);let Kt=Pc;oo([w()],Kt.prototype,"fieldOfView",1),oo([w()],Kt.prototype,"nearClipPlane",1),oo([w()],Kt.prototype,"farClipPlane",1),oo([w()],Kt.prototype,"clearFlags",1),oo([w()],Kt.prototype,"orthographic",2),oo([w()],Kt.prototype,"orthographicSize",2),oo([w()],Kt.prototype,"ARBackgroundAlpha",2),oo([w()],Kt.prototype,"cullingMask",1),oo([w()],Kt.prototype,"backgroundBlurriness",1),oo([w()],Kt.prototype,"backgroundIntensity",1),oo([w(wt)],Kt.prototype,"backgroundColor",1),oo([w(DQ)],Kt.prototype,"targetTexture",1);class itA{constructor(A){r(this,"_camera"),r(this,"_skybox"),this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(Oc&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=ue,this._skybox.mapping=vi,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this._camera.sourceId,this.context.lightmaps)}}function otA(t){aA("freecam")&&t.context.mainCameraComponent===t&&eA.getOrAddComponent(t.gameObject,vs)}class TQ extends RA{constructor(){super(...arguments),r(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new Gf),this._listener}awake(){hg.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const A=this.listener;if(A==null||A.parent)return;const e=eA.getComponentInParent(this.gameObject,Kt);e?e.cam.add(A):this.gameObject.add(A)})}}var CtA=Object.defineProperty,stA=Object.getOwnPropertyDescriptor,Qw=(t,A,e,g)=>{for(var I=g>1?void 0:g?stA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&CtA(A,e,I),I};class jc{constructor(){r(this,"guid")}}Qw([w()],jc.prototype,"guid",2);class _Q{constructor(){r(this,"signal"),r(this,"reaction")}}Qw([w(jc)],_Q.prototype,"signal",2),Qw([w(ti)],_Q.prototype,"reaction",2);var AM;const Ls=(AM=class extends RA{constructor(){super(...arguments),r(this,"events")}static invoke(t){if(Ls.receivers[t]){const A=Ls.receivers[t];if(!A)return;for(const e of A)e.invoke(t)}}onEnable(){if(this.events)for(const t of this.events)Ls.receivers[t.signal.guid]||(Ls.receivers[t.signal.guid]=[]),Ls.receivers[t.signal.guid].push(this)}onDisable(){if(this.events){for(const t of this.events)if(Ls.receivers[t.signal.guid]){const A=Ls.receivers[t.signal.guid].indexOf(this);A>=0&&Ls.receivers[t.signal.guid].splice(A,1)}}}invoke(t){if(!this.events||!Array.isArray(this.events))return;let A=typeof t=="object"?t.guid:t;for(const e of this.events)if(e.signal.guid===A)try{if(e.reaction){if(!e.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",e,this);continue}}else{console.warn("Missing reaction for signal",e,this);continue}e.reaction.invoke()}catch(g){console.error(g)}}},r(AM,"receivers",{}),AM);let OQ=Ls;Qw([w(_Q)],OQ.prototype,"events",2);var mi=(t=>(t.Activation="ActivationTrack",t.Animation="AnimationTrack",t.Audio="AudioTrack",t.Control="ControlTrack",t.Marker="MarkerTrack",t.Signal="SignalTrack",t))(mi||{}),on=(t=>(t[t.None=0]="None",t[t.Hold=1]="Hold",t[t.Loop=2]="Loop",t[t.PingPong=3]="PingPong",t[t.Continue=4]="Continue",t))(on||{}),eM=(t=>(t.Signal="SignalEmitter",t))(eM||{});const Wc=aA("debugtimeline"),tM=class extends RA{constructor(){super(...arguments),r(this,"playableAsset"),r(this,"playOnAwake"),r(this,"extrapolationMode",1),r(this,"waitForAudio",!0),r(this,"_visibilityChangeEvt"),r(this,"_clonedPlayableAsset",!1),r(this,"_speed",1),r(this,"_guidsMap"),r(this,"_isPlaying",!1),r(this,"_internalUpdateRoutine"),r(this,"_isPaused",!1),r(this,"_time",0),r(this,"_duration",0),r(this,"_weight",1),r(this,"_animationTracks",[]),r(this,"_audioTracks",[]),r(this,"_signalTracks",[]),r(this,"_controlTracks",[]),r(this,"_customTracks",[]),r(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks])}static registerCreateTrack(t,A){this.createTrackFunctions[t]=A}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(t){typeof t=="number"&&!Number.isNaN(t)?this._time=t:(Wc||fI())&&console.error("INVALID TIMELINE.TIME VALUE",t,this.name)}get duration(){return this._duration}set duration(t){this._duration=t}get weight(){return this._weight}set weight(t){this._weight=t}get speed(){return this._speed}set speed(t){this._speed=t}awake(){var t,A,e;Wc&&console.log(this,(t=this.playableAsset)==null?void 0:t.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(A=this.playableAsset)==null?void 0:A.tracks,Array.isArray((e=this.playableAsset)==null?void 0:e.tracks),this)}onEnable(){var t,A;for(const e of this._audioTracks)(t=e.onEnable)==null||t.call(e);for(const e of this._customTracks)(A=e.onEnable)==null||A.call(e);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(){var t,A;this.stop();for(const e of this._audioTracks)(t=e.onDisable)==null||t.call(e);for(const e of this._customTracks)(A=e.onDisable)==null||A.call(e);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var t;for(const A of this._allTracks)for(const e of A)(t=e.onDestroy)==null||t.call(e)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const t=this._isPaused==!0;if(this._isPaused=!1,t&&this.invokePauseChangedMethodsOnTracks(),!this._isPlaying){if(this._isPlaying=!0,this.waitForAudio){const A=[];for(const e of this._audioTracks){const g=e.loadAudio(this._time,1,0);g&&A.push(g)}if(A.length>0&&(await Promise.all(A),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!hg.userInteractionRegistered&&this.waitForAudio;)await _E(200)}this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.evaluate(),this.invokePauseChangedMethodsOnTracks()))}stop(){for(const e of this._audioTracks)e.stop();const t=this._isPaused==!0,A=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate(),t&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,t&&!A&&this.invokePauseChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}this.internalEvaluate(t)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const t of this._allTracks)for(const A of t)yield A}get audioTracks(){return this._audioTracks}resolveGuids(t){this._guidsMap=t}invokePauseChangedMethodsOnTracks(){var t;for(const A of this.forEachTrack())(t=A.onPauseChanged)==null||t.call(A)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.evaluate()),yield}internalEvaluate(t){for(const A of this.playableAsset.tracks)if(!A.muted)switch(A.type){case mi.Activation:for(let e=0;e<A.outputs.length;e++){const g=A.outputs[e];if(typeof g=="object"){let I=!1;for(const o of A.clips)o.start<=t&&t<=o.end&&(I=!0);const i=g;i.visible!==void 0&&(i.visible=I)}}break}for(const A of this._animationTracks)A.evaluate(t);for(const A of this._audioTracks)A.evaluate(t);for(const A of this._signalTracks)A.evaluate(t);for(const A of this._controlTracks)A.evaluate(t);for(const A of this._customTracks)A.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Sd(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const t=this.findRoot(this.gameObject);for(const A of this.playableAsset.tracks){for(let e=A.outputs.length-1;e>=0;e--){let g=A.outputs[e];if(typeof g=="string"){this._guidsMap&&this._guidsMap[g]&&(g=this._guidsMap[g]);const I=eA.findByGuid(g,t);I===null||typeof I!="object"?(A.outputs.splice(e,1),console.warn("Failed to resolve binding",g,A.name,A.type)):(Wc&&console.log("Resolved binding",g,"to",I),A.outputs[e]=I)}else if(g===null){if(A.outputs.splice(e,1),tM.createTrackFunctions[A.type])continue;A.type!==mi.Audio&&A.type!==mi.Control&&A.type!==mi.Marker&&A.type!==mi.Signal&&console.warn("Missing binding",g,A.name,A.type,this.name,this.playableAsset.name)}}if(A.type===mi.Control)for(let e=0;e<A.clips.length;e++){const g=A.clips[e];let I=g.asset.sourceObject;if(typeof I=="string"){this._guidsMap&&this._guidsMap[I]&&(I=this._guidsMap[I]);const i=eA.findByGuid(I,t);i===null||typeof i!="object"?console.warn("Failed to resolve sourceObject binding",I,A.name,g):(Wc&&console.log("Resolved binding",I,"to",i),g.asset.sourceObject=i)}}}}findRoot(t){return t.parent?this.findRoot(t.parent):t}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const t of this.playableAsset.tracks)if(t.muted!==!0){for(const A of t.clips)A.end>this._duration&&(this._duration=A.end);for(const A of t.markers)A.time>this._duration&&(this._duration=A.time+.001)}}}setupAndCreateTrackHandlers(){var t,A;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;const e=eA.findObjectOfType(TQ,this.context);for(const g of this.playableAsset.tracks){const I=g.type,i=tM.createTrackFunctions[I];if(i!=null){const o=i(this,g);if(typeof o.evaluate=="function"){o.director=this,o.track=g,this._customTracks.push(o);continue}}if(g.type===mi.Animation){if(g.clips.length<=0){Wc&&console.warn("Animation track has no clips",g);continue}for(let o=g.outputs.length-1;o>=0;o--){let C=g.outputs[o];if(C instanceof UA){const a=eA.getOrAddComponent(C,Ai);a&&(C=a)}const s=(t=C?.gameObject)==null?void 0:t.animations;if(s){const a=new Ew;a.trackOffset=g.trackOffset,a.director=this,a.track=g;for(let n=0;n<g.clips.length;n++){const B=g.clips[n],Q=B.asset;if(!Q){console.error("MISSING anim model?","clip#"+n,B,g,this.playableAsset,this.name);continue}const E=Q.clip;let h=E;if((typeof h=="string"||typeof h=="number")&&(h=s.find(l=>l.name===E)),!h){console.warn("Could not find animationClip for model",B,g.name,this.name,(A=this.playableAsset)==null?void 0:A.name);continue}a.mixer||(a.mixer=new Pp(C.gameObject)),a.clips.push(h),a.mixer.uncacheAction(h),a.createHooks(B.asset,h);const c=a.mixer.clipAction(h);a.actions.push(c),a.models.push(B)}this._animationTracks.push(a)}}}else if(g.type===mi.Audio){if(g.clips.length<=0)continue;const o=new Xc;if(o.director=this,o.track=g,this._audioTracks.push(o),!e)continue;o.listener=e.listener;for(let C=0;C<g.clips.length;C++){const s=g.clips[C];o.addModel(s)}}else if(g.type===mi.Marker){const o=new $c;o.director=this,o.track=g;for(const C of g.markers)switch(C.type){case eM.Signal:o.models.push(C),o.didTrigger.push(!1);break}if(o!==null&&o.models.length>0){const C=eA.getComponent(this.gameObject,OQ);C&&(o.receivers.push(C),this._signalTracks.push(o))}}else if(g.type===mi.Signal){const o=new $c;o.director=this,o.track=g;for(const C of g.markers)o.models.push(C),o.didTrigger.push(!1);for(const C of g.outputs)o.receivers.push(C);this._signalTracks.push(o)}else if(g.type===mi.Control){const o=new hw;o.director=this,o.track=g;for(const C of g.clips)o.models.push(C);o.resolveSourceObjects(this.context),this._controlTracks.push(o)}}}setAudioTracksAllowPlaying(t){for(const A of this._audioTracks)A.onAllowAudioChanged(t)}};let Vc=tM;r(Vc,"createTrackFunctions",{});const Mr=aA("debugtimeline");class zc{constructor(){r(this,"director"),r(this,"track")}get muted(){return this.track.muted}set muted(A){var e;A!==this.track.muted&&(this.track.muted=A,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(A=!1){var e;if((e=this.track)!=null&&e.clips)if(A)for(let g=this.track.clips.length-1;g>=0;g--)yield this.track.clips[g];else for(const g of this.track.clips)yield g}getClipTime(A,e){return e.clipIn+(A-e.start)*e.timeScale}getClipTimeNormalized(A,e){return(A-e.start)/e.duration}evaluateWeight(A,e,g,I=!0){if(e<0||e>=g.length)return 0;const i=g[e];if(I||A>=i.start&&A<=i.end){let o=1,C=!1;if(i.easeInDuration>0){const s=Math.min((A-i.start)/i.easeInDuration,1);o*=s}if(i.easeOutDuration>0&&!C){const s=Math.min((i.end-A)/i.easeOutDuration,1);o*=s}return o}return 0}}class atA{constructor(A){r(this,"clip"),r(this,"rootPositionOffset"),r(this,"rootQuaternionOffset"),r(this,"rootStartPosition"),r(this,"rootEndPosition"),r(this,"rootStartQuaternion"),r(this,"rootEndQuaternion");const e=A.getClip();this.clip=e;const g=A.getRoot(),I=g.name+".position",i=g.name+".quaternion";Mr&&console.log(e.name,e.tracks,I);for(const o of e.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(I))this.rootStartPosition=new f().fromArray(o.values,0),this.rootEndPosition=new f().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Mr&&console.log(this.rootPositionOffset);else if(o.name.endsWith(i)&&(this.rootStartQuaternion=new GA().fromArray(o.values,0),this.rootEndQuaternion=new GA().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Mr)){const C=new fg().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",C)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Ew extends zc{constructor(){super(...arguments),r(this,"models",[]),r(this,"trackOffset"),r(this,"target"),r(this,"mixer"),r(this,"clips",[]),r(this,"actions",[]),r(this,"_actionOffsets",[]),r(this,"_didBind",!1),r(this,"_animator",null),r(this,"_animatorWasEnabled",!1),r(this,"_useclipOffsets",!0),r(this,"_totalOffsetPosition",new f),r(this,"_totalOffsetRotation",new GA),r(this,"_totalOffsetPosition2",new f),r(this,"_totalOffsetRotation2",new GA),r(this,"_summedPos",new f),r(this,"_tempPos",new f),r(this,"_summedRot",new GA),r(this,"_tempRot",new GA),r(this,"_clipRotQuat",new GA)}onPauseChanged(){this._animator&&this._animatorWasEnabled!==void 0&&(this._animator.enabled=this.director.isPlaying===!1?this._animatorWasEnabled:!1)}createHooks(A,e){var g,I;if(((g=e.tracks)==null?void 0:g.length)<=0){console.warn("No tracks in AnimationClip",e);return}const i=e.tracks[0].name.split("."),o=i[i.length-2],C=o+".position",s=o+".quaternion";let a=!1,n=!1;for(const B of e.tracks)B.name.endsWith(C)?(a=!0,this.createPositionInterpolant(e,A,B)):B.name.endsWith(s)&&(n=!0,this.createRotationInterpolant(e,A,B));if(!a||!n){const B=(I=this.mixer)==null?void 0:I.getRoot(),Q=e.tracks[0],E=Q.name.lastIndexOf("."),h=Q.name.substring(0,E),c=h.substring(h.lastIndexOf(".")+1),l=B.getObjectByName(c);if(l)if(a){if(!n){const d=e.tracks[0].name.substring(0,E)+".quaternion";Mr&&console.warn("Create quaternion track",c,l);const u=l.quaternion,p=new Zo(d,[0,e.duration],[u.x,u.y,u.z,u.w,u.x,u.y,u.z,u.w]);e.tracks.push(p),this.createRotationInterpolant(e,A,p)}}else{const d=h+".position";Mr&&console.warn("Create position track",c,l);const u=l.position,p=new ya(d,[0,e.duration],[u.x,u.y,u.z,u.x,u.y,u.z]);e.tracks.push(p),this.createPositionInterpolant(e,A,p)}}}bind(){if(!this._didBind){this._didBind=!0,Mr&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const A of this.actions){const e=new atA(A);this._actionOffsets.push(e)}this.target&&(this._animator=eA.getComponent(this.target,Ai)??null,this._animator?(this._animatorWasEnabled=this._animator.enabled,this._animator.enabled=!1):this._animatorWasEnabled=!1);for(const A of this.models){const e=A.asset,g=e.position,I=e.rotation;g&&g.x!==void 0&&(g.isVector3||(e.position=new f(g.x,g.y,g.z)),I.isQuaternion||(e.rotation=new GA(I.x,I.y,I.z,I.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const A=this.trackOffset.position;A&&(A.isVector3||(this.trackOffset.position=new f(A.x,A.y,A.z)));const e=this.trackOffset.rotation;e&&(e.isQuaternion||(this.trackOffset.rotation=new GA(e.x,e.y,e.z,e.w)))}}evaluate(A){if(this.track.muted||!this.mixer)return;this.bind(),this._animator&&this.director.isPlaying&&this.director.weight>0&&(this._animator.enabled=!1),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 e=0,g=0,I=!1,i=!1;for(let o=0;o<this.clips.length;o++){const C=this.models[o],s=this.actions[o],a=C.asset;s.weight=0;const n=A>=C.start&&A<=C.end,B=C.preExtrapolationMode,Q=C.postExtrapolationMode,E=o<this.clips.length-1?this.models[o+1]:null;let h=n,c=!1;if(!h&&!I&&C.end<A&&Q!==on.None?(!E||E.start>A)&&(h=!0,I=!0):o==0&&!h&&!i&&C.start>A&&B!==on.None&&(!E||E.start<A)&&(h=!0,c=!0,i=!0),h){let l=1;l*=this.evaluateWeight(A,o,this.models,h),l*=this.director.weight;let d=n;c&&B!==on.Hold&&(A+=C.start,d=!0);let u=this.getClipTime(A,C),p=0;const D=a.duration;if(c&&B===on.Hold&&(u=0),d){if(a.loop)for(p+=Math.floor(u/(D+1e-6));u>D;)u-=D}else if(!n)switch(Q){case on.Loop:u%=D;break;case on.PingPong:const k=Math.floor(u/D)%2!==0;u%=D,k&&(u=D-u);break}C.reversed===!0?s.time=s.getClip().duration-u:s.time=u,s.timeScale=0;const y=l;if(s.weight=y,s.clampWhenFinished=!0,s.isRunning()||s.play(),this._useclipOffsets){const k=e==0?this._totalOffsetPosition:this._totalOffsetPosition2,F=e==0?this._totalOffsetRotation:this._totalOffsetRotation2;e<1&&(g=1-l),e+=1;const S=this._summedPos.set(0,0,0),U=this._tempPos.set(0,0,0),M=this._summedRot.identity(),Y=this._tempRot.identity(),_=a.rotation;_&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(_,l));const x=this._actionOffsets[o];if(x.hasOffsets)for(let v=0;v<p;v++)x.rootPositionOffset?U.copy(x.rootPositionOffset):U.set(0,0,0),U.applyQuaternion(M),this._clipRotQuat&&U.applyQuaternion(this._clipRotQuat),x.rootQuaternionOffset&&(Y.copy(x.rootQuaternionOffset),M.multiply(Y)),S.add(U);this._clipRotQuat&&F.multiply(this._clipRotQuat),F.multiply(M),a.position&&S.add(a.position),k.add(S)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,g),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,g)),this.mixer.update(A)}createRotationInterpolant(A,e,g){var I;const i=g.createInterpolant.bind(g),o=new GA;this.ensureTrackOffsets();const C=(I=this.trackOffset)==null?void 0:I.rotation;g.createInterpolant=()=>{const s=i(),a=s.evaluate.bind(s);return s.evaluate=n=>{const B=a(n);return o.set(B[0],B[1],B[2],B[3]),o.premultiply(this._totalOffsetRotation),C&&o.premultiply(C),B[0]=o.x,B[1]=o.y,B[2]=o.z,B[3]=o.w,B},s}}createPositionInterpolant(A,e,g){var I,i;const o=g.createInterpolant.bind(g),C=new f;this.ensureTrackOffsets();const s=(I=this.trackOffset)==null?void 0:I.rotation,a=(i=this.trackOffset)==null?void 0:i.position;let n;g.createInterpolant=()=>{const B=o(),Q=B.evaluate.bind(B);return B.evaluate=E=>{var h,c;const l=Q(E);return C.set(l[0],l[1],l[2]),e.removeStartOffset&&(n===void 0?(n=null,n=(c=(h=this._actionOffsets.find(d=>d.clip===A))==null?void 0:h.rootStartPosition)==null?void 0:c.clone()):n!=null&&n.isVector3&&C.sub(n)),C.applyQuaternion(this._totalOffsetRotation),C.add(this._totalOffsetPosition),s&&C.applyQuaternion(s),a&&(C.x-=a.x,C.y+=a.y,C.z+=a.z),l[0]=C.x,l[1]=C.y,l[2]=C.z,l},B}}}const ntA=aA("mutetimeline"),Zc=class extends zc{constructor(){super(...arguments),r(this,"models",[]),r(this,"listener"),r(this,"audio",[]),r(this,"audioContextTimeOffset",[]),r(this,"lastTime",0),r(this,"_audioLoader",null)}getAudioFilePath(t){const A=this.director.sourceId;return Ia(A,t)}onAllowAudioChanged(t){for(let A=0;A<this.models.length;A++){const e=this.models[A];this.audio[A].setVolume(t?e.asset.volume:0)}}addModel(t){const A=new Op(this.listener);this.audio.push(A),this.models.push(t)}onDisable(){for(const t of this.audio)t.isPlaying&&t.stop()}onMuteChanged(){if(this.muted)for(let t=0;t<this.audio.length;t++){const A=this.audio[t];A!=null&&A.isPlaying&&A.stop()}}stop(){for(let t=0;t<this.audio.length;t++){const A=this.audio[t];A!=null&&A.isPlaying&&A.stop()}}evaluate(t){if(ntA||this.track.muted||this.director.speed<0)return;const A=this.director.context.application.muted,e=A?.1:0;for(let g=0;g<this.models.length;g++){const I=this.models[g],i=this.audio[g];if((!i||!i.buffer)&&this.isInTimeRange(I,t-1,t+1)&&this.handleAudioLoading(I,i),hg.userInteractionRegistered!==!1&&!(i===null||!i.buffer))if(i.playbackRate=this.director.context.time.timeScale,i.loop=I.asset.loop,t>=I.start&&t<=I.end&&t<this.director.duration){if(this.director.isPlaying==!1){if(i.isPlaying&&i.stop(),this.lastTime===t)continue}else if(!i.isPlaying)i.offset=I.clipIn+(t-I.start)*I.timeScale,i.play(e);else{const C=I.clipIn+(t-I.start)*I.timeScale,s=i.context.currentTime-i._startedAt+i.offset;Math.abs(C-s)>.3&&(i.offset=C,i.stop(),i.play(e))}let o=I.asset.volume;if(A&&(o=0),I.easeInDuration>0){const C=Math.min((t-I.start)/I.easeInDuration,1);o*=C}if(I.easeOutDuration>0){const C=Math.min((I.end-t)/I.easeOutDuration,1);o*=C}i.setVolume(o*this.director.weight)}else i.isPlaying&&i.stop()}this.lastTime=t}loadAudio(t,A=0,e=0){let g=null;const I=t-e,i=t+A;for(const o of this.models)if(this.isInTimeRange(o,I,i)){const C=this.audio[this.models.indexOf(o)],s=this.handleAudioLoading(o,C);s!==null&&(g===null&&(g=[]),g.push(s))}return g!==null?Promise.all(g):null}isInTimeRange(t,A,e){return A<=t.start&&e>=t.end||A>=t.start&&A<=t.end||e>=t.start&&e<=t.end}static dispose(){Zc._currentlyLoading.clear()}handleAudioLoading(t,A){this._audioLoader||(this._audioLoader=new Tp);const e=this.getAudioFilePath(t.asset.clip);if(Zc._currentlyLoading.get(e)){const I=Zc._currentlyLoading.get(e);return I.then(i=>{i&&A.setBuffer(i)}),I}Mr&&console.warn("LOAD audio track",e,this.director.sourceId);const g=new Promise((I,i)=>{this._audioLoader.load(e,o=>{A.setBuffer(o),I(o)},void 0,o=>{console.error("Error loading audio",o),I(null)})});return Zc._currentlyLoading.set(e,g),g}};let Xc=Zc;r(Xc,"_currentlyLoading",new Map);class $c extends zc{constructor(){super(...arguments),r(this,"models",[]),r(this,"didTrigger",[]),r(this,"receivers",[])}evaluate(A){var e;if(!this.track.muted)for(let g=0;g<this.models.length;g++){const I=this.models[g],i=this.didTrigger[g],o=I.time-A;let C=!1;if(I.retroActive)C=o<=1e-6;else{const s=Math.abs(o);s>=1e-5&&s<.1&&(C=!0)}if(C){if(!i)if(this.didTrigger[g]=!0,((e=this.receivers)==null?void 0:e.length)<=0)OQ.invoke(I.asset);else for(const s of this.receivers)s&&s.invoke(I.asset)}else I.emitOnce||(this.didTrigger[g]=!1)}}}class hw extends zc{constructor(){super(...arguments),r(this,"models",[]),r(this,"timelines",[]),r(this,"_previousActiveModel",null)}resolveSourceObjects(A){for(let e=this.models.length-1;e>=0;e--){const g=this.models[e].asset;if(!g.sourceObject||typeof g.sourceObject!="object"){console.log("no source object, removing model",e,g),this.models.splice(e,1);continue}else{const I=eA.getComponent(g.sourceObject,Vc);this.timelines.push(I),I&&g.updateDirector&&(I.playOnAwake=!1)}}}evaluate(A){var e;this._previousActiveModel=null;for(let g=0;g<this.models.length;g++){const I=this.models[g],i=I.asset;if(A>=I.start&&A<=I.end){this._previousActiveModel=I;const o=this.getClipTime(A,I);if(i.controlActivation){const C=i.sourceObject;C.visible=!0}if(i.updateDirector){const C=this.timelines[g];C&&(C.isPlaying&&C.pause(),C.time=o,C.evaluate())}}else{const o=(e=this._previousActiveModel)==null?void 0:e.asset;if(i.controlActivation){const C=i.sourceObject;o?.sourceObject!==C&&(C.visible=!1)}}}}}var rtA=Object.defineProperty,BtA=Object.getOwnPropertyDescriptor,qH=(t,A,e,g)=>{for(var I=g>1?void 0:g?BtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&rtA(A,e,I),I};class qe{constructor(A){r(this,"_active",!0),r(this,"_value"),r(this,"_valueRaw"),r(this,"_defaultValue"),r(this,"valueProcessor"),r(this,"onValueChanged"),this._value=A,this._defaultValue=A}get overrideState(){return this._active}set overrideState(A){if(this._active===A)return;this._active=A;const e=A?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(A){this.processValue(A,!1)}set defaultValue(A){this._defaultValue=A}__init(){this.processValue(this._valueRaw,!0)}processValue(A,e){if(A==null||!e&&this.testIfValueChanged(A)===!1)return;const g=this._value;!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,A=this._defaultValue,this._valueRaw=A):(this._valueRaw=A,this._active&&this.valueProcessor&&(A=this.valueProcessor(A)),this._value=A),this.onValueChanged&&this.onValueChanged(A,g,this)}testIfValueChanged(A){return this._valueRaw!==A}}qH([w()],qe.prototype,"overrideState",1),qH([w()],qe.prototype,"value",1);var QtA=Object.defineProperty,EtA=Object.getOwnPropertyDescriptor,htA=(t,A,e,g)=>{for(var I=g>1?void 0:g?EtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&QtA(A,e,I),I};const ctA=aA("debugpost");class TI extends Ja{constructor(){super(...arguments),r(this,"active",!0),r(this,"_result")}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var A;return this._result||(this._result=(A=this.onCreateEffect)==null?void 0:A.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){ctA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(A=>A.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const A=Object.keys(this);for(const e of A){const g=this[e];g instanceof qe&&g.__init()}}onAfterDeserialize(A,e){if(typeof A=="object"){const g=this.$serializedTypes;if(g){for(const I of Object.keys(g))if(g[I]===qe){const i=A[I];if(i!==void 0){const o=this[I];o.value=i}}}}}onEditorModification(A){const e=A.propertyName;if(this[e]instanceof qe){const g=A.value;return this[e].value=g,!0}}}htA([w()],TI.prototype,"active",2);var ltA=Object.defineProperty,dtA=Object.getOwnPropertyDescriptor,ptA=(t,A,e,g)=>{for(var I=g>1?void 0:g?dtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&<A(A,e,I),I};const utA=aA("debugpost"),gM={};function uC(t,A){gM[t]=A}function DtA(t){return t.__type in gM?gM[t.__type]:(utA&&t.__type&&console.warn("Unknown postprocessing type",t.__type,t),TI)}class Al{constructor(){r(this,"components")}init(){var A;(A=this.components)==null||A.forEach(e=>e.init())}}ptA([gQ([t=>DtA(t),TI])],Al.prototype,"components",2);var wtA=Object.defineProperty,ytA=Object.getOwnPropertyDescriptor,StA=(t,A,e,g)=>{for(var I=g>1?void 0:g?ytA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&wtA(A,e,I),I};class el extends TI{constructor(){super(...arguments),r(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const A=new Oz({preset:AQ.HIGH,edgeDetectionMode:kk.DEPTH});return this.preset.onValueChanged=e=>{A.applyPreset(e)},A}}StA([w(qe)],el.prototype,"preset",2),uC("Antialiasing",el);class cw{constructor(){r(this,"files",[])}get extensionName(){return"Audio"}onExportObject(A,e,g){const I=eA.getComponents(A,hg);if(I.length)for(const i of I){if(!i.playOnAwake)continue;const o=i.clip.split("/").pop();this.files.includes(i.clip)||this.files.push(i.clip),e.addEventListener("serialize",(C,s)=>{C.appendLine(),C.beginBlock(`def SpatialAudio "${e.name}"`),C.appendLine(`uniform asset filePath = @audio/${o}@`),C.appendLine(`uniform token auralMode = "${i.spatialBlend>0?"spatial":"nonSpatial"}"`),C.appendLine(`uniform token playbackMode = "${i.loop?"loopFromStage":"onceFromStart"}"`),C.appendLine(`uniform float gain = ${i.volume}`),C.closeBlock()})}}async onAfterSerialize(A){console.warn("onAfterSerialize",this);for(const e of this.files){const g=e.split("/").pop(),I=await(await(await fetch(e)).blob()).arrayBuffer(),i=new Uint8Array(I);A.files["audio/"+g]=i}}}var ftA=Object.defineProperty,ktA=Object.getOwnPropertyDescriptor,bH=(t,A,e,g)=>{for(var I=g>1?void 0:g?ktA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&ftA(A,e,I),I};const GtA=aA("debugmouth");class tl extends RA{constructor(){super(...arguments),r(this,"idle",[]),r(this,"talking",[]),r(this,"marker",null),r(this,"voip",null),r(this,"lastMouthChangeTime",0),r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=eA.findObjectOfType(Xs,this.context),this.marker||(this.marker=eA.getComponentInParent(this.gameObject,uI))},3e3)}update(){var A;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((A=this.marker)==null?void 0:A.connectionId)??null;if(!e){GtA&&(e=null);return}const g=this.voip.getFrequency(e)??0;this.updateLips(g)}updateLips(A){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&A>30){this.lastMouthChangeTime=this.context.time.time;const e=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,e)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const e=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,e)}}}setMouthShapeActive(A,e){if(A){A!=this.idle?this.idle.map(g=>g.visible=!1):this.talking.map(g=>g.visible=!1);for(let g=0;g<A.length;g++){const I=A[g];I&&(I.visible=g===e)}}}}bH([w(UA)],tl.prototype,"idle",2),bH([w(UA)],tl.prototype,"talking",2);class IM extends RA{constructor(){super(...arguments),r(this,"voip",null),r(this,"marker",null),r(this,"_startPosition",null)}awake(){this.voip=eA.findObjectOfType(Xs,this.context),this.marker=eA.getComponentInParent(this.gameObject,uI)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const A=this.marker.connectionId,e=this.voip.getFrequency(A);if(e==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let g=e/100;this.gameObject.position.y=this._startPosition.y+g*.07}}var mtA=Object.defineProperty,MtA=Object.getOwnPropertyDescriptor,lw=(t,A,e,g)=>{for(var I=g>1?void 0:g?MtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&mtA(A,e,I),I};class Rr extends RA{constructor(){super(...arguments),r(this,"eyes",[]),r(this,"lastBlinkTime",0),r(this,"blinkLength",0),r(this,"eyesOpen",!0),r(this,"state",null)}awake(){this.state=eA.getComponentInParent(this.gameObject,xI)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&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(const A of this.eyes)A&&(A.visible=this.eyesOpen)}}}lw([w(UA)],Rr.prototype,"eyes",2),lw([w()],Rr.prototype,"lastBlinkTime",2),lw([w()],Rr.prototype,"blinkLength",2),lw([w()],Rr.prototype,"eyesOpen",2);var RtA=Object.defineProperty,UtA=Object.getOwnPropertyDescriptor,iM=(t,A,e,g)=>{for(var I=g>1?void 0:g?UtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&RtA(A,e,I),I},oM;const vH=(oM=class extends RA{constructor(){super(...arguments),r(this,"head",null),r(this,"eyes",null),r(this,"target",null),r(this,"brain",null),r(this,"vec",new f),r(this,"currentTargetPoint",new f)}awake(){this.brain||(this.brain=eA.getComponentInParent(this.gameObject,Gc)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=eA.addNewComponent(this.gameObject,Gc)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const t=this.target;if(t&&this.head){const A=this.eyes;if(A){const e=ye(t);this.currentTargetPoint.lerp(e,this.context.time.deltaTime/.1);const g=ye(this.head),I=this.vec.copy(this.currentTargetPoint).sub(g).normalize();if(I.length()<.1)return;const i=vH.forward;if(i.set(0,0,1),i.applyQuaternion(Ng(this.head)),i.dot(I)>.45)for(let o=0;o<A.length;o++)A[o].lookAt(this.currentTargetPoint)}}}},r(oM,"forward",new f(0,0,1)),oM);let PQ=vH;iM([w(UA)],PQ.prototype,"head",2),iM([w(UA)],PQ.prototype,"eyes",2),iM([w(UA)],PQ.prototype,"target",2);var FtA=Object.defineProperty,NtA=Object.getOwnPropertyDescriptor,CM=(t,A,e,g)=>{for(var I=g>1?void 0:g?NtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&FtA(A,e,I),I};class jQ extends RA{constructor(){super(...arguments),r(this,"length",1),r(this,"depthTest",!0),r(this,"isGizmo",!0),r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!Mh)return;this._axes||(this._axes=new _B(this.length)),this.gameObject.add(this._axes);const A=this._axes.material;A&&A.depthTest!==void 0&&(A.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}CM([w()],jQ.prototype,"length",2),CM([w()],jQ.prototype,"depthTest",2),CM([w()],jQ.prototype,"isGizmo",2);class sM extends RA{constructor(){super(...arguments),r(this,"from"),r(this,"to"),r(this,"hint"),r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let A=ye(this.to).clone(),e=ye(this.from).clone(),g=A.distanceTo(e),I=A.clone();I.sub(e);let i=e.clone();i.add(A),i.multiplyScalar(.5);let o=ye(this.hint).clone();o.sub(i);let C=new f;C.crossVectors(o,I),C.crossVectors(I,C),C.normalize();let s=g*.5,a=Math.max(this.desiredDistance,s),n=Math.sqrt(a*a-s*s),B=C.clone();B.multiplyScalar(n),B.add(i),tg(this.gameObject,B);let Q=i.clone();Q.sub(C),this.gameObject.lookAt(Q)}}class dw{constructor(){r(this,"behaviours",[]),r(this,"behaviourComponents",[]),r(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(A){this.behaviours.push(A)}onBeforeBuildDocument(A){A.root.traverse(e=>{eA.foreachComponent(e,g=>{var I;const i=g;(typeof i.createBehaviours=="function"||typeof i.beforeCreateDocument=="function"||typeof i.afterCreateDocument=="function")&&(this.behaviourComponents.push(i),(I=i.beforeCreateDocument)==null||I.call(i,this,A))},!1)})}onExportObject(A,e,g){var I;for(const i of this.behaviourComponents)(I=i.createBehaviours)==null||I.call(i,this,e,g)}onAfterBuildDocument(A){for(const e of this.behaviourComponents)typeof e.afterCreateDocument=="function"&&e.afterCreateDocument(this,A);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(A,e){var g;if((g=this.behaviours)!=null&&g.length){e.beginBlock('def Scope "Behaviors"');for(const I of this.behaviours)I.writeTo(this,A.document,e);e.closeBlock()}}async onAfterSerialize(A){console.log("onAfterSerialize",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)console.log("behaviour",e),typeof e.afterSerialize=="function"&&(console.log("beh has afterSerialize",e),e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,A):e.afterSerialize(this,A))}}var KtA=Object.defineProperty,JtA=Object.getOwnPropertyDescriptor,aM=(t,A,e,g)=>{for(var I=g>1?void 0:g?JtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&KtA(A,e,I),I};class Ur extends TI{constructor(){super(...arguments),r(this,"threshold"),r(this,"intensity"),r(this,"scatter"),r(this,"selectiveBloom",!0)}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>1*Math.PI*(1-A)):(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>100*(1-A))}onCreateEffect(){let A;if(this.selectiveBloom){const e=A=new Wb(this.context.scene,this.context.mainCamera,{blendFunction:Je.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});e.inverted=!0}else A=new Fk;return this.intensity.onValueChanged=e=>{A.intensity=e},this.threshold.onValueChanged=e=>{A.luminanceMaterial.threshold=e},this.scatter.onValueChanged=e=>{A.luminancePass.enabled=!0,A.luminanceMaterial.smoothing=e},A}}aM([w(qe)],Ur.prototype,"threshold",2),aM([w(qe)],Ur.prototype,"intensity",2),aM([w(qe)],Ur.prototype,"scatter",2),uC("Bloom",Ur);var qtA=Object.defineProperty,btA=Object.getOwnPropertyDescriptor,xo=(t,A,e,g)=>{for(var I=g>1?void 0:g?btA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&qtA(A,e,I),I};class DC extends RA{constructor(){super(...arguments),r(this,"attachedRigidbody",null),r(this,"isTrigger",!1),r(this,"sharedMaterial")}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ht))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ht))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ht))}onDisable(){var A;(A=this.context.physics.engine)==null||A.removeBody(this)}}xo([w(Ht)],DC.prototype,"attachedRigidbody",2),xo([w()],DC.prototype,"isTrigger",2),xo([w()],DC.prototype,"sharedMaterial",2);class gl extends DC{constructor(){super(...arguments),r(this,"radius",.5),r(this,"center",new f(0,0,0))}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addSphereCollider(this,this.center,this.radius)}}xo([w()],gl.prototype,"radius",2),xo([w(f)],gl.prototype,"center",2);class Il extends DC{constructor(){super(...arguments),r(this,"size",new f(1,1,1)),r(this,"center",new f(0,0,0))}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addBoxCollider(this,this.center,this.size)}}xo([w(f)],Il.prototype,"size",2),xo([w(f)],Il.prototype,"center",2);class il extends DC{constructor(){super(...arguments),r(this,"sharedMesh"),r(this,"convex",!1)}onEnable(){var A,e,g,I,i;if(super.onEnable(),(A=this.sharedMesh)!=null&&A.isMesh||this.gameObject instanceof yA&&(this.sharedMesh=this.gameObject),(e=this.sharedMesh)!=null&&e.isMesh)(g=this.context.physics.engine)==null||g.addMeshCollider(this,this.sharedMesh,this.convex,zg(this.gameObject));else{const o=this.sharedMesh;if(o!=null&&o.isGroup){console.warn(`MeshCollider mesh is a group "${(I=this.sharedMesh)==null?void 0:I.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);for(const C in o.children){const s=o.children[C];s.isMesh&&((i=this.context.physics.engine)==null||i.addMeshCollider(this,s,this.convex,zg(this.gameObject)))}}}}}xo([w()],il.prototype,"convex",2);class Cn extends DC{constructor(){super(...arguments),r(this,"center",new f(0,0,0)),r(this,"radius",.5),r(this,"height",2)}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addCapsuleCollider(this,this.center,this.height,this.radius)}}xo([w(f)],Cn.prototype,"center",2),xo([w()],Cn.prototype,"radius",2),xo([w()],Cn.prototype,"height",2);function nM(t){return t[Ns]||(t.parent?nM(t.parent):null)}function pw(t,A){if(!t)return;const e=t.material;if(e?.isMaterial===!0){const g=t.parent;g&&g.isText,e.side=A.doubleSided??!0?ft:kI,e.shadowSide=A.doubleSided?ft:kI,t.castShadow=A.castShadows?A.castShadows:!1,t.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const g of t.children)pw(g,A)}function WQ(t,A,e){t[A]===void 0&&console.warn("Field",A,"is undefined on",t);const g=Proxy.revocable(t[A],{set(o,C,s,a){const n=o[C],B=Reflect.set(o,C,s,a);return e(s,n),B}}),I=g.revoke,i=t[A];return g.revoke=()=>{t[A]=i,I()},t[A]=g.proxy,g}const LH=Symbol("Scheduled action");function vtA(t,A,e=ki.OnBeforeRender){let g=t[LH];g||(g=t[LH]={});const I=A.name;g[e]||(g[e]={});const i=g[e];if(i[I])return;function*o(){A?.call(t),i[I]=null}const C=t.startCoroutine(o(),e);i[I]=C}var LtA=Object.defineProperty,xtA=Object.getOwnPropertyDescriptor,Fr=(t,A,e,g)=>{for(var I=g>1?void 0:g?xtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&LtA(A,e,I),I};const rM=aA("debugui"),BM=aA("debuguilayout");class QM{constructor(){r(this,"width"),r(this,"height")}}class EM{constructor(){r(this,"x"),r(this,"y"),r(this,"width"),r(this,"height")}}const wC=new f,ol=new TA,uw=new GA,xH=class extends _o{constructor(){super(...arguments),r(this,"offset",.01),r(this,"_anchoredPosition"),r(this,"sizeDelta",new W(100,100)),r(this,"pivot",new W(.5,.5)),r(this,"anchorMin",new W(0,0)),r(this,"anchorMax",new W(1,1)),r(this,"offsetMin",new W(0,0)),r(this,"offsetMax",new W(0,0)),r(this,"lastMatrix"),r(this,"rectBlock"),r(this,"_transformNeedsUpdate",!1),r(this,"_initialPosition"),r(this,"_parentRectTransform"),r(this,"_lastUpdateFrame",-1),r(this,"_lastAnchoring"),r(this,"_createdBlocks",[]),r(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new W),this._anchoredPosition}set anchoredPosition(t){this._anchoredPosition=t}get width(){if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,A=this.anchorMax.x-this.anchorMin.x;let e=t*A;return e+=this.sizeDelta.x,e}return this.sizeDelta.x}get height(){if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,A=this.anchorMax.y-this.anchorMin.y;let e=t*A;return e+=this.sizeDelta.y,e}return this.sizeDelta.y}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new W),this.lastMatrix=new TA,this.rectBlock=new UA,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this.onApplyTransform("RectTransform awake"),WQ(this,"_anchoredPosition",()=>{this.markDirty()}),WQ(this,"sizeDelta",()=>{this.markDirty()}),WQ(this,"pivot",()=>{this.markDirty()}),WQ(this,"anchorMin",()=>{this.markDirty()}),WQ(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var t;super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(t=this.Canvas)==null||t.registerTransform(this)}onDisable(){var t;super.onDisable(),this.removeShadowComponent(),(t=this.Canvas)==null||t.unregisterTransform(this)}onParentRectTransformChanged(t){this._transformNeedsUpdate||this.onApplyTransform(BM?`${t.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(BM&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(t){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const A=this.shadowComponent;if(!A)return;this.gameObject.parent?this._parentRectTransform=eA.getComponentInParent(this.gameObject.parent,xH):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,BM&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+t),this.isRoot()?this.Root.screenspace||(A.rotation.y=Math.PI):(A.matrix.identity(),A.matrixAutoUpdate=!1,wC.set(0,0,0),this.applyPivot(wC),A.matrix.setPosition(wC.x,wC.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(uw.copy(this.gameObject.quaternion),uw.x*=-1,uw.z*=-1,ol.makeRotationFromQuaternion(uw),A.matrix.premultiply(ol)),wC.set(0,0,0),this.applyAnchoring(wC),wC.z+=this.offset,ol.identity(),ol.setPosition(wC.x,wC.y,wC.z),A.matrix.premultiply(ol),A.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const e=!0;for(const g of uk(this.gameObject,_o,e,1)){if(g===this||!g.activeAndEnabled)continue;const I=g;I.onParentRectTransformChanged&&I.onParentRectTransformChanged(this)}}applyAnchoring(t){this._lastAnchoring||(this._lastAnchoring=new W);const A=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=A.x,this.gameObject.position.y+=A.y,this._lastAnchoring.copy(this._anchoredPosition),t.x+=this._initialPosition.x-this.gameObject.position.x,t.y+=this._initialPosition.y-this.gameObject.position.y,t.z+=this._initialPosition.z-this.gameObject.position.z;const e=this._parentRectTransform;if(e){let g=0;const I=1-this.anchorMax.y-this.anchorMin.y;g-=e.height*.5*I,t.y+=g;let i=0;const o=1-this.anchorMax.x-this.anchorMin.x;i-=e.width*.5*o,t.x+=i}}applyPivot(t){if(this.pivot&&!this.isRoot()){const A=this.pivot.x-.5;t.x-=A*this.sizeDelta.x*this.gameObject.scale.x;const e=this.pivot.y-.5;t.y-=e*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const t={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(t),t}ensureValidSize(t,A=1e-4){return t.width<=0&&(t.width=A),t.height<=0&&(t.height=1e-4),t}createNewBlock(t){t={...this.getBasicOptions(),...t},rM&&console.log(this.name,t);const A=new Pm(t);return this._createdBlocks.push(A),A}createNewText(t){rM&&console.log(t),t={...this.getBasicOptions(),...t},rM&&console.log(this.name,t);const A=new kH(t);return this._createdTextBlocks.push(A),A}};let DI=xH;Fr([w(W)],DI.prototype,"anchoredPosition",1),Fr([w(W)],DI.prototype,"sizeDelta",2),Fr([w(W)],DI.prototype,"pivot",2),Fr([w(W)],DI.prototype,"anchorMin",2),Fr([w(W)],DI.prototype,"anchorMax",2),Fr([w(W)],DI.prototype,"offsetMin",2),Fr([w(W)],DI.prototype,"offsetMax",2);class YtA extends fH{constructor(A,e={}){super(A),A._simpleState__activeStates=[],A._simpleState__normalStyles={},A._simpleState__states=e,A._simpleState__statesProperties={};for(const g in e)for(const I in e[g])A._simpleState__statesProperties[I]||(A._simpleState__statesProperties[I]=[]),A._simpleState__statesProperties[I].push(g);for(const g of A._components)A._simpleState__statesProperties[g.id]&&(A._simpleState__normalStyles[g.id]=g.inline?g.inline:g._value);A.__overridedSet=A.set,A.set=this.storeSet.bind(A),A.renderStates=this.renderStates.bind(A),A.setupState=this.setupState.bind(A),A.setState=this.setState.bind(A),A.activatePseudoState=this.activatePseudoState.bind(A),A.deactivatePseudoState=this.deactivatePseudoState.bind(A),A.togglePseudoState=this.togglePseudoState.bind(A)}act(){}attach(){}detach(){}setupState(A,e){this._simpleState__states[A]=e;const g=[];for(const I in e)this._simpleState__statesProperties[I]||(this._simpleState__statesProperties[I]=[],g.push(I)),this._simpleState__statesProperties[I].push(A);for(const I of this._components)g.indexOf(I.id)>-1&&(this._simpleState__normalStyles[I.id]=I.inline?I.inline:I._value)}renderStates(){let A={...this._simpleState__normalStyles};for(const e in this._simpleState__states)this._simpleState__activeStates.indexOf(e)>-1&&(A={...A,...this._simpleState__states[e]});this.set(A,!1)}storeSet(A,e=!0){if(e)for(const g in A)this._simpleState__statesProperties[g]&&(this._simpleState__normalStyles[g]=A[g]);this.__overridedSet(A)}activatePseudoState(A){this._simpleState__activeStates.indexOf(A)===-1&&(this._simpleState__activeStates.push(A),this.renderStates())}deactivatePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1&&(this._simpleState__activeStates.splice(e,1),this.renderStates())}togglePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1?this._simpleState__activeStates.splice(e,1):this._simpleState__activeStates.push(A),this.renderStates()}setState(A){Array.isArray(A)?this._simpleState__activeStates=A:this._simpleState__activeStates=[A],this.renderStates()}}var HtA=Object.defineProperty,TtA=Object.getOwnPropertyDescriptor,YH=(t,A,e,g)=>{for(var I=g>1?void 0:g?TtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&HtA(A,e,I),I};class VQ extends RA{constructor(){super(...arguments),r(this,"effectColor"),r(this,"effectDistance")}}YH([w(wt)],VQ.prototype,"effectColor",2),YH([w(W)],VQ.prototype,"effectDistance",2);var _tA=Object.defineProperty,OtA=Object.getOwnPropertyDescriptor,HH=(t,A,e,g)=>{for(var I=g>1?void 0:g?OtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&_tA(A,e,I),I};const Dw={backgroundColor:new fA(1,1,1),backgroundOpacity:1,borderColor:new fA(1,1,1),borderOpacity:1};var hM;const ww=(hM=class extends _o{constructor(){super(...arguments),r(this,"_alphaFactor",1),r(this,"raycastTarget",!0),r(this,"uiObject",null),r(this,"_color",null),r(this,"_rect",null),r(this,"_stateManager",null),r(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new wt(1,1,1,1)),this._color}set color(t){(!this._color||this._color.r!==t.r||this._color.g!==t.g||this._color.b!==t.b||this._color.alpha!==t.alpha)&&(this._color||(this._color=new wt(1,1,1,1)),this._color.copy(t))}setAlphaFactor(t){this._alphaFactor=t,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(Dw.backgroundColor=this._color,Dw.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(Dw,this._alphaFactor),this.uiObject.set(Dw),this.markDirty())}get m_Color(){return this._color}get rectTransform(){return this._rect||(this._rect=eA.getComponent(this.gameObject,DI)),this._rect}onParentRectTransformChanged(){var t;(t=this.uiObject)==null||t.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone())}setState(t){this.makePanel(),this.uiObject&&(this.uiObject.setState(t),this==null||this.markDirty())}setupState(t){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new YtA(this.uiObject)),this.uiObject.setupState(t.state,t.attributes))}setOptions(t){this.makePanel(),this.uiObject&&this.uiObject.set(t)}awake(){super.awake(),this.makePanel(),WQ(this,"_color",()=>vtA(this,this.onColorChanged))}onEnable(){var t;super.onEnable(),this.uiObject&&((t=this.rectTransform.shadowComponent)==null||t.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(t){}onCreate(t){this.uiObject=this.rectTransform.createNewBlock(t),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(t,A=1){var e;const g=(e=this.gameObject)==null?void 0:e.getComponent(VQ);g&&(g.effectDistance&&(t.borderWidth=Math.max(Math.abs(g.effectDistance.x),Math.abs(g.effectDistance.y))),g.effectColor&&(t.borderColor=g.effectColor,t.borderOpacity=g.effectColor.alpha*A))}async setTexture(t){if(this.setOptions({backgroundOpacity:0}),t){if(t.encoding===ue)if(ww.textureCache.has(t))t=ww.textureCache.get(t);else{const A=t.clone();A.encoding=Zt,ww.textureCache.set(t,A),t=A}this.setOptions({backgroundImage:t,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"})}else this.setOptions({backgroundImage:null,borderRadius:0,backgroundOpacity:this.color.alpha})}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},r(hM,"textureCache",new Map),hM);let Nr=ww;HH([w(wt)],Nr.prototype,"color",1),HH([w()],Nr.prototype,"raycastTarget",2);class Cl extends Nr{constructor(){super(...arguments),r(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var PtA=Object.defineProperty,jtA=Object.getOwnPropertyDescriptor,yw=(t,A,e,g)=>{for(var I=g>1?void 0:g?jtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&PtA(A,e,I),I};let cM=class{constructor(){r(this,"texture",null),r(this,"rect")}};yw([w(Ye)],cM.prototype,"texture",2);let zQ=class extends Cl{constructor(){super(...arguments),r(this,"_sprite"),r(this,"pixelsPerUnitMultiplier",1)}set image(t){this.sprite?this.sprite.texture=t:(this.sprite=new cM,this.sprite.texture=t),this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(t){this._sprite!==t&&(this._sprite=t,this.onAfterCreated())}isBuiltinSprite(){var t,A,e,g,I,i,o,C;switch((A=(t=this.sprite)==null?void 0:t.texture)==null?void 0:A.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return((I=(g=(e=this.sprite)==null?void 0:e.texture)==null?void 0:g.image)==null?void 0:I.width)===32&&((C=(o=(i=this.sprite)==null?void 0:i.texture)==null?void 0:o.image)==null?void 0:C.height)===32}onBeforeCreate(t){var A,e;super.onBeforeCreate(t),this.isBuiltinSprite()&&(t.borderRadius=5/this.pixelsPerUnitMultiplier,((e=(A=this.sprite)==null?void 0:A.texture)==null?void 0:e.name)==="Knob"&&(t.borderRadius=999))}onAfterCreated(){var t;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((t=this.sprite)==null?void 0:t.texture))}};yw([w(cM)],zQ.prototype,"sprite",1),yw([w()],zQ.prototype,"pixelsPerUnitMultiplier",2);class Sw extends Cl{constructor(){super(...arguments),r(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(A){this._mainTexture!==A&&(this._mainTexture=A,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}yw([w(Ye)],Sw.prototype,"mainTexture",1);var WtA=Object.defineProperty,VtA=Object.getOwnPropertyDescriptor,Mi=(t,A,e,g)=>{for(var I=g>1?void 0:g?VtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&WtA(A,e,I),I};const ZQ=aA("debugbutton");class Kr{constructor(){r(this,"colorMultiplier"),r(this,"disabledColor"),r(this,"fadeDuration"),r(this,"highlightedColor"),r(this,"normalColor"),r(this,"pressedColor"),r(this,"selectedColor")}}Mi([w()],Kr.prototype,"colorMultiplier",2),Mi([w(wt)],Kr.prototype,"disabledColor",2),Mi([w()],Kr.prototype,"fadeDuration",2),Mi([w(wt)],Kr.prototype,"highlightedColor",2),Mi([w(wt)],Kr.prototype,"normalColor",2),Mi([w(wt)],Kr.prototype,"pressedColor",2),Mi([w(wt)],Kr.prototype,"selectedColor",2);class xs extends RA{constructor(){super(...arguments),r(this,"onClick"),r(this,"_isHovered",!1),r(this,"colors"),r(this,"transition"),r(this,"animationTriggers"),r(this,"animator"),r(this,"_interactable",!0),r(this,"_requestedAnimatorTrigger"),r(this,"_isInit",!1),r(this,"_image")}onPointerEnter(A){var e,g;ZQ&&console.log("Button Enter",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this._isHovered=!0,this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState("hovered")),this.context.input.setCursorPointer())}onPointerExit(){var A,e;ZQ&&console.log("Button Exit",(A=this.animationTriggers)==null?void 0:A.highlightedTrigger,this.animator),this._isHovered=!1,this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((e=this._image)==null||e.setState("normal")),this.context.input.setCursorNormal())}onPointerDown(A){var e,g;ZQ&&console.log("Button Down",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState("pressed")))}onPointerUp(A){var e,g;ZQ&&console.warn("Button Up",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState(this._isHovered?"hovered":"normal")))}onPointerClick(A){var e;this.interactable&&(ZQ&&(console.warn("Button Click",this.onClick),Hg("CLICKED button "+this.name+" at "+this.context.time.frameCount)),(e=this.onClick)==null||e.invoke())}set interactable(A){this._interactable=A,this._image&&(this._image.setInteractable(A),A?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(A){this.interactable=A}awake(){super.awake(),ZQ&&console.log(this),this._isInit=!1,this.init()}start(){var A;(A=this._image)==null||A.setInteractable(this.interactable)}onEnable(){super.onEnable()}*setAnimatorTriggerAtEndOfFrame(A){var e;this._requestedAnimatorTrigger=A,yield,yield,this._requestedAnimatorTrigger==A&&((e=this.animator)==null||e.SetTrigger(A))}init(){this._isInit||(this._isInit=!0,this._image=eA.getComponent(this.gameObject,zQ),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(A){var e,g,I,i,o;A.setInteractable(this.interactable);const C=this.getFinalColor(A.color,(e=this.colors)==null?void 0:e.normalColor),s={state:"normal",attributes:{backgroundColor:C,backgroundOpacity:C.alpha}};A.setupState(s);const a=this.getFinalColor(A.color,(g=this.colors)==null?void 0:g.highlightedColor),n={state:"hovered",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};A.setupState(n);const B=this.getFinalColor(A.color,(I=this.colors)==null?void 0:I.pressedColor),Q={state:"pressed",attributes:{backgroundColor:B,backgroundOpacity:B.alpha}};A.setupState(Q);const E=this.getFinalColor(A.color,(i=this.colors)==null?void 0:i.selectedColor),h={state:"selected",attributes:{backgroundColor:E,backgroundOpacity:E.alpha}};A.setupState(h);const c=this.getFinalColor(A.color,(o=this.colors)==null?void 0:o.disabledColor),l={state:"disabled",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};A.setupState(l)}getFinalColor(A,e){return e?A.clone().multiply(e):A.clone()}}Mi([w(ti)],xs.prototype,"onClick",2),Mi([w()],xs.prototype,"colors",2),Mi([w()],xs.prototype,"transition",2),Mi([w()],xs.prototype,"animationTriggers",2),Mi([w(Ai)],xs.prototype,"animator",2),Mi([w()],xs.prototype,"interactable",1);var ztA=Object.defineProperty,ZtA=Object.getOwnPropertyDescriptor,pg=(t,A,e,g)=>{for(var I=g>1?void 0:g?ZtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&ztA(A,e,I),I};const TH=aA("debuguilayout");class sn{constructor(){r(this,"left",0),r(this,"right",0),r(this,"top",0),r(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}pg([w()],sn.prototype,"left",2),pg([w()],sn.prototype,"right",2),pg([w()],sn.prototype,"top",2),pg([w()],sn.prototype,"bottom",2);class Ri extends RA{constructor(){super(...arguments),r(this,"_rectTransform",null),r(this,"_needsUpdate",!1),r(this,"childAlignment",0),r(this,"reverseArrangement",!1),r(this,"spacing",0),r(this,"padding"),r(this,"minWidth",0),r(this,"minHeight",0),r(this,"flexibleHeight",0),r(this,"flexibleWidth",0),r(this,"preferredHeight",0),r(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(A){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(TH&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){TH&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(DI);const A=this.gameObject.getComponentInParent(wI);A&&A.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const A=this.gameObject.getComponentInParent(wI);A&&A.unregisterLayoutGroup(this)}set m_Spacing(A){A!==this.spacing&&(this._needsUpdate=!0,this.spacing=A)}get m_Spacing(){return this.spacing}}pg([w()],Ri.prototype,"childAlignment",2),pg([w()],Ri.prototype,"reverseArrangement",2),pg([w()],Ri.prototype,"spacing",2),pg([w(sn)],Ri.prototype,"padding",2),pg([w()],Ri.prototype,"minWidth",2),pg([w()],Ri.prototype,"minHeight",2),pg([w()],Ri.prototype,"flexibleHeight",2),pg([w()],Ri.prototype,"flexibleWidth",2),pg([w()],Ri.prototype,"preferredHeight",2),pg([w()],Ri.prototype,"preferredWidth",2);class an extends Ri{constructor(){super(...arguments),r(this,"childControlHeight",!0),r(this,"childControlWidth",!0),r(this,"childForceExpandHeight",!1),r(this,"childForceExpandWidth",!1),r(this,"childScaleHeight",!1),r(this,"childScaleWidth",!1)}onCalculateLayout(A){var e;const g=this.primaryAxis,I=A.width;let i=I;const o=A.height;let C=o;i-=this.padding.horizontal,C-=this.padding.vertical,g==="x"?this.padding.horizontal:this.padding.vertical;const s=g==="x",a=s?"y":"x",n=s?this.childControlWidth:this.childControlHeight,B=s?this.childControlHeight:this.childControlWidth,Q=s?this.childForceExpandWidth:this.childForceExpandHeight,E=s?this.childForceExpandHeight:this.childForceExpandWidth,h=s?C:i,c=s?I:o,l=.5*(s?this.childAlignment%3:Math.floor(this.childAlignment/3));let d=0;s?d+=this.padding.left:d+=this.padding.top;let u=0,p=0;for(let S=0;S<this.gameObject.children.length;S++){const U=this.gameObject.children[S],M=eA.getComponent(U,DI);M!=null&&M.activeAndEnabled&&(p+=1,s?u+=M.width:u+=M.height)}let D=0;const y=this.spacing*(p-1);if(Q||n){let S=0;s?S=i-=y:S=C-=y,p>0&&(D=S/p)}let k=0;k+=this.padding.left,k-=this.padding.right,l!==0&&(d=c-u,d*=l,d-=y*l,s?(d-=this.padding.right*l,d+=this.padding.left*(1-l),d<this.padding.left&&(d=this.padding.left)):(d-=this.padding.bottom*l,d+=this.padding.top*(1-l),d<this.padding.top&&(d=this.padding.top)));let F=1;for(let S=0;S<this.gameObject.children.length;S++){const U=this.gameObject.children[S],M=eA.getComponent(U,DI);if(M!=null&&M.activeAndEnabled){(e=M.pivot)==null||e.set(.5,.5),M.anchorMin.set(0,1),M.anchorMax.set(0,1);const Y=I*.5+k*.5;M.anchoredPosition.x!==Y&&(M.anchoredPosition.x=Y);const _=o*-.5;M.anchoredPosition.y!==_&&(M.anchoredPosition.y=_),E&&B&&M.sizeDelta[a]!==h&&(M.sizeDelta[a]=h),Q&&n&&M.sizeDelta[g]!==D&&(M.sizeDelta[g]=D);const x=s?M.width:M.height;let v=x*.5;if(d+=v,Q){let gA=D*F-D*.5;gA>d&&(d=gA-D*.5+x+this.padding.left,d-=v)}let z=d;g==="y"&&(z=-z),M.anchoredPosition[g]!==z&&(M.anchoredPosition[g]=z),d+=v,d+=this.spacing,F+=1}}}}pg([w()],an.prototype,"childControlHeight",2),pg([w()],an.prototype,"childControlWidth",2),pg([w()],an.prototype,"childForceExpandHeight",2),pg([w()],an.prototype,"childForceExpandWidth",2),pg([w()],an.prototype,"childScaleHeight",2),pg([w()],an.prototype,"childScaleWidth",2);class lM extends an{get primaryAxis(){return"y"}}class dM extends an{get primaryAxis(){return"x"}}class pM extends Ri{onCalculateLayout(){}}var XtA=Object.defineProperty,$tA=Object.getOwnPropertyDescriptor,yC=(t,A,e,g)=>{for(var I=g>1?void 0:g?$tA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&XtA(A,e,I),I};const uM=aA("debuguilayout"),_H=class extends vc{constructor(){super(...arguments),r(this,"_renderOnTop"),r(this,"_depthWrite",!1),r(this,"_doubleSided",!0),r(this,"_castShadows",!1),r(this,"_receiveShadows",!1),r(this,"_renderMode",-1),r(this,"_rootCanvas"),r(this,"_scaleFactor",1),r(this,"worldCamera"),r(this,"planeDistance",-1),r(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),r(this,"previousParent",null),r(this,"_lastMatrixWorld",null),r(this,"_rectTransforms",[]),r(this,"_layoutGroups",new Map),r(this,"onBeforeRenderRoutine",()=>{var t,A;this.previousParent=this.gameObject.parent,this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(t=this.shadowComponent)==null||t.updateMatrixWorld(!0),(A=this.shadowComponent)==null||A.updateWorldMatrix(!0,!0),io.ensureUpdateMeshUI(mH,this.context))}),r(this,"onAfterRenderRoutine",()=>{var t,A;if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const e=this.context.mainCamera;e?.add(this.gameObject)}else this.previousParent.add(this.gameObject);this.context.renderer.autoClear=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(t=this.shadowComponent)==null||t.updateMatrixWorld(!0),io.ensureUpdateMeshUI(mH,this.context),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=!0,this.previousParent.add(this.gameObject)}(A=this._lastMatrixWorld)==null||A.copy(this.gameObject.matrixWorld)}),r(this,"_updateRenderSettingsRoutine"),r(this,"_activeRenderMode",-1),r(this,"_lastWidth",-1),r(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(t){t!==this._renderOnTop&&(this._renderOnTop=t,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(t){this._depthWrite!==t&&(this._depthWrite=t,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(t){this._doubleSided!==t&&(this._doubleSided=t,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(t){this._castShadows!==t&&(this._castShadows=t,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(t){this._receiveShadows!==t&&(this._receiveShadows=t,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(t){this._renderMode!==t&&(this._renderMode=t,this.onRenderSettingsChanged())}set rootCanvas(t){this._rootCanvas instanceof _H||(this._rootCanvas=t)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(t){this._scaleFactor=t}awake(){var t;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,uM&&console.log("Canvas.Awake()",((t=this.previousParent)==null?void 0:t.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new TA,this.onUpdateRenderMode(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);t!==-1&&this.context.pre_render_callbacks.splice(t,1);const A=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);A!==-1&&this.context.post_render_callbacks.splice(A,1)}registerTransform(t){this._rectTransforms.push(t)}unregisterTransform(t){const A=this._rectTransforms.indexOf(t);A!==-1&&this._rectTransforms.splice(A,1)}registerLayoutGroup(t){const A=t.gameObject;this._layoutGroups.set(A,t)}unregisterLayoutGroup(t){const A=t.gameObject;this._layoutGroups.delete(A)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new TA);const t=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);uM&&t&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);let A=!1;for(const e of this._rectTransforms){t&&e.markDirty();let g=this._layoutGroups.get(e.gameObject);e.isDirty&&!g&&(g=e.gameObject.getComponentInParent(Ri)),(e.isDirty||g!=null&&g.isDirty)&&(uM&&!A&&console.log("CANVAS UPDATE ### "+e.name+" ##################################### "+this.context.time.frame),g?.updateLayout(),e.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),ki.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),pw(this.shadowComponent,this);for(const t of eA.getComponentsInChildren(this.gameObject,_o))pw(t.shadowComponent,this)}}onUpdateRenderMode(t=!1){if(!t&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let A=this.context.mainCameraComponent,e=10;switch(A&&A.nearClipPlane>0&&A.farClipPlane>0&&(e=XA.lerp(A.nearClipPlane,A.farClipPlane,.15)),this._renderMode===1&&(this.worldCamera&&(A=this.worldCamera),this.planeDistance>0&&(e=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!A)return;const g=e+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-g,this.gameObject.quaternion.identity();const I=this.gameObject.getComponent(DI);let i=!1;I.sizeDelta.x!==this.context.domWidth&&(i=!0),I.sizeDelta.y!==this.context.domHeight&&(i=!0);const o=A.fieldOfView*Math.PI/180,C=2*Math.tan(o/2)*Math.abs(g);this.gameObject.scale.x=C/this.context.domHeight,this.gameObject.scale.y=C/this.context.domHeight,this.gameObject.scale.z=.01,i&&(I.sizeDelta.x=this.context.domWidth,I.sizeDelta.y=this.context.domHeight,I?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let wI=_H;yC([w()],wI.prototype,"renderOnTop",1),yC([w()],wI.prototype,"depthWrite",1),yC([w()],wI.prototype,"doubleSided",1),yC([w()],wI.prototype,"castShadows",1),yC([w()],wI.prototype,"receiveShadows",1),yC([w()],wI.prototype,"renderMode",1),yC([w(wI)],wI.prototype,"rootCanvas",1),yC([w()],wI.prototype,"scaleFactor",1),yC([w(Kt)],wI.prototype,"worldCamera",2),yC([w()],wI.prototype,"planeDistance",2);var AgA=Object.defineProperty,egA=Object.getOwnPropertyDescriptor,DM=(t,A,e,g)=>{for(var I=g>1?void 0:g?egA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&AgA(A,e,I),I};class XQ extends RA{constructor(){super(...arguments),r(this,"_alpha",1),r(this,"interactable",!0),r(this,"blocksRaycasts",!0),r(this,"_isDirty",!1),r(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(A){A!==this._alpha&&(this._alpha=A,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),ki.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){for(const A of eA.getComponentsInChildren(this.gameObject,_o,this._buffer)){const e=A;e.setAlphaFactor&&e.setAlphaFactor(this._alpha)}}}DM([w()],XQ.prototype,"alpha",1),DM([w()],XQ.prototype,"interactable",2),DM([w()],XQ.prototype,"blocksRaycasts",2);var tgA=Object.defineProperty,ggA=Object.getOwnPropertyDescriptor,Jt=(t,A,e,g)=>{for(var I=g>1?void 0:g?ggA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&tgA(A,e,I),I};class Jr extends RA{constructor(){super(...arguments),r(this,"object"),r(this,"target"),r(this,"duration",1),r(this,"relativeMotion",!1),r(this,"coroutine",null),r(this,"targetPos",new f),r(this,"targetRot",new GA),r(this,"targetScale",new f)}*moveToTarget(){if(!this.target||!this.object)return;const A=ye(this.object).clone(),e=ye(this.target).clone(),g=Ng(this.object).clone(),I=Ng(this.target).clone(),i=zg(this.object).clone(),o=zg(this.target).clone(),C=A.distanceTo(e),s=g.angleTo(I),a=i.distanceTo(o);if(C<.01&&s<.01&&a<.01){tg(this.object,e),zI(this.object,I),jf(this.object,o),this.coroutine=null;return}let n=0,B=0;for(;n<1;)n+=this.context.time.deltaTime/this.duration,n>1&&(n=1),B=n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2,this.targetPos.lerpVectors(A,e,B),this.targetRot.slerpQuaternions(g,I,B),this.targetScale.lerpVectors(i,o,B),tg(this.object,this.targetPos),zI(this.object,this.targetRot),jf(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const A=this.object.position.clone(),e=this.object.quaternion.clone(),g=this.object.scale.clone(),I=this.target.position.clone(),i=this.target.quaternion.clone(),o=this.target.scale.clone();I.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(I),this.targetRot.copy(this.object.quaternion).multiply(i),this.targetScale.copy(this.object.scale).multiply(o);let C=0,s=0;for(;C<1;)C+=this.context.time.deltaTime/this.duration,C>1&&(C=1),s=C<.5?4*C*C*C:1-Math.pow(-2*C+2,3)/2,this.object.position.lerpVectors(A,this.targetPos,s),this.object.quaternion.slerpQuaternions(e,this.targetRot,s),this.object.scale.lerpVectors(g,this.targetScale,s),yield;this.coroutine=null}onPointerClick(){this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}beforeCreateDocument(A){var e;if(this.target&&this.object&&this.gameObject){const g=new LI("Move to "+((e=this.target)==null?void 0:e.name),gi.tapTrigger(this.gameObject),at.transformAction(this.object,this.target,this.duration,this.relativeMotion?VG.Relative:VG.Absolute));A.addBehavior(g)}}}Jt([w(UA)],Jr.prototype,"object",2),Jt([w(UA)],Jr.prototype,"target",2),Jt([w()],Jr.prototype,"duration",2),Jt([w()],Jr.prototype,"relativeMotion",2);var wM;const $Q=(wM=class extends RA{constructor(){super(...arguments),r(this,"materialToSwitch"),r(this,"variantMaterial"),r(this,"_objectsWithThisMaterial",[]),r(this,"selfModel"),r(this,"targetModels",[])}awake(){if(this.variantMaterial&&this.materialToSwitch){const t=eA.findObjectsOfType(jt);for(const A of t)A.sharedMaterial===this.materialToSwitch&&this._objectsWithThisMaterial.push(A)}}onPointerClick(){if(this.variantMaterial)for(const t of this._objectsWithThisMaterial)t.sharedMaterial=this.variantMaterial}createBehaviours(t,A,e){this._objectsWithThisMaterial.find(g=>g.gameObject.uuid===A.uuid)&&this.targetModels.push(A),this.gameObject.uuid===A.uuid&&(this.selfModel=A,this.materialToSwitch&&($Q._materialTriggersPerId[this.materialToSwitch.uuid]||($Q._materialTriggersPerId[this.materialToSwitch.uuid]=[]),$Q._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(t,A){if(!this.materialToSwitch)return;const e=$Q._materialTriggersPerId[this.materialToSwitch.uuid];if(e){const g={};for(const i of e){const o=i.createVariants();o&&o.length>0&&(g[i.selfModel.uuid]=o)}const I=[];for(const i of e){for(const o in g)o!==i.selfModel.uuid&&I.push(g[o]);i.createAndAttachBehaviors(t,g[i.selfModel.uuid],I)}}delete $Q._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(t,A,e){const g=[],I=[];for(const i of this.targetModels){const o=at.fadeAction(i,0,!1);I.push(o)}for(const i of e)I.push(at.fadeAction(i,0,!1));for(const i of A)g.push(at.fadeAction(i,0,!1)),I.push(at.fadeAction(i,0,!0));t.addBehavior(new LI("Select "+this.selfModel.name,gi.tapTrigger(this.selfModel),at.parallel(...I))),t.addBehavior(new LI("Start hidden "+this.selfModel.name,gi.sceneStartTrigger(),at.parallel(...g)))}createVariants(){if(!this.variantMaterial)return null;const t=[];for(const A of this.targetModels){const e=A.clone();e.name+=" variant_"+this.variantMaterial.name,e.name=e.name.replace(/\s/g,"_"),e.material=this.variantMaterial,e.geometry=A.geometry,e.matrix=A.matrix,(!A.parent||!A.parent.isEmpty())&&BC.createEmptyParent(A),A.parent&&A.parent.add(e),t.push(e)}return t}},r(wM,"_materialTriggersPerId",{}),wM);let sl=$Q;Jt([w(Ue)],sl.prototype,"materialToSwitch",2),Jt([w(Ue)],sl.prototype,"variantMaterial",2);class AE extends RA{constructor(){super(...arguments),r(this,"target"),r(this,"toggleOnClick",!1),r(this,"targetState",!0),r(this,"hideSelf",!0),r(this,"selfModel"),r(this,"otherModel"),r(this,"toggleModel"),r(this,"stateBeforeCreatingDocument",!1)}onPointerClick(){!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(A,e,g){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}beforeCreateDocument(){this.stateBeforeCreatingDocument=this.gameObject.visible,this.gameObject.visible=!0}afterCreateDocument(A,e){if(this.target){if(this.otherModel=e.document.findById(this.target.uuid),this.selfModel&&this.otherModel){let g=this.hideSelf;this.targetState,this.toggleOnClick&&(g=!0,this.target.visible,(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&ux.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.clone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel));const I=[];if(g&&I.push(at.fadeAction(this.selfModel,0,!1)),this.toggleModel&&I.push(at.fadeAction(this.toggleModel,0,!0)),I.push(at.fadeAction(this.otherModel,0,this.targetState)),A.addBehavior(new LI("Toggle_"+this.selfModel.name+"_hideSelf",gi.tapTrigger(this.selfModel),at.sequence(...I))),this.toggleOnClick&&this.toggleModel){const i=[];i.push(at.fadeAction(this.toggleModel,0,!1)),i.push(at.fadeAction(this.selfModel,0,!0)),i.push(at.fadeAction(this.otherModel,0,!this.targetState)),A.addBehavior(new LI("Toggle_"+this.selfModel.name+"_toggleSelf",gi.tapTrigger(this.toggleModel),at.sequence(...i))),A.addBehavior(new LI("HideOnStart_"+this.gameObject.name,gi.sceneStartTrigger(),at.fadeAction(this.toggleModel,0,!1)))}}this.gameObject.visible=this.stateBeforeCreatingDocument}}}Jt([w(UA)],AE.prototype,"target",2),Jt([w()],AE.prototype,"targetState",2),Jt([w()],AE.prototype,"hideSelf",2);class yM extends RA{start(){this.gameObject.visible=!1}createBehaviours(A,e,g){e.uuid===this.gameObject.uuid&&A.addBehavior(new LI("HideOnStart_"+this.gameObject.name,gi.sceneStartTrigger(),at.fadeAction(e,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class eE extends RA{constructor(){super(...arguments),r(this,"target"),r(this,"duration",.5),r(this,"motionType",WG.bounce)}beforeCreateDocument(){}createBehaviours(A,e,g){if(this.target&&e.uuid===this.gameObject.uuid){const I=new LI("emphasize "+this.name,gi.tapTrigger(this.gameObject),at.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));A.addBehavior(I)}}afterCreateDocument(A,e){}}Jt([w()],eE.prototype,"target",2),Jt([w()],eE.prototype,"duration",2),Jt([w()],eE.prototype,"motionType",2);class tE extends RA{constructor(){super(...arguments),r(this,"target"),r(this,"clip",""),r(this,"toggleOnClick",!1)}onPointerClick(){if(!(!this.target&&!this.clip)){if(!this.target){const A=this.gameObject.addNewComponent(hg);A&&(A.spatialBlend=1,A.volume=1,A.loop=!1,this.target=A)}this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play()))}}createBehaviours(A,e,g){if(!(!this.target&&!this.clip)&&e.uuid===this.gameObject.uuid){const I=this.clip?this.clip:this.target?this.target.clip:void 0;if(!I)return;const i=this.target?this.target.gameObject:this.gameObject,o=I.split("/").pop(),C=this.target?this.target.volume:1,s=this.target&&this.target.spatialBlend==0?ZG.NonSpatial:ZG.Spatial,a=new LI("playAudio "+this.name,gi.tapTrigger(this.gameObject),at.playAudioAction(i,"audio/"+o,Nx.Play,C,s));A.addBehavior(a)}}async afterSerialize(A,e){if(!this.target&&!this.clip)return;const g=this.clip?this.clip:this.target?this.target.clip:void 0;if(!g)return;const I=g.split("/").pop(),i=await(await(await fetch(this.clip)).blob()).arrayBuffer(),o=new Uint8Array(i);e.files["audio/"+I]=o}}Jt([w(hg)],tE.prototype,"target",2),Jt([w(URL)],tE.prototype,"clip",2),Jt([w()],tE.prototype,"toggleOnClick",2);var SM;const gE=(SM=class extends RA{constructor(){super(...arguments),r(this,"target"),r(this,"animator"),r(this,"stateName"),r(this,"stateNameAfterPlaying"),r(this,"loopAfterPlaying",!1),r(this,"selfModel"),r(this,"stateAnimationModel"),r(this,"stateAnimation"),r(this,"stateAfterPlayingAnimationModel"),r(this,"stateAfterPlayingAnimation")}onPointerClick(){var t;this.target&&this.stateName&&((t=this.animator)==null||t.play(this.stateName,0,0,.1))}createBehaviours(t,A,e){A.uuid===this.gameObject.uuid&&(this.selfModel=A)}onAfterHierarchy(){gE.animationActions=[]}afterCreateDocument(t,A){!this.stateAnimation||!this.stateAnimationModel||A.document.traverse(e=>{var g,I;if(e.uuid===((g=this.target)==null?void 0:g.uuid)&&this.stateAnimation){const i=[];let o=gE.animationActions.find(s=>s.affectedObjects==e&&s.start==this.stateAnimation.start&&s.duration==this.stateAnimation.duration);if(o||(o=at.startAnimationAction(e,this.stateAnimation.start,this.stateAnimation.duration),gE.animationActions.push(o)),i.push(o),this.stateAfterPlayingAnimation&&this.stateAfterPlayingAnimationModel){let s=gE.animationActions.find(n=>n.affectedObjects==e&&n.start==this.stateAfterPlayingAnimation.start&&n.duration==this.stateAfterPlayingAnimation.duration);s||(s=at.startAnimationAction(e,this.stateAfterPlayingAnimation.start,this.stateAfterPlayingAnimation.duration),gE.animationActions.push(s));const a=at.sequence(s);this.loopAfterPlaying&&a.makeLooping(),i.push(a)}const C=new LI("tap "+this.name+" for "+this.stateName+" on "+((I=this.target)==null?void 0:I.name),gi.tapTrigger(this.selfModel),at.sequence(...i));t.addBehavior(C)}})}createAnimation(t,A,e){var g,I,i,o;if(this.target&&this.animator){const C=(I=(g=this.animator)==null?void 0:g.runtimeAnimatorController)==null?void 0:I.findState(this.stateName);this.stateAnimationModel=A,this.stateAnimation=t.registerAnimation(this.target,C?.motion.clip);const s=(o=(i=this.animator)==null?void 0:i.runtimeAnimatorController)==null?void 0:o.findState(this.stateNameAfterPlaying);this.stateAfterPlayingAnimationModel=A,this.stateAfterPlayingAnimation=t.registerAnimation(this.target,s?.motion.clip)}}},r(SM,"animationActions",[]),SM);let nn=gE;Jt([w(UA)],nn.prototype,"target",2),Jt([w(Ai)],nn.prototype,"animator",2),Jt([w()],nn.prototype,"stateName",2),Jt([w()],nn.prototype,"stateNameAfterPlaying",2),Jt([w()],nn.prototype,"loopAfterPlaying",2);class IE extends RA{constructor(){super(...arguments),r(this,"target")}getType(){}getDuration(){}}Jt([w(UA)],IE.prototype,"target",2);class al extends RA{constructor(){super(...arguments),r(this,"target")}}Jt([w(IE)],al.prototype,"target",2);class nl extends IE{constructor(){super(...arguments),r(this,"type",1),r(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Jt([w()],nl.prototype,"type",2),Jt([w()],nl.prototype,"duration",2);class fM extends al{}var IgA=Object.defineProperty,igA=Object.getOwnPropertyDescriptor,Ys=(t,A,e,g)=>{for(var I=g>1?void 0:g?igA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&IgA(A,e,I),I};class qr extends RA{constructor(){super(...arguments),r(this,"center",new f(0,0,0)),r(this,"radius",.5),r(this,"height",2),r(this,"_rigidbody",null),r(this,"_activeGroundCollisions",new Set)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Ht),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(Ht)),this.rigidbody)}onEnable(){let A=this.rigidbody,e=this.gameObject.getComponent(Cn);e||(e=this.gameObject.addNewComponent(Cn)),e.center.copy(this.center),e.radius=this.radius,e.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,A.lockRotationX=!0,A.lockRotationY=!0,A.lockRotationZ=!0}move(A){this.gameObject.position.add(A)}onCollisionEnter(A){for(const e of A.contacts)if(e.normal.y>.1){this._activeGroundCollisions.add(A);break}}onCollisionExit(A){this._activeGroundCollisions.delete(A)}get isGrounded(){return this._activeGroundCollisions.size>0}}Ys([w(f)],qr.prototype,"center",2),Ys([w()],qr.prototype,"radius",2),Ys([w()],qr.prototype,"height",2);class Hs extends RA{constructor(){super(...arguments),r(this,"controller"),r(this,"movementSpeed",2),r(this,"rotationSpeed",2),r(this,"jumpForce",1),r(this,"doubleJumpForce",2),r(this,"animator"),r(this,"lookForward",!0),r(this,"_currentSpeed",new f(0,0,0)),r(this,"_currentAngularSpeed",new f(0,0,0)),r(this,"_temp",new f(0,0,0)),r(this,"_jumpCount",0),r(this,"_currentRotation"),r(this,"_raycastOptions",new Go)}awake(){this._currentRotation=new GA}update(){var A,e,g,I,i,o,C,s,a,n,B;(A=this.controller)!=null&&A.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((e=this.animator)==null||e.setBool("doubleJump",!1)));const Q=this.context.input.isKeyPressed("w"),E=this.context.input.isKeyPressed("s"),h=this.context.input.isKeyPressed("a"),c=this.context.input.isKeyPressed("d"),l=this.context.input.isKeyDown(" "),d=(Q?1:0)+(E?-1:0);this._currentSpeed.z+=d*this.movementSpeed*this.context.time.deltaTime,(g=this.animator)==null||g.setBool("running",d!=0),(i=this.animator)==null||i.setBool("jumping",((I=this.controller)==null?void 0:I.isGrounded)===!0&&l),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);const u=(h?1:0)+(c?-1:0);if(this._currentAngularSpeed.y+=XA.toRadians(u*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const p=this.context.mainCameraComponent.forward;p.y=0,p.normalize(),this._currentRotation.setFromUnitVectors(new f(0,0,1),p),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&&l&&this.jumpForce>0){let p=(o=this.controller)==null?void 0:o.isGrounded;if(this.doubleJumpForce>0&&!((C=this.controller)!=null&&C.isGrounded)&&this._jumpCount===1&&(p=!0,(s=this.animator)==null||s.setBool("doubleJump",!0)),p){this._jumpCount+=1;const D=this.controller.rigidbody,y=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;D.applyImpulse(new f(0,1,0).multiplyScalar(y))}}if(this.controller){const p=(a=this.controller)==null?void 0:a.rigidbody.getVelocity().y;if(p<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new As),this._raycastOptions.ray.origin.copy(ye(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const D=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const y=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(D),(y.length&&y[0].distance>2||p<-10)&&((n=this.animator)==null||n.setBool("falling",!0))}else(B=this.animator)==null||B.setBool("falling",!1)}}}Ys([w(qr)],Hs.prototype,"controller",2),Ys([w()],Hs.prototype,"movementSpeed",2),Ys([w()],Hs.prototype,"rotationSpeed",2),Ys([w()],Hs.prototype,"jumpForce",2),Ys([w()],Hs.prototype,"doubleJumpForce",2),Ys([w(Ai)],Hs.prototype,"animator",2);var ogA=Object.defineProperty,CgA=Object.getOwnPropertyDescriptor,sgA=(t,A,e,g)=>{for(var I=g>1?void 0:g?CgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&ogA(A,e,I),I};class rl extends TI{constructor(){super(...arguments),r(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const A=new _b;return A.offset=new W(0,0),A.radialModulation=!0,A.modulationOffset=.15,this.intensity.valueProcessor=e=>e*.02,this.intensity.onValueChanged=e=>{A.offset.x=-e,A.offset.y=e},A}}sgA([w(qe)],rl.prototype,"intensity",2),uC("ChromaticAberration",rl);var agA=Object.defineProperty,ngA=Object.getOwnPropertyDescriptor,fw=(t,A,e,g)=>{for(var I=g>1?void 0:g?ngA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&agA(A,e,I),I};class rn extends TI{constructor(){super(...arguments),r(this,"postExposure"),r(this,"contrast"),r(this,"hueShift"),r(this,"saturation")}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=A=>(A=Math.pow(2,A),A),this.postExposure.defaultValue=0,this.contrast.valueProcessor=A=>{let e=1;return A>0?e=200:A<0&&(e=100),A/e},this.contrast.defaultValue=0,this.hueShift.valueProcessor=A=>Math.PI*A/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=A=>A<0?A/100:A/(100*Math.PI),this.saturation.defaultValue=0}unapply(){this.context.renderer.toneMappingExposure=1}onCreateEffect(){this.context.renderer.toneMapping===GI&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=VE);const A=new Tb;this.postExposure.onValueChanged=g=>{this.context.renderer.toneMapping===GI&&(this.context.renderer.toneMapping=VE),this.context.renderer.toneMappingExposure=g},this.contrast.onValueChanged=g=>{A.contrast=g};const e=new Pb;return this.hueShift.onValueChanged=g=>e.hue=g,this.saturation.onValueChanged=g=>e.saturation=g,[e,A]}}fw([w(qe)],rn.prototype,"postExposure",2),fw([w(qe)],rn.prototype,"contrast",2),fw([w(qe)],rn.prototype,"hueShift",2),fw([w(qe)],rn.prototype,"saturation",2),uC("ColorAdjustments",rn);const rgA=(Math.sqrt(5)-1)/4,tI=(5-Math.sqrt(5))/20,kw=t=>Math.floor(t)|0,Gw=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);function BgA(t=Math.random){const A=QgA(t),e=new Float64Array(A).map(o=>Gw[o%32*4]),g=new Float64Array(A).map(o=>Gw[o%32*4+1]),I=new Float64Array(A).map(o=>Gw[o%32*4+2]),i=new Float64Array(A).map(o=>Gw[o%32*4+3]);return function(o,C,s,a){let n,B,Q,E,h;const c=(o+C+s+a)*rgA,l=kw(o+c),d=kw(C+c),u=kw(s+c),p=kw(a+c),D=(l+d+u+p)*tI,y=l-D,k=d-D,F=u-D,S=p-D,U=o-y,M=C-k,Y=s-F,_=a-S;let x=0,v=0,z=0,gA=0;U>M?x++:v++,U>Y?x++:z++,U>_?x++:gA++,M>Y?v++:z++,M>_?v++:gA++,Y>_?z++:gA++;const CA=x>=3?1:0,AA=v>=3?1:0,dA=z>=3?1:0,rA=gA>=3?1:0,vA=x>=2?1:0,MA=v>=2?1:0,IA=z>=2?1:0,QA=gA>=2?1:0,NA=x>=1?1:0,$=v>=1?1:0,_A=z>=1?1:0,YA=gA>=1?1:0,JA=U-CA+tI,DA=M-AA+tI,cA=Y-dA+tI,wA=_-rA+tI,lA=U-vA+2*tI,xA=M-MA+2*tI,KA=Y-IA+2*tI,ne=_-QA+2*tI,uA=U-NA+3*tI,re=M-$+3*tI,Be=Y-_A+3*tI,Ne=_-YA+3*tI,it=U-1+4*tI,L=M-1+4*tI,J=Y-1+4*tI,BA=_-1+4*tI,FA=l&255,qA=d&255,OA=u&255,ie=p&255;let H=.6-U*U-M*M-Y*Y-_*_;if(H<0)n=0;else{const pA=FA+A[qA+A[OA+A[ie]]];H*=H,n=H*H*(e[pA]*U+g[pA]*M+I[pA]*Y+i[pA]*_)}let X=.6-JA*JA-DA*DA-cA*cA-wA*wA;if(X<0)B=0;else{const pA=FA+CA+A[qA+AA+A[OA+dA+A[ie+rA]]];X*=X,B=X*X*(e[pA]*JA+g[pA]*DA+I[pA]*cA+i[pA]*wA)}let jA=.6-lA*lA-xA*xA-KA*KA-ne*ne;if(jA<0)Q=0;else{const pA=FA+vA+A[qA+MA+A[OA+IA+A[ie+QA]]];jA*=jA,Q=jA*jA*(e[pA]*lA+g[pA]*xA+I[pA]*KA+i[pA]*ne)}let VA=.6-uA*uA-re*re-Be*Be-Ne*Ne;if(VA<0)E=0;else{const pA=FA+NA+A[qA+$+A[OA+_A+A[ie+YA]]];VA*=VA,E=VA*VA*(e[pA]*uA+g[pA]*re+I[pA]*Be+i[pA]*Ne)}let HA=.6-it*it-L*L-J*J-BA*BA;if(HA<0)h=0;else{const pA=FA+1+A[qA+1+A[OA+1+A[ie+1]]];HA*=HA,h=HA*HA*(e[pA]*it+g[pA]*L+I[pA]*J+i[pA]*BA)}return 27*(n+B+Q+E+h)}}function QgA(t){const A=new Uint8Array(512);for(let e=0;e<512/2;e++)A[e]=e;for(let e=0;e<512/2-1;e++){const g=e+~~(t()*(256-e)),I=A[e];A[e]=A[g],A[g]=I}for(let e=256;e<512;e++)A[e]=A[e-256];return A}var EgA=Object.defineProperty,hgA=Object.getOwnPropertyDescriptor,V=(t,A,e,g)=>{for(var I=g>1?void 0:g?hgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&EgA(A,e,I),I};const mw=aA("debugparticles");var SC=(t=>(t[t.Billboard=0]="Billboard",t[t.Stretch=1]="Stretch",t[t.HorizontalBillboard=2]="HorizontalBillboard",t[t.VerticalBillboard=3]="VerticalBillboard",t[t.Mesh=4]="Mesh",t))(SC||{});class Bn{constructor(){r(this,"alphaKeys"),r(this,"colorKeys")}get duration(){return 1}evaluate(A,e){let g,I=0,i=null,o=0;for(let C=0;C<this.alphaKeys.length;C++){const s=this.alphaKeys[C];(s.time<A||!g)&&(g=s,I=C)}for(let C=0;C<this.colorKeys.length;C++){const s=this.colorKeys[C];(s.time<A||!i)&&(i=s,o=C)}if(i)if(o+1<this.colorKeys.length){const C=this.colorKeys[o+1],s=XA.remap(A,i.time,C.time,0,1);e.r=XA.lerp(i.color.r,C.color.r,s),e.g=XA.lerp(i.color.g,C.color.g,s),e.b=XA.lerp(i.color.b,C.color.b,s)}else e.r=i.color.r,e.g=i.color.g,e.b=i.color.b;if(g)if(I+1<this.alphaKeys.length){const C=this.alphaKeys[I+1],s=XA.remap(A,g.time,C.time,0,1);e.alpha=XA.lerp(g.alpha,C.alpha,s)}else e.alpha=g.alpha;return e}}V([w()],Bn.prototype,"alphaKeys",2),V([w()],Bn.prototype,"colorKeys",2);var Mw=(t=>(t[t.Local=0]="Local",t[t.World=1]="World",t[t.Custom=2]="Custom",t))(Mw||{}),OH=(t=>(t[t.Sphere=0]="Sphere",t[t.SphereShell=1]="SphereShell",t[t.Hemisphere=2]="Hemisphere",t[t.HemisphereShell=3]="HemisphereShell",t[t.Cone=4]="Cone",t[t.Box=5]="Box",t[t.Mesh=6]="Mesh",t[t.ConeShell=7]="ConeShell",t[t.ConeVolume=8]="ConeVolume",t[t.ConeVolumeShell=9]="ConeVolumeShell",t[t.Circle=10]="Circle",t[t.CircleEdge=11]="CircleEdge",t[t.SingleSidedEdge=12]="SingleSidedEdge",t[t.MeshRenderer=13]="MeshRenderer",t[t.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",t[t.BoxShell=15]="BoxShell",t[t.BoxEdge=16]="BoxEdge",t[t.Donut=17]="Donut",t[t.Rectangle=18]="Rectangle",t[t.Sprite=19]="Sprite",t[t.SpriteRenderer=20]="SpriteRenderer",t))(OH||{});class ge{constructor(){r(this,"mode"),r(this,"constant"),r(this,"constantMin"),r(this,"constantMax"),r(this,"curve"),r(this,"curveMin"),r(this,"curveMax"),r(this,"curveMultiplier")}evaluate(A,e){const g=e===void 0?Math.random():e;switch(this.mode){case 0:return this.constant;case 1:return A=XA.clamp01(A),this.curve.evaluate(A)*this.curveMultiplier;case 2:const I=A*this.curveMin.duration,i=A*this.curveMax.duration;return XA.lerp(this.curveMin.evaluate(I),this.curveMax.evaluate(i),g%1)*this.curveMultiplier;case 3:return XA.lerp(this.constantMin,this.constantMax,g%1);default:this.curveMax.evaluate(A)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:return this.constant;case 1:return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(A){if(!A)return 0;let e=Number.MIN_VALUE;for(let g=0;g<A.keys.length;g++){const I=A.keys[g];I.value>e&&(e=I.value)}return e}}V([w()],ge.prototype,"mode",2),V([w()],ge.prototype,"constant",2),V([w()],ge.prototype,"constantMin",2),V([w()],ge.prototype,"constantMax",2),V([w(wr)],ge.prototype,"curve",2),V([w(wr)],ge.prototype,"curveMin",2),V([w(wr)],ge.prototype,"curveMax",2),V([w()],ge.prototype,"curveMultiplier",2);var Rw;const Yo=(Rw=class{constructor(){r(this,"mode"),r(this,"color"),r(this,"colorMin"),r(this,"colorMax"),r(this,"gradient"),r(this,"gradientMin"),r(this,"gradientMax")}evaluate(t,A){const e=A===void 0?Math.random():A;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(t,Yo._temp),Yo._temp;case 2:return Yo._temp.lerpColors(this.colorMin,this.colorMax,e);case 3:return this.gradientMin.evaluate(t,Yo._temp),this.gradientMax.evaluate(t,Yo._temp2),Yo._temp.lerp(Yo._temp2,e)}return Yo._temp.set(16711935),Yo._temp.alpha=1,Yo._temp}},r(Rw,"_temp",new wt(0,0,0,1)),r(Rw,"_temp2",new wt(0,0,0,1)),Rw);let Ci=Yo;V([w(wt)],Ci.prototype,"color",2),V([w(wt)],Ci.prototype,"colorMin",2),V([w(wt)],Ci.prototype,"colorMax",2),V([w(Bn)],Ci.prototype,"gradient",2),V([w(Bn)],Ci.prototype,"gradientMin",2),V([w(Bn)],Ci.prototype,"gradientMax",2);class gI{constructor(){r(this,"cullingMode"),r(this,"duration"),r(this,"emitterVelocityMode"),r(this,"flipRotation"),r(this,"gravityModifier"),r(this,"gravityModifierMultiplier"),r(this,"loop"),r(this,"maxParticles"),r(this,"playOnAwake"),r(this,"prewarm"),r(this,"ringBufferLoopRange"),r(this,"ringBufferMode"),r(this,"scalingMode"),r(this,"simulationSpace"),r(this,"simulationSpeed"),r(this,"startColor"),r(this,"startDelay"),r(this,"startDelayMultiplier"),r(this,"startLifetime"),r(this,"startLifetimeMultiplier"),r(this,"startRotation"),r(this,"startRotationMultiplier"),r(this,"startRotation3D"),r(this,"startRotationX"),r(this,"startRotationXMultiplier"),r(this,"startRotationY"),r(this,"startRotationYMultiplier"),r(this,"startRotationZ"),r(this,"startRotationZMultiplier"),r(this,"startSize"),r(this,"startSize3D"),r(this,"startSizeMultiplier"),r(this,"startSizeX"),r(this,"startSizeXMultiplier"),r(this,"startSizeY"),r(this,"startSizeYMultiplier"),r(this,"startSizeZ"),r(this,"startSizeZMultiplier"),r(this,"startSpeed"),r(this,"startSpeedMultiplier"),r(this,"stopAction"),r(this,"useUnscaledTime")}}V([w(ge)],gI.prototype,"gravityModifier",2),V([w(Ci)],gI.prototype,"startColor",2),V([w(ge)],gI.prototype,"startDelay",2),V([w(ge)],gI.prototype,"startLifetime",2),V([w(ge)],gI.prototype,"startRotation",2),V([w(ge)],gI.prototype,"startRotationX",2),V([w(ge)],gI.prototype,"startRotationY",2),V([w(ge)],gI.prototype,"startRotationZ",2),V([w(ge)],gI.prototype,"startSize",2),V([w(ge)],gI.prototype,"startSizeX",2),V([w(ge)],gI.prototype,"startSizeY",2),V([w(ge)],gI.prototype,"startSizeZ",2),V([w(ge)],gI.prototype,"startSpeed",2);class Bl{constructor(){r(this,"cycleCount"),r(this,"maxCount"),r(this,"minCount"),r(this,"probability"),r(this,"repeatInterval"),r(this,"time"),r(this,"count"),r(this,"_performed",0)}reset(){this._performed=0}run(A){if(A<=this.time)return this.reset(),0;let e=0;if(this.cycleCount===0||this._performed<this.cycleCount){const g=this.time+this.repeatInterval*this._performed;if(A>=g&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:e=this.count.constant;break;case 3:e=XA.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:e=this.count.curve.evaluate(Math.random());break;case 2:const I=Math.random();e=XA.lerp(this.count.curveMin.evaluate(I),this.count.curveMax.evaluate(I),Math.random());break}}return e}}class fC{constructor(){r(this,"enabled"),r(this,"bursts"),r(this,"rateOverTime"),r(this,"rateOverTimeMultiplier"),r(this,"rateOverDistance"),r(this,"rateOverDistanceMultiplier"),r(this,"system")}get burstCount(){var A;return((A=this.bursts)==null?void 0:A.length)??0}reset(){var A;(A=this.bursts)==null||A.forEach(e=>e.reset())}getBurst(){let A=0;if(this.burstCount>0)for(let e=0;e<this.burstCount;e++){const g=this.bursts[e];g.time>=this.system.time&&g.reset(),A+=Math.round(g.run(this.system.time))}return A}}V([w()],fC.prototype,"enabled",2),V([w()],fC.prototype,"bursts",2),V([w(ge)],fC.prototype,"rateOverTime",2),V([w()],fC.prototype,"rateOverTimeMultiplier",2),V([w(ge)],fC.prototype,"rateOverDistance",2),V([w()],fC.prototype,"rateOverDistanceMultiplier",2);class Ql{constructor(){r(this,"enabled"),r(this,"color")}}V([w(Ci)],Ql.prototype,"color",2);class Qn{constructor(){r(this,"enabled"),r(this,"separateAxes"),r(this,"size"),r(this,"sizeMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier"),r(this,"_time",0),r(this,"_temp",new f)}evaluate(A,e,g){if(e||(e=this._temp),!this.enabled)return e.x=e.y=e.z=1,e;if(this.separateAxes)e.x=this.x.evaluate(A,g)*this.xMultiplier,e.y=this.y.evaluate(A,g)*this.yMultiplier,e.z=this.z.evaluate(A,g)*this.zMultiplier;else{const I=this.size.evaluate(A,g)*this.sizeMultiplier;e.x=I}return e}}V([w(ge)],Qn.prototype,"size",2),V([w(ge)],Qn.prototype,"x",2),V([w(ge)],Qn.prototype,"y",2),V([w(ge)],Qn.prototype,"z",2);var Uw;const El=(Uw=class{constructor(){r(this,"shapeType",5),r(this,"enabled",!0),r(this,"alignToDirection",!1),r(this,"angle",0),r(this,"arc",360),r(this,"arcSpread"),r(this,"arcSpeedMultiplier"),r(this,"arcMode"),r(this,"boxThickness"),r(this,"position"),r(this,"rotation"),r(this,"_rotation",new fg),r(this,"scale"),r(this,"radius"),r(this,"radiusThickness"),r(this,"sphericalDirectionAmount"),r(this,"randomDirectionAmount"),r(this,"randomPositionAmount"),r(this,"system"),r(this,"_space"),r(this,"_worldSpaceMatrix",new TA),r(this,"_worldSpaceMatrixInverse",new TA),r(this,"_vector",new f(0,0,0)),r(this,"_temp",new f(0,0,0)),r(this,"_dir",new f),r(this,"_loopTime",0),r(this,"_loopDirection",1),mw&&console.log(this)}get type(){return OH[this.shapeType]}initialize(t){this.getPosition(),t.position.copy(this._vector)}toJSON(){return this}clone(){return new El}update(t,A,e,g){this.system=t,this._space=e,e===1&&(this._worldSpaceMatrix.copy(g.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(t){const A=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return A&&(this._rotation.x=XA.toRadians(this.rotation.x),this._rotation.y=XA.toRadians(this.rotation.y),this._rotation.z=XA.toRadians(this.rotation.z),this._rotation.order="ZYX",t.applyEuler(this._rotation)),A}get vector(){return this._vector}getPosition(){this._vector.set(0,0,0);const t=this._temp.copy(this.position),A=this._space===1;A&&t.applyQuaternion(this.system.worldQuaternion);let e=this.radius;if(A&&(e*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:mw&&nC.DrawBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,e,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,e,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,e,this.radiusThickness,this.arc,this._vector);break;default:this._vector.set(0,0,0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),A&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),mw&&nC.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(t){var A;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const e=t.x,g=t.y,I=t.z;this._dir.set(e,g,I),(A=this.system)!=null&&A.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),mw&&(nC.DrawSphere(t,.01,8925952,.5,!0),nC.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}randomizePosition(t,A){if(A<=0)return;const e=El._tempVec;e.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),e.x*=A*this.scale.x,e.y*=A*this.scale.y,e.z*=A*this.scale.z,t.add(e)}randomizeDirection(t,A){if(A===0)return;const e=El._randomQuat,g=El._tempVec;g.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),e.setFromAxisAngle(g,A*Math.random()*Math.PI),t.applyQuaternion(e)}spherizeDirection(t,A){if(A===0)return;const e=Math.random()*Math.PI*2,g=Math.acos(1-Math.random()*2),I=Math.sin(g)*Math.cos(e),i=Math.sin(g)*Math.sin(e),o=Math.cos(g),C=new f(I,i,o);t.lerp(C,A)}randomSpherePoint(t,A,e,g,I){const i=Math.random(),o=Math.random(),C=2*Math.PI*i*(g/360),s=Math.acos(2*o-1),a=XA.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,n=t.x+this.scale.x*(-a*Math.sin(s)*Math.cos(C)),B=t.y+this.scale.y*(a*Math.sin(s)*Math.sin(C)),Q=t.z+this.scale.z*(a*Math.cos(s));I.x=n,I.y=B,I.z=Q}randomCirclePoint(t,A,e,g,I){const i=Math.random(),o=2*Math.PI*i*(g/360),C=XA.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,s=t.x+this.scale.x*C*Math.cos(o),a=t.y+this.scale.y*C*Math.sin(o),n=t.z;I.x=s,I.y=a,I.z=n}randomConePoint(t,A,e,g,I,i,o){let C=0,s=0;switch(i){case 0:C=Math.random(),s=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:C=.5,s=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let a=2*Math.PI*C*(I/360);switch(i){case 2:case 1:a+=Math.PI+.5,a+=this._loopTime*Math.PI*2,a%=XA.toRadians(I);break}const n=Math.acos(2*s-1),B=XA.lerp(1,1-Math.pow(1-Math.random(),Math.PI),g)*e,Q=t.x+-B*Math.sin(n)*Math.cos(a),E=t.y+B*Math.sin(n)*Math.sin(a),h=t.z;o.x=Q*this.scale.x,o.y=E*this.scale.y,o.z=h*this.scale.z}},r(Uw,"_randomQuat",new GA),r(Uw,"_tempVec",new f),Uw);let og=El;V([w()],og.prototype,"shapeType",2),V([w()],og.prototype,"enabled",2),V([w()],og.prototype,"alignToDirection",2),V([w()],og.prototype,"angle",2),V([w()],og.prototype,"arc",2),V([w()],og.prototype,"arcSpread",2),V([w()],og.prototype,"arcSpeedMultiplier",2),V([w()],og.prototype,"arcMode",2),V([w(f)],og.prototype,"boxThickness",2),V([w(f)],og.prototype,"position",2),V([w(f)],og.prototype,"rotation",2),V([w(f)],og.prototype,"scale",2),V([w()],og.prototype,"radius",2),V([w()],og.prototype,"radiusThickness",2),V([w()],og.prototype,"sphericalDirectionAmount",2),V([w()],og.prototype,"randomDirectionAmount",2),V([w()],og.prototype,"randomPositionAmount",2);class Et{constructor(){r(this,"damping"),r(this,"enabled"),r(this,"frequency"),r(this,"octaveCount"),r(this,"octaveMultiplier"),r(this,"octaveScale"),r(this,"positionAmount"),r(this,"quality"),r(this,"remap"),r(this,"remapEnabled"),r(this,"remapMultiplier"),r(this,"remapX"),r(this,"remapXMultiplier"),r(this,"remapY"),r(this,"remapYMultiplier"),r(this,"remapZ"),r(this,"remapZMultiplier"),r(this,"scrollSpeedMultiplier"),r(this,"separateAxes"),r(this,"strengthMultiplier"),r(this,"strengthX"),r(this,"strengthXMultiplier"),r(this,"strengthY"),r(this,"strengthYMultiplier"),r(this,"strengthZ"),r(this,"strengthZMultiplier"),r(this,"_noise"),r(this,"_time",0),r(this,"_temp",new f)}update(A){this._time+=A.time.deltaTime*this.scrollSpeedMultiplier}apply(A,e,g,I,i,o){if(!this.enabled)return;this._noise||(this._noise=BgA(()=>0));const C=this._temp.set(e.x,e.y,e.z).multiplyScalar(this.frequency),s=this._noise(C.x,C.y,C.z,this._time),a=this._noise(C.x,C.y,C.z,this._time+1e3*this.frequency),n=this._noise(C.x,C.y,C.z,this._time+2e3*this.frequency);this._temp.set(s,a,n).normalize();const B=i/o;let Q=this.positionAmount.evaluate(B);this.separateAxes?(this._temp.x*=Q*this.strengthXMultiplier,this._temp.y*=Q*this.strengthYMultiplier,this._temp.z*=Q*this.strengthZMultiplier):(this.strengthX&&(Q*=this.strengthX.evaluate(B)*1.5),this._temp.multiplyScalar(Q)),g.x+=this._temp.x,g.y+=this._temp.y,g.z+=this._temp.z}}V([w()],Et.prototype,"damping",2),V([w()],Et.prototype,"enabled",2),V([w()],Et.prototype,"frequency",2),V([w()],Et.prototype,"octaveCount",2),V([w()],Et.prototype,"octaveMultiplier",2),V([w()],Et.prototype,"octaveScale",2),V([w(ge)],Et.prototype,"positionAmount",2),V([w()],Et.prototype,"quality",2),V([w(ge)],Et.prototype,"remap",2),V([w()],Et.prototype,"remapEnabled",2),V([w()],Et.prototype,"remapMultiplier",2),V([w(ge)],Et.prototype,"remapX",2),V([w()],Et.prototype,"remapXMultiplier",2),V([w(ge)],Et.prototype,"remapY",2),V([w()],Et.prototype,"remapYMultiplier",2),V([w(ge)],Et.prototype,"remapZ",2),V([w()],Et.prototype,"remapZMultiplier",2),V([w()],Et.prototype,"scrollSpeedMultiplier",2),V([w()],Et.prototype,"separateAxes",2),V([w()],Et.prototype,"strengthMultiplier",2),V([w(ge)],Et.prototype,"strengthX",2),V([w()],Et.prototype,"strengthXMultiplier",2),V([w(ge)],Et.prototype,"strengthY",2),V([w()],Et.prototype,"strengthYMultiplier",2),V([w(ge)],Et.prototype,"strengthZ",2),V([w()],Et.prototype,"strengthZMultiplier",2);class qt{constructor(){r(this,"enabled"),r(this,"attachRibbonToTransform",!1),r(this,"colorOverLifetime"),r(this,"colorOverTrail"),r(this,"dieWithParticles",!0),r(this,"inheritParticleColor",!0),r(this,"lifetime"),r(this,"lifetimeMultiplier"),r(this,"minVertexDistance",.2),r(this,"mode",0),r(this,"ratio",1),r(this,"ribbonCount",1),r(this,"shadowBias",0),r(this,"sizeAffectsLifetime",!1),r(this,"sizeAffectsWidth",!1),r(this,"splitSubEmitterRibbons",!1),r(this,"textureMode",0),r(this,"widthOverTrail"),r(this,"widthOverTrailMultiplier"),r(this,"worldSpace",!1)}getWidth(A,e,g){let I=this.widthOverTrail.evaluate(g);return g===0&&(I=A),A*=I,A}getColor(A,e,g){const I=this.colorOverTrail.evaluate(g),i=this.colorOverLifetime.evaluate(e);A.x*=I.r*i.r,A.y*=I.g*i.g,A.z*=I.b*i.b,A.w*=I.alpha*i.alpha}}V([w()],qt.prototype,"enabled",2),V([w()],qt.prototype,"attachRibbonToTransform",2),V([w(Ci)],qt.prototype,"colorOverLifetime",2),V([w(Ci)],qt.prototype,"colorOverTrail",2),V([w()],qt.prototype,"dieWithParticles",2),V([w()],qt.prototype,"inheritParticleColor",2),V([w(ge)],qt.prototype,"lifetime",2),V([w()],qt.prototype,"lifetimeMultiplier",2),V([w()],qt.prototype,"minVertexDistance",2),V([w()],qt.prototype,"mode",2),V([w()],qt.prototype,"ratio",2),V([w()],qt.prototype,"ribbonCount",2),V([w()],qt.prototype,"shadowBias",2),V([w()],qt.prototype,"sizeAffectsLifetime",2),V([w()],qt.prototype,"sizeAffectsWidth",2),V([w()],qt.prototype,"splitSubEmitterRibbons",2),V([w()],qt.prototype,"textureMode",2),V([w(ge)],qt.prototype,"widthOverTrail",2),V([w()],qt.prototype,"widthOverTrailMultiplier",2),V([w()],qt.prototype,"worldSpace",2);class Tt{constructor(){r(this,"enabled"),r(this,"space",0),r(this,"orbitalX"),r(this,"orbitalY"),r(this,"orbitalZ"),r(this,"orbitalXMultiplier"),r(this,"orbitalYMultiplier"),r(this,"orbitalZMultiplier"),r(this,"orbitalOffsetX"),r(this,"orbitalOffsetY"),r(this,"orbitalOffsetZ"),r(this,"speedModifier"),r(this,"speedModifierMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier"),r(this,"_system"),r(this,"_temp",new f),r(this,"_temp2",new f),r(this,"_temp3",new f),r(this,"_hasOrbital",!1),r(this,"_index",0),r(this,"_orbitalMatrix",new TA)}update(A){this._system=A}init(A){this._index==0&&(A.debug=!0),this._index+=1,A.orbitx=this.orbitalX.evaluate(Math.random()),A.orbity=this.orbitalY.evaluate(Math.random()),A.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=A.orbitx!=0||A.orbity!=0||A.orbitz!=0}apply(A,e,g,I,i,o,C){var s;if(!this.enabled)return;const a=o/C,n=this.speedModifier.evaluate(a)*this.speedModifierMultiplier,B=this.x.evaluate(a),Q=this.y.evaluate(a),E=this.z.evaluate(a);if(this._temp.set(-B,Q,E),this._system,this._hasOrbital&&((s=this._system)==null?void 0:s.worldPos)){const h=this._temp2.set(g.x,g.y,g.z),c=this.orbitalXMultiplier,l=this.orbitalYMultiplier,d=this.orbitalZMultiplier,u=n*Math.PI*2*10,p=Math.cos(u*c),D=Math.sin(u*c),y=Math.cos(u*l),k=Math.sin(u*l),F=Math.cos(u*d),S=Math.sin(u*d),U=h.x*(y*F)+h.y*(y*S)+h.z*-k,M=h.x*(D*k*F-p*S)+h.y*(D*k*S+p*F)+h.z*(D*y),Y=h.x*(p*k*F+D*S)+h.y*(p*k*S-D*F)+h.z*(p*y),_=this._temp3.set(h.x-U,h.y-M,h.z-Y);_.normalize(),_.multiplyScalar(.2/i*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),I.x+=_.x,I.y+=_.y,I.z+=_.z}I.x+=this._temp.x,I.y+=this._temp.y,I.z+=this._temp.z,I.x*=n,I.y*=n,I.z*=n}}V([w()],Tt.prototype,"enabled",2),V([w()],Tt.prototype,"space",2),V([w(ge)],Tt.prototype,"orbitalX",2),V([w(ge)],Tt.prototype,"orbitalY",2),V([w(ge)],Tt.prototype,"orbitalZ",2),V([w()],Tt.prototype,"orbitalXMultiplier",2),V([w()],Tt.prototype,"orbitalYMultiplier",2),V([w()],Tt.prototype,"orbitalZMultiplier",2),V([w()],Tt.prototype,"orbitalOffsetX",2),V([w()],Tt.prototype,"orbitalOffsetY",2),V([w()],Tt.prototype,"orbitalOffsetZ",2),V([w(ge)],Tt.prototype,"speedModifier",2),V([w()],Tt.prototype,"speedModifierMultiplier",2),V([w(ge)],Tt.prototype,"x",2),V([w()],Tt.prototype,"xMultiplier",2),V([w(ge)],Tt.prototype,"y",2),V([w()],Tt.prototype,"yMultiplier",2),V([w(ge)],Tt.prototype,"z",2),V([w()],Tt.prototype,"zMultiplier",2);class II{constructor(){r(this,"animation"),r(this,"enabled"),r(this,"cycleCount"),r(this,"frameOverTime"),r(this,"frameOverTimeMultiplier"),r(this,"numTilesX"),r(this,"numTilesY"),r(this,"startFrame"),r(this,"startFrameMultiplier"),r(this,"rowMode"),r(this,"rowIndex"),r(this,"spriteCount"),r(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(A){if(!this.sampleOnceAtStart())return this.getIndex(A)}getIndex(A){const e=this.numTilesX*this.numTilesY;A=A*this.cycleCount;let g=this.frameOverTime.evaluate(A%1);return g*=this.frameOverTimeMultiplier,g*=e,g=g%e,g=Math.floor(g),g}}V([w()],II.prototype,"animation",2),V([w()],II.prototype,"enabled",2),V([w()],II.prototype,"cycleCount",2),V([w(ge)],II.prototype,"frameOverTime",2),V([w()],II.prototype,"frameOverTimeMultiplier",2),V([w()],II.prototype,"numTilesX",2),V([w()],II.prototype,"numTilesY",2),V([w(ge)],II.prototype,"startFrame",2),V([w()],II.prototype,"startFrameMultiplier",2),V([w()],II.prototype,"rowMode",2),V([w()],II.prototype,"rowIndex",2),V([w()],II.prototype,"spriteCount",2),V([w()],II.prototype,"timeMode",2);class Co{constructor(){r(this,"enabled"),r(this,"separateAxes"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e){return this.enabled?this.separateAxes?0:this.z.evaluate(A,e)*-1:0}}V([w()],Co.prototype,"enabled",2),V([w()],Co.prototype,"separateAxes",2),V([w(ge)],Co.prototype,"x",2),V([w()],Co.prototype,"xMultiplier",2),V([w(ge)],Co.prototype,"y",2),V([w()],Co.prototype,"yMultiplier",2),V([w(ge)],Co.prototype,"z",2),V([w()],Co.prototype,"zMultiplier",2);class Ui{constructor(){r(this,"enabled"),r(this,"range"),r(this,"separateAxes"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e){if(!this.enabled)return 0;if(!this.separateAxes){const g=XA.lerp(this.range.x,this.range.y,e);return this.z.evaluate(g)*-1}return 0}}V([w()],Ui.prototype,"enabled",2),V([w()],Ui.prototype,"range",2),V([w()],Ui.prototype,"separateAxes",2),V([w(ge)],Ui.prototype,"x",2),V([w()],Ui.prototype,"xMultiplier",2),V([w(ge)],Ui.prototype,"y",2),V([w()],Ui.prototype,"yMultiplier",2),V([w(ge)],Ui.prototype,"z",2),V([w()],Ui.prototype,"zMultiplier",2);class ug{constructor(){r(this,"enabled"),r(this,"dampen"),r(this,"drag"),r(this,"dragMultiplier"),r(this,"limit"),r(this,"limitMultiplier"),r(this,"separateAxes"),r(this,"limitX"),r(this,"limitXMultiplier"),r(this,"limitY"),r(this,"limitYMultiplier"),r(this,"limitZ"),r(this,"limitZMultiplier"),r(this,"multiplyDragByParticleSize",!1),r(this,"multiplyDragByParticleVelocity",!1),r(this,"space"),r(this,"_temp",new f),r(this,"_temp2",new f)}apply(A,e,g,I,i,o,C){if(this.enabled){const s=this.limit.evaluate(i)*this.limitMultiplier;if(e.length()>s){this._temp.copy(e).normalize().multiplyScalar(s);let a=this.dampen*.5;e.x=XA.lerp(e.x,this._temp.x,a),e.y=XA.lerp(e.y,this._temp.y,a),e.z=XA.lerp(e.z,this._temp.z,a),g.x=XA.lerp(g.x,this._temp.x,a),g.y=XA.lerp(g.y,this._temp.y,a),g.z=XA.lerp(g.z,this._temp.z,a)}}}}V([w()],ug.prototype,"enabled",2),V([w()],ug.prototype,"dampen",2),V([w(ge)],ug.prototype,"drag",2),V([w()],ug.prototype,"dragMultiplier",2),V([w(ge)],ug.prototype,"limit",2),V([w()],ug.prototype,"limitMultiplier",2),V([w()],ug.prototype,"separateAxes",2),V([w(ge)],ug.prototype,"limitX",2),V([w()],ug.prototype,"limitXMultiplier",2),V([w(ge)],ug.prototype,"limitY",2),V([w()],ug.prototype,"limitYMultiplier",2),V([w(ge)],ug.prototype,"limitZ",2),V([w()],ug.prototype,"limitZMultiplier",2),V([w()],ug.prototype,"multiplyDragByParticleSize",2),V([w()],ug.prototype,"multiplyDragByParticleVelocity",2),V([w()],ug.prototype,"space",2);class En{constructor(){r(this,"enabled"),r(this,"curve"),r(this,"curveMultiplier"),r(this,"mode"),r(this,"system"),r(this,"_lastWorldPosition"),r(this,"_velocity",new f),r(this,"_temp",new f)}update(A){this.enabled&&this.system.worldspace!==!1&&(this._lastWorldPosition?(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)):(this._velocity.set(0,0,0),this._lastWorldPosition=this.system.worldPos.clone()))}applyInitial(A){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const e=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(e),A.add(this._temp)}}applyCurrent(A,e,g){if(this.enabled&&this.system.worldspace!==!1&&this.mode===1){const I=this.curve.evaluate(e,g);this._temp.copy(this._velocity).multiplyScalar(I),A.add(this._temp)}}}V([w()],En.prototype,"enabled",2),V([w(ge)],En.prototype,"curve",2),V([w()],En.prototype,"curveMultiplier",2),V([w()],En.prototype,"mode",2);class _I{constructor(){r(this,"enabled"),r(this,"range"),r(this,"separateAxes"),r(this,"size"),r(this,"sizeMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e,g,I){const i=A.length(),o=XA.remap(i,this.range.x,this.range.y,0,1),C=this.size.evaluate(o,g);return I*C}}V([w()],_I.prototype,"enabled",2),V([w(W)],_I.prototype,"range",2),V([w()],_I.prototype,"separateAxes",2),V([w(ge)],_I.prototype,"size",2),V([w()],_I.prototype,"sizeMultiplier",2),V([w(ge)],_I.prototype,"x",2),V([w()],_I.prototype,"xMultiplier",2),V([w(ge)],_I.prototype,"y",2),V([w()],_I.prototype,"yMultiplier",2),V([w(ge)],_I.prototype,"z",2),V([w()],_I.prototype,"zMultiplier",2);class br{constructor(){r(this,"enabled"),r(this,"range"),r(this,"color")}evaluate(A,e,g){const I=A.length(),i=XA.remap(I,this.range.x,this.range.y,0,1),o=this.color.evaluate(i,e);g.x*=o.r,g.y*=o.g,g.z*=o.b,g.w*=o.alpha}}V([w()],br.prototype,"enabled",2),V([w(W)],br.prototype,"range",2),V([w(Ci)],br.prototype,"color",2);function cgA(t){const A=t.domElement.querySelector("link[rel='ar']");if(A)return A;const e=document.createElement("div");e.classList.add("menu"),e.classList.add("quicklook-menu"),e.style.display="none",e.style.visibility="hidden";const g=document.createElement("button");g.id="open-in-ar",g.innerText="Open in QuickLook",e.appendChild(g);const I=document.createElement("a");I.id="needle-usdz-link",I.style.display="none",I.rel="ar",I.href="",e.appendChild(I);const i=document.createElement("img");return i.id="button",I.appendChild(i),t.domElement.appendChild(e),I}function lgA(){var t=new Date;const A=t.getMonth()+1,e=t.getDate(),g=t.getHours(),I=t.getMinutes(),i=t.getSeconds(),o=(A<10?"0":"")+A,C=(e<10?"0":"")+e,s=(g<10?"0":"")+g,a=(I<10?"0":"")+I,n=(i<10?"0":"")+i;return t.getFullYear()+o+C+"-"+s+a+n}const Fw=aA("debugusdz");function dgA(t,A){const e=[],g=eA.getComponentsInChildren(t,Ai);let I=!1;Fw&&console.log(g);for(const i of g){if(!i||!i.runtimeAnimatorController)continue;Fw&&console.log(i);const o=[];for(const C of i.runtimeAnimatorController.enumerateActions()){Fw&&console.log(C);const s=C.getClip();if(!I&&s.tracks.length>0){I=!0;const a=s.tracks[0],n=a.name.substring(0,a.name.lastIndexOf(".")),B=new Si(n+".position",[0,.01],[0,0,0,0,0,0]),Q=new Si(n+".quaternion",[0,.01],[0,0,0,1,0,0,0,1]);o.push(new Oi("rest",.01,[B,Q]))}o.includes(s)||o.push(s)}e.push({root:i.gameObject,clips:o})}Fw&&console.log(e);for(const i of e)for(const o of i.clips)A.registerAnimation(i.root,o)}var pgA=Object.defineProperty,ugA=Object.getOwnPropertyDescriptor,Ts=(t,A,e,g)=>{for(var I=g>1?void 0:g?ugA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&pgA(A,e,I),I};const kM=aA("debugtext");var bg=(t=>(t[t.UpperLeft=0]="UpperLeft",t[t.UpperCenter=1]="UpperCenter",t[t.UpperRight=2]="UpperRight",t[t.MiddleLeft=3]="MiddleLeft",t[t.MiddleCenter=4]="MiddleCenter",t[t.MiddleRight=5]="MiddleRight",t[t.LowerLeft=6]="LowerLeft",t[t.LowerCenter=7]="LowerCenter",t[t.LowerRight=8]="LowerRight",t))(bg||{});class OI extends Nr{constructor(){super(...arguments),r(this,"alignment",0),r(this,"verticalOverflow",0),r(this,"horizontalOverflow",0),r(this,"lineSpacing",1),r(this,"supportRichText",!1),r(this,"font"),r(this,"fontStyle",0),r(this,"_text",""),r(this,"_fontSize",12),r(this,"_textMeshUi",null),r(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(A){var e;super.setAlphaFactor(A),(e=this.uiObject)==null||e.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(A){A!==this._text&&(this._text=A,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(A){this.text=A}get fontSize(){return this._fontSize}set fontSize(A){var e;this._fontSize=A,(e=this.uiObject)==null||e.set({fontSize:A})}onColorChanged(){var A;(A=this.uiObject)==null||A.set({color:this.color,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeRender(){this.uiObject&&this.Root.screenspace&&this.updateOverflow()}updateOverflow(){var A;const e=(A=this.uiObject)==null?void 0:A._overflow;e&&(e._needsUpdate=!0,this.markDirty())}onCreate(A){kM&&console.log(this),this.horizontalOverflow==1&&(A.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,A.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,A.lineHeight=this.lineSpacing,delete A.backgroundOpacity,delete A.backgroundColor,kM&&(A.backgroundColor=16750848,A.backgroundOpacity=.5);const e=this.rectTransform;A={...A,...this.getTextOpts()},this.getAlignment(A),kM&&(A.backgroundColor=Math.random()*16777215,A.backgroundOpacity=.1),this.uiObject=e.createNewText(A),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){let A=this.fontSize;const e={color:this.color,fontOpacity:this.color.alpha,fontSize:A,fontKerning:"normal"};return this.setFont(e,this.fontStyle),e}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10)}getAlignment(A){switch(A.flexDirection="column",this.alignment){case 0:case 3:case 6:A.textAlign="left";break;case 1:case 4:case 7:A.textAlign="center";break;case 2:case 5:case 8:A.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:A.alignItems="start";break;case 3:case 4:case 5:A.alignItems="center";break;case 6:case 7:case 8:A.alignItems="end";break}return A}feedText(A,e){var g,I,i;if(!this.uiObject)return null;if(this._textMeshUi||(this._textMeshUi=[]),!e||A.length===0)this.uiObject.textContent=A;else{let o=this.getNextTag(A);if(o)o.startIndex>0&&this.uiObject.add(new gw({textContent:A.substring(0,o.startIndex),color:"inherit"}));else return this.uiObject.textContent=A;const C=[];for(;o;){const s=this.getNextTag(A,o.endIndex),a={fontFamily:(g=this.uiObject)==null?void 0:g.get("fontFamily"),color:"inherit",textContent:""};s?(a.textContent=this.getText(A,o,s),this.handleTag(o,a,C),(I=this.uiObject)==null||I.add(new gw(a))):(a.textContent=A.substring(o.endIndex),this.handleTag(o,a,C),(i=this.uiObject)==null||i.add(new gw(a))),o=s}}return null}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const A=[],e=this.canvas,g={renderOnTop:e.renderOnTop,depthWrite:e.depthWrite,doubleSided:e.doubleSided};for(;;){let I=!1;if(this._textMeshUi)for(let i=0;i<this._textMeshUi.length;i++){if(A[i]===!0)continue;I=!0;const o=this._textMeshUi[i];o.textContent&&(pw(o,g),A[i]=!0)}if(!I)break;yield}}handleTag(A,e,g){if(A.isEndTag){if(g.length>0){const I=g.pop();if(I)for(const i in I.previousValues){const o=I.previousValues[i];e[i]=o}}}else if(A.type.includes("color")){const I=new GM(A,{color:e.color});if(g.push(I),A.type.length>6){const i=parseInt("0x"+A.type.substring(7));e.color=i}else e.color=new fA(1,1,1)}else if(A.type=="b"){this.setFont(e,1);const I=new GM(A,{fontWeight:700});g.push(I)}else if(A.type=="i"){this.setFont(e,2);const I=new GM(A,{fontStyle:"italic"});g.push(I)}}getText(A,e,g){return A.substring(e.endIndex,g.startIndex)}getNextTag(A,e=0){const g=A.indexOf("<",e),I=A.indexOf(">",g);if(g>=0&&I>=0){const i=A.substring(g+1,I);return{type:i,startIndex:g,endIndex:I+1,isEndTag:i.startsWith("/")}}return null}setFont(A,e){if(!this.font)return;let g=this.font,I=jm.getFontFamily(g);I||(I=jm.addFontFamily(g)),A.fontFamily=I;const i=g.toLowerCase();switch(e){default:case 0:A.fontWeight=400,A.fontStyle="normal";break;case 1:A.fontWeight=700,A.fontStyle="normal",i.includes("-bold")||(g+="-bold");break;case 2:A.fontWeight=400,A.fontStyle="italic",i.includes("-italic")||(g+="-italic");break;case 3:A.fontStyle="italic",A.fontWeight=400,i.includes("-bold")||(g+="-bold"),i.includes("-italic")||(g+="-italic")}let o=I.getVariant(A.fontWeight,A.fontStyle);if(!o){let C=g;C!=null&&C.endsWith("-msdf.json")||(C+="-msdf.json");let s=g;s!=null&&s.endsWith(".png")||(s+=".png"),o=I.addVariant(A.fontWeight,A.fontStyle,C,s),o?.addEventListener("ready",()=>{this.markDirty()})}}}Ts([w()],OI.prototype,"alignment",2),Ts([w()],OI.prototype,"verticalOverflow",2),Ts([w()],OI.prototype,"horizontalOverflow",2),Ts([w()],OI.prototype,"lineSpacing",2),Ts([w()],OI.prototype,"supportRichText",2),Ts([w(URL)],OI.prototype,"font",2),Ts([w()],OI.prototype,"fontStyle",2),Ts([w()],OI.prototype,"text",1),Ts([w()],OI.prototype,"fontSize",1);class GM{constructor(A,e){r(this,"tag"),r(this,"previousValues"),this.tag=A,this.previousValues=e}}class hn{constructor(A){r(this,"id"),r(this,"content",""),r(this,"font",[]),r(this,"pointSize",144),r(this,"width"),r(this,"height"),r(this,"depth"),r(this,"wrapMode"),r(this,"horizontalAlignment"),r(this,"verticalAlignment"),r(this,"material"),this.id=A}static getId(){return this.global_id++}setDepth(A){return this.depth=A,this}setPointSize(A){return this.pointSize=A,this}setHorizontalAlignment(A){return this.horizontalAlignment=A,this}setVerticalAlignment(A){return this.verticalAlignment=A,this}writeTo(A,e){var g;e.beginBlock(`def Preliminary_Text "${this.id}"`),this.content&&e.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(g=this.font)==null||g.push("sans-serif"));const I=this.font.map(i=>`"${i}"`).join(", ");e.appendLine(`string[] font = [ ${I} ]`),e.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&e.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&e.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&e.appendLine(`double depth = ${this.depth}`),this.wrapMode&&e.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&e.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&e.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&e.appendLine(`rel material:binding = </Materials/Material_${this.material.id}>`),e.closeBlock()}}r(hn,"global_id",0);class Nw{static singleLine(A,e,g){const I=new hn("text_"+hn.getId());return I.content=A,e&&(I.pointSize=e),g&&(I.depth=g),I}static multiLine(A,e,g,I,i,o){const C=new hn("text_"+hn.getId());return C.content=A,C.width=e,C.height=g,C.horizontalAlignment=I,C.verticalAlignment=i,o!==void 0&&(C.wrapMode=o),C}}const DgA=new TA().makeRotationY(Math.PI);class Kw{get extensionName(){return"text"}onExportObject(A,e,g){const I=eA.getComponent(A,OI);if(I){const i=eA.getComponent(A,DI);let o=100,C=100;i&&(o=i.width,C=i.height);const s=e.clone();s.matrix=DgA.clone();const a=new fA().copySRGBToLinear(I.color);s.material=new zn({color:a,emissive:a}),e.add(s),s.addEventListener("serialize",(n,B)=>{const Q=Nw.multiLine(I.text,o,C,"center","bottom","flowing");this.setTextAlignment(Q,I.alignment),this.setOverflow(Q,I),s.material&&(Q.material=s.material),Q.pointSize=this.convertToTextSize(I.fontSize),Q.depth=.001,Q.writeTo(void 0,n)})}}convertToTextSize(A){return 1/.0502*144*A}setOverflow(A,e){e.horizontalOverflow?A.wrapMode="singleLine":A.wrapMode="flowing"}setTextAlignment(A,e){switch(e){case bg.LowerLeft:case bg.MiddleLeft:case bg.UpperLeft:A.horizontalAlignment="left";break;case bg.LowerCenter:case bg.MiddleCenter:case bg.UpperCenter:A.horizontalAlignment="center";break;case bg.LowerRight:case bg.MiddleRight:case bg.UpperRight:A.horizontalAlignment="right";break}switch(e){case bg.LowerLeft:case bg.LowerCenter:case bg.LowerRight:A.verticalAlignment="bottom";break;case bg.MiddleLeft:case bg.MiddleCenter:case bg.MiddleRight:A.verticalAlignment="middle";break;case bg.UpperLeft:case bg.UpperCenter:case bg.UpperRight:A.verticalAlignment="top";break}}}var wgA=Object.defineProperty,ygA=Object.getOwnPropertyDescriptor,so=(t,A,e,g)=>{for(var I=g>1?void 0:g?ygA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&wgA(A,e,I),I};const kC=aA("debugusdz");class cn{constructor(){r(this,"callToAction"),r(this,"checkoutTitle"),r(this,"checkoutSubtitle"),r(this,"callToActionURL")}}so([w()],cn.prototype,"callToAction",2),so([w()],cn.prototype,"checkoutTitle",2),so([w()],cn.prototype,"checkoutSubtitle",2),so([w()],cn.prototype,"callToActionURL",2);class ao extends RA{constructor(){super(...arguments),r(this,"objectToExport"),r(this,"autoExportAnimations",!1),r(this,"exportFileName"),r(this,"customUsdzFile"),r(this,"customBranding"),r(this,"anchoringType","plane"),r(this,"planeAnchoringAlignment","horizontal"),r(this,"interactive",!0),r(this,"extensions",[]),r(this,"link"),r(this,"webxr"),r(this,"webARSessionRoot"),r(this,"lastCallback"),r(this,"_quicklookButton"),r(this,"_quicklookButtonContainer",null)}start(){var A,e,g,I;kC&&(console.log(this),console.log("Debug USDZ, press 't' to export"),window.addEventListener("keydown",i=>{switch(i.key){case"t":this.exportAsync();break}}),Un()&&setTimeout(()=>{this.exportAsync()},2e3)),(A=document.getElementById("open-in-ar"))==null||A.addEventListener("click",i=>{i.preventDefault(),this.exportAsync()}),this.objectToExport||(this.objectToExport=this.gameObject),!((g=(e=this.objectToExport)==null?void 0:e.children)!=null&&g.length)&&!((I=this.objectToExport)!=null&&I.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new dw),this.extensions.push(new cw),this.extensions.push(new Kw))}onEnable(){const A=OE(),e=OC();(kC||A&&e)&&(this.addQuicklookButton(),this.webARSessionRoot=eA.findObjectOfType(Xa)??void 0,this.lastCallback=this.quicklookCallback.bind(this),this.link=cgA(this.context),this.link.addEventListener("message",this.lastCallback)),kC&&Hg("USDZ Exporter enabled: "+this.name)}onDisable(){var A;(A=this.link)==null||A.removeEventListener("message",this.lastCallback);const e=OE(),g=OC();(kC||e&&g)&&this.removeQuicklookButton(),kC&&Hg("USDZ Exporter disabled: "+this.name)}async exportAsync(){var A;let e=this.exportFileName??((A=this.objectToExport)==null?void 0:A.name)??this.name;if(qa()||(e+="-MadeWithNeedle"),e+="-"+lgA(),this.customUsdzFile){const E=this.buildQuicklookOverlay();kC&&console.log(E);const h=E.callToAction?encodeURIComponent(E.callToAction):"",c=E.checkoutTitle?encodeURIComponent(E.checkoutTitle):"",l=E.checkoutSubtitle?encodeURIComponent(E.checkoutSubtitle):"";this.link.href=this.customUsdzFile+`#callToAction=${h}&checkoutTitle=${c}&checkoutSubtitle=${l}&callToActionURL=${E.callToActionURL}`,console.log(this.link.href),this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click();return}if(!this.objectToExport)return;if(this.webARSessionRoot){const E=this.webARSessionRoot.gameObject,h=1/this.webARSessionRoot.arScale;E.matrix.makeScale(h,h,h),this.webARSessionRoot.invertForward&&E.matrix.multiply(new TA().makeRotationY(Math.PI))}const g=new J9,I=[...this.extensions],i=new UD;I.push(i),this.autoExportAnimations&&dgA(this.objectToExport,i);const o={self:this,exporter:g,extensions:I,object:this.objectToExport};this.dispatchEvent(new CustomEvent("before-export",{detail:o})),g.debug=kC,this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal");const C=await g.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:I,quickLookCompatible:!0}),s=new Blob([C],{type:"application/octet-stream"});this.dispatchEvent(new CustomEvent("after-export",{detail:o}));const a=this.buildQuicklookOverlay();kC&&console.log(a);const n=a.callToAction?encodeURIComponent(a.callToAction):"",B=a.checkoutTitle?encodeURIComponent(a.checkoutTitle):"",Q=a.checkoutSubtitle?encodeURIComponent(a.checkoutSubtitle):"";this.link.href=URL.createObjectURL(s)+`#callToAction=${n}&checkoutTitle=${B}&checkoutSubtitle=${Q}&callToActionURL=${a.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}quicklookCallback(A){if(A?.data=="_apple_ar_quicklook_button_tapped"){kC&&fo("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const g=new URLSearchParams(this.link.href);if(g){const I=g.get("callToActionURL");kC&&Hg("Quicklook url: "+I),I&&(qa()?globalThis.open(I,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",I))}}}}buildQuicklookOverlay(){var A,e,g;const I={};return this.customBranding&&Object.assign(I,this.customBranding),qa()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),I.callToAction="Close",I.checkoutTitle="\u{1F335} Made with Needle",I.checkoutSubtitle="_"),(A=I.callToAction)!=null&&A.length||(I.callToAction="Close"),(e=I.checkoutTitle)!=null&&e.length||(I.checkoutTitle="\u{1F335} Made with Needle"),(g=I.checkoutSubtitle)!=null&&g.length||(I.checkoutSubtitle="_"),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:I})),I}async createQuicklookButton(){var A,e;if(!this.webxr)if(await _E(1),this.webxr=eA.findObjectOfType(Se)??void 0,this.webxr)if(this.webxr.VRButton&&((A=this.webxr.VRButton.parentElement)==null||A.removeChild(this.webxr.VRButton)),this.webxr.ARButton&&this._quicklookButton!==this.webxr.ARButton){this._quicklookButton=this.webxr.ARButton;const g=(e=this.webxr.ARButton.parentElement)==null?void 0:e.querySelector("a");g&&(g.href=""),this.webxr.ARButton.innerText="Open in Quicklook",this.webxr.ARButton.disabled=!1,this.webxr.ARButton.addEventListener("click",I=>{I.preventDefault(),this.exportAsync()}),this.webxr.ARButton.classList.add("quicklook-ar-button"),this._quicklookButtonContainer=this.webxr.ARButton.parentElement,this.dispatchEvent(new CustomEvent("created-button",{detail:this.webxr.ARButton}))}else{this.webxr.createARButton=!1,this.webxr.createVRButton=!1;let g=window.document.querySelector(".webxr-buttons");g||(g=document.createElement("div"),g.classList.add("webxr-buttons"));const I=document.createElement("button");I.innerText="Open in Quicklook",I.addEventListener("click",()=>{this.exportAsync()}),I.classList.add("webxr-ar-button"),I.classList.add("webxr-button"),I.classList.add("quicklook-ar-button"),g.appendChild(I),this._quicklookButtonContainer=g,this.dispatchEvent(new CustomEvent("created-button",{detail:I}))}else console.warn("Could not find WebXR component: will not create Quicklook button",we.Current)}async addQuicklookButton(){await this.createQuicklookButton(),this._quicklookButton&&this._quicklookButtonContainer&&this._quicklookButtonContainer.appendChild(this._quicklookButton)}removeQuicklookButton(){var A;(A=this._quicklookButton)==null||A.remove()}}so([w(UA)],ao.prototype,"objectToExport",2),so([w()],ao.prototype,"autoExportAnimations",2),so([w()],ao.prototype,"exportFileName",2),so([w(URL)],ao.prototype,"customUsdzFile",2),so([w(cn)],ao.prototype,"customBranding",2),so([w()],ao.prototype,"anchoringType",2),so([w()],ao.prototype,"planeAnchoringAlignment",2),so([w()],ao.prototype,"interactive",2);const PH=aA("debugdeletable");class Jw extends rC{}class mM extends RA{constructor(){super(...arguments),r(this,"deleteBoxes",[])}awake(){this.deleteBoxes=eA.findObjectsOfType(Jw,this.context)}update(){for(const A of this.deleteBoxes){const e=this.gameObject;if(A.isInBox(e)===!0){const g=eA.getComponentInParent(this.gameObject,RQ);g?PH&&console.warn("Can not delete object with usage marker",this.guid,g):(PH&&console.log("DESTROY",this.gameObject),Fu(this.gameObject,this.context.connection))}}}}var SgA=Object.defineProperty,fgA=Object.getOwnPropertyDescriptor,vr=(t,A,e,g)=>{for(var I=g>1?void 0:g?fgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&SgA(A,e,I),I};class Ho extends TI{constructor(){super(...arguments),r(this,"mode"),r(this,"focusDistance"),r(this,"focalLength"),r(this,"aperture"),r(this,"gaussianMaxRadius"),r(this,"resolutionScale"),r(this,"bokehScale")}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=e=>{const g=e/300,I=2;return XA.lerp(I,.01,g)};const A=20;this.aperture.valueProcessor=e=>{const g=1-e/32;return XA.lerp(1,A,g)}}onCreateEffect(){if(this.mode===0)return;const A=1/window.devicePixelRatio;if(this.resolutionScale===void 0){let g=1;Un()&&(g=.6),this.resolutionScale=new qe(g*A)}const e=new Ob(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=g=>{e.circleOfConfusionMaterial.worldFocusDistance=g},this.focalLength.onValueChanged=g=>e.circleOfConfusionMaterial.worldFocusRange=g,this.aperture.onValueChanged=g=>e.bokehScale=g,this.resolutionScale&&(this.resolutionScale.onValueChanged=g=>e.resolution.scale=g),[e]}unapply(){}}vr([w()],Ho.prototype,"mode",2),vr([w(qe)],Ho.prototype,"focusDistance",2),vr([w(qe)],Ho.prototype,"focalLength",2),vr([w(qe)],Ho.prototype,"aperture",2),vr([w(qe)],Ho.prototype,"gaussianMaxRadius",2),vr([w(qe)],Ho.prototype,"resolutionScale",2),vr([w(qe)],Ho.prototype,"bokehScale",2),uC("DepthOfField",Ho);var kgA=Object.defineProperty,GgA=Object.getOwnPropertyDescriptor,mgA=(t,A,e,g)=>{for(var I=g>1?void 0:g?GgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&kgA(A,e,I),I};class qw extends RA{constructor(){super(...arguments),r(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||eA.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:MgA()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}mgA([w()],qw.prototype,"visibleOn",2);let bw;function MgA(){if(bw===!0||bw===!1)return bw;let t=!1;return function(A){(/(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(A)||/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(A.substr(0,4)))&&(t=!0)}(navigator.userAgent||navigator.vendor||window.opera),bw=t,t}class MM{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(A){}}var jH=(t=>(t.SelectStart="selectstart",t.SelectEnd="selectend",t))(jH||{});const ln=class extends MQ{constructor(){super(),r(this,"transformSelf",!0),r(this,"orbit",null),r(this,"selectStartEventListener",[]),r(this,"selectEndEventListener",[]),r(this,"_dragHelper",null),r(this,"_draggingRigidbodies",[]),r(this,"_waitingForDragStart",null),r(this,"_isDragging",!1),r(this,"_marker",null),r(this,"_dragDelta"),r(this,"_didDrag",!1),r(this,"_activePointerId"),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new W}static get HasAnySelected(){return this._active>0}addDragEventListener(t,A){switch(t){case"selectstart":this.selectStartEventListener.push(A);break;case"selectend":this.selectEndEventListener.push(A);break}}start(){this.orbit=eA.findObjectOfType(vs,this.context)}allowEdit(t=null){return this.context.connection.allowEditing}onPointerEnter(t){if(!this.allowEdit(this.gameObject)||Se.IsInWebXR)return;const A=eA.getComponentInParent(t.object,ln);!A||A!==this||(ln.lastHovered=t.object,this.context.domElement.style.cursor="pointer")}onPointerExit(t){this.allowEdit(this.gameObject)&&(Se.IsInWebXR||ln.lastHovered===t.object&&(this.context.domElement.style.cursor="auto"))}onPointerDown(t){this.allowEdit(this.gameObject)&&(Se.IsInWebXR||(ln._active+=1,this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=t,t.StopPropagation(),this.orbit&&(this.orbit.enabled=!1)))}onPointerUp(t){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(ln._active>0&&(ln._active-=1),!Se.IsInWebXR&&(this.onDragEnd(t),t.StopPropagation(),this.orbit&&(this.orbit.enabled=!0)))}update(){var t;if(!Se.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){const e=this.context.input.getPointerPositionDelta(0);if(e&&this._dragDelta.add(e),this._dragDelta.length()>2)this._didDrag=!0;else return}const A=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(A)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),(((t=this._dragHelper)==null?void 0:t.hasSelected)===!1||this._activePointerId!==void 0&&this.context.input.getPointerPressed(this._activePointerId)===!1)&&this.onDragEnd(null)}}onDragStart(t){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new VH(this.context.mainCamera);else return;if(!t||!t.object)return;const A=eA.getComponentInParent(t.object,ln);if(!A||A!==this)return;let e=t.object;this.transformSelf&&(e=this.gameObject);const g={selected:e,attached:e};for(const C of this.selectStartEventListener)C(this,g);if(this._activePointerId=t.pointerId,!g.attached)return;g.attached,e=g.attached,this._isDragging=!0,this._dragHelper.setSelected(e,this.context),this.orbit&&(this.orbit.enabled=!1);const I=eA.getComponentInChildren(e,tn);I&&(I.fastMode=!0,I?.requestOwnership()),this._marker=eA.addNewComponent(e,RQ),this._draggingRigidbodies.length=0;const i=eA.getComponentsInChildren(e,Ht);i&&this._draggingRigidbodies.push(...i);const o=yd();eA.invokeOnChildren(this._dragHelper.selected,o("onDragStart"))}onUpdateDrag(){if(this._dragHelper){this._dragHelper.onUpdate(this.context);for(const t of this._draggingRigidbodies)t.wakeUp(),t.resetVelocities()}}onDragEnd(t){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const g of this._draggingRigidbodies)g.setVelocity(g.smoothedVelocity);this._draggingRigidbodies.length=0;const A=this._dragHelper.selected;if(this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),t!=null&&t.object){const g=eA.getComponentInChildren(t.object,tn);g&&(g.fastMode=!1)}this._marker&&this._marker.destroy();for(const g of this.selectEndEventListener)g(this);const e=yd();eA.invokeOnChildren(A,e("onDragEnd"))}};let iE=ln;r(iE,"_active",0),r(iE,"lastHovered");const WH=class{constructor(t){r(this,"_selected",null),r(this,"_context",null),r(this,"_camera"),r(this,"_cameraPlane",new Hi),r(this,"_hasGroundPlane",!1),r(this,"_groundPlane",new Hi),r(this,"_groundOffset",new f),r(this,"_groundOffsetFactor",0),r(this,"_groundDistance",0),r(this,"_groundPlanePoint",new f),r(this,"_raycaster",new TB),r(this,"_cameraPlaneOffset",new f),r(this,"_intersection",new f),r(this,"_worldPosition",new f),r(this,"_inverseMatrix",new TA),r(this,"_rbs",[]),r(this,"_groundLine"),r(this,"_groundMarker"),r(this,"_groundOffsetVector",new f(0,1,0)),r(this,"_requireUpdateGroundPlane",!0),r(this,"_didDragOnGroundPlaneLastFrame",!1),this._camera=t;const A=new Ag(WH.geometry),e=A.material;e.color=new fA(.4,.4,.4),A.layers.set(2),A.name="line",A.scale.y=1,this._groundLine=A;const g=new Qo(.5,22,22),I=new lt({color:e.color}),i=new yA(g,I);i.visible=!1,i.layers.set(2),this._groundMarker=i}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(t,A){if(this._selected&&A)for(const e of this._rbs)e.wakeUp(),e.setVelocity(0,0,0);if(this._selected&&YI.Remove(A,this._selected),this._selected=t,this._context=A,this._rbs.length=0,t?(A.scene.add(this._groundLine),A.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!A){console.error("DragHelper: no context");return}YI.Add(A,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(t){var A,e,g,I,i;if(!this._context)return;const o="Space",C="KeyD",s=((A=this._context)==null?void 0:A.input.isKeyPressed(o))||((e=this._context)==null?void 0:e.input.isKeyPressed(C)),a=this._context.input.getTouchesPressedCount()>=2||s;if(a){const B=this._context.input.getPointerPositionDelta(0);B&&(this._groundOffsetVector.set(0,1,0),(g=this._selected)==null||g.rotateOnWorldAxis(this._groundOffsetVector,B.x*this._context.time.deltaTime))}const n=this._context.input.getPointerPositionRC(0);if(n&&(this._raycaster.setFromCamera(n,this._camera),this._selected)){this._groundOffsetVector.set(0,1,0);const B=ye(this._camera).clone().sub(ye(this._selected)).normalize(),Q=Math.abs(B.dot(this._groundOffsetVector)),E=((I=this._context)==null?void 0:I.input.isKeyPressed(o))||((i=this._context)==null?void 0:i.input.isKeyPressed(C)),h=!a&&Q>.2&&!E&&this._context.input.getPointerPressedCount()<=1,c=this._didDragOnGroundPlaneLastFrame!==h;if(this._didDragOnGroundPlaneLastFrame=h,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!h||c)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){const l=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=l,h){this._groundOffsetVector.set(0,1,0);const d=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(d,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);c&&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(t,A,e){if(this._selected){if(e){const g=ye(this._selected);g.y=t.y,t=g}if(tg(this._selected,t),tg(this._groundLine,t),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=A!==null,A){const g=ye(this._camera).distanceTo(A)*.01;this._groundMarker.scale.set(g,g,g),tg(this._groundMarker,A)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const t=this._context.input.getPointerPositionRC(0);t&&(this._raycaster.setFromCamera(t,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;const t=ye(this._selected),A=new As(new f(0,.1,0).add(t),new f(0,-1,0)),e=new Go;e.ignore=[this._selected];const g=this._context.physics.raycastFromRay(A,e);for(let I=0;I<g.length;I++){const i=g[I];if(!i.face||this.contains(this._selected,i.object))continue;const o=new f(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(o,i.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(A.direction.multiplyScalar(-1),A.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(t),this._groundOffset.copy(this._intersection).sub(t)}onDidUpdate(){Ei.markDirty(this._selected);for(const t of this._rbs)t.wakeUp(),t.resetForcesAndTorques(),t.setAngularVelocity(0,0,0)}contains(t,A){if(t===A)return!0;if(t.children){for(const e of t.children)if(this.contains(e,A))return!0}return!1}};let VH=WH;r(VH,"geometry",new pe().setFromPoints([new f(0,0,0),new f(0,-1,0)]));function RM(t,A,e){console.warn("Adding components on object has been temporarily disabled")}var zH=(t=>(t.File_Spawned="file-spawned",t))(zH||{});class ZH{constructor(A,e,g,I,i,o,C,s){r(this,"guid"),r(this,"file_name"),r(this,"file_hash"),r(this,"file_size"),r(this,"position"),r(this,"seed"),r(this,"sender"),r(this,"serverUrl"),r(this,"parentGuid"),r(this,"boundsSize"),this.seed=e,this.guid=g,this.file_name=I,this.file_hash=i,this.file_size=o,this.position=C,this.sender=A,this.serverUrl=s}}async function UM(t,A,e){const g=t.name;return g.endsWith(".gltf")||g.endsWith(".glb")?new Promise((I,i)=>{const o=new FileReader;o.readAsArrayBuffer(t),o.onloadend=async C=>{const s=o.result,a=Nu(),n=new VI(a),B=await Uo().parseSync(A,s,t.name,n);if(B&&B.scene){const Q=B.scene;if(!Q.guid){const E=new VI(a);Q.guid=E.generateUUID()}e&&RgA(A.connection,t,a,Q,e),RM(),I(B)}}}):(console.warn("Unsupported file type: "+g),console.log(t),null)}async function XH(t,A){return new Promise(async(e,g)=>{const I=Nu(),i=new VI(I),o=t.toString(),C=await Uo().loadSync(A,o,o,i);C&&C.scene?(C.scene,RM(),e(C)):console.warn("Unsupported file type: "+t.toString())})}_t.registerCallback(ci.ContextCreated,t=>{$H(t.context)});function $H(t){t.connection.beginListen("file-spawned",async A=>{if(A.sender!==t.connection.connectionId){console.log("received file event",A),UgA(A,t);let e=null;try{e=await bk(A.file_name,A.file_hash,A.file_size,A.serverUrl)}finally{FgA(A)}if(e){const g=new VI(A.seed),I=await Uo().parseSync(t,e,null,g);if(I&&I.scene){const i=I.scene;if(RM(),A.parentGuid){const o=zh(A.parentGuid,t.scene);"add"in o&&o.add(i)}i.parent||t.scene.add(i),A.position!==null&&i.position.copy(A.position)}}else console.error("download didnt return file")}})}async function RgA(t,A,e,g,I){if(!t.connectionId){console.error("Can not upload file - no connection id");return}if(!g.guid){console.error("Can not upload file - no guid",g,g.guid);return}const i=await av(A,I);if(!i)return;if(!i.filename){console.error("Can not send upload event - no filename",A.name);return}if(!i.hash){console.error("Can not send upload event - no hash",A.name);return}const o=new ZH(t.connectionId,e,g.guid,i.filename,i.hash,A.size,g.position,i.url??I);g.parent&&(o.parentGuid=g.parent.guid),t.send("file-spawned",o)}const FM={};function UgA(t,A){const e=new pt,g=new yA(e,new lt({color:65280})),I=new Xp(g,5592405);if(FM[t.guid]=I,A.scene.add(I),t.parentGuid){const i=zh(t.parentGuid,A.scene);i&&i.add(I)}t.position&&I.position.copy(t.position)}function FgA(t,A){const e=t.guid,g=FM[e];g&&(delete FM[e],g.removeFromParent())}var NgA=Object.defineProperty,KgA=Object.getOwnPropertyDescriptor,NM=(t,A,e,g)=>{for(var I=g>1?void 0:g?KgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&NgA(A,e,I),I};const JgA=aA("debugnet"),KM=class extends RA{constructor(){super(...arguments),r(this,"url",null),r(this,"urlParameterName",null),r(this,"localhost",null)}awake(){JgA&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let t=this.url?KM.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const e=aA(this.urlParameterName);e&&typeof e=="string"&&(t=e)}if(!t)return null;const A=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(t);return A!=null&&A.groups?A?.groups.socket_prefix?t:"wss://"+A?.groups.url:null}static GetUrl(t,A){let e=t;const g=KM.IsLocalNetwork()&&A;return g&&(e=A),t!=null&&t.startsWith("/")&&(e=(g?e:window.location.origin)+t),e}static IsLocalNetwork(t=window.location.hostname){return fI(t)}};let Lr=KM;NM([w()],Lr.prototype,"url",2),NM([w()],Lr.prototype,"urlParameterName",2),NM([w()],Lr.prototype,"localhost",2);var qgA=Object.defineProperty,bgA=Object.getOwnPropertyDescriptor,AT=(t,A,e,g)=>{for(var I=g>1?void 0:g?bgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&qgA(A,e,I),I};class hl extends RA{constructor(){super(...arguments),r(this,"filesBackendUrl"),r(this,"localhost"),r(this,"_dragOver"),r(this,"_drop")}onEnable(){this.filesBackendUrl=this.filesBackendUrl?Lr.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(A){A.preventDefault()}async addFiles(A){for(const e of A){if(!e)continue;console.log("Register file "+e.name+" to",this.filesBackendUrl,e);const g=await UM(e,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:e})),g&&this.addObject(void 0,g)}}async onDrop(A){if(console.log(A),!A.dataTransfer)return;A.preventDefault();const e=A.dataTransfer.items;if(e)for(const g in e){const I=e[g];if(I.kind==="file"){const i=I.getAsFile();if(!i)continue;console.log("Register file "+i.name+" to",this.filesBackendUrl,i);const o=await UM(i,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),o&&this.addObject(A,o)}else I.kind==="string"&&I.type=="text/plain"&&I.getAsString(async i=>{console.log("dropped url",i);try{const o=new URL(i);if(!o)return;const C=await XH(o,this.context);C&&this.addObject(A,C)}catch{console.log("dropped string is not a valid URL!",i)}})}}async addObject(A,e){console.log("Dropped",e);const g=e.scene;if(A!==void 0){const I=new Go;I.setMask(16777215),I.screenPointFromOffset(A.offsetX,A.offsetY);const i=this.context.physics.raycast(I);if(i&&i.length>0)for(const o of i){g.position.copy(o.point);break}}this.gameObject.add(g),this.dispatchEvent(new CustomEvent("object-added",{detail:e}))}}AT([w()],hl.prototype,"filesBackendUrl",2),AT([w()],hl.prototype,"localhost",2);var vgA=Object.defineProperty,LgA=Object.getOwnPropertyDescriptor,vw=(t,A,e,g)=>{for(var I=g>1?void 0:g?LgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&vgA(A,e,I),I};class xr extends MQ{constructor(){super(...arguments),r(this,"parent",null),r(this,"object",null),r(this,"limitCount",10),r(this,"limitInterval",60),r(this,"_currentCount",0),r(this,"_startPosition",null),r(this,"_startQuaternion",null)}awake(){var A,e;if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=((A=this.object.position)==null?void 0:A.clone())??new f(0,0,0),this._startQuaternion=((e=this.object.quaternion)==null?void 0:e.clone())??new GA(0,0,0,1)}const g=eA.getComponentInParent(this.gameObject,iE);g?g.addDragEventListener(jH.SelectStart,(I,i)=>{if(this._currentCount>=this.limitCount){i.attached=null;return}const o=this.handleDuplication(i.selected);o&&(console.assert(o!==i.selected,"Duplicated object is original"),i.attached=o)}):console.warn("Could no find drag controls in parent",this.name),dg.addEventListener(Ks.SelectStart,(I,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}const o=this.handleDuplication(i.selected);o&&(i.grab=o)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(A){var e;if(this._currentCount>=this.limitCount||!this.object)return null;if(A===this.gameObject||this.handleMultiObject(A)){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);const g=new gC;this.parent||(this.parent=this.gameObject.parent),this.parent&&(g.parent=this.parent.guid??((e=this.parent.userData)==null?void 0:e.guid),g.keepWorldPosition=!0),g.position=this.worldPosition,g.rotation=this.worldQuaternion,g.context=this.context,this._currentCount+=1;const I=eA.instantiateSynced(this.object,g);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(A){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,A):!1}isInChildren(A,e){if(!A)return!1;if(A===e)return!0;if(A.children){for(let g of A.children)if(this.isInChildren(g,e))return!0}return!1}}vw([w(UA)],xr.prototype,"parent",2),vw([w(UA)],xr.prototype,"object",2),vw([w()],xr.prototype,"limitCount",2),vw([w()],xr.prototype,"limitInterval",2);var oE=(t=>(t[t.PointerEnter=0]="PointerEnter",t[t.PointerExit=1]="PointerExit",t[t.PointerDown=2]="PointerDown",t[t.PointerUp=3]="PointerUp",t[t.PointerClick=4]="PointerClick",t[t.Drag=5]="Drag",t[t.Drop=6]="Drop",t[t.Scroll=7]="Scroll",t[t.UpdateSelected=8]="UpdateSelected",t[t.Select=9]="Select",t[t.Deselect=10]="Deselect",t[t.Move=11]="Move",t[t.InitializePotentialDrag=12]="InitializePotentialDrag",t[t.BeginDrag=13]="BeginDrag",t[t.EndDrag=14]="EndDrag",t[t.Submit=15]="Submit",t[t.Cancel=16]="Cancel",t))(oE||{}),xgA=Object.defineProperty,YgA=Object.getOwnPropertyDescriptor,JM=(t,A,e,g)=>{for(var I=g>1?void 0:g?YgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&xgA(A,e,I),I};class qM{constructor(){r(this,"eventID"),r(this,"callback")}}JM([w()],qM.prototype,"eventID",2),JM([w(ti)],qM.prototype,"callback",2);class Lw extends RA{constructor(){super(...arguments),r(this,"triggers")}invoke(A){if(this.triggers)for(const e of this.triggers)e.eventID===A&&e.callback.invoke()}onPointerClick(A){this.invoke(oE.PointerClick)}onPointerEnter(A){this.invoke(oE.PointerEnter)}onPointerExit(A){this.invoke(oE.PointerExit)}onPointerDown(A){this.invoke(oE.PointerDown)}onPointerUp(A){this.invoke(oE.PointerUp)}}JM([w(qM)],Lw.prototype,"triggers",2);var HgA=Object.defineProperty,TgA=Object.getOwnPropertyDescriptor,bM=(t,A,e,g)=>{for(var I=g>1?void 0:g?TgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&HgA(A,e,I),I};class vM extends RA{constructor(){super(...arguments),r(this,"connectedBody"),r(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ht)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.createJoint(this.rigidBody,this.connectedBody)}}bM([w(Ht)],vM.prototype,"connectedBody",2);class LM extends vM{createJoint(A,e){var g;(g=this.context.physics.engine)==null||g.addFixedJoint(A,e)}}class cl extends vM{constructor(){super(...arguments),r(this,"anchor"),r(this,"axis")}createJoint(A,e){var g;this.axis&&this.anchor&&((g=this.context.physics.engine)==null||g.addHingeJoint(A,e,this.anchor,this.axis))}}bM([w(f)],cl.prototype,"anchor",2),bM([w(f)],cl.prototype,"axis",2);const _gA={type:"change"};let OgA=class extends mg{constructor(t,A){super(),this.object=t,this.domElement=A,this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1;const e=this,g=1e-6,I=new GA,i=new f;this.tmpQuaternion=new GA,this.status=0,this.moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this.moveVector=new f(0,0,0),this.rotationVector=new f(0,0,0),this.keydown=function(B){if(!B.altKey){switch(B.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this.moveState.forward=1;break;case"KeyS":this.moveState.back=1;break;case"KeyA":this.moveState.left=1;break;case"KeyD":this.moveState.right=1;break;case"KeyR":this.moveState.up=1;break;case"KeyF":this.moveState.down=1;break;case"ArrowUp":this.moveState.pitchUp=1;break;case"ArrowDown":this.moveState.pitchDown=1;break;case"ArrowLeft":this.moveState.yawLeft=1;break;case"ArrowRight":this.moveState.yawRight=1;break;case"KeyQ":this.moveState.rollLeft=1;break;case"KeyE":this.moveState.rollRight=1;break}this.updateMovementVector(),this.updateRotationVector()}},this.keyup=function(B){switch(B.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this.moveState.forward=0;break;case"KeyS":this.moveState.back=0;break;case"KeyA":this.moveState.left=0;break;case"KeyD":this.moveState.right=0;break;case"KeyR":this.moveState.up=0;break;case"KeyF":this.moveState.down=0;break;case"ArrowUp":this.moveState.pitchUp=0;break;case"ArrowDown":this.moveState.pitchDown=0;break;case"ArrowLeft":this.moveState.yawLeft=0;break;case"ArrowRight":this.moveState.yawRight=0;break;case"KeyQ":this.moveState.rollLeft=0;break;case"KeyE":this.moveState.rollRight=0;break}this.updateMovementVector(),this.updateRotationVector()},this.pointerdown=function(B){if(this.dragToLook)this.status++;else{switch(B.button){case 0:this.moveState.forward=1;break;case 2:this.moveState.back=1;break}this.updateMovementVector()}},this.pointermove=function(B){if(!this.dragToLook||this.status>0){const Q=this.getContainerDimensions(),E=Q.size[0]/2,h=Q.size[1]/2;this.moveState.yawLeft=-(B.pageX-Q.offset[0]-E)/E,this.moveState.pitchDown=(B.pageY-Q.offset[1]-h)/h,this.updateRotationVector()}},this.pointerup=function(B){if(this.dragToLook)this.status--,this.moveState.yawLeft=this.moveState.pitchDown=0;else{switch(B.button){case 0:this.moveState.forward=0;break;case 2:this.moveState.back=0;break}this.updateMovementVector()}this.updateRotationVector()},this.update=function(B){const Q=B*e.movementSpeed,E=B*e.rollSpeed;e.object.translateX(e.moveVector.x*Q),e.object.translateY(e.moveVector.y*Q),e.object.translateZ(e.moveVector.z*Q),e.tmpQuaternion.set(e.rotationVector.x*E,e.rotationVector.y*E,e.rotationVector.z*E,1).normalize(),e.object.quaternion.multiply(e.tmpQuaternion),(i.distanceToSquared(e.object.position)>g||8*(1-I.dot(e.object.quaternion))>g)&&(e.dispatchEvent(_gA),I.copy(e.object.quaternion),i.copy(e.object.position))},this.updateMovementVector=function(){const B=this.moveState.forward||this.autoForward&&!this.moveState.back?1:0;this.moveVector.x=-this.moveState.left+this.moveState.right,this.moveVector.y=-this.moveState.down+this.moveState.up,this.moveVector.z=-B+this.moveState.back},this.updateRotationVector=function(){this.rotationVector.x=-this.moveState.pitchDown+this.moveState.pitchUp,this.rotationVector.y=-this.moveState.yawRight+this.moveState.yawLeft,this.rotationVector.z=-this.moveState.rollRight+this.moveState.rollLeft},this.getContainerDimensions=function(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}},this.dispose=function(){this.domElement.removeEventListener("contextmenu",eT),this.domElement.removeEventListener("pointerdown",C),this.domElement.removeEventListener("pointermove",o),this.domElement.removeEventListener("pointerup",s),window.removeEventListener("keydown",a),window.removeEventListener("keyup",n)};const o=this.pointermove.bind(this),C=this.pointerdown.bind(this),s=this.pointerup.bind(this),a=this.keydown.bind(this),n=this.keyup.bind(this);this.domElement.addEventListener("contextmenu",eT),this.domElement.addEventListener("pointerdown",C),this.domElement.addEventListener("pointermove",o),this.domElement.addEventListener("pointerup",s),window.addEventListener("keydown",a),window.addEventListener("keyup",n),this.updateMovementVector(),this.updateRotationVector()}};function eT(t){t.preventDefault()}class xM extends RA{constructor(){super(...arguments),r(this,"_controls",null)}onEnable(){var A;const e=(A=eA.getComponent(this.gameObject,Kt))==null?void 0:A.cam;this._controls=new OgA(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){var A;(A=this._controls)==null||A.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}}var PgA=Object.defineProperty,jgA=Object.getOwnPropertyDescriptor,YM=(t,A,e,g)=>{for(var I=g>1?void 0:g?jgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&PgA(A,e,I),I};class CE extends RA{constructor(){super(...arguments),r(this,"_fog")}get fog(){return this._fog||(this._fog=new O0(0,0,50)),this._fog}get mode(){return 1}set near(A){this.fog.near=A}get near(){return this.fog.near}set far(A){this.fog.far=A}get far(){return this.fog.far}set color(A){this.fog.color.copy(A)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}YM([w()],CE.prototype,"near",1),YM([w()],CE.prototype,"far",1),YM([w(fA)],CE.prototype,"color",1);let HM,TM,sE,xw;function _M(t,A,e){TM||(TM=new Wg(2,2,1,1)),sE||(sE=new je({uniforms:{blitTexture:new mA(t)},vertexShader:`
|
|
4561
|
+
`&&t.length>1&&EH([e],t[t.length-2]),A.offsetX}function oeA(t){if(!t[0])return 0;let A=[],e;for(let g=0;g<t.length;g++){const I=t[g];if(I.char&&BH[I.char]&&t.length>g){A.push(I),e=t[g+1];continue}break}hH(A,e),A=[],e=null;for(let g=t.length-1;g>0;g--){const I=t[g];if(I.char&&BH[I.char]&&g>0){A.push(I),e=t[g-1];continue}break}return EH(A,e),t[0].offsetX}function CeA(t){return t[0]?t[0].offsetX:0}function EH(t,A){if(A)for(let e=0;e<t.length;e++){const g=t[e];g.fontFactor=0,g.offsetX=A.offsetX+A.cumulativeWidth,g.cumulativeWidth=0}}function hH(t,A){if(A)for(let e=0;e<t.length;e++){const g=t[e];g.fontFactor=0,g.offsetX=A.offsetX,g.cumulativeWidth=0}}function cH(t,A,e,g){if(g=g||0,!t[A])return g;const I=t[A];return I.lineBreak?g+I.xadvance:cH(t,A+1,e,g+I.xadvance+I.xoffset+I.kerning+e.LETTERSPACING)}function seA(t,A,e,g){return!t||!t.char||A+e<g.INNER_WIDTH?!1:g.BREAKON.indexOf(t.char)>-1}class lH extends EY{constructor(){super(),this._input="inherit",this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A),A._fontSize._needsProcess=!0,A._layouter._needsProcess=!0}}class dH extends Ft{constructor(){super("fontSize","inherit",!0),this._allowsInherit=!1}computeOutputValue(A){this._value=this._inheritedInput,A._font._fontVariant&&(A._bounds._needsProcess=!0,A._layouter._needsProcess=!0)}process(A){if(!A._font._fontVariant||!A._font._fontVariant.isReady)return;const e=this._value/A._font._fontVariant.typographic.size,g=A._inlines._value;for(let I=0;I<g.length;I++){const i=g[I];i.resetOffsets(),i.fontSize=this._value,i.fontFactor=e}}get value(){return this._value}}class pH extends hY{constructor(){super("segments",1,!1),this._notInheritedValue=void 0}update(A,e){this._notInheritedValue=this._value,this._notInheritedValue==="inherit"&&(this._notInheritedValue=this.getInheritedInput(A)),A._layouter._needsUpdate=!0}set value(A){this._value!==A&&(this._value=A,this._needsUpdate=!0)}get value(){return this._value==="inherit"?this._notInheritedValue:this._value}}class aeA extends pH{constructor(){super(),this._value="inherit"}}class neA extends PD{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A),A._parent._value._layouter._needsProcess=!1}process(A){if(this._value!=="none"){const e=A._whiteSpace._whiteSpacedContent,g=A._inlines._value;for(let I=1;I<g.length;I++){const i=e[I-1]+e[I];g[I].kerning=A._font._fontVariant.getKerningAmount(i)}}}}class uH extends Qt{constructor(){super("children",null,!1),this._uis=[]}update(A,e){}process(A){}_compute(A){}dispose(){}}function reA(t,A=!1){const e=t[0].index!==null,g=new Set(Object.keys(t[0].attributes)),I=new Set(Object.keys(t[0].morphAttributes)),i={},o={},C=t[0].morphTargetsRelative,s=new $A.BufferGeometry;let a=0;for(let n=0;n<t.length;++n){const B=t[n];let Q=0;if(e!==(B.index!==null))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."),null;for(const E in B.attributes){if(!g.has(E))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+'. All geometries must have compatible attributes; make sure "'+E+'" attribute exists among all geometries, or in none of them.'),null;i[E]===void 0&&(i[E]=[]),i[E].push(B.attributes[E]),Q++}if(Q!==g.size)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+". Make sure all geometries have the same number of attributes."),null;if(C!==B.morphTargetsRelative)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+". .morphTargetsRelative must be consistent throughout all geometries."),null;for(const E in B.morphAttributes){if(!I.has(E))return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+". .morphAttributes must be consistent throughout all geometries."),null;o[E]===void 0&&(o[E]=[]),o[E].push(B.morphAttributes[E])}if(s.userData.mergedUserData=s.userData.mergedUserData||[],s.userData.mergedUserData.push(B.userData),A){let E;if(e)E=B.index.count;else if(B.attributes.position!==void 0)E=B.attributes.position.count;else return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index "+n+". The geometry must have either an index or a position attribute"),null;s.addGroup(a,E,n),a+=E}}if(e){let n=0;const B=[];for(let Q=0;Q<t.length;++Q){const E=t[Q].index;for(let h=0;h<E.count;++h)B.push(E.getX(h)+n);n+=t[Q].attributes.position.count}s.setIndex(B)}for(const n in i){const B=DH(i[n]);if(!B)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+n+" attribute."),null;s.setAttribute(n,B)}for(const n in o){const B=o[n][0].length;if(B===0)break;s.morphAttributes=s.morphAttributes||{},s.morphAttributes[n]=[];for(let Q=0;Q<B;++Q){const E=[];for(let c=0;c<o[n].length;++c)E.push(o[n][c][Q]);const h=DH(E);if(!h)return console.error("THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the "+n+" morphAttribute."),null;s.morphAttributes[n].push(h)}}return s}function DH(t){let A,e,g,I=0;for(let C=0;C<t.length;++C){const s=t[C];if(s.isInterleavedBufferAttribute)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported."),null;if(A===void 0&&(A=s.array.constructor),A!==s.array.constructor)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."),null;if(e===void 0&&(e=s.itemSize),e!==s.itemSize)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."),null;if(g===void 0&&(g=s.normalized),g!==s.normalized)return console.error("THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."),null;I+=s.array.length}const i=new A(I);let o=0;for(let C=0;C<t.length;++C)i.set(t[C].array,o),o+=t[C].array.length;return new $A.BufferAttribute(i,e,g)}class BeA extends Qt{constructor(){super("renderer")}render(A){if(!A._inlines._value||!A._inlines._value.length)return;const e=A._inlines._value.map(I=>A._font._fontVariant.getGeometricGlyph(I,A).translate(I.offsetX,I.offsetY,0)),g=reA(e);A.setFontMesh(new $A.Mesh(g,A.fontMaterial)),A._fontMesh.renderOrder=1/0}}class QeA extends Bm{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!1}computeOutputValue(A){this._value=this._inheritedInput,A._layouter._needsProcess=!0}}class LE extends bc{constructor(A={}){const e={};LE.definePropertiesValues(e,A),super(e,A),r(this,"_rebuildParentUI",()=>{super._rebuildParentUI(),this._layouter._needsUpdate=!0}),LE.init(this)}add(A){const e=[];for(let g=0;g<arguments.length;g++){const I=arguments[g];!I.isUI||I.isInline?(e.push(I),I.position.z=.005):console.warn("Block element can only contain Box elements.",I)}return super.add(...e)}set textContent(A){this._textContent.value=A}get textContent(){return this._textContent._value}set invertAlpha(A){this._invertAlpha.value=A}get invertAlpha(){return this._invertAlpha._value}static definePropertiesValues(A,e){A.children||(A.children=uH),A.textContent||(A.textContent=jAA),A.glyphs||(A.glyphs=VAA),A.inlines||(A.inlines=WAA),A.layouter||(A.layouter=sH),A.renderer||(A.renderer=BeA),A.fontFamily||(A.fontFamily=rH),A.fontWeight||(A.fontWeight=nH),A.fontStyle||(A.fontStyle=aH),A.fontSize||(A.fontSize=dH),A.color||(A.color=zAA),A.backgroundColor||(A.backgroundColor=ZAA),A.lineBreak||(A.lineBreak=CH),A.letterSpacing||(A.letterSpacing=lH),A.whiteSpace||(A.whiteSpace=Om),A.segments||(A.segments=aeA),A.textAlign||(A.textAlign=QeA),A.fontKerning||(A.fontKerning=neA)}static init(A){Object.defineProperties(A,{isInline:{configurable:!1,enumerable:!0,value:!0}})}}class EeA extends tY{constructor(){super("textContent",null,!1),this._needsUpdate=!1}set value(A){this._value!==A&&(this._value=A,this._needsUpdate=!0)}update(A,e){this._needsUpdate=!1;for(let g=A.children.length-1;g>=0;g--){const I=A.children[g];I.isUI&&(A.remove(I),I.clear())}A._children._uis=[],this._value&&A.add(new LE({name:"anonymousInline",textContent:this._value}))}}class heA extends Array{constructor(...A){super(...A),this.width=0,this.height=0}}class ceA extends Qt{constructor(){super("layouter",null,!1),this._value=null}update(A,e){}process(A){let e=A._width._value;A._width._auto?e=1/0:e=A._bounds._innerWidth;const g=A._lineHeight._value,I=new heA(new oH);let i=0;A._children._inlines.forEach(B=>{if(!B._inlines.value)return;this._resetInlines(B);const Q=B._fontSize._value,E=B._letterSpacing._value*Q,h=B._whiteSpace._value,c=B._lineBreak._value,l={WHITESPACE:h,LETTERSPACING:E,BREAKON:c,INNER_WIDTH:e},d=B._whiteSpace._inlineWrapper;i+=B._margin._value.w+B._padding._value.w,B._inlines.value.forEach((u,p,D)=>{const y=I[I.length-1];if(d(D,p,i,l)){if(I.push(new oH(u)),u.offsetX=u.xoffset,u.width===0){i=0;return}u.cumulativeWidth=u.xadvance+E,i=u.cumulativeWidth;return}I[I.length-1].push(u),u.offsetX=i+u.xoffset+u.kerning,u.cumulativeWidth=u.xadvance+u.kerning+E,i+=u.cumulativeWidth,y.length-1===1&&y[y.length-2].width===0&&(u.offsetX-=u.xoffset,i-=u.xoffset)}),i+=B._margin._value.y+B._padding._value.y});const o=A._whiteSpace._inlineCollapser;let C=0,s=0,a=0;I.forEach((B,Q)=>{const E=o(B);let h=0,c=0;if(B.forEach(l=>{h=Math.max(h,l.lineHeight),c=Math.max(c,l.lineBase),l.offsetX-=E}),B.lineHeight=h,B.lineBase=c,Q===0?a=-(h*g-h)*.5:a-=I[Q-1].lineHeight*g,B.y=a,B.x=0,B.forEach(l=>{l.offsetY=a-l.anchor,l.lineHeight<B.lineHeight&&(l.offsetY-=B.lineBase-l.lineBase)}),s+=B.lineHeight*g,B.width=0,B[0]){const l=B[B.length-1];B.width=l.offsetX+l.cumulativeWidth+l.paddingRight+l.marginRight+B[0].offsetX,C=Math.max(C,B.width)}}),I.height=s,I.width=C,this._value=I,e===1/0&&A._bounds.setChildrenWidth(A,I.width),A._height._auto&&A._bounds.setChildrenHeight(A,I.height);const n=A._parent._value;n&&(n._autoSize._needsProcess=!0,n._flexDirection._needsProcess=!0),A._inlineJustificator._needsProcess=!0,A._textAlign._needsProcess=!0,A._overflow._needsUpdate=!0}_resetInlines(A){A._fontSize.process(A)}}class leA extends Bm{constructor(){super(),this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(A){this._value=this._inheritedInput,this._needsProcess=!0}process(A){deA(A),A._renderer._needsRender=!0}}function deA(t){const A=t._layouter._value,e=t._textAlign._value,g=t._bounds._innerWidth;for(let I=0;I<A.length;I++){const i=A[I],o=peA(t,i,I===A.length-1),C=t._padding._value,s=t._borderWidth._value,a=(-C.w+C.y)/2+(-s.w+s.y)/2;i.x+=o;for(let n=0;n<i.length;n++)i[n].offsetX+=o-a}if(e.indexOf("justify")===0)for(let I=0;I<A.length;I++){const i=A[I];if(e.indexOf("-")!==-1&&I===A.length-1)return;const o=g-i.width;if(o<=0)return;let C=0;for(let B=1;B<i.length-1;B++)C+=i[B].char===" "?1:0;const s=o/C;let a=1;e==="justify-right"&&(i.reverse(),a=-1);let n=0;for(let B=1;B<=i.length-1;B++){const Q=i[B];Q.offsetX+=n*a,n+=Q.char===" "?s:0}e==="justify-right"&&i.reverse()}}function peA(t,A,e){switch(t._textAlign._value){case"justify-left":case"justify":case"left":return-t._bounds._innerWidth/2;case"justify-right":case"right":return-A.width+t._bounds._innerWidth/2;case"center":return-A.width/2;case"justify-center":return e?-A.width/2:-t._bounds._innerWidth/2;default:console.warn(`textAlign: '${t._textAlign._value}' is not valid`)}}class ueA extends Qm{constructor(){super(),this._value=this._input="column",this._allowsInherit=!1,this._needsUpdate=!0}computeOutputValue(A){this._value=this._inheritedInput}}class DeA extends BY{constructor(){super(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}}class weA extends PD{constructor(){super(),this._value=this._input=this.getDefaultValue(),this._allowsInherit=!1,this.computeOutputValue=this._computeFromInherited}_computeFromInherited(A){super._computeFromInherited(A)}}class yeA extends tH{constructor(){super(),this._innerWidth=1/0,this._innerHeight=0}}class SeA extends Qt{constructor(){super("children",null,!1),r(this,"_sortOrder",(A,e)=>A._order._value<e._order._value?-1:A._order._value>e._order._value?1:this._uis.indexOf(A)<this._uis.indexOf(e)?-1:1),this._uis=[],this._inlines=[],this._boxes=[]}update(A,e){this._compute(A),this._needsProcess=!0}process(A){this._compute(A),A._overflow._needsRender=!0}_compute(A){this._uis=A.children.filter(e=>e.visible&&e.isUI),this._inlines=this._uis.filter(e=>e.isInline).sort(this._sortOrder)}dispose(){this._inlines=null}}class feA extends Qt{constructor(){super("autosize")}process(A){if(A._layouter._value&&A._layouter._value.length){const e=A._layouter._value,g=A._padding._value,I=A._borderWidth._value;A._width._auto&&A._bounds.setOffsetWidth(A,e.width+g.w+g.y+I.w+I.y),A._height._auto&&A._bounds.setOffsetHeight(A,e.height+g.x+g.z+I.x+I.z)}}}class keA extends iH{constructor(){super("renderer"),this._needsUpdate=!1}render(A){super.render(A);for(const e of A._children._inlines)e._renderer.render(e);A.performAfterUpdate()}}class ud extends dd{constructor(A={},e={}){ud.definePropertiesValues(e,A),super(e,A),ud.init(this)}add(A){const e=[];let g=!1;for(let I=0;I<arguments.length;I++){const i=arguments[I];!i.isUI||i.isInline?(i.isInline&&(g=!0),e.push(i)):console.warn("Block element can only contain Box elements.",i)}return e.length>0&&super.add(...e),g&&(this._children._needsUpdate=!0,this._layouter._needsProcess=!0),this}set textContent(A){this._textContent.value=A}get textContent(){return super.textContent}set invertAlpha(A){this._invertAlpha.value=A}get invertAlpha(){return this._invertAlpha._value}get lines(){return this._layouter._value}static definePropertiesValues(A,e){A.flexDirection=ueA,A.justifyContent=Em,A.alignItems=rm,A.bounds=yeA,A.autoSize=feA,A.renderer=keA,A.children||(A.children=SeA),A.textContent||(A.textContent=EeA),A.layouter||(A.layouter=ceA),A.lineHeight||(A.lineHeight=DeA),A.textAlign||(A.textAlign=leA),A.whiteSpace||(A.whiteSpace=Om),A.fontKerning||(A.fontKerning=weA),A.segments||(A.segments=pH),e.width||(e.width="100%"),e.fontSide||(e.fontSide=0)}static init(A){Object.defineProperties(A,{isText:{configurable:!1,enumerable:!0,value:!0}})}}class GeA extends Qt{constructor(){super("inlines",null,!1),this._value=[]}process(A){this._value[0].paddingLeft=A._padding._value.w,this._value[0].marginLeft=A._margin._value.w;const e=this._value.length-1;this._value[e].paddingRight=A._padding._value.y,this._value[e].marginRight=A._margin._value.y}}class meA extends Qt{constructor(){super("renderer")}render(A){A._backgroundMesh||A.setBackgroundMesh(new IH(A)),A._backgroundMesh.position.x=A._inlines._value[0].offsetX+A._inlines._value[0].width/2,A._backgroundMesh.position.y=A._inlines._value[0].offsetY+A._inlines._value[0].lineBase/2,A._bounds.render(A)}}class MeA extends Qt{constructor(){super("bounds",null,!1),this._size=new $A.Vector3(1,1,1),this._offsetWidth=0,this._offsetHeight=0,this._innerWidth=0,this._innerHeight=0}update(A,e){this.output(e),this._needsProcess=!0}process(A){this._offsetWidth=this._innerWidth=A._inlines._value[0].width,this._offsetHeight=this._innerHeight=A._inlines._value[0].height,this._needsRender=!0,A._borderWidth._needsRender=!0,A._borderRadius._needsRender=!0}render(A){this._size.x=this._offsetWidth,this._size.y=this._offsetHeight}output(A){A.size=this._size}}class Dd extends bc{constructor(A={}){const e={};Dd.definePropertiesValues(e,A),super(e,A),Dd.init(this)}clear(){for(const A of this._inlines._value)A.clear();return super.clear()}bindBackgroundMeshProperties(){this._backgroundMesh.raycast=()=>{},this._bounds._size=this._backgroundMesh.scale,this._bounds._needsUpdate=!0}unbindBackgroundMeshProperties(){this._bounds._size=new $A.Vector3(1,1,1),this._bounds._needsUpdate=!0}add(A){const e=[];for(let g=0;g<arguments.length;g++){const I=arguments[g];I.isUI?console.warn("ThreeMeshUI::InlineBlockElement cannot contains UI Elements.",I):(e.push(I),I.position.z=.005)}return super.add(...e)}static definePropertiesValues(A,e){A.children||(A.children=uH),A.bounds||(A.bounds=MeA),A.inlines||(A.inlines=GeA),A.layouter||(A.layouter=sH),A.renderer||(A.renderer=meA),A.fontFamily||(A.fontFamily=rH),A.fontWeight||(A.fontWeight=nH),A.fontStyle||(A.fontStyle=aH),A.fontSize||(A.fontSize=dH),A.backgroundColor||(A.backgroundColor=$x),A.lineBreak||(A.lineBreak=CH),A.letterSpacing||(A.letterSpacing=lH),A.whiteSpace||(A.whiteSpace=Om),A.fontKerning||(A.fontKerning=PD),e.backgroundSize||(e.backgroundSize="cover"),e.width||(e.width="100%"),e.height||(e.height="100%"),e.boxSizing||(e.boxSizing="border-box")}static init(A){Object.defineProperties(A,{isInline:{configurable:!1,enumerable:!0,value:!0},isInlineBlock:{configurable:!1,enumerable:!0,value:!0}}),A._inlines._value=[new ReA(A)],A.backgroundMaterial=new eH,A._renderer.render(A)}}class ReA extends CY{constructor(A){super(),this._uiElement=A}get xadvance(){const A=this._uiElement._padding._value,e=this._uiElement._width;return e._relative?e._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.w+A.y+e.value}get width(){const A=this._uiElement._width;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get height(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get anchor(){return this.height}get lineHeight(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}get lineBase(){const A=this._uiElement._height;return A._relative?A._value*this._uiElement._fontSize.getInheritedInput(this._uiElement):A.value}clear(){this._uiElement=null}}class wH{constructor(A){this._subject=A}attach(){console.error(`Behavior::attach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}act(){throw new Error(`Behavior::act() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}detach(){console.error(`Behavior::detach() - Is abstract and therefore should be overridden in ${this.constructor.name}`)}clear(){}}const yH=()=>ew.update(),SH={BaseProperty:Qt,Block:pd,Text:ud,Inline:LE,InlineBlock:Dd,MeshUIBaseElement:bc,FontLibrary:Sr,update:yH,MSDFFontMaterialUtils:Eo,ShaderChunkUI:AH,Behavior:wH,FontVariant:Mc};typeof global<"u"&&(global.ThreeMeshUI=SH);const UeA=SH;var FeA=lg.w8,fH=lg.cg,Pm=lg.gO,NeA=lg.wb,jm=lg.zV,KeA=lg.HS,JeA=lg.Ec,gw=lg.gF,qeA=lg.ol,beA=lg.pz,veA=lg.tx,LeA=lg.hj,xeA=lg.FV,YeA=lg.sV,kH=lg.xv,HeA=lg.mx,TeA=lg.gE,_eA=lg.ZP,GH=lg.Vx;const mH=Object.freeze(Object.defineProperty({__proto__:null,BaseProperty:FeA,Behavior:fH,Block:Pm,DefaultValues:NeA,FontLibrary:jm,FontVariant:KeA,InheritableProperty:JeA,Inline:gw,InlineBlock:qeA,InlineGlyph:beA,MSDFFontMaterialUtils:veA,MaterialTransformers:LeA,MeshUIBaseElement:xeA,ShaderChunkUI:YeA,Text:kH,TypographicFont:HeA,TypographicGlyph:TeA,default:_eA,update:GH},Symbol.toStringTag,{value:"Module"}));Pm.prototype.interactable={get(){return this.interactive},set(t){this.interactable=t}};const Ns=Symbol("shadowDomOwner");class _o extends RA{constructor(){super(...arguments),r(this,"shadowComponent",null),r(this,"_controlsChildLayout",!0),r(this,"_root"),r(this,"_parentComponent")}isRoot(){var A;return((A=this.Root)==null?void 0:A.gameObject)===this.gameObject}get canvas(){const A=this.Root;return A!=null&&A.isCanvas?A:null}markDirty(){io.markUIDirty(this.context)}get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(A){this._controlsChildLayout=A,this.shadowComponent&&(this.shadowComponent.autoLayout=A)}get Root(){return this._root===void 0&&(this._root=eA.getComponentInParent(this.gameObject,vc)),this._root}get Canvas(){return this.canvas}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0}onEnable(){super.onEnable()}addShadowComponent(A,e){var g;this.removeShadowComponent();const I=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=eA.getComponentInParent(I,_o),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}A.name=this.name+" ("+(this.constructor.name??"UI")+")",A.autoLayout=this._parentComponent.controlsChildLayout,A[Ns]=this,this.setShadowComponentOwner(A);let i=!1;if(((g=this.Root)==null?void 0:g.gameObject)===this.gameObject)this.gameObject.add(A);else{let o=this._parentComponent.shadowComponent;o&&(o?.add(A),i=!0)}this.shadowComponent=A,e&&e.shadowComponent&&this.shadowComponent&&e.shadowComponent.add(this.shadowComponent),Mh&&A.add(new _B(.5)),this.onAfterAddedToScene(),i&&GH()}set(A){}setShadowComponentOwner(A){if(A&&(A[Ns]===void 0||A[Ns]===this)&&(A[Ns]=this,A.children))for(const e of A.children)this.setShadowComponentOwner(e)}traverseOwnedShadowComponents(A,e,g){if(A&&A[Ns]===e){g(A);for(const I of A.children)this.traverseOwnedShadowComponents(I,e,g)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(A){this.shadowComponent&&(this.shadowComponent.interactable=A)}}class vc extends _o{awake(){super.awake()}}class bQ{static getObject(A){const e=A[Ns];return e&&(e.isComponent===!0?A=e.gameObject:A=e),A}static isInteractable(A,e){if(e&&(e.canvasGroup=void 0,e.graphic=void 0),A==null||!A.visible||(A=this.getObject(A),!A.visible))return!1;const g=this.tryFindCanvasGroup(A);if(g?.isCanvasGroup===!0&&(e&&(e.canvasGroup=g),g.blocksRaycasts===!1||g.interactable===!1))return!1;const I=Qr(A,i=>{if(i.isGraphic===!0)return i},!1);return e&&I?.isGraphic===!0&&(e.graphic=I),!(I?.raycastTarget===!1||I?.layer===2)}static tryFindCanvasGroup(A){if(!A)return null;const e=Qr(A,g=>{const I=g;if(I.blocksRaycasts!==void 0&&I.interactable!==void 0)return I},!1);return e!==void 0?e:this.tryFindCanvasGroup(A.parent)}}const Lc=aA("debugwebxrcontroller");var vQ=(t=>(t[t.PhysicalDevice=0]="PhysicalDevice",t[t.Touch=1]="Touch",t))(vQ||{}),Ks=(t=>(t.SelectStart="select-start",t.SelectEnd="select-end",t.Update="update",t))(Ks||{});class Iw extends RA{}const eI=class extends RA{constructor(){super(...arguments),r(this,"webXR"),r(this,"index",-1),r(this,"controllerModel"),r(this,"controller"),r(this,"controllerGrip"),r(this,"hand"),r(this,"handPointerModel"),r(this,"grabbed",null),r(this,"input",null),r(this,"type",0),r(this,"showRaycastLine",!0),r(this,"_wristQuaternion",null),r(this,"movementVector",new f),r(this,"worldRot",new GA),r(this,"joystick",new W),r(this,"didRotate",!1),r(this,"didTeleport",!1),r(this,"didChangeScale",!1),r(this,"lastHit",null),r(this,"raycastLine",null),r(this,"_raycastHitPoint",null),r(this,"_connnectedCallback",null),r(this,"_disconnectedCallback",null),r(this,"_selectStartEvt",null),r(this,"_selectEndEvt",null),r(this,"_selectionPressed",!1),r(this,"_selectionPressedLastFrame",!1),r(this,"_selectionStartTime",0),r(this,"_selectionEndTime",0),r(this,"_useSmoothing",!0),r(this,"_isConnected",!1),r(this,"rayRotation",new GA),r(this,"_pinchStartTime"),r(this,"selectStartCallback",null),r(this,"lastSelectStartObject",null),r(this,"_didNotEndSelection",!1),r(this,"closeGrabBoundingBoxHelper")}static CreateRaycastLine(){const t=new Ag(this.geometry),A=t.material;return A.color=this.raycastColor,t.layers.set(2),t.name="line",t.scale.z=1,t}static CreateRaycastHitPoint(){const t=new Qo(.5,22,22),A=new lt({color:this.raycastColor}),e=new yA(t,A);return e.visible=!1,e.layers.set(2),e}static Create(t,A,e,g){const I=e?eA.addNewComponent(e,eI,!1):new eI;I.webXR=t,I.index=A,I.type=g;const i=t.context;I.controller=i.renderer.xr.getController(A),I.controllerGrip=i.renderer.xr.getControllerGrip(A),I.controllerModel=this.Factory.createControllerModel(I.controller),I.controllerGrip.add(I.controllerModel),I.hand=i.renderer.xr.getHand(A);const o=new IQ;Cc(o,i),I.webXR.handModelPath&&I.webXR.handModelPath!==""?o.setPath(Ia(t.sourceId,I.webXR.handModelPath)):o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/");const C=new l6(I.hand,o);return I.hand.add(C),I.hand.traverse(s=>s.layers.set(2)),I.handPointerModel=new S6(I.hand,I.controller),I.controller.addEventListener("connected",s=>{I.setControllerLayers(I.controllerModel,2),I.setControllerLayers(I.controllerGrip,2),I.setControllerLayers(I.hand,2),setTimeout(()=>{I.setControllerLayers(I.controllerModel,2),I.setControllerLayers(I.controllerGrip,2),I.setControllerLayers(I.hand,2)},1e3)}),I.hand.addEventListener("connected",s=>{var a;if(s.data.hand){t.Rig&&t.Rig.add(I.hand),I.type=0,I.handPointerModel.traverse(B=>B.layers.set(2)),(a=I.handPointerModel.pointerObject)==null||a.traverse(B=>B.layers.set(2));const n=I.hand.joints;if(n)for(const B of Object.keys(n)){const Q=n[B];Q.parent||I.hand.add(Q)}}}),I}static addEventListener(t,A){const e=this.eventSubs[t]??[];e.push(A),this.eventSubs[t]=e}static removeEventListener(t,A){if(!A)return;const e=this.eventSubs[t]??[],g=e.indexOf(A);g>=0&&e.splice(g,1),this.eventSubs[t]=e}get isUsingHands(){var t;return((t=this.input)==null?void 0:t.hand)!=null}get wrist(){if(!this.hand)return null;const t=this.hand.joints;return t?t.wrist:null}getWristQuaternion(){const t=this.wrist;return t?(this._wristQuaternion||(this._wristQuaternion=new GA),Ng(t).multiply(this._wristQuaternion.setFromEuler(new fg(-Math.PI/4,0,0)))):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}get useSmoothing(){return this._useSmoothing}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(){var t,A,e;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)),(t=this.hand)==null||t.clear(),(A=this.controllerGrip)==null||A.clear(),(e=this.controller)==null||e.clear()}onEnable(){var t,A,e,g,I;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=eI.CreateRaycastLine()),this._raycastHitPoint||(this._raycastHitPoint=eI.CreateRaycastHitPoint()),(t=this.webXR.Rig)==null||t.add(this.hand),(A=this.webXR.Rig)==null||A.add(this.controllerGrip),(e=this.webXR.Rig)==null||e.add(this.controller),(g=this.webXR.Rig)==null||g.add(this.raycastLine),(I=this.raycastLine)==null||I.add(this._raycastHitPoint),this._raycastHitPoint.visible=!1,this.hand.add(this.handPointerModel),Lc&&console.log("ADDED TO RIG",this.webXR.Rig)}onDisable(){var t,A,e,g,I;(t=this.hand)==null||t.removeFromParent(),(A=this.controllerGrip)==null||A.removeFromParent(),(e=this.controller)==null||e.removeFromParent(),(g=this.raycastLine)==null||g.removeFromParent(),(I=this._raycastHitPoint)==null||I.removeFromParent();const i=this.webXR.Controllers.indexOf(this);i>=0&&this.webXR.Controllers.splice(i,1)}onSourceConnected(t){if(this._isConnected){console.warn("Received connected event for controller that is already connected",this.index,t);return}this._isConnected=!0,this.input=t.data,this.type===1&&(this.onSelectStart(),this.createPointerEvent("down"))}onSourceDisconnected(t){if(!this._isConnected){console.warn("Received discnnected event for controller that is not connected",t);return}this._isConnected=!1,this.type===1&&(this.onSelectEnd(),this.createPointerEvent("up")),this.input=null}createPointerEvent(t){switch(t){case"down":this.context.input.createPointerDown({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break;case"move":break;case"up":this.context.input.createPointerUp({clientX:0,clientY:0,button:this.index,pointerType:"touch"});break}}update(){this.context.time.frameCount%60===0&&(this.setControllerLayers(this.controller,2),this.setControllerLayers(this.controllerGrip,2),this.setControllerLayers(this.hand,2));const t=eI.eventSubs.update;if(t&&t.length>0)for(const g of t)g(this);let A=1;this.type===0?A=this.context.time.deltaTime/.1:this.isUsingHands&&this.handPointerModel.pinched&&(A=this.context.time.deltaTime/.3),this.rayRotation.slerp(Ng(this.controller),this.useSmoothing?A:1);const e=ye(this.controller);if(this.isUsingHands&&this.handPointerModel.cursorObject&&(this.handPointerModel.cursorObject.visible=!1),this.raycastLine){const g=this.showRaycastLine&&this.type!==1;if(this.type===1)this.raycastLine.visible=!1;else if(this.isUsingHands){this.raycastLine.visible=!this.grabbed&&g,tg(this.raycastLine,e);const I=this.hand.joints;if(I&&I.wrist&&this.grabbed&&this.grabbed.isCloseGrab){const i=this.getWristQuaternion();i&&this.rayRotation.copy(i)}zI(this.raycastLine,this.rayRotation)}else this.raycastLine.visible=g,zI(this.raycastLine,this.rayRotation),tg(this.raycastLine,e)}this.lastHit=this.updateLastHit(),this.grabbed&&this.grabbed.update(),this._selectionPressedLastFrame=this._selectionPressed,this.selectStartCallback&&this.selectStartCallback()}onUpdate(t){var A,e;if(this.lastHit=null,!t||t.inputSources.length<=this.index){this.input=null;return}if(this.type===0&&(this.input=t.inputSources[this.index]),!this.input)return;const g=this.webXR.Rig;if(!g)return;this._didNotEndSelection&&!this.handPointerModel.pinched&&(this._didNotEndSelection=!1,this.onSelectEnd()),this.updateStick(this.input);const I=(e=(A=this.input)==null?void 0:A.gamepad)==null?void 0:e.buttons;switch(this.input.handedness){case"left":const i=3*eI.MovementSpeedFactor,o=2,C=XA.clamp01(this.joystick.length()*2),s=this.joystick.x>0?1:-1;let a=Math.pow(this.joystick.x,o);a*=s,a*=C;const n=this.joystick.y>0?1:-1;let B=Math.pow(this.joystick.y,o);B*=n,a*=C,g.getWorldQuaternion(this.worldRot),this.movementVector.set(a,0,B),this.movementVector.applyQuaternion(this.webXR.TransformOrientation),this.movementVector.y=0,this.movementVector.applyQuaternion(this.worldRot),this.movementVector.multiplyScalar(i*this.context.time.deltaTime),g.position.add(this.movementVector),this.isUsingHands&&this.runTeleport(g,I);break;case"right":const Q=this.joystick.x,E=Math.abs(Q);if(E<.4)this.didRotate=!1;else if(E>.5&&!this.didRotate){const h=Q>0?-1:1;g.rotateY(XA.toRadians(30*h)),this.didRotate=!0}this.runTeleport(g,I);break}}runTeleport(t,A){var e,g,I;let i=-this.joystick.y;if((e=this.hand)!=null&&e.visible&&!this.grabbed){const 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 o=i>.5&&this.webXR.IsInVR,C=this.webXR.Rig?((I=(g=this.webXR.Rig)==null?void 0:g.scale)==null?void 0:I.x)<.999:!1,s=null;if(A&&this.input&&!this.input.hand)for(let a=0;a<A.length;a++){const n=A[a];if(a===4)if(n.pressed&&!this.didChangeScale&&this.webXR.IsInVR){this.didChangeScale=!0;const B=this.webXR.Rig;if(B)if(C){C=!1,B.scale.set(1,1,1),s=1,eI.MovementSpeedFactor=1;const Q=this.context.mainCamera;eI.PreviousCameraFarDistance&&(Q.far=eI.PreviousCameraFarDistance)}else{C=!0,o=!0,s=.1,eI.MovementSpeedFactor=s*2;const Q=this.context.mainCamera;eI.PreviousCameraFarDistance=Q.far,Q.far/=s}}else n.pressed||(this.didChangeScale=!1)}if(o){if(!this.didTeleport){const a=this.raycast();if(this.didTeleport=!0,a&&a.length>0){const n=a[0];if(C||this.isValidTeleportTarget(n.object)){const B=n.point;tg(t,B)}}}}else i<.1&&(this.didTeleport=!1);s!==null&&(t.scale.set(s,s,s),t.updateMatrixWorld())}isValidTeleportTarget(t){return eA.getComponentInParent(t,Iw)!=null}updateStick(t){var A;!t||!t.gamepad||((A=t.gamepad.axes)==null?void 0:A.length)<4||(this.joystick.x=t.gamepad.axes[2],this.joystick.y=t.gamepad.axes[3])}updateLastHit(){var t;const A=this.raycast(),e=A?A[0]:null;this.lastHit=e;let g=1;if(this.webXR.Rig&&(g/=this.webXR.Rig.scale.x),this.raycastLine){this.raycastLine.scale.z=g*(((t=this.lastHit)==null?void 0:t.distance)??9999);const I=this.raycastLine.material;e!=null?I.color=eI.raycastColor:I.color=eI.raycastNoHitColor}if(this._raycastHitPoint){if(this.lastHit!=null){this._raycastHitPoint.position.z=-1;const I=XA.clamp(this.lastHit.distance*.01*g,.015,.1);this._raycastHitPoint.scale.set(I,I,I)}this._raycastHitPoint.visible=this.lastHit!==null&&this.lastHit!==void 0}return e}onSelectStart(){this.context.connection.allowEditing&&(this.selectStartCallback=()=>this.onHandleSelectStart())}onHandleSelectStart(){this.selectStartCallback=null,this._selectionPressed=!0,this._selectionStartTime=this.context.time.time,this._selectionEndTime=1e3;let t=null,A=!1;if(this.isUsingHands?(t=this.overlap(),t.length<=0?(t=this.raycast(),A=!1):A=!0):t=this.raycast(),Lc&&console.log("onHandleSelectStart","close grab? "+A,"intersections",t),t&&t.length>0)for(const e of t){const g=e.object;this.lastSelectStartObject=g;const I={selected:g,grab:g},i=eI.eventSubs["select-start"];if(i&&i.length>0)for(const o of i)o(this,I);I.grab!==g&&Lc&&console.log("Grabbed object changed","original",g,"new",I.grab),I.grab&&(this.grabbed=pC.TryTake(this,I.grab,e,A));break}else{const e=eI.eventSubs["select-start"],g={selected:null,grab:null};if(e&&e.length>0)for(const I of e)I(this,g)}}onSelectEnd(){var t;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;const A={grab:((t=this.grabbed)==null?void 0:t.selected)??this.lastSelectStartObject},e=eI.eventSubs["select-end"];if(e&&e.length>0)for(const g of e)g(this,A);this.grabbed&&(this.grabbed.free(),this.grabbed=null)}testIsVisible(t){return!(!t||eA.isActiveInHierarchy(t)===!1||bQ.isInteractable(t)===!1)}setControllerLayers(t,A){var e,g;if(t&&(t.layers.set(A),t.children))for(const I of t.children)((e=this.grabbed)==null?void 0:e.selected)===I||((g=this.grabbed)==null?void 0:g.selectedMesh)===I||this.setControllerLayers(I,A)}getRay(){const t=new As;return t.origin.copy(ye(this.controller)),t.direction.set(0,0,-1).applyQuaternion(this.rayRotation),t}overlap(){const t=this.isUsingHands&&this.handPointerModel?this.handPointerModel.pointerObject:this.controllerGrip;if(Lc&&(!this.closeGrabBoundingBoxHelper&&t&&(this.closeGrabBoundingBoxHelper=new Xp(t,16776960),this.scene.add(this.closeGrabBoundingBoxHelper)),this.closeGrabBoundingBoxHelper&&t&&this.closeGrabBoundingBoxHelper.setFromObject(t)),!t)return new Array;const A=ye(t).clone();return this.context.physics.sphereOverlap(A,.02)}raycast(){const t=new Go;t.layerMask=new xi,t.layerMask.enableAll(),t.layerMask.disable(2),t.ray=this.getRay();const A=this.context.physics.raycast(t);for(let e=0;e<A.length;e++){const g=A[e],I=g.object;if(!this.testIsVisible(I)){A.splice(e,1),e--;continue}g.object=bQ.getObject(I);break}return A}};let dg=eI;r(dg,"Factory",new q6),r(dg,"raycastColor",new fA(.9,.3,.3)),r(dg,"raycastNoHitColor",new fA(.6,.6,.6)),r(dg,"geometry",new pe().setFromPoints([new f(0,0,0),new f(0,0,-1)])),r(dg,"handModels",{}),r(dg,"eventSubs",{}),r(dg,"PreviousCameraFarDistance"),r(dg,"MovementSpeedFactor",1);var iw=(t=>(t.WillTake="WillTake",t.DidTake="DidTake",t.WillFree="WillFree",t.DidFree="DidFree",t))(iw||{});const oi=class{constructor(){r(this,"sync",null),r(this,"selected",null),r(this,"selectedParent",null),r(this,"selectedMesh",null),r(this,"controller",null),r(this,"grabTime",0),r(this,"grabUUID",""),r(this,"isCloseGrab",!1),r(this,"originalMaterial",null),r(this,"usageMarker",null),r(this,"rigidbodies",null),r(this,"didReparent",!1),r(this,"grabDistance",0),r(this,"interactable",null),r(this,"positionSource",null),r(this,"grabPoint",new f),r(this,"localPositionOffsetToGrab",null),r(this,"localPositionOffsetToGrab_worldSpace",new f),r(this,"localQuaternionToGrab",new GA(0,0,0,1)),r(this,"targetDir",null),r(this,"quaternionLerp",null),r(this,"controllerDir",new f),r(this,"controllerWorldPos",new f),r(this,"lastControllerWorldPos",new f),r(this,"controllerPosDelta",new f),r(this,"totalChangeAlongDirection",0),r(this,"rigPositionLastFrame",new f)}static AddEventListener(t,A){return oi.Events[t]||(oi.Events[t]=[]),oi.Events[t].push(A),A}static RemoveEventListener(t,A){if(!A||!oi.Events[t])return;const e=oi.Events[t].indexOf(A);e>=0&&oi.Events[t].splice(e,1)}static Register(t){this.Current.find(A=>A===t)||this.Current.push(t)}static Remove(t){const A=this.Current.indexOf(t);A>=0&&this.Current.splice(A,1)}static TryTake(t,A,e,g){const I=eA.getComponentInParent(A,MQ);if(I)A=I.gameObject;else return Lc&&console.warn("Prevented taking object that is not interactable",A),null;let i=A;const o=eA.getComponentInParent(A,tn);o&&(o.requestOwnership(),i=o.gameObject);for(const s of this.Current)if(s.selected===i)return s.controller===t||(s.free(),s.Take(t,i,A,o,I,e,g)),s;const C=new oi;return C.Take(t,i,A,o,I,e,g),C}Take(t,A,e,g,I,i,o){var C,s;if(console.assert(A!==null,"Expected object to be taken but was",A),t.isUsingHands?this.positionSource=o?t.wrist:t.controller:this.positionSource=t.controller,!this.positionSource)return console.warn("No position source"),this;const a={controller:t,take:A,hit:e,sync:g,interactable:I};(C=oi.Events.WillTake)==null||C.forEach(h=>h(this,a));const n=e;n!=null&&n.material&&(this.originalMaterial=n.material,Array.isArray(n.material)||(n.material=n.material.clone(),n.material&&n.material.emissive&&(n.material.emissive.b=.2))),this.selected=A,this.selectedParent||(this.selectedParent=A.parent),this.selectedMesh=n,this.controller=t,this.interactable=I,this.isCloseGrab=o,this.didReparent=!1,this.sync=g,this.grabTime=t.context.time.time,this.grabUUID=Date.now().toString(),this.usageMarker=eA.addNewComponent(this.selected,RQ),this.rigidbodies=eA.getComponentsInChildren(this.selected,Ht),ye(this.positionSource,this.lastControllerWorldPos);const B=()=>o?this.lastControllerWorldPos.clone():i.point.clone();this.grabDistance=B().distanceTo(this.lastControllerWorldPos),this.totalChangeAlongDirection=0,this.localPositionOffsetToGrab=this.selected.worldToLocal(B());const Q=t.isUsingHands&&o?this.controller.getWristQuaternion().clone():t.rayRotation.clone();Ng(this.selected,this.localQuaternionToGrab).premultiply(Q.invert());const E=this.controller.webXR.Rig;return E&&this.rigPositionLastFrame.copy(ye(E)),YI.Add(t.context,this.selected),oi.Register(this),this.sync&&(this.sync.fastMode=!0),(s=oi.Events.DidTake)==null||s.forEach(h=>h(this,a)),this}free(){var t,A,e,g;if(!this.selected)return;const I={controller:this.controller,take:this.selected,hit:this.selected,sync:this.sync,interactable:null};(t=oi.Events.WillFree)==null||t.forEach(C=>C(this,I)),YI.Remove(this.controller.context,this.selected),oi.Remove(this),this.sync&&(this.sync.fastMode=!1);const i=this.selectedMesh;i&&this.originalMaterial&&i.material&&(i.material=this.originalMaterial);const o=this.selected;if(this.didReparent&&o.parent){const C=this.selectedParent;C?C.attach(o):(A=this.controller)==null||A.context.scene.attach(o)}if((e=this.usageMarker)==null||e.destroy(),this.controller&&(this.controller.grabbed=null),this.selected=null,this.selectedParent=null,this.selectedMesh=null,this.sync=null,this.rigidbodies)for(const C of this.rigidbodies)C.wakeUp(),C.setVelocity(C.smoothedVelocity);this.rigidbodies=null,this.localPositionOffsetToGrab=null,this.quaternionLerp=null,(g=oi.Events.DidFree)==null||g.forEach(C=>C(this,I))}controllerMovementSinceLastFrame(){if(!this.positionSource||!this.controller)return 0;this.controllerDir.set(0,0,-1),this.controllerDir.applyQuaternion(this.controller.rayRotation),ye(this.positionSource,this.controllerWorldPos),this.controllerPosDelta.copy(this.controllerWorldPos),this.controllerPosDelta.sub(this.lastControllerWorldPos),this.lastControllerWorldPos.copy(this.controllerWorldPos);const t=this.controller.webXR.Rig;if(t){const A=ye(t),e=this.rigPositionLastFrame.sub(A);this.controllerPosDelta.add(e),this.rigPositionLastFrame.copy(A)}return this.controllerDir.dot(this.controllerPosDelta)}update(){var t;if(this.rigidbodies)for(const A of this.rigidbodies)A.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){const A=((t=this.controller.webXR.Rig)==null?void 0:t.scale.x)??1;this.totalChangeAlongDirection+=this.controllerMovementSinceLastFrame();let e=1;this.controller.type===0&&(e=Math.max(0,1+this.totalChangeAlongDirection*2/A),e=e*e*e),this.grabDistance/A<.8&&(e=1),this.targetDir||(this.targetDir=new f),this.targetDir.set(0,0,-this.grabDistance*e);const g=this.targetDir.applyQuaternion(this.controller.rayRotation).add(this.controllerWorldPos),I=this.controller.rayRotation.clone().multiplyQuaternions(this.controller.rayRotation,this.localQuaternionToGrab);this.quaternionLerp||(this.quaternionLerp=I.clone()),this.quaternionLerp.slerp(I,this.controller.useSmoothing?this.controller.context.time.deltaTime/.03:1),zI(this.selected,this.quaternionLerp),this.selected.updateWorldMatrix(!1,!1),this.grabPoint.copy(g),this.localPositionOffsetToGrab&&(this.localPositionOffsetToGrab_worldSpace.copy(this.localPositionOffsetToGrab),this.selected.localToWorld(this.localPositionOffsetToGrab_worldSpace).sub(ye(this.selected)),g.sub(this.localPositionOffsetToGrab_worldSpace)),tg(this.selected,g)}if(this.rigidbodies!=null)for(const A of this.rigidbodies)A.wakeUp();Ei.markDirty(this.selected,!0)}}};let pC=oi;r(pC,"Events",{}),r(pC,"Current",[]);var OeA=Object.defineProperty,PeA=Object.getOwnPropertyDescriptor,Wm=(t,A,e,g)=>{for(var I=g>1?void 0:g?PeA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&OeA(A,e,I),I};class kr extends RA{constructor(){super(...arguments),r(this,"objectBounds",!1),r(this,"color"),r(this,"isGizmo",!0),r(this,"_gizmoObject",null),r(this,"_boxHelper",null)}onEnable(){this.isGizmo&&!Mh||(this._gizmoObject||(this.objectBounds&&this.gameObject.isMesh===!0?this._gizmoObject=new Xp(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=Cx(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),ki.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(var A;this._boxHelper;)(A=this._boxHelper)==null||A.update(),yield}}Wm([w()],kr.prototype,"objectBounds",2),Wm([w(fA)],kr.prototype,"color",2),Wm([w()],kr.prototype,"isGizmo",2);const jeA=aA("debugrig");class ow extends RA{awake(){if(jeA){const A=new UA;A.position.y+=.5,this.gameObject.add(A);const e=A.addNewComponent(kr);e&&(e.isGizmo=!1)}}}class LQ{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,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(A,e,g,I,i){return A.prep(4,16),A.writeFloat32(i),A.writeFloat32(I),A.writeFloat32(g),A.writeFloat32(e),A.offset()}}class yI{constructor(){r(this,"bb",null),r(this,"bb_pos",0)}__init(A,e){return this.bb_pos=A,this.bb=e,this}static getRootAsVrUserStateBuffer(A,e){return(e||new yI).__init(A.readInt32(A.position())+A.position(),A)}static getSizePrefixedRootAsVrUserStateBuffer(A,e){return A.setPosition(A.position()+lu),(e||new yI).__init(A.readInt32(A.position())+A.position(),A)}guid(A){const e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,A):null}time(){const A=this.bb.__offset(this.bb_pos,6);return A?this.bb.readInt64(this.bb_pos+A):this.bb.createLong(0,0)}avatarId(A){const e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,A):null}position(A){const e=this.bb.__offset(this.bb_pos,10);return e?(A||new Gi).__init(this.bb_pos+e,this.bb):null}rotation(A){const e=this.bb.__offset(this.bb_pos,12);return e?(A||new LQ).__init(this.bb_pos+e,this.bb):null}scale(){const A=this.bb.__offset(this.bb_pos,14);return A?this.bb.readFloat32(this.bb_pos+A):0}posLeftHand(A){const e=this.bb.__offset(this.bb_pos,16);return e?(A||new Gi).__init(this.bb_pos+e,this.bb):null}posRightHand(A){const e=this.bb.__offset(this.bb_pos,18);return e?(A||new Gi).__init(this.bb_pos+e,this.bb):null}rotLeftHand(A){const e=this.bb.__offset(this.bb_pos,20);return e?(A||new LQ).__init(this.bb_pos+e,this.bb):null}rotRightHand(A){const e=this.bb.__offset(this.bb_pos,22);return e?(A||new LQ).__init(this.bb_pos+e,this.bb):null}static startVrUserStateBuffer(A){A.startObject(10)}static addGuid(A,e){A.addFieldOffset(0,e,0)}static addTime(A,e){A.addFieldInt64(1,e,A.createLong(0,0))}static addAvatarId(A,e){A.addFieldOffset(2,e,0)}static addPosition(A,e){A.addFieldStruct(3,e,0)}static addRotation(A,e){A.addFieldStruct(4,e,0)}static addScale(A,e){A.addFieldFloat32(5,e,0)}static addPosLeftHand(A,e){A.addFieldStruct(6,e,0)}static addPosRightHand(A,e){A.addFieldStruct(7,e,0)}static addRotLeftHand(A,e){A.addFieldStruct(8,e,0)}static addRotRightHand(A,e){A.addFieldStruct(9,e,0)}static endVrUserStateBuffer(A){return A.endObject()}static finishVrUserStateBufferBuffer(A,e){A.finish(e)}static finishSizePrefixedVrUserStateBufferBuffer(A,e){A.finish(e,void 0,!0)}}const MH=aA("debugxr"),xc=aA("debugavatar"),Vm="VRUS";Xf(Vm,yI.getRootAsVrUserStateBuffer);function zm(){return new Date().getTime()}function WeA(t){let A=t&4294967295,e=t/Math.pow(2,32)&1048575;return xC.create(A,e)}const Cw=class{constructor(t){r(this,"guid"),r(this,"time"),r(this,"avatarId"),r(this,"position",new f),r(this,"rotation",new Ie),r(this,"scale",1),r(this,"posLeftHand",new f),r(this,"posRightHand",new f),r(this,"rotLeftHand",new GA),r(this,"rotRightHand",new GA),this.guid=t}update(t,A,e,g,I){var i,o,C,s,a,n;this.time=zm(),this.avatarId=I,this.position.set(A.x,A.y,A.z),t&&this.position.applyMatrix4(t.matrixWorld);let B=Cw.quat0;const Q=Cw.quat1;B.set(e.x,e.y,e.z,e.w),B=B.multiplyQuaternions(B,Cw.invertRotation),t&&(t.getWorldQuaternion(Q),B.multiplyQuaternions(Q,B)),this.rotation.set(B.x,B.y,B.z,B.w),this.scale=t.scale.x;const E=(i=g.LeftController)==null?void 0:i.controllerGrip;E&&(E.getWorldPosition(this.posLeftHand),E.getWorldQuaternion(this.rotLeftHand));const h=(o=g.RightController)==null?void 0:o.controllerGrip;if(h&&(h.getWorldPosition(this.posRightHand),h.getWorldQuaternion(this.rotRightHand)),(s=(C=g.LeftController)==null?void 0:C.hand)!=null&&s.visible){const c=g.LeftController.wrist;c&&(c.getWorldPosition(this.posLeftHand),c.getWorldQuaternion(this.rotLeftHand))}if((n=(a=g.RightController)==null?void 0:a.hand)!=null&&n.visible){const c=g.RightController.wrist;c&&(c.getWorldPosition(this.posRightHand),c.getWorldQuaternion(this.rotRightHand))}}sendAsBuffer(t,A){t.clear();const e=t.createString(this.guid),g=t.createString(this.avatarId);yI.startVrUserStateBuffer(t),yI.addGuid(t,e),yI.addTime(t,WeA(this.time)),yI.addAvatarId(t,g),yI.addPosition(t,Gi.createVec3(t,this.position.x,this.position.y,this.position.z)),yI.addRotation(t,LQ.createVec4(t,this.rotation.x,this.rotation.y,this.rotation.z,this.rotation.w)),yI.addScale(t,this.scale),yI.addPosLeftHand(t,Gi.createVec3(t,this.posLeftHand.x,this.posLeftHand.y,this.posLeftHand.z)),yI.addPosRightHand(t,Gi.createVec3(t,this.posRightHand.x,this.posRightHand.y,this.posRightHand.z)),yI.addRotLeftHand(t,LQ.createVec4(t,this.rotLeftHand.x,this.rotLeftHand.y,this.rotLeftHand.z,this.rotLeftHand.w)),yI.addRotRightHand(t,LQ.createVec4(t,this.rotRightHand.x,this.rotRightHand.y,this.rotRightHand.z,this.rotRightHand.w));const I=yI.endVrUserStateBuffer(t);t.finish(I,Vm);const i=t.asUint8Array();A.sendBinary(i)}setFromBuffer(t,A){if(!t)return;this.guid=t,this.time=A.time().toFloat64();const e=A.avatarId();e&&(this.avatarId=e);const g=A.position();g&&this.position.set(g.x(),g.y(),g.z());const I=A.rotation();I&&this.rotation.set(I.x(),I.y(),I.z(),I.w());const i=A.posLeftHand();i&&this.posLeftHand.set(i.x(),i.y(),i.z());const o=A.posRightHand();o&&this.posRightHand.set(o.x(),o.y(),o.z());const C=A.rotLeftHand();C&&this.rotLeftHand.set(C.x(),C.y(),C.z(),C.w());const s=A.rotRightHand();s&&this.rotRightHand.set(s.x(),s.y(),s.z(),s.w()),this.scale=A.scale()}};let Js=Cw;r(Js,"invertRotation",new GA().setFromAxisAngle(new f(0,1,0),Math.PI)),r(Js,"quat0",new GA),r(Js,"quat1",new GA);class Yc extends RA{constructor(){super(...arguments),r(this,"webXR",null),r(this,"debugAvatarUser",null),r(this,"voip",null),r(this,"tempState",new Js("")),r(this,"_removeAvatarsList",[]),r(this,"eventSub_ConnectionEvent",null),r(this,"eventSub_WebXRStartEvent",null),r(this,"eventSub_WebXREndEvent",null),r(this,"eventSub_WebXRUpdateEvent",null),r(this,"avatars",{}),r(this,"localAvatar",null),r(this,"k_LocalAvatarNoNetworkingGuid","local"),r(this,"ownership",null),r(this,"xrState",null),r(this,"builder",new FE(1024))}async awake(){if(this.webXR||(this.webXR=eA.getComponent(this.gameObject,Se)),this.webXR||(this.webXR=eA.findObjectOfType(Se,this.context)),!this.webXR&&(console.log("Missing webxr component"),this.webXR=eA.findObjectOfType(Se,this.context),!this.webXR)){console.error("Could not find webxr component");return}if(this.voip||(this.voip=eA.findObjectOfType(Xs,this.context)),xc){const A="debug-avatar-"+xc,e=new An(this.context,A,this.webXR);if(this.debugAvatarUser=e,typeof xc=="string"&&xc.length>0)if(await e.setAvatarOverride(xc)){const g=new Js(A);g.position.y+=1;const I=.5;g.posLeftHand.y+=I,g.posLeftHand.x+=I,g.posRightHand.y+=I,g.posRightHand.x-=I,e.tryUpdate(g,0)}else e.destroy()}}onEnable(){if(!this.webXR&&(this.webXR=eA.getComponent(this.gameObject,Se),!this.webXR)){console.warn("Missing webxr component on "+this.gameObject.name);return}this.eventSub_WebXRStartEvent=this.onXRSessionStart.bind(this),Se.addEventListener(kt.XRStarted,this.eventSub_WebXRStartEvent),this.eventSub_WebXRUpdateEvent=this.onXRSessionUpdate.bind(this),Se.addEventListener(kt.XRUpdate,this.eventSub_WebXRUpdateEvent),this.eventSub_WebXREndEvent=this.onXRSessionEnded.bind(this),Se.addEventListener(kt.XRStopped,this.eventSub_WebXREndEvent),this.eventSub_ConnectionEvent=this.onConnected.bind(this),this.context.connection.beginListen(Pt.JoinedRoom,this.eventSub_ConnectionEvent),this.context.connection.beginListen("webxr-user-joined",A=>{console.log("webxr user joined evt")}),this.context.connection.beginListen("webxr-user-left",A=>{const e=A.id!==null&&A.id!==void 0;if(e&&(console.log("webxr user left evt"),e)){const g=this.avatars[A.id];g?.destroy(),this.avatars[A.id]=void 0}}),this.context.connection.beginListenBinary(Vm,A=>{const e=A.guid();if(!e)return;const g=A.time().toFloat64(),I=this.tempState;I.setFromBuffer(e,A);const i=this.onTryGetAvatar(e,g);i?.tryUpdate(I,g)}),this.context.connection.beginListen("vr-session-update",A=>{const e=A.guid,g=A.time,I=this.onTryGetAvatar(e,g);I?.tryUpdate(A,g)})}onTryGetAvatar(A,e){if(A===this.context.connection.connectionId)return null;const g=new Date().getTime()-e;if(g>5e3)return MH&&console.log("old data",g,A),null;let I=this.avatars[A];if(I===void 0)try{console.log("create new avatar");const i=new An(this.context,A,this.webXR);I=i,this.avatars[A]=i}catch(i){this.avatars[A]=null,console.error(i)}return I}onDisable(){this.eventSub_ConnectionEvent&&this.context.connection.stopListen(Pt.JoinedRoom,this.eventSub_ConnectionEvent),Se.removeEventListener(kt.XRStarted,this.eventSub_WebXRStartEvent),Se.removeEventListener(kt.XRUpdate,this.eventSub_WebXRUpdateEvent),Se.removeEventListener(kt.XRStopped,this.eventSub_WebXREndEvent)}update(){const A=zm();this.debugAvatarUser&&(this.debugAvatarUser.lastUpdate=A),this.detectPotentiallyDisconnectedAvatarsAndRemove();for(const e in this.avatars){const g=this.avatars[e];g&&g.update()}}detectPotentiallyDisconnectedAvatarsAndRemove(){const A=zm();for(const e in this.avatars){const g=this.avatars[e];if(!g){this._removeAvatarsList.push(e);continue}A-g.lastUpdate>1e4&&(console.log("avatar timed out (didnt receive any updates in a while) - destroying it now"),g.destroy(),this.avatars[e]=void 0)}for(const e of this._removeAvatarsList)delete this.avatars[e];this._removeAvatarsList.length=0}buildLocalAvatar(){var A;if(this.localAvatar)return;const e=((A=this.context.connection)==null?void 0:A.connectionId)??this.k_LocalAvatarNoNetworkingGuid;this.localAvatar=new An(this.context,e,this.webXR),this.localAvatar.isLocalAvatar=!0,this.localAvatar.setAvatarOverride(this.getAvatarId()),this.avatars[this.localAvatar.guid]=this.localAvatar}onConnected(){var A,e,g;MH&&console.log("Hey you are connected as "+this.context.connection.connectionId),((A=this.localAvatar)==null?void 0:A.guid)===this.k_LocalAvatarNoNetworkingGuid&&(this.localAvatar&&((e=this.localAvatar)==null||e.destroy(),this.avatars[this.localAvatar.guid]=void 0),this.localAvatar=null,this.xrState=null,(g=this.ownership)==null||g.freeOwnership(),this.ownership=null)}onXRSessionStart(A){var e,g,I;if(console.log("XR session started"),this.context.connection.send("webxr-user-joined",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((e=this.localAvatar)==null||e.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null),this.xrState=null,(g=this.ownership)==null||g.freeOwnership(),this.ownership=null,this.avatars)for(const i in this.avatars)(I=this.avatars[i])==null||I.updateFlags()}onXRSessionEnded(A){var e;console.log("XR session ended"),this.context.connection.send("webxr-user-left",{id:this.context.connection.connectionId,mode:"vr"}),this.localAvatar&&((e=this.localAvatar)==null||e.destroy(),this.avatars[this.localAvatar.guid]=void 0,this.localAvatar=null)}onXRSessionUpdate(A){this.xrState??(this.xrState=new Js(this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership??(this.ownership=new Ru(this.context.connection,this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid)),this.ownership.guid=this.context.connection.connectionId??this.k_LocalAvatarNoNetworkingGuid,this.buildLocalAvatar();const{frame:e,xr:g,rig:I}=A,i=e.getViewerPose(g.getReferenceSpace());if(!i)return;const o=i?.transform,C=o.position,s=o.orientation;this.xrState.update(I,C,s,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 aA("avatar")??null}}var VeA=Object.defineProperty,zeA=Object.getOwnPropertyDescriptor,xQ=(t,A,e,g)=>{for(var I=g>1?void 0:g?zeA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&VeA(A,e,I),I};async function RH(){return yS()?!0:"xr"in navigator?await navigator.xr.isSessionSupported("immersive-ar")===!0:!1}async function UH(){return"xr"in navigator?await navigator.xr.isSessionSupported("immersive-vr")===!0:!1}let sw=!1,aw=!1;RH().then(t=>sw=t),UH().then(t=>aw=t);var kt=(t=>(t.XRStarted="xrStarted",t.XRStopped="xrStopped",t.XRUpdate="xrUpdate",t.RequestVRSession="requestVRSession",t.ModifyAROptions="modify-ar-options",t))(kt||{}),YQ;const qg=(YQ=class extends RA{constructor(){super(...arguments),r(this,"enableVR",!0),r(this,"enableAR",!0),r(this,"defaultAvatar"),r(this,"handModelPath",""),r(this,"createVRButton",!0),r(this,"createARButton",!0),r(this,"controllers",[]),r(this,"rig"),r(this,"isInit",!1),r(this,"_requestedAR",!1),r(this,"_requestedVR",!1),r(this,"_isInAR",!1),r(this,"_isInVR",!1),r(this,"_arButton"),r(this,"_vrButton"),r(this,"webAR",null),r(this,"_transformOrientation",new GA),r(this,"_currentHeadPose",null),r(this,"_originalCameraParent",null),r(this,"_originalCameraPosition",new f),r(this,"_originalCameraRotation",new GA),r(this,"_originalXRRigParent",null),r(this,"_originalXRRigPosition",new f),r(this,"_originalXRRigRotation",new GA),r(this,"xrMirrorWindow",null)}static get IsInWebXR(){return this._isInXr}static get XRSupported(){return"xr"in navigator&&(sw||aw)}static get IsARSupported(){return sw}static get IsVRSupported(){return aw}static get OptionalFeatures_VR(){return this._optionalFeatures_VR}static get OptionalFeatures_AR(){return this._optionalFeatures_AR}static addEventListener(t,A){return this.events.addEventListener(t,A),A}static removeEventListener(t,A){return this.events.removeEventListener(t,A),A}static dispatchEvent(t,A){this.events.dispatchEvent({type:t,detail:A})}static createVRButton(t,A){qg.XRSupported?t.__internalAwake():console.warn("WebXR is not supported on this device");const e={optionalFeatures:qg.OptionalFeatures_VR},g=tm.createButton(t.context.renderer,e);return g.classList.add("webxr-ar-button"),g.classList.add("webxr-button"),this.resetButtonStyles(g),(A?.registerClick??!0)&&g.addEventListener("click",t.onClickedVRButton.bind(t)),g}static createARButton(t,A){var e;t.__internalAwake();const g=(e=t.webAR)==null?void 0:e.getAROverlayContainer(),I={optionalFeatures:[...this.OptionalFeatures_AR]};g?(I.domOverlay={root:g},I.optionalFeatures.push("dom-overlay"),I.optionalFeatures.push("hit-test")):console.warn("No dom overlay root found, HTML overlays on top of screen-based AR will not work.");const i=o6.createButton(t.context.renderer,I,this.onModifyAROptions.bind(this));return i.classList.add("webxr-ar-button"),i.classList.add("webxr-button"),qg.resetButtonStyles(i),(A?.registerClick??!0)&&i.addEventListener("click",t.onClickedARButton.bind(t)),i}static onModifyAROptions(t){qg.dispatchEvent("modify-ar-options",t)}static resetButtonStyles(t){t&&(t.style.position="",t.style.bottom="",t.style.left="")}endSession(){const t=this.context.renderer.xr.getSession();t&&t.end()}get Rig(){return this.rig||this.ensureRig(),this.rig}get Controllers(){return this.controllers}get LeftController(){var t,A;return this.controllers.length>0&&((t=this.controllers[0].input)==null?void 0:t.handedness)==="left"?this.controllers[0]:this.controllers.length>1&&((A=this.controllers[1].input)==null?void 0:A.handedness)==="left"?this.controllers[1]:null}get RightController(){var t,A;return this.controllers.length>0&&((t=this.controllers[0].input)==null?void 0:t.handedness)==="right"?this.controllers[0]:this.controllers.length>1&&((A=this.controllers[1].input)==null?void 0:A.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}awake(){if(this.defaultAvatar&&typeof this.defaultAvatar=="string"&&(this.defaultAvatar=dI.getOrCreate(this.sourceId??"/",this.defaultAvatar,this.context)),!eA.findObjectOfType(Yc,this.context)){const t=eA.addNewComponent(this.gameObject,Yc,!1);t.webXR=this}this.webAR=new Tc(this)}start(){location.protocol=="http:"&&location.host.indexOf("localhost")<0&&(fo("WebXR only works on https"),console.warn("WebXR only works on https. https://engine.needle.tools/docs/xr.html"))}onEnable(){if(this.isInit||!this.enableAR&&!this.enableVR)return;this.isInit=!0,this.context.renderer.xr.enabled=!0,qg.XRSupported;let t,A;const e=document.createElement("div");e.classList.add("webxr-buttons"),this.context.domElement.append(e),this.enableAR&&this.createARButton&&sw&&(t=qg.createARButton(this),this._arButton=t,e.appendChild(t)),this.createVRButton&&this.enableVR&&aw&&(A=qg.createVRButton(this),this._vrButton=A,e.appendChild(A)),setTimeout(()=>{qg.resetButtonStyles(A),qg.resetButtonStyles(t)},1e3)}get TransformOrientation(){return this._transformOrientation}get HeadPose(){return this._currentHeadPose}onBeforeRender(t){var A;if(!t)return;const e=this.context.renderer.xr.getSession();if(e){const g=t.getViewerPose(this.context.renderer.xr.getReferenceSpace());if(!g)return;this._currentHeadPose=g;const I=g?.transform;I&&this._transformOrientation.set(I.orientation.x,I.orientation.y,I.orientation.z,I.orientation.w),qg._isInXr===!1&&e&&this.onEnterXR(e,t);for(const i of this.controllers)i.onUpdate(e);this._isInAR&&((A=this.webAR)==null||A.onUpdate(e,t))}qg.events.dispatchEvent({type:"xrUpdate",frame:t,xr:this.context.renderer.xr,rig:this.rig})}onClickedARButton(){this._isInAR||(this._requestedAR=!0,this._requestedVR=!1,this.captureStateBeforeXR())}onClickedVRButton(){if(!this._isInVR){if(this._requestedVR){this.onExitXR(null);return}this._requestedAR=!1,this._requestedVR=!0,this.captureStateBeforeXR(),this.ensureRig();for(let t=0;t<2;t++)dg.Create(this,t,this.gameObject,vQ.PhysicalDevice);qg.events.dispatchEvent({type:"requestVRSession"})}}captureStateBeforeXR(){this.context.mainCamera&&(this._originalCameraPosition.copy(ye(this.context.mainCamera)),this._originalCameraRotation.copy(Ng(this.context.mainCamera)),this._originalCameraParent=this.context.mainCamera.parent),this.Rig&&(this._originalXRRigParent=this.Rig.parent,this._originalXRRigPosition.copy(this.Rig.position),this._originalXRRigRotation.copy(this.Rig.quaternion))}ensureRig(){if(!this.rig){const t=eA.findObjectOfType(ow,this.context);t?this.rig=t.gameObject:(this.rig=new Ti,this.rig.rotateY(Math.PI),this.rig.name="XRRig",this.context.scene.add(this.rig))}}onEnterXR(t,A){var e,g;console.log("[XR] session begin",t),qg._isInXr=!0,this.ensureRig();const I=this.context.renderer.xr.getReferenceSpace();if(I&&this.rig){const C=A.getViewerPose(I),s=C?.transform.orientation;if(s){const a=new GA(s.x,s.y,s.z,s.w),n=new fg().setFromQuaternion(a);this.rig.rotateY(n.y)}}const i=this.context.renderer.xr;if(this.context.mainCamera){const C=i.getCamera(this.context.mainCamera),s=(e=this.context.mainCameraComponent)==null?void 0:e.cullingMask;if(s!==void 0){for(const a of C.cameras)a.layers.mask=s;C.layers.mask=s}else{for(const a of C.cameras)a.layers.enableAll();C.layers.enableAll()}this.rig.add(this.context.mainCamera),this._requestedAR&&this.context.scene.add(this.rig)}const o=this._requestedAR?cg.AR:cg.VR;switch(QC.Global.Set(o),o){case cg.AR:this.context.xrSessionMode=gc.ImmersiveAR,this._isInAR=!0,(g=this.webAR)==null||g.onBegin(t);break;case cg.VR:this.context.xrSessionMode=gc.ImmersiveVR,this._isInVR=!0,this.onEnterVR(t);break}t.addEventListener("end",()=>{console.log("[XR] session end"),qg._isInXr=!1,this.onExitXR(t)}),this.onEnterXR_HandleMirrorWindow(t),qg.events.dispatchEvent({type:"xrStarted",session:t})}onExitXR(t){var A,e,g;const I=this._isInAR;this._isInAR&&t&&((A=this.webAR)==null||A.onEnd(t)),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&&((e=this._originalCameraParent)==null||e.add(this.context.mainCamera),tg(this.context.mainCamera,this._originalCameraPosition),zI(this.context.mainCamera,this._originalCameraRotation),this.context.mainCamera.scale.set(1,1,1)),I&&((g=this._originalXRRigParent)==null||g.add(this.rig),this.rig.position.copy(this._originalXRRigPosition),this.rig.quaternion.copy(this._originalXRRigRotation)),QC.Global.Set(cg.Browser|cg.ThirdPerson),qg.events.dispatchEvent({type:"xrStopped",session:t})}onEnterVR(t){}destroyControllers(){var t;for(let A=this.controllers.length-1;A>=0;A-=1)(t=this.controllers[A])==null||t.destroy();this.controllers.length=0}onEnterXR_HandleMirrorWindow(t){aA("mirror")&&setTimeout(()=>{if(!qg.IsInWebXR)return;const A=new URL(window.location.href);TE(A.searchParams,FD,1),TE(A.searchParams,"isMirror",1);const e=A.toString();this.xrMirrorWindow=window.open(e,"webxr sync","popup=yes"),this.xrMirrorWindow&&(this.xrMirrorWindow.onload=()=>{this.xrMirrorWindow&&(this.xrMirrorWindow.onbeforeunload=()=>{qg.IsInWebXR&&t.end()})})},1e3)}},r(YQ,"_isInXr",!1),r(YQ,"events",new mg),r(YQ,"_optionalFeatures_VR",["local-floor","bounded-floor","hand-tracking","high-fixed-foveation-level","layers"]),r(YQ,"_optionalFeatures_AR",["anchors","local-floor","hand-tracking","layers"]),YQ);let Se=qg;xQ([w()],Se.prototype,"enableVR",2),xQ([w()],Se.prototype,"enableAR",2),xQ([w(dI)],Se.prototype,"defaultAvatar",2),xQ([w()],Se.prototype,"handModelPath",2),xQ([w()],Se.prototype,"createVRButton",2),xQ([w()],Se.prototype,"createARButton",2);const Hc=class{constructor(t){r(this,"_webxr"),r(this,"reticle",null),r(this,"reticleParent",null),r(this,"hitTestSource",null),r(this,"reticleActive",!0),r(this,"previousBackground",null),r(this,"previousEnvironment",null),r(this,"sessionRoot",null),r(this,"_previousParent",null),r(this,"arDomOverlay",null),r(this,"arOverlayElement",null),r(this,"noHitTestAvailable",!1),r(this,"didPlaceARSessionRoot",!1),this._webxr=t}get webxr(){return this._webxr}get context(){return this.webxr.context}getAROverlayContainer(){this.arDomOverlay=this.webxr.context.domElement;const t=this.arDomOverlay;return t.getAROverlayContainer?this.arOverlayElement=t.getAROverlayContainer():this.arOverlayElement=this.arDomOverlay,this.arOverlayElement}setReticleActive(t){this.reticleActive=t}async onBegin(t){var A,e,g,I;const i=this.webxr.context;this.reticleActive=!0,this.didPlaceARSessionRoot=!1,this.getAROverlayContainer();const o=(A=navigator.userAgent)!=null&&A.includes("OculusBrowser")?vQ.PhysicalDevice:vQ.Touch,C=o===vQ.Touch?4:2;for(let a=0;a<C;a++)dg.Create(this.webxr,a,this.webxr.gameObject,o);(!this.sessionRoot||this.sessionRoot.destroyed||!this.sessionRoot.activeAndEnabled)&&(this.sessionRoot=eA.findObjectOfType(Xa,i)),this.previousBackground=i.scene.background,this.previousEnvironment=i.scene.environment,i.scene.background=null,t.requestReferenceSpace("viewer").then(a=>{var n,B;(B=(n=t.requestHitTestSource)==null?void 0:n.call(t,{space:a}))==null||B.then(Q=>{this.hitTestSource=Q}).catch(Q=>{this.noHitTestAvailable=!0,console.warn("WebXR: Hit test not supported",Q)})}),!this.reticle&&this.sessionRoot&&(this.reticle=new yA(new UE(.07,.09,32).rotateX(-Math.PI/2),new lt),this.reticle.name="AR Placement reticle",this.reticle.matrixAutoUpdate=!1,this.reticle.visible=!1,this.reticleParent=new UA,this.reticleParent.name="AR Reticle Parent",this.reticleParent.matrixAutoUpdate=!1,this.reticleParent.add(this.reticle),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,Hc.tempWebXRObject||(Hc.tempWebXRObject=new UA),this.context.scene.add(Hc.tempWebXRObject),eA.addComponent(Hc.tempWebXRObject,this.webxr),this.sessionRoot?(this.sessionRoot.webAR=this,(e=this.sessionRoot)==null||e.onBegin(t)):console.warn("No WebARSessionRoot found in scene");const s=this.context.domElement;(g=s?.onEnterAR)==null||g.call(s,t,this.arOverlayElement),(I=this.context.mainCameraComponent)==null||I.applyClearFlagsIfIsActiveCamera()}onEnd(t){var A,e;this._previousParent&&(eA.addComponent(this._previousParent,this.webxr),this._previousParent=null),this.hitTestSource=null;const g=this.webxr.context;g.scene.background=this.previousBackground,g.scene.environment=this.previousEnvironment,this.sessionRoot&&this.sessionRoot.onEnd(this.webxr.Rig,t);const I=this.context.domElement;(A=I.onExitAR)==null||A.call(I,t),(e=this.context.mainCameraComponent)==null||e.applyClearFlagsIfIsActiveCamera()}onUpdate(t,A){var e,g;if(this.noHitTestAvailable===!0){if(this.reticle&&(this.reticle.visible=!1),!this.didPlaceARSessionRoot){this.didPlaceARSessionRoot=!0;const i=this.webxr.Rig,o=ZeA.clone();(e=this.sessionRoot)==null||e.placeAt(i,o)}return}if(!this.hitTestSource)return;const I=A.getHitTestResults(this.hitTestSource);if(I.length){const i=I[0],o=this.webxr.context.renderer.xr.getReferenceSpace();if(o){const C=i.getPose(o);if(this.sessionRoot){const s=this.sessionRoot.onUpdate(this.webxr.Rig,t,C);this.didPlaceARSessionRoot=s}if(this.reticle&&(this.reticle.visible=this.reticleActive,this.reticleActive&&C)){const s=C.transform.matrix;this.reticle.matrix.fromArray(s),this.webxr.Rig&&this.reticle.matrix.premultiply(this.webxr.Rig.matrix)}}}else(g=this.sessionRoot)==null||g.onUpdate(this.webxr.Rig,t,null),this.reticle&&(this.reticle.visible=!1)}};let Tc=Hc;r(Tc,"tempWebXRObject");const ZeA=new TA().identity().makeTranslation(0,0,0);class Gr{constructor(A,e){r(this,"used",!1),r(this,"inputSource"),r(this,"object"),r(this,"pointerId"),r(this,"isDown"),r(this,"isUp"),r(this,"isPressed"),r(this,"isClicked"),r(this,"input"),r(this,"event"),this.event=e,this.input=A}use(){this.used=!0,this.pointerId!==void 0&&this.input.setPointerUsed(this.pointerId)}stopPropagation(){var A;(A=this.event)==null||A.stopImmediatePropagation()}Use(){this.use()}StopPropagation(){var A;(A=this.event)==null||A.stopImmediatePropagation()}}class HQ extends RA{awake(){io.createIfNoneExists(this.context)}onEnable(){var A;(A=io.get(this.context))==null||A.register(this)}onDisable(){var A;(A=io.get(this.context))==null||A.unregister(this)}performRaycast(A=null){return null}}class mr extends HQ{constructor(){super(...arguments),r(this,"targets",null),r(this,"raycastHits",[])}start(){this.targets=[this.gameObject]}performRaycast(A=null){return this.targets?(A??(A=new Go),A.targets=this.targets,A.results=this.raycastHits,this.context.physics.raycast(A)):null}}class Zm extends mr{}const _c=aA("debugeventsystem");var Xm=(t=>(t.BeforeHandleInput="BeforeHandleInput",t.AfterHandleInput="AfterHandleInput",t))(Xm||{});const qs=class extends RA{constructor(){super(),r(this,"raycaster",[]),r(this,"_selectStartFn"),r(this,"_selectEndFn"),r(this,"_selectUpdateFn"),r(this,"_handleEventFn"),r(this,"lastPointerEvent",null),r(this,"objectsHoveredThisFrame",[]),r(this,"objectsHoveredLastFrame",[]),r(this,"raisedPointerDownEvents",[]),r(this,"raisedPointerDownObjects",[]),r(this,"_didMove",!1),r(this,"_tempComponentsArray",[]),r(this,"_sortedHits",[]),r(this,"_sortingBuffer",[]),r(this,"_noDepthTestingResults",[]),r(this,"handleEventsArray",[]),r(this,"out",{}),r(this,"currentActiveMeshUIComponents",[]),qs.systems.push(this)}static createIfNoneExists(t){this.didSearchEventSystem||(this.didSearchEventSystem=!0,qs.systems.length<=0&&qs.systems.push(...eA.findObjectsOfType(qs,t)));for(const e of qs.systems)if(e.context===t)return;const A=new UA;eA.addNewComponent(A,qs),t.scene.add(A)}static get systems(){const t=we.Current;return this._eventSystemMap.has(t)||this._eventSystemMap.set(t,[]),this._eventSystemMap.get(t)}static get(t){const A=this._eventSystemMap.get(t);return A&&A.length>0?A[0]:null}static get instance(){return this.systems[0]}static ensureUpdateMeshUI(t,A){bs.update(t,A)}static markUIDirty(t){bs.markDirty()}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.objectsHoveredThisFrame.length>0}onDestroy(){qs.systems.splice(qs.systems.indexOf(this),1)}start(){if(this.raycaster.length<=0&&!eA.findObjectOfType(HQ,this.context)){const t=eA.addNewComponent(this.context.scene,mr);this.raycaster.push(t),UI()&&console.warn("Added an ObjectRaycaster to the scene because no raycaster was found",this)}}register(t){var A;t&&this.raycaster&&!this.raycaster.includes(t)&&((A=this.raycaster)==null||A.push(t))}unregister(t){var A,e;const g=(A=this.raycaster)==null?void 0:A.indexOf(t);g!==void 0&&g!==-1&&((e=this.raycaster)==null||e.splice(g,1))}onEnable(){const t=new Map;this._selectStartFn??(this._selectStartFn=(e,g)=>{if(!g.grab)return;bs.resetLastSelected();const I=new Gr(this.context.input);I.inputSource=e,I.isDown=e.selectionDown,I.isUp=e.selectionUp,I.isPressed=e.selectionPressed,I.isClicked=!1,t.set(e,g.grab),g.grab&&!this.handleEvents(g.grab,I)&&(g.grab=null)}),this._selectEndFn??(this._selectEndFn=(e,g)=>{var I;if(!g.grab)return;const i=new Gr(this.context.input);i.inputSource=e,i.isDown=e.selectionDown,i.isUp=e.selectionUp,i.isPressed=e.selectionPressed,i.isClicked=e.selectionClick,this.handleEvents(g.grab,i);const o=t.get(e);if(t.set(e,null),o)for(let C=0;C<this.raisedPointerDownEvents.length;C++){const s=this.raisedPointerDownEvents[C];this.raisedPointerDownObjects[C]===o&&s&&((I=s.onPointerUp)==null||I.call(s,i),this.raisedPointerDownEvents.splice(C,1),this.raisedPointerDownObjects.splice(C,1),C--)}});const A=new Go;this._selectUpdateFn??(this._selectUpdateFn=e=>{A.ray=e.getRay();const g=this.performRaycast(A);if(!g)return;const I=new Gr(this.context.input);I.inputSource=e,this.handleIntersections(g,I)}),dg.addEventListener(Ks.SelectStart,this._selectStartFn),dg.addEventListener(Ks.SelectEnd,this._selectEndFn),dg.addEventListener(Ks.Update,this._selectUpdateFn),this._handleEventFn??(this._handleEventFn=this.onHandleEvents.bind(this)),this.context.pre_update_callbacks.push(this._handleEventFn)}onDisable(){dg.removeEventListener(Ks.SelectStart,this._selectStartFn),dg.removeEventListener(Ks.SelectEnd,this._selectEndFn),dg.removeEventListener(Ks.Update,this._selectUpdateFn),this.context.pre_update_callbacks.splice(this.context.pre_update_callbacks.indexOf(this._handleEventFn),1)}onHandleEvents(){if(this.objectsHoveredThisFrame.length=0,this.resetMeshUIStates(),Se.IsInWebXR||this.context.input.isKeyPressed("AltLeft")||this.context.input.isKeyPressed("AltRight"))return;if(!this._didMove){const i=this.context.input.getPointerPositionRC(0);if(i&&i.x===0&&i.y===0)return;this._didMove=!0}let t=0;for(const i of this.context.input.foreachPointerId()){const o=this.context.input.getPointerDown(i),C=this.context.input.getPointerUp(i);if(o||C){t=i;break}}const A=this.context.input.getPointerEvent(t),e=new Gr(this.context.input,A);e.inputSource=this.context.input,e.pointerId=t,e.isClicked=this.context.input.getPointerClicked(t),e.isDown=this.context.input.getPointerDown(t),e.isUp=this.context.input.getPointerUp(t),e.isPressed=this.context.input.getPointerPressed(t),_c&&e.isClicked&&console.log("CLICK",t);const g=this.performRaycast(null);if(!g)return;this.lastPointerEvent=e;const I={sender:this,args:e,hasActiveUI:this.currentActiveMeshUIComponents.length>0};_c&&e.isClicked&&Hg("EventSystem: "+e.pointerId+" - "+this.context.time.frame+" - Up:"+e.isUp+", Down:"+e.isDown),this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:I})),this.handleIntersections(g,e),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:I}))}onBeforeRender(){if(this.lastPointerEvent)this.lastPointerEvent.used=!1;else return;if(this.lastPointerEvent.isUp){for(const A of this.raisedPointerDownEvents)A.onPointerUp&&A.onPointerUp(this.lastPointerEvent);this.raisedPointerDownEvents.length=0,this.raisedPointerDownObjects.length=0}for(const A of this.objectsHoveredLastFrame)if(this.objectsHoveredThisFrame.indexOf(A)<0){this._tempComponentsArray.length=0;const e=eA.getComponentsInParent(A,RA,this._tempComponentsArray);this.lastPointerEvent.object=A;for(let g=0;g<e.length;g++){const I=e[g];if(!I.gameObject||I.destroyed)continue;const i=I;i.onPointerExit&&i.onPointerExit(this.lastPointerEvent)}}const t=this.objectsHoveredLastFrame;this.objectsHoveredLastFrame=this.objectsHoveredThisFrame,this.objectsHoveredThisFrame=t}performRaycast(t){if(!this.raycaster)return null;this._sortedHits.length=0;for(const A of this.raycaster){if(!A.activeAndEnabled)continue;const e=A.performRaycast(t);e&&e.length>0&&this._sortedHits.push(...e)}return this._sortedHits.sort((A,e)=>A.distance-e.distance),this._sortedHits}handleIntersections(t,A){if(!t||t.length<=0)return!1;t=this.sortCandidates(t);for(const e of t){const{object:g}=e;if(this.handleEvents(g,A))return!0}return!1}sortCandidates(t){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let A=0;A<t.length;A++){const e=t[A],g=e.object;if(g.material&&g.material.depthTest===!1){this._noDepthTestingResults.push(e);continue}this._sortingBuffer.push(e)}for(const A of this._sortingBuffer)this._noDepthTestingResults.push(A);return this._noDepthTestingResults}handleEvents(t,A){if(!this.testIsVisible(t))return A.isClicked&&_c&&console.log("not allowed",t),!1;const e=t;A.object=t,this.lastPointerEvent=A;const g=t.parent;let I=!1;const i=A.isClicked??!1;let o=null;if(g&&g.isUI){const C=(A.isPressed||A.isClicked)??!1;if(g[Ns]){const s=g[Ns].gameObject;if(s){if(!bQ.isInteractable(s,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(t,C),t=s,I=!0}}if(!I&&this.handleMeshUiObjectWithoutShadowDom(g,C))return!0}if(i&&_c&&console.log(this.context.time.frame,t),this.objectsHoveredThisFrame.push(t),o===null||o.interactable){const C=this.objectsHoveredLastFrame.indexOf(t)>=0;this.handleEventsArray.length=0;const s=eA.getComponentsInParent(t,RA,this.handleEventsArray);for(let a=0;a<s.length;a++){if(A.used)return!0;if(s[a].destroyed)continue;const n=s[a];if(n.interactable!==!1){if(n.onPointerEnter&&(C||n.onPointerEnter(A)),n.onPointerMove&&n.onPointerMove(A),A.isDown&&n.onPointerDown&&!this.raisedPointerDownEvents.includes(n)&&(n.onPointerDown(A),this.raisedPointerDownEvents.push(n),this.raisedPointerDownObjects.push(e)),A.isUp&&n.onPointerUp){const B=this.raisedPointerDownEvents.indexOf(n);B!==-1&&this.raisedPointerDownEvents.splice(B,1),n.onPointerUp(A)}A.isClicked&&n.onPointerClick&&n.onPointerClick(A)}}}return!0}handleMeshUiObjectWithoutShadowDom(t,A){return!t||!t.isUI?!0:this.handleMeshUIIntersection(t,A)}handleMeshUIIntersection(t,A){const e=bs.updateState(t,A);return e&&this.currentActiveMeshUIComponents.push(e),e!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&bs.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let t=0;t<this.currentActiveMeshUIComponents.length;t++){const A=this.currentActiveMeshUIComponents[t];bs.resetState(A)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(t){return t?eA.isActiveSelf(t)?this.testIsVisible(t.parent):!1:!0}};let io=qs;r(io,"_eventSystemMap",new Map),r(io,"didSearchEventSystem",!1);class bs{static markDirty(){this.needsUpdate=!0}static update(A,e){const g=e.time.frameCount;for(const I of this.lastUpdateFrame)if(I.context===e){if(g===I.frame)return;I.frame=g;let i=this.needsUpdate||g<1;I.nextUpdate===e.time.frameCount&&(i=!0),i&&(_c&&console.log("Update threemeshui"),this.needsUpdate=!1,A.update());return}this.lastUpdateFrame=[{context:e,frame:g,nextUpdate:g}],A.update()}static updateState(A,e){let g=null;if(A&&(g=this.findBlockInParent(A),g&&g!==this.lastSelected)){if(g.interactable===!1)return null;this.needsUpdate=!0}return g}static resetLastSelected(){const A=this.lastSelected;A&&(this.lastSelected=null,this.resetState(A))}static resetState(A){A&&(this.needsUpdate=!0)}static findBlockInParent(A){return A?A.isBlock?A:this.findBlockInParent(A.parent):null}}r(bs,"lastSelected",null),r(bs,"lastUpdateFrame",[]),r(bs,"needsUpdate",!1);const nw=Symbol("cameraController");function XeA(t){return t[nw]}function FH(t,A,e){e?t[nw]=A:t[nw]===A&&(t[nw]=null)}var $eA=Object.defineProperty,AtA=Object.getOwnPropertyDescriptor,etA=(t,A,e,g)=>{for(var I=g>1?void 0:g?AtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&$eA(A,e,I),I};const rw=aA("freecam"),NH=aA("debugcamerafit"),ttA={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let $m;class vs extends RA{constructor(){super(...arguments),r(this,"autoRotate",!1),r(this,"autoRotateSpeed",1),r(this,"enableKeys",!0),r(this,"enableDamping",!0),r(this,"dampingFactor",.1),r(this,"enableZoom",!0),r(this,"minZoom",0),r(this,"maxZoom",1/0),r(this,"enablePan",!0),r(this,"lookAtConstraint",null),r(this,"lookAtConstraint01",1),r(this,"middleClickToFocus",!0),r(this,"doubleClickToFocus",!0),r(this,"useSlerp",!0),r(this,"debugLog",!1),r(this,"targetLerpSpeed",5),r(this,"_lookTargetPosition"),r(this,"_controls",null),r(this,"_cameraObject",null),r(this,"_lerpToTargetPosition",!1),r(this,"_lerpCameraToTarget",!1),r(this,"_cameraTargetPosition",null),r(this,"_inputs",0),r(this,"_enableTime",0),r(this,"_startedListeningToKeyEvents",!1),r(this,"_eventSystem"),r(this,"_afterHandleInputFn"),r(this,"_camera",null),r(this,"_syncedTransform"),r(this,"targetElement",null),r(this,"onControlsChangeStarted",()=>{this._syncedTransform&&this._syncedTransform.requestOwnership()}),r(this,"_shouldDisable",!1),r(this,"_haveAttachedKeyboardEvents",!1)}get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(A){var e;(e=this.controls)==null||e.addEventListener("start",A)}awake(){this._lookTargetPosition=new f,this._startedListeningToKeyEvents=!1}start(){if(this._controls){const A=eA.getComponent(this.gameObject,Kt);if(A&&!this.setFromTargetPosition()){this.debugLog&&console.log("NO TARGET");const e=ye(A.cam).length(),g=new f(0,0,-e).applyMatrix4(A.cam.matrixWorld);this.setTarget(g,!0)}}this.startCoroutine(this.startRaycastDelayed()),this._eventSystem=io.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Xm.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){var A,e;(A=this._controls)==null||A.dispose(),(e=this._eventSystem)==null||e.removeEventListener(Xm.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._enableTime=this.context.time.time;const A=eA.getComponent(this.gameObject,Kt);this._camera=A;const e=A?.cam;if(e&&FH(e,this,!0),!this._controls){console.assert(e!=null,"Missing camera",this),e&&(this._cameraObject=e);const g=this.targetElement??this.context.domElement,I=e?.quaternion.clone();this._controls=new i6(e,g),e?.quaternion.copy(I),$m===void 0&&($m={...this._controls.keys})}this._controls&&(rw&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,Un()&&(this.doubleClickToFocus=!0)),this._controls.enableDamping=this.enableDamping,this._controls.keys=this.enableKeys?$m:ttA,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.addEventListener("start",this.onControlsChangeStarted),e?.type==="PerspectiveCamera"?rw||(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom):rw||(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))),this._syncedTransform=eA.getComponent(this.gameObject,tn)??void 0}onDisable(){var A;(A=this._camera)!=null&&A.cam&&FH(this._camera.cam,this,!1),this._controls&&(this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted))}afterHandleInput(A){A.detail.args.pointerId===0&&(A.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!A.detail.args.isPressed||A.detail.args.isUp)&&(this._shouldDisable=!1))}*startRaycastDelayed(){if(yield,!this.setFromTargetPosition()){const A=new Go;A.screenPoint=new W(0,0),A.lineThreshold=.1;const e=this.context.physics.raycast(A);e.length>0&&this.setTarget(e[0].point,!0)}}onBeforeRender(){var A,e,g;if(!this._controls||this._cameraObject!==this.context.mainCamera)return;(this.context.input.getPointerDown(0)||this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2))&&(this._inputs+=1),this._inputs>0&&(this.autoRotate=!1,this._controls.autoRotate=!1,this._lerpCameraToTarget=!1,this._lerpToTargetPosition=!1),this._inputs=0;let I=this.middleClickToFocus&&this.context.input.getPointerClicked(1);if(I||(I=this.doubleClickToFocus&&this.context.input.getPointerDoubleClicked(0)&&this.context.time.time-this._enableTime>.3),I?this.setTargetFromRaycast():(this.context.input.getPointerDown(0)||this.context.input.mouseWheelChanged)&&(this._lerpToTargetPosition=!1,this._lerpCameraToTarget=!1),this._lerpToTargetPosition||this._lerpCameraToTarget){const i=this.context.time.deltaTime*this.targetLerpSpeed;if(this._lerpCameraToTarget&&this._cameraTargetPosition&&this._cameraObject){if(this.useSlerp){const o=(A=this._cameraObject)==null?void 0:A.position;sJ(o,this._cameraTargetPosition,i)}else(e=this._cameraObject)==null||e.position.lerp(this._cameraTargetPosition,i);this._cameraObject.position.distanceTo(this._cameraTargetPosition)<1e-4&&(this._lerpCameraToTarget=!1)}this._lerpToTargetPosition&&(this.lerpTarget(this._lookTargetPosition,i),this._lookTargetPosition.distanceTo(this._controls.target)<1e-5&&(this._lerpToTargetPosition=!1))}!rw&&(g=this.lookAtConstraint)!=null&&g.locked&&this.setFromTargetPosition(0,this.lookAtConstraint01),this._controls&&!this.context.isInXR&&(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent,this._controls.update())}setCameraTarget(A,e=!1){var g;A?(this._lerpCameraToTarget=!0,this._cameraTargetPosition=A.clone(),e&&this._cameraTargetPosition&&((g=this.controllerObject)==null||g.position.copy(this._cameraTargetPosition))):this._lerpCameraToTarget=!1}setFromTargetPosition(A=0,e=1){var g;if(!this._controls)return!1;const I=(g=this.lookAtConstraint)==null?void 0:g.sources;if(I&&I.length>0){const i=I[A];if(i)return i.getWorldPosition(this._lookTargetPosition),this.lerpTarget(this._lookTargetPosition,e),!0}return!1}setTarget(A=null,e=!1){this._controls&&(A!==null&&this._lookTargetPosition.copy(A),e?this._controls.target.copy(this._lookTargetPosition):this._lerpToTargetPosition=!0)}lerpTarget(A,e){this._controls&&this._controls.target.lerp(A,e)}distanceToTarget(A){return this._controls?this._controls.target.distanceTo(A):-1}setTargetFromRaycast(){var A,e;if(!this.controls)return;const g=this.context.physics.raycast();for(const I of g)if(I.distance>0&&eA.isActiveInHierarchy(I.object)){if(this._lookTargetPosition.copy(I.point),this._lerpToTargetPosition=!0,this._cameraTargetPosition=null,this.context.mainCamera){this._lerpCameraToTarget=!0;const i=ye(this.context.mainCamera);this._cameraTargetPosition=i.clone().sub(this.controls.target).add(this._lookTargetPosition),(e=(A=this._cameraObject)==null?void 0:A.parent)==null||e.worldToLocal(this._cameraTargetPosition)}break}}fitCamera(A,e=1.1){const g=this._cameraObject,I=this._controls;if(A!=null&&A.length||(A=this.context.scene.children),!g||!I)return;const i=new f,o=new f,C=new BI;C.makeEmpty();for(const c of A)c instanceof Nf||C.expandByObject(c,!0);g.updateMatrixWorld(),g.updateProjectionMatrix(),C.getCenter(o),C.applyMatrix4(g.matrixWorldInverse),C.getSize(i),C.setFromCenterAndSize(o,i);const s=g.fov,a=2*Math.atan(Math.tan(s*Math.PI/360/2)*g.aspect)/Math.PI*360,n=i.y/(2*Math.atan(Math.PI*s/360)),B=i.x/(2*Math.atan(Math.PI*a/360)),Q=e*Math.max(n,B)+i.z/2;NH&&console.log("Fit camera to objects",n,B,"distance",Q);const E=ye(g),h=I.target.clone().sub(E).normalize().multiplyScalar(Q);if(I.maxDistance=Q*10,I.minDistance=Q*.01,I.target.copy(o),g.near=Q/100,g.far=Q*100,g.updateMatrixWorld(),g.updateProjectionMatrix(),tg(g,I.target.clone().sub(h)),NH){const c=new Nf(C);this.context.scene.add(c),cJ(c,ou(g)),this._haveAttachedKeyboardEvents||(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",l=>{l.code==="KeyF"&&this.fitCamera(A)}))}I.update()}}etA([w(Sc)],vs.prototype,"lookAtConstraint",2);var gtA=Object.defineProperty,ItA=Object.getOwnPropertyDescriptor,oo=(t,A,e,g)=>{for(var I=g>1?void 0:g?ItA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&>A(A,e,I),I},KH=(t=>(t[t.Skybox=1]="Skybox",t[t.SolidColor=2]="SolidColor",t[t.Uninitialized=4]="Uninitialized",t))(KH||{});const Oc=aA("debugcam"),JH=aA("debugscreenpointtoray");var Bw;const Pc=(Bw=class extends RA{constructor(){super(...arguments),r(this,"_nearClipPlane",.1),r(this,"_farClipPlane",1e3),r(this,"orthographic",!1),r(this,"orthographicSize",5),r(this,"ARBackgroundAlpha",0),r(this,"_cullingMask",4294967295),r(this,"_backgroundBlurriness"),r(this,"_backgroundIntensity"),r(this,"_targetTexture",null),r(this,"_backgroundColor"),r(this,"_fov"),r(this,"_cam",null),r(this,"_clearFlags",2),r(this,"_skybox")}get isCamera(){return!0}get aspect(){return this._cam instanceof Xe?this._cam.aspect:this.context.domWidth/this.context.domHeight}get fieldOfView(){return this._cam instanceof Xe?this._cam.fov:this._fov}set fieldOfView(t){const A=this._fov!=t;if(this._fov=t,A&&this._cam&&this._cam instanceof Xe){if(this._fov===void 0){console.error("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(t){const A=this._nearClipPlane!=t;this._nearClipPlane=t,this._cam&&A&&(this._cam.near=t,this._cam.updateProjectionMatrix())}get farClipPlane(){return this._farClipPlane}set farClipPlane(t){const A=this._farClipPlane!=t;this._farClipPlane=t,this._cam&&A&&(this._cam.far=t,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(t){t!==this._clearFlags&&(this._clearFlags=t,this.applyClearFlagsIfIsActiveCamera())}set cullingMask(t){this._cullingMask=t,this._cam&&(this._cam.layers.mask=t)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}set backgroundBlurriness(t){t!==this._backgroundBlurriness&&(t===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(t,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}set backgroundIntensity(t){t!==this._backgroundIntensity&&(t===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(t,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}get backgroundColor(){return this._backgroundColor??null}set backgroundColor(t){if(t){if(this._backgroundColor)this._backgroundColor.copy(t);else{if(!t.clone)return;this._backgroundColor=t.clone()}t.alpha===void 0&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera()}}set targetTexture(t){this._targetTexture=t}get targetTexture(){return this._targetTexture}get cam(){return this.activeAndEnabled&&this.buildCamera(),this._cam}screenPointToRay(t,A,e){let g=this.cam;const I=Pc._origin;I.set(t,A,-1),this.context.input.convertScreenspaceToRaycastSpace(I),JH&&console.log("screenPointToRay",t.toFixed(2),A.toFixed(2),"now:",I.x.toFixed(2),I.y.toFixed(2),"isInXR:"+this.context.isInXR),I.z=-1,I.unproject(g);const i=Pc._direction.set(I.x,I.y,I.z),o=ye(g);return i.sub(o),i.normalize(),e?(e.set(o,i),e):new As(o.clone(),i.clone())}awake(){JH&&window.addEventListener("pointerdown",t=>{const A=t.clientX,e=t.clientY;console.log("touch",A.toFixed(2),e.toFixed(2));const g=this.screenPointToRay(A,e),I="#"+Math.floor(Math.random()*16777215).toString(16);nC.DrawRay(g.origin,g.direction,I,10)})}onEnable(){Oc&&console.log(this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),otA(this)),this.applyClearFlagsIfIsActiveCamera()}onDisable(){this.context.removeCamera(this)}onBeforeRender(){if(this._cam&&this._targetTexture){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const t=this.context.renderer;t&&this._targetTexture.render(this.context.scene,this._cam,t)}}buildCamera(){if(this._cam)return;const t=this.gameObject.isCamera;let A=null;if(t?(A=this.gameObject,A?.layers.enableAll(),A instanceof Xe&&(this._fov=A.fov)):A=this.gameObject.children[0],A&&A.isCamera)A.type==="PerspectiveCamera"&&(this._fov&&(A.fov=this._fov),A.near=this._nearClipPlane,A.far=this._farClipPlane,A.updateProjectionMatrix());else if(!this.orthographic)A=new Xe(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(A.fov=this.fieldOfView),this.gameObject.add(A);else{const e=this.orthographicSize*100;A=new MB(window.innerWidth/-e,window.innerWidth/e,window.innerHeight/e,window.innerHeight/-e,this._nearClipPlane,this._farClipPlane),this.gameObject.add(A)}this._cam=A,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(){this.context.mainCameraComponent===this&&this.applyClearFlags()}applyClearFlags(){if(!this._cam){Oc&&console.log("Camera does not exist (apply clear flags)");return}switch(Oc&&Hg("apply Camera clear flags: "+this._clearFlags),this._clearFlags){case 1:if(Pc.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}this.enableSkybox(),this._backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this._backgroundBlurriness),this._backgroundIntensity!==void 0&&(this.context.scene.backgroundIntensity=this._backgroundIntensity);break;case 2:if(this._backgroundColor){let t=this._backgroundColor.alpha;Pc.backgroundShouldBeTransparent(this.context)&&(t=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.renderer.setClearColor(this._backgroundColor,t)}break;case 4:this.context.scene.background=null,this.context.renderer.setClearColor(0,0);break}}enableSkybox(){this._skybox||(this._skybox=new itA(this)),this._skybox.enable()}static backgroundShouldBeTransparent(t){var A,e,g,I;const i=(A=t.renderer.xr)==null?void 0:A.getSession();if(!i)return!1;const o=i.environmentBlendMode;Oc&&Hg("Environment blend mode: "+o+" on "+navigator.userAgent);const C=o==="additive"||o==="alpha-blend";return t.xrSessionMode===gc.ImmersiveAR&&o==="opaque"&&((e=navigator.userAgent)!=null&&e.includes("OculusBrowser")||(g=navigator.userAgent)!=null&&g.includes("Mozilla")&&(I=navigator.userAgent)!=null&&I.includes("Mobile WebXRViewer/v2"))?!0:C}},r(Bw,"_origin",new f),r(Bw,"_direction",new f),Bw);let Kt=Pc;oo([w()],Kt.prototype,"fieldOfView",1),oo([w()],Kt.prototype,"nearClipPlane",1),oo([w()],Kt.prototype,"farClipPlane",1),oo([w()],Kt.prototype,"clearFlags",1),oo([w()],Kt.prototype,"orthographic",2),oo([w()],Kt.prototype,"orthographicSize",2),oo([w()],Kt.prototype,"ARBackgroundAlpha",2),oo([w()],Kt.prototype,"cullingMask",1),oo([w()],Kt.prototype,"backgroundBlurriness",1),oo([w()],Kt.prototype,"backgroundIntensity",1),oo([w(wt)],Kt.prototype,"backgroundColor",1),oo([w(DQ)],Kt.prototype,"targetTexture",1);class itA{constructor(A){r(this,"_camera"),r(this,"_skybox"),this._camera=A}get context(){var A;return(A=this._camera)==null?void 0:A.context}enable(){this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),this._skybox?this.context.scene.background!==this._skybox&&(Oc&&console.log("Set skybox",this._camera,this._skybox),this._skybox.encoding=ue,this._skybox.mapping=vi,this.context.scene.background=this._skybox):console.warn("Failed to load/find skybox texture",this._camera.sourceId,this.context.lightmaps)}}function otA(t){aA("freecam")&&t.context.mainCameraComponent===t&&eA.getOrAddComponent(t.gameObject,vs)}class TQ extends RA{constructor(){super(...arguments),r(this,"_listener",null)}get listener(){return this._listener==null&&(this._listener=new Gf),this._listener}awake(){hg.registerWaitForAllowAudio(()=>{if(this.destroyed)return;const A=this.listener;if(A==null||A.parent)return;const e=eA.getComponentInParent(this.gameObject,Kt);e?e.cam.add(A):this.gameObject.add(A)})}}var CtA=Object.defineProperty,stA=Object.getOwnPropertyDescriptor,Qw=(t,A,e,g)=>{for(var I=g>1?void 0:g?stA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&CtA(A,e,I),I};class jc{constructor(){r(this,"guid")}}Qw([w()],jc.prototype,"guid",2);class _Q{constructor(){r(this,"signal"),r(this,"reaction")}}Qw([w(jc)],_Q.prototype,"signal",2),Qw([w(ti)],_Q.prototype,"reaction",2);var AM;const Ls=(AM=class extends RA{constructor(){super(...arguments),r(this,"events")}static invoke(t){if(Ls.receivers[t]){const A=Ls.receivers[t];if(!A)return;for(const e of A)e.invoke(t)}}onEnable(){if(this.events)for(const t of this.events)Ls.receivers[t.signal.guid]||(Ls.receivers[t.signal.guid]=[]),Ls.receivers[t.signal.guid].push(this)}onDisable(){if(this.events){for(const t of this.events)if(Ls.receivers[t.signal.guid]){const A=Ls.receivers[t.signal.guid].indexOf(this);A>=0&&Ls.receivers[t.signal.guid].splice(A,1)}}}invoke(t){if(!this.events||!Array.isArray(this.events))return;let A=typeof t=="object"?t.guid:t;for(const e of this.events)if(e.signal.guid===A)try{if(e.reaction){if(!e.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",e,this);continue}}else{console.warn("Missing reaction for signal",e,this);continue}e.reaction.invoke()}catch(g){console.error(g)}}},r(AM,"receivers",{}),AM);let OQ=Ls;Qw([w(_Q)],OQ.prototype,"events",2);var mi=(t=>(t.Activation="ActivationTrack",t.Animation="AnimationTrack",t.Audio="AudioTrack",t.Control="ControlTrack",t.Marker="MarkerTrack",t.Signal="SignalTrack",t))(mi||{}),on=(t=>(t[t.None=0]="None",t[t.Hold=1]="Hold",t[t.Loop=2]="Loop",t[t.PingPong=3]="PingPong",t[t.Continue=4]="Continue",t))(on||{}),eM=(t=>(t.Signal="SignalEmitter",t))(eM||{});const Wc=aA("debugtimeline"),tM=class extends RA{constructor(){super(...arguments),r(this,"playableAsset"),r(this,"playOnAwake"),r(this,"extrapolationMode",1),r(this,"waitForAudio",!0),r(this,"_visibilityChangeEvt"),r(this,"_clonedPlayableAsset",!1),r(this,"_speed",1),r(this,"_guidsMap"),r(this,"_isPlaying",!1),r(this,"_internalUpdateRoutine"),r(this,"_isPaused",!1),r(this,"_time",0),r(this,"_duration",0),r(this,"_weight",1),r(this,"_animationTracks",[]),r(this,"_audioTracks",[]),r(this,"_signalTracks",[]),r(this,"_controlTracks",[]),r(this,"_customTracks",[]),r(this,"_allTracks",[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks])}static registerCreateTrack(t,A){this.createTrackFunctions[t]=A}get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(t){typeof t=="number"&&!Number.isNaN(t)?this._time=t:(Wc||fI())&&console.error("INVALID TIMELINE.TIME VALUE",t,this.name)}get duration(){return this._duration}set duration(t){this._duration=t}get weight(){return this._weight}set weight(t){this._weight=t}get speed(){return this._speed}set speed(t){this._speed=t}awake(){var t,A,e;Wc&&console.log(this,(t=this.playableAsset)==null?void 0:t.tracks),this.rebuildGraph(),this.isValid()||console.warn("PlayableDirector is not valid",this.playableAsset,(A=this.playableAsset)==null?void 0:A.tracks,Array.isArray((e=this.playableAsset)==null?void 0:e.tracks),this)}onEnable(){var t,A;for(const e of this._audioTracks)(t=e.onEnable)==null||t.call(e);for(const e of this._customTracks)(A=e.onEnable)==null||A.call(e);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(){var t,A;this.stop();for(const e of this._audioTracks)(t=e.onDisable)==null||t.call(e);for(const e of this._customTracks)(A=e.onDisable)==null||A.call(e);this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){var t;for(const A of this._allTracks)for(const e of A)(t=e.onDestroy)==null||t.call(e)}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const t=this._isPaused==!0;if(this._isPaused=!1,t&&this.invokePauseChangedMethodsOnTracks(),!this._isPlaying){if(this._isPlaying=!0,this.waitForAudio){const A=[];for(const e of this._audioTracks){const g=e.loadAudio(this._time,1,0);g&&A.push(g)}if(A.length>0&&(await Promise.all(A),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!hg.userInteractionRegistered&&this.waitForAudio;)await _E(200)}this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate())}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.evaluate(),this.invokePauseChangedMethodsOnTracks()))}stop(){for(const e of this._audioTracks)e.stop();const t=this._isPaused==!0,A=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.evaluate(),t&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,t&&!A&&this.invokePauseChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null}evaluate(){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}this.internalEvaluate(t)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const t of this._allTracks)for(const A of t)yield A}get audioTracks(){return this._audioTracks}resolveGuids(t){this._guidsMap=t}invokePauseChangedMethodsOnTracks(){var t;for(const A of this.forEachTrack())(t=A.onPauseChanged)==null||t.call(A)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.evaluate()),yield}internalEvaluate(t){for(const A of this.playableAsset.tracks)if(!A.muted)switch(A.type){case mi.Activation:for(let e=0;e<A.outputs.length;e++){const g=A.outputs[e];if(typeof g=="object"){let I=!1;for(const o of A.clips)o.start<=t&&t<=o.end&&(I=!0);const i=g;i.visible!==void 0&&(i.visible=I)}}break}for(const A of this._animationTracks)A.evaluate(t);for(const A of this._audioTracks)A.evaluate(t);for(const A of this._signalTracks)A.evaluate(t);for(const A of this._controlTracks)A.evaluate(t);for(const A of this._customTracks)A.evaluate(t)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Sd(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const t=this.findRoot(this.gameObject);for(const A of this.playableAsset.tracks){for(let e=A.outputs.length-1;e>=0;e--){let g=A.outputs[e];if(typeof g=="string"){this._guidsMap&&this._guidsMap[g]&&(g=this._guidsMap[g]);const I=eA.findByGuid(g,t);I===null||typeof I!="object"?(A.outputs.splice(e,1),console.warn("Failed to resolve binding",g,A.name,A.type)):(Wc&&console.log("Resolved binding",g,"to",I),A.outputs[e]=I)}else if(g===null){if(A.outputs.splice(e,1),tM.createTrackFunctions[A.type])continue;A.type!==mi.Audio&&A.type!==mi.Control&&A.type!==mi.Marker&&A.type!==mi.Signal&&console.warn("Missing binding",g,A.name,A.type,this.name,this.playableAsset.name)}}if(A.type===mi.Control)for(let e=0;e<A.clips.length;e++){const g=A.clips[e];let I=g.asset.sourceObject;if(typeof I=="string"){this._guidsMap&&this._guidsMap[I]&&(I=this._guidsMap[I]);const i=eA.findByGuid(I,t);i===null||typeof i!="object"?console.warn("Failed to resolve sourceObject binding",I,A.name,g):(Wc&&console.log("Resolved binding",I,"to",i),g.asset.sourceObject=i)}}}}findRoot(t){return t.parent?this.findRoot(t.parent):t}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const t of this.playableAsset.tracks)if(t.muted!==!0){for(const A of t.clips)A.end>this._duration&&(this._duration=A.end);for(const A of t.markers)A.time>this._duration&&(this._duration=A.time+.001)}}}setupAndCreateTrackHandlers(){var t,A;if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;const e=eA.findObjectOfType(TQ,this.context);for(const g of this.playableAsset.tracks){const I=g.type,i=tM.createTrackFunctions[I];if(i!=null){const o=i(this,g);if(typeof o.evaluate=="function"){o.director=this,o.track=g,this._customTracks.push(o);continue}}if(g.type===mi.Animation){if(g.clips.length<=0){Wc&&console.warn("Animation track has no clips",g);continue}for(let o=g.outputs.length-1;o>=0;o--){let C=g.outputs[o];if(C instanceof UA){const a=eA.getOrAddComponent(C,Ai);a&&(C=a)}const s=(t=C?.gameObject)==null?void 0:t.animations;if(s){const a=new Ew;a.trackOffset=g.trackOffset,a.director=this,a.track=g;for(let n=0;n<g.clips.length;n++){const B=g.clips[n],Q=B.asset;if(!Q){console.error("MISSING anim model?","clip#"+n,B,g,this.playableAsset,this.name);continue}const E=Q.clip;let h=E;if((typeof h=="string"||typeof h=="number")&&(h=s.find(l=>l.name===E)),!h){console.warn("Could not find animationClip for model",B,g.name,this.name,(A=this.playableAsset)==null?void 0:A.name);continue}a.mixer||(a.mixer=new Pp(C.gameObject)),a.clips.push(h),a.mixer.uncacheAction(h),a.createHooks(B.asset,h);const c=a.mixer.clipAction(h);a.actions.push(c),a.models.push(B)}this._animationTracks.push(a)}}}else if(g.type===mi.Audio){if(g.clips.length<=0)continue;const o=new Xc;if(o.director=this,o.track=g,this._audioTracks.push(o),!e)continue;o.listener=e.listener;for(let C=0;C<g.clips.length;C++){const s=g.clips[C];o.addModel(s)}}else if(g.type===mi.Marker){const o=new $c;o.director=this,o.track=g;for(const C of g.markers)switch(C.type){case eM.Signal:o.models.push(C),o.didTrigger.push(!1);break}if(o!==null&&o.models.length>0){const C=eA.getComponent(this.gameObject,OQ);C&&(o.receivers.push(C),this._signalTracks.push(o))}}else if(g.type===mi.Signal){const o=new $c;o.director=this,o.track=g;for(const C of g.markers)o.models.push(C),o.didTrigger.push(!1);for(const C of g.outputs)o.receivers.push(C);this._signalTracks.push(o)}else if(g.type===mi.Control){const o=new hw;o.director=this,o.track=g;for(const C of g.clips)o.models.push(C);o.resolveSourceObjects(this.context),this._controlTracks.push(o)}}}setAudioTracksAllowPlaying(t){for(const A of this._audioTracks)A.onAllowAudioChanged(t)}};let Vc=tM;r(Vc,"createTrackFunctions",{});const Mr=aA("debugtimeline");class zc{constructor(){r(this,"director"),r(this,"track")}get muted(){return this.track.muted}set muted(A){var e;A!==this.track.muted&&(this.track.muted=A,(e=this.onMuteChanged)==null||e.call(this))}*forEachClip(A=!1){var e;if((e=this.track)!=null&&e.clips)if(A)for(let g=this.track.clips.length-1;g>=0;g--)yield this.track.clips[g];else for(const g of this.track.clips)yield g}getClipTime(A,e){return e.clipIn+(A-e.start)*e.timeScale}getClipTimeNormalized(A,e){return(A-e.start)/e.duration}evaluateWeight(A,e,g,I=!0){if(e<0||e>=g.length)return 0;const i=g[e];if(I||A>=i.start&&A<=i.end){let o=1,C=!1;if(i.easeInDuration>0){const s=Math.min((A-i.start)/i.easeInDuration,1);o*=s}if(i.easeOutDuration>0&&!C){const s=Math.min((i.end-A)/i.easeOutDuration,1);o*=s}return o}return 0}}class atA{constructor(A){r(this,"clip"),r(this,"rootPositionOffset"),r(this,"rootQuaternionOffset"),r(this,"rootStartPosition"),r(this,"rootEndPosition"),r(this,"rootStartQuaternion"),r(this,"rootEndQuaternion");const e=A.getClip();this.clip=e;const g=A.getRoot(),I=g.name+".position",i=g.name+".quaternion";Mr&&console.log(e.name,e.tracks,I);for(const o of e.tracks)if(!(o.times.length<=0)){if(o.name.endsWith(I))this.rootStartPosition=new f().fromArray(o.values,0),this.rootEndPosition=new f().fromArray(o.values,o.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Mr&&console.log(this.rootPositionOffset);else if(o.name.endsWith(i)&&(this.rootStartQuaternion=new GA().fromArray(o.values,0),this.rootEndQuaternion=new GA().fromArray(o.values,o.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Mr)){const C=new fg().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",C)}}}get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}}class Ew extends zc{constructor(){super(...arguments),r(this,"models",[]),r(this,"trackOffset"),r(this,"target"),r(this,"mixer"),r(this,"clips",[]),r(this,"actions",[]),r(this,"_actionOffsets",[]),r(this,"_didBind",!1),r(this,"_animator",null),r(this,"_animatorWasEnabled",!1),r(this,"_useclipOffsets",!0),r(this,"_totalOffsetPosition",new f),r(this,"_totalOffsetRotation",new GA),r(this,"_totalOffsetPosition2",new f),r(this,"_totalOffsetRotation2",new GA),r(this,"_summedPos",new f),r(this,"_tempPos",new f),r(this,"_summedRot",new GA),r(this,"_tempRot",new GA),r(this,"_clipRotQuat",new GA)}onPauseChanged(){this._animator&&this._animatorWasEnabled!==void 0&&(this._animator.enabled=this.director.isPlaying===!1?this._animatorWasEnabled:!1)}createHooks(A,e){var g,I;if(((g=e.tracks)==null?void 0:g.length)<=0){console.warn("No tracks in AnimationClip",e);return}const i=e.tracks[0].name.split("."),o=i[i.length-2],C=o+".position",s=o+".quaternion";let a=!1,n=!1;for(const B of e.tracks)B.name.endsWith(C)?(a=!0,this.createPositionInterpolant(e,A,B)):B.name.endsWith(s)&&(n=!0,this.createRotationInterpolant(e,A,B));if(!a||!n){const B=(I=this.mixer)==null?void 0:I.getRoot(),Q=e.tracks[0],E=Q.name.lastIndexOf("."),h=Q.name.substring(0,E),c=h.substring(h.lastIndexOf(".")+1),l=B.getObjectByName(c);if(l)if(a){if(!n){const d=e.tracks[0].name.substring(0,E)+".quaternion";Mr&&console.warn("Create quaternion track",c,l);const u=l.quaternion,p=new Zo(d,[0,e.duration],[u.x,u.y,u.z,u.w,u.x,u.y,u.z,u.w]);e.tracks.push(p),this.createRotationInterpolant(e,A,p)}}else{const d=h+".position";Mr&&console.warn("Create position track",c,l);const u=l.position,p=new ya(d,[0,e.duration],[u.x,u.y,u.z,u.x,u.y,u.z]);e.tracks.push(p),this.createPositionInterpolant(e,A,p)}}}bind(){if(!this._didBind){this._didBind=!0,Mr&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const A of this.actions){const e=new atA(A);this._actionOffsets.push(e)}this.target&&(this._animator=eA.getComponent(this.target,Ai)??null,this._animator?(this._animatorWasEnabled=this._animator.enabled,this._animator.enabled=!1):this._animatorWasEnabled=!1);for(const A of this.models){const e=A.asset,g=e.position,I=e.rotation;g&&g.x!==void 0&&(g.isVector3||(e.position=new f(g.x,g.y,g.z)),I.isQuaternion||(e.rotation=new GA(I.x,I.y,I.z,I.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const A=this.trackOffset.position;A&&(A.isVector3||(this.trackOffset.position=new f(A.x,A.y,A.z)));const e=this.trackOffset.rotation;e&&(e.isQuaternion||(this.trackOffset.rotation=new GA(e.x,e.y,e.z,e.w)))}}evaluate(A){if(this.track.muted||!this.mixer)return;this.bind(),this._animator&&this.director.isPlaying&&this.director.weight>0&&(this._animator.enabled=!1),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 e=0,g=0,I=!1,i=!1;for(let o=0;o<this.clips.length;o++){const C=this.models[o],s=this.actions[o],a=C.asset;s.weight=0;const n=A>=C.start&&A<=C.end,B=C.preExtrapolationMode,Q=C.postExtrapolationMode,E=o<this.clips.length-1?this.models[o+1]:null;let h=n,c=!1;if(!h&&!I&&C.end<A&&Q!==on.None?(!E||E.start>A)&&(h=!0,I=!0):o==0&&!h&&!i&&C.start>A&&B!==on.None&&(!E||E.start<A)&&(h=!0,c=!0,i=!0),h){let l=1;l*=this.evaluateWeight(A,o,this.models,h),l*=this.director.weight;let d=n;c&&B!==on.Hold&&(A+=C.start,d=!0);let u=this.getClipTime(A,C),p=0;const D=a.duration;if(c&&B===on.Hold&&(u=0),d){if(a.loop)for(p+=Math.floor(u/(D+1e-6));u>D;)u-=D}else if(!n)switch(Q){case on.Loop:u%=D;break;case on.PingPong:const k=Math.floor(u/D)%2!==0;u%=D,k&&(u=D-u);break}C.reversed===!0?s.time=s.getClip().duration-u:s.time=u,s.timeScale=0;const y=l;if(s.weight=y,s.clampWhenFinished=!0,s.isRunning()||s.play(),this._useclipOffsets){const k=e==0?this._totalOffsetPosition:this._totalOffsetPosition2,F=e==0?this._totalOffsetRotation:this._totalOffsetRotation2;e<1&&(g=1-l),e+=1;const S=this._summedPos.set(0,0,0),U=this._tempPos.set(0,0,0),M=this._summedRot.identity(),Y=this._tempRot.identity(),_=a.rotation;_&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(_,l));const x=this._actionOffsets[o];if(x.hasOffsets)for(let v=0;v<p;v++)x.rootPositionOffset?U.copy(x.rootPositionOffset):U.set(0,0,0),U.applyQuaternion(M),this._clipRotQuat&&U.applyQuaternion(this._clipRotQuat),x.rootQuaternionOffset&&(Y.copy(x.rootQuaternionOffset),M.multiply(Y)),S.add(U);this._clipRotQuat&&F.multiply(this._clipRotQuat),F.multiply(M),a.position&&S.add(a.position),k.add(S)}}}this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,g),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,g)),this.mixer.update(A)}createRotationInterpolant(A,e,g){var I;const i=g.createInterpolant.bind(g),o=new GA;this.ensureTrackOffsets();const C=(I=this.trackOffset)==null?void 0:I.rotation;g.createInterpolant=()=>{const s=i(),a=s.evaluate.bind(s);return s.evaluate=n=>{const B=a(n);return o.set(B[0],B[1],B[2],B[3]),o.premultiply(this._totalOffsetRotation),C&&o.premultiply(C),B[0]=o.x,B[1]=o.y,B[2]=o.z,B[3]=o.w,B},s}}createPositionInterpolant(A,e,g){var I,i;const o=g.createInterpolant.bind(g),C=new f;this.ensureTrackOffsets();const s=(I=this.trackOffset)==null?void 0:I.rotation,a=(i=this.trackOffset)==null?void 0:i.position;let n;g.createInterpolant=()=>{const B=o(),Q=B.evaluate.bind(B);return B.evaluate=E=>{var h,c;const l=Q(E);return C.set(l[0],l[1],l[2]),e.removeStartOffset&&(n===void 0?(n=null,n=(c=(h=this._actionOffsets.find(d=>d.clip===A))==null?void 0:h.rootStartPosition)==null?void 0:c.clone()):n!=null&&n.isVector3&&C.sub(n)),C.applyQuaternion(this._totalOffsetRotation),C.add(this._totalOffsetPosition),s&&C.applyQuaternion(s),a&&(C.x-=a.x,C.y+=a.y,C.z+=a.z),l[0]=C.x,l[1]=C.y,l[2]=C.z,l},B}}}const ntA=aA("mutetimeline"),Zc=class extends zc{constructor(){super(...arguments),r(this,"models",[]),r(this,"listener"),r(this,"audio",[]),r(this,"audioContextTimeOffset",[]),r(this,"lastTime",0),r(this,"_audioLoader",null)}getAudioFilePath(t){const A=this.director.sourceId;return Ia(A,t)}onAllowAudioChanged(t){for(let A=0;A<this.models.length;A++){const e=this.models[A];this.audio[A].setVolume(t?e.asset.volume:0)}}addModel(t){const A=new Op(this.listener);this.audio.push(A),this.models.push(t)}onDisable(){for(const t of this.audio)t.isPlaying&&t.stop()}onMuteChanged(){if(this.muted)for(let t=0;t<this.audio.length;t++){const A=this.audio[t];A!=null&&A.isPlaying&&A.stop()}}stop(){for(let t=0;t<this.audio.length;t++){const A=this.audio[t];A!=null&&A.isPlaying&&A.stop()}}evaluate(t){if(ntA||this.track.muted||this.director.speed<0)return;const A=this.director.context.application.muted,e=A?.1:0;for(let g=0;g<this.models.length;g++){const I=this.models[g],i=this.audio[g];if((!i||!i.buffer)&&this.isInTimeRange(I,t-1,t+1)&&this.handleAudioLoading(I,i),hg.userInteractionRegistered!==!1&&!(i===null||!i.buffer))if(i.playbackRate=this.director.context.time.timeScale,i.loop=I.asset.loop,t>=I.start&&t<=I.end&&t<this.director.duration){if(this.director.isPlaying==!1){if(i.isPlaying&&i.stop(),this.lastTime===t)continue}else if(!i.isPlaying)i.offset=I.clipIn+(t-I.start)*I.timeScale,i.play(e);else{const C=I.clipIn+(t-I.start)*I.timeScale,s=i.context.currentTime-i._startedAt+i.offset;Math.abs(C-s)>.3&&(i.offset=C,i.stop(),i.play(e))}let o=I.asset.volume;if(A&&(o=0),I.easeInDuration>0){const C=Math.min((t-I.start)/I.easeInDuration,1);o*=C}if(I.easeOutDuration>0){const C=Math.min((I.end-t)/I.easeOutDuration,1);o*=C}i.setVolume(o*this.director.weight)}else i.isPlaying&&i.stop()}this.lastTime=t}loadAudio(t,A=0,e=0){let g=null;const I=t-e,i=t+A;for(const o of this.models)if(this.isInTimeRange(o,I,i)){const C=this.audio[this.models.indexOf(o)],s=this.handleAudioLoading(o,C);s!==null&&(g===null&&(g=[]),g.push(s))}return g!==null?Promise.all(g):null}isInTimeRange(t,A,e){return A<=t.start&&e>=t.end||A>=t.start&&A<=t.end||e>=t.start&&e<=t.end}static dispose(){Zc._currentlyLoading.clear()}handleAudioLoading(t,A){this._audioLoader||(this._audioLoader=new Tp);const e=this.getAudioFilePath(t.asset.clip);if(Zc._currentlyLoading.get(e)){const I=Zc._currentlyLoading.get(e);return I.then(i=>{i&&A.setBuffer(i)}),I}Mr&&console.warn("LOAD audio track",e,this.director.sourceId);const g=new Promise((I,i)=>{this._audioLoader.load(e,o=>{A.setBuffer(o),I(o)},void 0,o=>{console.error("Error loading audio",o),I(null)})});return Zc._currentlyLoading.set(e,g),g}};let Xc=Zc;r(Xc,"_currentlyLoading",new Map);class $c extends zc{constructor(){super(...arguments),r(this,"models",[]),r(this,"didTrigger",[]),r(this,"receivers",[])}evaluate(A){var e;if(!this.track.muted)for(let g=0;g<this.models.length;g++){const I=this.models[g],i=this.didTrigger[g],o=I.time-A;let C=!1;if(I.retroActive)C=o<=1e-6;else{const s=Math.abs(o);s>=1e-5&&s<.1&&(C=!0)}if(C){if(!i)if(this.didTrigger[g]=!0,((e=this.receivers)==null?void 0:e.length)<=0)OQ.invoke(I.asset);else for(const s of this.receivers)s&&s.invoke(I.asset)}else I.emitOnce||(this.didTrigger[g]=!1)}}}class hw extends zc{constructor(){super(...arguments),r(this,"models",[]),r(this,"timelines",[]),r(this,"_previousActiveModel",null)}resolveSourceObjects(A){for(let e=this.models.length-1;e>=0;e--){const g=this.models[e].asset;if(!g.sourceObject||typeof g.sourceObject!="object"){console.log("no source object, removing model",e,g),this.models.splice(e,1);continue}else{const I=eA.getComponent(g.sourceObject,Vc);this.timelines.push(I),I&&g.updateDirector&&(I.playOnAwake=!1)}}}evaluate(A){var e;this._previousActiveModel=null;for(let g=0;g<this.models.length;g++){const I=this.models[g],i=I.asset;if(A>=I.start&&A<=I.end){this._previousActiveModel=I;const o=this.getClipTime(A,I);if(i.controlActivation){const C=i.sourceObject;C.visible=!0}if(i.updateDirector){const C=this.timelines[g];C&&(C.isPlaying&&C.pause(),C.time=o,C.evaluate())}}else{const o=(e=this._previousActiveModel)==null?void 0:e.asset;if(i.controlActivation){const C=i.sourceObject;o?.sourceObject!==C&&(C.visible=!1)}}}}}var rtA=Object.defineProperty,BtA=Object.getOwnPropertyDescriptor,qH=(t,A,e,g)=>{for(var I=g>1?void 0:g?BtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&rtA(A,e,I),I};class qe{constructor(A){r(this,"_active",!0),r(this,"_value"),r(this,"_valueRaw"),r(this,"_defaultValue"),r(this,"valueProcessor"),r(this,"onValueChanged"),this._value=A,this._defaultValue=A}get overrideState(){return this._active}set overrideState(A){if(this._active===A)return;this._active=A;const e=A?this._valueRaw:this._defaultValue;this.processValue(e,!0)}get value(){return this._valueRaw}set value(A){this.processValue(A,!1)}set defaultValue(A){this._defaultValue=A}__init(){this.processValue(this._valueRaw,!0)}processValue(A,e){if(A==null||!e&&this.testIfValueChanged(A)===!1)return;const g=this._value;!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,A=this._defaultValue,this._valueRaw=A):(this._valueRaw=A,this._active&&this.valueProcessor&&(A=this.valueProcessor(A)),this._value=A),this.onValueChanged&&this.onValueChanged(A,g,this)}testIfValueChanged(A){return this._valueRaw!==A}}qH([w()],qe.prototype,"overrideState",1),qH([w()],qe.prototype,"value",1);var QtA=Object.defineProperty,EtA=Object.getOwnPropertyDescriptor,htA=(t,A,e,g)=>{for(var I=g>1?void 0:g?EtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&QtA(A,e,I),I};const ctA=aA("debugpost");class TI extends Ja{constructor(){super(...arguments),r(this,"active",!0),r(this,"_result")}onEnable(){this.__internalDidAwakeAndStart&&(this.active=!0)}onDisable(){this.active=!1}init(){}apply(){var A;return this._result||(this._result=(A=this.onCreateEffect)==null?void 0:A.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){ctA&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(A=>A.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const A=Object.keys(this);for(const e of A){const g=this[e];g instanceof qe&&g.__init()}}onAfterDeserialize(A,e){if(typeof A=="object"){const g=this.$serializedTypes;if(g){for(const I of Object.keys(g))if(g[I]===qe){const i=A[I];if(i!==void 0){const o=this[I];o.value=i}}}}}onEditorModification(A){const e=A.propertyName;if(this[e]instanceof qe){const g=A.value;return this[e].value=g,!0}}}htA([w()],TI.prototype,"active",2);var ltA=Object.defineProperty,dtA=Object.getOwnPropertyDescriptor,ptA=(t,A,e,g)=>{for(var I=g>1?void 0:g?dtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&<A(A,e,I),I};const utA=aA("debugpost"),gM={};function uC(t,A){gM[t]=A}function DtA(t){return t.__type in gM?gM[t.__type]:(utA&&t.__type&&console.warn("Unknown postprocessing type",t.__type,t),TI)}class Al{constructor(){r(this,"components")}init(){var A;(A=this.components)==null||A.forEach(e=>e.init())}}ptA([gQ([t=>DtA(t),TI])],Al.prototype,"components",2);var wtA=Object.defineProperty,ytA=Object.getOwnPropertyDescriptor,StA=(t,A,e,g)=>{for(var I=g>1?void 0:g?ytA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&wtA(A,e,I),I};class el extends TI{constructor(){super(...arguments),r(this,"preset")}get typeName(){return"Antialiasing"}onCreateEffect(){const A=new Oz({preset:AQ.HIGH,edgeDetectionMode:kk.DEPTH});return this.preset.onValueChanged=e=>{A.applyPreset(e)},A}}StA([w(qe)],el.prototype,"preset",2),uC("Antialiasing",el);class cw{constructor(){r(this,"files",[])}get extensionName(){return"Audio"}onExportObject(A,e,g){const I=eA.getComponents(A,hg);if(I.length)for(const i of I){if(!i.playOnAwake)continue;const o=i.clip.split("/").pop();this.files.includes(i.clip)||this.files.push(i.clip),e.addEventListener("serialize",(C,s)=>{C.appendLine(),C.beginBlock(`def SpatialAudio "${e.name}"`),C.appendLine(`uniform asset filePath = @audio/${o}@`),C.appendLine(`uniform token auralMode = "${i.spatialBlend>0?"spatial":"nonSpatial"}"`),C.appendLine(`uniform token playbackMode = "${i.loop?"loopFromStage":"onceFromStart"}"`),C.appendLine(`uniform float gain = ${i.volume}`),C.closeBlock()})}}async onAfterSerialize(A){console.warn("onAfterSerialize",this);for(const e of this.files){const g=e.split("/").pop(),I=await(await(await fetch(e)).blob()).arrayBuffer(),i=new Uint8Array(I);A.files["audio/"+g]=i}}}var ftA=Object.defineProperty,ktA=Object.getOwnPropertyDescriptor,bH=(t,A,e,g)=>{for(var I=g>1?void 0:g?ktA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&ftA(A,e,I),I};const GtA=aA("debugmouth");class tl extends RA{constructor(){super(...arguments),r(this,"idle",[]),r(this,"talking",[]),r(this,"marker",null),r(this,"voip",null),r(this,"lastMouthChangeTime",0),r(this,"mouthChangeLength",0)}awake(){setTimeout(()=>{this.voip=eA.findObjectOfType(Xs,this.context),this.marker||(this.marker=eA.getComponentInParent(this.gameObject,uI))},3e3)}update(){var A;if(!this.voip||this.context.time.frameCount%10!==0)return;let e=((A=this.marker)==null?void 0:A.connectionId)??null;if(!e){GtA&&(e=null);return}const g=this.voip.getFrequency(e)??0;this.updateLips(g)}updateLips(A){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&A>30){this.lastMouthChangeTime=this.context.time.time;const e=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,e)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const e=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,e)}}}setMouthShapeActive(A,e){if(A){A!=this.idle?this.idle.map(g=>g.visible=!1):this.talking.map(g=>g.visible=!1);for(let g=0;g<A.length;g++){const I=A[g];I&&(I.visible=g===e)}}}}bH([w(UA)],tl.prototype,"idle",2),bH([w(UA)],tl.prototype,"talking",2);class IM extends RA{constructor(){super(...arguments),r(this,"voip",null),r(this,"marker",null),r(this,"_startPosition",null)}awake(){this.voip=eA.findObjectOfType(Xs,this.context),this.marker=eA.getComponentInParent(this.gameObject,uI)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const A=this.marker.connectionId,e=this.voip.getFrequency(A);if(e==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());let g=e/100;this.gameObject.position.y=this._startPosition.y+g*.07}}var mtA=Object.defineProperty,MtA=Object.getOwnPropertyDescriptor,lw=(t,A,e,g)=>{for(var I=g>1?void 0:g?MtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&mtA(A,e,I),I};class Rr extends RA{constructor(){super(...arguments),r(this,"eyes",[]),r(this,"lastBlinkTime",0),r(this,"blinkLength",0),r(this,"eyesOpen",!0),r(this,"state",null)}awake(){this.state=eA.getComponentInParent(this.gameObject,xI)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&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(const A of this.eyes)A&&(A.visible=this.eyesOpen)}}}lw([w(UA)],Rr.prototype,"eyes",2),lw([w()],Rr.prototype,"lastBlinkTime",2),lw([w()],Rr.prototype,"blinkLength",2),lw([w()],Rr.prototype,"eyesOpen",2);var RtA=Object.defineProperty,UtA=Object.getOwnPropertyDescriptor,iM=(t,A,e,g)=>{for(var I=g>1?void 0:g?UtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&RtA(A,e,I),I},oM;const vH=(oM=class extends RA{constructor(){super(...arguments),r(this,"head",null),r(this,"eyes",null),r(this,"target",null),r(this,"brain",null),r(this,"vec",new f),r(this,"currentTargetPoint",new f)}awake(){this.brain||(this.brain=eA.getComponentInParent(this.gameObject,Gc)),this.brain||(console.log("No look at brain found, adding it now"),this.brain=eA.addNewComponent(this.gameObject,Gc)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}update(){const t=this.target;if(t&&this.head){const A=this.eyes;if(A){const e=ye(t);this.currentTargetPoint.lerp(e,this.context.time.deltaTime/.1);const g=ye(this.head),I=this.vec.copy(this.currentTargetPoint).sub(g).normalize();if(I.length()<.1)return;const i=vH.forward;if(i.set(0,0,1),i.applyQuaternion(Ng(this.head)),i.dot(I)>.45)for(let o=0;o<A.length;o++)A[o].lookAt(this.currentTargetPoint)}}}},r(oM,"forward",new f(0,0,1)),oM);let PQ=vH;iM([w(UA)],PQ.prototype,"head",2),iM([w(UA)],PQ.prototype,"eyes",2),iM([w(UA)],PQ.prototype,"target",2);var FtA=Object.defineProperty,NtA=Object.getOwnPropertyDescriptor,CM=(t,A,e,g)=>{for(var I=g>1?void 0:g?NtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&FtA(A,e,I),I};class jQ extends RA{constructor(){super(...arguments),r(this,"length",1),r(this,"depthTest",!0),r(this,"isGizmo",!0),r(this,"_axes",null)}onEnable(){if(this.isGizmo&&!Mh)return;this._axes||(this._axes=new _B(this.length)),this.gameObject.add(this._axes);const A=this._axes.material;A&&A.depthTest!==void 0&&(A.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}CM([w()],jQ.prototype,"length",2),CM([w()],jQ.prototype,"depthTest",2),CM([w()],jQ.prototype,"isGizmo",2);class sM extends RA{constructor(){super(...arguments),r(this,"from"),r(this,"to"),r(this,"hint"),r(this,"desiredDistance",1)}onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;let A=ye(this.to).clone(),e=ye(this.from).clone(),g=A.distanceTo(e),I=A.clone();I.sub(e);let i=e.clone();i.add(A),i.multiplyScalar(.5);let o=ye(this.hint).clone();o.sub(i);let C=new f;C.crossVectors(o,I),C.crossVectors(I,C),C.normalize();let s=g*.5,a=Math.max(this.desiredDistance,s),n=Math.sqrt(a*a-s*s),B=C.clone();B.multiplyScalar(n),B.add(i),tg(this.gameObject,B);let Q=i.clone();Q.sub(C),this.gameObject.lookAt(Q)}}class dw{constructor(){r(this,"behaviours",[]),r(this,"behaviourComponents",[]),r(this,"behaviourComponentsCopy",[])}get extensionName(){return"Behaviour"}addBehavior(A){this.behaviours.push(A)}onBeforeBuildDocument(A){A.root.traverse(e=>{eA.foreachComponent(e,g=>{var I;const i=g;(typeof i.createBehaviours=="function"||typeof i.beforeCreateDocument=="function"||typeof i.afterCreateDocument=="function")&&(this.behaviourComponents.push(i),(I=i.beforeCreateDocument)==null||I.call(i,this,A))},!1)})}onExportObject(A,e,g){var I;for(const i of this.behaviourComponents)(I=i.createBehaviours)==null||I.call(i,this,e,g)}onAfterBuildDocument(A){for(const e of this.behaviourComponents)typeof e.afterCreateDocument=="function"&&e.afterCreateDocument(this,A);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0}onAfterHierarchy(A,e){var g;if((g=this.behaviours)!=null&&g.length){e.beginBlock('def Scope "Behaviors"');for(const I of this.behaviours)I.writeTo(this,A.document,e);e.closeBlock()}}async onAfterSerialize(A){console.log("onAfterSerialize",this.behaviourComponentsCopy);for(const e of this.behaviourComponentsCopy)console.log("behaviour",e),typeof e.afterSerialize=="function"&&(console.log("beh has afterSerialize",e),e.afterSerialize.constructor.name==="AsyncFunction"?await e.afterSerialize(this,A):e.afterSerialize(this,A))}}var KtA=Object.defineProperty,JtA=Object.getOwnPropertyDescriptor,aM=(t,A,e,g)=>{for(var I=g>1?void 0:g?JtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&KtA(A,e,I),I};class Ur extends TI{constructor(){super(...arguments),r(this,"threshold"),r(this,"intensity"),r(this,"scatter"),r(this,"selectiveBloom",!0)}get typeName(){return"Bloom"}init(){this.threshold.defaultValue=1,this.intensity.defaultValue=0,this.scatter.defaultValue=.2,this.selectiveBloom?(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>1*Math.PI*(1-A)):(this.threshold.valueProcessor=A=>A,this.intensity.valueProcessor=A=>A,this.scatter.valueProcessor=A=>100*(1-A))}onCreateEffect(){let A;if(this.selectiveBloom){const e=A=new Wb(this.context.scene,this.context.mainCamera,{blendFunction:Je.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,intensity:this.intensity.value});e.inverted=!0}else A=new Fk;return this.intensity.onValueChanged=e=>{A.intensity=e},this.threshold.onValueChanged=e=>{A.luminanceMaterial.threshold=e},this.scatter.onValueChanged=e=>{A.luminancePass.enabled=!0,A.luminanceMaterial.smoothing=e},A}}aM([w(qe)],Ur.prototype,"threshold",2),aM([w(qe)],Ur.prototype,"intensity",2),aM([w(qe)],Ur.prototype,"scatter",2),uC("Bloom",Ur);var qtA=Object.defineProperty,btA=Object.getOwnPropertyDescriptor,xo=(t,A,e,g)=>{for(var I=g>1?void 0:g?btA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&qtA(A,e,I),I};class DC extends RA{constructor(){super(...arguments),r(this,"attachedRigidbody",null),r(this,"isTrigger",!1),r(this,"sharedMaterial")}get isCollider(){return!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ht))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ht))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ht))}onDisable(){var A;(A=this.context.physics.engine)==null||A.removeBody(this)}}xo([w(Ht)],DC.prototype,"attachedRigidbody",2),xo([w()],DC.prototype,"isTrigger",2),xo([w()],DC.prototype,"sharedMaterial",2);class gl extends DC{constructor(){super(...arguments),r(this,"radius",.5),r(this,"center",new f(0,0,0))}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addSphereCollider(this,this.center,this.radius)}}xo([w()],gl.prototype,"radius",2),xo([w(f)],gl.prototype,"center",2);class Il extends DC{constructor(){super(...arguments),r(this,"size",new f(1,1,1)),r(this,"center",new f(0,0,0))}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addBoxCollider(this,this.center,this.size)}}xo([w(f)],Il.prototype,"size",2),xo([w(f)],Il.prototype,"center",2);class il extends DC{constructor(){super(...arguments),r(this,"sharedMesh"),r(this,"convex",!1)}onEnable(){var A,e,g,I,i;if(super.onEnable(),(A=this.sharedMesh)!=null&&A.isMesh||this.gameObject instanceof yA&&(this.sharedMesh=this.gameObject),(e=this.sharedMesh)!=null&&e.isMesh)(g=this.context.physics.engine)==null||g.addMeshCollider(this,this.sharedMesh,this.convex,zg(this.gameObject));else{const o=this.sharedMesh;if(o!=null&&o.isGroup){console.warn(`MeshCollider mesh is a group "${(I=this.sharedMesh)==null?void 0:I.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);for(const C in o.children){const s=o.children[C];s.isMesh&&((i=this.context.physics.engine)==null||i.addMeshCollider(this,s,this.convex,zg(this.gameObject)))}}}}}xo([w()],il.prototype,"convex",2);class Cn extends DC{constructor(){super(...arguments),r(this,"center",new f(0,0,0)),r(this,"radius",.5),r(this,"height",2)}onEnable(){var A;super.onEnable(),(A=this.context.physics.engine)==null||A.addCapsuleCollider(this,this.center,this.height,this.radius)}}xo([w(f)],Cn.prototype,"center",2),xo([w()],Cn.prototype,"radius",2),xo([w()],Cn.prototype,"height",2);function nM(t){return t[Ns]||(t.parent?nM(t.parent):null)}function pw(t,A){if(!t)return;const e=t.material;if(e?.isMaterial===!0){const g=t.parent;g&&g.isText,e.side=A.doubleSided??!0?ft:kI,e.shadowSide=A.doubleSided?ft:kI,t.castShadow=A.castShadows?A.castShadows:!1,t.receiveShadow=A.receiveShadows?A.receiveShadows:!1}for(const g of t.children)pw(g,A)}function WQ(t,A,e){t[A]===void 0&&console.warn("Field",A,"is undefined on",t);const g=Proxy.revocable(t[A],{set(o,C,s,a){const n=o[C],B=Reflect.set(o,C,s,a);return e(s,n),B}}),I=g.revoke,i=t[A];return g.revoke=()=>{t[A]=i,I()},t[A]=g.proxy,g}const LH=Symbol("Scheduled action");function vtA(t,A,e=ki.OnBeforeRender){let g=t[LH];g||(g=t[LH]={});const I=A.name;g[e]||(g[e]={});const i=g[e];if(i[I])return;function*o(){A?.call(t),i[I]=null}const C=t.startCoroutine(o(),e);i[I]=C}var LtA=Object.defineProperty,xtA=Object.getOwnPropertyDescriptor,Fr=(t,A,e,g)=>{for(var I=g>1?void 0:g?xtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&LtA(A,e,I),I};const rM=aA("debugui"),BM=aA("debuguilayout");class QM{constructor(){r(this,"width"),r(this,"height")}}class EM{constructor(){r(this,"x"),r(this,"y"),r(this,"width"),r(this,"height")}}const wC=new f,ol=new TA,uw=new GA,xH=class extends _o{constructor(){super(...arguments),r(this,"offset",.01),r(this,"_anchoredPosition"),r(this,"sizeDelta",new W(100,100)),r(this,"pivot",new W(.5,.5)),r(this,"anchorMin",new W(0,0)),r(this,"anchorMax",new W(1,1)),r(this,"offsetMin",new W(0,0)),r(this,"offsetMax",new W(0,0)),r(this,"lastMatrix"),r(this,"rectBlock"),r(this,"_transformNeedsUpdate",!1),r(this,"_initialPosition"),r(this,"_parentRectTransform"),r(this,"_lastUpdateFrame",-1),r(this,"_lastAnchoring"),r(this,"_createdBlocks",[]),r(this,"_createdTextBlocks",[])}get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new W),this._anchoredPosition}set anchoredPosition(t){this._anchoredPosition=t}get width(){if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,A=this.anchorMax.x-this.anchorMin.x;let e=t*A;return e+=this.sizeDelta.x,e}return this.sizeDelta.x}get height(){if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,A=this.anchorMax.y-this.anchorMin.y;let e=t*A;return e+=this.sizeDelta.y,e}return this.sizeDelta.y}awake(){super.awake(),this._anchoredPosition||(this._anchoredPosition=new W),this.lastMatrix=new TA,this.rectBlock=new UA,this.rectBlock.position.z=.1,this.rectBlock.name=this.name,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this.onApplyTransform("RectTransform awake"),WQ(this,"_anchoredPosition",()=>{this.markDirty()}),WQ(this,"sizeDelta",()=>{this.markDirty()}),WQ(this,"pivot",()=>{this.markDirty()}),WQ(this,"anchorMin",()=>{this.markDirty()}),WQ(this,"anchorMax",()=>{this.markDirty()})}onEnable(){var t;super.onEnable(),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,(t=this.Canvas)==null||t.registerTransform(this)}onDisable(){var t;super.onDisable(),this.removeShadowComponent(),(t=this.Canvas)==null||t.unregisterTransform(this)}onParentRectTransformChanged(t){this._transformNeedsUpdate||this.onApplyTransform(BM?`${t.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(BM&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(t){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const A=this.shadowComponent;if(!A)return;this.gameObject.parent?this._parentRectTransform=eA.getComponentInParent(this.gameObject.parent,xH):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,BM&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+t),this.isRoot()?this.Root.screenspace||(A.rotation.y=Math.PI):(A.matrix.identity(),A.matrixAutoUpdate=!1,wC.set(0,0,0),this.applyPivot(wC),A.matrix.setPosition(wC.x,wC.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(uw.copy(this.gameObject.quaternion),uw.x*=-1,uw.z*=-1,ol.makeRotationFromQuaternion(uw),A.matrix.premultiply(ol)),wC.set(0,0,0),this.applyAnchoring(wC),wC.z+=this.offset,ol.identity(),ol.setPosition(wC.x,wC.y,wC.z),A.matrix.premultiply(ol),A.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const e=!0;for(const g of uk(this.gameObject,_o,e,1)){if(g===this||!g.activeAndEnabled)continue;const I=g;I.onParentRectTransformChanged&&I.onParentRectTransformChanged(this)}}applyAnchoring(t){this._lastAnchoring||(this._lastAnchoring=new W);const A=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=A.x,this.gameObject.position.y+=A.y,this._lastAnchoring.copy(this._anchoredPosition),t.x+=this._initialPosition.x-this.gameObject.position.x,t.y+=this._initialPosition.y-this.gameObject.position.y,t.z+=this._initialPosition.z-this.gameObject.position.z;const e=this._parentRectTransform;if(e){let g=0;const I=1-this.anchorMax.y-this.anchorMin.y;g-=e.height*.5*I,t.y+=g;let i=0;const o=1-this.anchorMax.x-this.anchorMin.x;i-=e.width*.5*o,t.x+=i}}applyPivot(t){if(this.pivot&&!this.isRoot()){const A=this.pivot.x-.5;t.x-=A*this.sizeDelta.x*this.gameObject.scale.x;const e=this.pivot.y-.5;t.y-=e*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const t={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:this.offset,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(t),t}ensureValidSize(t,A=1e-4){return t.width<=0&&(t.width=A),t.height<=0&&(t.height=1e-4),t}createNewBlock(t){t={...this.getBasicOptions(),...t},rM&&console.log(this.name,t);const A=new Pm(t);return this._createdBlocks.push(A),A}createNewText(t){rM&&console.log(t),t={...this.getBasicOptions(),...t},rM&&console.log(this.name,t);const A=new kH(t);return this._createdTextBlocks.push(A),A}};let DI=xH;Fr([w(W)],DI.prototype,"anchoredPosition",1),Fr([w(W)],DI.prototype,"sizeDelta",2),Fr([w(W)],DI.prototype,"pivot",2),Fr([w(W)],DI.prototype,"anchorMin",2),Fr([w(W)],DI.prototype,"anchorMax",2),Fr([w(W)],DI.prototype,"offsetMin",2),Fr([w(W)],DI.prototype,"offsetMax",2);class YtA extends fH{constructor(A,e={}){super(A),A._simpleState__activeStates=[],A._simpleState__normalStyles={},A._simpleState__states=e,A._simpleState__statesProperties={};for(const g in e)for(const I in e[g])A._simpleState__statesProperties[I]||(A._simpleState__statesProperties[I]=[]),A._simpleState__statesProperties[I].push(g);for(const g of A._components)A._simpleState__statesProperties[g.id]&&(A._simpleState__normalStyles[g.id]=g.inline?g.inline:g._value);A.__overridedSet=A.set,A.set=this.storeSet.bind(A),A.renderStates=this.renderStates.bind(A),A.setupState=this.setupState.bind(A),A.setState=this.setState.bind(A),A.activatePseudoState=this.activatePseudoState.bind(A),A.deactivatePseudoState=this.deactivatePseudoState.bind(A),A.togglePseudoState=this.togglePseudoState.bind(A)}act(){}attach(){}detach(){}setupState(A,e){this._simpleState__states[A]=e;const g=[];for(const I in e)this._simpleState__statesProperties[I]||(this._simpleState__statesProperties[I]=[],g.push(I)),this._simpleState__statesProperties[I].push(A);for(const I of this._components)g.indexOf(I.id)>-1&&(this._simpleState__normalStyles[I.id]=I.inline?I.inline:I._value)}renderStates(){let A={...this._simpleState__normalStyles};for(const e in this._simpleState__states)this._simpleState__activeStates.indexOf(e)>-1&&(A={...A,...this._simpleState__states[e]});this.set(A,!1)}storeSet(A,e=!0){if(e)for(const g in A)this._simpleState__statesProperties[g]&&(this._simpleState__normalStyles[g]=A[g]);this.__overridedSet(A)}activatePseudoState(A){this._simpleState__activeStates.indexOf(A)===-1&&(this._simpleState__activeStates.push(A),this.renderStates())}deactivatePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1&&(this._simpleState__activeStates.splice(e,1),this.renderStates())}togglePseudoState(A){const e=this._simpleState__activeStates.indexOf(A);e>-1?this._simpleState__activeStates.splice(e,1):this._simpleState__activeStates.push(A),this.renderStates()}setState(A){Array.isArray(A)?this._simpleState__activeStates=A:this._simpleState__activeStates=[A],this.renderStates()}}var HtA=Object.defineProperty,TtA=Object.getOwnPropertyDescriptor,YH=(t,A,e,g)=>{for(var I=g>1?void 0:g?TtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&HtA(A,e,I),I};class VQ extends RA{constructor(){super(...arguments),r(this,"effectColor"),r(this,"effectDistance")}}YH([w(wt)],VQ.prototype,"effectColor",2),YH([w(W)],VQ.prototype,"effectDistance",2);var _tA=Object.defineProperty,OtA=Object.getOwnPropertyDescriptor,HH=(t,A,e,g)=>{for(var I=g>1?void 0:g?OtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&_tA(A,e,I),I};const Dw={backgroundColor:new fA(1,1,1),backgroundOpacity:1,borderColor:new fA(1,1,1),borderOpacity:1};var hM;const ww=(hM=class extends _o{constructor(){super(...arguments),r(this,"_alphaFactor",1),r(this,"raycastTarget",!0),r(this,"uiObject",null),r(this,"_color",null),r(this,"_rect",null),r(this,"_stateManager",null),r(this,"_currentlyCreatingPanel",!1)}get isGraphic(){return!0}get color(){return this._color||(this._color=new wt(1,1,1,1)),this._color}set color(t){(!this._color||this._color.r!==t.r||this._color.g!==t.g||this._color.b!==t.b||this._color.alpha!==t.alpha)&&(this._color||(this._color=new wt(1,1,1,1)),this._color.copy(t))}setAlphaFactor(t){this._alphaFactor=t,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}onColorChanged(){this.uiObject&&(Dw.backgroundColor=this._color,Dw.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(Dw,this._alphaFactor),this.uiObject.set(Dw),this.markDirty())}get m_Color(){return this._color}get rectTransform(){return this._rect||(this._rect=eA.getComponent(this.gameObject,DI)),this._rect}onParentRectTransformChanged(){var t;(t=this.uiObject)==null||t.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(){super.__internalNewInstanceCreated(),this._rect=null,this.uiObject=null,this._color&&(this._color=this._color.clone())}setState(t){this.makePanel(),this.uiObject&&(this.uiObject.setState(t),this==null||this.markDirty())}setupState(t){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new YtA(this.uiObject)),this.uiObject.setupState(t.state,t.attributes))}setOptions(t){this.makePanel(),this.uiObject&&this.uiObject.set(t)}awake(){super.awake(),this.makePanel(),WQ(this,"_color",()=>vtA(this,this.onColorChanged))}onEnable(){var t;super.onEnable(),this.uiObject&&((t=this.rectTransform.shadowComponent)==null||t.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:1};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated()}onBeforeCreate(t){}onCreate(t){this.uiObject=this.rectTransform.createNewBlock(t),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(t,A=1){var e;const g=(e=this.gameObject)==null?void 0:e.getComponent(VQ);g&&(g.effectDistance&&(t.borderWidth=Math.max(Math.abs(g.effectDistance.x),Math.abs(g.effectDistance.y))),g.effectColor&&(t.borderColor=g.effectColor,t.borderOpacity=g.effectColor.alpha*A))}async setTexture(t){if(this.setOptions({backgroundOpacity:0}),t){if(t.encoding===ue)if(ww.textureCache.has(t))t=ww.textureCache.get(t);else{const A=t.clone();A.encoding=Zt,ww.textureCache.set(t,A),t=A}this.setOptions({backgroundImage:t,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"})}else this.setOptions({backgroundImage:null,borderRadius:0,backgroundOpacity:this.color.alpha})}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}},r(hM,"textureCache",new Map),hM);let Nr=ww;HH([w(wt)],Nr.prototype,"color",1),HH([w()],Nr.prototype,"raycastTarget",2);class Cl extends Nr{constructor(){super(...arguments),r(this,"_flippedObject",!1)}onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var PtA=Object.defineProperty,jtA=Object.getOwnPropertyDescriptor,yw=(t,A,e,g)=>{for(var I=g>1?void 0:g?jtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&PtA(A,e,I),I};let cM=class{constructor(){r(this,"texture",null),r(this,"rect")}};yw([w(Ye)],cM.prototype,"texture",2);let zQ=class extends Cl{constructor(){super(...arguments),r(this,"_sprite"),r(this,"pixelsPerUnitMultiplier",1)}set image(t){this.sprite?this.sprite.texture=t:(this.sprite=new cM,this.sprite.texture=t),this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(t){this._sprite!==t&&(this._sprite=t,this.onAfterCreated())}isBuiltinSprite(){var t,A,e,g,I,i,o,C;switch((A=(t=this.sprite)==null?void 0:t.texture)==null?void 0:A.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return((I=(g=(e=this.sprite)==null?void 0:e.texture)==null?void 0:g.image)==null?void 0:I.width)===32&&((C=(o=(i=this.sprite)==null?void 0:i.texture)==null?void 0:o.image)==null?void 0:C.height)===32}onBeforeCreate(t){var A,e;super.onBeforeCreate(t),this.isBuiltinSprite()&&(t.borderRadius=5/this.pixelsPerUnitMultiplier,((e=(A=this.sprite)==null?void 0:A.texture)==null?void 0:e.name)==="Knob"&&(t.borderRadius=999))}onAfterCreated(){var t;this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture((t=this.sprite)==null?void 0:t.texture))}};yw([w(cM)],zQ.prototype,"sprite",1),yw([w()],zQ.prototype,"pixelsPerUnitMultiplier",2);class Sw extends Cl{constructor(){super(...arguments),r(this,"_mainTexture")}get mainTexture(){return this._mainTexture}set mainTexture(A){this._mainTexture!==A&&(this._mainTexture=A,this.onAfterCreated())}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}yw([w(Ye)],Sw.prototype,"mainTexture",1);var WtA=Object.defineProperty,VtA=Object.getOwnPropertyDescriptor,Mi=(t,A,e,g)=>{for(var I=g>1?void 0:g?VtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&WtA(A,e,I),I};const ZQ=aA("debugbutton");class Kr{constructor(){r(this,"colorMultiplier"),r(this,"disabledColor"),r(this,"fadeDuration"),r(this,"highlightedColor"),r(this,"normalColor"),r(this,"pressedColor"),r(this,"selectedColor")}}Mi([w()],Kr.prototype,"colorMultiplier",2),Mi([w(wt)],Kr.prototype,"disabledColor",2),Mi([w()],Kr.prototype,"fadeDuration",2),Mi([w(wt)],Kr.prototype,"highlightedColor",2),Mi([w(wt)],Kr.prototype,"normalColor",2),Mi([w(wt)],Kr.prototype,"pressedColor",2),Mi([w(wt)],Kr.prototype,"selectedColor",2);class xs extends RA{constructor(){super(...arguments),r(this,"onClick"),r(this,"_isHovered",!1),r(this,"colors"),r(this,"transition"),r(this,"animationTriggers"),r(this,"animator"),r(this,"_interactable",!0),r(this,"_requestedAnimatorTrigger"),r(this,"_isInit",!1),r(this,"_image")}onPointerEnter(A){var e,g;ZQ&&console.log("Button Enter",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this._isHovered=!0,this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState("hovered")),this.context.input.setCursorPointer())}onPointerExit(){var A,e;ZQ&&console.log("Button Exit",(A=this.animationTriggers)==null?void 0:A.highlightedTrigger,this.animator),this._isHovered=!1,this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((e=this._image)==null||e.setState("normal")),this.context.input.setCursorNormal())}onPointerDown(A){var e,g;ZQ&&console.log("Button Down",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState("pressed")))}onPointerUp(A){var e,g;ZQ&&console.warn("Button Up",(e=this.animationTriggers)==null?void 0:e.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&((g=this._image)==null||g.setState(this._isHovered?"hovered":"normal")))}onPointerClick(A){var e;this.interactable&&(ZQ&&(console.warn("Button Click",this.onClick),Hg("CLICKED button "+this.name+" at "+this.context.time.frameCount)),(e=this.onClick)==null||e.invoke())}set interactable(A){this._interactable=A,this._image&&(this._image.setInteractable(A),A?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}set_interactable(A){this.interactable=A}awake(){super.awake(),ZQ&&console.log(this),this._isInit=!1,this.init()}start(){var A;(A=this._image)==null||A.setInteractable(this.interactable)}onEnable(){super.onEnable()}*setAnimatorTriggerAtEndOfFrame(A){var e;this._requestedAnimatorTrigger=A,yield,yield,this._requestedAnimatorTrigger==A&&((e=this.animator)==null||e.SetTrigger(A))}init(){this._isInit||(this._isInit=!0,this._image=eA.getComponent(this.gameObject,zQ),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(A){var e,g,I,i,o;A.setInteractable(this.interactable);const C=this.getFinalColor(A.color,(e=this.colors)==null?void 0:e.normalColor),s={state:"normal",attributes:{backgroundColor:C,backgroundOpacity:C.alpha}};A.setupState(s);const a=this.getFinalColor(A.color,(g=this.colors)==null?void 0:g.highlightedColor),n={state:"hovered",attributes:{backgroundColor:a,backgroundOpacity:a.alpha}};A.setupState(n);const B=this.getFinalColor(A.color,(I=this.colors)==null?void 0:I.pressedColor),Q={state:"pressed",attributes:{backgroundColor:B,backgroundOpacity:B.alpha}};A.setupState(Q);const E=this.getFinalColor(A.color,(i=this.colors)==null?void 0:i.selectedColor),h={state:"selected",attributes:{backgroundColor:E,backgroundOpacity:E.alpha}};A.setupState(h);const c=this.getFinalColor(A.color,(o=this.colors)==null?void 0:o.disabledColor),l={state:"disabled",attributes:{backgroundColor:c,backgroundOpacity:c.alpha}};A.setupState(l)}getFinalColor(A,e){return e?A.clone().multiply(e):A.clone()}}Mi([w(ti)],xs.prototype,"onClick",2),Mi([w()],xs.prototype,"colors",2),Mi([w()],xs.prototype,"transition",2),Mi([w()],xs.prototype,"animationTriggers",2),Mi([w(Ai)],xs.prototype,"animator",2),Mi([w()],xs.prototype,"interactable",1);var ztA=Object.defineProperty,ZtA=Object.getOwnPropertyDescriptor,pg=(t,A,e,g)=>{for(var I=g>1?void 0:g?ZtA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&ztA(A,e,I),I};const TH=aA("debuguilayout");class sn{constructor(){r(this,"left",0),r(this,"right",0),r(this,"top",0),r(this,"bottom",0)}get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}pg([w()],sn.prototype,"left",2),pg([w()],sn.prototype,"right",2),pg([w()],sn.prototype,"top",2),pg([w()],sn.prototype,"bottom",2);class Ri extends RA{constructor(){super(...arguments),r(this,"_rectTransform",null),r(this,"_needsUpdate",!1),r(this,"childAlignment",0),r(this,"reverseArrangement",!1),r(this,"spacing",0),r(this,"padding"),r(this,"minWidth",0),r(this,"minHeight",0),r(this,"flexibleHeight",0),r(this,"flexibleWidth",0),r(this,"preferredHeight",0),r(this,"preferredWidth",0)}get rectTransform(){return this._rectTransform}onParentRectTransformChanged(A){this._needsUpdate=!0}get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(TH&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}start(){this._needsUpdate=!0}onEnable(){TH&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(DI);const A=this.gameObject.getComponentInParent(wI);A&&A.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const A=this.gameObject.getComponentInParent(wI);A&&A.unregisterLayoutGroup(this)}set m_Spacing(A){A!==this.spacing&&(this._needsUpdate=!0,this.spacing=A)}get m_Spacing(){return this.spacing}}pg([w()],Ri.prototype,"childAlignment",2),pg([w()],Ri.prototype,"reverseArrangement",2),pg([w()],Ri.prototype,"spacing",2),pg([w(sn)],Ri.prototype,"padding",2),pg([w()],Ri.prototype,"minWidth",2),pg([w()],Ri.prototype,"minHeight",2),pg([w()],Ri.prototype,"flexibleHeight",2),pg([w()],Ri.prototype,"flexibleWidth",2),pg([w()],Ri.prototype,"preferredHeight",2),pg([w()],Ri.prototype,"preferredWidth",2);class an extends Ri{constructor(){super(...arguments),r(this,"childControlHeight",!0),r(this,"childControlWidth",!0),r(this,"childForceExpandHeight",!1),r(this,"childForceExpandWidth",!1),r(this,"childScaleHeight",!1),r(this,"childScaleWidth",!1)}onCalculateLayout(A){var e;const g=this.primaryAxis,I=A.width;let i=I;const o=A.height;let C=o;i-=this.padding.horizontal,C-=this.padding.vertical,g==="x"?this.padding.horizontal:this.padding.vertical;const s=g==="x",a=s?"y":"x",n=s?this.childControlWidth:this.childControlHeight,B=s?this.childControlHeight:this.childControlWidth,Q=s?this.childForceExpandWidth:this.childForceExpandHeight,E=s?this.childForceExpandHeight:this.childForceExpandWidth,h=s?C:i,c=s?I:o,l=.5*(s?this.childAlignment%3:Math.floor(this.childAlignment/3));let d=0;s?d+=this.padding.left:d+=this.padding.top;let u=0,p=0;for(let S=0;S<this.gameObject.children.length;S++){const U=this.gameObject.children[S],M=eA.getComponent(U,DI);M!=null&&M.activeAndEnabled&&(p+=1,s?u+=M.width:u+=M.height)}let D=0;const y=this.spacing*(p-1);if(Q||n){let S=0;s?S=i-=y:S=C-=y,p>0&&(D=S/p)}let k=0;k+=this.padding.left,k-=this.padding.right,l!==0&&(d=c-u,d*=l,d-=y*l,s?(d-=this.padding.right*l,d+=this.padding.left*(1-l),d<this.padding.left&&(d=this.padding.left)):(d-=this.padding.bottom*l,d+=this.padding.top*(1-l),d<this.padding.top&&(d=this.padding.top)));let F=1;for(let S=0;S<this.gameObject.children.length;S++){const U=this.gameObject.children[S],M=eA.getComponent(U,DI);if(M!=null&&M.activeAndEnabled){(e=M.pivot)==null||e.set(.5,.5),M.anchorMin.set(0,1),M.anchorMax.set(0,1);const Y=I*.5+k*.5;M.anchoredPosition.x!==Y&&(M.anchoredPosition.x=Y);const _=o*-.5;M.anchoredPosition.y!==_&&(M.anchoredPosition.y=_),E&&B&&M.sizeDelta[a]!==h&&(M.sizeDelta[a]=h),Q&&n&&M.sizeDelta[g]!==D&&(M.sizeDelta[g]=D);const x=s?M.width:M.height;let v=x*.5;if(d+=v,Q){let gA=D*F-D*.5;gA>d&&(d=gA-D*.5+x+this.padding.left,d-=v)}let z=d;g==="y"&&(z=-z),M.anchoredPosition[g]!==z&&(M.anchoredPosition[g]=z),d+=v,d+=this.spacing,F+=1}}}}pg([w()],an.prototype,"childControlHeight",2),pg([w()],an.prototype,"childControlWidth",2),pg([w()],an.prototype,"childForceExpandHeight",2),pg([w()],an.prototype,"childForceExpandWidth",2),pg([w()],an.prototype,"childScaleHeight",2),pg([w()],an.prototype,"childScaleWidth",2);class lM extends an{get primaryAxis(){return"y"}}class dM extends an{get primaryAxis(){return"x"}}class pM extends Ri{onCalculateLayout(){}}var XtA=Object.defineProperty,$tA=Object.getOwnPropertyDescriptor,yC=(t,A,e,g)=>{for(var I=g>1?void 0:g?$tA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&XtA(A,e,I),I};const uM=aA("debuguilayout"),_H=class extends vc{constructor(){super(...arguments),r(this,"_renderOnTop"),r(this,"_depthWrite",!1),r(this,"_doubleSided",!0),r(this,"_castShadows",!1),r(this,"_receiveShadows",!1),r(this,"_renderMode",-1),r(this,"_rootCanvas"),r(this,"_scaleFactor",1),r(this,"worldCamera"),r(this,"planeDistance",-1),r(this,"_boundRenderSettingsChanged",this.onRenderSettingsChanged.bind(this)),r(this,"previousParent",null),r(this,"_lastMatrixWorld",null),r(this,"_rectTransforms",[]),r(this,"_layoutGroups",new Map),r(this,"onBeforeRenderRoutine",()=>{var t,A;this.previousParent=this.gameObject.parent,this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),(t=this.shadowComponent)==null||t.updateMatrixWorld(!0),(A=this.shadowComponent)==null||A.updateWorldMatrix(!0,!0),io.ensureUpdateMeshUI(mH,this.context))}),r(this,"onAfterRenderRoutine",()=>{var t,A;if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){if(this.screenspace){const e=this.context.mainCamera;e?.add(this.gameObject)}else this.previousParent.add(this.gameObject);this.context.renderer.autoClear=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),(t=this.shadowComponent)==null||t.updateMatrixWorld(!0),io.ensureUpdateMeshUI(mH,this.context),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=!0,this.previousParent.add(this.gameObject)}(A=this._lastMatrixWorld)==null||A.copy(this.gameObject.matrixWorld)}),r(this,"_updateRenderSettingsRoutine"),r(this,"_activeRenderMode",-1),r(this,"_lastWidth",-1),r(this,"_lastHeight",-1)}get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(t){t!==this._renderOnTop&&(this._renderOnTop=t,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}set depthWrite(t){this._depthWrite!==t&&(this._depthWrite=t,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}set doubleSided(t){this._doubleSided!==t&&(this._doubleSided=t,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}set castShadows(t){this._castShadows!==t&&(this._castShadows=t,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}set receiveShadows(t){this._receiveShadows!==t&&(this._receiveShadows=t,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}get renderMode(){return this._renderMode}set renderMode(t){this._renderMode!==t&&(this._renderMode=t,this.onRenderSettingsChanged())}set rootCanvas(t){this._rootCanvas instanceof _H||(this._rootCanvas=t)}get rootCanvas(){return this._rootCanvas}get scaleFactor(){return this._scaleFactor}set scaleFactor(t){this._scaleFactor=t}awake(){var t;this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,uM&&console.log("Canvas.Awake()",((t=this.previousParent)==null?void 0:t.name)+"/"+this.gameObject.name),super.awake()}start(){this.onUpdateRenderMode()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new TA,this.onUpdateRenderMode(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);t!==-1&&this.context.pre_render_callbacks.splice(t,1);const A=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);A!==-1&&this.context.post_render_callbacks.splice(A,1)}registerTransform(t){this._rectTransforms.push(t)}unregisterTransform(t){const A=this._rectTransforms.indexOf(t);A!==-1&&this._rectTransforms.splice(A,1)}registerLayoutGroup(t){const A=t.gameObject;this._layoutGroups.set(A,t)}unregisterLayoutGroup(t){const A=t.gameObject;this._layoutGroups.delete(A)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new TA);const t=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);uM&&t&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);let A=!1;for(const e of this._rectTransforms){t&&e.markDirty();let g=this._layoutGroups.get(e.gameObject);e.isDirty&&!g&&(g=e.gameObject.getComponentInParent(Ri)),(e.isDirty||g!=null&&g.isDirty)&&(uM&&!A&&console.log("CANVAS UPDATE ### "+e.name+" ##################################### "+this.context.time.frame),g?.updateLayout(),e.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),ki.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),pw(this.shadowComponent,this);for(const t of eA.getComponentsInChildren(this.gameObject,_o))pw(t.shadowComponent,this)}}onUpdateRenderMode(t=!1){if(!t&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let A=this.context.mainCameraComponent,e=10;switch(A&&A.nearClipPlane>0&&A.farClipPlane>0&&(e=XA.lerp(A.nearClipPlane,A.farClipPlane,.15)),this._renderMode===1&&(this.worldCamera&&(A=this.worldCamera),this.planeDistance>0&&(e=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!A)return;const g=e+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-g,this.gameObject.quaternion.identity();const I=this.gameObject.getComponent(DI);let i=!1;I.sizeDelta.x!==this.context.domWidth&&(i=!0),I.sizeDelta.y!==this.context.domHeight&&(i=!0);const o=A.fieldOfView*Math.PI/180,C=2*Math.tan(o/2)*Math.abs(g);this.gameObject.scale.x=C/this.context.domHeight,this.gameObject.scale.y=C/this.context.domHeight,this.gameObject.scale.z=.01,i&&(I.sizeDelta.x=this.context.domWidth,I.sizeDelta.y=this.context.domHeight,I?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};let wI=_H;yC([w()],wI.prototype,"renderOnTop",1),yC([w()],wI.prototype,"depthWrite",1),yC([w()],wI.prototype,"doubleSided",1),yC([w()],wI.prototype,"castShadows",1),yC([w()],wI.prototype,"receiveShadows",1),yC([w()],wI.prototype,"renderMode",1),yC([w(wI)],wI.prototype,"rootCanvas",1),yC([w()],wI.prototype,"scaleFactor",1),yC([w(Kt)],wI.prototype,"worldCamera",2),yC([w()],wI.prototype,"planeDistance",2);var AgA=Object.defineProperty,egA=Object.getOwnPropertyDescriptor,DM=(t,A,e,g)=>{for(var I=g>1?void 0:g?egA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&AgA(A,e,I),I};class XQ extends RA{constructor(){super(...arguments),r(this,"_alpha",1),r(this,"interactable",!0),r(this,"blocksRaycasts",!0),r(this,"_isDirty",!1),r(this,"_buffer",[])}get alpha(){return this._alpha}set alpha(A){A!==this._alpha&&(this._alpha=A,this.markDirty())}get isCanvasGroup(){return!0}markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),ki.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}applyChangesNow(){for(const A of eA.getComponentsInChildren(this.gameObject,_o,this._buffer)){const e=A;e.setAlphaFactor&&e.setAlphaFactor(this._alpha)}}}DM([w()],XQ.prototype,"alpha",1),DM([w()],XQ.prototype,"interactable",2),DM([w()],XQ.prototype,"blocksRaycasts",2);var tgA=Object.defineProperty,ggA=Object.getOwnPropertyDescriptor,Jt=(t,A,e,g)=>{for(var I=g>1?void 0:g?ggA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&tgA(A,e,I),I};class Jr extends RA{constructor(){super(...arguments),r(this,"object"),r(this,"target"),r(this,"duration",1),r(this,"relativeMotion",!1),r(this,"coroutine",null),r(this,"targetPos",new f),r(this,"targetRot",new GA),r(this,"targetScale",new f)}*moveToTarget(){if(!this.target||!this.object)return;const A=ye(this.object).clone(),e=ye(this.target).clone(),g=Ng(this.object).clone(),I=Ng(this.target).clone(),i=zg(this.object).clone(),o=zg(this.target).clone(),C=A.distanceTo(e),s=g.angleTo(I),a=i.distanceTo(o);if(C<.01&&s<.01&&a<.01){tg(this.object,e),zI(this.object,I),jf(this.object,o),this.coroutine=null;return}let n=0,B=0;for(;n<1;)n+=this.context.time.deltaTime/this.duration,n>1&&(n=1),B=n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2,this.targetPos.lerpVectors(A,e,B),this.targetRot.slerpQuaternions(g,I,B),this.targetScale.lerpVectors(i,o,B),tg(this.object,this.targetPos),zI(this.object,this.targetRot),jf(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const A=this.object.position.clone(),e=this.object.quaternion.clone(),g=this.object.scale.clone(),I=this.target.position.clone(),i=this.target.quaternion.clone(),o=this.target.scale.clone();I.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(I),this.targetRot.copy(this.object.quaternion).multiply(i),this.targetScale.copy(this.object.scale).multiply(o);let C=0,s=0;for(;C<1;)C+=this.context.time.deltaTime/this.duration,C>1&&(C=1),s=C<.5?4*C*C*C:1-Math.pow(-2*C+2,3)/2,this.object.position.lerpVectors(A,this.targetPos,s),this.object.quaternion.slerpQuaternions(e,this.targetRot,s),this.object.scale.lerpVectors(g,this.targetScale,s),yield;this.coroutine=null}onPointerClick(){this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}beforeCreateDocument(A){var e;if(this.target&&this.object&&this.gameObject){const g=new LI("Move to "+((e=this.target)==null?void 0:e.name),gi.tapTrigger(this.gameObject),at.transformAction(this.object,this.target,this.duration,this.relativeMotion?VG.Relative:VG.Absolute));A.addBehavior(g)}}}Jt([w(UA)],Jr.prototype,"object",2),Jt([w(UA)],Jr.prototype,"target",2),Jt([w()],Jr.prototype,"duration",2),Jt([w()],Jr.prototype,"relativeMotion",2);var wM;const $Q=(wM=class extends RA{constructor(){super(...arguments),r(this,"materialToSwitch"),r(this,"variantMaterial"),r(this,"_objectsWithThisMaterial",[]),r(this,"selfModel"),r(this,"targetModels",[])}awake(){if(this.variantMaterial&&this.materialToSwitch){const t=eA.findObjectsOfType(jt);for(const A of t)A.sharedMaterial===this.materialToSwitch&&this._objectsWithThisMaterial.push(A)}}onPointerClick(){if(this.variantMaterial)for(const t of this._objectsWithThisMaterial)t.sharedMaterial=this.variantMaterial}createBehaviours(t,A,e){this._objectsWithThisMaterial.find(g=>g.gameObject.uuid===A.uuid)&&this.targetModels.push(A),this.gameObject.uuid===A.uuid&&(this.selfModel=A,this.materialToSwitch&&($Q._materialTriggersPerId[this.materialToSwitch.uuid]||($Q._materialTriggersPerId[this.materialToSwitch.uuid]=[]),$Q._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(t,A){if(!this.materialToSwitch)return;const e=$Q._materialTriggersPerId[this.materialToSwitch.uuid];if(e){const g={};for(const i of e){const o=i.createVariants();o&&o.length>0&&(g[i.selfModel.uuid]=o)}const I=[];for(const i of e){for(const o in g)o!==i.selfModel.uuid&&I.push(g[o]);i.createAndAttachBehaviors(t,g[i.selfModel.uuid],I)}}delete $Q._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(t,A,e){const g=[],I=[];for(const i of this.targetModels){const o=at.fadeAction(i,0,!1);I.push(o)}for(const i of e)I.push(at.fadeAction(i,0,!1));for(const i of A)g.push(at.fadeAction(i,0,!1)),I.push(at.fadeAction(i,0,!0));t.addBehavior(new LI("Select "+this.selfModel.name,gi.tapTrigger(this.selfModel),at.parallel(...I))),t.addBehavior(new LI("Start hidden "+this.selfModel.name,gi.sceneStartTrigger(),at.parallel(...g)))}createVariants(){if(!this.variantMaterial)return null;const t=[];for(const A of this.targetModels){const e=A.clone();e.name+=" variant_"+this.variantMaterial.name,e.name=e.name.replace(/\s/g,"_"),e.material=this.variantMaterial,e.geometry=A.geometry,e.matrix=A.matrix,(!A.parent||!A.parent.isEmpty())&&BC.createEmptyParent(A),A.parent&&A.parent.add(e),t.push(e)}return t}},r(wM,"_materialTriggersPerId",{}),wM);let sl=$Q;Jt([w(Ue)],sl.prototype,"materialToSwitch",2),Jt([w(Ue)],sl.prototype,"variantMaterial",2);class AE extends RA{constructor(){super(...arguments),r(this,"target"),r(this,"toggleOnClick",!1),r(this,"targetState",!0),r(this,"hideSelf",!0),r(this,"selfModel"),r(this,"otherModel"),r(this,"toggleModel"),r(this,"stateBeforeCreatingDocument",!1)}onPointerClick(){!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}createBehaviours(A,e,g){e.uuid===this.gameObject.uuid&&(this.selfModel=e)}beforeCreateDocument(){this.stateBeforeCreatingDocument=this.gameObject.visible,this.gameObject.visible=!0}afterCreateDocument(A,e){if(this.target){if(this.otherModel=e.document.findById(this.target.uuid),this.selfModel&&this.otherModel){let g=this.hideSelf;this.targetState,this.toggleOnClick&&(g=!0,this.target.visible,(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&ux.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.clone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel));const I=[];if(g&&I.push(at.fadeAction(this.selfModel,0,!1)),this.toggleModel&&I.push(at.fadeAction(this.toggleModel,0,!0)),I.push(at.fadeAction(this.otherModel,0,this.targetState)),A.addBehavior(new LI("Toggle_"+this.selfModel.name+"_hideSelf",gi.tapTrigger(this.selfModel),at.sequence(...I))),this.toggleOnClick&&this.toggleModel){const i=[];i.push(at.fadeAction(this.toggleModel,0,!1)),i.push(at.fadeAction(this.selfModel,0,!0)),i.push(at.fadeAction(this.otherModel,0,!this.targetState)),A.addBehavior(new LI("Toggle_"+this.selfModel.name+"_toggleSelf",gi.tapTrigger(this.toggleModel),at.sequence(...i))),A.addBehavior(new LI("HideOnStart_"+this.gameObject.name,gi.sceneStartTrigger(),at.fadeAction(this.toggleModel,0,!1)))}}this.gameObject.visible=this.stateBeforeCreatingDocument}}}Jt([w(UA)],AE.prototype,"target",2),Jt([w()],AE.prototype,"targetState",2),Jt([w()],AE.prototype,"hideSelf",2);class yM extends RA{start(){this.gameObject.visible=!1}createBehaviours(A,e,g){e.uuid===this.gameObject.uuid&&A.addBehavior(new LI("HideOnStart_"+this.gameObject.name,gi.sceneStartTrigger(),at.fadeAction(e,0,!1)))}beforeCreateDocument(){this.gameObject.visible=!0}afterCreateDocument(){this.gameObject.visible=!1}}class eE extends RA{constructor(){super(...arguments),r(this,"target"),r(this,"duration",.5),r(this,"motionType",WG.bounce)}beforeCreateDocument(){}createBehaviours(A,e,g){if(this.target&&e.uuid===this.gameObject.uuid){const I=new LI("emphasize "+this.name,gi.tapTrigger(this.gameObject),at.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));A.addBehavior(I)}}afterCreateDocument(A,e){}}Jt([w()],eE.prototype,"target",2),Jt([w()],eE.prototype,"duration",2),Jt([w()],eE.prototype,"motionType",2);class tE extends RA{constructor(){super(...arguments),r(this,"target"),r(this,"clip",""),r(this,"toggleOnClick",!1)}onPointerClick(){if(!(!this.target&&!this.clip)){if(!this.target){const A=this.gameObject.addNewComponent(hg);A&&(A.spatialBlend=1,A.volume=1,A.loop=!1,this.target=A)}this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play()))}}createBehaviours(A,e,g){if(!(!this.target&&!this.clip)&&e.uuid===this.gameObject.uuid){const I=this.clip?this.clip:this.target?this.target.clip:void 0;if(!I)return;const i=this.target?this.target.gameObject:this.gameObject,o=I.split("/").pop(),C=this.target?this.target.volume:1,s=this.target&&this.target.spatialBlend==0?ZG.NonSpatial:ZG.Spatial,a=new LI("playAudio "+this.name,gi.tapTrigger(this.gameObject),at.playAudioAction(i,"audio/"+o,Nx.Play,C,s));A.addBehavior(a)}}async afterSerialize(A,e){if(!this.target&&!this.clip)return;const g=this.clip?this.clip:this.target?this.target.clip:void 0;if(!g)return;const I=g.split("/").pop(),i=await(await(await fetch(this.clip)).blob()).arrayBuffer(),o=new Uint8Array(i);e.files["audio/"+I]=o}}Jt([w(hg)],tE.prototype,"target",2),Jt([w(URL)],tE.prototype,"clip",2),Jt([w()],tE.prototype,"toggleOnClick",2);var SM;const gE=(SM=class extends RA{constructor(){super(...arguments),r(this,"target"),r(this,"animator"),r(this,"stateName"),r(this,"stateNameAfterPlaying"),r(this,"loopAfterPlaying",!1),r(this,"selfModel"),r(this,"stateAnimationModel"),r(this,"stateAnimation"),r(this,"stateAfterPlayingAnimationModel"),r(this,"stateAfterPlayingAnimation")}onPointerClick(){var t;this.target&&this.stateName&&((t=this.animator)==null||t.play(this.stateName,0,0,.1))}createBehaviours(t,A,e){A.uuid===this.gameObject.uuid&&(this.selfModel=A)}onAfterHierarchy(){gE.animationActions=[]}afterCreateDocument(t,A){!this.stateAnimation||!this.stateAnimationModel||A.document.traverse(e=>{var g,I;if(e.uuid===((g=this.target)==null?void 0:g.uuid)&&this.stateAnimation){const i=[];let o=gE.animationActions.find(s=>s.affectedObjects==e&&s.start==this.stateAnimation.start&&s.duration==this.stateAnimation.duration);if(o||(o=at.startAnimationAction(e,this.stateAnimation.start,this.stateAnimation.duration),gE.animationActions.push(o)),i.push(o),this.stateAfterPlayingAnimation&&this.stateAfterPlayingAnimationModel){let s=gE.animationActions.find(n=>n.affectedObjects==e&&n.start==this.stateAfterPlayingAnimation.start&&n.duration==this.stateAfterPlayingAnimation.duration);s||(s=at.startAnimationAction(e,this.stateAfterPlayingAnimation.start,this.stateAfterPlayingAnimation.duration),gE.animationActions.push(s));const a=at.sequence(s);this.loopAfterPlaying&&a.makeLooping(),i.push(a)}const C=new LI("tap "+this.name+" for "+this.stateName+" on "+((I=this.target)==null?void 0:I.name),gi.tapTrigger(this.selfModel),at.sequence(...i));t.addBehavior(C)}})}createAnimation(t,A,e){var g,I,i,o;if(this.target&&this.animator){const C=(I=(g=this.animator)==null?void 0:g.runtimeAnimatorController)==null?void 0:I.findState(this.stateName);this.stateAnimationModel=A,this.stateAnimation=t.registerAnimation(this.target,C?.motion.clip);const s=(o=(i=this.animator)==null?void 0:i.runtimeAnimatorController)==null?void 0:o.findState(this.stateNameAfterPlaying);this.stateAfterPlayingAnimationModel=A,this.stateAfterPlayingAnimation=t.registerAnimation(this.target,s?.motion.clip)}}},r(SM,"animationActions",[]),SM);let nn=gE;Jt([w(UA)],nn.prototype,"target",2),Jt([w(Ai)],nn.prototype,"animator",2),Jt([w()],nn.prototype,"stateName",2),Jt([w()],nn.prototype,"stateNameAfterPlaying",2),Jt([w()],nn.prototype,"loopAfterPlaying",2);class IE extends RA{constructor(){super(...arguments),r(this,"target")}getType(){}getDuration(){}}Jt([w(UA)],IE.prototype,"target",2);class al extends RA{constructor(){super(...arguments),r(this,"target")}}Jt([w(IE)],al.prototype,"target",2);class nl extends IE{constructor(){super(...arguments),r(this,"type",1),r(this,"duration",1)}getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Jt([w()],nl.prototype,"type",2),Jt([w()],nl.prototype,"duration",2);class fM extends al{}var IgA=Object.defineProperty,igA=Object.getOwnPropertyDescriptor,Ys=(t,A,e,g)=>{for(var I=g>1?void 0:g?igA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&IgA(A,e,I),I};class qr extends RA{constructor(){super(...arguments),r(this,"center",new f(0,0,0)),r(this,"radius",.5),r(this,"height",2),r(this,"_rigidbody",null),r(this,"_activeGroundCollisions",new Set)}get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Ht),this._rigidbody||(this._rigidbody=this.gameObject.addNewComponent(Ht)),this.rigidbody)}onEnable(){let A=this.rigidbody,e=this.gameObject.getComponent(Cn);e||(e=this.gameObject.addNewComponent(Cn)),e.center.copy(this.center),e.radius=this.radius,e.height=this.height,this.gameObject.rotation.x=0,this.gameObject.rotation.z=0,A.lockRotationX=!0,A.lockRotationY=!0,A.lockRotationZ=!0}move(A){this.gameObject.position.add(A)}onCollisionEnter(A){for(const e of A.contacts)if(e.normal.y>.1){this._activeGroundCollisions.add(A);break}}onCollisionExit(A){this._activeGroundCollisions.delete(A)}get isGrounded(){return this._activeGroundCollisions.size>0}}Ys([w(f)],qr.prototype,"center",2),Ys([w()],qr.prototype,"radius",2),Ys([w()],qr.prototype,"height",2);class Hs extends RA{constructor(){super(...arguments),r(this,"controller"),r(this,"movementSpeed",2),r(this,"rotationSpeed",2),r(this,"jumpForce",1),r(this,"doubleJumpForce",2),r(this,"animator"),r(this,"lookForward",!0),r(this,"_currentSpeed",new f(0,0,0)),r(this,"_currentAngularSpeed",new f(0,0,0)),r(this,"_temp",new f(0,0,0)),r(this,"_jumpCount",0),r(this,"_currentRotation"),r(this,"_raycastOptions",new Go)}awake(){this._currentRotation=new GA}update(){var A,e,g,I,i,o,C,s,a,n,B;(A=this.controller)!=null&&A.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&((e=this.animator)==null||e.setBool("doubleJump",!1)));const Q=this.context.input.isKeyPressed("w"),E=this.context.input.isKeyPressed("s"),h=this.context.input.isKeyPressed("a"),c=this.context.input.isKeyPressed("d"),l=this.context.input.isKeyDown(" "),d=(Q?1:0)+(E?-1:0);this._currentSpeed.z+=d*this.movementSpeed*this.context.time.deltaTime,(g=this.animator)==null||g.setBool("running",d!=0),(i=this.animator)==null||i.setBool("jumping",((I=this.controller)==null?void 0:I.isGrounded)===!0&&l),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp);const u=(h?1:0)+(c?-1:0);if(this._currentAngularSpeed.y+=XA.toRadians(u*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const p=this.context.mainCameraComponent.forward;p.y=0,p.normalize(),this._currentRotation.setFromUnitVectors(new f(0,0,1),p),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&&l&&this.jumpForce>0){let p=(o=this.controller)==null?void 0:o.isGrounded;if(this.doubleJumpForce>0&&!((C=this.controller)!=null&&C.isGrounded)&&this._jumpCount===1&&(p=!0,(s=this.animator)==null||s.setBool("doubleJump",!0)),p){this._jumpCount+=1;const D=this.controller.rigidbody,y=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;D.applyImpulse(new f(0,1,0).multiplyScalar(y))}}if(this.controller){const p=(a=this.controller)==null?void 0:a.rigidbody.getVelocity().y;if(p<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new As),this._raycastOptions.ray.origin.copy(ye(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const D=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const y=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(D),(y.length&&y[0].distance>2||p<-10)&&((n=this.animator)==null||n.setBool("falling",!0))}else(B=this.animator)==null||B.setBool("falling",!1)}}}Ys([w(qr)],Hs.prototype,"controller",2),Ys([w()],Hs.prototype,"movementSpeed",2),Ys([w()],Hs.prototype,"rotationSpeed",2),Ys([w()],Hs.prototype,"jumpForce",2),Ys([w()],Hs.prototype,"doubleJumpForce",2),Ys([w(Ai)],Hs.prototype,"animator",2);var ogA=Object.defineProperty,CgA=Object.getOwnPropertyDescriptor,sgA=(t,A,e,g)=>{for(var I=g>1?void 0:g?CgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&ogA(A,e,I),I};class rl extends TI{constructor(){super(...arguments),r(this,"intensity")}get typeName(){return"ChromaticAberration"}init(){this.intensity.defaultValue=0}onCreateEffect(){const A=new _b;return A.offset=new W(0,0),A.radialModulation=!0,A.modulationOffset=.15,this.intensity.valueProcessor=e=>e*.02,this.intensity.onValueChanged=e=>{A.offset.x=-e,A.offset.y=e},A}}sgA([w(qe)],rl.prototype,"intensity",2),uC("ChromaticAberration",rl);var agA=Object.defineProperty,ngA=Object.getOwnPropertyDescriptor,fw=(t,A,e,g)=>{for(var I=g>1?void 0:g?ngA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&agA(A,e,I),I};class rn extends TI{constructor(){super(...arguments),r(this,"postExposure"),r(this,"contrast"),r(this,"hueShift"),r(this,"saturation")}get typeName(){return"ColorAdjustments"}init(){this.postExposure.valueProcessor=A=>(A=Math.pow(2,A),A),this.postExposure.defaultValue=0,this.contrast.valueProcessor=A=>{let e=1;return A>0?e=200:A<0&&(e=100),A/e},this.contrast.defaultValue=0,this.hueShift.valueProcessor=A=>Math.PI*A/180,this.hueShift.defaultValue=0,this.saturation.valueProcessor=A=>A<0?A/100:A/(100*Math.PI),this.saturation.defaultValue=0}unapply(){this.context.renderer.toneMappingExposure=1}onCreateEffect(){this.context.renderer.toneMapping===GI&&this.postExposure.overrideState&&(this.context.renderer.toneMapping=VE);const A=new Tb;this.postExposure.onValueChanged=g=>{this.context.renderer.toneMapping===GI&&(this.context.renderer.toneMapping=VE),this.context.renderer.toneMappingExposure=g},this.contrast.onValueChanged=g=>{A.contrast=g};const e=new Pb;return this.hueShift.onValueChanged=g=>e.hue=g,this.saturation.onValueChanged=g=>e.saturation=g,[e,A]}}fw([w(qe)],rn.prototype,"postExposure",2),fw([w(qe)],rn.prototype,"contrast",2),fw([w(qe)],rn.prototype,"hueShift",2),fw([w(qe)],rn.prototype,"saturation",2),uC("ColorAdjustments",rn);const rgA=(Math.sqrt(5)-1)/4,tI=(5-Math.sqrt(5))/20,kw=t=>Math.floor(t)|0,Gw=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]);function BgA(t=Math.random){const A=QgA(t),e=new Float64Array(A).map(o=>Gw[o%32*4]),g=new Float64Array(A).map(o=>Gw[o%32*4+1]),I=new Float64Array(A).map(o=>Gw[o%32*4+2]),i=new Float64Array(A).map(o=>Gw[o%32*4+3]);return function(o,C,s,a){let n,B,Q,E,h;const c=(o+C+s+a)*rgA,l=kw(o+c),d=kw(C+c),u=kw(s+c),p=kw(a+c),D=(l+d+u+p)*tI,y=l-D,k=d-D,F=u-D,S=p-D,U=o-y,M=C-k,Y=s-F,_=a-S;let x=0,v=0,z=0,gA=0;U>M?x++:v++,U>Y?x++:z++,U>_?x++:gA++,M>Y?v++:z++,M>_?v++:gA++,Y>_?z++:gA++;const CA=x>=3?1:0,AA=v>=3?1:0,dA=z>=3?1:0,rA=gA>=3?1:0,vA=x>=2?1:0,MA=v>=2?1:0,IA=z>=2?1:0,QA=gA>=2?1:0,NA=x>=1?1:0,$=v>=1?1:0,_A=z>=1?1:0,YA=gA>=1?1:0,JA=U-CA+tI,DA=M-AA+tI,cA=Y-dA+tI,wA=_-rA+tI,lA=U-vA+2*tI,xA=M-MA+2*tI,KA=Y-IA+2*tI,ne=_-QA+2*tI,uA=U-NA+3*tI,re=M-$+3*tI,Be=Y-_A+3*tI,Ne=_-YA+3*tI,it=U-1+4*tI,L=M-1+4*tI,J=Y-1+4*tI,BA=_-1+4*tI,FA=l&255,qA=d&255,OA=u&255,ie=p&255;let H=.6-U*U-M*M-Y*Y-_*_;if(H<0)n=0;else{const pA=FA+A[qA+A[OA+A[ie]]];H*=H,n=H*H*(e[pA]*U+g[pA]*M+I[pA]*Y+i[pA]*_)}let X=.6-JA*JA-DA*DA-cA*cA-wA*wA;if(X<0)B=0;else{const pA=FA+CA+A[qA+AA+A[OA+dA+A[ie+rA]]];X*=X,B=X*X*(e[pA]*JA+g[pA]*DA+I[pA]*cA+i[pA]*wA)}let jA=.6-lA*lA-xA*xA-KA*KA-ne*ne;if(jA<0)Q=0;else{const pA=FA+vA+A[qA+MA+A[OA+IA+A[ie+QA]]];jA*=jA,Q=jA*jA*(e[pA]*lA+g[pA]*xA+I[pA]*KA+i[pA]*ne)}let VA=.6-uA*uA-re*re-Be*Be-Ne*Ne;if(VA<0)E=0;else{const pA=FA+NA+A[qA+$+A[OA+_A+A[ie+YA]]];VA*=VA,E=VA*VA*(e[pA]*uA+g[pA]*re+I[pA]*Be+i[pA]*Ne)}let HA=.6-it*it-L*L-J*J-BA*BA;if(HA<0)h=0;else{const pA=FA+1+A[qA+1+A[OA+1+A[ie+1]]];HA*=HA,h=HA*HA*(e[pA]*it+g[pA]*L+I[pA]*J+i[pA]*BA)}return 27*(n+B+Q+E+h)}}function QgA(t){const A=new Uint8Array(512);for(let e=0;e<512/2;e++)A[e]=e;for(let e=0;e<512/2-1;e++){const g=e+~~(t()*(256-e)),I=A[e];A[e]=A[g],A[g]=I}for(let e=256;e<512;e++)A[e]=A[e-256];return A}var EgA=Object.defineProperty,hgA=Object.getOwnPropertyDescriptor,V=(t,A,e,g)=>{for(var I=g>1?void 0:g?hgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&EgA(A,e,I),I};const mw=aA("debugparticles");var SC=(t=>(t[t.Billboard=0]="Billboard",t[t.Stretch=1]="Stretch",t[t.HorizontalBillboard=2]="HorizontalBillboard",t[t.VerticalBillboard=3]="VerticalBillboard",t[t.Mesh=4]="Mesh",t))(SC||{});class Bn{constructor(){r(this,"alphaKeys"),r(this,"colorKeys")}get duration(){return 1}evaluate(A,e){let g,I=0,i=null,o=0;for(let C=0;C<this.alphaKeys.length;C++){const s=this.alphaKeys[C];(s.time<A||!g)&&(g=s,I=C)}for(let C=0;C<this.colorKeys.length;C++){const s=this.colorKeys[C];(s.time<A||!i)&&(i=s,o=C)}if(i)if(o+1<this.colorKeys.length){const C=this.colorKeys[o+1],s=XA.remap(A,i.time,C.time,0,1);e.r=XA.lerp(i.color.r,C.color.r,s),e.g=XA.lerp(i.color.g,C.color.g,s),e.b=XA.lerp(i.color.b,C.color.b,s)}else e.r=i.color.r,e.g=i.color.g,e.b=i.color.b;if(g)if(I+1<this.alphaKeys.length){const C=this.alphaKeys[I+1],s=XA.remap(A,g.time,C.time,0,1);e.alpha=XA.lerp(g.alpha,C.alpha,s)}else e.alpha=g.alpha;return e}}V([w()],Bn.prototype,"alphaKeys",2),V([w()],Bn.prototype,"colorKeys",2);var Mw=(t=>(t[t.Local=0]="Local",t[t.World=1]="World",t[t.Custom=2]="Custom",t))(Mw||{}),OH=(t=>(t[t.Sphere=0]="Sphere",t[t.SphereShell=1]="SphereShell",t[t.Hemisphere=2]="Hemisphere",t[t.HemisphereShell=3]="HemisphereShell",t[t.Cone=4]="Cone",t[t.Box=5]="Box",t[t.Mesh=6]="Mesh",t[t.ConeShell=7]="ConeShell",t[t.ConeVolume=8]="ConeVolume",t[t.ConeVolumeShell=9]="ConeVolumeShell",t[t.Circle=10]="Circle",t[t.CircleEdge=11]="CircleEdge",t[t.SingleSidedEdge=12]="SingleSidedEdge",t[t.MeshRenderer=13]="MeshRenderer",t[t.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",t[t.BoxShell=15]="BoxShell",t[t.BoxEdge=16]="BoxEdge",t[t.Donut=17]="Donut",t[t.Rectangle=18]="Rectangle",t[t.Sprite=19]="Sprite",t[t.SpriteRenderer=20]="SpriteRenderer",t))(OH||{});class ge{constructor(){r(this,"mode"),r(this,"constant"),r(this,"constantMin"),r(this,"constantMax"),r(this,"curve"),r(this,"curveMin"),r(this,"curveMax"),r(this,"curveMultiplier")}evaluate(A,e){const g=e===void 0?Math.random():e;switch(this.mode){case 0:return this.constant;case 1:return A=XA.clamp01(A),this.curve.evaluate(A)*this.curveMultiplier;case 2:const I=A*this.curveMin.duration,i=A*this.curveMax.duration;return XA.lerp(this.curveMin.evaluate(I),this.curveMax.evaluate(i),g%1)*this.curveMultiplier;case 3:return XA.lerp(this.constantMin,this.constantMax,g%1);default:this.curveMax.evaluate(A)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:return this.constant;case 1:return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(A){if(!A)return 0;let e=Number.MIN_VALUE;for(let g=0;g<A.keys.length;g++){const I=A.keys[g];I.value>e&&(e=I.value)}return e}}V([w()],ge.prototype,"mode",2),V([w()],ge.prototype,"constant",2),V([w()],ge.prototype,"constantMin",2),V([w()],ge.prototype,"constantMax",2),V([w(wr)],ge.prototype,"curve",2),V([w(wr)],ge.prototype,"curveMin",2),V([w(wr)],ge.prototype,"curveMax",2),V([w()],ge.prototype,"curveMultiplier",2);var Rw;const Yo=(Rw=class{constructor(){r(this,"mode"),r(this,"color"),r(this,"colorMin"),r(this,"colorMax"),r(this,"gradient"),r(this,"gradientMin"),r(this,"gradientMax")}evaluate(t,A){const e=A===void 0?Math.random():A;switch(this.mode){case 0:return this.color;case 1:return this.gradient.evaluate(t,Yo._temp),Yo._temp;case 2:return Yo._temp.lerpColors(this.colorMin,this.colorMax,e);case 3:return this.gradientMin.evaluate(t,Yo._temp),this.gradientMax.evaluate(t,Yo._temp2),Yo._temp.lerp(Yo._temp2,e)}return Yo._temp.set(16711935),Yo._temp.alpha=1,Yo._temp}},r(Rw,"_temp",new wt(0,0,0,1)),r(Rw,"_temp2",new wt(0,0,0,1)),Rw);let Ci=Yo;V([w(wt)],Ci.prototype,"color",2),V([w(wt)],Ci.prototype,"colorMin",2),V([w(wt)],Ci.prototype,"colorMax",2),V([w(Bn)],Ci.prototype,"gradient",2),V([w(Bn)],Ci.prototype,"gradientMin",2),V([w(Bn)],Ci.prototype,"gradientMax",2);class gI{constructor(){r(this,"cullingMode"),r(this,"duration"),r(this,"emitterVelocityMode"),r(this,"flipRotation"),r(this,"gravityModifier"),r(this,"gravityModifierMultiplier"),r(this,"loop"),r(this,"maxParticles"),r(this,"playOnAwake"),r(this,"prewarm"),r(this,"ringBufferLoopRange"),r(this,"ringBufferMode"),r(this,"scalingMode"),r(this,"simulationSpace"),r(this,"simulationSpeed"),r(this,"startColor"),r(this,"startDelay"),r(this,"startDelayMultiplier"),r(this,"startLifetime"),r(this,"startLifetimeMultiplier"),r(this,"startRotation"),r(this,"startRotationMultiplier"),r(this,"startRotation3D"),r(this,"startRotationX"),r(this,"startRotationXMultiplier"),r(this,"startRotationY"),r(this,"startRotationYMultiplier"),r(this,"startRotationZ"),r(this,"startRotationZMultiplier"),r(this,"startSize"),r(this,"startSize3D"),r(this,"startSizeMultiplier"),r(this,"startSizeX"),r(this,"startSizeXMultiplier"),r(this,"startSizeY"),r(this,"startSizeYMultiplier"),r(this,"startSizeZ"),r(this,"startSizeZMultiplier"),r(this,"startSpeed"),r(this,"startSpeedMultiplier"),r(this,"stopAction"),r(this,"useUnscaledTime")}}V([w(ge)],gI.prototype,"gravityModifier",2),V([w(Ci)],gI.prototype,"startColor",2),V([w(ge)],gI.prototype,"startDelay",2),V([w(ge)],gI.prototype,"startLifetime",2),V([w(ge)],gI.prototype,"startRotation",2),V([w(ge)],gI.prototype,"startRotationX",2),V([w(ge)],gI.prototype,"startRotationY",2),V([w(ge)],gI.prototype,"startRotationZ",2),V([w(ge)],gI.prototype,"startSize",2),V([w(ge)],gI.prototype,"startSizeX",2),V([w(ge)],gI.prototype,"startSizeY",2),V([w(ge)],gI.prototype,"startSizeZ",2),V([w(ge)],gI.prototype,"startSpeed",2);class Bl{constructor(){r(this,"cycleCount"),r(this,"maxCount"),r(this,"minCount"),r(this,"probability"),r(this,"repeatInterval"),r(this,"time"),r(this,"count"),r(this,"_performed",0)}reset(){this._performed=0}run(A){if(A<=this.time)return this.reset(),0;let e=0;if(this.cycleCount===0||this._performed<this.cycleCount){const g=this.time+this.repeatInterval*this._performed;if(A>=g&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:e=this.count.constant;break;case 3:e=XA.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:e=this.count.curve.evaluate(Math.random());break;case 2:const I=Math.random();e=XA.lerp(this.count.curveMin.evaluate(I),this.count.curveMax.evaluate(I),Math.random());break}}return e}}class fC{constructor(){r(this,"enabled"),r(this,"bursts"),r(this,"rateOverTime"),r(this,"rateOverTimeMultiplier"),r(this,"rateOverDistance"),r(this,"rateOverDistanceMultiplier"),r(this,"system")}get burstCount(){var A;return((A=this.bursts)==null?void 0:A.length)??0}reset(){var A;(A=this.bursts)==null||A.forEach(e=>e.reset())}getBurst(){let A=0;if(this.burstCount>0)for(let e=0;e<this.burstCount;e++){const g=this.bursts[e];g.time>=this.system.time&&g.reset(),A+=Math.round(g.run(this.system.time))}return A}}V([w()],fC.prototype,"enabled",2),V([w()],fC.prototype,"bursts",2),V([w(ge)],fC.prototype,"rateOverTime",2),V([w()],fC.prototype,"rateOverTimeMultiplier",2),V([w(ge)],fC.prototype,"rateOverDistance",2),V([w()],fC.prototype,"rateOverDistanceMultiplier",2);class Ql{constructor(){r(this,"enabled"),r(this,"color")}}V([w(Ci)],Ql.prototype,"color",2);class Qn{constructor(){r(this,"enabled"),r(this,"separateAxes"),r(this,"size"),r(this,"sizeMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier"),r(this,"_time",0),r(this,"_temp",new f)}evaluate(A,e,g){if(e||(e=this._temp),!this.enabled)return e.x=e.y=e.z=1,e;if(this.separateAxes)e.x=this.x.evaluate(A,g)*this.xMultiplier,e.y=this.y.evaluate(A,g)*this.yMultiplier,e.z=this.z.evaluate(A,g)*this.zMultiplier;else{const I=this.size.evaluate(A,g)*this.sizeMultiplier;e.x=I}return e}}V([w(ge)],Qn.prototype,"size",2),V([w(ge)],Qn.prototype,"x",2),V([w(ge)],Qn.prototype,"y",2),V([w(ge)],Qn.prototype,"z",2);var Uw;const El=(Uw=class{constructor(){r(this,"shapeType",5),r(this,"enabled",!0),r(this,"alignToDirection",!1),r(this,"angle",0),r(this,"arc",360),r(this,"arcSpread"),r(this,"arcSpeedMultiplier"),r(this,"arcMode"),r(this,"boxThickness"),r(this,"position"),r(this,"rotation"),r(this,"_rotation",new fg),r(this,"scale"),r(this,"radius"),r(this,"radiusThickness"),r(this,"sphericalDirectionAmount"),r(this,"randomDirectionAmount"),r(this,"randomPositionAmount"),r(this,"system"),r(this,"_space"),r(this,"_worldSpaceMatrix",new TA),r(this,"_worldSpaceMatrixInverse",new TA),r(this,"_vector",new f(0,0,0)),r(this,"_temp",new f(0,0,0)),r(this,"_dir",new f),r(this,"_loopTime",0),r(this,"_loopDirection",1),mw&&console.log(this)}get type(){return OH[this.shapeType]}initialize(t){this.getPosition(),t.position.copy(this._vector)}toJSON(){return this}clone(){return new El}update(t,A,e,g){this.system=t,this._space=e,e===1&&(this._worldSpaceMatrix.copy(g.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(t){const A=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return A&&(this._rotation.x=XA.toRadians(this.rotation.x),this._rotation.y=XA.toRadians(this.rotation.y),this._rotation.z=XA.toRadians(this.rotation.z),this._rotation.order="ZYX",t.applyEuler(this._rotation)),A}get vector(){return this._vector}getPosition(){this._vector.set(0,0,0);const t=this._temp.copy(this.position),A=this._space===1;A&&t.applyQuaternion(this.system.worldQuaternion);let e=this.radius;if(A&&(e*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:mw&&nC.DrawBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,e,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,e,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,e,this.radiusThickness,this.arc,this._vector);break;default:this._vector.set(0,0,0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),A&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),mw&&nC.DrawSphere(this._vector,.03,16711680,.5,!0)}getDirection(t){var A;if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const e=t.x,g=t.y,I=t.z;this._dir.set(e,g,I),(A=this.system)!=null&&A.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),mw&&(nC.DrawSphere(t,.01,8925952,.5,!0),nC.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}randomizePosition(t,A){if(A<=0)return;const e=El._tempVec;e.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),e.x*=A*this.scale.x,e.y*=A*this.scale.y,e.z*=A*this.scale.z,t.add(e)}randomizeDirection(t,A){if(A===0)return;const e=El._randomQuat,g=El._tempVec;g.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),e.setFromAxisAngle(g,A*Math.random()*Math.PI),t.applyQuaternion(e)}spherizeDirection(t,A){if(A===0)return;const e=Math.random()*Math.PI*2,g=Math.acos(1-Math.random()*2),I=Math.sin(g)*Math.cos(e),i=Math.sin(g)*Math.sin(e),o=Math.cos(g),C=new f(I,i,o);t.lerp(C,A)}randomSpherePoint(t,A,e,g,I){const i=Math.random(),o=Math.random(),C=2*Math.PI*i*(g/360),s=Math.acos(2*o-1),a=XA.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,n=t.x+this.scale.x*(-a*Math.sin(s)*Math.cos(C)),B=t.y+this.scale.y*(a*Math.sin(s)*Math.sin(C)),Q=t.z+this.scale.z*(a*Math.cos(s));I.x=n,I.y=B,I.z=Q}randomCirclePoint(t,A,e,g,I){const i=Math.random(),o=2*Math.PI*i*(g/360),C=XA.lerp(1,1-Math.pow(1-Math.random(),Math.PI),e)*A,s=t.x+this.scale.x*C*Math.cos(o),a=t.y+this.scale.y*C*Math.sin(o),n=t.z;I.x=s,I.y=a,I.z=n}randomConePoint(t,A,e,g,I,i,o){let C=0,s=0;switch(i){case 0:C=Math.random(),s=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:C=.5,s=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let a=2*Math.PI*C*(I/360);switch(i){case 2:case 1:a+=Math.PI+.5,a+=this._loopTime*Math.PI*2,a%=XA.toRadians(I);break}const n=Math.acos(2*s-1),B=XA.lerp(1,1-Math.pow(1-Math.random(),Math.PI),g)*e,Q=t.x+-B*Math.sin(n)*Math.cos(a),E=t.y+B*Math.sin(n)*Math.sin(a),h=t.z;o.x=Q*this.scale.x,o.y=E*this.scale.y,o.z=h*this.scale.z}},r(Uw,"_randomQuat",new GA),r(Uw,"_tempVec",new f),Uw);let og=El;V([w()],og.prototype,"shapeType",2),V([w()],og.prototype,"enabled",2),V([w()],og.prototype,"alignToDirection",2),V([w()],og.prototype,"angle",2),V([w()],og.prototype,"arc",2),V([w()],og.prototype,"arcSpread",2),V([w()],og.prototype,"arcSpeedMultiplier",2),V([w()],og.prototype,"arcMode",2),V([w(f)],og.prototype,"boxThickness",2),V([w(f)],og.prototype,"position",2),V([w(f)],og.prototype,"rotation",2),V([w(f)],og.prototype,"scale",2),V([w()],og.prototype,"radius",2),V([w()],og.prototype,"radiusThickness",2),V([w()],og.prototype,"sphericalDirectionAmount",2),V([w()],og.prototype,"randomDirectionAmount",2),V([w()],og.prototype,"randomPositionAmount",2);class Et{constructor(){r(this,"damping"),r(this,"enabled"),r(this,"frequency"),r(this,"octaveCount"),r(this,"octaveMultiplier"),r(this,"octaveScale"),r(this,"positionAmount"),r(this,"quality"),r(this,"remap"),r(this,"remapEnabled"),r(this,"remapMultiplier"),r(this,"remapX"),r(this,"remapXMultiplier"),r(this,"remapY"),r(this,"remapYMultiplier"),r(this,"remapZ"),r(this,"remapZMultiplier"),r(this,"scrollSpeedMultiplier"),r(this,"separateAxes"),r(this,"strengthMultiplier"),r(this,"strengthX"),r(this,"strengthXMultiplier"),r(this,"strengthY"),r(this,"strengthYMultiplier"),r(this,"strengthZ"),r(this,"strengthZMultiplier"),r(this,"_noise"),r(this,"_time",0),r(this,"_temp",new f)}update(A){this._time+=A.time.deltaTime*this.scrollSpeedMultiplier}apply(A,e,g,I,i,o){if(!this.enabled)return;this._noise||(this._noise=BgA(()=>0));const C=this._temp.set(e.x,e.y,e.z).multiplyScalar(this.frequency),s=this._noise(C.x,C.y,C.z,this._time),a=this._noise(C.x,C.y,C.z,this._time+1e3*this.frequency),n=this._noise(C.x,C.y,C.z,this._time+2e3*this.frequency);this._temp.set(s,a,n).normalize();const B=i/o;let Q=this.positionAmount.evaluate(B);this.separateAxes?(this._temp.x*=Q*this.strengthXMultiplier,this._temp.y*=Q*this.strengthYMultiplier,this._temp.z*=Q*this.strengthZMultiplier):(this.strengthX&&(Q*=this.strengthX.evaluate(B)*1.5),this._temp.multiplyScalar(Q)),g.x+=this._temp.x,g.y+=this._temp.y,g.z+=this._temp.z}}V([w()],Et.prototype,"damping",2),V([w()],Et.prototype,"enabled",2),V([w()],Et.prototype,"frequency",2),V([w()],Et.prototype,"octaveCount",2),V([w()],Et.prototype,"octaveMultiplier",2),V([w()],Et.prototype,"octaveScale",2),V([w(ge)],Et.prototype,"positionAmount",2),V([w()],Et.prototype,"quality",2),V([w(ge)],Et.prototype,"remap",2),V([w()],Et.prototype,"remapEnabled",2),V([w()],Et.prototype,"remapMultiplier",2),V([w(ge)],Et.prototype,"remapX",2),V([w()],Et.prototype,"remapXMultiplier",2),V([w(ge)],Et.prototype,"remapY",2),V([w()],Et.prototype,"remapYMultiplier",2),V([w(ge)],Et.prototype,"remapZ",2),V([w()],Et.prototype,"remapZMultiplier",2),V([w()],Et.prototype,"scrollSpeedMultiplier",2),V([w()],Et.prototype,"separateAxes",2),V([w()],Et.prototype,"strengthMultiplier",2),V([w(ge)],Et.prototype,"strengthX",2),V([w()],Et.prototype,"strengthXMultiplier",2),V([w(ge)],Et.prototype,"strengthY",2),V([w()],Et.prototype,"strengthYMultiplier",2),V([w(ge)],Et.prototype,"strengthZ",2),V([w()],Et.prototype,"strengthZMultiplier",2);class qt{constructor(){r(this,"enabled"),r(this,"attachRibbonToTransform",!1),r(this,"colorOverLifetime"),r(this,"colorOverTrail"),r(this,"dieWithParticles",!0),r(this,"inheritParticleColor",!0),r(this,"lifetime"),r(this,"lifetimeMultiplier"),r(this,"minVertexDistance",.2),r(this,"mode",0),r(this,"ratio",1),r(this,"ribbonCount",1),r(this,"shadowBias",0),r(this,"sizeAffectsLifetime",!1),r(this,"sizeAffectsWidth",!1),r(this,"splitSubEmitterRibbons",!1),r(this,"textureMode",0),r(this,"widthOverTrail"),r(this,"widthOverTrailMultiplier"),r(this,"worldSpace",!1)}getWidth(A,e,g){let I=this.widthOverTrail.evaluate(g);return g===0&&(I=A),A*=I,A}getColor(A,e,g){const I=this.colorOverTrail.evaluate(g),i=this.colorOverLifetime.evaluate(e);A.x*=I.r*i.r,A.y*=I.g*i.g,A.z*=I.b*i.b,A.w*=I.alpha*i.alpha}}V([w()],qt.prototype,"enabled",2),V([w()],qt.prototype,"attachRibbonToTransform",2),V([w(Ci)],qt.prototype,"colorOverLifetime",2),V([w(Ci)],qt.prototype,"colorOverTrail",2),V([w()],qt.prototype,"dieWithParticles",2),V([w()],qt.prototype,"inheritParticleColor",2),V([w(ge)],qt.prototype,"lifetime",2),V([w()],qt.prototype,"lifetimeMultiplier",2),V([w()],qt.prototype,"minVertexDistance",2),V([w()],qt.prototype,"mode",2),V([w()],qt.prototype,"ratio",2),V([w()],qt.prototype,"ribbonCount",2),V([w()],qt.prototype,"shadowBias",2),V([w()],qt.prototype,"sizeAffectsLifetime",2),V([w()],qt.prototype,"sizeAffectsWidth",2),V([w()],qt.prototype,"splitSubEmitterRibbons",2),V([w()],qt.prototype,"textureMode",2),V([w(ge)],qt.prototype,"widthOverTrail",2),V([w()],qt.prototype,"widthOverTrailMultiplier",2),V([w()],qt.prototype,"worldSpace",2);class Tt{constructor(){r(this,"enabled"),r(this,"space",0),r(this,"orbitalX"),r(this,"orbitalY"),r(this,"orbitalZ"),r(this,"orbitalXMultiplier"),r(this,"orbitalYMultiplier"),r(this,"orbitalZMultiplier"),r(this,"orbitalOffsetX"),r(this,"orbitalOffsetY"),r(this,"orbitalOffsetZ"),r(this,"speedModifier"),r(this,"speedModifierMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier"),r(this,"_system"),r(this,"_temp",new f),r(this,"_temp2",new f),r(this,"_temp3",new f),r(this,"_hasOrbital",!1),r(this,"_index",0),r(this,"_orbitalMatrix",new TA)}update(A){this._system=A}init(A){this._index==0&&(A.debug=!0),this._index+=1,A.orbitx=this.orbitalX.evaluate(Math.random()),A.orbity=this.orbitalY.evaluate(Math.random()),A.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=A.orbitx!=0||A.orbity!=0||A.orbitz!=0}apply(A,e,g,I,i,o,C){var s;if(!this.enabled)return;const a=o/C,n=this.speedModifier.evaluate(a)*this.speedModifierMultiplier,B=this.x.evaluate(a),Q=this.y.evaluate(a),E=this.z.evaluate(a);if(this._temp.set(-B,Q,E),this._system,this._hasOrbital&&((s=this._system)==null?void 0:s.worldPos)){const h=this._temp2.set(g.x,g.y,g.z),c=this.orbitalXMultiplier,l=this.orbitalYMultiplier,d=this.orbitalZMultiplier,u=n*Math.PI*2*10,p=Math.cos(u*c),D=Math.sin(u*c),y=Math.cos(u*l),k=Math.sin(u*l),F=Math.cos(u*d),S=Math.sin(u*d),U=h.x*(y*F)+h.y*(y*S)+h.z*-k,M=h.x*(D*k*F-p*S)+h.y*(D*k*S+p*F)+h.z*(D*y),Y=h.x*(p*k*F+D*S)+h.y*(p*k*S-D*F)+h.z*(p*y),_=this._temp3.set(h.x-U,h.y-M,h.z-Y);_.normalize(),_.multiplyScalar(.2/i*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),I.x+=_.x,I.y+=_.y,I.z+=_.z}I.x+=this._temp.x,I.y+=this._temp.y,I.z+=this._temp.z,I.x*=n,I.y*=n,I.z*=n}}V([w()],Tt.prototype,"enabled",2),V([w()],Tt.prototype,"space",2),V([w(ge)],Tt.prototype,"orbitalX",2),V([w(ge)],Tt.prototype,"orbitalY",2),V([w(ge)],Tt.prototype,"orbitalZ",2),V([w()],Tt.prototype,"orbitalXMultiplier",2),V([w()],Tt.prototype,"orbitalYMultiplier",2),V([w()],Tt.prototype,"orbitalZMultiplier",2),V([w()],Tt.prototype,"orbitalOffsetX",2),V([w()],Tt.prototype,"orbitalOffsetY",2),V([w()],Tt.prototype,"orbitalOffsetZ",2),V([w(ge)],Tt.prototype,"speedModifier",2),V([w()],Tt.prototype,"speedModifierMultiplier",2),V([w(ge)],Tt.prototype,"x",2),V([w()],Tt.prototype,"xMultiplier",2),V([w(ge)],Tt.prototype,"y",2),V([w()],Tt.prototype,"yMultiplier",2),V([w(ge)],Tt.prototype,"z",2),V([w()],Tt.prototype,"zMultiplier",2);class II{constructor(){r(this,"animation"),r(this,"enabled"),r(this,"cycleCount"),r(this,"frameOverTime"),r(this,"frameOverTimeMultiplier"),r(this,"numTilesX"),r(this,"numTilesY"),r(this,"startFrame"),r(this,"startFrameMultiplier"),r(this,"rowMode"),r(this,"rowIndex"),r(this,"spriteCount"),r(this,"timeMode")}sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(A){if(!this.sampleOnceAtStart())return this.getIndex(A)}getIndex(A){const e=this.numTilesX*this.numTilesY;A=A*this.cycleCount;let g=this.frameOverTime.evaluate(A%1);return g*=this.frameOverTimeMultiplier,g*=e,g=g%e,g=Math.floor(g),g}}V([w()],II.prototype,"animation",2),V([w()],II.prototype,"enabled",2),V([w()],II.prototype,"cycleCount",2),V([w(ge)],II.prototype,"frameOverTime",2),V([w()],II.prototype,"frameOverTimeMultiplier",2),V([w()],II.prototype,"numTilesX",2),V([w()],II.prototype,"numTilesY",2),V([w(ge)],II.prototype,"startFrame",2),V([w()],II.prototype,"startFrameMultiplier",2),V([w()],II.prototype,"rowMode",2),V([w()],II.prototype,"rowIndex",2),V([w()],II.prototype,"spriteCount",2),V([w()],II.prototype,"timeMode",2);class Co{constructor(){r(this,"enabled"),r(this,"separateAxes"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e){return this.enabled?this.separateAxes?0:this.z.evaluate(A,e)*-1:0}}V([w()],Co.prototype,"enabled",2),V([w()],Co.prototype,"separateAxes",2),V([w(ge)],Co.prototype,"x",2),V([w()],Co.prototype,"xMultiplier",2),V([w(ge)],Co.prototype,"y",2),V([w()],Co.prototype,"yMultiplier",2),V([w(ge)],Co.prototype,"z",2),V([w()],Co.prototype,"zMultiplier",2);class Ui{constructor(){r(this,"enabled"),r(this,"range"),r(this,"separateAxes"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e){if(!this.enabled)return 0;if(!this.separateAxes){const g=XA.lerp(this.range.x,this.range.y,e);return this.z.evaluate(g)*-1}return 0}}V([w()],Ui.prototype,"enabled",2),V([w()],Ui.prototype,"range",2),V([w()],Ui.prototype,"separateAxes",2),V([w(ge)],Ui.prototype,"x",2),V([w()],Ui.prototype,"xMultiplier",2),V([w(ge)],Ui.prototype,"y",2),V([w()],Ui.prototype,"yMultiplier",2),V([w(ge)],Ui.prototype,"z",2),V([w()],Ui.prototype,"zMultiplier",2);class ug{constructor(){r(this,"enabled"),r(this,"dampen"),r(this,"drag"),r(this,"dragMultiplier"),r(this,"limit"),r(this,"limitMultiplier"),r(this,"separateAxes"),r(this,"limitX"),r(this,"limitXMultiplier"),r(this,"limitY"),r(this,"limitYMultiplier"),r(this,"limitZ"),r(this,"limitZMultiplier"),r(this,"multiplyDragByParticleSize",!1),r(this,"multiplyDragByParticleVelocity",!1),r(this,"space"),r(this,"_temp",new f),r(this,"_temp2",new f)}apply(A,e,g,I,i,o,C){if(this.enabled){const s=this.limit.evaluate(i)*this.limitMultiplier;if(e.length()>s){this._temp.copy(e).normalize().multiplyScalar(s);let a=this.dampen*.5;e.x=XA.lerp(e.x,this._temp.x,a),e.y=XA.lerp(e.y,this._temp.y,a),e.z=XA.lerp(e.z,this._temp.z,a),g.x=XA.lerp(g.x,this._temp.x,a),g.y=XA.lerp(g.y,this._temp.y,a),g.z=XA.lerp(g.z,this._temp.z,a)}}}}V([w()],ug.prototype,"enabled",2),V([w()],ug.prototype,"dampen",2),V([w(ge)],ug.prototype,"drag",2),V([w()],ug.prototype,"dragMultiplier",2),V([w(ge)],ug.prototype,"limit",2),V([w()],ug.prototype,"limitMultiplier",2),V([w()],ug.prototype,"separateAxes",2),V([w(ge)],ug.prototype,"limitX",2),V([w()],ug.prototype,"limitXMultiplier",2),V([w(ge)],ug.prototype,"limitY",2),V([w()],ug.prototype,"limitYMultiplier",2),V([w(ge)],ug.prototype,"limitZ",2),V([w()],ug.prototype,"limitZMultiplier",2),V([w()],ug.prototype,"multiplyDragByParticleSize",2),V([w()],ug.prototype,"multiplyDragByParticleVelocity",2),V([w()],ug.prototype,"space",2);class En{constructor(){r(this,"enabled"),r(this,"curve"),r(this,"curveMultiplier"),r(this,"mode"),r(this,"system"),r(this,"_lastWorldPosition"),r(this,"_velocity",new f),r(this,"_temp",new f)}update(A){this.enabled&&this.system.worldspace!==!1&&(this._lastWorldPosition?(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)):(this._velocity.set(0,0,0),this._lastWorldPosition=this.system.worldPos.clone()))}applyInitial(A){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const e=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(e),A.add(this._temp)}}applyCurrent(A,e,g){if(this.enabled&&this.system.worldspace!==!1&&this.mode===1){const I=this.curve.evaluate(e,g);this._temp.copy(this._velocity).multiplyScalar(I),A.add(this._temp)}}}V([w()],En.prototype,"enabled",2),V([w(ge)],En.prototype,"curve",2),V([w()],En.prototype,"curveMultiplier",2),V([w()],En.prototype,"mode",2);class _I{constructor(){r(this,"enabled"),r(this,"range"),r(this,"separateAxes"),r(this,"size"),r(this,"sizeMultiplier"),r(this,"x"),r(this,"xMultiplier"),r(this,"y"),r(this,"yMultiplier"),r(this,"z"),r(this,"zMultiplier")}evaluate(A,e,g,I){const i=A.length(),o=XA.remap(i,this.range.x,this.range.y,0,1),C=this.size.evaluate(o,g);return I*C}}V([w()],_I.prototype,"enabled",2),V([w(W)],_I.prototype,"range",2),V([w()],_I.prototype,"separateAxes",2),V([w(ge)],_I.prototype,"size",2),V([w()],_I.prototype,"sizeMultiplier",2),V([w(ge)],_I.prototype,"x",2),V([w()],_I.prototype,"xMultiplier",2),V([w(ge)],_I.prototype,"y",2),V([w()],_I.prototype,"yMultiplier",2),V([w(ge)],_I.prototype,"z",2),V([w()],_I.prototype,"zMultiplier",2);class br{constructor(){r(this,"enabled"),r(this,"range"),r(this,"color")}evaluate(A,e,g){const I=A.length(),i=XA.remap(I,this.range.x,this.range.y,0,1),o=this.color.evaluate(i,e);g.x*=o.r,g.y*=o.g,g.z*=o.b,g.w*=o.alpha}}V([w()],br.prototype,"enabled",2),V([w(W)],br.prototype,"range",2),V([w(Ci)],br.prototype,"color",2);function cgA(t){const A=t.domElement.querySelector("link[rel='ar']");if(A)return A;const e=document.createElement("div");e.classList.add("menu"),e.classList.add("quicklook-menu"),e.style.display="none",e.style.visibility="hidden";const g=document.createElement("button");g.id="open-in-ar",g.innerText="Open in QuickLook",e.appendChild(g);const I=document.createElement("a");I.id="needle-usdz-link",I.style.display="none",I.rel="ar",I.href="",e.appendChild(I);const i=document.createElement("img");return i.id="button",I.appendChild(i),t.domElement.appendChild(e),I}function lgA(){var t=new Date;const A=t.getMonth()+1,e=t.getDate(),g=t.getHours(),I=t.getMinutes(),i=t.getSeconds(),o=(A<10?"0":"")+A,C=(e<10?"0":"")+e,s=(g<10?"0":"")+g,a=(I<10?"0":"")+I,n=(i<10?"0":"")+i;return t.getFullYear()+o+C+"-"+s+a+n}const Fw=aA("debugusdz");function dgA(t,A){const e=[],g=eA.getComponentsInChildren(t,Ai);let I=!1;Fw&&console.log(g);for(const i of g){if(!i||!i.runtimeAnimatorController)continue;Fw&&console.log(i);const o=[];for(const C of i.runtimeAnimatorController.enumerateActions()){Fw&&console.log(C);const s=C.getClip();if(!I&&s.tracks.length>0){I=!0;const a=s.tracks[0],n=a.name.substring(0,a.name.lastIndexOf(".")),B=new Si(n+".position",[0,.01],[0,0,0,0,0,0]),Q=new Si(n+".quaternion",[0,.01],[0,0,0,1,0,0,0,1]);o.push(new Oi("rest",.01,[B,Q]))}o.includes(s)||o.push(s)}e.push({root:i.gameObject,clips:o})}Fw&&console.log(e);for(const i of e)for(const o of i.clips)A.registerAnimation(i.root,o)}var pgA=Object.defineProperty,ugA=Object.getOwnPropertyDescriptor,Ts=(t,A,e,g)=>{for(var I=g>1?void 0:g?ugA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&pgA(A,e,I),I};const kM=aA("debugtext");var bg=(t=>(t[t.UpperLeft=0]="UpperLeft",t[t.UpperCenter=1]="UpperCenter",t[t.UpperRight=2]="UpperRight",t[t.MiddleLeft=3]="MiddleLeft",t[t.MiddleCenter=4]="MiddleCenter",t[t.MiddleRight=5]="MiddleRight",t[t.LowerLeft=6]="LowerLeft",t[t.LowerCenter=7]="LowerCenter",t[t.LowerRight=8]="LowerRight",t))(bg||{});class OI extends Nr{constructor(){super(...arguments),r(this,"alignment",0),r(this,"verticalOverflow",0),r(this,"horizontalOverflow",0),r(this,"lineSpacing",1),r(this,"supportRichText",!1),r(this,"font"),r(this,"fontStyle",0),r(this,"_text",""),r(this,"_fontSize",12),r(this,"_textMeshUi",null),r(this,"_didHandleTextRenderOnTop",!1)}setAlphaFactor(A){var e;super.setAlphaFactor(A),(e=this.uiObject)==null||e.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(A){A!==this._text&&(this._text=A,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(A){this.text=A}get fontSize(){return this._fontSize}set fontSize(A){var e;this._fontSize=A,(e=this.uiObject)==null||e.set({fontSize:A})}onColorChanged(){var A;(A=this.uiObject)==null||A.set({color:this.color,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeRender(){this.uiObject&&this.Root.screenspace&&this.updateOverflow()}updateOverflow(){var A;const e=(A=this.uiObject)==null?void 0:A._overflow;e&&(e._needsUpdate=!0,this.markDirty())}onCreate(A){kM&&console.log(this),this.horizontalOverflow==1&&(A.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,A.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,A.lineHeight=this.lineSpacing,delete A.backgroundOpacity,delete A.backgroundColor,kM&&(A.backgroundColor=16750848,A.backgroundOpacity=.5);const e=this.rectTransform;A={...A,...this.getTextOpts()},this.getAlignment(A),kM&&(A.backgroundColor=Math.random()*16777215,A.backgroundOpacity=.1),this.uiObject=e.createNewText(A),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}getTextOpts(){let A=this.fontSize;const e={color:this.color,fontOpacity:this.color.alpha,fontSize:A,fontKerning:"normal"};return this.setFont(e,this.fontStyle),e}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10)}getAlignment(A){switch(A.flexDirection="column",this.alignment){case 0:case 3:case 6:A.textAlign="left";break;case 1:case 4:case 7:A.textAlign="center";break;case 2:case 5:case 8:A.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:A.alignItems="start";break;case 3:case 4:case 5:A.alignItems="center";break;case 6:case 7:case 8:A.alignItems="end";break}return A}feedText(A,e){var g,I,i;if(!this.uiObject)return null;if(this._textMeshUi||(this._textMeshUi=[]),!e||A.length===0)this.uiObject.textContent=A;else{let o=this.getNextTag(A);if(o)o.startIndex>0&&this.uiObject.add(new gw({textContent:A.substring(0,o.startIndex),color:"inherit"}));else return this.uiObject.textContent=A;const C=[];for(;o;){const s=this.getNextTag(A,o.endIndex),a={fontFamily:(g=this.uiObject)==null?void 0:g.get("fontFamily"),color:"inherit",textContent:""};s?(a.textContent=this.getText(A,o,s),this.handleTag(o,a,C),(I=this.uiObject)==null||I.add(new gw(a))):(a.textContent=A.substring(o.endIndex),this.handleTag(o,a,C),(i=this.uiObject)==null||i.add(new gw(a))),o=s}}return null}handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const A=[],e=this.canvas,g={renderOnTop:e.renderOnTop,depthWrite:e.depthWrite,doubleSided:e.doubleSided};for(;;){let I=!1;if(this._textMeshUi)for(let i=0;i<this._textMeshUi.length;i++){if(A[i]===!0)continue;I=!0;const o=this._textMeshUi[i];o.textContent&&(pw(o,g),A[i]=!0)}if(!I)break;yield}}handleTag(A,e,g){if(A.isEndTag){if(g.length>0){const I=g.pop();if(I)for(const i in I.previousValues){const o=I.previousValues[i];e[i]=o}}}else if(A.type.includes("color")){const I=new GM(A,{color:e.color});if(g.push(I),A.type.length>6){const i=parseInt("0x"+A.type.substring(7));e.color=i}else e.color=new fA(1,1,1)}else if(A.type=="b"){this.setFont(e,1);const I=new GM(A,{fontWeight:700});g.push(I)}else if(A.type=="i"){this.setFont(e,2);const I=new GM(A,{fontStyle:"italic"});g.push(I)}}getText(A,e,g){return A.substring(e.endIndex,g.startIndex)}getNextTag(A,e=0){const g=A.indexOf("<",e),I=A.indexOf(">",g);if(g>=0&&I>=0){const i=A.substring(g+1,I);return{type:i,startIndex:g,endIndex:I+1,isEndTag:i.startsWith("/")}}return null}setFont(A,e){if(!this.font)return;let g=this.font,I=jm.getFontFamily(g);I||(I=jm.addFontFamily(g)),A.fontFamily=I;const i=g.toLowerCase();switch(e){default:case 0:A.fontWeight=400,A.fontStyle="normal";break;case 1:A.fontWeight=700,A.fontStyle="normal",i.includes("-bold")||(g+="-bold");break;case 2:A.fontWeight=400,A.fontStyle="italic",i.includes("-italic")||(g+="-italic");break;case 3:A.fontStyle="italic",A.fontWeight=400,i.includes("-bold")||(g+="-bold"),i.includes("-italic")||(g+="-italic")}let o=I.getVariant(A.fontWeight,A.fontStyle);if(!o){let C=g;C!=null&&C.endsWith("-msdf.json")||(C+="-msdf.json");let s=g;s!=null&&s.endsWith(".png")||(s+=".png"),o=I.addVariant(A.fontWeight,A.fontStyle,C,s),o?.addEventListener("ready",()=>{this.markDirty()})}}}Ts([w()],OI.prototype,"alignment",2),Ts([w()],OI.prototype,"verticalOverflow",2),Ts([w()],OI.prototype,"horizontalOverflow",2),Ts([w()],OI.prototype,"lineSpacing",2),Ts([w()],OI.prototype,"supportRichText",2),Ts([w(URL)],OI.prototype,"font",2),Ts([w()],OI.prototype,"fontStyle",2),Ts([w()],OI.prototype,"text",1),Ts([w()],OI.prototype,"fontSize",1);class GM{constructor(A,e){r(this,"tag"),r(this,"previousValues"),this.tag=A,this.previousValues=e}}class hn{constructor(A){r(this,"id"),r(this,"content",""),r(this,"font",[]),r(this,"pointSize",144),r(this,"width"),r(this,"height"),r(this,"depth"),r(this,"wrapMode"),r(this,"horizontalAlignment"),r(this,"verticalAlignment"),r(this,"material"),this.id=A}static getId(){return this.global_id++}setDepth(A){return this.depth=A,this}setPointSize(A){return this.pointSize=A,this}setHorizontalAlignment(A){return this.horizontalAlignment=A,this}setVerticalAlignment(A){return this.verticalAlignment=A,this}writeTo(A,e){var g;e.beginBlock(`def Preliminary_Text "${this.id}"`),this.content&&e.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||(this.font=[]),(g=this.font)==null||g.push("sans-serif"));const I=this.font.map(i=>`"${i}"`).join(", ");e.appendLine(`string[] font = [ ${I} ]`),e.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&e.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&e.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&e.appendLine(`double depth = ${this.depth}`),this.wrapMode&&e.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&e.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&e.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&e.appendLine(`rel material:binding = </Materials/Material_${this.material.id}>`),e.closeBlock()}}r(hn,"global_id",0);class Nw{static singleLine(A,e,g){const I=new hn("text_"+hn.getId());return I.content=A,e&&(I.pointSize=e),g&&(I.depth=g),I}static multiLine(A,e,g,I,i,o){const C=new hn("text_"+hn.getId());return C.content=A,C.width=e,C.height=g,C.horizontalAlignment=I,C.verticalAlignment=i,o!==void 0&&(C.wrapMode=o),C}}const DgA=new TA().makeRotationY(Math.PI);class Kw{get extensionName(){return"text"}onExportObject(A,e,g){const I=eA.getComponent(A,OI);if(I){const i=eA.getComponent(A,DI);let o=100,C=100;i&&(o=i.width,C=i.height);const s=e.clone();s.matrix=DgA.clone();const a=new fA().copySRGBToLinear(I.color);s.material=new zn({color:a,emissive:a}),e.add(s),s.addEventListener("serialize",(n,B)=>{const Q=Nw.multiLine(I.text,o,C,"center","bottom","flowing");this.setTextAlignment(Q,I.alignment),this.setOverflow(Q,I),s.material&&(Q.material=s.material),Q.pointSize=this.convertToTextSize(I.fontSize),Q.depth=.001,Q.writeTo(void 0,n)})}}convertToTextSize(A){return 1/.0502*144*A}setOverflow(A,e){e.horizontalOverflow?A.wrapMode="singleLine":A.wrapMode="flowing"}setTextAlignment(A,e){switch(e){case bg.LowerLeft:case bg.MiddleLeft:case bg.UpperLeft:A.horizontalAlignment="left";break;case bg.LowerCenter:case bg.MiddleCenter:case bg.UpperCenter:A.horizontalAlignment="center";break;case bg.LowerRight:case bg.MiddleRight:case bg.UpperRight:A.horizontalAlignment="right";break}switch(e){case bg.LowerLeft:case bg.LowerCenter:case bg.LowerRight:A.verticalAlignment="bottom";break;case bg.MiddleLeft:case bg.MiddleCenter:case bg.MiddleRight:A.verticalAlignment="middle";break;case bg.UpperLeft:case bg.UpperCenter:case bg.UpperRight:A.verticalAlignment="top";break}}}var wgA=Object.defineProperty,ygA=Object.getOwnPropertyDescriptor,so=(t,A,e,g)=>{for(var I=g>1?void 0:g?ygA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&wgA(A,e,I),I};const kC=aA("debugusdz");class cn{constructor(){r(this,"callToAction"),r(this,"checkoutTitle"),r(this,"checkoutSubtitle"),r(this,"callToActionURL")}}so([w()],cn.prototype,"callToAction",2),so([w()],cn.prototype,"checkoutTitle",2),so([w()],cn.prototype,"checkoutSubtitle",2),so([w()],cn.prototype,"callToActionURL",2);class ao extends RA{constructor(){super(...arguments),r(this,"objectToExport"),r(this,"autoExportAnimations",!1),r(this,"exportFileName"),r(this,"customUsdzFile"),r(this,"customBranding"),r(this,"anchoringType","plane"),r(this,"planeAnchoringAlignment","horizontal"),r(this,"interactive",!0),r(this,"extensions",[]),r(this,"link"),r(this,"webxr"),r(this,"webARSessionRoot"),r(this,"lastCallback"),r(this,"_quicklookButton"),r(this,"_quicklookButtonContainer",null)}start(){var A,e,g,I;kC&&(console.log(this),console.log("Debug USDZ, press 't' to export"),window.addEventListener("keydown",i=>{switch(i.key){case"t":this.exportAsync();break}}),Un()&&setTimeout(()=>{this.exportAsync()},2e3)),(A=document.getElementById("open-in-ar"))==null||A.addEventListener("click",i=>{i.preventDefault(),this.exportAsync()}),this.objectToExport||(this.objectToExport=this.gameObject),!((g=(e=this.objectToExport)==null?void 0:e.children)!=null&&g.length)&&!((I=this.objectToExport)!=null&&I.isMesh)&&(this.objectToExport=this.context.scene),this.interactive&&(this.extensions.push(new dw),this.extensions.push(new cw),this.extensions.push(new Kw))}onEnable(){const A=OE(),e=OC();(kC||A&&e)&&(this.addQuicklookButton(),this.webARSessionRoot=eA.findObjectOfType(Xa)??void 0,this.lastCallback=this.quicklookCallback.bind(this),this.link=cgA(this.context),this.link.addEventListener("message",this.lastCallback)),kC&&Hg("USDZ Exporter enabled: "+this.name)}onDisable(){var A;(A=this.link)==null||A.removeEventListener("message",this.lastCallback);const e=OE(),g=OC();(kC||e&&g)&&this.removeQuicklookButton(),kC&&Hg("USDZ Exporter disabled: "+this.name)}async exportAsync(){var A;let e=this.exportFileName??((A=this.objectToExport)==null?void 0:A.name)??this.name;if(qa()||(e+="-MadeWithNeedle"),e+="-"+lgA(),this.customUsdzFile){const E=this.buildQuicklookOverlay();kC&&console.log(E);const h=E.callToAction?encodeURIComponent(E.callToAction):"",c=E.checkoutTitle?encodeURIComponent(E.checkoutTitle):"",l=E.checkoutSubtitle?encodeURIComponent(E.checkoutSubtitle):"";this.link.href=this.customUsdzFile+`#callToAction=${h}&checkoutTitle=${c}&checkoutSubtitle=${l}&callToActionURL=${E.callToActionURL}`,console.log(this.link.href),this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click();return}if(!this.objectToExport)return;if(this.webARSessionRoot){const E=this.webARSessionRoot.gameObject,h=1/this.webARSessionRoot.arScale;E.matrix.makeScale(h,h,h),this.webARSessionRoot.invertForward&&E.matrix.multiply(new TA().makeRotationY(Math.PI))}const g=new J9,I=[...this.extensions],i=new UD;I.push(i),this.autoExportAnimations&&dgA(this.objectToExport,i);const o={self:this,exporter:g,extensions:I,object:this.objectToExport};this.dispatchEvent(new CustomEvent("before-export",{detail:o})),g.debug=kC,this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal");const C=await g.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:I,quickLookCompatible:!0}),s=new Blob([C],{type:"application/octet-stream"});this.dispatchEvent(new CustomEvent("after-export",{detail:o}));const a=this.buildQuicklookOverlay();kC&&console.log(a);const n=a.callToAction?encodeURIComponent(a.callToAction):"",B=a.checkoutTitle?encodeURIComponent(a.checkoutTitle):"",Q=a.checkoutSubtitle?encodeURIComponent(a.checkoutSubtitle):"";this.link.href=URL.createObjectURL(s)+`#callToAction=${n}&checkoutTitle=${B}&checkoutSubtitle=${Q}&callToActionURL=${a.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=e+".usdz",this.link.click()}quicklookCallback(A){if(A?.data=="_apple_ar_quicklook_button_tapped"){kC&&fo("Quicklook closed via call to action button");var e=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(e),!e.defaultPrevented){const g=new URLSearchParams(this.link.href);if(g){const I=g.get("callToActionURL");kC&&Hg("Quicklook url: "+I),I&&(qa()?globalThis.open(I,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",I))}}}}buildQuicklookOverlay(){var A,e,g;const I={};return this.customBranding&&Object.assign(I,this.customBranding),qa()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),I.callToAction="Close",I.checkoutTitle="\u{1F335} Made with Needle",I.checkoutSubtitle="_"),(A=I.callToAction)!=null&&A.length||(I.callToAction="Close"),(e=I.checkoutTitle)!=null&&e.length||(I.checkoutTitle="\u{1F335} Made with Needle"),(g=I.checkoutSubtitle)!=null&&g.length||(I.checkoutSubtitle="_"),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:I})),I}async createQuicklookButton(){var A,e;if(!this.webxr)if(await _E(1),this.webxr=eA.findObjectOfType(Se)??void 0,this.webxr)if(this.webxr.VRButton&&((A=this.webxr.VRButton.parentElement)==null||A.removeChild(this.webxr.VRButton)),this.webxr.ARButton&&this._quicklookButton!==this.webxr.ARButton){this._quicklookButton=this.webxr.ARButton;const g=(e=this.webxr.ARButton.parentElement)==null?void 0:e.querySelector("a");g&&(g.href=""),this.webxr.ARButton.innerText="Open in Quicklook",this.webxr.ARButton.disabled=!1,this.webxr.ARButton.addEventListener("click",I=>{I.preventDefault(),this.exportAsync()}),this.webxr.ARButton.classList.add("quicklook-ar-button"),this._quicklookButtonContainer=this.webxr.ARButton.parentElement,this.dispatchEvent(new CustomEvent("created-button",{detail:this.webxr.ARButton}))}else{this.webxr.createARButton=!1,this.webxr.createVRButton=!1;let g=window.document.querySelector(".webxr-buttons");g||(g=document.createElement("div"),g.classList.add("webxr-buttons"));const I=document.createElement("button");I.innerText="Open in Quicklook",I.addEventListener("click",()=>{this.exportAsync()}),I.classList.add("webxr-ar-button"),I.classList.add("webxr-button"),I.classList.add("quicklook-ar-button"),g.appendChild(I),this._quicklookButtonContainer=g,this.dispatchEvent(new CustomEvent("created-button",{detail:I}))}else console.warn("Could not find WebXR component: will not create Quicklook button",we.Current)}async addQuicklookButton(){await this.createQuicklookButton(),this._quicklookButton&&this._quicklookButtonContainer&&this._quicklookButtonContainer.appendChild(this._quicklookButton)}removeQuicklookButton(){var A;(A=this._quicklookButton)==null||A.remove()}}so([w(UA)],ao.prototype,"objectToExport",2),so([w()],ao.prototype,"autoExportAnimations",2),so([w()],ao.prototype,"exportFileName",2),so([w(URL)],ao.prototype,"customUsdzFile",2),so([w(cn)],ao.prototype,"customBranding",2),so([w()],ao.prototype,"anchoringType",2),so([w()],ao.prototype,"planeAnchoringAlignment",2),so([w()],ao.prototype,"interactive",2);const PH=aA("debugdeletable");class Jw extends rC{}class mM extends RA{constructor(){super(...arguments),r(this,"deleteBoxes",[])}awake(){this.deleteBoxes=eA.findObjectsOfType(Jw,this.context)}update(){for(const A of this.deleteBoxes){const e=this.gameObject;if(A.isInBox(e)===!0){const g=eA.getComponentInParent(this.gameObject,RQ);g?PH&&console.warn("Can not delete object with usage marker",this.guid,g):(PH&&console.log("DESTROY",this.gameObject),Fu(this.gameObject,this.context.connection))}}}}var SgA=Object.defineProperty,fgA=Object.getOwnPropertyDescriptor,vr=(t,A,e,g)=>{for(var I=g>1?void 0:g?fgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&SgA(A,e,I),I};class Ho extends TI{constructor(){super(...arguments),r(this,"mode"),r(this,"focusDistance"),r(this,"focalLength"),r(this,"aperture"),r(this,"gaussianMaxRadius"),r(this,"resolutionScale"),r(this,"bokehScale")}get typeName(){return"DepthOfField"}init(){this.focalLength.valueProcessor=e=>{const g=e/300,I=2;return XA.lerp(I,.01,g)};const A=20;this.aperture.valueProcessor=e=>{const g=1-e/32;return XA.lerp(1,A,g)}}onCreateEffect(){if(this.mode===0)return;const A=1/window.devicePixelRatio;if(this.resolutionScale===void 0){let g=1;Un()&&(g=.6),this.resolutionScale=new qe(g*A)}const e=new Ob(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=g=>{e.circleOfConfusionMaterial.worldFocusDistance=g},this.focalLength.onValueChanged=g=>e.circleOfConfusionMaterial.worldFocusRange=g,this.aperture.onValueChanged=g=>e.bokehScale=g,this.resolutionScale&&(this.resolutionScale.onValueChanged=g=>e.resolution.scale=g),[e]}unapply(){}}vr([w()],Ho.prototype,"mode",2),vr([w(qe)],Ho.prototype,"focusDistance",2),vr([w(qe)],Ho.prototype,"focalLength",2),vr([w(qe)],Ho.prototype,"aperture",2),vr([w(qe)],Ho.prototype,"gaussianMaxRadius",2),vr([w(qe)],Ho.prototype,"resolutionScale",2),vr([w(qe)],Ho.prototype,"bokehScale",2),uC("DepthOfField",Ho);var kgA=Object.defineProperty,GgA=Object.getOwnPropertyDescriptor,mgA=(t,A,e,g)=>{for(var I=g>1?void 0:g?GgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&kgA(A,e,I),I};class qw extends RA{constructor(){super(...arguments),r(this,"visibleOn")}onEnable(){this.apply()}apply(){this.test()||eA.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:MgA()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}mgA([w()],qw.prototype,"visibleOn",2);let bw;function MgA(){if(bw===!0||bw===!1)return bw;let t=!1;return function(A){(/(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(A)||/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(A.substr(0,4)))&&(t=!0)}(navigator.userAgent||navigator.vendor||window.opera),bw=t,t}class MM{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(A){}}var jH=(t=>(t.SelectStart="selectstart",t.SelectEnd="selectend",t))(jH||{});const ln=class extends MQ{constructor(){super(),r(this,"transformSelf",!0),r(this,"orbit",null),r(this,"selectStartEventListener",[]),r(this,"selectEndEventListener",[]),r(this,"_dragHelper",null),r(this,"_draggingRigidbodies",[]),r(this,"_waitingForDragStart",null),r(this,"_isDragging",!1),r(this,"_marker",null),r(this,"_dragDelta"),r(this,"_didDrag",!1),r(this,"_activePointerId"),this.selectStartEventListener=[],this.selectEndEventListener=[],this._dragDelta=new W}static get HasAnySelected(){return this._active>0}addDragEventListener(t,A){switch(t){case"selectstart":this.selectStartEventListener.push(A);break;case"selectend":this.selectEndEventListener.push(A);break}}start(){this.orbit=eA.findObjectOfType(vs,this.context)}allowEdit(t=null){return this.context.connection.allowEditing}onPointerEnter(t){if(!this.allowEdit(this.gameObject)||Se.IsInWebXR)return;const A=eA.getComponentInParent(t.object,ln);!A||A!==this||(ln.lastHovered=t.object,this.context.domElement.style.cursor="pointer")}onPointerExit(t){this.allowEdit(this.gameObject)&&(Se.IsInWebXR||ln.lastHovered===t.object&&(this.context.domElement.style.cursor="auto"))}onPointerDown(t){this.allowEdit(this.gameObject)&&(Se.IsInWebXR||(ln._active+=1,this._dragDelta.set(0,0),this._didDrag=!1,this._waitingForDragStart=t,t.StopPropagation(),this.orbit&&(this.orbit.enabled=!1)))}onPointerUp(t){this._waitingForDragStart=null,this.allowEdit(this.gameObject)&&(ln._active>0&&(ln._active-=1),!Se.IsInWebXR&&(this.onDragEnd(t),t.StopPropagation(),this.orbit&&(this.orbit.enabled=!0)))}update(){var t;if(!Se.IsInWebXR){if(this._waitingForDragStart){if(!this._didDrag){const e=this.context.input.getPointerPositionDelta(0);if(e&&this._dragDelta.add(e),this._dragDelta.length()>2)this._didDrag=!0;else return}const A=this._waitingForDragStart;this._waitingForDragStart=null,this.onDragStart(A)}this._dragHelper&&this._dragHelper.hasSelected&&this.onUpdateDrag(),(((t=this._dragHelper)==null?void 0:t.hasSelected)===!1||this._activePointerId!==void 0&&this.context.input.getPointerPressed(this._activePointerId)===!1)&&this.onDragEnd(null)}}onDragStart(t){if(!this._dragHelper)if(this.context.mainCamera)this._dragHelper=new VH(this.context.mainCamera);else return;if(!t||!t.object)return;const A=eA.getComponentInParent(t.object,ln);if(!A||A!==this)return;let e=t.object;this.transformSelf&&(e=this.gameObject);const g={selected:e,attached:e};for(const C of this.selectStartEventListener)C(this,g);if(this._activePointerId=t.pointerId,!g.attached)return;g.attached,e=g.attached,this._isDragging=!0,this._dragHelper.setSelected(e,this.context),this.orbit&&(this.orbit.enabled=!1);const I=eA.getComponentInChildren(e,tn);I&&(I.fastMode=!0,I?.requestOwnership()),this._marker=eA.addNewComponent(e,RQ),this._draggingRigidbodies.length=0;const i=eA.getComponentsInChildren(e,Ht);i&&this._draggingRigidbodies.push(...i);const o=yd();eA.invokeOnChildren(this._dragHelper.selected,o("onDragStart"))}onUpdateDrag(){if(this._dragHelper){this._dragHelper.onUpdate(this.context);for(const t of this._draggingRigidbodies)t.wakeUp(),t.resetVelocities()}}onDragEnd(t){if(!this||!this._isDragging||(this._isDragging=!1,!this._dragHelper))return;for(const g of this._draggingRigidbodies)g.setVelocity(g.smoothedVelocity);this._draggingRigidbodies.length=0;const A=this._dragHelper.selected;if(this._dragHelper.setSelected(null,this.context),this.orbit&&(this.orbit.enabled=!0),t!=null&&t.object){const g=eA.getComponentInChildren(t.object,tn);g&&(g.fastMode=!1)}this._marker&&this._marker.destroy();for(const g of this.selectEndEventListener)g(this);const e=yd();eA.invokeOnChildren(A,e("onDragEnd"))}};let iE=ln;r(iE,"_active",0),r(iE,"lastHovered");const WH=class{constructor(t){r(this,"_selected",null),r(this,"_context",null),r(this,"_camera"),r(this,"_cameraPlane",new Hi),r(this,"_hasGroundPlane",!1),r(this,"_groundPlane",new Hi),r(this,"_groundOffset",new f),r(this,"_groundOffsetFactor",0),r(this,"_groundDistance",0),r(this,"_groundPlanePoint",new f),r(this,"_raycaster",new TB),r(this,"_cameraPlaneOffset",new f),r(this,"_intersection",new f),r(this,"_worldPosition",new f),r(this,"_inverseMatrix",new TA),r(this,"_rbs",[]),r(this,"_groundLine"),r(this,"_groundMarker"),r(this,"_groundOffsetVector",new f(0,1,0)),r(this,"_requireUpdateGroundPlane",!0),r(this,"_didDragOnGroundPlaneLastFrame",!1),this._camera=t;const A=new Ag(WH.geometry),e=A.material;e.color=new fA(.4,.4,.4),A.layers.set(2),A.name="line",A.scale.y=1,this._groundLine=A;const g=new Qo(.5,22,22),I=new lt({color:e.color}),i=new yA(g,I);i.visible=!1,i.layers.set(2),this._groundMarker=i}get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}setSelected(t,A){if(this._selected&&A)for(const e of this._rbs)e.wakeUp(),e.setVelocity(0,0,0);if(this._selected&&YI.Remove(A,this._selected),this._selected=t,this._context=A,this._rbs.length=0,t?(A.scene.add(this._groundLine),A.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!A){console.error("DragHelper: no context");return}YI.Add(A,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}onUpdate(t){var A,e,g,I,i;if(!this._context)return;const o="Space",C="KeyD",s=((A=this._context)==null?void 0:A.input.isKeyPressed(o))||((e=this._context)==null?void 0:e.input.isKeyPressed(C)),a=this._context.input.getTouchesPressedCount()>=2||s;if(a){const B=this._context.input.getPointerPositionDelta(0);B&&(this._groundOffsetVector.set(0,1,0),(g=this._selected)==null||g.rotateOnWorldAxis(this._groundOffsetVector,B.x*this._context.time.deltaTime))}const n=this._context.input.getPointerPositionRC(0);if(n&&(this._raycaster.setFromCamera(n,this._camera),this._selected)){this._groundOffsetVector.set(0,1,0);const B=ye(this._camera).clone().sub(ye(this._selected)).normalize(),Q=Math.abs(B.dot(this._groundOffsetVector)),E=((I=this._context)==null?void 0:I.input.isKeyPressed(o))||((i=this._context)==null?void 0:i.input.isKeyPressed(C)),h=!a&&Q>.2&&!E&&this._context.input.getPointerPressedCount()<=1,c=this._didDragOnGroundPlaneLastFrame!==h;if(this._didDragOnGroundPlaneLastFrame=h,this._hasGroundPlane||(this._requireUpdateGroundPlane=!0),(this._requireUpdateGroundPlane||!h||c)&&this.onUpdateGroundPlane(),this._requireUpdateGroundPlane=!1,this._hasGroundPlane)if(this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection)){const l=this._intersection.y;if(this._groundPlanePoint.copy(this._intersection).sub(this._groundOffset),this._groundPlanePoint.y=l,h){this._groundOffsetVector.set(0,1,0);const d=this._intersection.sub(this._groundOffset).add(this._groundOffsetVector.multiplyScalar(this._groundOffsetFactor));this.onUpdateWorldPosition(d,this._groundPlanePoint,!1),this.onDidUpdate();return}}else this._groundPlanePoint.set(0,99999,0);c&&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(t,A,e){if(this._selected){if(e){const g=ye(this._selected);g.y=t.y,t=g}if(tg(this._selected,t),tg(this._groundLine,t),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundMarker.visible=A!==null,A){const g=ye(this._camera).distanceTo(A)*.01;this._groundMarker.scale.set(g,g,g),tg(this._groundMarker,A)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const t=this._context.input.getPointerPositionRC(0);t&&(this._raycaster.setFromCamera(t,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;const t=ye(this._selected),A=new As(new f(0,.1,0).add(t),new f(0,-1,0)),e=new Go;e.ignore=[this._selected];const g=this._context.physics.raycastFromRay(A,e);for(let I=0;I<g.length;I++){const i=g[I];if(!i.face||this.contains(this._selected,i.object))continue;const o=new f(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(o,i.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(A.direction.multiplyScalar(-1),A.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(t),this._groundOffset.copy(this._intersection).sub(t)}onDidUpdate(){Ei.markDirty(this._selected);for(const t of this._rbs)t.wakeUp(),t.resetForcesAndTorques(),t.setAngularVelocity(0,0,0)}contains(t,A){if(t===A)return!0;if(t.children){for(const e of t.children)if(this.contains(e,A))return!0}return!1}};let VH=WH;r(VH,"geometry",new pe().setFromPoints([new f(0,0,0),new f(0,-1,0)]));function RM(t,A,e){console.warn("Adding components on object has been temporarily disabled")}var zH=(t=>(t.File_Spawned="file-spawned",t))(zH||{});class ZH{constructor(A,e,g,I,i,o,C,s){r(this,"guid"),r(this,"file_name"),r(this,"file_hash"),r(this,"file_size"),r(this,"position"),r(this,"seed"),r(this,"sender"),r(this,"serverUrl"),r(this,"parentGuid"),r(this,"boundsSize"),this.seed=e,this.guid=g,this.file_name=I,this.file_hash=i,this.file_size=o,this.position=C,this.sender=A,this.serverUrl=s}}async function UM(t,A,e){const g=t.name;return g.endsWith(".gltf")||g.endsWith(".glb")?new Promise((I,i)=>{const o=new FileReader;o.readAsArrayBuffer(t),o.onloadend=async C=>{const s=o.result,a=Nu(),n=new VI(a),B=await Uo().parseSync(A,s,t.name,n);if(B&&B.scene){const Q=B.scene;if(!Q.guid){const E=new VI(a);Q.guid=E.generateUUID()}e&&RgA(A.connection,t,a,Q,e),RM(),I(B)}}}):(console.warn("Unsupported file type: "+g),console.log(t),null)}async function XH(t,A){return new Promise(async(e,g)=>{const I=Nu(),i=new VI(I),o=t.toString(),C=await Uo().loadSync(A,o,o,i);C&&C.scene?(C.scene,RM(),e(C)):console.warn("Unsupported file type: "+t.toString())})}_t.registerCallback(ci.ContextCreated,t=>{$H(t.context)});function $H(t){t.connection.beginListen("file-spawned",async A=>{if(A.sender!==t.connection.connectionId){console.log("received file event",A),UgA(A,t);let e=null;try{e=await bk(A.file_name,A.file_hash,A.file_size,A.serverUrl)}finally{FgA(A)}if(e){const g=new VI(A.seed),I=await Uo().parseSync(t,e,null,g);if(I&&I.scene){const i=I.scene;if(RM(),A.parentGuid){const o=zh(A.parentGuid,t.scene);"add"in o&&o.add(i)}i.parent||t.scene.add(i),A.position!==null&&i.position.copy(A.position)}}else console.error("download didnt return file")}})}async function RgA(t,A,e,g,I){if(!t.connectionId){console.error("Can not upload file - no connection id");return}if(!g.guid){console.error("Can not upload file - no guid",g,g.guid);return}const i=await av(A,I);if(!i)return;if(!i.filename){console.error("Can not send upload event - no filename",A.name);return}if(!i.hash){console.error("Can not send upload event - no hash",A.name);return}const o=new ZH(t.connectionId,e,g.guid,i.filename,i.hash,A.size,g.position,i.url??I);g.parent&&(o.parentGuid=g.parent.guid),t.send("file-spawned",o)}const FM={};function UgA(t,A){const e=new pt,g=new yA(e,new lt({color:65280})),I=new Xp(g,5592405);if(FM[t.guid]=I,A.scene.add(I),t.parentGuid){const i=zh(t.parentGuid,A.scene);i&&i.add(I)}t.position&&I.position.copy(t.position)}function FgA(t,A){const e=t.guid,g=FM[e];g&&(delete FM[e],g.removeFromParent())}var NgA=Object.defineProperty,KgA=Object.getOwnPropertyDescriptor,NM=(t,A,e,g)=>{for(var I=g>1?void 0:g?KgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&NgA(A,e,I),I};const JgA=aA("debugnet"),KM=class extends RA{constructor(){super(...arguments),r(this,"url",null),r(this,"urlParameterName",null),r(this,"localhost",null)}awake(){JgA&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let t=this.url?KM.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const e=aA(this.urlParameterName);e&&typeof e=="string"&&(t=e)}if(!t)return null;const A=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(t);return A!=null&&A.groups?A?.groups.socket_prefix?t:"wss://"+A?.groups.url:null}static GetUrl(t,A){let e=t;const g=KM.IsLocalNetwork()&&A;return g&&(e=A),t!=null&&t.startsWith("/")&&(e=(g?e:window.location.origin)+t),e}static IsLocalNetwork(t=window.location.hostname){return fI(t)}};let Lr=KM;NM([w()],Lr.prototype,"url",2),NM([w()],Lr.prototype,"urlParameterName",2),NM([w()],Lr.prototype,"localhost",2);var qgA=Object.defineProperty,bgA=Object.getOwnPropertyDescriptor,AT=(t,A,e,g)=>{for(var I=g>1?void 0:g?bgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&qgA(A,e,I),I};class hl extends RA{constructor(){super(...arguments),r(this,"filesBackendUrl"),r(this,"localhost"),r(this,"_dragOver"),r(this,"_drop")}onEnable(){this.filesBackendUrl=this.filesBackendUrl?Lr.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(A){A.preventDefault()}async addFiles(A){for(const e of A){if(!e)continue;console.log("Register file "+e.name+" to",this.filesBackendUrl,e);const g=await UM(e,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:e})),g&&this.addObject(void 0,g)}}async onDrop(A){if(console.log(A),!A.dataTransfer)return;A.preventDefault();const e=A.dataTransfer.items;if(e)for(const g in e){const I=e[g];if(I.kind==="file"){const i=I.getAsFile();if(!i)continue;console.log("Register file "+i.name+" to",this.filesBackendUrl,i);const o=await UM(i,this.context,this.filesBackendUrl);this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),o&&this.addObject(A,o)}else I.kind==="string"&&I.type=="text/plain"&&I.getAsString(async i=>{console.log("dropped url",i);try{const o=new URL(i);if(!o)return;const C=await XH(o,this.context);C&&this.addObject(A,C)}catch{console.log("dropped string is not a valid URL!",i)}})}}async addObject(A,e){console.log("Dropped",e);const g=e.scene;if(A!==void 0){const I=new Go;I.setMask(16777215),I.screenPointFromOffset(A.offsetX,A.offsetY);const i=this.context.physics.raycast(I);if(i&&i.length>0)for(const o of i){g.position.copy(o.point);break}}this.gameObject.add(g),this.dispatchEvent(new CustomEvent("object-added",{detail:e}))}}AT([w()],hl.prototype,"filesBackendUrl",2),AT([w()],hl.prototype,"localhost",2);var vgA=Object.defineProperty,LgA=Object.getOwnPropertyDescriptor,vw=(t,A,e,g)=>{for(var I=g>1?void 0:g?LgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&vgA(A,e,I),I};class xr extends MQ{constructor(){super(...arguments),r(this,"parent",null),r(this,"object",null),r(this,"limitCount",10),r(this,"limitInterval",60),r(this,"_currentCount",0),r(this,"_startPosition",null),r(this,"_startQuaternion",null)}awake(){var A,e;if(this.object){if(this.object===this.gameObject){console.error("Can not duplicate self");return}this.object.visible=!1,this._startPosition=((A=this.object.position)==null?void 0:A.clone())??new f(0,0,0),this._startQuaternion=((e=this.object.quaternion)==null?void 0:e.clone())??new GA(0,0,0,1)}const g=eA.getComponentInParent(this.gameObject,iE);g?g.addDragEventListener(jH.SelectStart,(I,i)=>{if(this._currentCount>=this.limitCount){i.attached=null;return}const o=this.handleDuplication(i.selected);o&&(console.assert(o!==i.selected,"Duplicated object is original"),i.attached=o)}):console.warn("Could no find drag controls in parent",this.name),dg.addEventListener(Ks.SelectStart,(I,i)=>{if(this._currentCount>=this.limitCount){i.grab=null;return}const o=this.handleDuplication(i.selected);o&&(i.grab=o)}),this.cloneLimitIntervalFn()}cloneLimitIntervalFn(){this.destroyed||(this._currentCount>0&&(this._currentCount-=1),setTimeout(()=>{this.cloneLimitIntervalFn()},this.limitInterval/this.limitCount*1e3))}handleDuplication(A){var e;if(this._currentCount>=this.limitCount||!this.object)return null;if(A===this.gameObject||this.handleMultiObject(A)){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);const g=new gC;this.parent||(this.parent=this.gameObject.parent),this.parent&&(g.parent=this.parent.guid??((e=this.parent.userData)==null?void 0:e.guid),g.keepWorldPosition=!0),g.position=this.worldPosition,g.rotation=this.worldQuaternion,g.context=this.context,this._currentCount+=1;const I=eA.instantiateSynced(this.object,g);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(A){return this.gameObject.type==="Group"||this.gameObject.type==="Object3D"?this.isInChildren(this.gameObject,A):!1}isInChildren(A,e){if(!A)return!1;if(A===e)return!0;if(A.children){for(let g of A.children)if(this.isInChildren(g,e))return!0}return!1}}vw([w(UA)],xr.prototype,"parent",2),vw([w(UA)],xr.prototype,"object",2),vw([w()],xr.prototype,"limitCount",2),vw([w()],xr.prototype,"limitInterval",2);var oE=(t=>(t[t.PointerEnter=0]="PointerEnter",t[t.PointerExit=1]="PointerExit",t[t.PointerDown=2]="PointerDown",t[t.PointerUp=3]="PointerUp",t[t.PointerClick=4]="PointerClick",t[t.Drag=5]="Drag",t[t.Drop=6]="Drop",t[t.Scroll=7]="Scroll",t[t.UpdateSelected=8]="UpdateSelected",t[t.Select=9]="Select",t[t.Deselect=10]="Deselect",t[t.Move=11]="Move",t[t.InitializePotentialDrag=12]="InitializePotentialDrag",t[t.BeginDrag=13]="BeginDrag",t[t.EndDrag=14]="EndDrag",t[t.Submit=15]="Submit",t[t.Cancel=16]="Cancel",t))(oE||{}),xgA=Object.defineProperty,YgA=Object.getOwnPropertyDescriptor,JM=(t,A,e,g)=>{for(var I=g>1?void 0:g?YgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&xgA(A,e,I),I};class qM{constructor(){r(this,"eventID"),r(this,"callback")}}JM([w()],qM.prototype,"eventID",2),JM([w(ti)],qM.prototype,"callback",2);class Lw extends RA{constructor(){super(...arguments),r(this,"triggers")}invoke(A){if(this.triggers)for(const e of this.triggers)e.eventID===A&&e.callback.invoke()}onPointerClick(A){this.invoke(oE.PointerClick)}onPointerEnter(A){this.invoke(oE.PointerEnter)}onPointerExit(A){this.invoke(oE.PointerExit)}onPointerDown(A){this.invoke(oE.PointerDown)}onPointerUp(A){this.invoke(oE.PointerUp)}}JM([w(qM)],Lw.prototype,"triggers",2);var HgA=Object.defineProperty,TgA=Object.getOwnPropertyDescriptor,bM=(t,A,e,g)=>{for(var I=g>1?void 0:g?TgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&HgA(A,e,I),I};class vM extends RA{constructor(){super(...arguments),r(this,"connectedBody"),r(this,"_rigidBody",null)}get rigidBody(){return this._rigidBody}onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ht)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.createJoint(this.rigidBody,this.connectedBody)}}bM([w(Ht)],vM.prototype,"connectedBody",2);class LM extends vM{createJoint(A,e){var g;(g=this.context.physics.engine)==null||g.addFixedJoint(A,e)}}class cl extends vM{constructor(){super(...arguments),r(this,"anchor"),r(this,"axis")}createJoint(A,e){var g;this.axis&&this.anchor&&((g=this.context.physics.engine)==null||g.addHingeJoint(A,e,this.anchor,this.axis))}}bM([w(f)],cl.prototype,"anchor",2),bM([w(f)],cl.prototype,"axis",2);const _gA={type:"change"};let OgA=class extends mg{constructor(t,A){super(),this.object=t,this.domElement=A,this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1;const e=this,g=1e-6,I=new GA,i=new f;this.tmpQuaternion=new GA,this.status=0,this.moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this.moveVector=new f(0,0,0),this.rotationVector=new f(0,0,0),this.keydown=function(B){if(!B.altKey){switch(B.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this.moveState.forward=1;break;case"KeyS":this.moveState.back=1;break;case"KeyA":this.moveState.left=1;break;case"KeyD":this.moveState.right=1;break;case"KeyR":this.moveState.up=1;break;case"KeyF":this.moveState.down=1;break;case"ArrowUp":this.moveState.pitchUp=1;break;case"ArrowDown":this.moveState.pitchDown=1;break;case"ArrowLeft":this.moveState.yawLeft=1;break;case"ArrowRight":this.moveState.yawRight=1;break;case"KeyQ":this.moveState.rollLeft=1;break;case"KeyE":this.moveState.rollRight=1;break}this.updateMovementVector(),this.updateRotationVector()}},this.keyup=function(B){switch(B.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this.moveState.forward=0;break;case"KeyS":this.moveState.back=0;break;case"KeyA":this.moveState.left=0;break;case"KeyD":this.moveState.right=0;break;case"KeyR":this.moveState.up=0;break;case"KeyF":this.moveState.down=0;break;case"ArrowUp":this.moveState.pitchUp=0;break;case"ArrowDown":this.moveState.pitchDown=0;break;case"ArrowLeft":this.moveState.yawLeft=0;break;case"ArrowRight":this.moveState.yawRight=0;break;case"KeyQ":this.moveState.rollLeft=0;break;case"KeyE":this.moveState.rollRight=0;break}this.updateMovementVector(),this.updateRotationVector()},this.pointerdown=function(B){if(this.dragToLook)this.status++;else{switch(B.button){case 0:this.moveState.forward=1;break;case 2:this.moveState.back=1;break}this.updateMovementVector()}},this.pointermove=function(B){if(!this.dragToLook||this.status>0){const Q=this.getContainerDimensions(),E=Q.size[0]/2,h=Q.size[1]/2;this.moveState.yawLeft=-(B.pageX-Q.offset[0]-E)/E,this.moveState.pitchDown=(B.pageY-Q.offset[1]-h)/h,this.updateRotationVector()}},this.pointerup=function(B){if(this.dragToLook)this.status--,this.moveState.yawLeft=this.moveState.pitchDown=0;else{switch(B.button){case 0:this.moveState.forward=0;break;case 2:this.moveState.back=0;break}this.updateMovementVector()}this.updateRotationVector()},this.update=function(B){const Q=B*e.movementSpeed,E=B*e.rollSpeed;e.object.translateX(e.moveVector.x*Q),e.object.translateY(e.moveVector.y*Q),e.object.translateZ(e.moveVector.z*Q),e.tmpQuaternion.set(e.rotationVector.x*E,e.rotationVector.y*E,e.rotationVector.z*E,1).normalize(),e.object.quaternion.multiply(e.tmpQuaternion),(i.distanceToSquared(e.object.position)>g||8*(1-I.dot(e.object.quaternion))>g)&&(e.dispatchEvent(_gA),I.copy(e.object.quaternion),i.copy(e.object.position))},this.updateMovementVector=function(){const B=this.moveState.forward||this.autoForward&&!this.moveState.back?1:0;this.moveVector.x=-this.moveState.left+this.moveState.right,this.moveVector.y=-this.moveState.down+this.moveState.up,this.moveVector.z=-B+this.moveState.back},this.updateRotationVector=function(){this.rotationVector.x=-this.moveState.pitchDown+this.moveState.pitchUp,this.rotationVector.y=-this.moveState.yawRight+this.moveState.yawLeft,this.rotationVector.z=-this.moveState.rollRight+this.moveState.rollLeft},this.getContainerDimensions=function(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}},this.dispose=function(){this.domElement.removeEventListener("contextmenu",eT),this.domElement.removeEventListener("pointerdown",C),this.domElement.removeEventListener("pointermove",o),this.domElement.removeEventListener("pointerup",s),window.removeEventListener("keydown",a),window.removeEventListener("keyup",n)};const o=this.pointermove.bind(this),C=this.pointerdown.bind(this),s=this.pointerup.bind(this),a=this.keydown.bind(this),n=this.keyup.bind(this);this.domElement.addEventListener("contextmenu",eT),this.domElement.addEventListener("pointerdown",C),this.domElement.addEventListener("pointermove",o),this.domElement.addEventListener("pointerup",s),window.addEventListener("keydown",a),window.addEventListener("keyup",n),this.updateMovementVector(),this.updateRotationVector()}};function eT(t){t.preventDefault()}class xM extends RA{constructor(){super(...arguments),r(this,"_controls",null)}onEnable(){var A;const e=(A=eA.getComponent(this.gameObject,Kt))==null?void 0:A.cam;this._controls=new OgA(e,this.context.renderer.domElement),this._controls.rollSpeed=.5,this._controls.movementSpeed=3,this._controls.dragToLook=!0}onDisable(){var A;(A=this._controls)==null||A.dispose(),this._controls=null}update(){this._controls&&this._controls.update(this.context.time.deltaTime)}}var PgA=Object.defineProperty,jgA=Object.getOwnPropertyDescriptor,YM=(t,A,e,g)=>{for(var I=g>1?void 0:g?jgA(A,e):A,i=t.length-1,o;i>=0;i--)(o=t[i])&&(I=(g?o(A,e,I):o(I))||I);return g&&I&&PgA(A,e,I),I};class CE extends RA{constructor(){super(...arguments),r(this,"_fog")}get fog(){return this._fog||(this._fog=new O0(0,0,50)),this._fog}get mode(){return 1}set near(A){this.fog.near=A}get near(){return this.fog.near}set far(A){this.fog.far=A}get far(){return this.fog.far}set color(A){this.fog.color.copy(A)}get color(){return this.fog.color}onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}YM([w()],CE.prototype,"near",1),YM([w()],CE.prototype,"far",1),YM([w(fA)],CE.prototype,"color",1);let HM,TM,sE,xw;function _M(t,A,e){TM||(TM=new Wg(2,2,1,1)),sE||(sE=new je({uniforms:{blitTexture:new mA(t)},vertexShader:`
|
|
4562
4562
|
varying vec2 vUv;
|
|
4563
4563
|
void main(){
|
|
4564
4564
|
vUv = uv;
|