@chronodivide/game-api 0.57.0 → 0.59.0

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/dist/index.js CHANGED
@@ -1 +1 @@
1
- import*as __WEBPACK_EXTERNAL_MODULE_fetch_blob_71f8024a__ from"fetch-blob";import*as __WEBPACK_EXTERNAL_MODULE_three__ from"three";import*as __WEBPACK_EXTERNAL_MODULE_websocket_polyfill_8396782d__ from"websocket-polyfill";import{createRequire as __WEBPACK_EXTERNAL_createRequire}from"module";import*as __WEBPACK_EXTERNAL_MODULE_es_dirname_044d89a0__ from"es-dirname";import*as __WEBPACK_EXTERNAL_MODULE_file_system_access_58c08c7f__ from"file-system-access";import*as __WEBPACK_EXTERNAL_MODULE_file_system_access_lib_adapters_node_js_b1c03fd5__ from"file-system-access/lib/adapters/node.js";var __webpack_modules__={251:(e,t,i)=>{i.r(t),i.d(t,{default:()=>s});const s=function(){"use strict";var i=new function(){this.blockSize=131072,this.minNewSize=this.blockSize,this.maxSize=0,this.OK=0,this.INPUT_OVERRUN=-4,this.OUTPUT_OVERRUN=-5,this.LOOKBEHIND_OVERRUN=-6,this.EOF_FOUND=-999,this.ret=0,this.buf=null,this.buf32=null,this.out=new Uint8Array(262144),this.cbl=0,this.ip_end=0,this.op_end=0,this.t=0,this.ip=0,this.op=0,this.m_pos=0,this.m_len=0,this.m_off=0,this.dv_hi=0,this.dv_lo=0,this.dindex=0,this.ii=0,this.jj=0,this.tt=0,this.v=0,this.dict=new Uint32Array(16384),this.emptyDict=new Uint32Array(16384),this.skipToFirstLiteralFun=!1,this.returnNewBuffers=!0,this.setBlockSize=function(e){return"number"==typeof e&&!isNaN(e)&&0<parseInt(e)&&(this.blockSize=parseInt(e),!0)},this.setOutputSize=function(e){return"number"==typeof e&&!isNaN(e)&&0<parseInt(e)&&(this.out=new Uint8Array(parseInt(e)),!0)},this.setReturnNewBuffers=function(e){this.returnNewBuffers=!!e},this.applyConfig=function(e){void 0!==e&&(void 0!==e.outputSize&&i.setOutputSize(e.outputSize),void 0!==e.blockSize&&i.setBlockSize(e.blockSize))},this.ctzl=function(e){var t;return 1&e?t=0:(t=1,0==(65535&e)&&(e>>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),t-=1&e),t},this.extendBuffer=function(){var e=new Uint8Array(this.minNewSize+(this.blockSize-this.minNewSize%this.blockSize));e.set(this.out),this.out=e,this.cbl=this.out.length},this.match_next=function(){this.minNewSize=this.op+3,this.minNewSize>this.cbl&&this.extendBuffer(),this.out[this.op++]=this.buf[this.ip++],1<this.t&&(this.out[this.op++]=this.buf[this.ip++],2<this.t&&(this.out[this.op++]=this.buf[this.ip++])),this.t=this.buf[this.ip++]},this.match_done=function(){return this.t=3&this.buf[this.ip-2],this.t},this.copy_match=function(){for(this.t+=2,this.minNewSize=this.op+this.t,this.minNewSize>this.cbl&&this.extendBuffer();this.out[this.op++]=this.out[this.m_pos++],0<--this.t;);},this.copy_from_buf=function(){for(this.minNewSize=this.op+this.t,this.minNewSize>this.cbl&&this.extendBuffer();this.out[this.op++]=this.buf[this.ip++],0<--this.t;);},this.match=function(){for(;;){if(64<=this.t)this.m_pos=this.op-1-(this.t>>2&7)-(this.buf[this.ip++]<<3),this.t=(this.t>>5)-1,this.copy_match();else if(32<=this.t){if(this.t&=31,0===this.t){for(;0===this.buf[this.ip];)this.t+=255,this.ip++;this.t+=31+this.buf[this.ip++]}this.m_pos=this.op-1-(this.buf[this.ip]>>2)-(this.buf[this.ip+1]<<6),this.ip+=2,this.copy_match()}else if(16<=this.t){if(this.m_pos=this.op-((8&this.t)<<11),this.t&=7,0===this.t){for(;0===this.buf[this.ip];)this.t+=255,this.ip++;this.t+=7+this.buf[this.ip++]}if(this.m_pos-=(this.buf[this.ip]>>2)+(this.buf[this.ip+1]<<6),this.ip+=2,this.m_pos===this.op)return this.state.outputBuffer=!0===this.returnNewBuffers?new Uint8Array(this.out.subarray(0,this.op)):this.out.subarray(0,this.op),this.EOF_FOUND;this.m_pos-=16384,this.copy_match()}else this.m_pos=this.op-1-(this.t>>2)-(this.buf[this.ip++]<<2),this.minNewSize=this.op+2,this.minNewSize>this.cbl&&this.extendBuffer(),this.out[this.op++]=this.out[this.m_pos++],this.out[this.op++]=this.out[this.m_pos];if(0===this.match_done())return this.OK;this.match_next()}},this.decompress=function(e){if(this.state=e,this.buf=this.state.inputBuffer,this.cbl=this.out.length,this.ip_end=this.buf.length,this.t=0,this.ip=0,this.op=0,this.m_pos=0,this.skipToFirstLiteralFun=!1,17<this.buf[this.ip])if(this.t=this.buf[this.ip++]-17,this.t<4){if(this.match_next(),this.ret=this.match(),this.ret!==this.OK)return this.ret===this.EOF_FOUND?this.OK:this.ret}else this.copy_from_buf(),this.skipToFirstLiteralFun=!0;for(;;){if(this.skipToFirstLiteralFun)this.skipToFirstLiteralFun=!1;else{if(this.t=this.buf[this.ip++],16<=this.t){if(this.ret=this.match(),this.ret!==this.OK)return this.ret===this.EOF_FOUND?this.OK:this.ret;continue}if(0===this.t){for(;0===this.buf[this.ip];)this.t+=255,this.ip++;this.t+=15+this.buf[this.ip++]}this.t+=3,this.copy_from_buf()}if(this.t=this.buf[this.ip++],this.t<16){if(this.m_pos=this.op-2049,this.m_pos-=this.t>>2,this.m_pos-=this.buf[this.ip++]<<2,this.minNewSize=this.op+3,this.minNewSize>this.cbl&&this.extendBuffer(),this.out[this.op++]=this.out[this.m_pos++],this.out[this.op++]=this.out[this.m_pos++],this.out[this.op++]=this.out[this.m_pos],0===this.match_done())continue;this.match_next()}if(this.ret=this.match(),this.ret!==this.OK)return this.ret===this.EOF_FOUND?this.OK:this.ret}return this.OK},this._compressCore=function(){for(this.ip_start=this.ip,this.ip_end=this.ip+this.ll-20,this.jj=this.ip,this.ti=this.t,this.ip+=this.ti<4?4-this.ti:0,this.ip+=1+(this.ip-this.jj>>5);!(this.ip>=this.ip_end);)if(this.dv_lo=this.buf[this.ip]|this.buf[this.ip+1]<<8,this.dv_hi=this.buf[this.ip+2]|this.buf[this.ip+3]<<8,this.dindex=((17053*this.dv_lo>>>16)+17053*this.dv_hi+6180*this.dv_lo&65535)>>>2,this.m_pos=this.ip_start+this.dict[this.dindex],this.dict[this.dindex]=this.ip-this.ip_start,(this.dv_hi<<16)+this.dv_lo==(this.buf[this.m_pos]|this.buf[this.m_pos+1]<<8|this.buf[this.m_pos+2]<<16|this.buf[this.m_pos+3]<<24)){if(this.jj-=this.ti,this.ti=0,this.v=this.ip-this.jj,0!==this.v)if(this.v<=3)for(this.out[this.op-2]|=this.v;this.out[this.op++]=this.buf[this.jj++],0<--this.v;);else{if(this.v<=18)this.out[this.op++]=this.v-3;else{for(this.tt=this.v-18,this.out[this.op++]=0;255<this.tt;)this.tt-=255,this.out[this.op++]=0;this.out[this.op++]=this.tt}for(;this.out[this.op++]=this.buf[this.jj++],0<--this.v;);}if(this.m_len=4,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len])for(;this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&!(this.ip+this.m_len>=this.ip_end)&&this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]))))))););if(this.m_off=this.ip-this.m_pos,this.ip+=this.m_len,this.jj=this.ip,this.m_len<=8&&this.m_off<=2048)--this.m_off,this.out[this.op++]=this.m_len-1<<5|(7&this.m_off)<<2,this.out[this.op++]=this.m_off>>3;else if(this.m_off<=16384){if(--this.m_off,this.m_len<=33)this.out[this.op++]=32|this.m_len-2;else{for(this.m_len-=33,this.out[this.op++]=32;255<this.m_len;)this.m_len-=255,this.out[this.op++]=0;this.out[this.op++]=this.m_len}this.out[this.op++]=this.m_off<<2,this.out[this.op++]=this.m_off>>6}else{if(this.m_off-=16384,this.m_len<=9)this.out[this.op++]=16|this.m_off>>11&8|this.m_len-2;else{for(this.m_len-=9,this.out[this.op++]=16|this.m_off>>11&8;255<this.m_len;)this.m_len-=255,this.out[this.op++]=0;this.out[this.op++]=this.m_len}this.out[this.op++]=this.m_off<<2,this.out[this.op++]=this.m_off>>6}}else this.ip+=1+(this.ip-this.jj>>5);this.t=this.ll-(this.jj-this.ip_start-this.ti)},this.compress=function(e){for(this.state=e,this.ip=0,this.buf=this.state.inputBuffer,this.maxSize=this.buf.length+Math.ceil(this.buf.length/16)+64+3,this.maxSize>this.out.length&&(this.out=new Uint8Array(this.maxSize)),this.op=0,this.l=this.buf.length,this.t=0;20<this.l&&(this.ll=this.l<=49152?this.l:49152,!(this.t+this.ll>>5<=0));)this.dict.set(this.emptyDict),this.prev_ip=this.ip,this._compressCore(),this.ip=this.prev_ip+this.ll,this.l-=this.ll;if(this.t+=this.l,0<this.t){if(this.ii=this.buf.length-this.t,0===this.op&&this.t<=238)this.out[this.op++]=17+this.t;else if(this.t<=3)this.out[this.op-2]|=this.t;else if(this.t<=18)this.out[this.op++]=this.t-3;else{for(this.tt=this.t-18,this.out[this.op++]=0;255<this.tt;)this.tt-=255,this.out[this.op++]=0;this.out[this.op++]=this.tt}for(;this.out[this.op++]=this.buf[this.ii++],0<--this.t;);}return this.out[this.op++]=17,this.out[this.op++]=0,this.out[this.op++]=0,this.state.outputBuffer=!0===this.returnNewBuffers?new Uint8Array(this.out.subarray(0,this.op)):this.out.subarray(0,this.op),this.OK}};return{setBlockSize:function(e){return i.setBlockSize(e)},setOutputEstimate:function(e){return i.setOutputSize(e)},setReturnNewBuffers:function(e){i.setReturnNewBuffers(e)},compress:function(e,t){return void 0!==t&&i.applyConfig(t),i.compress(e)},decompress:function(e,t){return void 0!==t&&i.applyConfig(t),i.decompress(e)}}}()},163:function(h,l,c){var u;!function(){"use strict";function e(e,t){return function(){return t.apply(e,arguments)}}function i(){for(var e,t=arguments,i=t[0],s=1;s<t.length;s++)for(e in t[s])e in i||!t[s].hasOwnProperty(e)||(i[e]=t[s][e]);return i}var s,o={VERSION:"1.4.1"},r={},t=function(e,t){return{value:e,name:t}};o.DEBUG=t(1,"DEBUG"),o.INFO=t(2,"INFO"),o.TIME=t(3,"TIME"),o.WARN=t(4,"WARN"),o.ERROR=t(8,"ERROR"),o.OFF=t(99,"OFF");function a(e){this.context=e,this.setLevel(e.filterLevel),this.log=this.info}a.prototype={setLevel:function(e){e&&"value"in e&&(this.context.filterLevel=e)},getLevel:function(){return this.context.filterLevel},enabledFor:function(e){var t=this.context.filterLevel;return e.value>=t.value},debug:function(){this.invoke(o.DEBUG,arguments)},info:function(){this.invoke(o.INFO,arguments)},warn:function(){this.invoke(o.WARN,arguments)},error:function(){this.invoke(o.ERROR,arguments)},time:function(e){"string"==typeof e&&0<e.length&&this.invoke(o.TIME,[e,"start"])},timeEnd:function(e){"string"==typeof e&&0<e.length&&this.invoke(o.TIME,[e,"end"])},invoke:function(e,t){s&&this.enabledFor(e)&&s(t,i({level:e},this.context))}};var n=new a({filterLevel:o.OFF});(t=o).enabledFor=e(n,n.enabledFor),t.debug=e(n,n.debug),t.time=e(n,n.time),t.timeEnd=e(n,n.timeEnd),t.info=e(n,n.info),t.warn=e(n,n.warn),t.error=e(n,n.error),t.log=t.info,o.setHandler=function(e){s=e},o.setLevel=function(e){for(var t in n.setLevel(e),r)r.hasOwnProperty(t)&&r[t].setLevel(e)},o.getLevel=function(){return n.getLevel()},o.get=function(e){return r[e]||(r[e]=new a(i({name:e},n.context)))},o.createDefaultHandler=function(r){(r=r||{}).formatter=r.formatter||function(e,t){t.name&&e.unshift("["+t.name+"]")};function a(e,t){Function.prototype.apply.call(e,console,t)}var n={};return"undefined"==typeof console?function(){}:function(e,t){e=Array.prototype.slice.call(e);var i,s=console.log;t.level===o.TIME?(i=(t.name?"["+t.name+"] ":"")+e[0],"start"===e[1]?console.time?console.time(i):n[i]=(new Date).getTime():console.timeEnd?console.timeEnd(i):a(s,[i+": "+((new Date).getTime()-n[i])+"ms"])):(t.level===o.WARN&&console.warn?s=console.warn:t.level===o.ERROR&&console.error?s=console.error:t.level===o.INFO&&console.info?s=console.info:t.level===o.DEBUG&&console.debug&&(s=console.debug),r.formatter(e,t),a(s,e))}},o.useDefaults=function(e){o.setLevel(e&&e.defaultLevel||o.DEBUG),o.setHandler(o.createDefaultHandler(e))},void 0===(u="function"==typeof(u=o)?u.call(l,c,l,h):u)||(h.exports=u)}()},948:e=>{function t(e){null==e&&(e=(new Date).getTime()),this.N=624,this.M=397,this.MATRIX_A=2567483615,this.UPPER_MASK=2147483648,this.LOWER_MASK=2147483647,this.mt=new Array(this.N),this.mti=this.N+1,e.constructor==Array?this.init_by_array(e,e.length):this.init_seed(e)}t.prototype.init_seed=function(e){for(this.mt[0]=e>>>0,this.mti=1;this.mti<this.N;this.mti++){e=this.mt[this.mti-1]^this.mt[this.mti-1]>>>30;this.mt[this.mti]=(1812433253*((4294901760&e)>>>16)<<16)+1812433253*(65535&e)+this.mti,this.mt[this.mti]>>>=0}},t.prototype.init_by_array=function(e,t){var i,s,r;for(this.init_seed(19650218),i=1,s=0,r=this.N>t?this.N:t;r;r--){var a=this.mt[i-1]^this.mt[i-1]>>>30;this.mt[i]=(this.mt[i]^(1664525*((4294901760&a)>>>16)<<16)+1664525*(65535&a))+e[s]+s,this.mt[i]>>>=0,s++,++i>=this.N&&(this.mt[0]=this.mt[this.N-1],i=1),t<=s&&(s=0)}for(r=this.N-1;r;r--){a=this.mt[i-1]^this.mt[i-1]>>>30;this.mt[i]=(this.mt[i]^(1566083941*((4294901760&a)>>>16)<<16)+1566083941*(65535&a))-i,this.mt[i]>>>=0,++i>=this.N&&(this.mt[0]=this.mt[this.N-1],i=1)}this.mt[0]=2147483648},t.prototype.random_int=function(){var e,t,i=new Array(0,this.MATRIX_A);if(this.mti>=this.N){for(this.mti==this.N+1&&this.init_seed(5489),t=0;t<this.N-this.M;t++)e=this.mt[t]&this.UPPER_MASK|this.mt[t+1]&this.LOWER_MASK,this.mt[t]=this.mt[t+this.M]^e>>>1^i[1&e];for(;t<this.N-1;t++)e=this.mt[t]&this.UPPER_MASK|this.mt[t+1]&this.LOWER_MASK,this.mt[t]=this.mt[t+(this.M-this.N)]^e>>>1^i[1&e];e=this.mt[this.N-1]&this.UPPER_MASK|this.mt[0]&this.LOWER_MASK,this.mt[this.N-1]=this.mt[this.M-1]^e>>>1^i[1&e],this.mti=0}return e=this.mt[this.mti++],e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,(e^=e>>>18)>>>0},t.prototype.random_int31=function(){return this.random_int()>>>1},t.prototype.random_incl=function(){return this.random_int()*(1/4294967295)},t.prototype.random=function(){return this.random_int()*(1/4294967296)},t.prototype.random_excl=function(){return(this.random_int()+.5)*(1/4294967296)},t.prototype.random_long=function(){return 1/9007199254740992*(67108864*(this.random_int()>>>5)+(this.random_int()>>>6))},e.exports=t},367:e=>{e.exports=function(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");for(var t=["on","fire","off"],i=0;i<t.length;++i)if(e.hasOwnProperty(t[i]))throw new Error("Subject cannot be eventified, since it already has property '"+t[i]+"'")}(e);var a,n,t=(a=e,n=Object.create(null),{on:function(e,t,i){if("function"!=typeof t)throw new Error("callback is expected to be a function");return(n[e]||(n[e]=[])).push({callback:t,ctx:i}),a},off:function(e,t){if(void 0===e)return n=Object.create(null),a;if(n[e])if("function"!=typeof t)delete n[e];else for(var i=n[e],s=0;s<i.length;++s)i[s].callback===t&&i.splice(s,1);return a},fire:function(e){var t,i=n[e];if(!i)return a;1<arguments.length&&(t=Array.prototype.splice.call(arguments,1));for(var s=0;s<i.length;++s){var r=i[s];r.callback.apply(r.ctx,t)}return a}});return e.on=t.on,e.off=t.off,e.fire=t.fire,e}},495:(e,t,i)=>{e.exports=function(e){"uniqueLinkId"in(e=e||{})&&(console.warn("ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\nUse `multigraph` option instead\n","\n","Note: there is also change in default behavior: From now on each graph\nis considered to be not a multigraph by default (each edge is unique)."),e.multigraph=e.uniqueLinkId);void 0===e.multigraph&&(e.multigraph=!1);if("function"!=typeof Map)throw new Error("ngraph.graph requires `Map` to be defined. Please polyfill it before using ngraph");var n=new Map,a=[],o={},t=0,h=e.multigraph?function(e,t,i){var s=x(e,t),r=o.hasOwnProperty(s);(r||b(e,t))&&(r||(o[s]=0),r="@"+ ++o[s],s=x(e+r,t+r));return new B(e,t,i,s)}:function(e,t,i){var s=x(e,t);return new B(e,t,i,s)},i=[],l=v,r=v,c=v,u=v,s={addNode:g,addLink:function(e,t,i){c();var s=m(e)||g(e),r=m(t)||g(t),i=h(e,t,i);a.push(i),A(s,i),e!==t&&A(r,i);return l(i,"add"),u(),i},removeLink:T,removeNode:f,getNode:m,getNodeCount:y,getLinkCount:w,getLinksCount:w,getNodesCount:y,getLinks:function(e){e=m(e);return e?e.links:null},forEachNode:O,forEachLinkedNode:function(e,t,i){var s=m(e);if(s&&s.links&&"function"==typeof t)return(i?function(e,t,i){for(var s=0;s<e.length;++s){var r=e[s];if(r.fromId===t&&i(n.get(r.toId),r))return!0}}:function(e,t,i){for(var s=0;s<e.length;++s){var r=e[s],a=r.fromId===t?r.toId:r.fromId;if(i(n.get(a),r))return!0}})(s.links,e,t)},forEachLink:function(e){var t,i;if("function"==typeof e)for(t=0,i=a.length;t<i;++t)e(a[t])},beginUpdate:c,endUpdate:u,clear:function(){c(),O(function(e){f(e.id)}),u()},hasLink:b,hasNode:m,getLink:b};return _(s),function(){var e=s.on;s.on=function(){return s.beginUpdate=c=S,s.endUpdate=u=k,l=d,r=p,(s.on=e).apply(s,arguments)}}(),s;function d(e,t){i.push({link:e,changeType:t})}function p(e,t){i.push({node:e,changeType:t})}function g(e,t){if(void 0===e)throw new Error("Invalid node identifier");c();var i=m(e);return i?(i.data=t,r(i,"update")):(i=new C(e,t),r(i,"add")),n.set(e,i),u(),i}function m(e){return n.get(e)}function f(e){var t=m(e);if(!t)return!1;c();var i=t.links;if(i){t.links=null;for(var s=0;s<i.length;++s)T(i[s])}return n.delete(e),r(t,"remove"),u(),!0}function y(){return n.size}function w(){return a.length}function T(e){if(!e)return!1;var t=I(e,a);if(t<0)return!1;c(),a.splice(t,1);var i=m(e.fromId),s=m(e.toId);return i&&0<=(t=I(e,i.links))&&i.links.splice(t,1),s&&0<=(t=I(e,s.links))&&s.links.splice(t,1),l(e,"remove"),u(),!0}function b(e,t){var i,s=m(e);if(!s||!s.links)return null;for(i=0;i<s.links.length;++i){var r=s.links[i];if(r.fromId===e&&r.toId===t)return r}return null}function v(){}function S(){t+=1}function k(){0===--t&&0<i.length&&(s.fire("changed",i),i.length=0)}function O(e){if("function"!=typeof e)throw new Error("Function is expected to iterate over graph nodes. You passed "+e);for(var t=n.values(),i=t.next();!i.done;){if(e(i.value))return!0;i=t.next()}}};var _=i(367);function I(e,t){if(!t)return-1;if(t.indexOf)return t.indexOf(e);for(var i=t.length,s=0;s<i;s+=1)if(t[s]===e)return s;return-1}function C(e,t){this.id=e,this.links=null,this.data=t}function A(e,t){e.links?e.links.push(t):e.links=[t]}function B(e,t,i,s){this.fromId=e,this.toId=t,this.data=i,this.id=s}function x(e,t){return e.toString()+"👉 "+t.toString()}},603:e=>{function s(e,t){if(!(this instanceof s))return new s(e,t);if(Array.isArray(e)||(t=e,e=[]),t=t||{},this.data=e||[],this.length=this.data.length,this.compare=t.compare||a,this.setNodeId=t.setNodeId||r,0<this.length)for(var i=this.length>>1;0<=i;i--)this._down(i);if(t.setNodeId)for(i=0;i<this.length;++i)this.setNodeId(this.data[i],i)}function r(){}function a(e,t){return e-t}(e.exports=s).prototype={push:function(e){this.data.push(e),this.setNodeId(e,this.length),this.length++,this._up(this.length-1)},pop:function(){if(0!==this.length){var e=this.data[0];return this.length--,0<this.length&&(this.data[0]=this.data[this.length],this.setNodeId(this.data[0],0),this._down(0)),this.data.pop(),e}},peek:function(){return this.data[0]},updateItem:function(e){this._down(e),this._up(e)},_up:function(e){for(var t=this.data,i=this.compare,s=this.setNodeId,r=t[e];0<e;){var a=e-1>>1,n=t[a];if(0<=i(r,n))break;s(t[e]=n,e),e=a}s(t[e]=r,e)},_down:function(e){for(var t=this.data,i=this.compare,s=this.length>>1,r=t[e],a=this.setNodeId;e<s;){var n=1+(e<<1),o=n+1,h=t[n];if(o<this.length&&i(t[o],h)<0&&(h=t[n=o]),0<=i(h,r))break;a(t[e]=h,e),e=n}a(t[e]=r,e)}}},142:(e,t,i)=>{e.exports=function(y,e){var w=(e=e||{}).oriented,T=e.bestEffort,b=e.heuristic;b=b||O.heuristic;var v=e.distance;v=v||O.distance;var S=s();return{find:function(e,t){var a=y.getNode(e);if(!a)throw new Error("fromId is not defined in this graph: "+e);var n=y.getNode(t);if(!n)throw new Error("toId is not defined in this graph: "+t);if(a===n)return[a];S.reset();var i=w?function(e,t){if(d===_){if(t.fromId===g.node.id)return f(e,t,g)}else if(d===I&&t.toId===g.node.id)return f(e,t,g)}:function(e,t){return f(e,t,g)},o=new Map,s=new k({compare:O.compareFScore,setNodeId:O.setHeapIndex}),r=new k({compare:O.compareFScore,setNodeId:O.setHeapIndex}),t=S.createNewState(a);o.set(e,t),t.fScore=b(a,n),t.distanceToSource=0,s.push(t),t.open=_;e=S.createNewState(n);e.fScore=b(n,a),e.distanceToSource=0,r.push(e),e.open=I;var h,l,c=Number.POSITIVE_INFINITY,u=s,d=_,p=t;for(;0<s.length&&(0<r.length||T);){var g=(u=s.length<r.length||!r.length&&T?(d=_,s):(d=I,r)).pop();if(g.closed=!0,!(g.distanceToSource>c)&&(y.forEachLinkedNode(g.node.id,i),h&&l))return m(h,l)}return T?m(p):C;function m(e,t){for(var i=[],s=e;s;)i.push(s.node),s=s.parent;for(var r=t;r;)i.unshift(r.node),r=r.parent;return i}function f(e,t,i){var s,r=o.get(e.id);r||(r=S.createNewState(e),o.set(e.id,r)),r.closed||((e=(e=r).open)&&e!==d?(s=r.distanceToSource+i.distanceToSource)<c&&(h=r,l=i,c=s):(e=i.distanceToSource+v(r.node,i.node,t))>=r.distanceToSource||(s=d===_?n:a,t=e+b(r.node,s,r),c<=t||(r.fScore=t,0===r.open&&(u.push(r),u.updateItem(r.heapIndex),r.open=d),r.parent=i,r.distanceToSource=e,s===n&&t-e<p.fScore-p.distanceToSource&&(p=r))))}}}};var k=i(603),s=i(573),r=i(884),O=i(8),_=1,I=2,C=O.NO_PATH;e.exports.l2=r.l2,e.exports.l1=r.l1},118:(e,t,i)=>{e.exports=function(c,e){var u=(e=e||{}).oriented,d=e.bestEffort,p=e.maxExpandedNodes||Number.POSITIVE_INFINITY,g=e.heuristic;g=g||w.heuristic;var m=e.distance;m=m||w.distance;var f=s();return{find:function(e,t){var i=c.getNode(e);if(!i)throw new Error("fromId is not defined in this graph: "+e);var s=c.getNode(t);if(!s)throw new Error("toId is not defined in this graph: "+t);f.reset();var r,a=new Map,n=new y({compare:w.compareFScore,setNodeId:w.setHeapIndex}),t=f.createNewState(i);a.set(e,t),t.fScore=g(i,s),t.distanceToSource=0,n.push(t),t.open=1;var o=t,h=0;for(;0<n.length;){if(function(e,t){return e.node===t}(r=n.pop(),s))return b(r);if(p<++h)break;r.closed=!0,c.forEachLinkedNode(r.node.id,l,u)}return d?b(o):T;function l(e,t){var i=a.get(e.id);i||(i=f.createNewState(e),a.set(e.id,i)),i.closed||(0===i.open&&(n.push(i),i.open=1),(t=r.distanceToSource+m(r.node,e,t))>=i.distanceToSource||(i.parent=r,i.distanceToSource=t,i.fScore=t+g(i.node,s,i),i.fScore-i.distanceToSource<o.fScore-o.distanceToSource&&(o=i),n.updateItem(i.heapIndex)))}}}};var y=i(603),s=i(573),r=i(884),w=i(8),T=w.NO_PATH;function b(e){for(var t=[e.node],i=e.parent;i;)t.push(i.node),i=i.parent;return t}e.exports.l2=r.l2,e.exports.l1=r.l1},8:e=>{var t=[];"function"==typeof Object.freeze&&Object.freeze(t),e.exports={heuristic:function(){return 0},distance:function(){return 1},compareFScore:function(e,t){return e.fScore-t.fScore},NO_PATH:t,setHeapIndex:function(e,t){e.heapIndex=t},setH1:function(e,t){e.h1=t},setH2:function(e,t){e.h2=t},compareF1Score:function(e,t){return e.f1-t.f1},compareF2Score:function(e,t){return e.f2-t.f2}}},884:e=>{e.exports={l2:function(e,t){var i=e.x-t.x,t=e.y-t.y;return Math.sqrt(i*i+t*t)},l1:function(e,t){var i=e.x-t.x,t=e.y-t.y;return Math.abs(i)+Math.abs(t)}}},573:e=>{function r(e){this.node=e,this.parent=null,this.closed=!1,this.open=0,this.distanceToSource=Number.POSITIVE_INFINITY,this.fScore=Number.POSITIVE_INFINITY,this.heapIndex=-1}e.exports=function(){var i=0,s=[];return{createNewState:function(e){var t=s[i];t?(t.node=e,t.parent=null,t.closed=!1,t.open=0,t.distanceToSource=Number.POSITIVE_INFINITY,t.fScore=Number.POSITIVE_INFINITY,t.heapIndex=-1):(t=new r(e),s[i]=t);return i++,t},reset:function(){i=0}}}},377:(e,t,i)=>{e.exports=function(y,e){var w=(e=e||{}).oriented,T=e.quitFast,b=e.heuristic;b=b||O.heuristic;var v=e.distance;v=v||O.distance;var S=r();return{find:function(e,t){var s=y.getNode(e);if(!s)throw new Error("fromId is not defined in this graph: "+e);var r=y.getNode(t);if(!r)throw new Error("toId is not defined in this graph: "+t);S.reset();var a,i=w?function(e,t){if(t.fromId===p.node.id)return m(e,t)}:m,n=w?function(e,t){if(t.toId===p.node.id)return f(e,t)}:f,o=new Map,h=new k({compare:O.compareF1Score,setNodeId:O.setH1}),l=new k({compare:O.compareF2Score,setNodeId:O.setH2}),c=Number.POSITIVE_INFINITY,u=S.createNewState(s);o.set(e,u),u.g1=0;var d=b(s,r);u.f1=d,h.push(u);u=S.createNewState(r);o.set(t,u),u.g2=0;var p,g=d;u.f2=g,l.push(u);for(;l.length&&h.length&&(h.length<l.length?(p=h.pop()).closed||(p.closed=!0,p.f1<c&&p.g1+g-b(s,p.node)<c&&y.forEachLinkedNode(p.node.id,i),0<h.length&&(d=h.peek().f1)):(p=l.pop()).closed||(p.closed=!0,p.f2<c&&p.g2+d-b(p.node,r)<c&&y.forEachLinkedNode(p.node.id,n),0<l.length&&(g=l.peek().f2)),!T||!a););return function(e){if(!e)return _;var t=[e.node],i=e.p1;for(;i;)t.push(i.node),i=i.p1;var s=e.p2;for(;s;)t.unshift(s.node),s=s.p2;return t}(a);function m(e,t){var i=o.get(e.id);i||(i=S.createNewState(e),o.set(e.id,i)),i.closed||((t=p.g1+v(p.node,e,t))<i.g1&&(i.g1=t,i.f1=t+b(i.node,r),i.p1=p,i.h1<0?h.push(i):h.updateItem(i.h1)),(t=i.g1+i.g2)<c&&(c=t,a=i))}function f(e,t){var i=o.get(e.id);i||(i=S.createNewState(e),o.set(e.id,i)),i.closed||((t=p.g2+v(p.node,e,t))<i.g2&&(i.g2=t,i.f2=t+b(s,i.node),i.p2=p,i.h2<0?l.push(i):l.updateItem(i.h2)),(t=i.g1+i.g2)<c&&(c=t,a=i))}}}};var k=i(603),s=i(884),O=i(8),r=i(808),_=O.NO_PATH;e.exports.l2=s.l2,e.exports.l1=s.l1},808:e=>{function r(e){this.node=e,this.p1=null,this.p2=null,this.closed=!1,this.g1=Number.POSITIVE_INFINITY,this.g2=Number.POSITIVE_INFINITY,this.f1=Number.POSITIVE_INFINITY,this.f2=Number.POSITIVE_INFINITY,this.h1=-1,this.h2=-1}e.exports=function(){var i=0,s=[];return{createNewState:function(e){var t=s[i];t?(t.node=e,t.p1=null,t.p2=null,t.closed=!1,t.g1=Number.POSITIVE_INFINITY,t.g2=Number.POSITIVE_INFINITY,t.f1=Number.POSITIVE_INFINITY,t.f2=Number.POSITIVE_INFINITY,t.h1=-1,t.h2=-1):(t=new r(e),s[i]=t);return i++,t},reset:function(){i=0}}}},45:(e,t,i)=>{e.exports={aStar:i(118),aGreedy:i(142),nba:i(377)}},91:e=>{e.exports=__WEBPACK_EXTERNAL_MODULE_fetch_blob_71f8024a__},949:e=>{e.exports=__WEBPACK_EXTERNAL_MODULE_three__}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;t=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(t.exports,t,t.exports,__webpack_require__),t.exports}__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},__webpack_require__.d=(e,t)=>{for(var i in t)__webpack_require__.o(t,i)&&!__webpack_require__.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{ApiEventType:()=>$p,ArmorType:()=>ri,AttackState:()=>yn,Bot:()=>jp,Box2:()=>Fn,BuildCat:()=>Ki,BuildStatus:()=>In,Cylindrical:()=>Wm,Euler:()=>Fm,FactoryStatus:()=>Sn,FactoryType:()=>Ji,GameInstanceApi:()=>Tm,GameMath:()=>Qi,InfDeathType:()=>ei,LandTargeting:()=>ai,LandType:()=>Kt,LocomotorType:()=>ii,Matrix4:()=>Xs,MovementZone:()=>si,NavalTargeting:()=>ni,ObjectType:()=>Bt,OrderType:()=>An,PipColor:()=>ti,PrereqCategory:()=>Qt,PublicApi:()=>_m,Quaternion:()=>Yi,QueueStatus:()=>fn,QueueType:()=>mn,RadarEventType:()=>Zt,SideType:()=>Xt,SpeedType:()=>Jt,Spherical:()=>Um,StanceType:()=>Rs,SuperWeaponStatus:()=>Ps,SuperWeaponType:()=>ts,TagRepeatType:()=>Gt,TerrainType:()=>Yt,TheaterType:()=>I,Vector2:()=>Ss,Vector3:()=>ss,VeteranAbility:()=>hi,VeteranLevel:()=>Jr,VhpScan:()=>li,WeaponType:()=>oi,ZoneType:()=>bs,cdapi:()=>zm});__WEBPACK_EXTERNAL_MODULE_websocket_polyfill_8396782d__;const a=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");const e=__WEBPACK_EXTERNAL_MODULE_es_dirname_044d89a0__;const n=__WEBPACK_EXTERNAL_MODULE_file_system_access_58c08c7f__;const o=__WEBPACK_EXTERNAL_MODULE_file_system_access_lib_adapters_node_js_b1c03fd5__;class h{constructor(e){this.entries=new Map,this.name=e}clone(){let i=new h(this.name);return this.entries.forEach((e,t)=>{i.set(t,e)}),i}set(e,t){this.entries.set(e,t)}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}getString(e,t=""){e=this.get(e);return e||t}getNumber(e,t=0){var i=this.get(e);if(!i)return t;var s=this.parseNumber(i);return void 0===s?(console.warn(`Invalid value for key ${e}. "${i}" is not a valid number or percentage string.`),t):s}parseNumber(e){let t;if(t=e.match(/%$/)?Number(e.replace("%",""))/100:Number(e),!isNaN(t))return t}getFixed(e,t=0){return this.toFixedPointPrecision(this.getNumber(e,t))}toFixedPointPrecision(e){return(65536*e|0)/65536}getBool(e,t=!1){let i=this.getString(e).trim();return i=i&&i.toLowerCase(),!(!i||-1===["yes","1","true","on"].indexOf(i))||(!i||-1===["no","0","false","off"].indexOf(i))&&t}getArray(e,t=/\,\s*/,i=[]){let s=this.getString(e).trim();return s=s.replace(/\,$/,"").replace(/\,+/g,","),s?s.split(t):i}getNumberArray(e,t=/\,\s*/,i=[]){let s=this.getString(e).trim();if(!s)return i;let r=[];for(var a of s.split(t)){if(!a)return i;var n=this.parseNumber(a);if(void 0===n)return console.warn(`Invalid value for key ${e}. "${a}" is not a valid number or percentage string.`),i;r.push(n)}return r}getFixedArray(e,t=/\,\s*/,i=[]){return this.getNumberArray(e,t,i).map(e=>this.toFixedPointPrecision(e))}getEnum(e,t,i,s=!1){let r=this.getString(e).trim();if(!r)return i;let a;if(s){let e=Object.getOwnPropertyNames(t);s=e.find(e=>e.toLowerCase()===r.toLowerCase());s&&(a=t[s])}else t.hasOwnProperty(r)&&(a=t[r]);return void 0===a?(console.warn(`Invalid value for key "${e}". "${r}" is not an accepted enum value.`),i):a}getEnumNumeric(e,t,i){var s=this.getString(e).trim();if(!s)return i;let r;return Number.isInteger(parseInt(s,10))&&t.hasOwnProperty(s)&&(r=parseInt(s,10)),void 0===r?(console.warn(`Invalid value for key "${e}". "${s}" is not an accepted enum value.`),i):r}getEnumArray(e,s,t=/\,\s*/,r=[],a=!1){let n=this.getString(e).trim();if(!n)return r;let o=[];for(let i of n.split(t)){if(!i)return r;let t=!1;if(a){let e=Object.getOwnPropertyNames(s);var h=e.find(e=>e.toLowerCase()===i.toLowerCase());h&&(o.push(s[h]),t=!0)}else s.hasOwnProperty(i)&&(o.push(s[i]),t=!0);if(!t)return console.warn(`Invalid value "${i}" for key "${e}".`),r}return o}getHighestNumericIndex(){let i=0,s;return this.entries.forEach((e,t)=>{s=parseInt(t,10),s>i&&(i=s)}),i}getConcatenatedValues(){let e="";for(var t of this.entries.values())e+=t;return e}toString(){let e=[];e.push(`[${this.name}]`);for(var[t,i]of this.entries)e.push(`${t}=${i}`);return e.push(""),e.join("\r\n")}}class t{parse(e){let o={},s=o,r,a=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,t=e.split(/[\r\n]+/g);return t.forEach((t,e,i)=>{if(t&&!t.match(/^\s*[;#]/)){t=(t=t.replace(/]\s*(\/\/|;|#).*$/,"]")).match(a);if(t){if(void 0!==t[1])return r=this.unsafe(t[1]),void(s=o[r]=o[r]||{});let e=this.unsafe(t[2]);t=t[3]?this.unsafe(t[4]||""):"";2<e.length&&"[]"===e.slice(-2)&&(e=e.substring(0,e.length-2),s[e]?Array.isArray(s[e])||(s[e]=[s[e]]):s[e]=[]),Array.isArray(s[e])?s[e].push(t):s[e]=t}}}),Object.keys(o).filter((e,t,i)=>{if(!o[e]||"object"!=typeof o[e]||Array.isArray(o[e]))return!1;let s=this.dotSplit(e),r=o,a=s.pop();var n=a.replace(/\\\./g,".");return s.forEach(function(e,t,i){r[e]&&"object"==typeof r[e]||(r[e]={}),r=r[e]}),(r!==o||n!==a)&&(r[n]=o[e],!0)}).forEach(function(e,t,i){delete o[e]}),o}dotSplit(e){return e.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,""))}isQuoted(e){return'"'===e.charAt(0)&&'"'===e.slice(-1)||"'"===e.charAt(0)&&"'"===e.slice(-1)}unsafe(r){if(r=(r||"").trim(),this.isQuoted(r))return r=r.substr(1,r.length-2);{let i=!1,s="";for(let e=0,t=r.length;e<t;e++){var a=r.charAt(e);if(i)-1!=="\\;#".indexOf(a)?s+=a:s+="\\"+a,i=!1;else{if(-1!==";#".indexOf(a))break;"\\"===a?i=!0:s+=a}}return i&&(s+="\\"),s=s.trim(),s}}}class b{constructor(e,t,i=b.LITTLE_ENDIAN){this.endianness=i,this.position=0,this._dynamicSize=!0,this._byteLength=0,this._byteOffset=t||0,e instanceof ArrayBuffer?this.buffer=e:"object"==typeof e?(this.dataView=e,t&&(this._byteOffset+=t)):this.buffer=new ArrayBuffer(e||0)}get dynamicSize(){return this._dynamicSize}set dynamicSize(e){e||this._trimAlloc(),this._dynamicSize=e}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){return this._trimAlloc(),this._buffer}set buffer(e){this._buffer=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get byteOffset(){return this._byteOffset}set byteOffset(e){this._byteOffset=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get dataView(){return this._dataView}set dataView(e){this._byteOffset=e.byteOffset,this._buffer=e.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+e.byteLength}bigEndian(){return this.endianness=b.BIG_ENDIAN,this}_realloc(t){if(this._dynamicSize){var i=this._byteOffset+this.position+t;let e=this._buffer.byteLength;if(i<=e)i>this._byteLength&&(this._byteLength=i);else{for(e<1&&(e=1);i>e;)e*=2;var s=new ArrayBuffer(e),t=new Uint8Array(this._buffer);const r=new Uint8Array(s,0,t.length);r.set(t),this.buffer=s,this._byteLength=i}}}_trimAlloc(){if(this._byteLength!==this._buffer.byteLength){var e=new ArrayBuffer(this._byteLength);const i=new Uint8Array(e);var t=new Uint8Array(this._buffer,0,i.length);i.set(t),this.buffer=e}}seek(e){e=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(e)||!isFinite(e)?0:e}isEof(){return this.position>=this.byteLength}mapInt32Array(e,t){this._realloc(4*e);var i=new Int32Array(this._buffer,this.byteOffset+this.position,e);return b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=4*e,i}mapInt16Array(e,t){this._realloc(2*e);var i=new Int16Array(this._buffer,this.byteOffset+this.position,e);return b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=2*e,i}mapInt8Array(e){this._realloc(e);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e,t}mapUint32Array(e,t){this._realloc(4*e);var i=new Uint32Array(this._buffer,this.byteOffset+this.position,e);return b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=4*e,i}mapUint16Array(e,t){this._realloc(2*e);var i=new Uint16Array(this._buffer,this.byteOffset+this.position,e);return b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=2*e,i}mapUint8Array(e){this._realloc(e);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e,t}mapFloat64Array(e,t){this._realloc(8*e);var i=new Float64Array(this._buffer,this.byteOffset+this.position,e);return b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=8*e,i}mapFloat32Array(e,t){this._realloc(4*e);var i=new Float32Array(this._buffer,this.byteOffset+this.position,e);return b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=4*e,i}readInt32Array(e,t){e=void 0===e?this.byteLength-this.position/4:e;var i=new Int32Array(e);return b.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}readInt16Array(e,t){e=void 0===e?this.byteLength-this.position/2:e;var i=new Int16Array(e);return b.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}readInt8Array(e){e=void 0===e?this.byteLength-this.position:e;var t=new Int8Array(e);return b.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t}readUint32Array(e,t){e=void 0===e?this.byteLength-this.position/4:e;var i=new Uint32Array(e);return b.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}readUint16Array(e,t){e=void 0===e?this.byteLength-this.position/2:e;var i=new Uint16Array(e);return b.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}readUint8Array(e){e=void 0===e?this.byteLength-this.position:e;var t=new Uint8Array(e);return b.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t}readFloat64Array(e,t){e=void 0===e?this.byteLength-this.position/8:e;var i=new Float64Array(e);return b.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}readFloat32Array(e,t){e=void 0===e?this.byteLength-this.position/4:e;var i=new Float32Array(e);return b.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),b.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}writeInt32Array(t,i){if(this._realloc(4*t.length),t instanceof Int32Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)b.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapInt32Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeInt32(t[e],i);return this}writeInt16Array(t,i){if(this._realloc(2*t.length),t instanceof Int16Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)b.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapInt16Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeInt16(t[e],i);return this}writeInt8Array(t){if(this._realloc(t.length),t instanceof Int8Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)b.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapInt8Array(t.length);else for(let e=0;e<t.length;e++)this.writeInt8(t[e]);return this}writeUint32Array(t,i){if(this._realloc(4*t.length),t instanceof Uint32Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)b.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapUint32Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeUint32(t[e],i);return this}writeUint16Array(t,i){if(this._realloc(2*t.length),t instanceof Uint16Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)b.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapUint16Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeUint16(t[e],i);return this}writeUint8Array(t){if(this._realloc(t.length),t instanceof Uint8Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)b.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapUint8Array(t.length);else for(let e=0;e<t.length;e++)this.writeUint8(t[e]);return this}writeFloat64Array(t,i){if(this._realloc(8*t.length),t instanceof Float64Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)b.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapFloat64Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeFloat64(t[e],i);return this}writeFloat32Array(t,i){if(this._realloc(4*t.length),t instanceof Float32Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)b.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapFloat32Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeFloat32(t[e],i);return this}readInt32(e){e=this._dataView.getInt32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readInt16(e){e=this._dataView.getInt16(this.position,void 0===e?this.endianness:e);return this.position+=2,e}readInt8(){var e=this._dataView.getInt8(this.position);return this.position+=1,e}readUint32(e){e=this._dataView.getUint32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readUint16(e){e=this._dataView.getUint16(this.position,void 0===e?this.endianness:e);return this.position+=2,e}readUint8(){var e=this._dataView.getUint8(this.position);return this.position+=1,e}readFloat32(e){e=this._dataView.getFloat32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readFloat64(e){e=this._dataView.getFloat64(this.position,void 0===e?this.endianness:e);return this.position+=8,e}writeInt32(e,t){return this._realloc(4),this._dataView.setInt32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeInt16(e,t){return this._realloc(2),this._dataView.setInt16(this.position,e,void 0===t?this.endianness:t),this.position+=2,this}writeInt8(e){return this._realloc(1),this._dataView.setInt8(this.position,e),this.position+=1,this}writeUint32(e,t){return this._realloc(4),this._dataView.setUint32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeUint16(e,t){return this._realloc(2),this._dataView.setUint16(this.position,e,void 0===t?this.endianness:t),this.position+=2,this}writeUint8(e){return this._realloc(1),this._dataView.setUint8(this.position,e),this.position+=1,this}writeFloat32(e,t){return this._realloc(4),this._dataView.setFloat32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeFloat64(e,t){return this._realloc(8),this._dataView.setFloat64(this.position,e,void 0===t?this.endianness:t),this.position+=8,this}static memcpy(e,t,i,s,r){const a=new Uint8Array(e,t,r);r=new Uint8Array(i,s,r);a.set(r)}static arrayToNative(e,t){return t===this.endianness?e:this.flipArrayEndianness(e)}static nativeToEndian(e,t){return this.endianness===t?e:this.flipArrayEndianness(e)}static flipArrayEndianness(s){const r=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);for(let i=0;i<s.byteLength;i+=s.BYTES_PER_ELEMENT)for(let e=i+s.BYTES_PER_ELEMENT-1,t=i;e>t;e--,t++){var a=r[t];r[t]=r[e],r[e]=a}return s}static createStringFromArray(t){const i=[];for(let e=0;e<t.length;e+=32768)i.push(String.fromCharCode.apply(void 0,t.subarray(e,e+32768)));return i.join("")}readUCS2String(e,t){return b.createStringFromArray(this.readUint16Array(e,t))}writeUCS2String(e,t,i){void 0===i&&(i=e.length);let s=0;for(;s<e.length&&s<i;s++)this.writeUint16(e.charCodeAt(s),t);for(;s<i;s++)this.writeUint16(0);return this}readString(e,t){return void 0===t||"ASCII"===t?b.createStringFromArray(this.mapUint8Array(void 0===e?this.byteLength-this.position:e)):new TextDecoder(t).decode(this.mapUint8Array(e))}writeString(t,e,i){if(void 0===e||"ASCII"===e)if(void 0!==i){let e;var s=Math.min(t.length,i);for(e=0;e<s;e++)this.writeUint8(t.charCodeAt(e));for(;e<i;e++)this.writeUint8(0)}else for(let e=0;e<t.length;e++)this.writeUint8(t.charCodeAt(e));else this.writeUint8Array((new TextEncoder).encode(t.substring(0,i)));return this}writeUtf8WithLen(e){e=(new TextEncoder).encode(e);return this.writeUint16(e.length).writeUint8Array(e)}readUtf8WithLen(){var e=this.readUint16();return(new TextDecoder).decode(this.mapUint8Array(e))}readCString(e){var t=this.byteLength-this.position,i=new Uint8Array(this._buffer,this._byteOffset+this.position);let s=t;void 0!==e&&(s=Math.min(e,t));let r=0;for(;r<s&&0!==i[r];r++);var a=b.createStringFromArray(this.mapUint8Array(r));return void 0!==e?this.position+=s-r:r!==t&&(this.position+=1),a}writeCString(t,i){if(void 0!==i){let e;var s=Math.min(t.length,i);for(e=0;e<s;e++)this.writeUint8(t.charCodeAt(e));for(;e<i;e++)this.writeUint8(0)}else{for(let e=0;e<t.length;e++)this.writeUint8(t.charCodeAt(e));this.writeUint8(0)}return this}toUint8Array(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}}b.BIG_ENDIAN=!1,b.LITTLE_ENDIAN=!0,b.endianness=0<new Int8Array(new Int16Array([1]).buffer)[0];class l extends Error{constructor(){super(...arguments),this.name="IOError"}}class i{constructor(e,t){this.stream=e,this.filename=t}static async fromRealFile(t){try{const e=new b(await t.arrayBuffer());return e._trimAlloc=()=>{},new this(e,t.name)}catch(e){if(e instanceof DOMException)throw new l(`File "${t.name}" could not be read (${e.name})`,{cause:e});throw e}}static fromBytes(e,t){let i=new b(e);return i._trimAlloc=()=>{},new this(i,t)}static factory(e,t,i=0,s=e.byteLength){s=new DataView(e.buffer,e.byteOffset+i,s);const r=new b(s);return r._trimAlloc=()=>{},new this(r,t)}readAsString(e){return this.stream.seek(0),this.stream.readString(this.stream.byteLength,e)}getBytes(){return new Uint8Array(this.stream.buffer,this.stream.byteOffset,this.stream.byteLength)}getSize(){return this.stream.byteLength}asFile(e){return new File([this.getBytes()],this.filename,{type:e})}}class c{constructor(e){this.sections=new Map,e instanceof i?this.fromVirtualFile(e):"object"==typeof e?this.fromJson(e):"string"==typeof e&&this.fromString(e)}fromVirtualFile(e){return this.fromString(e.readAsString())}fromString(e){return this.fromJson((new t).parse(e)),this}fromJson(e){let t,i,s,r;var a;for(t in e)if(e.hasOwnProperty(t)){for(r in i=e[t],s=new h(t),i)i.hasOwnProperty(r)&&(a=i[r],s.set(r,a));this.sections.set(t,s)}}toString(){let e=[];for(var t of this.sections.values())e.push(t.toString());return e.join("\r\n")}clone(){let i=new c;return this.sections.forEach((e,t)=>{i.sections.set(t,e.clone())}),i}getOrCreateSection(e){let t=this.sections.get(e);return t||(t=new h(e),this.sections.set(e,t)),t}getSection(e){return this.sections.get(e)}getOrderedSections(){return[...this.sections.values()]}isValueArray(e){return-1!==["BuildingTypes","AircraftTypes","InfantryTypes","OverlayTypes","TerrainTypes","SmudgeTypes","VehicleTypes","Animations","VoxelAnims","SuperWeaponTypes","Countries","Warheads","Tiberiums"].indexOf(e)}mergeWith(e){return e.sections.forEach((e,t)=>{let s=this.getOrCreateSection(t);if(this.isValueArray(t)){let i=s.getHighestNumericIndex()+1;e.entries.forEach((e,t)=>{s.set((i++).toString(),e)})}else e.entries.forEach((e,t)=>{s.set(t,e)})}),this}}class d{constructor(e){this.height=1,this.width=1,this.x=0,this.y=0,this.imageData=e??new Uint8Array(0)}clip(i,e){let t=new d;t.width=Math.min(this.width,i),t.height=Math.min(this.height,e);let s=new Uint8Array(i*e),r=0;for(let t=0;t<this.height&&!(t>=e);t++)for(let e=0;e<this.width;e++)e>=i||(s[r++]=this.imageData[t*this.width+e]);return t.imageData=s,t.x=this.x,t.y=this.y,t}}class s{constructor(e){this.height=0,this.width=0,this.numImages=0,this.images=[],e instanceof i&&this.fromVirtualFile(e)}fromVirtualFile(e){this.filename=e.filename;let r=e.stream;if(0===r.readInt16()){this.width=r.readInt16(),this.height=r.readInt16(),this.numImages=r.readInt16();let s=[];for(let e=0;e<this.numImages;++e)s.push(this.readFrameHeader(r));this.images=[];for(let i=0;i<this.numImages;++i){var{compressionType:a,imageDataStartOffset:n,x:o,y:h,width:l,height:c}=s[i];let e=i<this.numImages-1?s[i+1].imageDataStartOffset:r.byteLength;e<n&&(e=r.byteLength);var u=e-n;r.seek(n);u=this.readImageData(r,l,c,a,u);let t=new d(u);t.x=o,t.y=h,t.width=l,t.height=c,this.images.push(t)}}}readFrameHeader(e){var t=e.readInt16(),i=e.readInt16(),s=e.readInt16(),r=e.readInt16(),a=e.readUint8();return e.readUint8(),e.readUint8(),e.readUint8(),e.readInt32(),e.readInt32(),{x:t,y:i,width:s,height:r,compressionType:a,imageDataStartOffset:e.readInt32()}}readImageData(s,e,r,t,i){var a=e*r;if(t<=1){var n=new Uint8Array(s.buffer,s.byteOffset+s.position,a);return s.position+=a,n}if(2===t){let t=0,i=new Uint8Array(a);for(let e=0;e<r;++e){var o=s.readUint16()-2;i.set(new Uint8Array(s.buffer,s.byteOffset+s.position,o),t),s.position+=o,t+=o}return i}if(3!==t)return new Uint8Array;t=new Uint8Array(s.buffer,s.byteOffset+s.position,i);return s.position+=i,class{static decode(s,r,t){let a=new Uint8Array(r*t),n=0,o=0;for(let e=0;e<t;e++){let t=(s[n+1]<<8|s[n])-2;n+=2;let i=0;for(;0<t--;){let e=s[n++];if(0!==e)i++,a[o++]=e;else for(t--,e=s[n++],i+e>r&&(e=r-i&255),i+=e;0!=e--;)a[o++]=0}}return a}}.decode(t,e,r)}getImage(e){if(e<0||this.images.length<=e)throw new RangeError(`Image index out of bounds (file=${this.filename}, index=${e}, length=${this.images.length})`);return this.images[e]}addImage(e){this.images.push(e),this.numImages++}clip(e,t){let i=new s;return i.filename=this.filename,i.width=Math.min(this.width,e),i.height=Math.min(this.height,t),i.images=this.images.map(e=>e.clip(i.width,i.height)),i.numImages=this.numImages,i}}var r=__webpack_require__(949).Vector3;const u=[new r(.54946297,-183e-6,-.835518),new r(.00014400001,.54940403,-.83555698),new r(-.54940403,-68000001e-12,-.83555698),new r(106e-6,-.54946297,-.835518),new r(.94900799,.00031599999,-.31525001),new r(-186e-6,.94899702,-.31528401),new r(-.94899702,.00031800001,-.31528401),new r(-447e-6,-.94900799,-.31525001),new r(.95084399,-279e-6,.30967101),new r(202e-6,.95084798,.30965701),new r(-.95084798,-70000002e-12,.30965701),new r(147e-6,-.95084399,.30967101),new r(.55237001,-11e-6,.83359897),new r(19999999e-12,.55238003,.833592),new r(-.55238003,57000001e-12,.83359301),new r(-66000001e-12,-.55237001,.83359897)],p=[new r(.67121398,.19849201,-.714194),new r(.26964301,.58439398,-.76536),new r(-.040546,.096988,-.99445897),new r(-.57242799,-.091913998,-.81478697),new r(-.17140099,-.57270998,-.80163902),new r(.36255699,-.30299899,-.88133103),new r(.81034702,-.34897199,-.470698),new r(.103962,.93867201,-.328767),new r(-.324047,.58766901,-.74137598),new r(-.80086499,.34046099,-.49264699),new r(-.66549802,-.59014702,-.45698899),new r(.314767,-.803002,-.506073),new r(.97262901,.151076,-.17655),new r(.680291,.68423599,-.26272699),new r(-.52007902,.82777703,-.210483),new r(-.96164399,-.179001,-.207847),new r(-.262714,-.937451,-.22840101),new r(.219707,-.97130102,.091124997),new r(.92380798,-.229975,.30608699),new r(-.082488999,.97065997,.225866),new r(-.59179801,.69678998,.40528899),new r(-.92529601,.36660099,.097111002),new r(-.705051,-.68777502,.172828),new r(.7324,-.68036699,-.026304999),new r(.85516202,.37458199,.358311),new r(.47300601,.83648002,.276705),new r(-.097617,.65411198,.750072),new r(-.90412402,-.153725,.39865801),new r(-.211916,-.85808998,.46773201),new r(.50022697,-.67440802,.543091),new r(.584539,-.110249,.80384099),new r(.43737301,.45464399,.77588898),new r(-.042440999,.083318003,.995619),new r(-.59625101,.22013199,.77202803),new r(-.506455,-.39697701,.76544899),new r(.070569001,-.47847399,.87526202)],g=[new r(.45651099,-.073968001,-.88663799),new r(.50769401,.38511699,-.77067),new r(.095431998,.22666401,-.96928602),new r(-.35876599,.54318798,-.75910097),new r(-.361276,.13299499,-.92292601),new r(-.48311701,-.32406601,-.813375),new r(-.018073,-.197559,-.980124),new r(.3211,-.501477,-.80337799),new r(.79949099,.069615997,-.59662998),new r(.390971,.77130598,-.50222403),new r(.080782004,.61448997,-.784778),new r(-.73275,.41143101,-.54203498),new r(-.73525399,.0091019999,-.67773098),new r(-.80249399,-.39490801,-.44727099),new r(-.13413,-.58915502,-.79680902),new r(.71955299,-.37622699,-.58369303),new r(.96687502,.173593,-.187132),new r(.760831,.51910597,-.38944301),new r(-.114642,.87551898,-.46938601),new r(-.53236699,.76885903,-.354177),new r(-.96226698,.024977,-.27095801),new r(-.46738699,-.721986,-.51018202),new r(.058449998,-.85235399,-.51968902),new r(.49823299,-.74374002,-.44566301),new r(.93915099,-.27024499,-.212044),new r(.58393198,.80944198,-.061857),new r(.183797,.97322798,-.138007),new r(-.88435501,.45221901,-.115822),new r(-.943178,-.33206701,.012138),new r(-.69844002,-.70656699,-.113772),new r(-.228411,-.95470601,-.190694),new r(.73156399,-.675861,-.089588001),new r(.96925098,.046804,.24158201),new r(.85564703,.50347698,.119916),new r(-.25115299,.96794701,-80999998e-12),new r(-.64779502,.75674897,.087711997),new r(-.96916401,.14519399,.1991),new r(-.41479301,-.88896698,.194126),new r(.25077501,-.961178,-.115109),new r(.47862899,-.84259301,.246883),new r(.89004397,-.39614201,.225595),new r(.52405101,.76235998,.37970701),new r(.11962,.94548202,.30291),new r(-.76085001,.49007499,.42536199),new r(-.86978501,-.20215,.450122),new r(-.70946699,-.60242403,.36570701),new r(.019308999,-.95887101,.28318599),new r(.626113,-.564677,.53770101),new r(.769943,-.126663,.62541503),new r(.76419097,.35070199,.54131401),new r(-.001878,.74136698,.67109799),new r(-.37088001,.81836802,.43900099),new r(-.71390897,.12865201,.68831801),new r(-.295165,-.73866397,.60601401),new r(.186195,-.73836899,.648184),new r(.387523,-.35878301,.84917599),new r(.481022,.124846,.86777401),new r(.391808,.54505599,.741216),new r(-.0035359999,.36559799,.93076599),new r(-.42049801,.484961,.76680797),new r(-.35490301,.019470001,.93470001),new r(-.54783702,-.35920799,.75554299),new r(-.106662,-.445115,.88909799),new r(.086796001,-.059307002,.99445897)],m=[new r(.52657801,-.35962099,-.77031702),new r(.150482,.43598399,.88728398),new r(.414195,.73825502,-.53237402),new r(.075152002,.91624898,-.393498),new r(-.316149,.93073601,-.18379299),new r(-.77381903,.62333399,-.11251),new r(-.90084201,.42853701,-.069568001),new r(-.99894202,-.010971,.044665001),new r(-.979761,-.15767001,-.123324),new r(-.91127402,-.362371,-.19562),new r(-.62406898,-.72094101,-.301301),new r(-.310173,-.80934501,-.498752),new r(.146613,-.81581903,-.55941403),new r(-.71651602,-.69435602,-.066887997),new r(.50397199,-.114202,-.85613698),new r(.45549101,.87262702,-.176211),new r(-.00501,-.114373,-.99342501),new r(-.104675,-.327701,-.93896502),new r(.56041199,.75258899,-.34575599),new r(-.060575999,.82162797,-.566796),new r(-.30234101,.79700702,-.522847),new r(-.671543,.67074001,-.314863),new r(-.77840102,-.12835699,.61450499),new r(-.92404997,.278382,-.261985),new r(-.69977301,-.55049098,-.45527801),new r(-.56824797,-.51718903,-.64000797),new r(.054097999,-.93286401,-.356143),new r(.75838202,.57289302,-.31088799),new r(.0036200001,.30502599,-.95233703),new r(-.060849998,-.98688602,-.14951099),new r(.63523,.045478001,-.77098298),new r(.52170497,.241309,-.81828701),new r(.26940399,.63542497,-.72364098),new r(.045676,.67275399,-.738455),new r(-.180511,.67465699,-.71571898),new r(-.397131,.63664001,-.66104198),new r(-.55200398,.47251499,-.687038),new r(-.77217001,.08309,-.62996),new r(-.669819,-.119533,-.73284),new r(-.54045498,-.31844401,-.77878201),new r(-.38613501,-.522789,-.75999397),new r(-.261466,-.68856698,-.676395),new r(-.019412,-.69610298,-.71767998),new r(.30356899,-.48184401,-.82199299),new r(.68193901,-.19512901,-.70490003),new r(-.24488901,-.116562,-.96251899),new r(.80075902,-.022979001,-.59854603),new r(-.37027499,.095583998,-.92399102),new r(-.33067101,-.32657799,-.88543999),new r(-.16322,-.52757901,-.83367902),new r(.12639,-.313146,-.941257),new r(.34954801,-.27222601,-.89649802),new r(.23991799,-.085825004,-.96699202),new r(.390845,.081537001,-.91683799),new r(.25526699,.26869699,-.92878503),new r(.146245,.48043799,-.86474901),new r(-.32601601,.47845599,-.81534898),new r(-.46968201,-.112519,-.87563598),new r(.81844002,-.25852001,-.51315099),new r(-.474318,.292238,-.83043301),new r(.778943,.39584199,-.48637101),new r(.62409401,.39377299,-.67487001),new r(.74088597,.203834,-.63995302),new r(.48021701,.565768,-.67029703),new r(.38093001,.42453501,-.82137799),new r(-.093422003,.50112402,-.86031801),new r(-.236485,.29619801,-.92538702),new r(-.131531,.093959004,-.98684901),new r(-.82356203,.29577699,-.48400599),new r(.61106598,-.624304,-.486664),new r(.069495998,-.52033001,-.85113299),new r(.226522,-.66487902,-.711775),new r(.47130799,-.56890398,-.67395699),new r(.38842499,-.74262398,-.54556),new r(.78367501,-.48072901,-.39338499),new r(.962394,.135676,-.235349),new r(.876607,.172034,-.449406),new r(.63340503,.58979303,-.50094098),new r(.182276,.80065799,-.57072097),new r(.177003,.76413399,.62029701),new r(-.544016,.675515,-.49772099),new r(-.67929697,.28646699,-.67564201),new r(-.59039098,.091369003,-.801929),new r(-.82436001,-.13312399,-.55018902),new r(-.71579403,-.33454201,-.61296099),new r(.17428599,-.89248401,.416049),new r(-.082528003,-.83712298,-.54075301),new r(.28333101,-.88087398,-.37918901),new r(.675134,-.42662701,-.60181701),new r(.84372002,-.512335,-.160156),new r(.97730398,-.098555997,-.18752),new r(.846295,.522672,-.102947),new r(.67714101,.72132498,-.145501),new r(.32096499,.87089199,-.37219399),new r(-.178978,.911533,-.37023601),new r(-.44716901,.82670099,-.341474),new r(-.70320302,.496328,-.50908101),new r(-.97718102,.063562997,-.202674),new r(-.87817001,-.412938,.241455),new r(-.83583099,-.35855001,-.415728),new r(-.499174,-.69343299,-.51959199),new r(-.188789,-.92375302,-.33322501),new r(.19225401,-.96936101,-.152896),new r(.51594001,-.783907,-.34539199),new r(.90592498,-.30095199,-.29787099),new r(.99111199,-.127746,.037106998),new r(.99513501,.098424003,-.0043830001),new r(.76012301,.64627701,.067367002),new r(.205221,.95958,-.192591),new r(-.042750001,.97951299,-.19679099),new r(-.43801701,.89892697,.0084920004),new r(-.82199401,.48078501,-.30523899),new r(-.89991701,.081710003,-.42833701),new r(-.92661202,-.144618,-.347096),new r(-.79365999,-.55779201,-.24283899),new r(-.43134999,-.84777898,-.30855799),new r(-.0054919999,-.96499997,.26219299),new r(.58790499,-.80402601,-.088940002),new r(.69949299,-.66768599,-.254765),new r(.88930303,.359795,-.282291),new r(.780972,.197037,.59267199),new r(.52012098,.50669599,.68755698),new r(.40389499,.69396102,.59605998),new r(-.154983,.89923602,.40909001),new r(-.65733802,.53716803,.528543),new r(-.74619502,.33409101,.575827),new r(-.62495202,-.049144,.77911502),new r(.31814101,-.254715,.913185),new r(-.555897,.405294,.725752),new r(-.79443401,.099405997,.59916002),new r(-.64036101,-.68946302,.33849499),new r(-.12671299,-.73409498,.66711998),new r(.105457,-.78081697,.61579502),new r(.40799299,-.48091599,.77605498),new r(.69513601,-.54512,.468647),new r(.97319102,-.0064889998,.229908),new r(.94689399,.317509,-.050799001),new r(.56358302,.82561201,.027183),new r(.325773,.94542301,.0069490001),new r(-.171821,.98509699,-.0078149997),new r(-.67044097,.73993897,.054768998),new r(-.822981,.55496198,.121322),new r(-.96619302,.117857,.229307),new r(-.95376903,-.29470399,.058945),new r(-.86438698,-.50272799,-.010015),new r(-.53060901,-.84200603,-.097365998),new r(-.162618,-.98407501,.071772002),new r(.081446998,-.99601102,.036439002),new r(.74598402,-.66596299,.00076199998),new r(.94205701,-.32926899,-.064106002),new r(.93970197,-.28108999,.194803),new r(.77121401,.55067003,.319363),new r(.641348,.73069,.23402099),new r(.080682002,.99669099,.0098789996),new r(-.046725001,.97664303,.20972501),new r(-.53107601,.82100099,.209562),new r(-.69581503,.65599,.29243499),new r(-.97612202,.216709,-.014913),new r(-.96166098,-.14412899,.23331399),new r(-.772084,-.61364698,.165299),new r(-.44960001,-.83605999,.314426),new r(-.39269999,-.91461599,.096247002),new r(.390589,-.91947001,.044890001),new r(.58252901,-.79919797,.148127),new r(.866431,-.48981199,.096864),new r(.90458697,.111498,.41145),new r(.95353699,.23232999,.191806),new r(.497311,.77080297,.398177),new r(.194066,.95631999,.218611),new r(.422876,.882276,.206797),new r(-.373797,.84956598,.37217399),new r(-.53449702,.71402299,.4522),new r(-.881827,.23716,.40759799),new r(-.904948,-.014069,.42528901),new r(-.751827,-.51281703,.41445801),new r(-.50101501,-.69791698,.51175803),new r(-.23519,-.92592299,.295555),new r(.228983,-.95393997,.193819),new r(.734025,-.63489801,.241062),new r(.91375297,-.063253,-.40131599),new r(.90573502,-.161487,.391875),new r(.85892999,.342446,.38074899),new r(.62448603,.60758102,.49077699),new r(.28926399,.85747898,.42550799),new r(.069968,.90216899,.42567101),new r(-.28617999,.94069999,.182165),new r(-.57401299,.80511898,-.14930899),new r(.111258,.099717997,-.98877603),new r(-.30539301,-.94422799,-.12316),new r(-.60116601,-.78957599,.123163),new r(-.290645,-.81213999,.50591898),new r(-.064920001,-.87716299,.47578499),new r(.408301,-.862216,.29978901),new r(.56609702,-.72556603,.39126399),new r(.83936399,-.427387,.33586901),new r(.81889999,-.041305002,.57244802),new r(.71978402,.41499701,.55649698),new r(.88174403,.45027,.140659),new r(.40182301,-.89822,-.17815199),new r(-.054019999,.79134399,.60898),new r(-.29377401,.76399398,.57446498),new r(-.450798,.61034697,.65135098),new r(-.63822103,.186694,.74687302),new r(-.87287003,-.25712699,.41470799),new r(-.58725703,-.52170998,.618828),new r(-.35365799,-.64197397,.680291),new r(.041648999,-.61127299,.79032302),new r(.348342,-.77918297,.52108699),new r(.499167,-.62244099,.602826),new r(.79001898,-.30383101,.53250003),new r(.66011798,.060733002,.74870199),new r(.60492098,.29416099,.73996001),new r(.38569701,.37934601,.84103203),new r(.239693,.207876,.94833201),new r(.012623,.25853199,.96591997),new r(-.100557,.457147,.88368797),new r(.046967,.62858802,.77631903),new r(-.43039101,-.44540501,.785097),new r(-.43429101,-.196228,.87913901),new r(-.25663701,-.336867,.90590203),new r(-.131372,-.15891001,.97851402),new r(.102379,-.208767,.972592),new r(.195687,-.450129,.87125802),new r(.62731898,-.42314801,.65377098),new r(.68743902,-.171583,.70568198),new r(.27592,-.021255,.96094602),new r(.45936701,.15746599,.87417799),new r(.285395,.583184,.76055598),new r(-.81217402,.46030301,.35846099),new r(-.189068,.64122301,.743698),new r(-.338875,.47648001,.811252),new r(-.92099398,.347186,.176727),new r(.040638998,.024465,.99887401),new r(-.73913199,-.35374701,.57318997),new r(-.60351199,-.28661501,.74405998),new r(-.188676,-.547059,.81555402),new r(-.026045,-.39782,.91709399),new r(.26789701,-.649041,.71202302),new r(.518246,-.28489101,.80638599),new r(.493451,-.066532999,.86722499),new r(-.328188,.140251,.93414301),new r(.328188,.140251,.93414301),new r(-.328188,.140251,.93414301),new r(-.328188,.140251,.93414301),new r(-.328188,.140251,.93414301)];class f{constructor(e,t,i){this.sizeX=e,this.sizeY=t,this.sizeZ=i,this.arr=new Array(e*t*i)}add(e){this.arr[e.x+e.y*this.sizeX+e.z*this.sizeX*this.sizeY]=e}get(e,t,i){if(!(e>=this.sizeX||t>=this.sizeY||i>=this.sizeZ))return this.arr[e+t*this.sizeX+i*this.sizeX*this.sizeY]}}var y=__webpack_require__(949);class w{get spanX(){return this.maxBounds.x-this.minBounds.x}get spanY(){return this.maxBounds.y-this.minBounds.y}get spanZ(){return this.maxBounds.z-this.minBounds.z}get scaleX(){return this.spanX/this.sizeX}get scaleY(){return this.spanY/this.sizeY}get scaleZ(){return this.spanZ/this.sizeZ}get scale(){return new y.Vector3(this.scaleX,this.scaleY,this.scaleZ)}getAllVoxels(){let i=[],s=new f(this.sizeX+1,this.sizeY+1,this.sizeZ+1);for(let e=0,t=this.spans.length;e<t;e++){var r=this.spans[e].voxels;for(let e=0,t=r.length;e<t;e++){var a=r[e];i.push(a),s.add(a)}}return{voxels:i,voxelField:s}}getNormals(){switch(this.normalsMode){case 1:return u;case 2:return p;case 3:return g;case 4:return m;default:throw new Error(`Invalid normalsmode ${this.normalsMode}`)}}scaleHvaMatrix(e){return(e=e.clone()).elements[12]*=this.hvaMultiplier,e.elements[13]*=this.hvaMultiplier,e.elements[14]*=this.hvaMultiplier,e}toPlain(){return{name:this.name,normalsMode:this.normalsMode,minBounds:this.minBounds.toArray(),maxBounds:this.maxBounds.toArray(),sizeX:this.sizeX,sizeY:this.sizeY,sizeZ:this.sizeZ,hvaMultiplier:this.hvaMultiplier,transfMatrix:this.transfMatrix.toArray(),spans:this.spans}}fromPlain(e){return this.name=e.name,this.normalsMode=e.normalsMode,this.minBounds=(new y.Vector3).fromArray(e.minBounds),this.maxBounds=(new y.Vector3).fromArray(e.maxBounds),this.sizeX=e.sizeX,this.sizeY=e.sizeY,this.sizeZ=e.sizeZ,this.hvaMultiplier=e.hvaMultiplier,this.transfMatrix=(new y.Matrix4).fromArray(e.transfMatrix),this.spans=e.spans,this}}class T{read(e){this.fileName=e.readCString(16),this.paletteCount=e.readUint32(),this.headerCount=e.readUint32(),this.tailerCount=e.readUint32(),this.bodySize=e.readUint32(),this.paletteRemapStart=e.readUint8(),this.paletteRemapEnd=e.readUint8(),e.seek(e.position+768)}}T.size=32;var v=__webpack_require__(949);class S{constructor(e){this.voxelCount=0,e instanceof i&&this.fromVirtualFile(e)}fromVirtualFile(e){this.filename=e.filename;let r=e.stream;if(this.sections=[],!(r.byteLength<T.size)){let s=new T;if(s.read(r),s.headerCount&&s.tailerCount&&s.tailerCount===s.headerCount){for(let e=0;e<s.headerCount;++e){const n=new w;this.readSectionHeader(n,r),this.sections.find(e=>e.name===n.name)&&console.warn(`Duplicate section name "${n.name}" found in VXL "${this.filename}".`),this.sections.push(n)}var a=r.position;r.seek(r.position+s.bodySize);let t=[];for(let e=0;e<s.tailerCount;++e)t[e]=this.readSectionTailer(this.sections[e],r);let i=0;for(let e=0;e<s.headerCount;++e)r.seek(a),i+=this.readSectionBodySpans(this.sections[e],t[e],r);this.voxelCount=i}}}readSectionHeader(e,t){e.name=t.readCString(16),t.readUint32(),t.readUint32(),t.readUint32()}readSectionTailer(e,t){var i=t.readUint32(),s=t.readUint32(),r=t.readUint32();return e.hvaMultiplier=t.readFloat32(),e.transfMatrix=this.readTransfMatrix(t),e.minBounds=new v.Vector3(t.readFloat32(),t.readFloat32(),t.readFloat32()),e.maxBounds=new v.Vector3(t.readFloat32(),t.readFloat32(),t.readFloat32()),e.sizeX=t.readUint8(),e.sizeY=t.readUint8(),e.sizeZ=t.readUint8(),e.normalsMode=t.readUint8(),{startingSpanOffset:i,endingSpanOffset:s,dataSpanOffset:r}}readTransfMatrix(t){let i=[];for(let e=0;e<3;++e)i.push(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32());return i.push(0,0,0,1),(new v.Matrix4).fromArray(i).transpose()}readSectionBodySpans(e,t,i){i.seek(i.position+t.startingSpanOffset);var{sizeX:s,sizeY:r,sizeZ:a}=e;let n=new Array(r);for(let t=0;t<r;++t){n[t]=new Array(s);for(let e=0;e<s;++e)n[t][e]=i.readInt32()}let o=new Array(r);for(let t=0;t<r;++t){o[t]=new Array(s);for(let e=0;e<s;++e)o[t][e]=i.readInt32()}let h=e.spans=[],l=0;for(let t=0;t<r;++t)for(let e=0;e<s;++e){var c={x:e,y:t,voxels:this.readSpanVoxels(n[t][e],o[t][e],e,t,a,i)};h.push(c),l+=c.voxels.length}return l}readSpanVoxels(e,t,i,s,r,a){if(-1===e||-1===t)return[];let n=[];for(let t=0;t<r;){t+=a.readUint8();var o=a.readUint8();for(let e=0;e<o;++e){var h={x:i,y:s,z:t++,colorIndex:a.readUint8(),normalIndex:a.readUint8()};n.push(h)}a.readUint8()}return n}fromPlain(e){return this.sections=e.sections.map(e=>(new w).fromPlain(e)),this.voxelCount=e.voxelCount,this}toPlain(){return{sections:this.sections.map(e=>e.toPlain()),voxelCount:this.voxelCount}}getSection(e){return this.sections[e]}}var k,O,_,I,C,A=__webpack_require__(949);(r=k=k||{})[r.ExtraData=1]="ExtraData",r[r.ZData=2]="ZData",r[r.DamagedData=4]="DamagedData";const B=e=>e<0?e+256:e;class x{constructor(e,t,i){this.fromStream(e,t,i)}fromStream(e,t,i){this.x=e.readInt32(),this.y=e.readInt32(),e.readInt32(),e.readInt32();var s=e.readInt32();this.extraX=e.readInt32(),this.extraY=e.readInt32(),this.extraWidth=e.readInt32(),this.extraHeight=e.readInt32();var r=e.readUint32();this.height=e.readUint8(),this.terrainType=e.readUint8(),this.rampType=e.readUint8(),this.radarLeft=this.readRadarRgb(e.readInt8(),e.readInt8(),e.readInt8()),this.radarRight=this.readRadarRgb(e.readInt8(),e.readInt8(),e.readInt8()),e.seek(e.position+3),this.tileData=new Uint8Array(e.buffer,e.byteOffset+e.position,t*i/2),e.position+=t*i/2,this.hasZData=(r&k.ZData)===k.ZData,this.hasZData&&(e.position+=t*i/2),this.hasExtraData=(r&k.ExtraData)===k.ExtraData,this.hasExtraData&&(r=Math.abs(this.extraWidth*this.extraHeight),this.extraData=new Uint8Array(e.buffer,e.byteOffset+e.position,r),e.position+=r),this.hasZData&&this.hasExtraData&&0<s&&s<e.byteLength&&(e.position+=Math.abs(this.extraWidth*this.extraHeight))}readRadarRgb(e,t,i){return new A.Color(B(e)/255,B(t)/255,B(i)/255)}}class E{constructor(e){this.images=[],e instanceof i&&this.fromVirtualFile(e)}fromVirtualFile(e){let t=e.stream;this.width=t.readInt32(),this.height=t.readInt32(),this.blockWidth=t.readInt32(),this.blockHeight=t.readInt32();var i=this.width*this.height,s=new Uint8Array(t.buffer,t.byteOffset+t.position,4*i);this.images=[];for(let e=0;e<i;e++){var r=s[4*e+3]<<24|s[4*e+2]<<16|s[4*e+1]<<8|s[4*e];t.seek(r);r=new x(t,this.blockWidth,this.blockHeight);this.images.push(r)}}}class P{static encode(e){return void 0!==globalThis.btoa?globalThis.btoa(e):Buffer.from(e,"binary").toString("base64")}static decode(e){return void 0!==globalThis.atob?globalThis.atob(e):Buffer.from(e,"base64").toString("binary")}static isBase64(e){return!!e.match(/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/)}}function N(e,t="0000"){e=""+e;return t.substring(0,t.length-e.length)+e}function M(e,t){return e.toLowerCase()===t.toLowerCase()}function D(t){var i=t.length;let s=new Uint8Array(i);for(let e=0;e<i;e++)s[e]=t.charCodeAt(e);return s}function R(e){return D(P.decode(e))}function L(e){return e.reduce((e,t)=>e+String.fromCharCode(t),"")}function F(t){var i=t.length;let s="";for(let e=0;e<i;e++){var r=t.charCodeAt(e);s+=String.fromCharCode(r>>8),s+=String.fromCharCode(255&r)}return s}function j(t){var i=t.length;let s="";for(let e=0;e<i;e+=2){var r=(t.charCodeAt(e)<<8)+t.charCodeAt(e+1);s+=String.fromCharCode(r)}return s}class U{constructor(e,t,i){this.r=e,this.g=t,this.b=i}static fromRgb(e,t,i){return new U(e,t,i)}static fromHsv(e,t,i){let s=0,r=0,a=0;if(e=e/255*360%360,i/=255,0===(t/=255))s=i,r=i,a=i;else{var n=e/60,e=Math.floor(n),n=n-e,o=i*(1-t),h=i*(1-t*n),l=i*(1-t*(1-n));switch(e){case 0:s=i,r=l,a=o;break;case 1:s=h,r=i,a=o;break;case 2:s=o,r=i,a=l;break;case 3:s=o,r=h,a=i;break;case 4:s=l,r=o,a=i;break;case 5:s=i,r=o,a=h}}return U.fromRgb(Math.floor(255*s),Math.floor(255*r),Math.floor(255*a))}asHex(){return(this.r<<16)+(this.g<<8)+this.b}asHexString(){return"#"+N(this.asHex().toString(16),"000000")}clone(){return new U(this.r,this.g,this.b)}}function W(e,t,i){return Math.min(i,Math.max(e,t))}function z(e,t,i){return t<=e&&e<=i}function V(e,t,i){return(1-i)*e+i*t}function H(i){let s=2166136261;for(let e=0,t=i.length;e<t;++e)s^=i[e],s+=(s<<1)+(s<<4)+(s<<7)+(s<<8)+(s<<24);return s>>>0}class G{constructor(e){e instanceof i?this.fromVirtualFile(e):"object"==typeof e&&this.fromJson(e)}fromVirtualFile(e){e=e.stream.readUint8Array(768);this.fromJson(e)}fromJson(t){this.colors=[];for(let e=0;e<t.length/3;++e)this.colors.push(U.fromRgb(4*t[3*e],4*t[3*e+1],4*t[3*e+2]));this._hash=this.computeHash(this.colors)}getColor(e){return this.colors[e]}getColorAsHex(e){return this.getColor(e).asHex()}setColors(e){this.colors=e,this._hash=this.computeHash(this.colors)}get size(){return this.colors.length}get hash(){return this._hash}computeHash(e){let t=new Uint8Array(3*this.size),i=0;for(var s of e)t[i]=s.r,t[i+1]=s.g,t[i+2]=s.b,i+=3;return H(t)}clone(){let e=new G;return e.colors=this.colors.map(e=>e.clone()),e._hash=this._hash,e}remap(t){var i=[63,59,55,52,48,44,41,37,33,30,26,22,19,15,11,8];for(let e=G.REMAP_START_IDX;e<G.REMAP_START_IDX+i.length;e++)this.colors[e].r=Math.floor(t.r/255*i[e-G.REMAP_START_IDX]*4),this.colors[e].g=Math.floor(t.g/255*i[e-G.REMAP_START_IDX]*4),this.colors[e].b=Math.floor(t.b/255*i[e-G.REMAP_START_IDX]*4);return this._hash=this.computeHash(this.colors),this}}G.REMAP_START_IDX=16;class ${constructor(e,t){this.owner=e,this.index=t,this.files=[]}addFile(e){this.files.push(e)}setAnimation(e){this.animation=e}getAnimation(){return this.animation}getTmpFile(e,t,i=!1){if(this.files.length){t=this.files[t(0,this.files.length-1)];return t.images[Math.min(e,t.images.length-1)].hasDamagedData?this.files[Math.min(i?1:0,this.files.length-1)]:t}}}class q{constructor(e,t,i){this.fileName=e,this.setName=t,this.tilesInSet=i,this.entries=[]}}class X{constructor(e,t,i,s){this.name=e,this.subTile=t,this.offsetX=i,this.offsetY=s}}(r=O=O||{})[r.TopLeft=0]="TopLeft",r[r.BottomRight=1]="BottomRight",r[r.TopRight=2]="TopRight",r[r.BottomLeft=3]="BottomLeft",r[r.MiddleTlBr=4]="MiddleTlBr",r[r.MiddleTrBl=5]="MiddleTrBl";const Z=new Map([[O.TopLeft,["BridgeTopLeft1","BridgeTopLeft2"]],[O.BottomRight,["BridgeBottomRight1","BridgeBottomRight2"]],[O.TopRight,["BridgeTopRight1","BridgeTopRight2"]],[O.BottomLeft,["BridgeBottomLeft1","BridgeBottomLeft2"]],[O.MiddleTlBr,["BridgeMiddle1"]],[O.MiddleTrBl,["BridgeMiddle2"]]]);class Q{constructor(e){this.theaterIni=e,this.tileSets=[],this.orderedEntries=[],this.highBridgeSetNums=[this.getGeneralValue("BridgeSet"),this.getGeneralValue("WoodBridgeSet")],this.cliffSetNums=[this.getGeneralValue("CliffSet"),this.getGeneralValue("WaterCliffs"),this.getGeneralValue("DestroyableCliffs")]}getTile(e){return this.orderedEntries[e]}getTileImage(e,t,i){let s=this.getTile(e);if(!s)throw new Error(`TileNum ${e} not found`);i=s.getTmpFile(t,i);if(!i||t>=i.images.length)throw new Error(`SubTile ${t} not found`);return i.images[t]}getSetNum(e){var t=this.orderedEntries[e];if(!t)throw new Error("Invalid tileNum "+e);return this.tileSets.indexOf(t.owner)}getTileNumFromSet(i,s=0){let r=0;return this.tileSets.some((e,t)=>t===i?(r+=s,!0):(r+=e.entries.length,!1)),r}getGeneralValue(e){let t=this.theaterIni.getSection("General");if(!t)throw new Error("Missing [General] section in theather ini");return t.getNumber(e)}loadTileData(e,t){this.tileSets.length=0,this.orderedEntries.length=0,this.initTileSets(e,t),this.initAnimations()}readMaxTileNum(){let t=0,i=0;for(;;){var s="TileSet"+N(t,"0000");let e=this.theaterIni.getSection(s);if(!e)break;t++,i+=e.getNumber("TilesInSet")}return i}initTileSets(a,n){let e=0,t;for(var i;;){if(i="TileSet"+N(e,"0000"),t=this.theaterIni.getSection(i),!t)break;e++;let r=new q(t.getString("FileName"),t.getString("SetName"),t.getNumber("TilesInSet"));this.tileSets.push(r);for(let s=1;s<=r.tilesInSet;s++){let i=new $(r,s-1);var o="a".charCodeAt(0);for(let t=o-1;t<="z".charCodeAt(0);t++)if(!(t>=o&&"Bridges"===r.setName)){let e=r.fileName+N(s,"00");t>=o&&(e+=String.fromCharCode(t)),e+=n;var h=a.get(e);if(!h)break;i.addFile(h)}r.entries.push(i),this.orderedEntries.push(i)}}}initAnimations(){var s=this.theaterIni.getOrderedSections();for(let e=this.tileSets.length;e<s.length;++e){let t=s[e],i=this.tileSets.find(e=>e.setName===t.name);if(i)for(let e=1;e<=i.tilesInSet;++e){var r=`Tile${N(e,"00")}`,a=`${r}Anim`,n=t.getString(a);n?(r=new X(n,t.getNumber(`${r}AttachesTo`),t.getNumber(`${r}XOffset`),t.getNumber(`${r}YOffset`)),i.entries[e-1].setAnimation(r)):console.warn(`Missing anim "${a}" for tileset ${i.setName}`)}}}isLAT(e){return e===this.getGeneralValue("RoughTile")||e===this.getGeneralValue("SandTile")||e===this.getGeneralValue("GreenTile")||e===this.getGeneralValue("PaveTile")}isCLAT(e){return e===this.getGeneralValue("ClearToRoughLat")||e===this.getGeneralValue("ClearToSandLat")||e===this.getGeneralValue("ClearToGreenLat")||e===this.getGeneralValue("ClearToPaveLat")}getLAT(e){return e===this.getGeneralValue("ClearToRoughLat")?this.getGeneralValue("RoughTile"):e===this.getGeneralValue("ClearToSandLat")?this.getGeneralValue("SandTile"):e===this.getGeneralValue("ClearToGreenLat")?this.getGeneralValue("GreenTile"):e===this.getGeneralValue("ClearToPaveLat")?this.getGeneralValue("PaveTile"):-1}getCLATSet(e){return e===this.getGeneralValue("RoughTile")?this.getGeneralValue("ClearToRoughLat"):e===this.getGeneralValue("SandTile")?this.getGeneralValue("ClearToSandLat"):e===this.getGeneralValue("GreenTile")?this.getGeneralValue("ClearToGreenLat"):e===this.getGeneralValue("PaveTile")?this.getGeneralValue("ClearToPaveLat"):-1}canConnectTiles(e,t){if(e===t)return!1;var i=this.getGeneralValue("GreenTile"),s=this.getGeneralValue("PaveTile"),r=this.getGeneralValue("MiscPaveTile"),a=this.getGeneralValue("ShorePieces"),n=this.getGeneralValue("WaterBridge"),o=this.getGeneralValue("PavedRoads"),h=this.getGeneralValue("Medians");return!(e===i&&t===a||t===i&&e===a)&&(!(e===i&&t===n||t===i&&e===n)&&(!(e===s&&t===o||t===s&&e===o)&&(!(e===s&&t===r||t===s&&e===r)&&!(e===s&&t===h||t===s&&e===h))))}getHighBridgeHeadType(e){for(var[t,i]of Z)for(var s of i)if(this.getGeneralValue(s)===e+1)return t}getOppositeHighBridgeHeadType(e){switch(e){case O.TopLeft:return O.BottomRight;case O.TopRight:return O.BottomLeft;case O.BottomLeft:return O.TopRight;case O.BottomRight:return O.TopLeft;case O.MiddleTlBr:case O.MiddleTrBl:throw new Error("Middle bridge heads can't have opposites");default:throw new Error(`Unhandled headType ${e}`)}}isCliffTile(e){return this.cliffSetNums.includes(this.getSetNum(e))}isHighBridgeBoundaryTile(e){if(this.highBridgeSetNums.includes(this.getSetNum(e))){e=this.getTile(e),e=this.getHighBridgeHeadType(e.index);return void 0!==e&&![O.MiddleTlBr,O.MiddleTrBl].includes(e)}return!1}isHighBridgeMiddleTile(e){if(this.highBridgeSetNums.includes(this.getSetNum(e))){e=this.getTile(e),e=this.getHighBridgeHeadType(e.index);return void 0!==e&&[O.MiddleTlBr,O.MiddleTrBl].includes(e)}return!1}}(r=_=_||{})[r.None=0]="None",r[r.Iso=1]="Iso",r[r.Unit=2]="Unit",r[r.Overlay=3]="Overlay",r[r.Anim=4]="Anim",r[r.Custom=5]="Custom",r[r.Default=6]="Default";class Y{constructor(e,t,i,s,r,a,n,o,h){this.type=e,this.settings=t,this.palettes=i,this.isoPalette=s,this.ovlPalette=r,this.unitPalette=a,this.animPalette=n,this.libPalette=o,this.tileSets=h}static factory(e,t,i,s,r){var a=r.get(i.IsoPaletteName);if(!a)throw new Error(`Missing palette "${i.IsoPaletteName}"`);var n=r.get(i.OverlayPaletteName);if(!n)throw new Error(`Missing palette "${i.OverlayPaletteName}"`);var o=r.get(i.UnitPaletteName);if(!o)throw new Error(`Missing palette "${i.UnitPaletteName}"`);var h=r.get("anim.pal");if(!h)throw new Error("Missing anim palette");var l=r.get(i.LibPaletteName);if(!l)throw new Error(`Missing lib palette ${i.LibPaletteName}`);let c=new Q(t);return c.loadTileData(s,i.Extension),new this(e,i,r,a,n,o,h,l,c)}getPalette(e,t){switch(e){case _.Anim:return this.animPalette;case _.Overlay:return this.ovlPalette;case _.Unit:return this.unitPalette;case _.Custom:if("lib"===t)return this.libPalette;var i=this.palettes.get(t+".pal");if(!i)throw new Error(`Custom palette "${t}" not found`);return i;default:_.Iso;return this.isoPalette}}}(r=I=I||{})[r.None=0]="None",r[r.Temperate=1]="Temperate",r[r.Urban=2]="Urban",r[r.Snow=4]="Snow",r[r.Lunar=8]="Lunar",r[r.Desert=16]="Desert",r[r.NewUrban=32]="NewUrban",r[r.All=63]="All";class K{constructor(){this.fileData=new Map}fromVirtualFile(e,t){var i,s;for([i,s]of t.entries){var r=this.buildWavData(e.stream,s);this.fileData.set(i,r)}return this}getFileList(){return[...this.fileData.keys()]}containsFile(e){return this.fileData.has(e)}openFile(e){if(!this.containsFile(e))throw new Error(`File "${e}" not found`);return new i(this.fileData.get(e),e)}buildWavData(e,t){let i=new b;var s,r,a,n,o=0<(1&t.flags)?2:1;let h=0;0<(2&t.flags)?(i.writeString("RIFF"),i.writeUint32(t.length+36),i.writeString("WAVE"),i.writeString("fmt "),i.writeInt32(16),i.writeInt16(1),i.writeInt16(o),i.writeUint32(t.sampleRate),i.writeUint32(2*o*t.sampleRate),i.writeInt16(2*o),i.writeInt16(16),i.writeString("data"),i.writeUint32(t.length)):0<(8&t.flags)&&(s=11100*o*(t.sampleRate/22050|0),r=t.chunkSize,a=1017*(n=Math.max(2,Math.ceil(t.length/r))),n=n*r,h=n-t.length,i.writeString("RIFF"),i.writeUint32(52+n),i.writeString("WAVE"),i.writeString("fmt "),i.writeUint32(20),i.writeInt16(17),i.writeInt16(o),i.writeUint32(t.sampleRate),i.writeInt32(s),i.writeInt16(r),i.writeInt16(4),i.writeInt16(2),i.writeInt16(1017),i.writeString("fact"),i.writeUint32(4),i.writeInt32(a),i.writeString("data"),i.writeUint32(n)),e.seek(t.offset),i.writeUint8Array(e.readUint8Array(t.length));for(let e=0;e<h;e++)i.writeUint8(0);return i.seek(0),i._trimAlloc=()=>{},i}}class J{}class ee{constructor(e){this.entries=new Map,this.parse(e)}parse(t){var e=t.readCString(4);if("GABA"!==e)throw new Error(`Unable to load Idx file, did not find magic id, found ${e} instead`);e=t.readInt32();if(2!==e)throw new Error(`Unable to load Idx file, did not find magic number 2, found ${e} instead`);var i=t.readInt32();for(let e=0;e<i;e++){const r=new J;let e=t.readString(16);var s=e.indexOf("\0");0!==s&&(e=e.substr(0,s)),r.filename=e+".wav",r.offset=t.readUint32(),r.length=t.readUint32(),r.sampleRate=t.readUint32(),r.flags=t.readUint32(),r.chunkSize=t.readUint32(),this.entries.set(r.filename,r)}}}function te(e){return e=((e=(e<<16>>>0|e>>>16)>>>0)<<8>>>0&4278255360|e>>>8&16711935)>>>0}class ie{constructor(i){this.m_p=new Uint32Array([608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731]),this.m_s=[new Uint32Array([3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946]),new Uint32Array([1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055]),new Uint32Array([3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504]),new Uint32Array([976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462])];for(let e=0,t=0;e<18;++e){var s=i[t++%i.length],r=i[t++%i.length],a=i[t++%i.length],n=i[t++%i.length];this.m_p[e]^=s<<24|r<<16|a<<8|n}let o=0,h=0;for(let e=0;e<18;)[o,h]=this._encrypt(o,h),this.m_p[e++]=o,this.m_p[e++]=h;for(let t=0;t<4;++t)for(let e=0;e<256;)[o,h]=this._encrypt(o,h),this.m_s[t][e++]=o,this.m_s[t][e++]=h}encrypt(e){return this.runCipher(e,this._encrypt.bind(this))}decrypt(e){return this.runCipher(e,this._decrypt.bind(this))}runCipher(e,t){let i=new Uint32Array(e.length),s=e.length/2|0,r=0;for(;0<s--;){var a=te(e[r]),n=te(e[r+1]);[a,n]=t(a,n),i[r++]=te(a),i[r++]=te(n)}return i}_encrypt(e,t){let i=e,s=t;i^=this.m_p[0];let r=!1;for(let e=1;e<=16;e++,r=!r)r?i=this.round(i,s,e):s=this.round(s,i,e);return s^=this.m_p[17],[s,i]}_decrypt(e,t){let i=e,s=t;i^=this.m_p[17];let r=!1;for(let e=16;1<=e;e--,r=!r)r?i=this.round(i,s,e):s=this.round(s,i,e);return s^=this.m_p[0],[s,i]}s(e,t){return this.m_s[t][e>>(3-t<<3)&255]}bf_f(e){return(this.s(e,0)+this.s(e,1)>>>0^this.s(e,2))+this.s(e,3)>>>0}round(e,t,i){return e^(this.bf_f(t)^this.m_p[i])}}const se="AihRvNoIbTn85FZRYNZRcT+i6KpU+maCsEqr3Q5q+LDB5tH7Tz2qQ38V",re=new Int8Array([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]);class ae{constructor(){this.key1=new Uint32Array(64),this.key2=new Uint32Array(64)}}class ne{constructor(){this.pubkey=new ae,this.glob1=new Uint32Array(64),this.glob2=new Uint32Array(130),this.glob1_hi=new Uint32Array(4),this.glob1_hi_inv=new Uint32Array(4)}init_bignum(t,e,i){for(let e=0;e<i;e++)t[e]=0;t[0]=e}move_key_to_big(e,t,i,s){let r;r=0!=(128&t[0])?255:0;const a=new Uint8Array(e.buffer,e.byteOffset);let n=4*s;for(;n>i;n--)a[n-1]=r;for(;0<n;n--)a[n-1]=t[i-n]}key_to_bignum(e,t,i){let s,r,a=0;if(2===t[a]){if(a++,0!=(128&t[a])){for(s=0,r=0;r<(127&t[a]);r++)s=(s<<8>>>0|t[a+r+1])>>>0;a+=1+(127&t[a])}else s=t[a],a++;s<=4*i&&this.move_key_to_big(e,t.subarray(a),s,i)}}len_bignum(e,t){let i=t-1;for(;0<=i&&0===e[i];)i--;return i+1}bitlen_bignum(e,t){var i;let s,r;if(0===(i=this.len_bignum(e,t)))return 0;for(s=32*i,r=2147483648;0==(r&e[i-1]);)r>>>=1,s--;return s}init_pubkey(){let e=0,t;var i;const s=new Uint8Array(256);for(this.init_bignum(this.pubkey.key2,65537,64),t=0;e<se.length;)i=(((re[se.charCodeAt(e++)]>>>0<<6>>>0|255&re[se.charCodeAt(e++)])>>>0<<6>>>0|255&re[se.charCodeAt(e++)])>>>0<<6>>>0|255&re[se.charCodeAt(e++)])>>>0,s[t++]=i>>16&255,s[t++]=i>>8&255,s[t++]=255&i;this.key_to_bignum(this.pubkey.key1,s,64),this.pubkey.len=this.bitlen_bignum(this.pubkey.key1,64)-1}len_predata(){var e=(this.pubkey.len-1)/8|0;return(1+(55/e|0))*(1+e)>>>0}cmp_bignum(e,t,i){for(;0<i;){if(e[--i]<t[i])return-1;if(e[i]>t[i])return 1}return 0}mov_bignum(t,i,s){for(let e=0;e<s;e++)t[e]=i[e]}shr_bignum(e,t,i){let s;var r=t/32|0;if(0<r){for(s=0;s<i-r;s++)e[s]=e[s+r];for(;s<i;s++)e[s]=0;t%=32}if(0!==t){for(s=0;s<i-1;s++)e[s]=(e[s]>>>t|e[s+1]<<32-t>>>0)>>>0;e[s]=e[s]>>>t}}shl_bignum(e,t,i){let s;var r=t/32|0;if(0<r){for(s=i-1;s>r;s--)e[s]=e[s-r];for(;0<s;s--)e[s]=0;t%=32}if(0!==t){for(s=i-1;0<s;s--)e[s]=(e[s]<<t>>>0|e[s-1]>>>32-t)>>>0;e[0]=e[0]<<t>>>0}}sub_bignum(e,t,i,s,r){var a,n;r+=r;var o=new Uint16Array(t.buffer,t.byteOffset),h=new Uint16Array(i.buffer,i.byteOffset);const l=new Uint16Array(e.buffer,e.byteOffset);let c=0;for(;-1!=--r;)a=o[c],n=h[c],l[c]=a-n-s&65535,s=0!=(a-n-s&65536)?1:0,c++;return s}sub_bignum_word(e,t,i,s,r){var a,n;let o=0;for(;-1!=--r;)a=t[o],n=i[o],e[o]=a-n-s&65535,s=0!=(a-n-s&65536)?1:0,o++;return s}inv_bignum(e,t,i){const s=new Uint32Array(64);var r;let a,n,o=0;for(this.init_bignum(s,0,i),this.init_bignum(e,0,i),n=this.bitlen_bignum(t,i),a=1<<n%32>>>0,o=((n+32)/32|0)-1,r=4*((n-1)/32|0)>>>0,s[r/4|0]=s[r/4|0]|1<<(n-1&31)>>>0;0<n;)n--,this.shl_bignum(s,1,i),-1!==this.cmp_bignum(s,t,i)&&(this.sub_bignum(s,s,t,0,i),e[o]=e[o]|a>>>0),a>>>=1,0===a&&(o--,a=2147483648);this.init_bignum(s,0,i)}inc_bignum(e,t){let i=0;for(;0==++e[i]&&0<--t;)i++}init_two_dw(e,t){this.mov_bignum(this.glob1,e,t),this.glob1_bitlen=this.bitlen_bignum(this.glob1,t),this.glob1_len_x2=(this.glob1_bitlen+15)/16|0,this.mov_bignum(this.glob1_hi,this.glob1.subarray(this.len_bignum(this.glob1,t)-2),2),this.glob1_hi_bitlen=this.bitlen_bignum(this.glob1_hi,2)-32>>>0,this.shr_bignum(this.glob1_hi,this.glob1_hi_bitlen,2),this.inv_bignum(this.glob1_hi_inv,this.glob1_hi,2),this.shr_bignum(this.glob1_hi_inv,1,2),this.glob1_hi_bitlen=(this.glob1_hi_bitlen+15)%16+1>>>0,this.inc_bignum(this.glob1_hi_inv,2),32<this.bitlen_bignum(this.glob1_hi_inv,2)&&(this.shr_bignum(this.glob1_hi_inv,1,2),this.glob1_hi_bitlen--),this.glob1_hi_inv_lo=65535&this.glob1_hi_inv[0],this.glob1_hi_inv_hi=this.glob1_hi_inv[0]>>>16&65535}mul_bignum_word(e,t,i,s){let r,a;var n=new Uint16Array(t.buffer,t.byteOffset);let o=a=0;for(r=0;r<s;r++)a=i*n[o]+e[o]+a,e[o]=65535&a,o++,a>>>=16;e[o]+=65535&a}mul_bignum(e,t,i,s){let r;var a=new Uint16Array(i.buffer,i.byteOffset);let n=new Uint16Array(e.buffer,e.byteOffset);this.init_bignum(e,0,2*s);let o=0;for(r=0;r<2*s;r++)this.mul_bignum_word(n.subarray(o),t,a[o],2*s),o++}not_bignum(e,t){let i;for(i=0;i<t;i++)e[i]=~e[i]>>>0}neg_bignum(e,t){this.not_bignum(e,t),this.inc_bignum(e,t)}get_mulword(e,t){let i=((((65535&(65535^e[t-1]))*this.glob1_hi_inv_lo+65536>>>1)+((65535^e[t-2])*this.glob1_hi_inv_hi+this.glob1_hi_inv_hi>>>1)+1>>>16)+((65535&(65535^e[t-1]))*this.glob1_hi_inv_hi>>>1)+((65535^e[t])*this.glob1_hi_inv_lo>>>1)+1>>>14)+this.glob1_hi_inv_hi*(65535^e[t])*2>>>this.glob1_hi_bitlen>>>0;return 65535<i&&(i=65535),65535&i}dec_bignum(e,t){let i=0;for(;--e[i]>>>0==4294967295&&0<--t;)i++}calc_a_bignum(e,t,s,r){let a;var n=this.glob1,o=this.glob2;if(this.mul_bignum(this.glob2,t,s,r),this.glob2[2*r]=0,(s=2*this.len_bignum(this.glob2,2*r+1))>=this.glob1_len_x2){this.inc_bignum(this.glob2,2*r+1),this.neg_bignum(this.glob2,2*r+1),a=1+s-this.glob1_len_x2;let e=new Uint16Array(o.buffer),t=a,i=1+s;for(;0!==a;a--){i--;var h=this.get_mulword(e,i);t--;var l=e.subarray(t);0<h&&(this.mul_bignum_word(l,this.glob1,h,2*r),0==(32768&e[i])&&0!==this.sub_bignum_word(l,l,new Uint16Array(n.buffer),0,2*r)&&e[i]--)}this.neg_bignum(this.glob2,r),this.dec_bignum(this.glob2,r)}this.mov_bignum(e,this.glob2,r)}clear_tmp_vars(e){this.init_bignum(this.glob1,0,e),this.init_bignum(this.glob2,0,e),this.init_bignum(this.glob1_hi_inv,0,4),this.init_bignum(this.glob1_hi,0,4),this.glob1_bitlen=0,this.glob1_hi_bitlen=0,this.glob1_len_x2=0,this.glob1_hi_inv_lo=0,this.glob1_hi_inv_hi=0}calc_a_key(e,t,i,s,r){var a,n=new Uint32Array(64);let o,h,l=0;for(this.init_bignum(e,1,r),a=this.len_bignum(s,r),this.init_two_dw(s,a),o=this.bitlen_bignum(i,a)<<24>>24,s=((o+31)/32|0)>>>0,h=1<<(o-1)%32>>>1,l+=s-1,o--,this.mov_bignum(e,t,a);-1!=--o;)0===h&&(h=2147483648,l--),this.calc_a_bignum(n,e,e,a),0!=(i[l]&h)?this.calc_a_bignum(e,n,t,a):this.mov_bignum(e,n,a),h>>>=1;this.init_bignum(n,0,a),this.clear_tmp_vars(r)}memcpy(e,t,i){let s=0;for(;0!=i--;)e[s]=t[s],s++}process_predata(e,t,i){var s=new Uint32Array(64),r=new Uint32Array(64);let a=0,n=0;for(var o=(this.pubkey.len-1)/8|0;1+o<=t;)this.init_bignum(s,0,64),this.memcpy(new Uint8Array(s.buffer),e.subarray(a),1+o),this.calc_a_key(r,s,this.pubkey.key2,this.pubkey.key1,64),this.memcpy(i.subarray(n),new Uint8Array(r.buffer),o),t-=1+o,a+=1+o,n+=o}decryptKey(e){this.init_pubkey();let t=new Uint8Array(256);return this.process_predata(e,this.len_predata(),t),t.subarray(0,56)}}class oe{constructor(e=4294967295){this.polynomal=e,this.crc=e}static calculateCrc(i,e=4294967295){let s=e;for(let e=0,t=i.length;e<t;e++)s=(s>>>8^this.lookUp[255&s^i[e]])>>>0;return s=(s^e)>>>0,s}append(i){for(let e=0,t=i.length;e<t;e++)this.crc=(this.crc>>>8^oe.lookUp[255&this.crc^i[e]])>>>0}get(){return(this.crc^this.polynomal)>>>0}}oe.lookUp=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);class he{constructor(e,t,i){this.hash=e,this.offset=t,this.length=i}static hashFilename(t){var i=(t=t.toUpperCase()).length,s=i>>2;if(0!=(3&i)){t+=String.fromCharCode(i-(s<<2));let e=3-(3&i);for(;0!=e--;)t+=t[s<<2]}return oe.calculateCrc(D(t))}}he.size=12,(r=C=C||{})[r.Checksum=65536]="Checksum",r[r.Encrypted=131072]="Encrypted";class le{constructor(e){this.stream=e,this.headerStart=84,this.index=new Map,this.parseHeader()}parseHeader(){var e=this.stream.readUint32(),t=0==(e&~(C.Checksum|C.Encrypted));if(t){if(0!=(e&C.Encrypted))return void(this.dataStart=this.parseRaHeader())}else this.stream.seek(0);this.dataStart=this.parseTdHeader(this.stream)}parseRaHeader(){const e=this.stream;var t=e.readUint8Array(80),i=(new ne).decryptKey(t),s=e.readUint32Array(2);const r=new ie(i);let a=new b(r.decrypt(s));t=a.readUint16();a.readUint32(),e.position=this.headerStart;i=6+t*he.size,t=(3+i)/4|0,s=e.readUint32Array(t+t%2);a=new b(r.decrypt(s));i=this.headerStart+i+(1+(~i>>>0)&7);return this.parseTdHeader(a),i}parseTdHeader(t){var i=t.readUint16();t.readUint32();for(let e=0;e<i;e++){var s=new he(t.readUint32(),t.readUint32(),t.readUint32());this.index.set(s.hash,s)}return t.position}containsFile(e){return this.index.has(he.hashFilename(e))}openFile(e){var t=this.index.get(he.hashFilename(e));if(!t)throw new Error(`File "${e}" not found`);return i.factory(this.stream,e,this.dataStart+t.offset,t.length)}}class ce extends Error{constructor(){super(...arguments),this.name="FileNotFoundError"}}class ue{constructor(){this.entries=new Map}addFile(e){this.entries.set(e.filename,e)}containsFile(e){return this.entries.has(e)}openFile(e){if(!this.containsFile(e))throw new Error(`File "${e}" not found`);return this.entries.get(e)}}class de{constructor(e,t){this.rfs=e,this.logger=t,this.allArchives=new Map,this.archivesByPriority=[]}fileExists(e){for(const t of this.archivesByPriority)if(t.containsFile(e))return!0;return!1}openFile(e){for(const t of this.archivesByPriority)if(t.containsFile(e))return t.openFile(e);throw new ce(`File "${e}" not found in VFS`)}addArchive(e,t){this.allArchives.has(t)||(this.allArchives.set(t,e),this.archivesByPriority.push(e)),this.logger.info(`Added archive "${t}" to VFS`)}hasArchive(e){return this.allArchives.has(e)}removeArchive(e){var t=this.allArchives.get(e);t&&(this.allArchives.delete(e),this.archivesByPriority.splice(this.archivesByPriority.indexOf(t),1),this.logger.info(`Removed archive "${e}" from VFS`))}listArchives(){return[...this.allArchives.keys()]}async addMixFile(e){await this.addArchiveByFilename(e,e=>new le(e.stream))}async addBagFile(e){const i=await this.openFileWithRfs(e.replace(".bag",".idx"));await this.addArchiveByFilename(e,e=>{var t=new ee(i.stream);return(new K).fromVirtualFile(e,t)})}async addArchiveByFilename(e,t){var i;this.allArchives.has(e)||(i=await this.openFileWithRfs(e))&&this.addArchive(t(i),e)}async openFileWithRfs(e){let t;try{t=await this.rfs.openFile(e)}catch(e){if(!(e instanceof ce))throw e}if(!t){if(!this.fileExists(e))throw new ce(`File "${e}" not found`);t=this.openFile(e)}return t}async loadImplicitMixFiles(e){this.logger.info("Initializing implicit mix files..."),e===At.YurisRevenge&&await this.addMixFile("langmd.mix"),await this.addMixFile("language.mix"),e===At.YurisRevenge&&await this.addMixFile("ra2md.mix"),await this.addMixFile("ra2.mix"),e===At.YurisRevenge&&await this.addMixFile("cachemd.mix"),await this.addMixFile("cache.mix"),e===At.YurisRevenge&&await this.addMixFile("loadmd.mix"),await this.addMixFile("load.mix"),e===At.YurisRevenge&&await this.addMixFile("localmd.mix"),await this.addMixFile("local.mix"),e===At.YurisRevenge&&await this.addMixFile("ntrlmd.mix"),await this.addMixFile("neutral.mix"),e===At.YurisRevenge&&await this.addMixFile("audiomd.mix"),await this.addMixFile("audio.mix"),await this.addBagFile("audio.bag"),await this.addMixFile("conquer.mix"),e===At.YurisRevenge&&(await this.addMixFile("conqmd.mix"),await this.addMixFile("genermd.mix")),await this.addMixFile("generic.mix"),e===At.YurisRevenge&&await this.addMixFile("isogenmd.mix"),await this.addMixFile("isogen.mix"),e===At.YurisRevenge&&await this.addMixFile("cameomd.mix"),await this.addMixFile("cameo.mix"),e===At.YurisRevenge&&await this.addMixFile("multimd.mix"),await this.addMixFile("multi.mix")}async loadExtraMixFiles(i){let s=new Set;for await(var e of this.rfs.getEntries())s.add(e.toLowerCase());for(var r of["ecache","expand","elocal"])for(let t=99;0<=t;t--){let e=[`${r}${N(t,"00")}.mix`];i===At.YurisRevenge&&e.push(`${r}md${N(t,"00")}.mix`);for(var a of e)s.has(a)&&await this.addMixFile(a)}let t=[".mmx"];i===At.YurisRevenge&&t.push(".yro");for(const n of t)for(const o of s)o.endsWith(n)&&this.addArchive(new le((await this.rfs.openFile(o)).stream),o)}async loadStandaloneFiles(e){let i=["ini","csf"],s=new Set(e?.exclude),r=[];for await(var a of this.rfs.getEntries()){let t=a.toLowerCase();i.some(e=>t.endsWith("."+e))&&!s.has(t)&&r.push(await this.rfs.openFile(a,!0))}if(r.length){let e=new ue;for(var t of r)e.addFile(t);this.addArchive(e,"mem.archive")}}}class pe extends Error{constructor(e){super("Storage quota exceeded",e),this.name="StorageQuotaError"}}class ge extends l{constructor(){super(...arguments),this.name="NameNotAllowedError"}}class me{constructor(e,t=!1){this.handle=e,this.caseSensitive=t}get name(){return this.handle.name}async*getEntries(){try{for await(var e of this.handle.keys())yield e}catch(e){if("NotFoundError"===e.name)throw new ce(`Directory "${this.handle.name}" not found`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${this.handle.name}" could not be read (${e.name})`,{cause:e});throw e}}async listEntries(){let e=[];for await(var t of this.getEntries())e.push(t);return e}async*getFileHandles(){try{for await(const e of this.handle.values())"file"===e.kind&&(yield e)}catch(e){if("NotFoundError"===e.name)throw new ce(`Directory "${this.handle.name}" not found`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${this.handle.name}" could not be read (${e.name})`,{cause:e});throw e}}async*getRawFiles(){for await(const e of this.getFileHandles())yield await e.getFile()}async containsEntry(e){return void 0!==await this.resolveEntryName(e)}async resolveEntryName(e){if(this.caseSensitive)return(await this.handle.getFileHandle(e).catch(()=>this.handle.getDirectoryHandle(e)).catch(()=>{}))?.name;for await(const t of this.getEntries())if(M(t,e))return t}async fixEntryCase(e){if(!this.caseSensitive)for await(var t of this.getEntries())if(M(t,e)){e=t;break}return e}async getRawFile(t,e=!1,i){let s;try{var r=e?t:await this.fixEntryCase(t);s=await this.handle.getFileHandle(r)}catch(e){if("NotFoundError"===e.name)throw new ce(`File "${t}" not found in directory "${this.handle.name}"`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new ge(`File name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`File "${t}" could not be read (${e.name})`,{cause:e});throw e}t=await s.getFile();return i?new File([t],t.name,{type:i}):t}async openFile(e,t=!1){t=await this.getRawFile(e,t);return i.fromRealFile(t)}async writeFile(i,s){s=s??(i instanceof File?i.name:i.filename);try{var r=await this.fixEntryCase(s);await this.deleteFile(r,!0);let e=await this.handle.getFileHandle(r,{create:!0}),t=await e.createWritable();try{await t.write(i instanceof File?i:new Uint8Array(i.stream.buffer,i.stream.byteOffset,i.stream.byteLength)),await t.close()}catch(e){throw await t.abort(),e}}catch(e){if("QuotaExceededError"===e.name)throw new pe({cause:e});if("NotFoundError"===e.name)throw new ce(`Directory "${this.handle.name}" not found`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new ge(`File name "${s}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`File "${s}" could not be written (${e.name})`,{cause:e});throw e}}async deleteFile(t,i=!1){t=i?t:await this.resolveEntryName(t);if(t)try{await this.handle.removeEntry(t)}catch(e){if(i&&"NotFoundError"===e.name)return;if("QuotaExceededError"===e.name)throw new pe({cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new ge(`File name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`File "${t}" could not be deleted (${e.name})`,{cause:e});throw e}}async getDirectory(t,e=this.caseSensitive){var i=e?t:await this.fixEntryCase(t);let s;try{s=await this.handle.getDirectoryHandle(i)}catch(e){if("NotFoundError"===e.name)throw new ce(`Directory "${t}" not found or parent directory "${this.handle.name}" is gone`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new ge(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be read (${e.name})`,{cause:e});throw e}return new me(s,e)}async getOrCreateDirectory(t,e=this.caseSensitive){var i=e?t:await this.fixEntryCase(t);try{return new me(await this.handle.getDirectoryHandle(i,{create:!0}),e)}catch(e){if("QuotaExceededError"===e.name)throw new pe({cause:e});if("NotFoundError"===e.name)throw new ce(`Directory "${this.handle.name}" not found"`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new ge(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be created (${e.name})`,{cause:e});throw e}}async deleteDirectory(t,e=!1){t=await this.resolveEntryName(t);if(t)try{await this.handle.removeEntry(t,{recursive:e})}catch(e){if("QuotaExceededError"===e.name)throw new pe({cause:e});if("InvalidModificationError"===e.name)throw new l("Can't delete non-empty directory when recursive = false");if(e instanceof TypeError&&e.message.includes("not allowed"))throw new ge(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be deleted (${e.name})`,{cause:e});throw e}}}class fe{constructor(){this.directories=[]}addRootDirectoryHandle(e){this.rootDirectory=this.addDirectoryHandle(e),this.rootDirectoryHandle=e}getRootDirectoryHandle(){return this.rootDirectoryHandle}addDirectoryHandle(e){e=new me(e);return this.directories.push(e),e}addDirectory(e){this.directories.push(e)}async getDirectory(e){var t=await this.findDirectory(e);if(!t)throw new Error(`Directory "${e}" not found in real file system`);return t}async findDirectory(e){for(const t of this.directories)if(await t.containsEntry(e))return await t.getDirectory(e)}getRootDirectory(){return this.rootDirectory}async containsEntry(e){for(const t of this.directories)if(await t.containsEntry(e))return!0;return!1}async openFile(e,t=!1){for(const i of this.directories)try{return await i.openFile(e,t)}catch(e){if(!(e instanceof ce))throw e}throw new ce(`File "${e}" not found in real file system`)}async getRawFile(e){for(const t of this.directories)if(await t.containsEntry(e))return await t.getRawFile(e);throw new Error(`File "${e}" not found in real file system`)}async*getEntries(){for(var e of this.directories)for await(var t of e.getEntries())yield t}}class ye{constructor(e){this.resourceFactory=e,this.resources=new Map}setVfs(e){this.vfs=e}set(e,t){this.resources.set(e,t)}has(e){return!!this.resources.has(e)||(this.vfs?.fileExists(e)??!1)}get(e){let t;return t=this.resources.get(e),!t&&this.vfs?.fileExists(e)&&(t=this.resourceFactory(this.vfs.openFile(e)),this.resources.set(e,t)),t}clear(e){e?this.resources.delete(e):this.resources.clear()}}const we="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Te(s,e,r,t){if(-1<["32f","64"].indexOf(e)&&-1<["32f","64"].indexOf(t))r.set(s);else{ke(e),ke(t);let i=function(e,t){let i=function(e){return e};e!=t&&(i=["32f","64"].includes(e)?ve:["32f","64"].includes(t)?Se:be);return i}(e,t);var a={oldMin:Math.pow(2,parseInt(e,10))/2,newMin:Math.pow(2,parseInt(t,10))/2,oldMax:Math.pow(2,parseInt(e,10))/2-1,newMax:Math.pow(2,parseInt(t,10))/2-1};Oe(e,s,!0);for(let e=0,t=s.length;e<t;e++)r[e]=i(s[e],a);Oe(t,r,!1)}}function be(e,t){return e=0<e?parseInt(e/t.oldMax*t.newMax,10):parseInt(e/t.oldMin*t.newMin,10)}function ve(e,t){return parseInt(0<e?e*t.newMax:e*t.newMin,10)}function Se(e,t){return 0<e?e/t.oldMax:e/t.oldMin}function ke(e){if("32f"!=e&&"64"!=e&&(parseInt(e,10)<"8"||"53"<parseInt(e,10)))throw new Error("Invalid bit depth.")}function Oe(e,i,t){if("8"==e){var s=t?-128:128;for(let e=0,t=i.length;e<t;e++)i[e]=i[e]+=s}}const _e=[-1,-1,-1,-1,2,4,6,8,-1,-1,-1,-1,2,4,6,8],Ie=[7,8,9,10,11,12,13,14,16,17,19,21,23,25,28,31,34,37,41,45,50,55,60,66,73,80,88,97,107,118,130,143,157,173,190,209,230,253,279,307,337,371,408,449,494,544,598,658,724,796,876,963,1060,1166,1282,1411,1552,1707,1878,2066,2272,2499,2749,3024,3327,3660,4026,4428,4871,5358,5894,6484,7132,7845,8630,9493,10442,11487,12635,13899,15289,16818,18500,20350,22385,24623,27086,29794,32767];function Ce(i){var s={index:0,predicted:0,step:7};let r=new Uint8Array(i.length),a=[],n=0,o=0;for(let e=0,t=i.length;e<t;e++)e%505==0&&0!=e&&(r.set(function(i,s){let r=function(e,t){Be(e,t);let i=[];return i.push(255&e),i.push(e>>8&255),i.push(t.index),i.push(0),i}(i[0],s);for(let e=3,t=i.length;e<t;e+=2){var a=Be(i[e],s),n=Be(i[e+1],s);r.push(n<<4|a)}return r}(a,s),n),n+=256,a=[],o++),a.push(i[e]);let e=i.length/2;return e%2&&e++,r.slice(0,e+512+4*o)}function Ae(t,e=256){var i={index:0,predicted:0,step:7};let s=new Int16Array(2*t.length),r=[],a=0,n=t.length,o=0;for(;0<n;){var h=Math.min(n,e);for(let e=0;e<h;e++)r.push(t[o]),o++;var l=function(i,s){s.predicted=function(e){return 32767<e?e-65536:e}(i[1]<<8|i[0]),s.index=i[2],s.step=Ie[s.index];let r=[s.predicted];for(let e=4,t=i.length;e<t;e++){var a=i[e],n=a>>4,a=n<<4^a;r.push(xe(a,s)),r.push(xe(n,s))}return r}(r,i);s.set(l,a),a+=l.length,r=[],n-=e}return s.slice(0,a)}function Be(e,t){let i=e-t.predicted,s=0;0<=i?s=0:(s=8,i=-i);let r=Ie[t.index],a=r>>3;return i>r&&(s|=4,i-=r,a+=r),r>>=1,i>r&&(s|=2,i-=r,a+=r),r>>=1,i>r&&(s|=1,a+=r),function(e,t,i){8&e?i.predicted-=t:i.predicted+=t;i.predicted<-32768?i.predicted=-32768:32767<i.predicted&&(i.predicted=32767);i.index+=_e[7&e],i.index<0?i.index=0:88<i.index&&(i.index=88)}(s,a,t),s}function xe(e,t){let i=0;return 4&e&&(i+=t.step),2&e&&(i+=t.step>>1),1&e&&(i+=t.step>>2),i+=t.step>>3,8&e&&(i=-i),t.predicted+=i,32767<t.predicted?t.predicted=32767:t.predicted<-32768&&(t.predicted=-32768),function(e,t){t.index+=_e[e],t.index<0?t.index=0:88<t.index&&(t.index=88);t.step=Ie[t.index]}(e,t),t.predicted}const Ee=[1,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7];function Pe(i){let s=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=function(e){let t;var i,s=~(e=-32768==e?-32767:e)>>8&128;return s||(e*=-1),32635<e&&(e=32635),t=256<=e?(i=Ee[e>>8&127])<<4|e>>i+3&15:e>>4,85^t^s}(i[e]);return s}function Ne(i){let s=new Int16Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=function(e){let t=0;0!=(128&(e^=85))&&(e&=-129,t=-1);var i=4+((240&e)>>4);let s=0;return s=4!=i?1<<i|(15&e)<<i-4|1<<i-5:e<<1|1,s=0===t?s:-s,8*s*-1}(i[e]);return s}const Me=132,De=32635,Re=[0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],Le=[0,132,396,924,1980,4092,8316,16764];function Fe(i){let s=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=(r=i[e],a=void 0,0!=(a=r>>8&128)&&(r=-r),(r+=Me)>De&&(r=De),~(a|(a=Re[r>>7&255])<<4|r>>a+3&15));var r,a;return s}function je(i){let s=new Int16Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=function(e){var t,i;let s;return t=128&(e=~e),i=e>>4&7,e=15&e,s=Le[i]+(e<<3+i),0!=t&&(s=-s),s}(i[e]);return s}function Ue(t,i,s=0,r=t.length){for(let e=s;e<r;e+=i)!function(t,i,s){i--;for(let e=0;e<i;e++){var r=t[s+e];t[s+e]=t[s+i],t[s+i]=r,i--}}(t,i,e)}function We(e,i,s=0){let r=0;for(var t=e.length;r<t;){var a=e.codePointAt(r);if(a<128)i[s]=a,s++;else{let e=0,t=0;for(a<=2047?(e=1,t=192):a<=65535?(e=2,t=224):a<=1114111&&(e=3,t=240,r++),i[s]=(a>>6*e)+t,s++;0<e;)i[s]=128|a>>6*(e-1)&63,s++,e--}r++}return s}const ze=new Array(8).fill(0).map((e,t)=>Math.pow(2,8*t));class Ve{constructor(e,t=!1){this.bits=e,this.offset=Math.ceil(e/8),this.max=Math.pow(2,e)-1,this.min=0,this.unpack=this.unpack_,t&&(this.max=Math.pow(2,e)/2-1,this.min=-this.max-1,this.unpack=this.unpackSigned_)}pack(i,s,r=0){s=this.clamp_(Math.round(s));for(let e=0,t=this.offset;e<t;e++)i[r]=255&Math.floor(s/ze[e]),r++;return r}unpack_(t,i=0){let s=0;for(let e=0;e<this.offset;e++)s+=t[i+e]*ze[e];return s}unpackSigned_(e,t=0){return this.sign_(this.unpack_(e,t))}clamp_(e){return e>this.max?this.max:e<this.min?this.min:e}sign_(e){return e>this.max&&(e-=2*this.max+2),e}}class He{constructor(e,t){this.offset=Math.ceil((e+t)/8),this.ebits=e,this.fbits=t,this.bias=(1<<e-1)-1,this.biasP2=Math.pow(2,this.bias+1),this.ebitsFbits=e+t,this.fbias=Math.pow(2,-(8*this.offset-1-e))}pack(e,t,i){var s=((t=+(t=Math.abs(t)>this.biasP2-2*this.ebitsFbits?t<0?-1/0:1/0:t))||1/t)<0||t<0?1:0;t=Math.abs(t);let r=Math.min(Math.floor(Math.log(t)/Math.LN2),1023),a=Ge(t/Math.pow(2,r)*Math.pow(2,this.fbits));return t!=t?(a=Math.pow(2,this.fbits-1),r=(1<<this.ebits)-1):0!==t&&(t>=Math.pow(2,1-this.bias)?(2<=a/Math.pow(2,this.fbits)&&(r+=1,a=1),a=r>this.bias?(r=(1<<this.ebits)-1,0):(r+=this.bias,Ge(a)-Math.pow(2,this.fbits))):(a=Ge(t/Math.pow(2,1-this.bias-this.fbits)),r=0)),this.packFloatBits_(e,i,s,r,a)}unpack(t,i){var e=(1<<this.ebits)-1;let s,r="";for(let e=this.offset-1;0<=e;e--){var a=t[e+i].toString(2);r+="00000000".substring(a.length)+a}var n="1"==r.charAt(0)?-1:1;r=r.substring(1);let o=parseInt(r.substring(0,this.ebits),2);return r=r.substring(this.ebits),o==e?0!==parseInt(r,2)?NaN:1/0*n:(s=0===o?(o+=1,parseInt(r,2)):parseInt("1"+r,2),n*s*this.fbias*Math.pow(2,o-this.bias))}packFloatBits_(e,t,i,s,r){let a=[];a.push(i);for(let e=this.ebits;0<e;--e)a[e]=s%2?1:0,s=Math.floor(s/2);var n=a.length;for(let e=this.fbits;0<e;--e)a[n+e]=r%2?1:0,r=Math.floor(r/2);let o=a.join(""),h=this.offset+t-1,l=t;for(;h>=t;)e[h]=parseInt(o.substring(0,8),2),o=o.substring(8),h--,l++;return l}}function Ge(e){var t=Math.floor(e),e=e-t;return!(e<.5)&&(.5<e||t%2)?t+1:t}function $e(e,t=0,i=e.length){return function(o,e=0,t=o.length){let h="";for(let n=e;n<t;){let i=128,s=191,r=!1,a=o[n++];if(0<=a&&a<=127)h+=String.fromCharCode(a);else{let t=0;194<=a&&a<=223?t=1:224<=a&&a<=239?(t=2,224===o[n]&&(i=160),237===o[n]&&(s=159)):240<=a&&a<=244?(t=3,240===o[n]&&(i=144),244===o[n]&&(s=143)):r=!0,a&=(1<<8-t-1)-1;for(let e=0;e<t;e++)(o[n]<i||o[n]>s)&&(r=!0),a=a<<6|63&o[n],n++;r?h+=String.fromCharCode(65533):a<=65535?h+=String.fromCharCode(a):(a-=65536,h+=String.fromCharCode(55296+(a>>10&1023),56320+(1023&a)))}}return h}(e,t,i)}function qe(e){var t=[];return We(e,t),t}function Xe(e,t,i=0){return We(e,t,i)}function Ze(e,t,i,s=0){let r=tt((t=t||{}).bits,t.fp,t.signed);var a=Math.ceil(t.bits/8);let n=0;for(var o=s,h=e.length;n<h;n++)s=r.pack(i,e[n],s);return t.be&&Ue(i,a,o,s),s}function Qe(e,t,i,s=0,r=e.length){var a,n=tt((t=t||{}).bits,t.fp,t.signed);r=function(e,t,i){i=(t-e)%i;return t-i}(s,r,n.offset),t.be?(a=new Uint8Array(e),t.be&&Ue(a,n.offset,s,r),et(a,i,s,r,n)):et(e,i,s,r,n)}function Ye(e,t,i,s=0){return Ze([e],t,i,s)}function Ke(e,t){var i=[];return Ye(e,t,i,0),i}function Je(e,t,i=0){var s=[];return Qe(e,t,s,i,i+Math.ceil(t.bits/8)),s[0]}function et(i,s,r,a,n){var o=n.offset;for(let e=0,t=r;t<a;t+=o,e++)s[e]=n.unpack(i,t)}function tt(e,t,i){return t&&32==e?new He(8,23):t&&64==e?new He(11,52):new Ve(e,i)}function it(e,t){let i=qe(e);for(let e=i.length;e<t;e++)i.push(0);return i}(class Vm extends class{constructor(){this.container="",this.chunkSize=0,this.format="",this.signature=null,this.head=0,this.uInt32={bits:32,be:!1},this.supported_containers=["RIFF","RIFX"]}setSignature(e){if(this.head=0,this.container=this.readString(e,4),-1===this.supported_containers.indexOf(this.container))throw Error("Not a supported format.");this.uInt32.be="RIFX"===this.container,this.chunkSize=this.readUInt32(e),this.format=this.readString(e,4),this.signature={chunkId:this.container,chunkSize:this.chunkSize,format:this.format,subChunks:this.getSubChunksIndex_(e)}}findChunk(t,i=!1){var s=this.signature.subChunks;let r=[];for(let e=0;e<s.length;e++)if(s[e].chunkId==t){if(!i)return s[e];r.push(s[e])}return"LIST"==t&&r.length?r:null}readString(e,t){e=$e(e,this.head,this.head+t);return this.head+=t,e}readUInt32(e){return e=Je(e,this.uInt32,this.head),this.head+=4,e}getSubChunksIndex_(e){let t=[],i=this.head;for(;i<=e.length-8;)t.push(this.getSubChunkIndex_(e,i)),i+=8+t[t.length-1].chunkSize,i=i%2?i+1:i;return t}getSubChunkIndex_(e,t){let i={chunkId:this.getChunkId_(e,t),chunkSize:this.getChunkSize_(e,t)};return"LIST"==i.chunkId?(i.format=$e(e,t+8,t+12),this.head+=4,i.subChunks=this.getSubChunksIndex_(e)):(e=i.chunkSize%2?i.chunkSize+1:i.chunkSize,this.head=t+8+e,i.chunkData={start:t+8,end:this.head}),i}getChunkId_(e,t){return this.head+=4,$e(e,t,t+4)}getChunkSize_(e,t){return this.head+=4,Je(e,this.uInt32,t+4)}}{constructor(){super(),this.supported_containers.push("RF64"),this.fmt={chunkId:"",chunkSize:0,audioFormat:0,numChannels:0,sampleRate:0,byteRate:0,blockAlign:0,bitsPerSample:0,cbSize:0,validBitsPerSample:0,dwChannelMask:0,subformat:[]},this.fact={chunkId:"",chunkSize:0,dwSampleLength:0},this.cue={chunkId:"",chunkSize:0,dwCuePoints:0,points:[]},this.smpl={chunkId:"",chunkSize:0,dwManufacturer:0,dwProduct:0,dwSamplePeriod:0,dwMIDIUnityNote:0,dwMIDIPitchFraction:0,dwSMPTEFormat:0,dwSMPTEOffset:0,dwNumSampleLoops:0,dwSamplerData:0,loops:[]},this.bext={chunkId:"",chunkSize:0,description:"",originator:"",originatorReference:"",originationDate:"",originationTime:"",timeReference:[0,0],version:0,UMID:"",loudnessValue:0,loudnessRange:0,maxTruePeakLevel:0,maxMomentaryLoudness:0,maxShortTermLoudness:0,reserved:"",codingHistory:""},this.iXML={chunkId:"",chunkSize:0,value:""},this.ds64={chunkId:"",chunkSize:0,riffSizeHigh:0,riffSizeLow:0,dataSizeHigh:0,dataSizeLow:0,originationTime:0,sampleCountHigh:0,sampleCountLow:0},this.data={chunkId:"",chunkSize:0,samples:new Uint8Array(0)},this.LIST=[],this.junk={chunkId:"",chunkSize:0,chunkData:[]},this._PMX={chunkId:"",chunkSize:0,value:""},this.uInt16={bits:16,be:!1,signed:!1,fp:!1}}fromBuffer(e,t=!0){if(this.clearHeaders(),this.setSignature(e),this.uInt16.be=this.uInt32.be,"WAVE"!=this.format)throw Error('Could not find the "WAVE" format identifier');this.readDs64Chunk_(e),this.readFmtChunk_(e),this.readFactChunk_(e),this.readBextChunk_(e),this.readiXMLChunk_(e),this.readCueChunk_(e),this.readSmplChunk_(e),this.readDataChunk_(e,t),this.readJunkChunk_(e),this.readLISTChunk_(e),this.read_PMXChunk_(e)}clearHeaders(){var e=new Vm;Object.assign(this.fmt,e.fmt),Object.assign(this.fact,e.fact),Object.assign(this.cue,e.cue),Object.assign(this.smpl,e.smpl),Object.assign(this.bext,e.bext),Object.assign(this.iXML,e.iXML),Object.assign(this.ds64,e.ds64),Object.assign(this.data,e.data),this.LIST=[],Object.assign(this.junk,e.junk),Object.assign(this._PMX,e._PMX)}readFmtChunk_(e){var t=this.findChunk("fmt ");if(!t)throw Error('Could not find the "fmt " chunk');this.head=t.chunkData.start,this.fmt.chunkId=t.chunkId,this.fmt.chunkSize=t.chunkSize,this.fmt.audioFormat=this.readUInt16_(e),this.fmt.numChannels=this.readUInt16_(e),this.fmt.sampleRate=this.readUInt32(e),this.fmt.byteRate=this.readUInt32(e),this.fmt.blockAlign=this.readUInt16_(e),this.fmt.bitsPerSample=this.readUInt16_(e),this.readFmtExtension_(e)}readFmtExtension_(e){16<this.fmt.chunkSize&&(this.fmt.cbSize=this.readUInt16_(e),18<this.fmt.chunkSize&&(this.fmt.validBitsPerSample=this.readUInt16_(e),20<this.fmt.chunkSize&&(this.fmt.dwChannelMask=this.readUInt32(e),this.fmt.subformat=[this.readUInt32(e),this.readUInt32(e),this.readUInt32(e),this.readUInt32(e)])))}readFactChunk_(e){var t=this.findChunk("fact");t&&(this.head=t.chunkData.start,this.fact.chunkId=t.chunkId,this.fact.chunkSize=t.chunkSize,this.fact.dwSampleLength=this.readUInt32(e))}readCueChunk_(t){var e=this.findChunk("cue ");if(e){this.head=e.chunkData.start,this.cue.chunkId=e.chunkId,this.cue.chunkSize=e.chunkSize,this.cue.dwCuePoints=this.readUInt32(t);for(let e=0;e<this.cue.dwCuePoints;e++)this.cue.points.push({dwName:this.readUInt32(t),dwPosition:this.readUInt32(t),fccChunk:this.readString(t,4),dwChunkStart:this.readUInt32(t),dwBlockStart:this.readUInt32(t),dwSampleOffset:this.readUInt32(t)})}}readSmplChunk_(t){var e=this.findChunk("smpl");if(e){this.head=e.chunkData.start,this.smpl.chunkId=e.chunkId,this.smpl.chunkSize=e.chunkSize,this.smpl.dwManufacturer=this.readUInt32(t),this.smpl.dwProduct=this.readUInt32(t),this.smpl.dwSamplePeriod=this.readUInt32(t),this.smpl.dwMIDIUnityNote=this.readUInt32(t),this.smpl.dwMIDIPitchFraction=this.readUInt32(t),this.smpl.dwSMPTEFormat=this.readUInt32(t),this.smpl.dwSMPTEOffset=this.readUInt32(t),this.smpl.dwNumSampleLoops=this.readUInt32(t),this.smpl.dwSamplerData=this.readUInt32(t);for(let e=0;e<this.smpl.dwNumSampleLoops;e++)this.smpl.loops.push({dwName:this.readUInt32(t),dwType:this.readUInt32(t),dwStart:this.readUInt32(t),dwEnd:this.readUInt32(t),dwFraction:this.readUInt32(t),dwPlayCount:this.readUInt32(t)})}}readDataChunk_(e,t){var i=this.findChunk("data");if(!i)throw Error('Could not find the "data" chunk');this.data.chunkId="data",this.data.chunkSize=i.chunkSize,t&&(this.data.samples=e.slice(i.chunkData.start,i.chunkData.end))}readBextChunk_(e){var t=this.findChunk("bext");t&&(this.head=t.chunkData.start,this.bext.chunkId=t.chunkId,this.bext.chunkSize=t.chunkSize,this.bext.description=this.readString(e,256),this.bext.originator=this.readString(e,32),this.bext.originatorReference=this.readString(e,32),this.bext.originationDate=this.readString(e,10),this.bext.originationTime=this.readString(e,8),this.bext.timeReference=[this.readUInt32(e),this.readUInt32(e)],this.bext.version=this.readUInt16_(e),this.bext.UMID=this.readString(e,64),this.bext.loudnessValue=this.readUInt16_(e),this.bext.loudnessRange=this.readUInt16_(e),this.bext.maxTruePeakLevel=this.readUInt16_(e),this.bext.maxMomentaryLoudness=this.readUInt16_(e),this.bext.maxShortTermLoudness=this.readUInt16_(e),this.bext.reserved=this.readString(e,180),this.bext.codingHistory=this.readString(e,this.bext.chunkSize-602))}readiXMLChunk_(e){var t=this.findChunk("iXML");t&&(this.head=t.chunkData.start,this.iXML.chunkId=t.chunkId,this.iXML.chunkSize=t.chunkSize,this.iXML.value=$e(e,this.head,this.head+this.iXML.chunkSize))}readDs64Chunk_(e){var t=this.findChunk("ds64");if(t)this.head=t.chunkData.start,this.ds64.chunkId=t.chunkId,this.ds64.chunkSize=t.chunkSize,this.ds64.riffSizeHigh=this.readUInt32(e),this.ds64.riffSizeLow=this.readUInt32(e),this.ds64.dataSizeHigh=this.readUInt32(e),this.ds64.dataSizeLow=this.readUInt32(e),this.ds64.originationTime=this.readUInt32(e),this.ds64.sampleCountHigh=this.readUInt32(e),this.ds64.sampleCountLow=this.readUInt32(e);else if("RF64"==this.container)throw Error('Could not find the "ds64" chunk')}readLISTChunk_(t){var i=this.findChunk("LIST",!0);if(null!==i)for(let e=0;e<i.length;e++){var s=i[e];this.LIST.push({chunkId:s.chunkId,chunkSize:s.chunkSize,format:s.format,subChunks:[]});for(let e=0;e<s.subChunks.length;e++)this.readLISTSubChunks_(s.subChunks[e],s.format,t)}}readLISTSubChunks_(e,t,i){"adtl"==t?-1<["labl","note","ltxt"].indexOf(e.chunkId)&&this.readLISTadtlSubChunks_(i,e):"INFO"==t&&this.readLISTINFOSubChunks_(i,e)}readLISTadtlSubChunks_(e,t){this.head=t.chunkData.start;let i={chunkId:t.chunkId,chunkSize:t.chunkSize,dwName:this.readUInt32(e)};"ltxt"==t.chunkId?(i.dwSampleLength=this.readUInt32(e),i.dwPurposeID=this.readUInt32(e),i.dwCountry=this.readUInt16_(e),i.dwLanguage=this.readUInt16_(e),i.dwDialect=this.readUInt16_(e),i.dwCodePage=this.readUInt16_(e),i.value=""):i.value=this.readZSTR_(e,this.head),this.LIST[this.LIST.length-1].subChunks.push(i)}readLISTINFOSubChunks_(e,t){this.head=t.chunkData.start,this.LIST[this.LIST.length-1].subChunks.push({chunkId:t.chunkId,chunkSize:t.chunkSize,value:this.readZSTR_(e,this.head)})}readJunkChunk_(e){var t=this.findChunk("junk");t&&(this.junk={chunkId:t.chunkId,chunkSize:t.chunkSize,chunkData:[].slice.call(e.slice(t.chunkData.start,t.chunkData.end))})}read_PMXChunk_(e){var t=this.findChunk("_PMX");t&&(this.head=t.chunkData.start,this._PMX.chunkId=t.chunkId,this._PMX.chunkSize=t.chunkSize,this._PMX.value=$e(e,this.head,this.head+this._PMX.chunkSize))}readZSTR_(t,i=0){for(let e=i;e<t.length&&(this.head++,0!==t[e]);e++);return $e(t,i,this.head-1)}readUInt16_(e){return e=Je(e,this.uInt16,this.head),this.head+=2,e}});function st(e,t,i){return!(i<1||4294967295<e*(t/8)*i)}class rt extends class extends class Vm extends class{constructor(){this.container="",this.chunkSize=0,this.format="",this.signature=null,this.head=0,this.uInt32={bits:32,be:!1},this.supported_containers=["RIFF","RIFX"]}setSignature(e){if(this.head=0,this.container=this.readString(e,4),-1===this.supported_containers.indexOf(this.container))throw Error("Not a supported format.");this.uInt32.be="RIFX"===this.container,this.chunkSize=this.readUInt32(e),this.format=this.readString(e,4),this.signature={chunkId:this.container,chunkSize:this.chunkSize,format:this.format,subChunks:this.getSubChunksIndex_(e)}}findChunk(t,i=!1){var s=this.signature.subChunks;let r=[];for(let e=0;e<s.length;e++)if(s[e].chunkId==t){if(!i)return s[e];r.push(s[e])}return"LIST"==t&&r.length?r:null}readString(e,t){e=$e(e,this.head,this.head+t);return this.head+=t,e}readUInt32(e){return e=Je(e,this.uInt32,this.head),this.head+=4,e}getSubChunksIndex_(e){let t=[],i=this.head;for(;i<=e.length-8;)t.push(this.getSubChunkIndex_(e,i)),i+=8+t[t.length-1].chunkSize,i=i%2?i+1:i;return t}getSubChunkIndex_(e,t){let i={chunkId:this.getChunkId_(e,t),chunkSize:this.getChunkSize_(e,t)};return"LIST"==i.chunkId?(i.format=$e(e,t+8,t+12),this.head+=4,i.subChunks=this.getSubChunksIndex_(e)):(e=i.chunkSize%2?i.chunkSize+1:i.chunkSize,this.head=t+8+e,i.chunkData={start:t+8,end:this.head}),i}getChunkId_(e,t){return this.head+=4,$e(e,t,t+4)}getChunkSize_(e,t){return this.head+=4,Je(e,this.uInt32,t+4)}}{constructor(){super(),this.supported_containers.push("RF64"),this.fmt={chunkId:"",chunkSize:0,audioFormat:0,numChannels:0,sampleRate:0,byteRate:0,blockAlign:0,bitsPerSample:0,cbSize:0,validBitsPerSample:0,dwChannelMask:0,subformat:[]},this.fact={chunkId:"",chunkSize:0,dwSampleLength:0},this.cue={chunkId:"",chunkSize:0,dwCuePoints:0,points:[]},this.smpl={chunkId:"",chunkSize:0,dwManufacturer:0,dwProduct:0,dwSamplePeriod:0,dwMIDIUnityNote:0,dwMIDIPitchFraction:0,dwSMPTEFormat:0,dwSMPTEOffset:0,dwNumSampleLoops:0,dwSamplerData:0,loops:[]},this.bext={chunkId:"",chunkSize:0,description:"",originator:"",originatorReference:"",originationDate:"",originationTime:"",timeReference:[0,0],version:0,UMID:"",loudnessValue:0,loudnessRange:0,maxTruePeakLevel:0,maxMomentaryLoudness:0,maxShortTermLoudness:0,reserved:"",codingHistory:""},this.iXML={chunkId:"",chunkSize:0,value:""},this.ds64={chunkId:"",chunkSize:0,riffSizeHigh:0,riffSizeLow:0,dataSizeHigh:0,dataSizeLow:0,originationTime:0,sampleCountHigh:0,sampleCountLow:0},this.data={chunkId:"",chunkSize:0,samples:new Uint8Array(0)},this.LIST=[],this.junk={chunkId:"",chunkSize:0,chunkData:[]},this._PMX={chunkId:"",chunkSize:0,value:""},this.uInt16={bits:16,be:!1,signed:!1,fp:!1}}fromBuffer(e,t=!0){if(this.clearHeaders(),this.setSignature(e),this.uInt16.be=this.uInt32.be,"WAVE"!=this.format)throw Error('Could not find the "WAVE" format identifier');this.readDs64Chunk_(e),this.readFmtChunk_(e),this.readFactChunk_(e),this.readBextChunk_(e),this.readiXMLChunk_(e),this.readCueChunk_(e),this.readSmplChunk_(e),this.readDataChunk_(e,t),this.readJunkChunk_(e),this.readLISTChunk_(e),this.read_PMXChunk_(e)}clearHeaders(){var e=new Vm;Object.assign(this.fmt,e.fmt),Object.assign(this.fact,e.fact),Object.assign(this.cue,e.cue),Object.assign(this.smpl,e.smpl),Object.assign(this.bext,e.bext),Object.assign(this.iXML,e.iXML),Object.assign(this.ds64,e.ds64),Object.assign(this.data,e.data),this.LIST=[],Object.assign(this.junk,e.junk),Object.assign(this._PMX,e._PMX)}readFmtChunk_(e){var t=this.findChunk("fmt ");if(!t)throw Error('Could not find the "fmt " chunk');this.head=t.chunkData.start,this.fmt.chunkId=t.chunkId,this.fmt.chunkSize=t.chunkSize,this.fmt.audioFormat=this.readUInt16_(e),this.fmt.numChannels=this.readUInt16_(e),this.fmt.sampleRate=this.readUInt32(e),this.fmt.byteRate=this.readUInt32(e),this.fmt.blockAlign=this.readUInt16_(e),this.fmt.bitsPerSample=this.readUInt16_(e),this.readFmtExtension_(e)}readFmtExtension_(e){16<this.fmt.chunkSize&&(this.fmt.cbSize=this.readUInt16_(e),18<this.fmt.chunkSize&&(this.fmt.validBitsPerSample=this.readUInt16_(e),20<this.fmt.chunkSize&&(this.fmt.dwChannelMask=this.readUInt32(e),this.fmt.subformat=[this.readUInt32(e),this.readUInt32(e),this.readUInt32(e),this.readUInt32(e)])))}readFactChunk_(e){var t=this.findChunk("fact");t&&(this.head=t.chunkData.start,this.fact.chunkId=t.chunkId,this.fact.chunkSize=t.chunkSize,this.fact.dwSampleLength=this.readUInt32(e))}readCueChunk_(t){var e=this.findChunk("cue ");if(e){this.head=e.chunkData.start,this.cue.chunkId=e.chunkId,this.cue.chunkSize=e.chunkSize,this.cue.dwCuePoints=this.readUInt32(t);for(let e=0;e<this.cue.dwCuePoints;e++)this.cue.points.push({dwName:this.readUInt32(t),dwPosition:this.readUInt32(t),fccChunk:this.readString(t,4),dwChunkStart:this.readUInt32(t),dwBlockStart:this.readUInt32(t),dwSampleOffset:this.readUInt32(t)})}}readSmplChunk_(t){var e=this.findChunk("smpl");if(e){this.head=e.chunkData.start,this.smpl.chunkId=e.chunkId,this.smpl.chunkSize=e.chunkSize,this.smpl.dwManufacturer=this.readUInt32(t),this.smpl.dwProduct=this.readUInt32(t),this.smpl.dwSamplePeriod=this.readUInt32(t),this.smpl.dwMIDIUnityNote=this.readUInt32(t),this.smpl.dwMIDIPitchFraction=this.readUInt32(t),this.smpl.dwSMPTEFormat=this.readUInt32(t),this.smpl.dwSMPTEOffset=this.readUInt32(t),this.smpl.dwNumSampleLoops=this.readUInt32(t),this.smpl.dwSamplerData=this.readUInt32(t);for(let e=0;e<this.smpl.dwNumSampleLoops;e++)this.smpl.loops.push({dwName:this.readUInt32(t),dwType:this.readUInt32(t),dwStart:this.readUInt32(t),dwEnd:this.readUInt32(t),dwFraction:this.readUInt32(t),dwPlayCount:this.readUInt32(t)})}}readDataChunk_(e,t){var i=this.findChunk("data");if(!i)throw Error('Could not find the "data" chunk');this.data.chunkId="data",this.data.chunkSize=i.chunkSize,t&&(this.data.samples=e.slice(i.chunkData.start,i.chunkData.end))}readBextChunk_(e){var t=this.findChunk("bext");t&&(this.head=t.chunkData.start,this.bext.chunkId=t.chunkId,this.bext.chunkSize=t.chunkSize,this.bext.description=this.readString(e,256),this.bext.originator=this.readString(e,32),this.bext.originatorReference=this.readString(e,32),this.bext.originationDate=this.readString(e,10),this.bext.originationTime=this.readString(e,8),this.bext.timeReference=[this.readUInt32(e),this.readUInt32(e)],this.bext.version=this.readUInt16_(e),this.bext.UMID=this.readString(e,64),this.bext.loudnessValue=this.readUInt16_(e),this.bext.loudnessRange=this.readUInt16_(e),this.bext.maxTruePeakLevel=this.readUInt16_(e),this.bext.maxMomentaryLoudness=this.readUInt16_(e),this.bext.maxShortTermLoudness=this.readUInt16_(e),this.bext.reserved=this.readString(e,180),this.bext.codingHistory=this.readString(e,this.bext.chunkSize-602))}readiXMLChunk_(e){var t=this.findChunk("iXML");t&&(this.head=t.chunkData.start,this.iXML.chunkId=t.chunkId,this.iXML.chunkSize=t.chunkSize,this.iXML.value=$e(e,this.head,this.head+this.iXML.chunkSize))}readDs64Chunk_(e){var t=this.findChunk("ds64");if(t)this.head=t.chunkData.start,this.ds64.chunkId=t.chunkId,this.ds64.chunkSize=t.chunkSize,this.ds64.riffSizeHigh=this.readUInt32(e),this.ds64.riffSizeLow=this.readUInt32(e),this.ds64.dataSizeHigh=this.readUInt32(e),this.ds64.dataSizeLow=this.readUInt32(e),this.ds64.originationTime=this.readUInt32(e),this.ds64.sampleCountHigh=this.readUInt32(e),this.ds64.sampleCountLow=this.readUInt32(e);else if("RF64"==this.container)throw Error('Could not find the "ds64" chunk')}readLISTChunk_(t){var i=this.findChunk("LIST",!0);if(null!==i)for(let e=0;e<i.length;e++){var s=i[e];this.LIST.push({chunkId:s.chunkId,chunkSize:s.chunkSize,format:s.format,subChunks:[]});for(let e=0;e<s.subChunks.length;e++)this.readLISTSubChunks_(s.subChunks[e],s.format,t)}}readLISTSubChunks_(e,t,i){"adtl"==t?-1<["labl","note","ltxt"].indexOf(e.chunkId)&&this.readLISTadtlSubChunks_(i,e):"INFO"==t&&this.readLISTINFOSubChunks_(i,e)}readLISTadtlSubChunks_(e,t){this.head=t.chunkData.start;let i={chunkId:t.chunkId,chunkSize:t.chunkSize,dwName:this.readUInt32(e)};"ltxt"==t.chunkId?(i.dwSampleLength=this.readUInt32(e),i.dwPurposeID=this.readUInt32(e),i.dwCountry=this.readUInt16_(e),i.dwLanguage=this.readUInt16_(e),i.dwDialect=this.readUInt16_(e),i.dwCodePage=this.readUInt16_(e),i.value=""):i.value=this.readZSTR_(e,this.head),this.LIST[this.LIST.length-1].subChunks.push(i)}readLISTINFOSubChunks_(e,t){this.head=t.chunkData.start,this.LIST[this.LIST.length-1].subChunks.push({chunkId:t.chunkId,chunkSize:t.chunkSize,value:this.readZSTR_(e,this.head)})}readJunkChunk_(e){var t=this.findChunk("junk");t&&(this.junk={chunkId:t.chunkId,chunkSize:t.chunkSize,chunkData:[].slice.call(e.slice(t.chunkData.start,t.chunkData.end))})}read_PMXChunk_(e){var t=this.findChunk("_PMX");t&&(this.head=t.chunkData.start,this._PMX.chunkId=t.chunkId,this._PMX.chunkSize=t.chunkSize,this._PMX.value=$e(e,this.head,this.head+this._PMX.chunkSize))}readZSTR_(t,i=0){for(let e=i;e<t.length&&(this.head++,0!==t[e]);e++);return $e(t,i,this.head-1)}readUInt16_(e){return e=Je(e,this.uInt16,this.head),this.head+=2,e}}{toBuffer(){this.uInt16.be="RIFX"===this.container,this.uInt32.be=this.uInt16.be;var t=[this.getJunkBytes_(),this.getDs64Bytes_(),this.getBextBytes_(),this.getiXMLBytes_(),this.getFmtBytes_(),this.getFactBytes_(),qe(this.data.chunkId),Ke(this.data.samples.length,this.uInt32),this.data.samples,this.getCueBytes_(),this.getSmplBytes_(),this.getLISTBytes_(),this.get_PMXBytes_()];let i=0;for(let e=0;e<t.length;e++)i+=t[e].length;let s=new Uint8Array(i+12),r=0;r=Xe(this.container,s,r),r=Ye(i+4,this.uInt32,s,r),r=Xe(this.format,s,r);for(let e=0;e<t.length;e++)s.set(t[e],r),r+=t[e].length;return s}getBextBytes_(){let e=[];return this.enforceBext_(),this.bext.chunkId&&(this.bext.chunkSize=602+this.bext.codingHistory.length,e=e.concat(qe(this.bext.chunkId),Ke(602+this.bext.codingHistory.length,this.uInt32),it(this.bext.description,256),it(this.bext.originator,32),it(this.bext.originatorReference,32),it(this.bext.originationDate,10),it(this.bext.originationTime,8),Ke(this.bext.timeReference[0],this.uInt32),Ke(this.bext.timeReference[1],this.uInt32),Ke(this.bext.version,this.uInt16),it(this.bext.UMID,64),Ke(this.bext.loudnessValue,this.uInt16),Ke(this.bext.loudnessRange,this.uInt16),Ke(this.bext.maxTruePeakLevel,this.uInt16),Ke(this.bext.maxMomentaryLoudness,this.uInt16),Ke(this.bext.maxShortTermLoudness,this.uInt16),it(this.bext.reserved,180),it(this.bext.codingHistory,this.bext.codingHistory.length))),this.enforceByteLen_(e),e}enforceBext_(){for(var e in this.bext)if(this.bext.hasOwnProperty(e)&&this.bext[e]&&"timeReference"!=e){this.bext.chunkId="bext";break}(this.bext.timeReference[0]||this.bext.timeReference[1])&&(this.bext.chunkId="bext")}getiXMLBytes_(){let e=[];var t;return this.iXML.chunkId&&(t=qe(this.iXML.value),this.iXML.chunkSize=t.length,e=e.concat(qe(this.iXML.chunkId),Ke(this.iXML.chunkSize,this.uInt32),t)),this.enforceByteLen_(e),e}getDs64Bytes_(){let e=[];return this.ds64.chunkId&&(e=e.concat(qe(this.ds64.chunkId),Ke(this.ds64.chunkSize,this.uInt32),Ke(this.ds64.riffSizeHigh,this.uInt32),Ke(this.ds64.riffSizeLow,this.uInt32),Ke(this.ds64.dataSizeHigh,this.uInt32),Ke(this.ds64.dataSizeLow,this.uInt32),Ke(this.ds64.originationTime,this.uInt32),Ke(this.ds64.sampleCountHigh,this.uInt32),Ke(this.ds64.sampleCountLow,this.uInt32))),this.enforceByteLen_(e),e}getCueBytes_(){let e=[];var t;return this.cue.chunkId&&(t=this.getCuePointsBytes_(),e=e.concat(qe(this.cue.chunkId),Ke(t.length+4,this.uInt32),Ke(this.cue.dwCuePoints,this.uInt32),t)),this.enforceByteLen_(e),e}getCuePointsBytes_(){let t=[];for(let e=0;e<this.cue.dwCuePoints;e++)t=t.concat(Ke(this.cue.points[e].dwName,this.uInt32),Ke(this.cue.points[e].dwPosition,this.uInt32),qe(this.cue.points[e].fccChunk),Ke(this.cue.points[e].dwChunkStart,this.uInt32),Ke(this.cue.points[e].dwBlockStart,this.uInt32),Ke(this.cue.points[e].dwSampleOffset,this.uInt32));return t}getSmplBytes_(){let e=[];var t;return this.smpl.chunkId&&(t=this.getSmplLoopsBytes_(),e=e.concat(qe(this.smpl.chunkId),Ke(t.length+36,this.uInt32),Ke(this.smpl.dwManufacturer,this.uInt32),Ke(this.smpl.dwProduct,this.uInt32),Ke(this.smpl.dwSamplePeriod,this.uInt32),Ke(this.smpl.dwMIDIUnityNote,this.uInt32),Ke(this.smpl.dwMIDIPitchFraction,this.uInt32),Ke(this.smpl.dwSMPTEFormat,this.uInt32),Ke(this.smpl.dwSMPTEOffset,this.uInt32),Ke(this.smpl.dwNumSampleLoops,this.uInt32),Ke(this.smpl.dwSamplerData,this.uInt32),t)),this.enforceByteLen_(e),e}getSmplLoopsBytes_(){let t=[];for(let e=0;e<this.smpl.dwNumSampleLoops;e++)t=t.concat(Ke(this.smpl.loops[e].dwName,this.uInt32),Ke(this.smpl.loops[e].dwType,this.uInt32),Ke(this.smpl.loops[e].dwStart,this.uInt32),Ke(this.smpl.loops[e].dwEnd,this.uInt32),Ke(this.smpl.loops[e].dwFraction,this.uInt32),Ke(this.smpl.loops[e].dwPlayCount,this.uInt32));return t}getFactBytes_(){let e=[];return this.fact.chunkId&&(e=e.concat(qe(this.fact.chunkId),Ke(this.fact.chunkSize,this.uInt32),Ke(this.fact.dwSampleLength,this.uInt32))),this.enforceByteLen_(e),e}getFmtBytes_(){if(this.fmt.chunkId){var e=[].concat(qe(this.fmt.chunkId),Ke(this.fmt.chunkSize,this.uInt32),Ke(this.fmt.audioFormat,this.uInt16),Ke(this.fmt.numChannels,this.uInt16),Ke(this.fmt.sampleRate,this.uInt32),Ke(this.fmt.byteRate,this.uInt32),Ke(this.fmt.blockAlign,this.uInt16),Ke(this.fmt.bitsPerSample,this.uInt16),this.getFmtExtensionBytes_());return this.enforceByteLen_(e),e}throw Error('Could not find the "fmt " chunk')}getFmtExtensionBytes_(){let e=[];return 16<this.fmt.chunkSize&&(e=e.concat(Ke(this.fmt.cbSize,this.uInt16))),18<this.fmt.chunkSize&&(e=e.concat(Ke(this.fmt.validBitsPerSample,this.uInt16))),20<this.fmt.chunkSize&&(e=e.concat(Ke(this.fmt.dwChannelMask,this.uInt32))),24<this.fmt.chunkSize&&(e=e.concat(Ke(this.fmt.subformat[0],this.uInt32),Ke(this.fmt.subformat[1],this.uInt32),Ke(this.fmt.subformat[2],this.uInt32),Ke(this.fmt.subformat[3],this.uInt32))),e}getLISTBytes_(){let t=[];for(let e=0;e<this.LIST.length;e++){var i=this.getLISTSubChunksBytes_(this.LIST[e].subChunks,this.LIST[e].format);t=t.concat(qe(this.LIST[e].chunkId),Ke(i.length+4,this.uInt32),qe(this.LIST[e].format),i)}return this.enforceByteLen_(t),t}getLISTSubChunksBytes_(i,s){let r=[];for(let e=0,t=i.length;e<t;e++)"INFO"==s?r=r.concat(this.getLISTINFOSubChunksBytes_(i[e])):"adtl"==s&&(r=r.concat(this.getLISTadtlSubChunksBytes_(i[e]))),this.enforceByteLen_(r);return r}getLISTINFOSubChunksBytes_(e){let t=[];var i=it(e.value,e.value.length);return t=t.concat(qe(e.chunkId),Ke(i.length+1,this.uInt32),i),t.push(0),t}getLISTadtlSubChunksBytes_(e){let t=[];var i;return-1<["labl","note"].indexOf(e.chunkId)?(i=it(e.value,e.value.length),t=t.concat(qe(e.chunkId),Ke(i.length+4+1,this.uInt32),Ke(e.dwName,this.uInt32),i),t.push(0)):"ltxt"==e.chunkId&&(t=t.concat(this.getLtxtChunkBytes_(e))),t}getLtxtChunkBytes_(e){return[].concat(qe(e.chunkId),Ke(e.value.length+20,this.uInt32),Ke(e.dwName,this.uInt32),Ke(e.dwSampleLength,this.uInt32),Ke(e.dwPurposeID,this.uInt32),Ke(e.dwCountry,this.uInt16),Ke(e.dwLanguage,this.uInt16),Ke(e.dwDialect,this.uInt16),Ke(e.dwCodePage,this.uInt16),it(e.value,e.value.length))}get_PMXBytes_(){let e=[];var t;return this._PMX.chunkId&&(t=qe(this._PMX.value),this._PMX.chunkSize=t.length,e=e.concat(qe(this._PMX.chunkId),Ke(this._PMX.chunkSize,this.uInt32),t)),this.enforceByteLen_(e),e}getJunkBytes_(){let e=[];return this.junk.chunkId?e.concat(qe(this.junk.chunkId),Ke(this.junk.chunkData.length,this.uInt32),this.junk.chunkData):(this.enforceByteLen_(e),e)}enforceByteLen_(e){e.length%2&&e.push(0)}}{constructor(){super(),this.bitDepth="0",this.dataType={bits:0,be:!1},this.WAV_AUDIO_FORMATS={4:17,8:1,"8a":6,"8m":7,16:1,24:1,32:1,"32f":3,64:3}}fromScratch(e,t,i,s,r){r=r||{},this.clearHeaders(),this.newWavFile_(e,t,i,s,r)}fromBuffer(e,t=!0){super.fromBuffer(e,t),this.bitDepthFromFmt_(),this.updateDataType_()}toBuffer(){return this.validateWavHeader_(),super.toBuffer()}getSamples(e=!1,t=Float64Array){var i=new t(this.data.samples.length/(this.dataType.bits/8));return Qe(this.data.samples,this.dataType,i,0,this.data.samples.length),!e&&1<this.fmt.numChannels?function(s,r,t=Float64Array){let a=[];for(let e=0;e<r;e++)a[e]=new t(s.length/r);for(let i=0;i<r;i++)for(let e=i,t=0;e<s.length;e+=r,t++)a[i][t]=s[e];return a}(i,this.fmt.numChannels,t):i}getSample(e){if((e*=this.dataType.bits/8)+this.dataType.bits/8>this.data.samples.length)throw new Error("Range error");return Je(this.data.samples.slice(e,e+this.dataType.bits/8),this.dataType)}setSample(e,t){if((e*=this.dataType.bits/8)+this.dataType.bits/8>this.data.samples.length)throw new Error("Range error");Ye(t,this.dataType,this.data.samples,e)}getiXML(){return this.iXML.value}setiXML(e){if("string"!=typeof e)throw new TypeError("iXML value must be a string.");this.iXML.value=e,this.iXML.chunkId="iXML"}get_PMX(){return this._PMX.value}set_PMX(e){if("string"!=typeof e)throw new TypeError("_PMX value must be a string.");this._PMX.value=e,this._PMX.chunkId="_PMX"}newWavFile_(e,t,i,s,r){r.container||(r.container="RIFF"),this.container=r.container,this.bitDepth=i,s=function(r){let a=[];if(0<r.length)if(r[0].constructor!==Number){a=new Float64Array(r[0].length*r.length);for(let i=0,e=r[0].length,s=0;i<e;i++)for(let e=0,t=r.length;e<t;e++,s++)a[s]=r[e][i]}else a=r;return a}(s),this.updateDataType_();var a=this.dataType.bits/8;this.data.samples=new Uint8Array(s.length*a),Ze(s,this.dataType,this.data.samples,0),this.makeWavHeader_(i,e,t,a,this.data.samples.length,r),this.data.chunkId="data",this.data.chunkSize=this.data.samples.length,this.validateWavHeader_()}makeWavHeader_(e,t,i,s,r,a){"4"==e?this.createADPCMHeader_(e,t,i,s,r,a):"8a"==e||"8m"==e?this.createALawMulawHeader_(e,t,i,s,r,a):-1==Object.keys(this.WAV_AUDIO_FORMATS).indexOf(e)||2<t?this.createExtensibleHeader_(e,t,i,s,r,a):this.createPCMHeader_(e,t,i,s,r,a)}createPCMHeader_(e,t,i,s,r,a){this.container=a.container,this.chunkSize=36+r,this.format="WAVE",this.bitDepth=e,this.fmt={chunkId:"fmt ",chunkSize:16,audioFormat:this.WAV_AUDIO_FORMATS[e]||65534,numChannels:t,sampleRate:i,byteRate:t*s*i,blockAlign:t*s,bitsPerSample:parseInt(e,10),cbSize:0,validBitsPerSample:0,dwChannelMask:0,subformat:[]}}createADPCMHeader_(e,t,i,s,r,a){this.createPCMHeader_(e,t,i,s,r,a),this.chunkSize=40+r,this.fmt.chunkSize=20,this.fmt.byteRate=4055,this.fmt.blockAlign=256,this.fmt.bitsPerSample=4,this.fmt.cbSize=2,this.fmt.validBitsPerSample=505,this.fact={chunkId:"fact",chunkSize:4,dwSampleLength:2*r}}createExtensibleHeader_(e,t,i,s,r,a){this.createPCMHeader_(e,t,i,s,r,a),this.chunkSize=60+r,this.fmt.chunkSize=40,this.fmt.bitsPerSample=1+(parseInt(e,10)-1|7),this.fmt.cbSize=22,this.fmt.validBitsPerSample=parseInt(e,10),this.fmt.dwChannelMask=function(e){let t=0;1===e?t=4:2===e?t=3:4===e?t=51:6===e?t=63:8===e&&(t=1599);return t}(t),this.fmt.subformat=[1,1048576,2852126848,1905997824]}createALawMulawHeader_(e,t,i,s,r,a){this.createPCMHeader_(e,t,i,s,r,a),this.chunkSize=40+r,this.fmt.chunkSize=20,this.fmt.cbSize=2,this.fmt.validBitsPerSample=8,this.fact={chunkId:"fact",chunkSize:4,dwSampleLength:r}}bitDepthFromFmt_(){3===this.fmt.audioFormat&&32===this.fmt.bitsPerSample?this.bitDepth="32f":6===this.fmt.audioFormat?this.bitDepth="8a":7===this.fmt.audioFormat?this.bitDepth="8m":this.bitDepth=this.fmt.bitsPerSample.toString()}validateBitDepth_(){if(this.WAV_AUDIO_FORMATS[this.bitDepth])return!0;if(8<parseInt(this.bitDepth,10)&&parseInt(this.bitDepth,10)<54)return!0;throw new Error("Invalid bit depth.")}updateDataType_(){this.dataType={bits:1+(parseInt(this.bitDepth,10)-1|7),fp:"32f"==this.bitDepth||"64"==this.bitDepth,signed:"8"!=this.bitDepth,be:"RIFX"==this.container},-1<["4","8a","8m"].indexOf(this.bitDepth)&&(this.dataType.bits=8,this.dataType.signed=!1)}validateWavHeader_(){if(this.validateBitDepth_(),e=this.fmt.numChannels,t=this.fmt.bitsPerSample,e<1||65535<e*t/8)throw new Error("Invalid number of channels.");var e,t;if(!st(this.fmt.numChannels,this.fmt.bitsPerSample,this.fmt.sampleRate))throw new Error("Invalid sample rate.")}}class at extends rt{getTag(e){e=this.getTagIndex_(e);return null!==e.TAG?this.LIST[e.LIST].subChunks[e.TAG].value:null}setTag(e,t){e=function(i){{if(i.constructor!==String)throw new Error("Invalid tag name.");if(i.length<4)for(let e=0,t=4-i.length;e<t;e++)i+=" "}return i}(e);var i=this.getTagIndex_(e);null!==i.TAG?(this.LIST[i.LIST].subChunks[i.TAG].chunkSize=t.length+1,this.LIST[i.LIST].subChunks[i.TAG].value=t):null!==i.LIST?this.LIST[i.LIST].subChunks.push({chunkId:e,chunkSize:t.length+1,value:t}):(this.LIST.push({chunkId:"LIST",chunkSize:8+t.length+1,format:"INFO",subChunks:[]}),this.LIST[this.LIST.length-1].subChunks.push({chunkId:e,chunkSize:t.length+1,value:t}))}deleteTag(e){e=this.getTagIndex_(e);return null!==e.TAG&&(this.LIST[e.LIST].subChunks.splice(e.TAG,1),!0)}listTags(){var i=this.getLISTIndex("INFO");let s={};if(null!==i)for(let e=0,t=this.LIST[i].subChunks.length;e<t;e++)s[this.LIST[i].subChunks[e].chunkId]=this.LIST[i].subChunks[e].value;return s}getLISTIndex(i){for(let e=0,t=this.LIST.length;e<t;e++)if(this.LIST[e].format==i)return e;return null}getTagIndex_(s){let r={LIST:null,TAG:null};for(let i=0,e=this.LIST.length;i<e;i++)if("INFO"==this.LIST[i].format){r.LIST=i;for(let e=0,t=this.LIST[i].subChunks.length;e<t;e++)if(this.LIST[i].subChunks[e].chunkId==s){r.TAG=e;break}break}return r}}class nt extends at{listCuePoints(){let i=this.getCuePoints_();for(let e=0,t=i.length;e<t;e++)i[e].position=i[e].dwSampleOffset/this.fmt.sampleRate*1e3,i[e].dwSampleLength?(i[e].end=i[e].dwSampleLength/this.fmt.sampleRate*1e3,i[e].end+=i[e].position):i[e].end=null,delete i[e].value;return i}setCuePoint(e){this.cue.chunkId="cue ",e.label||(e.label="");var t=this.getCuePoints_();this.clearLISTadtl_(),this.cue.points=[],e.dwSampleOffset=e.position*this.fmt.sampleRate/1e3,e.dwSampleLength=0,e.end&&(e.dwSampleLength=e.end*this.fmt.sampleRate/1e3-e.dwSampleOffset),0===t.length?this.setCuePoint_(e,1):this.setCuePointInOrder_(t,e),this.cue.dwCuePoints=this.cue.points.length}deleteCuePoint(t){this.cue.chunkId="cue ";var i=this.getCuePoints_();this.clearLISTadtl_();var s=this.cue.points.length;this.cue.points=[];for(let e=0;e<s;e++)e+1!==t&&this.setCuePoint_(i[e],e+1);this.cue.dwCuePoints=this.cue.points.length,this.cue.dwCuePoints?this.cue.chunkId="cue ":(this.cue.chunkId="",this.clearLISTadtl_())}updateLabel(i,s){var r=this.getLISTIndex("adtl");if(null!==r)for(let e=0,t=this.LIST[r].subChunks.length;e<t;e++)this.LIST[r].subChunks[e].dwName==i&&(this.LIST[r].subChunks[e].value=s)}getCuePoints_(){let i=[];for(let t=0;t<this.cue.points.length;t++){var s=this.cue.points[t];let e=this.getDataForCuePoint_(s.dwName);e.label=e.value||"",e.dwPosition=s.dwPosition,e.fccChunk=s.fccChunk,e.dwChunkStart=s.dwChunkStart,e.dwBlockStart=s.dwBlockStart,e.dwSampleOffset=s.dwSampleOffset,i.push(e)}return i}getDataForCuePoint_(e){var t=this.getLISTIndex("adtl"),i={};return null!==t&&this.getCueDataFromLIST_(i,t,e),i}getCueDataFromLIST_(i,s,r){for(let e=0,t=this.LIST[s].subChunks.length;e<t;e++){var a;this.LIST[s].subChunks[e].dwName==r&&(a=this.LIST[s].subChunks[e],i.value=a.value||i.value,i.dwName=a.dwName||0,i.dwSampleLength=a.dwSampleLength||0,i.dwPurposeID=a.dwPurposeID||0,i.dwCountry=a.dwCountry||0,i.dwLanguage=a.dwLanguage||0,i.dwDialect=a.dwDialect||0,i.dwCodePage=a.dwCodePage||0)}}setCuePoint_(e,t){this.cue.points.push({dwName:t,dwPosition:e.dwPosition||0,fccChunk:e.fccChunk||"data",dwChunkStart:e.dwChunkStart||0,dwBlockStart:e.dwBlockStart||0,dwSampleOffset:e.dwSampleOffset}),this.setLabl_(e,t)}setCuePointInOrder_(t,i){let s=!1;for(let e=0;e<t.length;e++)t[e].dwSampleOffset>i.dwSampleOffset&&!s?(this.setCuePoint_(i,e+1),this.setCuePoint_(t[e],e+2),s=!0):this.setCuePoint_(t[e],s?e+2:e+1);s||this.setCuePoint_(i,this.cue.points.length+1)}clearLISTadtl_(){for(let e=0,t=this.LIST.length;e<t;e++)"adtl"==this.LIST[e].format&&this.LIST.splice(e)}setLabl_(e,t){let i=this.getLISTIndex("adtl");null===i&&(this.LIST.push({chunkId:"LIST",chunkSize:4,format:"adtl",subChunks:[]}),i=this.LIST.length-1),this.setLabelText_(i,e,t),e.dwSampleLength&&this.setLtxtChunk_(i,e,t)}setLabelText_(e,t,i){this.LIST[e].subChunks.push({chunkId:"labl",chunkSize:4,dwName:i,value:t.label}),this.LIST[e].chunkSize+=12}setLtxtChunk_(e,t,i){this.LIST[e].subChunks.push({chunkId:"ltxt",chunkSize:20,dwName:i,dwSampleLength:t.dwSampleLength,dwPurposeID:t.dwPurposeID||0,dwCountry:t.dwCountry||0,dwLanguage:t.dwLanguage||0,dwDialect:t.dwDialect||0,dwCodePage:t.dwCodePage||0,value:t.label}),this.LIST[e].chunkSize+=28}}class ot{constructor(e,t,i){var s;this.length_=e,this.scaleFactor_=(e-1)/t,this.interpolate=this.sinc,"point"===i.method?this.interpolate=this.point:"linear"===i.method?this.interpolate=this.linear:"cubic"===i.method&&(this.interpolate=this.cubic),this.tangentFactor_=1-Math.max(0,Math.min(1,i.tension||0)),this.sincFilterSize_=i.sincFilterSize||1,this.kernel_=(s=i.sincWindow||ht,function(e){return(0!==(t=e)?Math.sin(Math.PI*t)/(Math.PI*t):1)*s(e);var t})}point(e,t){return this.getClippedInput_(Math.round(this.scaleFactor_*e),t)}linear(e,t){e=this.scaleFactor_*e;var i=Math.floor(e);return(1-(e-=i))*this.getClippedInput_(i,t)+e*this.getClippedInput_(i+1,t)}cubic(e,t){e=this.scaleFactor_*e;var i=Math.floor(e),s=[this.getTangent_(i,t),this.getTangent_(i+1,t)],r=[this.getClippedInput_(i,t),this.getClippedInput_(i+1,t)],t=(e-=i)*e,i=e*t;return(2*i-3*t+1)*r[0]+(i-2*t+e)*s[0]+(-2*i+3*t)*r[1]+(i-t)*s[1]}sinc(t,i){t=this.scaleFactor_*t;var e=Math.floor(t),s=e-this.sincFilterSize_+1,r=e+this.sincFilterSize_;let a=0;for(let e=s;e<=r;e++)a+=this.kernel_(t-e)*this.getClippedInput_(e,i);return a}getTangent_(e,t){return this.tangentFactor_*(this.getClippedInput_(e+1,t)-this.getClippedInput_(e-1,t))/2}getClippedInput_(e,t){return 0<=e&&e<this.length_?t[e]:0}}function ht(e){return Math.exp(-e/2*e/2)}const lt={point:!1,linear:!1,cubic:!0,sinc:!0},ct={IIR:16,FIR:71},ut={IIR:class{constructor(t,i,s){let r=[];for(let e=0;e<t;e++)r.push(this.getCoeffs_({Fs:i,Fc:s,Q:.5/Math.sin(Math.PI/(2*t)*(e+.5))}));this.stages=[];for(let e=0;e<r.length;e++)this.stages[e]={b0:r[e].b[0],b1:r[e].b[1],b2:r[e].b[2],a1:r[e].a[0],a2:r[e].a[1],k:r[e].k,z:[0,0]}}filter(e){let i=e;for(let e=0,t=this.stages.length;e<t;e++)i=this.runStage_(e,i);return i}getCoeffs_(e){let t={a:[],b:[]};e=this.preCalc_(e,t);return t.k=1,t.b.push((1-e.cw)/(2*e.a0)),t.b.push(2*t.b[0]),t.b.push(t.b[0]),t}preCalc_(e,t){let i={};var s=2*Math.PI*e.Fc/e.Fs;return i.alpha=Math.sin(s)/(2*e.Q),i.cw=Math.cos(s),i.a0=1+i.alpha,t.a0=i.a0,t.a.push(-2*i.cw/i.a0),t.k=1,t.a.push((1-i.alpha)/i.a0),i}runStage_(e,t){var i=t*this.stages[e].k-this.stages[e].a1*this.stages[e].z[0]-this.stages[e].a2*this.stages[e].z[1],t=this.stages[e].b0*i+this.stages[e].b1*this.stages[e].z[0]+this.stages[e].b2*this.stages[e].z[1];return this.stages[e].z[1]=this.stages[e].z[0],this.stages[e].z[0]=i,t}reset(){for(let e=0;e<this.stages.length;e++)this.stages[e].z=[0,0]}},FIR:class{constructor(t,e,i){var s=2*Math.PI*i/e;let r=0;this.filters=[];for(let e=0;e<=t;e++)e-t/2==0?this.filters[e]=s:(this.filters[e]=Math.sin(s*(e-t/2))/(e-t/2),this.filters[e]*=.54-.46*Math.cos(2*Math.PI*e/t)),r+=this.filters[e];for(let e=0;e<=t;e++)this.filters[e]/=r;this.z=this.initZ_()}filter(e){this.z.buf[this.z.pointer]=e;let i=0;for(let e=0,t=this.z.buf.length;e<t;e++)i+=this.filters[e]*this.z.buf[(this.z.pointer+e)%this.z.buf.length];return this.z.pointer=(this.z.pointer+1)%this.z.buf.length,i}reset(){this.z=this.initZ_()}initZ_(){let t=[];for(let e=0;e<this.filters.length-1;e++)t.push(0);return{buf:t,pointer:0}}}};function dt(e,t,i,s=null){s=s||{};var r=new Float64Array(e.length*((i-t)/t+1));s.method=s.method||"cubic";var a=new ot(e.length,r.length,{method:s.method,tension:s.tension||0,sincFilterSize:s.sincFilterSize||6,sincWindow:s.sincWindow||void 0,clip:s.clip||"mirror"});if(void 0===s.LPF&&(s.LPF=lt[s.method]),s.LPF){s.LPFType=s.LPFType||"IIR";const n=ut[s.LPFType];t<i?function(i,s,r,a){for(let e=0,t=s.length;e<t;e++)s[e]=a.filter(r.interpolate(e,i));a.reset();for(let e=s.length-1;0<=e;e--)s[e]=a.filter(s[e])}(e,r,a,new n(s.LPForder||ct[s.LPFType],i,t/2)):function(i,e,t,s){for(let e=0,t=i.length;e<t;e++)i[e]=s.filter(i[e]);s.reset();for(let e=i.length-1;0<=e;e--)i[e]=s.filter(i[e]);pt(i,e,t)}(e,r,a,new n(s.LPForder||ct[s.LPFType],t,i/2))}else pt(e,r,a);return r}function pt(i,s,r){for(let e=0,t=s.length;e<t;e++)s[e]=r.interpolate(e,i)}class gt extends nt{toRIFF(){var e=new Float64Array(mt(this.data.samples.length,this.dataType.bits/8));Qe(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,this.bitDepth,e,{container:"RIFF"})}toRIFX(){var e=new Float64Array(mt(this.data.samples.length,this.dataType.bits/8));Qe(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,this.bitDepth,e,{container:"RIFX"})}toIMAADPCM(){if(8e3!==this.fmt.sampleRate)throw new Error("Only 8000 Hz files can be compressed as IMA-ADPCM.");if(1!==this.fmt.numChannels)throw new Error("Only mono files can be compressed as IMA-ADPCM.");this.assure16Bit_();var e=new Int16Array(mt(this.data.samples.length,2));Qe(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"4",Ce(e),{container:this.correctContainer_()})}fromIMAADPCM(e="16"){let r;if(1<this.fmt.numChannels){if(2<this.fmt.numChannels)throw new Error("Only 1 or 2 channels are supported");var a=this.data.samples.length/2;let t=new Uint8Array(a),i=new Uint8Array(a),s=0;for(let e=0;e<a;e++)e&&e%4==0&&(s+=4),t[e]=this.data.samples[s+e],i[e]=this.data.samples[s+e+4];r=[Ae(t,this.fmt.blockAlign/2),Ae(i,this.fmt.blockAlign/2)]}else r=Ae(this.data.samples,this.fmt.blockAlign);this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",r,{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toALaw(){this.assure16Bit_();var e=new Int16Array(mt(this.data.samples.length,2));Qe(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"8a",Pe(e),{container:this.correctContainer_()})}fromALaw(e="16"){this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",Ne(this.data.samples),{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toMuLaw(){this.assure16Bit_();var e=new Int16Array(mt(this.data.samples.length,2));Qe(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"8m",Fe(e),{container:this.correctContainer_()})}fromMuLaw(e="16"){this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",je(this.data.samples),{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toBitDepth(e,t=!0){let i=e,s=this.bitDepth;t||("32f"!=e&&(i=this.dataType.bits.toString()),s=""+this.dataType.bits),this.assureUncompressed_();var r=this.getSamples(!0),t=new Float64Array(r.length);Te(r,s,t,i),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,e,t,{container:this.correctContainer_()})}toSampleRate(t,i){this.validateResample_(t);var s=this.getSamples();let r=[];if(s.constructor===Float64Array)r=dt(s,this.fmt.sampleRate,t,i);else for(let e=0;e<s.length;e++)r.push(dt(s[e],this.fmt.sampleRate,t,i));this.fromExisting_(this.fmt.numChannels,t,this.bitDepth,r,{container:this.correctContainer_()})}validateResample_(e){if(!st(this.fmt.numChannels,this.fmt.bitsPerSample,e))throw new Error("Invalid sample rate.");if(-1<["4","8a","8m"].indexOf(this.bitDepth))throw new Error("wavefile can't change the sample rate of compressed files.")}assure16Bit_(){this.assureUncompressed_(),"16"!=this.bitDepth&&this.toBitDepth("16")}assureUncompressed_(){"8a"==this.bitDepth?this.fromALaw():"8m"==this.bitDepth?this.fromMuLaw():"4"==this.bitDepth&&this.fromIMAADPCM()}correctContainer_(){return"RF64"==this.container?"RIFF":this.container}fromExisting_(e,t,i,s,r){var a=new nt;Object.assign(this.fmt,a.fmt),Object.assign(this.fact,a.fact),Object.assign(this.ds64,a.ds64),Object.assign(this.data,a.data),this.newWavFile_(e,t,i,s,r)}}function mt(e,t){let i=e/t;return i%2&&i++,i}class ft extends gt{constructor(e){super(),e&&this.fromBuffer(e)}fromBase64(e){this.fromBuffer(function(i){let s=new Uint8Array(256);for(let e=0;e<we.length;e++)s[we.charCodeAt(e)]=e;let e=.75*i.length;"="===i[i.length-1]&&(e--,"="===i[i.length-2]&&e--);let r=new Uint8Array(e);for(let e=0,t=0;e<i.length;e+=4){var a=s[i.charCodeAt(e)],n=s[i.charCodeAt(e+1)],o=s[i.charCodeAt(e+2)],h=s[i.charCodeAt(e+3)];r[t++]=a<<2|n>>4,r[t++]=(15&n)<<4|o>>2,r[t++]=(3&o)<<6|63&h}return r}(e))}toBase64(){return function(t){let i="";for(let e=0;e<t.length;e+=3)i+=we[t[e]>>2],i+=we[(3&t[e])<<4|t[e+1]>>4],i+=we[(15&t[e+1])<<2|t[e+2]>>6],i+=we[63&t[e+2]];return t.length%3==2?i=i.substring(0,i.length-1)+"=":t.length%3==1&&(i=i.substring(0,i.length-2)+"=="),i}(this.toBuffer())}toDataURI(){return"data:audio/wav;base64,"+this.toBase64()}fromDataURI(e){this.fromBase64(e.replace("data:audio/wav;base64,",""))}}class yt{constructor(e){e instanceof Uint8Array?this.fromRawData(e):e instanceof i&&this.fromVirtualFile(e)}fromRawData(e){return this.rawData=e,this}fromVirtualFile(e){e=e.stream;return this.rawData=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),this}getRawData(){return this.rawData}getData(){if(!this.decodedData){if(!this.rawData)throw new Error("No data loaded");this.decodedData=this.decodeData(this.rawData),this.rawData=void 0}return this.decodedData}setData(e){this.rawData=void 0,this.decodedData=e}decodeData(e){let t=new ft(e);return"4"===t.bitDepth&&t.fromIMAADPCM(),t.toBuffer()}isRawImaAdpcm(){return this.rawData&&"4"===new ft(this.rawData).bitDepth}}class wt{constructor(e,t=!0){this.resourceFactory=e,this.cache=t,this.resources=new Map}setDir(e){this.rfsDir=e}set(e,t){this.resources.set(e,t)}async has(e){return!!this.resources.has(e)||(await this.rfsDir?.containsEntry(e)??!1)}async get(e){let t;return t=this.resources.get(e),!t&&await this.rfsDir?.containsEntry(e)&&(t=await this.resourceFactory(await this.rfsDir.getRawFile(e)),this.cache&&this.resources.set(e,t)),t}clear(){this.resources.clear()}}class Tt{constructor(e){this.file=e}asFile(){return new File([this.file],this.file.name,{type:"audio/mp3"})}}const bt=(new Map).set("cameo.mix",["adogicon.shp","adoguico.shp","aengicon.shp","aenguico.shp","agapgen.shp","agisicon.shp","ahrvicon.shp","ahrvuico.shp","aparicon.shp","apchicon.shp","apcicon.shp","artyicon.shp","asaticon.shp","ayaricon.shp","batricon.shp","beagicon.shp","bggyicon.shp","bolticon.shp","brrkicon.shp","carricon.shp","ccomicon.shp","ccomuico.shp","chemicon.shp","chroicon.shp","clckicon.shp","clegicon.shp","cleguico.shp","clonicon.shp","cnsticon.shp","crryicon.shp","csphicon.shp","darken.shp","desoicon.shp","desouico.shp","desticon.shp","detnicon.shp","dlphicon.shp","dlphuico.shp","dogicon.shp","doguico.shp","dredicon.shp","dronicon.shp","e1icon.shp","e1uico.shp","e2icon.shp","e2uico.shp","e4icon.shp","empicon.shp","engnicon.shp","facticon.shp","falcicon.shp","fixicon.shp","flakicon.shp","flkticon.shp","flktuico.shp","forticon.shp","fsdicon.shp","fspicon.shp","fstdicon.shp","fvicon.shp","fvuico.shp","gapicon.shp","gat2icon.shp","gateicon.shp","gbayicon.shp","gcanicon.shp","giicon.shp","giuico.shp","gorep.shp","gtnkicon.shp","gtnkuico.shp","gwepicon.shp","handicon.shp","harvicon.shp","harvuico.shp","heliicon.shp","hindicon.shp","hmecicon.shp","hovricon.shp","htkicon.shp","htkuico.shp","htnkicon.shp","htnkuico.shp","ioncicon.shp","ircricon.shp","ironicon.shp","ivanicon.shp","ivanuico.shp","ivncicon.shp","ivncuico.shp","jjeticon.shp","jjetuico.shp","landicon.shp","lasricon.shp","liteicon.shp","lpsticon.shp","mcvicon.shp","mcvuico.shp","metricon.shp","mltiicon.shp","mmchicon.shp","msslicon.shp","mtnkicon.shp","mtnkuico.shp","mutcicon.shp","nga2icon.shp","ngaticon.shp","nhpdicon.shp","npsiicon.shp","npwricon.shp","nradicon.shp","nrcticon.shp","nreficon.shp","ntchicon.shp","nukeicon.shp","nwalicon.shp","nwepicon.shp","obliicon.shp","obmbicon.shp","orcaicon.shp","otrnicon.shp","paraicon.shp","pillicon.shp","plticon.shp","plugicon.shp","podsicon.shp","powricon.shp","prisicon.shp","proicon.shp","psicicon.shp","psicuico.shp","psisicon.shp","psiticon.shp","psituico.shp","rad1icon.shp","rad2icon.shp","rad3icon.shp","radricon.shp","rboticon.shp","reficon.shp","rfixicon.shp","rtnkicon.shp","rtnkuico.shp","samicon.shp","sapcicon.shp","sapicon.shp","sbagicon.shp","sealicon.shp","sealuico.shp","seekicon.shp","shadicon.shp","shaduico.shp","shkicon.shp","shkuico.shp","smchicon.shp","smcvicon.shp","smcvuico.shp","snipicon.shp","snipuico.shp","soniicon.shp","spoticon.shp","spyicon.shp","spyuico.shp","sqdicon.shp","sreficon.shp","srefuico.shp","stnkicon.shp","subicon.shp","subticon.shp","tanyicon.shp","tanyuico.shp","techicon.shp","tempicon.shp","teslaicon.shp","tickicon.shp","tnkdicon.shp","tnkduico.shp","towricon.shp","trkaicon.shp","trsticon.shp","trstuico.shp","tslaicon.shp","ttnkicon.shp","ttnkuico.shp","turbicon.shp","twr1icon.shp","twr2icon.shp","twr3icon.shp","v3icon.shp","v3uico.shp","wallicon.shp","weapicon.shp","weaticon.shp","weedicon.shp","wethicon.shp","xxicon.shp","yardicon.shp","yuriicon.shp","yuriuico.shp","yurpicon.shp","yurpuico.shp","zepicon.shp","zepuico.shp"]).set("theme.mix",["200meter.wav","blowitup.wav","burn.wav","destroy.wav","eaglehun.wav","fortific.wav","grinder.wav","hm2.wav","indeep.wav","industro.wav","jank.wav","motorize.wav","power.wav","ra2-opt.wav","ra2-sco.wav","tension.wav"]);r=["addon.shp","bkgdlg.shp","bkgdmd.shp","bkgdsm.shp","bttnbkgd.shp","button00.shp","button01.shp","button02.shp","button03.shp","button04.shp","button05.shp","button06.shp","button07.shp","button08.shp","button09.shp","button10.shp","button11.shp","credits.shp","diplobtn.shp","gclock2.shp","key.ini","lendcap.shp","lspacer.shp","optbtn.shp","pbeacon.shp","power.shp","powerp.shp","pwrlvl.shp","radar.shp","radar01.shp","radar02.shp","r-dn.shp","rdrbeacn.shp","rendcap.shp","repair.shp","r-up.shp","sell.shp","side1.shp","side2.shp","side2b.shp","side3.shp","sidebar.pal","sidebttn.shp","tab00.shp","tab01.shp","tab02.shp","tab03.shp","tabs.shp","top.shp","uibkgd.pal","wayp.shp"];bt.set("sidec01.mix",r).set("sidec02.mix",r);var vt,St,r=["reportbug.shp"];bt.set("sidec01cd.mix",r).set("sidec02cd.mix",r),(r=vt=vt||{})[r.Archive=0]="Archive",r[r.Cdn=1]="Cdn",r[r.Local=2]="Local";class kt{readIni(e){return this.minMoney=e.getNumber("MinMoney"),this.money=e.getNumber("Money"),this.maxMoney=e.getNumber("MaxMoney"),this.moneyIncrement=e.getNumber("MoneyIncrement"),this.minUnitCount=e.getNumber("MinUnitCount"),this.unitCount=e.getNumber("UnitCount"),this.maxUnitCount=e.getNumber("MaxUnitCount"),this.crates=e.getBool("Crates"),this.gameSpeed=e.getNumber("GameSpeed"),this.mcvRedeploys=e.getBool("MCVRedeploys"),this.shortGame=e.getBool("ShortGame"),this.superWeapons=e.getBool("SuperWeapons"),this.techLevel=e.getNumber("TechLevel"),this.alliesAllowed=e.getBool("AlliesAllowed",!0),this.allyChangeAllowed=e.getBool("AllyChangeAllowed",!0),this.mustAlly=e.getBool("MustAlly"),this}}(r=St=St||{})[r.Battle=0]="Battle",r[r.ManBattle=1]="ManBattle",r[r.FreeForAll=2]="FreeForAll",r[r.Unholy=3]="Unholy",r[r.Cooperative=4]="Cooperative";class Ot{constructor(e,t){this.modeIniLoader=t,this.entries=new Map,this.loadIni(e)}loadIni(e){e.getOrderedSections().forEach(s=>{let r=St[s.name]??St.Battle;[...s.entries.keys()].forEach(e=>{let t=s.getArray(e);if(t.length<5)throw new Error(`Invalid format for mp mode entry "${e}".`);var i=Number(e),e=t[2].toLowerCase(),e={id:i,type:r,label:t[0],description:t[1],rulesOverride:e,mapFilter:t[3],randomMapsAllowed:t[4],aiAllowed:i<3,mpDialogSettings:(new kt).readIni(this.modeIniLoader(e).getOrCreateSection("MultiplayerDialogSettings"))};this.entries.set(i,e)})})}getById(e){if(!this.entries.has(e))throw new Error(`No game mode found with id ${e}`);return this.entries.get(e)}hasId(e){return this.entries.has(e)}getAll(){return[...this.entries.values()]}}class _t{fromIni(t,e){return this.fileName=t.getString("File")||t.name.toLowerCase()+".map",this.uiName=t.getString("Description"),this.maxSlots=t.getNumber("MaxPlayers"),this.official=!0,this.gameModes=e.filter(e=>t.getArray("GameMode").includes(e.mapFilter)),this}getFullMapTitle(e){return this.addTitleSlotsSuffix(e.get(this.uiName),this.maxSlots)}addTitleSlotsSuffix(e,t){return e.match(/(\(|()\s*\d(-\d)?\s*(\)|))\s*$/)||(e+=` (2${2<t?"-"+t:""})`),e}fromMapFile(e,t){var i=e.readAsString();let s=e.filename;const r=new c(this.extractIniSection("Basic",i)).getSection("Basic");if(!r)throw new Error(`Map "${s}" is missing the [Basic] section`);this.fileName=s,this.uiName="NOSTR:"+(r.getString("Name")||s.replace(/\.[^.]+$/,""));let a=r.getNumber("MaxPlayer");if(!a){i=this.extractIniSection("Header",i);const o=i?new c(i).getSection("Header"):void 0;a=o?.getNumber("NumberStartingPoints")||2}this.maxSlots=a,this.official=r.getBool("Official");let n=r.getArray("GameMode",void 0,["standard"]);return this.gameModes=t.filter(e=>n.includes(e.mapFilter)),this}extractIniSection(t,i){t=i.indexOf(`[${t}]`);if(-1!==t){let e=t+1;for(;e<i.length&&("["!==i[e]||"\n"!==i[e-1]);e++);return i.slice(t,e)}}}class It{constructor(e){this.gameModes=e,this.manifests=[]}addFromIni(i){let e=i.getSection("MultiMaps");if(!e)throw new Error("Invalid map list. Missing [MultiMaps] section.");return this.manifests=this.manifests.concat([...e.entries.values()].map(e=>{var t=i.getSection(e);if(!t)throw new Error(`Invalid map list. Missing [${e}] section.`);return(new _t).fromIni(t,this.gameModes.getAll())})),this.dedupeEntries(),this}add(e){this.manifests.push(e)}addFromMapFile(e){this.add((new _t).fromMapFile(e,this.gameModes.getAll()))}getAll(){return this.manifests}getByName(t){return this.manifests.find(e=>e.fileName.toLowerCase()===t.toLowerCase())}sortByName(){this.manifests.sort((e,t)=>e.fileName.localeCompare(t.fileName))}clone(){let e=new It(this.gameModes);return e.manifests=[...this.manifests],e}mergeWith(e){return this.manifests.push(...e.manifests),this.dedupeEntries(),this}dedupeEntries(){this.manifests=[...new Map(this.manifests.map(e=>[e.fileName.toLowerCase(),e])).values()]}}class Ct{getMatrix(e){return this.matrices[e]}}var At,Bt,xt=__webpack_require__(949);class Et{constructor(e){e instanceof i&&this.fromVirtualFile(e)}fromVirtualFile(e){this.filename=e.filename;let i=e.stream;this.sections=[],i.readCString(16);var s=i.readInt32(),r=i.readInt32();for(let e=0;e<r;++e){let e=new Ct;e.name=i.readCString(16),e.matrices=new Array(s),this.sections.push(e)}for(let t=0;t<s;++t)for(let e=0;e<r;++e)this.sections[e].matrices[t]=this.readMatrix(i)}readMatrix(t){let i=[];for(let e=0;e<3;++e)i.push(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32());return i.push(0,0,0,1),(new xt.Matrix4).fromArray(i).transpose()}}(r=At=At||{})[r.AutoDetect=0]="AutoDetect",r[r.TiberianSun=1]="TiberianSun",r[r.Firestorm=2]="Firestorm",r[r.RedAlert2=3]="RedAlert2",r[r.YurisRevenge=4]="YurisRevenge";class Pt{static getVersion(){return"0.62.0".split(".").slice(0,2).join(".")}static getModHash(){if(!this.modHash)throw new Error("Rules must be loaded first");return this.modHash}static getActiveMod(){return this.activeMod}static setActiveMod(e){this.activeMod=e}static initGameResSource(e){this.gameResSource=e}static async initRfs(e){let t=this.rfs=new fe;return t.addRootDirectoryHandle(e),t}static async initVfs(e,t){return this.vfs=new de(e,t),Pt.iniFiles.setVfs(this.vfs),Pt.palettes.setVfs(this.vfs),Pt.images.setVfs(this.vfs),Pt.voxels.setVfs(this.vfs),Pt.voxelAnims.setVfs(this.vfs),Pt.tileData.setVfs(this.vfs),Pt.sounds.setVfs(this.vfs),Pt.themes.setDir(await this.rfs?.findDirectory(Pt.rfsSettings.musicDir)),Pt.taunts.setDir(await this.rfs?.findDirectory(Pt.rfsSettings.tauntsDir)),this.vfs}static supportsTheater(t){var e=this.getActiveEngine();return this.theaterSettings.get(e)?.some(e=>e.Type===t)||!1}static getTheaterSettings(e,t){if(!this.theaterSettings.has(e))throw new Error(`Unknown engineType "${e}`);e=this.theaterSettings.get(e).find(e=>e.Type===t);if(!e)throw new Error(`Unsupported theater "${I[t]}"`);return e}static async loadTheater(e){if(!Pt.rules||!Pt.art)throw new Error("Rules and art should be loaded first");if(void 0===Pt.gameResSource)throw new Error("No gameResSource is set");var t=Pt.getActiveEngine();let i;var s,r=Pt.getTheaterSettings(t,e);if(Pt.gameResSource!==vt.Cdn)for(var a of r.Mixes)await Pt.vfs.addMixFile(a);return Pt.theaters.has(e)?i=Pt.theaters.get(e):(s=Pt.getTheaterIni(t,e),t=Pt.getTileData(),i=Y.factory(e,s,r,t,Pt.palettes),Pt.theaters.set(e,i)),Pt.activeTheater=i,i}static unloadTheater(e){if(Pt.vfs){var t,i=Pt.getActiveEngine();for(t of Pt.getTheaterSettings(i,e).Mixes)Pt.vfs.removeArchive(t)}}static unloadSideMixData(){for(var e of["sidec01.mix","sidec01cd.mix"]){var t,i=bt.get(e);if(!i)return void console.warn(`Mix "${e}" not found in mix database`);for(t of i)("pal"===t.split(".").pop()?Pt.palettes:Pt.images).clear(t)}}static getTheaterIni(e,t){t=Pt.getTheaterSettings(e,t).TheaterIni;return Pt.getIni(t)}static loadRules(){var e=this.getFileNameVariant("rules.ini"),t=this.getFileNameVariant("art.ini"),i=this.getFileNameVariant("ai.ini");let s=this.iniFiles.get(e),r=this.iniFiles.get(t);var a=this.iniFiles.get(i);if(!s)throw new Error(`Rules "${e}" not found`);if(!r)throw new Error(`Art "${t}" not found`);if(!a)throw new Error(`AI "${i}" not found`);t=this.iniFiles.get(Pt.customRulesFileName),i=this.iniFiles.get(Pt.customArtFileName);if(!t)throw new Error(`Rules "${Pt.customRulesFileName}" not found`);if(!i)throw new Error(`Art "${Pt.customArtFileName}" not found`);Pt.art=r.clone().mergeWith(i),Pt.rules=s.clone().mergeWith(t),Pt.ai=a,Pt.modHash=Pt.computeModHash()}static computeModHash(){if(!this.vfs)throw new Error("VFS not initialized");let e=[this.customRulesFileName,this.customArtFileName,this.customMpModesFileName,this.getFileNameVariant("rules.ini"),this.getFileNameVariant("art.ini"),this.getFileNameVariant("ai.ini")];var t,i,s,r=this.theaterSettings.get(this.getActiveEngine());if(!r)throw new Error(`Unsupported engineType "${this.getActiveEngine()}`);for(t of r)e.push(this.getFileNameVariant(t.TheaterIni));let a=this.getMpModes();for(i of a.getAll())e.push(i.rulesOverride);let n=new oe;for(s of e){if(!this.vfs.fileExists(s))throw new Error(`File ${s} not found`);var o=this.vfs.openFile(s).stream;n.append(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}return n.append(D(this.getVersion())),n.get()}static getRules(){if(!Pt.rules)throw new Error("Rules must be loaded first");return Pt.rules}static getArt(){if(!Pt.art)throw new Error("Art must be loaded first");return Pt.art}static getAi(){if(!Pt.ai)throw new Error("AI must be loaded first");return Pt.ai}static getFileNameVariant(e){var t=this.getActiveEngine();let i;if(t===At.YurisRevenge)i="md";else{if(t!==At.RedAlert2)throw new Error(`Unsupported engine type ${At[t]}`);i=""}return i?e.replace(/\.([^.]+)$/,i+".$1"):e}static getMpModes(){return new Ot(this.getIni(this.customMpModesFileName),e=>this.getIni(e))}static getUiIni(){var e=this.getFileNameVariant("ui.ini");return this.getIni(e)}static getIni(e){if(!this.iniFiles.has(e))throw new Error(`INI file ${e} not found.`);return this.iniFiles.get(e)}static async loadMapList(){if(!this.vfs)throw new Error("File system not initialized");var e,i,s,t=this.getMpModes();let r=new It(t);r.addFromIni(this.getIni(this.getFileNameVariant("missions.pkt")));for(e of this.vfs.listArchives()){var a=e.toLowerCase().replace(/\.[^.]+$/,"")+".pkt";this.vfs.fileExists(a)&&r.addFromIni(new c(this.vfs.openFile(a)))}let n=new It(t);if(this.rfs)for await(var o of this.rfs.getEntries()){let t=o.toLowerCase();try{t.endsWith(".pkt")?(i=new c(await this.rfs.openFile(o,!0)),r.addFromIni(i)):this.supportedMapTypes.some(e=>t.endsWith("."+e))&&(s=await this.rfs.openFile(o,!0),n.addFromMapFile(s))}catch(e){console.warn(`Couldn't read file "${o}"`,e)}}return n.sortByName(),r.mergeWith(n),this.mapList=r,r}static getTileData(){return Pt.tileData}static getImages(){return Pt.images}static getVoxels(){return Pt.voxels}static getVoxelAnims(){return Pt.voxelAnims}static getPalettes(){return Pt.palettes}static getSounds(){return Pt.sounds}static getThemes(){return Pt.themes}static getTaunts(){return Pt.taunts}static getActiveEngine(){return At.RedAlert2}static getLastTheaterType(){return Pt.activeTheater?.type}static getCacheDir(){try{return this.getOrCreateDir(this.rfsSettings.cacheDir,!0)}catch(e){return void console.error("Couldn't get cache directory",[e])}}static async getReplayDir(){var i=this.getActiveMod();if(i){let e=await this.getModDir(),t=await e?.getDirectory(i);return t?.getOrCreateDirectory(Pt.rfsSettings.replayDir)}return this.getOrCreateDir(this.rfsSettings.replayDir)}static getModDir(){return this.getOrCreateDir(Pt.rfsSettings.modDir)}static getMapDir(){return this.getOrCreateDir(Pt.rfsSettings.mapDir)}static async getOrCreateDir(e,t=!1){let i=this.rfs?.getRootDirectory();if(i)return await i.getOrCreateDirectory(e,t)}static getMapList(){return this.mapList}static destroy(){this.activeTheater=void 0,this.activeMod=void 0,this.modHash=void 0,this.mapList=void 0,this.rfs=void 0,this.vfs=void 0,this.art=void 0,this.iniFiles.clear(),this.images.clear(),this.palettes.clear(),this.rules=void 0,this.ai=void 0,this.theaters.clear(),this.tileData.clear(),this.voxels.clear(),this.voxelAnims.clear()}}Pt,Pt.UI_ANIM_SPEED=2,Pt.rfsSettings={menuVideoFileName:"ra2ts_l.webm",splashImgFileName:"glsl.png",mapDir:"maps",modDir:"mods",musicDir:"music",tauntsDir:"Taunts",cacheDir:"cache",replayDir:"replays"},Pt.supportedMapTypes=["mpr","map"],Pt.images=new ye(e=>new s(e)),Pt.voxels=new ye(e=>new S(e)),Pt.voxelAnims=new ye(e=>new Et(e)),Pt.sounds=new ye(e=>new yt(e)),Pt.themes=new wt(e=>new Tt(e),!1),Pt.taunts=new wt(async e=>new yt(new Uint8Array(await e.arrayBuffer()))),Pt.iniFiles=new ye(e=>new c(e)),Pt.tileData=new ye(e=>new E(e)),Pt.palettes=new ye(e=>new G(e)),Pt.theaters=new Map,Pt.theaterSettings=(new Map).set(At.RedAlert2,[{Type:I.Temperate,TheaterIni:"temperat.ini",Mixes:["isotemp.mix","temperat.mix","tem.mix"],Extension:".tem",NewTheaterChar:"T",IsoPaletteName:"isotem.pal",UnitPaletteName:"unittem.pal",OverlayPaletteName:"temperat.pal",LibPaletteName:"libtem.pal"},{Type:I.Snow,TheaterIni:"snow.ini",Mixes:["isosnow.mix","snow.mix","sno.mix"],Extension:".sno",NewTheaterChar:"A",IsoPaletteName:"isosno.pal",UnitPaletteName:"unitsno.pal",OverlayPaletteName:"snow.pal",LibPaletteName:"libsno.pal"},{Type:I.Urban,TheaterIni:"urban.ini",Mixes:["isourb.mix","urb.mix","urban.mix"],Extension:".urb",NewTheaterChar:"U",IsoPaletteName:"isourb.pal",UnitPaletteName:"uniturb.pal",OverlayPaletteName:"urban.pal",LibPaletteName:"liburb.pal"}]).set(At.YurisRevenge,[{Type:I.Temperate,TheaterIni:"temperatmd.ini",Mixes:["isotemp.mix","isotemmd.mix","temperat.mix","tem.mix"],Extension:".tem",NewTheaterChar:"T",IsoPaletteName:"isotem.pal",UnitPaletteName:"unittem.pal",OverlayPaletteName:"temperat.pal",LibPaletteName:"libtem.pal"},{Type:I.Snow,TheaterIni:"snowmd.ini",Mixes:["isosnomd.mix","snowmd.mix","isosnow.mix","snow.mix","sno.mix"],Extension:".sno",NewTheaterChar:"A",IsoPaletteName:"isosno.pal",UnitPaletteName:"unitsno.pal",OverlayPaletteName:"snow.pal",LibPaletteName:"libsno.pal"},{Type:I.Urban,TheaterIni:"urbanmd.ini",Mixes:["isourbmd.mix","isourb.mix","urb.mix","urban.mix"],Extension:".urb",NewTheaterChar:"U",IsoPaletteName:"isourb.pal",UnitPaletteName:"uniturb.pal",OverlayPaletteName:"urban.pal",LibPaletteName:"liburb.pal"},{Type:I.NewUrban,TheaterIni:"urbannmd.ini",Mixes:["isoubnmd.mix","isoubn.mix","ubn.mix","urbann.mix"],Extension:".ubn",NewTheaterChar:"N",IsoPaletteName:"isoubn.pal",UnitPaletteName:"unitubn.pal",OverlayPaletteName:"urbann.pal",LibPaletteName:"libubn.pal"},{Type:I.Desert,TheaterIni:"desertmd.ini",Mixes:["isodesmd.mix","desert.mix","des.mix","isodes.mix"],Extension:".des",NewTheaterChar:"D",IsoPaletteName:"isodes.pal",UnitPaletteName:"unitdes.pal",OverlayPaletteName:"desert.pal",LibPaletteName:"libdes.pal"},{Type:I.Lunar,TheaterIni:"lunarmd.ini",Mixes:["isolunmd.mix","isolun.mix","lun.mix","lunar.mix"],Extension:".lun",NewTheaterChar:"L",IsoPaletteName:"isolun.pal",UnitPaletteName:"unitlun.pal",OverlayPaletteName:"lunar.pal",LibPaletteName:"liblun.pal"}]),Pt.customRulesFileName="rulescd.ini",Pt.customArtFileName="artcd.ini",Pt.customMpModesFileName="mpmodescd.ini",(r=Bt=Bt||{})[r.None=0]="None",r[r.Aircraft=1]="Aircraft",r[r.Building=2]="Building",r[r.Infantry=3]="Infantry",r[r.Overlay=4]="Overlay",r[r.Smudge=5]="Smudge",r[r.Terrain=6]="Terrain",r[r.Vehicle=7]="Vehicle",r[r.Animation=8]="Animation",r[r.Projectile=9]="Projectile",r[r.VoxelAnim=10]="VoxelAnim",r[r.Debris=11]="Debris";class Nt{constructor(e){this.type=e}isStructure(){return this.type===Bt.Building}isVehicle(){return this.type===Bt.Vehicle}isInfantry(){return this.type===Bt.Infantry}isAircraft(){return this.type===Bt.Aircraft}isTerrain(){return this.type===Bt.Terrain}isSmudge(){return this.type===Bt.Smudge}isOverlay(){return this.type===Bt.Overlay}isNamed(){return"name"in this}isTechno(){return"health"in this}}class Mt extends Nt{}class Dt extends Mt{}class Rt extends Dt{constructor(){super(Bt.Building)}}class Lt extends Dt{constructor(){super(Bt.Vehicle)}}class Ft extends Dt{constructor(){super(Bt.Infantry)}}class jt extends Dt{constructor(){super(Bt.Aircraft)}}class Ut extends Mt{constructor(){super(Bt.Terrain)}}class Wt extends Mt{constructor(){super(Bt.Smudge)}}class zt extends Nt{constructor(){super(Bt.Overlay)}}class Vt{static decode(e,t){t=new Uint8Array(t);return this.decodeInto(e,t),t}static decodeInto(e,t){let i=new b(new DataView(e.buffer,e.byteOffset,e.byteLength)),s=0;for(;;){var r=i.readUint8();if(0==(128&r)){var a=i.readUint8(),n=3+((112&r)>>4);this.replicatePrevious(t,s,s-(((15&r)<<8)+a),n),s+=n}else if(0==(64&r)){n=63&r;if(0==n)return s;t.set(i.readUint8Array(n),s),s+=n}else{r=63&r;if(62==r)for(var o=i.readInt16(),h=i.readUint8(),l=s+o;s<l;s++)t[s]=h;else if(63==r){o=i.readInt16();let e=i.readInt16();if(e>=s)throw new Error(`srcIndex >= destIndex ${e} ${s}`);for(var c=s+o;s<c;s++)t[s]=t[e++]}else{r=3+r;let e=i.readInt16();if(e>=s)throw new Error(`srcIndex >= destIndex ${e} ${s}`);for(var u=s+r;s<u;s++)t[s]=t[e++]}}}}static replicatePrevious(t,i,s,r){if(i<s)throw new Error(`srcIndex > destIndex ${s} ${i}`);if(i-s==1)for(let e=0;e<r;e++)t[i+e]=t[i-1];else for(let e=0;e<r;e++)t[i+e]=t[s+e]}}var Ht,Gt,$t,qt,Xt,Zt,Qt,Yt,Kt,Jt,ei,ti,ii,si,ri,ai,ni,oi,hi,li,ci=__webpack_require__(251).default;class ui{static decompress(e,t){e={inputBuffer:e,outputBuffer:null},t=ci.decompress(e,{outputSize:t});if(0!==t)throw new Error(`MiniLzo decode failed with code ${t}`);return e.outputBuffer}}class di{static decode(e,t,i=5){t=new Uint8Array(t);return this.decodeInto(e,t,i),t}static decodeInto(e,i,s=5){var t=i.length;let r=0,a=0;for(;a<t;){var n=e[r+1]<<8|e[r];r+=2;var o=e[r+1]<<8|e[r];if(r+=2,!n||!o)break;let t;t=80===s?Vt.decode(e.subarray(r,r+n),o):ui.decompress(e.subarray(r,r+n),o);for(let e=0;e<o;++e)i[a+e]=t[e];r+=n,a+=o}}}function pi(e){switch(e){case Ht.Indexed:return 1;case Ht.Rgb:return 3;case Ht.Rgba:return 4;default:throw new Error(`Unsupported pixel format ${e}`)}}(r=Ht=Ht||{})[r.Rgb=1]="Rgb",r[r.Rgba=2]="Rgba",r[r.Indexed=3]="Indexed";class gi{constructor(e,t,i,s=Ht.Rgba){var r=pi(s);this.data=i||new Uint8Array(r*e*t),this.pixelFormat=s,this.width=e,this.height=t}drawIndexedImage(t,e,i){var s=pi(this.pixelFormat);const r=this.data;var a=this.width,n=s*a,o=s*a*this.height;let h=0+n*i+s*e,l=0;for(let e=0;e<t.height;e++){for(let e=0;e<t.width;e++){var c=t.data[l];0!==c&&0<=h&&h<o&&(r[h]=c,3<=s&&(r[h+1]=0,r[h+2]=0),4===s&&(r[h+3]=255)),h+=s,l++}h+=n-t.width*s}}}class mi extends gi{constructor(e,t,i){super(e,t,i,Ht.Rgb)}}(r=Gt=Gt||{})[r.OnceAny=0]="OnceAny",r[r.OnceAll=1]="OnceAll",r[r.Repeat=2]="Repeat";class fi{read(e){let t=[];for(var[i,s]of e.entries){var r=s.split(",");r.length<3?console.warn(`Invalid tag ${i}=${s}. Skipping.`):(s=Number(r[0]),void 0!==Gt[s]?(r={id:i,repeatType:s,name:r[1],triggerId:r[2]},t.push(r)):console.warn(`Invalid repeat value ${s} for tag id ${i}. Skipping.`))}return t}}(r=$t=$t||{})[r.NoEvent=0]="NoEvent",r[r.EnteredBy=1]="EnteredBy",r[r.SpiedBy=2]="SpiedBy",r[r.AttackedByAny=6]="AttackedByAny",r[r.DestroyedByAny=7]="DestroyedByAny",r[r.AnyEvent=8]="AnyEvent",r[r.DestroyedAllUnits=9]="DestroyedAllUnits",r[r.DestroyedAllBuildings=10]="DestroyedAllBuildings",r[r.DestroyedAll=11]="DestroyedAll",r[r.CreditsExceed=12]="CreditsExceed",r[r.ElapsedTime=13]="ElapsedTime",r[r.MissionTimerExpired=14]="MissionTimerExpired",r[r.DestroyedBuildings=15]="DestroyedBuildings",r[r.DestroyedUnits=16]="DestroyedUnits",r[r.NoFactoriesLeft=17]="NoFactoriesLeft",r[r.BuildBuilding=19]="BuildBuilding",r[r.BuildUnit=20]="BuildUnit",r[r.BuildInfantry=21]="BuildInfantry",r[r.BuildAircraft=22]="BuildAircraft",r[r.CrossesHorizontalLine=25]="CrossesHorizontalLine",r[r.CrossesVerticalLine=26]="CrossesVerticalLine",r[r.GlobalIsSet=27]="GlobalIsSet",r[r.GlobalIsCleared=28]="GlobalIsCleared",r[r.DestroyedOrCaptured=29]="DestroyedOrCaptured",r[r.LowPower=30]="LowPower",r[r.DestroyedBridge=31]="DestroyedBridge",r[r.BuildingExists=32]="BuildingExists",r[r.ComesNearWaypoint=34]="ComesNearWaypoint",r[r.LocalIsSet=36]="LocalIsSet",r[r.LocalIsCleared=37]="LocalIsCleared",r[r.FirstDamagedCombat=38]="FirstDamagedCombat",r[r.HalfHealthCombat=39]="HalfHealthCombat",r[r.QuarterHealthCombat=40]="QuarterHealthCombat",r[r.FirstDamagedAny=41]="FirstDamagedAny",r[r.HalfHealthAny=42]="HalfHealthAny",r[r.QuarterHealthAny=43]="QuarterHealthAny",r[r.AttackedByHouse=44]="AttackedByHouse",r[r.AmbientLightBelow=45]="AmbientLightBelow",r[r.AmbientLightAbove=46]="AmbientLightAbove",r[r.ElapsedScenarioTime=47]="ElapsedScenarioTime",r[r.DestroyedOrCapturedOrInfiltrated=48]="DestroyedOrCapturedOrInfiltrated",r[r.PickupCrate=49]="PickupCrate",r[r.PickupCrateAny=50]="PickupCrateAny",r[r.RandomDelay=51]="RandomDelay",r[r.CreditsBelow=52]="CreditsBelow",r[r.SpyEnteringAsHouse=53]="SpyEnteringAsHouse",r[r.SpyEnteringAsInfantry=54]="SpyEnteringAsInfantry",r[r.DestroyedAllUnitsNaval=55]="DestroyedAllUnitsNaval",r[r.DestroyedAllUnitsLand=56]="DestroyedAllUnitsLand",r[r.BuildingNotExists=57]="BuildingNotExists",(r=qt=qt||{})[r.NoAction=0]="NoAction",r[r.FireSale=9]="FireSale",r[r.TextTrigger=11]="TextTrigger",r[r.DestroyTrigger=12]="DestroyTrigger",r[r.ChangeHouse=14]="ChangeHouse",r[r.RevealMap=16]="RevealMap",r[r.RevealAroundWaypoint=17]="RevealAroundWaypoint",r[r.PlaySoundFx=19]="PlaySoundFx",r[r.PlaySpeech=21]="PlaySpeech",r[r.ForceTrigger=22]="ForceTrigger",r[r.TimerStart=23]="TimerStart",r[r.TimerStop=24]="TimerStop",r[r.TimerExtend=25]="TimerExtend",r[r.TimerShorten=26]="TimerShorten",r[r.TimerSet=27]="TimerSet",r[r.GlobalSet=28]="GlobalSet",r[r.GlobalClear=29]="GlobalClear",r[r.DestroyObject=32]="DestroyObject",r[r.AddOneTimeSuperWeapon=33]="AddOneTimeSuperWeapon",r[r.AddRepeatingSuperWeapon=34]="AddRepeatingSuperWeapon",r[r.AllChangeHouse=36]="AllChangeHouse",r[r.ResizePlayerView=40]="ResizePlayerView",r[r.PlayAnimAt=41]="PlayAnimAt",r[r.DetonateWarhead=42]="DetonateWarhead",r[r.ReshroudMap=51]="ReshroudMap",r[r.EnableTrigger=53]="EnableTrigger",r[r.DisableTrigger=54]="DisableTrigger",r[r.CreateRadarEvent=55]="CreateRadarEvent",r[r.LocalSet=56]="LocalSet",r[r.LocalClear=57]="LocalClear",r[r.SellBuilding=60]="SellBuilding",r[r.TurnOffBuilding=61]="TurnOffBuilding",r[r.TurnOnBuilding=62]="TurnOnBuilding",r[r.ApplyOneHundredDamage=63]="ApplyOneHundredDamage",r[r.ForceEnd=69]="ForceEnd",r[r.DestroyTag=70]="DestroyTag",r[r.SetAmbientStep=71]="SetAmbientStep",r[r.SetAmbientRate=72]="SetAmbientRate",r[r.SetAmbientLight=73]="SetAmbientLight",r[r.NukeStrike=95]="NukeStrike",r[r.PlaySoundFxAt=99]="PlaySoundFxAt",r[r.UnrevealAroundWaypoint=101]="UnrevealAroundWaypoint",r[r.LightningStrike=102]="LightningStrike",r[r.TimerText=103]="TimerText",r[r.CreateCrate=108]="CreateCrate",r[r.IronCurtainAt=109]="IronCurtainAt",r[r.EvictOccupiers=111]="EvictOccupiers",r[r.Cheer=113]="Cheer",r[r.StopSoundsAt=116]="StopSoundsAt";class yi{read(e,t,i,s){let r=this.readTriggers(e),{events:a,unknownEventTypes:n}=this.readEvents(t),{actions:o,unknownActionTypes:h}=this.readActions(i),l=[...s.values()],c=new Set(r);for(let t of r.values()){var u=a.get(t.id);u&&t.events.push(...u);u=o.get(t.id);u&&t.actions.push(...u),!t.attachedTriggerId||(u=r.find(e=>e.id===t.attachedTriggerId))&&(t.attachedTrigger=u,c.delete(u))}for(let t of c){var d=l.find(e=>e.triggerId===t.id);if(d){let e=t;for(;e;)e.tag=d,e=e.attachedTrigger}else{let e=t;for(;e;){console.warn(`Trigger ${e.id} has no associated tag or valid root trigger. Skipping.`);var p=r.indexOf(e);-1!==p&&r.splice(p,1),e=e.attachedTrigger}}}return{triggers:r,unknownEventTypes:n,unknownActionTypes:h}}readTriggers(e){let t=[];for(var[i,s]of e.entries){var r=s.split(",");r.length<8?console.warn(`Invalid trigger ${i}=${s}. Skipping.`):(r={id:i,houseName:r[0],attachedTriggerId:"<none>"!==r[1]?r[1]:void 0,attachedTrigger:void 0,name:r[2],disabled:Boolean(Number(r[3])),difficulties:{easy:Boolean(Number(r[4])),medium:Boolean(Number(r[5])),hard:Boolean(Number(r[6]))},events:[],actions:[],tag:void 0},t.push(r))}return t}readEvents(e){let t=new Map,r=new Set;for(var[a,i]of e.entries){let s=i.split(",");if(s.length<4)console.warn(`Invalid event ${a}=${i}. Skipping.`);else{var n=Number(s.shift());let i=[];for(let t=0;t<n;t++){var o=Number(s.shift()),h=Number(s.shift());let e=s.splice(0,2===h?2:1);void 0!==$t[o]?(h={triggerId:a,eventIndex:t,type:o,params:[h,...e.map(e=>e||"0")]},i.push(h)):(r.add(o),console.warn(`Unknown event type ${o} for trigger id ${a}. Skipping.`))}t.set(a,i)}}return{events:t,unknownEventTypes:r}}readActions(e){let s=new Map,r=new Set;for(var[a,t]of e.entries){let i=t.split(",");if(i.length<9)console.warn(`Invalid action ${a}=${t}. Skipping.`);else{var n=Number(i.shift());if(i.length<8*n)console.warn(`Invalid action ${a}=${t}. Skipping.`);else{let t=[];for(let e=0;e<n;e++){var o=Number(i.shift()),h=i.splice(0,7);void 0!==qt[o]?(h={triggerId:a,index:e,type:o,params:[Number(h[0]||"0"),h[1]||"0",h[2]||"0",h[3]||"0",h[4]||"0",h[5]||"0",h[6]?this.readAZActionParam(h[6]):0]},t.push(h)):(r.add(o),console.warn(`Unknown action type ${o} for trigger id "${a}". Skipping.`))}s.set(a,t)}}}return{actions:s,unknownActionTypes:r}}readAZActionParam(e){var t="Z".charCodeAt(0),i="A".charCodeAt(0),t=t-i+1;return 1<e.length?e.charCodeAt(1)-i+(e.charCodeAt(0)-i+1)*t:e.charCodeAt(0)-i}}class wi{constructor(){this.level=0,this.ambient=1,this.red=1,this.green=1,this.blue=1,this.ground=0,this.forceTint=!1}read(e,t=""){return this.level=e.getNumber(t+"Level",.032),this.ambient=e.getNumber(t+"Ambient",1),this.red=e.getNumber(t+"Red",1),this.green=e.getNumber(t+"Green",1),this.blue=e.getNumber(t+"Blue",1),this.ground=e.getNumber(t+"Ground",0),this}copy(e){return this.level=e.level,this.ambient=e.ambient,this.red=e.red,this.green=e.green,this.blue=e.blue,this.ground=e.ground,this.forceTint=e.forceTint,this}}class Ti{read(e,t){let i=[];for(var[s,r]of e.entries){s={tagId:r,coords:this.readCoords(Number(s),t)};i.push(s)}return i}readCoords(e,t){t=t<4?128:1e3;return{x:e%t,y:Math.floor(e/t)}}}class bi{constructor(e,t){this.name=e,this.value=t}clone(){return new bi(this.name,this.value)}}class vi{read(e){return this.initialVeteran=e.getBool("InitialVeteran"),this}}class Si extends c{fromString(e){super.fromString(e);let t=this.getSection("Map");if(!t)throw new Error("[Map] section not found");e=t.getNumberArray("Size");if(this.fullSize={x:e[0],y:e[1],width:e[2],height:e[3]},e=t.getNumberArray("LocalSize"),this.localSize={x:e[0],y:e[1],width:e[2],height:e[3]},this.theaterType=t.getEnum("Theater",I,I.None,!0),this.theaterType===I.None)throw new Error(`Unsupported theater type "${t.getString("Theater")}"`);let i=this.getSection("Basic");e=this.iniFormat=i?.getNumber("NewINIFormat")??0;return this.readTiles(),i?.getBool("MultiplayerOnly")&&this.readWaypoints(this.getOrCreateSection("Waypoints")),this.readStructures(this.getOrCreateSection("Structures")),this.readVehicles(),this.readInfantries(),this.readAircrafts(),this.readTerrains(this.getOrCreateSection("Terrain")),this.readOverlays(),this.readSmudges(),this.readLighting(),this.readTagsAndTriggers(),this.readCellTags(e),this.readVariableNames(),this.startingLocations=this.readStartingLocations(this.waypoints),this.specialFlags=(new vi).read(this.getOrCreateSection("SpecialFlags")),this}readStartingLocations(e){let t=[];var i;for(i of e.filter(e=>e.number<8).sort((e,t)=>e.number<t.number?-1:1))t.push({x:i.rx,y:i.ry});return t}readLighting(){var e=this.getOrCreateSection("Lighting");this.lighting=(new wi).read(e),this.ionLighting=(new wi).read(e,"Ion"),this.ionLighting.forceTint=!0}readTagsAndTriggers(){this.tags=(new fi).read(this.getOrCreateSection("Tags"));var e=this.getOrCreateSection("Triggers"),t=this.getOrCreateSection("Events"),i=this.getOrCreateSection("Actions"),{triggers:e,unknownEventTypes:t,unknownActionTypes:i}=(new yi).read(e,t,i,this.tags);this.triggers=e,this.unknownEventTypes=t,this.unknownActionTypes=i}readCellTags(e){this.cellTags=(new Ti).read(this.getOrCreateSection("CellTags"),e)}readVariableNames(){var e,t,i=this.getOrCreateSection("VariableNames");let s=new Map;for([e,t]of i.entries){var r,a,n=Number(e);Number.isNaN(n)?console.warn(`Map [VariableNames] contains non-numeric index "${e}". Skipping.`):([r,a]=t.split(","),a=new bi(r,Boolean(Number(a))),s.set(n,a))}this.variables=s}readTiles(){let e=this.getSection("IsoMapPack5");if(!e)throw new Error("[IsoMapPack5] section not found");var t=R(e.getConcatenatedValues()),i=(2*this.fullSize.width-1)*this.fullSize.height,s=new Uint8Array(11*i+4);di.decodeInto(t,s);let r=new b(s.buffer),a=2*this.fullSize.width-1;var n,o,h,l,s=this.fullSize.height,c=(e,t)=>t*a+e;this.tiles=new Array(a*s);for(let e=this.maxTileNum=0;e<i;e++){var u=r.readUint16(),d=r.readUint16(),p=Math.max(0,r.readInt16());this.maxTileNum=Math.max(this.maxTileNum,p),r.readInt16();var g=r.readUint8(),m=r.readUint8();r.readUint8();var f=u-d+this.fullSize.width-1,y=u+d-this.fullSize.width-1;0<=f&&f<2*this.fullSize.width&&0<=y&&y<2*this.fullSize.height&&(g={dx:f,dy:y,rx:u,ry:d,z:m,tileNum:p,subTile:g},this.tiles[c(f,Math.floor(y/2))]=g)}for(let t=0;t<this.fullSize.height;t++)for(let e=0;e<=2*this.fullSize.width-2;e++)null==this.tiles[c(e,t)]&&(n=e,l=(o=2*t+e%2)-(h=(n+o)/2+1)+this.fullSize.width+1,this.tiles[c(e,t)]={dx:n,dy:o,rx:h,ry:l,z:0,tileNum:0,subTile:0})}readWaypoints(e){this.waypoints=[];for(var[t,i]of e.entries){var s;let e;isNaN(s=parseInt(t,10))||isNaN(e=parseInt(i,10))||(t=Math.floor(e/1e3),i=e-1e3*t,this.waypoints.push({number:s,rx:i,ry:t}))}}readStructures(e){this.structures=[];for(var[,t]of e.entries){t=t.split(",");if(!(t.length<=15)){let e=new Rt;e.owner=t[0],e.name=t[1],e.health=Number(t[2]),e.rx=Number(t[3]),e.ry=Number(t[4]),e.tag=this.readTagId(t[6]),e.poweredOn=Boolean(Number(t[9])),this.structures.push(e)}}}readTagId(e){return"none"!==e.toLowerCase()?e:void 0}readVehicles(){this.vehicles=[];let e=this.getSection("Units");if(e)for(var t of e.entries.values()){var i=t.split(",");if(i.length<=11)console.warn(`Invalid Vehicle entry: "${t}"`);else{let e=new Lt;e.owner=i[0],e.name=i[1],e.health=Number(i[2]),e.rx=Number(i[3]),e.ry=Number(i[4]),e.direction=Number(i[5]),e.tag=this.readTagId(i[7]),e.veterancy=Number(i[8]),e.onBridge="1"===i[10],this.vehicles.push(e)}}}readInfantries(){this.infantries=[];let e=this.getSection("Infantry");if(e)for(var t of e.entries.values()){var i=t.split(",");let e=new Ft;i.length<=8?console.warn(`Invalid Infantry entry: "${t}"`):(e.owner=i[0],e.name=i[1],e.health=Number(i[2]),e.rx=Number(i[3]),e.ry=Number(i[4]),e.subCell=Number(i[5]),e.direction=Number(i[7]),e.tag=this.readTagId(i[8]),e.veterancy=Number(i[9]),e.onBridge="1"===i[11],this.infantries.push(e))}}readAircrafts(){this.aircrafts=[];let e=this.getSection("Aircraft");if(e)for(var t of e.entries.values()){t=t.split(",");let e=new jt;e.owner=t[0],e.name=t[1],e.health=Number(t[2]),e.rx=Number(t[3]),e.ry=Number(t[4]),e.direction=Number(t[5]),e.tag=this.readTagId(t[7]),e.veterancy=Number(t[8]),e.onBridge="1"===t[t.length-4],this.aircrafts.push(e)}}readTerrains(e){this.terrains=[];for(var[t,i]of e.entries){t=Number(t);if(!isNaN(t)){let e=new Ut;e.name=i,e.rx=t%1e3,e.ry=Math.floor(t/1e3),this.terrains.push(e)}}}readOverlays(){this.overlays=[],this.maxOverlayId=0;let t=this.getSection("OverlayPack");if(t){var i=R(t.getConcatenatedValues()),s=new Uint8Array(1<<18);di.decodeInto(i,s,80);let e=this.getSection("OverlayDataPack");if(e){var i=R(e.getConcatenatedValues()),r=new Uint8Array(1<<18);di.decodeInto(i,r,80);for(let t=0;t<this.fullSize.height;t++)for(let e=2*this.fullSize.width-2;0<=e;e--){var a=e,n=2*t+e%2,o=(a+n)/2+1,h=n-o+this.fullSize.width+1,a=o+512*h,n=s[a];if(255!==n){a=r[a];let e=new zt;e.id=n,e.value=a,e.rx=o,e.ry=h,this.overlays.push(e),this.maxOverlayId=Math.max(this.maxOverlayId,n)}}}else console.warn("[OverlayDataPack] section not found. Skipping.")}else console.warn("[Overlay] section not found. Skipping.")}readSmudges(){this.smudges=[];let e=this.getSection("Smudge");if(e)for(var t of e.entries.values()){t=t.split(",");if(t.length<=2)console.warn(`Invalid Smudge entry: "${t}"`);else{let e=new Wt;e.name=t[0],e.rx=Number(t[1]),e.ry=Number(t[2]),this.smudges.push(e)}}}decodePreviewImage(){let e=this.getSection("Preview"),t=this.getSection("PreviewPack");if(e&&t){var[,,i,s]=e.getArray("Size").map(e=>Number(e)),r=R(t.getConcatenatedValues()),s=new mi(i,s);return di.decodeInto(r,s.data),s}}}(r=Xt=Xt||{})[r.GDI=0]="GDI",r[r.Nod=1]="Nod",r[r.Civilian=2]="Civilian",r[r.Mutant=3]="Mutant";const ki=(new Map).set("GDI",Xt.GDI).set("Nod",Xt.Nod).set("Civilian",Xt.Civilian).set("Mutant",Xt.Mutant),Oi=new Map([["Americans","STT:PlayerSideAmerica"],["Alliance","STT:PlayerSideKorea"],["French","STT:PlayerSideFrance"],["Germans","STT:PlayerSideGermany"],["British","STT:PlayerSideBritain"],["Africans","STT:PlayerSideLibya"],["Arabs","STT:PlayerSideIraq"],["Confederation","STT:PlayerSideCuba"],["Russians","STT:PlayerSideRussia"]]);class _i{constructor(e){this.id=e}readIni(e){this.name=e.name,this.uiName=e.getString("UIName"),this.uiTooltip=e.get("UITooltip")||Oi.get(this.name);var t=e.getString("Side");if(!t)throw new Error(`Missing Side for country "${this.name}"`);var i=ki.get(t);if(void 0===i)throw new Error(`Unknown side "${t}" for country "${this.name}"`);this.side=i,this.multiplay=e.getBool("Multiplay"),this.multiplayPassive=e.getBool("MultiplayPassive"),this.veteranAircraft=e.getArray("VeteranAircraft"),this.veteranInfantry=e.getArray("VeteranInfantry"),this.veteranUnits=e.getArray("VeteranUnits")}}class Ii{constructor(e,t,i=-1){this.type=e,this.ini=t,this.index=i,this.parse()}static iniSpeedToLeptonsPerTick(e,t){return Math.min(256,256*e/t)}static iniRotToDegsPerTick(e){return e/256*360}parse(){this.alphaImage=this.ini.getString("AlphaImage")||void 0,this.alternateArcticArt=this.ini.getBool("AlternateArcticArt"),this.crushable=this.ini.getBool("Crushable",this.type===Bt.Infantry),this.crushSound=this.ini.getString("CrushSound")||void 0,this.dontScore=this.ini.getBool("DontScore"),this.insignificant=this.ini.getBool("Insignificant"),this.legalTarget=this.ini.getBool("LegalTarget",!0),this.noShadow=this.ini.getBool("NoShadow"),this.uiName=this.ini.getString("UIName")}get name(){return this.ini.name}get imageName(){let e=this.ini.getString("Image");return e&&"null"!==e||(e=this.name),e}}Ii.IMAGE_NONE="none";class Ci{constructor(e){this.rules=e,this.parse()}parse(){this.ambientDamage=this.rules.getNumber("AmbientDamage"),this.anim=this.rules.getArray("Anim"),this.areaFire=this.rules.getBool("AreaFire"),this.burst=this.rules.getNumber("Burst",1),this.cellRangefinding=this.rules.getBool("CellRangefinding"),this.damage=this.rules.getNumber("Damage"),this.decloakToFire=this.rules.getBool("DecloakToFire",!0),this.fireOnce=this.rules.getBool("FireOnce"),this.isAlternateColor=this.rules.getBool("IsAlternateColor"),this.isElectricBolt=this.rules.getBool("IsElectricBolt"),this.isHouseColor=this.rules.getBool("IsHouseColor"),this.isLaser=this.rules.getBool("IsLaser"),this.isRadBeam=this.rules.getBool("IsRadBeam"),this.isSonic=this.rules.getBool("IsSonic"),this.laserDuration=this.rules.getNumber("LaserDuration"),this.limboLaunch=this.rules.getBool("LimboLaunch"),this.minimumRange=this.rules.getNumber("MinimumRange"),this.name=this.rules.name,this.neverUse=this.rules.getBool("NeverUse"),this.omniFire=this.rules.getBool("OmniFire"),this.projectile=this.rules.getString("Projectile"),this.radLevel=this.rules.getNumber("RadLevel"),this.range=this.rules.getNumber("Range"),-2===this.range&&(this.range=Number.POSITIVE_INFINITY),this.report=this.rules.getArray("Report"),this.revealOnFire=this.rules.getBool("RevealOnFire",!0),this.rof=this.rules.getNumber("ROF"),this.sabotageCursor=this.rules.getBool("SabotageCursor"),this.spawner=this.rules.getBool("Spawner");var e=this.rules.getNumber("Speed");this.iniSpeed=e,this.speed=Ii.iniSpeedToLeptonsPerTick(e,100),this.suicide=this.rules.getBool("Suicide"),this.useSparkParticles=this.rules.getBool("UseSparkParticles"),this.warhead=this.rules.getString("Warhead")}}class Ai{readIni(e){this.ini=e,this.ambientChangeRate=e.getNumber("AmbientChangeRate"),this.ambientChangeStep=e.getNumber("AmbientChangeStep"),this.behind=e.getString("Behind"),this.bridgeExplosions=e.getArray("BridgeExplosions"),this.chronoBeamColor=e.getNumberArray("ChronoBeamColor"),this.chronoBlast=e.getString("ChronoBlast"),this.chronoBlastDest=e.getString("ChronoBlastDest"),this.chronoPlacement=e.getString("ChronoPlacement"),this.chronoSparkle1=e.getString("ChronoSparkle1"),this.conditionRed=e.getNumber("ConditionRed"),this.conditionYellow=e.getNumber("ConditionYellow"),this.creditTicks=e.getArray("CreditTicks"),this.extraAircraftLight=e.getNumber("ExtraAircraftLight"),this.extraInfantryLight=e.getNumber("ExtraInfantryLight"),this.extraUnitLight=e.getNumber("ExtraUnitLight");let t=e.getString("DamageFireTypes");t=t||"FIRE01,FIRE02,FIRE03",this.fireNames=t.split(/\.|,/).filter(e=>""!==e),this.flyerHelper=e.getString("FlyerHelper"),this.gravity=e.getNumber("Gravity"),this.idleActionFrequency=60*e.getNumber("IdleActionFrequency"),this.impactLandSound=e.getString("ImpactLandSound")||void 0,this.impactWaterSound=e.getString("ImpactWaterSound")||void 0,this.infantryExplode=e.getString("InfantryExplode"),this.flamingInfantry=e.getString("FlamingInfantry"),this.infantryHeadPop=e.getString("InfantryHeadPop"),this.infantryNuked=e.getString("InfantryNuked"),this.ironCurtainInvokeAnim=e.getString("IronCurtainInvokeAnim"),this.messageDuration=e.getNumber("MessageDuration",10),this.metallicDebris=e.getArray("MetallicDebris"),this.nukeTakeOff=e.getString("NukeTakeOff"),this.deadBodies=e.getArray("DeadBodies"),this.wake=e.getString("Wake"),this.parachute=e.getString("Parachute"),this.moveFlash=e.getString("MoveFlash"),this.warpOut=e.getString("WarpOut"),this.warpAway=e.getString("WarpAway"),this.weaponNullifyAnim=e.getString("WeaponNullifyAnim"),this.weatherConClouds=e.getArray("WeatherConClouds"),this.weatherConBoltExplosion=e.getString("WeatherConBoltExplosion"),this.weatherConBolts=e.getArray("WeatherConBolts")}}(r=Zt=Zt||{})[r.GenericCombat=0]="GenericCombat",r[r.GenericNonCombat=1]="GenericNonCombat",r[r.DropZone=2]="DropZone",r[r.BaseUnderAttack=3]="BaseUnderAttack",r[r.HarvesterUnderAttack=4]="HarvesterUnderAttack",r[r.EnemyObjectSensed=5]="EnemyObjectSensed";class Bi{readIni(e){return this.eventSuppressionDistances=e.getNumberArray("RadarEventSuppressionDistances"),this.eventVisibilityDurations=e.getNumberArray("RadarEventVisibilityDurations"),this.eventDurations=e.getNumberArray("RadarEventDurations"),this.flashFrameTime=e.getNumber("FlashFrameTime"),this.combatFlashTime=e.getNumber("RadarCombatFlashTime"),this.eventMinRadius=e.getNumber("RadarEventMinRadius"),this.eventSpeed=e.getNumber("RadarEventSpeed"),this.eventRotationSpeed=e.getNumber("RadarEventRotationSpeed"),this.eventColorSpeed=e.getNumber("RadarEventColorSpeed"),this}getEventSuppresionDistance(e){if(e>this.eventSuppressionDistances.length-1)throw new RangeError(`No event suppression distance is defined for type ${Zt[e]}`);return this.eventSuppressionDistances[e]}getEventVisibilityDuration(e){if(e>this.eventVisibilityDurations.length-1)throw new RangeError(`No event visibility duration is defined for type ${Zt[e]}`);return this.eventVisibilityDurations[e]}getEventDuration(e){if(e>this.eventDurations.length-1)throw new RangeError(`No event duration is defined for type ${Zt[e]}`);return this.eventDurations[e]}}class xi{readIni(e){return this.reloadRate=e.getNumber("ReloadRate"),this.repairPercent=e.getNumber("RepairPercent"),this.repairRate=e.getNumber("RepairRate"),this.repairStep=e.getNumber("RepairStep"),this.uRepairRate=e.getNumber("URepairRate"),this.iRepairRate=e.getNumber("IRepairRate"),this.iRepairStep=e.getNumber("IRepairStep"),this}}class Ei{readIni(e){return this.veteranRatio=e.getNumber("VeteranRatio",3),this.veteranCombat=e.getNumber("VeteranCombat",1),this.veteranSpeed=e.getNumber("VeteranSpeed",1),this.veteranSight=Math.max(1,e.getNumber("VeteranSight",1)),this.veteranArmor=e.getNumber("VeteranArmor",1),this.veteranROF=e.getNumber("VeteranROF",1),this.veteranCap=e.getNumber("VeteranCap",2),this.initialVeteran=e.getBool("InitialVeteran"),this}}class Pi{readIni(e){return this.alliedCrew=e.getString("AlliedCrew"),this.alliedSurvivorDivisor=e.getNumber("AlliedSurvivorDivisor"),this.crewEscape=e.getNumber("CrewEscape"),this.sovietCrew=e.getString("SovietCrew"),this.sovietSurvivorDivisor=e.getNumber("SovietSurvivorDivisor"),this.survivorRate=e.getNumber("SurvivorRate"),this}}class Ni{readIni(e){return this.type=e.getString("PrismType"),this.supportHeight=e.getNumber("PrismSupportHeight"),this.supportMax=e.getNumber("PrismSupportMax"),this.supportModifier=e.getNumber("PrismSupportModifier",1),this}}class Mi{readIni(e){return this.myEffectivenessCoefficientDefault=e.getNumber("MyEffectivenessCoefficientDefault"),this.targetEffectivenessCoefficientDefault=e.getNumber("TargetEffectivenessCoefficientDefault"),this.targetSpecialThreatCoefficientDefault=e.getNumber("TargetSpecialThreatCoefficientDefault"),this.targetStrengthCoefficientDefault=e.getNumber("TargetStrengthCoefficientDefault"),this.targetDistanceCoefficientDefault=e.getNumber("TargetDistanceCoefficientDefault"),this}}class Di{readIni(e){if(this.allyParaDrop=this.readParadropSquad(e.getArray("AllyParaDropInf"),e.getNumberArray("AllyParaDropNum"),"Ally"),this.amerParaDrop=this.readParadropSquad(e.getArray("AmerParaDropInf"),e.getNumberArray("AmerParaDropNum"),"Amer"),this.sovParaDrop=this.readParadropSquad(e.getArray("SovParaDropInf"),e.getNumberArray("SovParaDropNum"),"Sov"),this.paradropPlane=e.getString("ParadropPlane"),!this.paradropPlane)throw new Error("Missing rules [General]->ParadropPlane");return this.paradropRadius=e.getNumber("ParadropRadius"),this}readParadropSquad(t,i,e){if(t.length!==i.length)throw new RangeError(`${e}ParaDropInf/Num size mismatch (${t.length}, ${i.length})`);let s=[];for(let e=0;e<t.length;++e)0<i[e]&&s.push({inf:t[e],num:i[e]});return s}getParadropSquads(e){switch(e){case Xt.GDI:return this.allyParaDrop;case Xt.Nod:return this.sovParaDrop;default:throw new Error(`Unhandled side type "${e}"`)}}}class Ri{readIni(e){return this.deferment=e.getNumber("LightningDeferment"),this.damage=e.getNumber("LightningDamage"),this.duration=e.getNumber("LightningStormDuration"),this.warhead=e.getString("LightningWarhead"),this.hitDelay=e.getNumber("LightningHitDelay"),this.scatterDelay=e.getNumber("LightningScatterDelay"),this.cellSpread=e.getNumber("LightningCellSpread"),this.separation=e.getNumber("LightningSeparation"),this}}class Li{}class Fi extends Li{readIni(e){return this.pauseFrames=e.getNumber("V3RocketPauseFrames"),this.tiltFrames=e.getNumber("V3RocketTiltFrames"),this.pitchInitial=e.getNumber("V3RocketPitchInitial"),this.pitchFinal=e.getNumber("V3RocketPitchFinal"),this.turnRate=e.getNumber("V3RocketTurnRate"),this.acceleration=e.getNumber("V3RocketAcceleration"),this.altitude=e.getNumber("V3RocketAltitude"),this.damage=e.getNumber("V3RocketDamage"),this.eliteDamage=e.getNumber("V3RocketEliteDamage"),this.bodyLength=e.getNumber("V3RocketBodyLength"),this.lazyCurve=e.getBool("V3RocketLazyCurve"),this.type=e.getString("V3RocketType"),this}}class ji extends Li{readIni(e){return this.pauseFrames=e.getNumber("DMislPauseFrames"),this.tiltFrames=e.getNumber("DMislTiltFrames"),this.pitchInitial=e.getNumber("DMislPitchInitial"),this.pitchFinal=e.getNumber("DMislPitchFinal"),this.turnRate=e.getNumber("DMislTurnRate"),this.acceleration=e.getNumber("DMislAcceleration"),this.altitude=e.getNumber("DMislAltitude"),this.damage=e.getNumber("DMislDamage"),this.eliteDamage=e.getNumber("DMislEliteDamage"),this.bodyLength=e.getNumber("DMislBodyLength"),this.lazyCurve=e.getBool("DMislLazyCurve"),this.type=e.getString("DMislType"),this}}class Ui{readIni(e){return this.height=e.getNumber("HoverHeight"),this.dampen=e.getNumber("HoverDampen"),this.bob=e.getNumber("HoverBob"),this.boost=e.getNumber("HoverBoost"),this.acceleration=e.getNumber("HoverAcceleration"),this.brake=e.getNumber("HoverBrake"),this}}(r=Qt=Qt||{})[r.Power=0]="Power",r[r.Factory=1]="Factory",r[r.Barracks=2]="Barracks",r[r.Radar=3]="Radar",r[r.Tech=4]="Tech",r[r.Proc=5]="Proc";const Wi=(new Map).set(Qt.Power,"PrerequisitePower").set(Qt.Factory,"PrerequisiteFactory").set(Qt.Barracks,"PrerequisiteBarracks").set(Qt.Radar,"PrerequisiteRadar").set(Qt.Tech,"PrerequisiteTech").set(Qt.Proc,"PrerequisiteProc");class zi{constructor(){this.prereqCategories=new Map}readIni(e){this.aircraftFogReveal=e.getNumber("AircraftFogReveal"),this.alliedDisguise=e.getString("AlliedDisguise"),this.baseUnit=e.getArray("BaseUnit"),this.bridgeVoxelMax=e.getNumber("BridgeVoxelMax"),this.buildSpeed=e.getFixed("BuildSpeed"),this.buildupTime=e.getNumber("BuildupTime"),this.chronoDelay=e.getNumber("ChronoDelay"),this.chronoDistanceFactor=e.getNumber("ChronoDistanceFactor",32),this.chronoHarvTooFarDistance=e.getNumber("ChronoHarvTooFarDistance"),this.chronoMinimumDelay=e.getNumber("ChronoMinimumDelay"),this.chronoRangeMinimum=e.getNumber("ChronoRangeMinimum"),this.chronoTrigger=e.getBool("ChronoTrigger",!0),this.cliffBackImpassability=e.getNumber("CliffBackImpassability",2),this.cloakDelay=e.getNumber("CloakDelay"),this.closeEnough=e.getNumber("CloseEnough"),this.crew=(new Pi).readIni(e),this.defaultMirageDisguises=e.getArray("DefaultMirageDisguises"),this.dMisl=(new ji).readIni(e),this.dropPodWeapon=e.getString("DropPodWeapon"),this.engineer=e.getString("Engineer"),this.flightLevel=e.getNumber("FlightLevel"),this.guardAreaTargetingDelay=e.getNumber("GuardAreaTargetingDelay"),this.harvesterTooFarDistance=e.getNumber("HarvesterTooFarDistance"),this.harvesterUnit=e.getArray("HarvesterUnit"),this.hover=(new Ui).readIni(e),this.infantryBlinkDisguiseTime=e.getNumber("InfantryBlinkDisguiseTime"),this.lightningStorm=(new Ri).readIni(e),this.lowPowerPenaltyModifier=e.getNumber("LowPowerPenaltyModifier",1),this.minLowPowerProductionSpeed=e.getFixed("MinLowPowerProductionSpeed",.5),this.maxLowPowerProductionSpeed=e.getFixed("MaxLowPowerProductionSpeed",1),this.maximumCheerRate=e.getNumber("MaximumCheerRate"),this.maximumQueuedObjects=e.getNumber("MaximumQueuedObjects"),this.maxWaypointPathLength=e.getNumber("MaxWaypointPathLength"),this.multipleFactory=e.getFixed("MultipleFactory",1),this.normalTargetingDelay=e.getNumber("NormalTargetingDelay"),this.padAircraft=e.getArray("PadAircraft"),this.parachuteMaxFallRate=e.getNumber("ParachuteMaxFallRate"),this.paradrop=(new Di).readIni(e),this.prism=(new Ni).readIni(e),this.purifierBonus=e.getNumber("PurifierBonus"),this.radar=(new Bi).readIni(e),this.refundPercent=W(e.getNumber("RefundPercent"),0,1),this.repair=(new xi).readIni(e),this.revealTriggerRadius=Math.min(10,e.getNumber("RevealTriggerRadius")),this.shipSinkingWeight=e.getNumber("ShipSinkingWeight"),this.sovietDisguise=e.getString("SovietDisguise"),this.spyMoneyStealPercent=e.getNumber("SpyMoneyStealPercent"),this.spyPowerBlackout=e.getNumber("SpyPowerBlackout"),this.technician=e.getString("Technician"),this.threat=(new Mi).readIni(e),this.treeStrength=e.getNumber("TreeStrength"),this.v3Rocket=(new Fi).readIni(e),this.veteran=(new Ei).readIni(e),this.wallBuildSpeedCoefficient=e.getFixed("WallBuildSpeedCoefficient"),this.readPrereqCategories(e)}readPrereqCategories(e){for(var[t,i]of Wi){if(!e.has(i))throw new Error(`Missing prerequisite category ${i} in [General] section`);this.prereqCategories.set(t,e.getArray(i))}}getMissileRules(e){switch(e){case this.v3Rocket.type:return this.v3Rocket;case this.dMisl.type:return this.dMisl;default:throw new Error(`Unsupported missile type "${e}"`)}}}(r=Yt=Yt||{})[r.Default=0]="Default",r[r.Tunnel=5]="Tunnel",r[r.Railroad=6]="Railroad",r[r.Rock1=7]="Rock1",r[r.Rock2=8]="Rock2",r[r.Water=9]="Water",r[r.Shore=10]="Shore",r[r.Pavement=11]="Pavement",r[r.Dirt=12]="Dirt",r[r.Clear=13]="Clear",r[r.Rough=14]="Rough",r[r.Cliff=15]="Cliff",(r=Kt=Kt||{})[r.Clear=0]="Clear",r[r.Road=1]="Road",r[r.Rock=2]="Rock",r[r.Beach=3]="Beach",r[r.Rough=4]="Rough",r[r.Railroad=5]="Railroad",r[r.Weeds=6]="Weeds",r[r.Water=7]="Water",r[r.Wall=8]="Wall",r[r.Tiberium=9]="Tiberium",r[r.Cliff=10]="Cliff";const Vi=new Map([[Yt.Default,Kt.Clear],[Yt.Clear,Kt.Clear],[Yt.Tunnel,Kt.Cliff],[Yt.Railroad,Kt.Railroad],[Yt.Rock1,Kt.Rock],[Yt.Rock2,Kt.Rock],[Yt.Water,Kt.Water],[Yt.Shore,Kt.Beach],[Yt.Pavement,Kt.Road],[Yt.Dirt,Kt.Road],[Yt.Rough,Kt.Rough],[Yt.Cliff,Kt.Cliff]]);function Hi(e){if(!Vi.has(e))throw new Error(`Unknown terrain type ${e}`);return Vi.get(e)}(r=Jt=Jt||{})[r.Foot=0]="Foot",r[r.Track=1]="Track",r[r.Wheel=2]="Wheel",r[r.Hover=3]="Hover",r[r.Float=4]="Float",r[r.FloatBeach=5]="FloatBeach",r[r.Amphibious=6]="Amphibious",r[r.Winged=7]="Winged";class Gi{constructor(){this.speedModifiers=new Map}readIni(t){return this.buildable=t.getBool("Buildable",!1),[...t.entries.keys()].forEach(e=>{void 0!==Jt[e]&&this.speedModifiers.set(Jt[e],t.getNumber(e))}),this}getSpeedModifier(e){if(e===Jt.Foot&&0===this.speedModifiers.get(Jt.Track))return 0;let t=this.speedModifiers.get(e);return void 0===t&&(t=1),e!==Jt.Track&&e!==Jt.Wheel&&0<t&&(t=1),t}}(r=ei=ei||{})[r.None=0]="None",r[r.Gunfire=1]="Gunfire",r[r.Explode=2]="Explode",r[r.ExplodeAlt=3]="ExplodeAlt",r[r.Fire=4]="Fire",r[r.Electro=5]="Electro",r[r.HeadExplode=6]="HeadExplode",r[r.Nuke=7]="Nuke";class $i{constructor(e){this.rules=e,this.verses=new Map,this.parse()}get name(){return this.rules.name}parse(){this.animList=this.rules.getArray("AnimList"),this.bombDisarm=this.rules.getBool("BombDisarm"),this.bullets=this.rules.getBool("Bullets"),this.causesDelayKill=this.rules.getBool("CausesDelayKill"),this.cellSpread=this.rules.getNumber("CellSpread"),this.conventional=this.rules.getBool("Conventional"),this.culling=this.rules.getBool("Culling"),this.delayKillAtMax=this.rules.getNumber("DelayKillAtMax"),this.delayKillFrames=this.rules.getNumber("DelayKillFrames"),this.electricAssault=this.rules.getBool("ElectricAssault"),this.emEffect=this.rules.getBool("EMEffect"),this.infDeath=this.rules.getEnumNumeric("InfDeath",ei,ei.None),this.ivanBomb=this.rules.getBool("IvanBomb"),this.makesDisguise=this.rules.getBool("MakesDisguise"),this.mindControl=this.rules.getBool("MindControl"),this.nukeMaker=this.rules.getBool("NukeMaker"),this.paralyzes=this.rules.getNumber("Paralyzes"),this.parasite=this.rules.getBool("Parasite"),this.percentAtMax=this.rules.getNumber("PercentAtMax",1),this.proneDamage=this.rules.getNumber("ProneDamage",1),this.psychicDamage=this.rules.getBool("PsychicDamage"),this.radiation=this.rules.getBool("Radiation"),this.rocker=this.rules.getBool("Rocker"),this.sonic=this.rules.getBool("Sonic"),this.temporal=this.rules.getBool("Temporal");let e=this.rules.getFixedArray("Verses");e.forEach((e,t)=>this.verses.set(t,e)),this.wallAbsoluteDestroyer=this.rules.getBool("WallAbsoluteDestroyer"),this.wall=this.rules.getBool("Wall"),this.wood=this.rules.getBool("Wood")}}class qi extends Ii{parse(){super.parse();var e=this.ini.getNumber("ROT",0);let t=this.ini.getNumber("Acceleration");1!==e||t||(t=Number.POSITIVE_INFINITY),t=t||3,this.acceleration=t,this.arcing=this.ini.getBool("Arcing"),this.courseLockDuration=this.ini.getNumber("CourseLockDuration"),this.detonationAltitude=this.ini.getNumber("DetonationAltitude"),this.firersPalette=this.ini.getBool("FirersPalette"),this.flakScatter=this.ini.getBool("FlakScatter"),this.inaccurate=this.ini.getBool("Inaccurate"),this.inviso=this.ini.getBool("Inviso"),this.isAntiAir=this.ini.getBool("AA"),this.isAntiGround=this.ini.getBool("AG",!0),this.level=this.ini.getBool("Level"),this.rot=Ii.iniRotToDegsPerTick(e),this.iniRot=e,this.shadow=this.ini.getBool("Shadow",!0),this.shrapnelWeapon=this.ini.getString("ShrapnelWeapon")||void 0,this.shrapnelCount=this.ini.getNumber("ShrapnelCount"),this.subjectToCliffs=this.ini.getBool("SubjectToCliffs"),this.subjectToElevation=this.ini.getBool("SubjectToElevation"),this.subjectToWalls=this.ini.getBool("SubjectToWalls"),this.vertical=this.ini.getBool("Vertical")}}(r=ti=ti||{})[r.Green=0]="Green",r[r.Yellow=1]="Yellow",r[r.White=2]="White",r[r.Red=3]="Red",r[r.Blue=4]="Blue",(r=ii=ii||{})[r.Statue=0]="Statue",r[r.Aircraft=1]="Aircraft",r[r.Chrono=2]="Chrono",r[r.Hover=3]="Hover",r[r.Infantry=4]="Infantry",r[r.Jumpjet=5]="Jumpjet",r[r.Missile=6]="Missile",r[r.Ship=7]="Ship",r[r.Vehicle=8]="Vehicle";const Xi=new Map([["{4A582746-9839-11d1-B709-00A024DDAFD1}",ii.Aircraft],["{4A582747-9839-11d1-B709-00A024DDAFD1}",ii.Chrono],["{4A582742-9839-11d1-B709-00A024DDAFD1}",ii.Hover],["{4A582744-9839-11d1-B709-00A024DDAFD1}",ii.Infantry],["{92612C46-F71F-11d1-AC9F-006008055BB5}",ii.Jumpjet],["{B7B49766-E576-11d3-9BD9-00104B972FE8}",ii.Missile],["{2BEA74E1-7CCA-11d3-BE14-00104B62A16C}",ii.Ship],["{4A582741-9839-11d1-B709-00A024DDAFD1}",ii.Vehicle]]),Zi=new Map([[ii.Infantry,Jt.Foot],[ii.Ship,Jt.Float],[ii.Hover,Jt.Hover],[ii.Jumpjet,Jt.Winged],[ii.Aircraft,Jt.Winged],[ii.Missile,Jt.Winged]]);(r=si=si||{})[r.Amphibious=0]="Amphibious",r[r.AmphibiousCrusher=1]="AmphibiousCrusher",r[r.AmphibiousDestroyer=2]="AmphibiousDestroyer",r[r.Crusher=3]="Crusher",r[r.CrusherAll=4]="CrusherAll",r[r.Destroyer=5]="Destroyer",r[r.Fly=6]="Fly",r[r.Infantry=7]="Infantry",r[r.InfantryDestroyer=8]="InfantryDestroyer",r[r.Normal=9]="Normal",r[r.Subterranean=10]="Subterranean",r[r.Water=11]="Water",(r=ri=ri||{})[r.None=0]="None",r[r.Flak=1]="Flak",r[r.Plate=2]="Plate",r[r.Light=3]="Light",r[r.Medium=4]="Medium",r[r.Heavy=5]="Heavy",r[r.Wood=6]="Wood",r[r.Steel=7]="Steel",r[r.Concrete=8]="Concrete",r[r.Special_1=9]="Special_1",r[r.Special_2=10]="Special_2",(r=ai=ai||{})[r.LandOk=0]="LandOk",r[r.LandNotOk=1]="LandNotOk",r[r.LandSecondary=2]="LandSecondary",(r=ni=ni||{})[r.UnderwaterNever=0]="UnderwaterNever",r[r.UnderwaterSecondary=1]="UnderwaterSecondary",r[r.UnderwaterOnly=2]="UnderwaterOnly",r[r.OrganicSecondary=3]="OrganicSecondary",r[r.SealSpecial=4]="SealSpecial",r[r.NavalAll=5]="NavalAll",r[r.NavalNone=6]="NavalNone",(r=oi=oi||{})[r.Primary=0]="Primary",r[r.Secondary=1]="Secondary",r[r.DeathWeapon=2]="DeathWeapon",(r=hi=hi||{})[r.FASTER=0]="FASTER",r[r.STRONGER=1]="STRONGER",r[r.FIREPOWER=2]="FIREPOWER",r[r.SCATTER=3]="SCATTER",r[r.ROF=4]="ROF",r[r.SIGHT=5]="SIGHT",r[r.SELF_HEAL=6]="SELF_HEAL",r[r.CLOAK=7]="CLOAK",r[r.EXPLODES=8]="EXPLODES",r[r.RADAR_INVISIBLE=9]="RADAR_INVISIBLE",r[r.SENSORS=10]="SENSORS",r[r.FEARLESS=11]="FEARLESS",r[r.C4=12]="C4",r[r.GUARD_AREA=13]="GUARD_AREA",r[r.CRUSHER=14]="CRUSHER",(r=li=li||{})[r.None=0]="None",r[r.Normal=1]="Normal",r[r.Strong=2]="Strong";class Qi{static reverseSinTableLookup(e,t,i,s){for(;t<=i;){var r=Math.floor((t+i)/2),a=this.SIN_TABLE[r];if(a===e)return r;(s?e<a:a<e)?t=r+1:i=r-1}return Math.abs(e-this.SIN_TABLE[t])<Math.abs(e-this.SIN_TABLE[i])?t:i}static pow(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||Number.isSafeInteger(e)&&Number.isSafeInteger(t))return e**t;if(!Number.isSafeInteger(t))throw new Error("Exponent must be a safe integer");return Math.floor(e*this.EXP_10_PRECISION)**t/this.EXP_10_PRECISION**t}static sqrt(e){if(0===e)return 0;var t;let i=e/3;for(;t=i,i=(e/i+i)/2,5e-15<Math.abs(t-i););return i}static sin(e){if(!Number.isFinite(e))return NaN;if(!e)return e;e=e/(2*Math.PI)-Math.floor(e/(2*Math.PI)),e=Math.floor(e*this.SIN_TABLE.length);return this.SIN_TABLE[e]}static cos(e){return this.sin(e+Math.PI/2)}static asin(e){if(!z(e,-1,1))return NaN;if(!e)return 0;let t;var i=this.SIN_TABLE.length;return t=0<e?2*Math.PI*this.reverseSinTableLookup(e,0,i/4,!1)/i:Math.PI-2*Math.PI*this.reverseSinTableLookup(e,i/2,.75*i,!0)/i,t}static acos(e){return Math.PI/2-this.asin(e)}static atan2(e,t){if(Number.isNaN(t)||Number.isNaN(e))return NaN;let i;return i=Number.isFinite(e)||Number.isFinite(t)?Number.isFinite(t)&&0!==e?Number.isFinite(e)&&0!==t?this.atan2FiniteNonZero(e,t):this.signIncZero(e)*Math.PI*.5:this.signIncZero(e)*(this.signIncZero(t)<0?Math.PI:0):Math.sign(e)*Math.PI*(0<Math.sign(t)?.25:.75),i}static atan2FiniteNonZero(e,t){var i=Math.abs(t),s=Math.abs(e),r=Math.min(i,s)/Math.max(i,s),a=r*r;let n=((-.0464964749*a+.15931422)*a-.327622764)*a*r+r;return i<s&&(n=Math.PI/2-n),t<0&&(n=Math.PI-n),e<0&&(n=-n),n}static signIncZero(e){return e===-1/0||1/e<0?-1:1}}Qi.PRECISION=6,Qi.EXP_10_PRECISION=10**Qi.PRECISION,Qi.SIN_TABLE=[0,.004848117819001859,.009696121685978396,.014543897651582654,.01939133177182437,.024238310110748135,.0290847187431114,.03393044375706223,.03877537125681671,.043619387365336,.04846237822700296,.05330423001029823,.05814482891047582,.06298406115223795,.06782181299240934,.0726579707226106,.07749242067193093,.08232504920959989,.08715574274765817,.09198438774362744,.09681087070317909,.10163507818280187,.10645689679246824,.11127621319829964,.11609291412523022,.12090688635966935,.12571801675216268,.13052619222005157,.13533129975013108,.14013322640130627,.14493185930724672,.1497270856790396,.15451879280784048,.15930686806752256,.16409119891732396,.1688716729044928,.17364817766693033,.17842060093583212,.18318883053832663,.18795275440011186,.19271226054808968,.19746723711299752,.20221757233203794,.20696315455150538,.2117038722294107,.21643961393810288,.22117026836688775,.2258957243246448,.23061587074244014,.2353305966761376,.24003979130900588,.2447433439543238,.24944114405798126,.25413308120107847,.25881904510252074,.26349892562161076,.2681726127606373,.272839996667461,.27750096763809573,.28215541611928774,.2868032327110902,.29144430816943495,.2960785334086999,.3007057995042731,.3053259976951131,.30993901938630514,.31454475615161365,.31914309973603083,.323733942058321,.328317175213561,.33289269147567657,.3374603832999741,.3420201433256687,.34657186437840753,.3511154394727888,.3556507618148765,.3601777248047104,.36469622203881186,.3692061473126844,.3737073946233105,.3781998581716425,.3826834323650898,.3871580118200006,.3916234913641391,.3960797660391568,.4005267311030606,.4049642820326736,.4093923145260926,.4138107245051391,.4182194081178064,.42261826174069944,.4270071819814715,.4313860656812534,.4357548099170794,.4401133120043048,.44446146949902104,.4487991802004621,.4531263421534082,.4574428536505808,.4617486132350339,.46604351970253877,.4703274721039625,.4746003697476404,.4788621122017435,.4831125992966384,.48735173112724234,.49157940805537054,.49579553071207916,.49999999999999994,.5041927170956704,.5083735834518556,.5125425007998652,.5166993711518628,.5208440968031697,.5249765803345602,.5290967246145525,.5332044328016912,.5372996083468239,.5413821549953696,.5454519767895825,.549508978070806,.5535530634817223,.5575841379685927,.5616021067834929,.5656068754865385,.5695983499481065,.573576436351046,.5775410411928851,.5814920712880266,.5854294337699405,.5893530360933448,.593262786036382,.5971585917027862,.6010403615240428,.6049080042615417,.6087614290087207,.6126005451932028,.6164252625789254,.62023549126826,.6240311417041269,.6278121246720986,.6315783513024975,.6353297330724851,.6390661818081416,.6427876096865393,.6464939292378065,.6501850533471834,.6538608952570697,.6575213685690636,.6611663872459932,.6647958656139378,.6684097183642425,.6720078605555224,.6755902076156601,.6791566753437932,.6827071799122926,.6862416378687335,.6897599661378576,.6932620820235242,.696747903210655,.7002173477671685,.7036703341459059,.7071067811865475,.710526608117521,.713929734557899,.7173160805192894,.7206855664077146,.7240381130254825,.7273736415730487,.7306920736508674,.7339933312612352,.7372773368101241,.7405440131090046,.7437932833766612,.747025071240996,.7502393007408245,.7534358963276606,.7566147828674927,.7597758856425494,.7629191303530553,.766044443118978,.7691517504817651,.7722409794060692,.7753120572814658,.7783649119241599,.7813994715786823,.7844156649195757,.7874134210530723,.7903926695187593,.7933533402912352,.7962953637817558,.7992186708398696,.8021231927550437,.8050088612582783,.8078756085237111,.8107233671702122,.8135520702629676,.8163616513150519,.8191520442889918,.821923183598318,.8246750041091067,.8274074411415104,.8301204304712788,.8328139083312671,.8354878114129364,.8381420768678404,.8407766423091032,.8433914458128856,.845986425919841,.848561521636559,.8511166724369997,.8536518182639162,.8561668995302665,.8586618571206132,.8611366323925137,.8635911671778986,.8660254037844386,.8684392849969005,.870832754078492,.8732057547721958,.8755582313020908,.8778901283746645,.8802013911801111,.8824919653936212,.8847617971766577,.8870108331782216,.8892390205361062,.8914463068781385,.8936326403234122,.8957979694835052,.8979422434636881,.9000654118641211,.9021674247810376,.9042482328079179,.9063077870366499,.9083460390586793,.9103629409661466,.9123584453530141,.9143325053161794,.9162850744565779,.918216106880274,.9201255571995389,.9220133805339185,.9238795325112867,.9257239692688903,.9275466474543786,.9293475242268224,.9311265572577219,.9328837047320004,.9346189253489884,.9363321783233931,.9380234233862578,.9396926207859083,.9413397312888874,.942964716180876,.9445675372676047,.9461481568757504,.947706537853822,.9492426435730339,.9507564379281666,.9522478853384153,.9537169507482269,.955163599628123,.9565877979755122,.9579895123154889,.9593687097016201,.9607253577167205,.9620594244736131,.9633708786158803,.9646596893185995,.9659258262890683,.9671692597675166,.9683899605278059,.969587899878116,.97076304966162,.9719153822571454,.9730448705798238,.9741514880817275,.9752352087524931,.9762960071199334,.9773338582506355,.9783487377505475,.9793406217655515,.980309486982024,.9812553106273847,.9821780704706308,.98307774482286,.9839543125377807,.984807753012208,.9856380461865492,.9864451725452739,.987229113117374,.987989849476809,.9887273637429388,.9894416385809445,.9901326572022359,.9908004033648453,.9914448613738104,.9920660160815423,.9926638528881819,.993238357741943,.9937895171394426,.9943173181260184,.9948217482960331,.9953027957931658,.9957604493106914,.9961946980917455,.9966055319295779,.996992941167792,.9973569167005722,.9976974499728977,.9980145329807433,.9983081582712682,.9985783189429907,.9988250086459504,.9990482215818578,.99924795250423,.9994241967185149,.9995769500822006,.9997062090049132,.9998119704485015,.9998942319271075,.9999529915072262,.9999882478077495,1,.9999882478077495,.9999529915072262,.9998942319271075,.9998119704485015,.9997062090049132,.9995769500822006,.9994241967185149,.99924795250423,.9990482215818578,.9988250086459504,.9985783189429907,.9983081582712682,.9980145329807433,.9976974499728977,.9973569167005722,.996992941167792,.9966055319295779,.9961946980917455,.9957604493106914,.9953027957931658,.9948217482960331,.9943173181260184,.9937895171394426,.993238357741943,.9926638528881819,.9920660160815423,.9914448613738105,.9908004033648453,.9901326572022359,.9894416385809446,.9887273637429388,.987989849476809,.987229113117374,.9864451725452739,.9856380461865492,.984807753012208,.9839543125377807,.98307774482286,.9821780704706307,.9812553106273847,.9803094869820241,.9793406217655516,.9783487377505476,.9773338582506356,.9762960071199334,.9752352087524931,.9741514880817276,.9730448705798238,.9719153822571455,.9707630496616201,.969587899878116,.9683899605278059,.9671692597675166,.9659258262890683,.9646596893185995,.9633708786158803,.9620594244736133,.9607253577167205,.9593687097016202,.9579895123154889,.9565877979755123,.9551635996281231,.9537169507482269,.9522478853384153,.9507564379281666,.949242643573034,.9477065378538221,.9461481568757505,.9445675372676048,.942964716180876,.9413397312888873,.9396926207859084,.9380234233862579,.9363321783233931,.9346189253489885,.9328837047320006,.9311265572577219,.9293475242268225,.9275466474543786,.9257239692688904,.9238795325112867,.9220133805339185,.920125557199539,.918216106880274,.916285074456578,.9143325053161794,.9123584453530141,.9103629409661467,.9083460390586793,.90630778703665,.904248232807918,.9021674247810377,.9000654118641213,.8979422434636883,.8957979694835051,.8936326403234123,.8914463068781386,.8892390205361062,.8870108331782218,.8847617971766579,.8824919653936212,.8802013911801111,.8778901283746644,.8755582313020909,.8732057547721958,.8708327540784921,.8684392849969006,.8660254037844387,.8635911671778987,.8611366323925138,.858661857120613,.8561668995302665,.8536518182639163,.8511166724369997,.8485615216365591,.8459864259198412,.8433914458128856,.8407766423091031,.8381420768678404,.8354878114129364,.8328139083312672,.8301204304712789,.8274074411415107,.8246750041091069,.8219231835983182,.819152044288992,.8163616513150518,.8135520702629675,.8107233671702123,.8078756085237112,.8050088612582784,.802123192755044,.7992186708398695,.7962953637817556,.7933533402912352,.7903926695187593,.7874134210530723,.7844156649195758,.7813994715786824,.7783649119241601,.775312057281466,.7722409794060693,.769151750481765,.766044443118978,.7629191303530551,.7597758856425494,.756614782867493,.7534358963276608,.7502393007408243,.7470250712409959,.7437932833766611,.7405440131090045,.7372773368101241,.7339933312612353,.7306920736508675,.7273736415730488,.7240381130254827,.7206855664077148,.7173160805192896,.713929734557899,.710526608117521,.7071067811865476,.703670334145906,.7002173477671687,.6967479032106549,.6932620820235241,.6897599661378576,.6862416378687336,.6827071799122926,.6791566753437933,.6755902076156604,.6720078605555225,.6684097183642426,.6647958656139381,.6611663872459935,.6575213685690636,.6538608952570697,.6501850533471835,.6464939292378067,.6427876096865395,.6390661818081418,.635329733072485,.6315783513024975,.6278121246720986,.6240311417041269,.6202354912682602,.6164252625789255,.612600545193203,.6087614290087209,.6049080042615419,.6010403615240432,.5971585917027862,.593262786036382,.5893530360933449,.5854294337699406,.5814920712880268,.5775410411928852,.5735764363510459,.5695983499481064,.5656068754865385,.5616021067834929,.5575841379685929,.5535530634817224,.5495089780708062,.5454519767895827,.5413821549953699,.5372996083468241,.5332044328016912,.5290967246145525,.5249765803345602,.5208440968031698,.516699371151863,.5125425007998654,.5083735834518555,.5041927170956703,.49999999999999994,.49579553071207916,.49157940805537065,.48735173112724245,.48311259929663863,.4788621122017437,.47460036974764064,.47032747210396275,.46604351970253877,.4617486132350339,.45744285365058085,.4531263421534083,.44879918020046233,.4444614694990212,.4401133120043047,.43575480991707927,.43138606568125343,.4270071819814714,.4226182617406995,.4182194081178065,.4138107245051393,.40939231452609276,.4049642820326738,.40052673110306086,.3960797660391572,.39162349136413904,.38715801182000065,.3826834323650899,.37819985817164264,.3737073946233107,.3692061473126843,.36469622203881175,.3601777248047104,.3556507618148765,.35111543947278884,.34657186437840765,.3420201433256689,.3374603832999743,.33289269147567685,.32831717521356135,.3237339420583214,.31914309973603083,.3145447561516137,.30993901938630525,.30532599769511326,.30070579950427334,.29607853340870016,.2914443081694349,.2868032327110902,.28215541611928774,.2775009676380958,.2728399966674611,.26817261276063753,.263498925621611,.258819045102521,.2541330812010788,.24944114405798165,.24474334395432376,.24003979130900596,.2353305966761377,.23061587074244033,.225895724324645,.22117026836688802,.21643961393810274,.21170387222941067,.20696315455150538,.20221757233203796,.19746723711299763,.19271226054808982,.18795275440011205,.18318883053832688,.17842060093583242,.17364817766693072,.16887167290449276,.16409119891732402,.15930686806752267,.15451879280784062,.1497270856790398,.14493185930724697,.14013322640130613,.135331299750131,.13052619222005157,.12571801675216274,.12090688635966945,.11609291412523036,.11127621319829985,.1064568967924685,.10163507818280217,.09681087070317945,.09198438774362741,.0871557427476582,.08232504920959997,.07749242067193107,.07265797072261079,.0678218129924096,.06298406115223781,.05814482891047573,.0533042300102982,.04846237822700297,.04361938736533607,.038775371256816835,.03393044375706242,.029084718743111644,.02423831011074843,.01939133177182472,.014543897651583058,.009696121685978408,.004848117819001927,12246467991473532e-32,-.004848117819001238,-.009696121685978163,-.01454389765158237,-.019391331771824474,-.02423831011074774,-.029084718743111398,-.03393044375706173,-.03877537125681659,-.04361938736533583,-.048462378227003174,-.05330423001029795,-.05814482891047593,-.06298406115223758,-.06782181299240934,-.07265797072261056,-.07749242067193128,-.08232504920959974,-.08715574274765794,-.09198438774362716,-.09681087070317876,-.10163507818280193,-.10645689679246781,-.1112762131982996,-.11609291412523012,-.12090688635966965,-.1257180167521625,-.13052619222005177,-.13533129975013078,-.14013322640130632,-.14493185930724675,-.14972708567904,-.1545187928078404,-.15930686806752198,-.16409119891732377,-.16887167290449254,-.17364817766693047,-.17842060093583176,-.18318883053832663,-.1879527544001114,-.1927122605480896,-.19746723711299738,-.20221757233203816,-.20696315455150513,-.21170387222941087,-.21643961393810252,-.2211702683668878,-.22589572432464475,-.23061587074244053,-.23533059667613745,-.2400397913090053,-.2447433439543235,-.24944114405798098,-.2541330812010786,-.25881904510252035,-.2634989256216107,-.26817261276063686,-.2728399966674609,-.27750096763809556,-.2821554161192879,-.28680323271108993,-.29144430816943506,-.29607853340869994,-.30070579950427306,-.30532599769511304,-.3099390193863046,-.3145447561516135,-.3191430997360306,-.3237339420583211,-.3283171752135607,-.33289269147567657,-.3374603832999737,-.34202014332566866,-.3465718643784074,-.35111543947278906,-.35565076181487626,-.36017772480471055,-.3646962220388115,-.3692061473126845,-.3737073946233105,-.3781998581716428,-.38268343236508967,-.38715801182000004,-.3916234913641388,-.39607976603915657,-.40052673110306064,-.4049642820326732,-.40939231452609254,-.41381072450513867,-.4182194081178062,-.4226182617406993,-.4270071819814716,-.4313860656812532,-.43575480991707943,-.4401133120043045,-.444461469499021,-.4487991802004621,-.4531263421534085,-.4574428536505806,-.46174861323503374,-.46604351970253854,-.47032747210396214,-.4746003697476404,-.47886211220174313,-.4831125992966384,-.4873517311272422,-.4915794080553708,-.49579553071207894,-.5000000000000001,-.50419271709567,-.5083735834518556,-.5125425007998652,-.5166993711518633,-.5208440968031696,-.5249765803345596,-.5290967246145523,-.533204432801691,-.5372996083468239,-.5413821549953693,-.5454519767895825,-.5495089780708056,-.5535530634817222,-.5575841379685926,-.5616021067834931,-.5656068754865384,-.5695983499481065,-.5735764363510458,-.577541041192885,-.5814920712880266,-.5854294337699408,-.5893530360933448,-.5932627860363815,-.597158591702786,-.6010403615240426,-.6049080042615417,-.6087614290087203,-.6126005451932028,-.6164252625789249,-.6202354912682599,-.6240311417041268,-.6278121246720987,-.6315783513024973,-.6353297330724852,-.6390661818081416,-.6427876096865393,-.6464939292378065,-.6501850533471829,-.6538608952570695,-.6575213685690635,-.6611663872459933,-.6647958656139376,-.6684097183642425,-.6720078605555221,-.6755902076156601,-.6791566753437931,-.6827071799122927,-.6862416378687334,-.6897599661378577,-.693262082023524,-.696747903210655,-.7002173477671685,-.7036703341459061,-.7071067811865475,-.7105266081175206,-.7139297345578989,-.7173160805192892,-.7206855664077146,-.7240381130254823,-.7273736415730487,-.7306920736508671,-.7339933312612352,-.737277336810124,-.7405440131090048,-.743793283376661,-.747025071240996,-.7502393007408242,-.7534358963276607,-.7566147828674927,-.7597758856425493,-.7629191303530554,-.7660444431189779,-.7691517504817651,-.7722409794060688,-.7753120572814659,-.7783649119241597,-.7813994715786822,-.7844156649195754,-.7874134210530722,-.7903926695187589,-.7933533402912349,-.7962953637817558,-.79921867083987,-.8021231927550437,-.8050088612582785,-.8078756085237111,-.8107233671702119,-.8135520702629674,-.8163616513150515,-.8191520442889916,-.8219231835983181,-.8246750041091064,-.8274074411415104,-.830120430471279,-.8328139083312671,-.8354878114129365,-.8381420768678401,-.8407766423091032,-.8433914458128855,-.8459864259198411,-.8485615216365587,-.8511166724369996,-.8536518182639165,-.8561668995302664,-.8586618571206132,-.8611366323925135,-.8635911671778986,-.8660254037844385,-.8684392849969005,-.8708327540784918,-.8732057547721956,-.8755582313020905,-.8778901283746643,-.8802013911801112,-.8824919653936215,-.8847617971766578,-.8870108331782218,-.889239020536106,-.8914463068781383,-.8936326403234122,-.8957979694835049,-.897942243463688,-.9000654118641208,-.9021674247810375,-.9042482328079179,-.90630778703665,-.9083460390586792,-.9103629409661468,-.912358445353014,-.9143325053161795,-.9162850744565778,-.918216106880274,-.9201255571995388,-.9220133805339183,-.9238795325112865,-.9257239692688903,-.9275466474543786,-.9293475242268223,-.9311265572577219,-.9328837047320003,-.9346189253489884,-.9363321783233929,-.9380234233862578,-.9396926207859082,-.9413397312888873,-.9429647161808761,-.9445675372676049,-.9461481568757504,-.9477065378538222,-.9492426435730339,-.9507564379281666,-.9522478853384153,-.9537169507482267,-.9551635996281229,-.956587797975512,-.9579895123154888,-.9593687097016201,-.9607253577167205,-.9620594244736131,-.9633708786158804,-.9646596893185994,-.9659258262890683,-.9671692597675166,-.9683899605278059,-.9695878998781159,-.97076304966162,-.9719153822571452,-.9730448705798238,-.9741514880817276,-.975235208752493,-.9762960071199334,-.9773338582506355,-.9783487377505475,-.9793406217655514,-.980309486982024,-.9812553106273846,-.9821780704706307,-.98307774482286,-.9839543125377805,-.984807753012208,-.9856380461865493,-.9864451725452739,-.9872291131173742,-.9879898494768089,-.9887273637429387,-.9894416385809445,-.9901326572022358,-.9908004033648452,-.9914448613738104,-.9920660160815423,-.9926638528881818,-.993238357741943,-.9937895171394426,-.9943173181260184,-.994821748296033,-.9953027957931658,-.9957604493106913,-.9961946980917455,-.9966055319295779,-.996992941167792,-.9973569167005722,-.9976974499728977,-.9980145329807433,-.9983081582712682,-.9985783189429907,-.9988250086459504,-.9990482215818578,-.99924795250423,-.9994241967185149,-.9995769500822006,-.9997062090049132,-.9998119704485015,-.9998942319271076,-.9999529915072262,-.9999882478077495,-1,-.9999882478077495,-.9999529915072262,-.9998942319271076,-.9998119704485015,-.9997062090049132,-.9995769500822006,-.9994241967185149,-.99924795250423,-.9990482215818578,-.9988250086459504,-.9985783189429907,-.9983081582712682,-.9980145329807433,-.9976974499728977,-.9973569167005724,-.996992941167792,-.9966055319295779,-.9961946980917455,-.9957604493106914,-.9953027957931658,-.9948217482960331,-.9943173181260185,-.9937895171394426,-.993238357741943,-.9926638528881819,-.9920660160815424,-.9914448613738105,-.9908004033648453,-.9901326572022358,-.9894416385809446,-.9887273637429387,-.987989849476809,-.9872291131173742,-.986445172545274,-.9856380461865493,-.9848077530122081,-.9839543125377807,-.9830777448228601,-.9821780704706308,-.9812553106273846,-.9803094869820241,-.9793406217655515,-.9783487377505476,-.9773338582506355,-.9762960071199335,-.9752352087524931,-.9741514880817276,-.9730448705798239,-.9719153822571454,-.9707630496616201,-.969587899878116,-.968389960527806,-.9671692597675167,-.9659258262890684,-.9646596893185995,-.9633708786158806,-.9620594244736133,-.9607253577167206,-.9593687097016202,-.9579895123154889,-.9565877979755121,-.955163599628123,-.9537169507482268,-.9522478853384154,-.9507564379281668,-.949242643573034,-.9477065378538223,-.9461481568757506,-.944567537267605,-.9429647161808762,-.9413397312888874,-.9396926207859083,-.9380234233862579,-.936332178323393,-.9346189253489885,-.9328837047320004,-.9311265572577221,-.9293475242268224,-.9275466474543788,-.9257239692688904,-.9238795325112866,-.9220133805339186,-.9201255571995389,-.9182161068802742,-.9162850744565779,-.9143325053161796,-.9123584453530141,-.9103629409661469,-.9083460390586794,-.9063077870366503,-.9042482328079181,-.9021674247810376,-.9000654118641209,-.8979422434636882,-.895797969483505,-.8936326403234123,-.8914463068781384,-.8892390205361063,-.887010833178222,-.8847617971766579,-.8824919653936216,-.8802013911801113,-.8778901283746645,-.8755582313020907,-.8732057547721959,-.870832754078492,-.8684392849969007,-.8660254037844386,-.8635911671778989,-.8611366323925137,-.8586618571206134,-.8561668995302666,-.8536518182639167,-.8511166724369998,-.848561521636559,-.8459864259198413,-.8433914458128857,-.8407766423091034,-.8381420768678404,-.8354878114129367,-.8328139083312672,-.8301204304712791,-.8274074411415107,-.8246750041091067,-.8219231835983183,-.8191520442889918,-.8163616513150517,-.8135520702629676,-.8107233671702121,-.8078756085237113,-.8050088612582788,-.802123192755044,-.7992186708398701,-.796295363781756,-.7933533402912352,-.7903926695187591,-.7874134210530724,-.7844156649195756,-.7813994715786825,-.7783649119241599,-.7753120572814661,-.7722409794060691,-.7691517504817653,-.7660444431189781,-.7629191303530556,-.7597758856425495,-.7566147828674927,-.753435896327661,-.7502393007408246,-.7470250712409963,-.7437932833766612,-.740544013109005,-.7372773368101242,-.7339933312612357,-.7306920736508676,-.7273736415730492,-.7240381130254828,-.7206855664077145,-.7173160805192891,-.7139297345578991,-.7105266081175208,-.7071067811865477,-.7036703341459063,-.7002173477671687,-.6967479032106556,-.6932620820235246,-.6897599661378577,-.6862416378687334,-.6827071799122926,-.679156675343793,-.6755902076156605,-.6720078605555223,-.6684097183642427,-.6647958656139378,-.6611663872459935,-.6575213685690637,-.6538608952570701,-.6501850533471836,-.6464939292378064,-.6427876096865396,-.6390661818081416,-.6353297330724854,-.6315783513024976,-.627812124672099,-.624031141704127,-.6202354912682606,-.6164252625789255,-.6126005451932034,-.6087614290087209,-.6049080042615417,-.6010403615240425,-.5971585917027863,-.5932627860363818,-.589353036093345,-.585429433769941,-.5814920712880269,-.5775410411928856,-.5735764363510465,-.5695983499481065,-.5656068754865391,-.561602106783493,-.5575841379685926,-.5535530634817225,-.5495089780708059,-.5454519767895828,-.5413821549953696,-.5372996083468242,-.5332044328016913,-.5290967246145529,-.5249765803345603,-.5208440968031696,-.5166993711518632,-.5125425007998651,-.5083735834518559,-.5041927170956704,-.5000000000000004,-.49579553071207927,-.49157940805537115,-.48735173112724256,-.48311259929663913,-.4788621122017438,-.47460036974764036,-.4703274721039621,-.4660435197025389,-.46174861323503363,-.45744285365058096,-.4531263421534088,-.44879918020046244,-.4444614694990217,-.4401133120043052,-.43575480991708015,-.4313860656812539,-.42700718198147153,-.4226182617406992,-.4182194081178066,-.413810724505139,-.40939231452609287,-.40496428203267354,-.400526731103061,-.3960797660391569,-.39162349136413954,-.38715801182000076,-.3826834323650904,-.37819985817164276,-.3737073946233104,-.3692061473126848,-.36469622203881186,-.3601777248047109,-.3556507618148766,-.3511154394727894,-.34657186437840776,-.34202014332566943,-.3374603832999744,-.3328926914756765,-.32831717521356063,-.32373394205832107,-.31914309973603056,-.3145447561516138,-.3099390193863049,-.30532599769511337,-.30070579950427384,-.2960785334087003,-.29144430816943584,-.2868032327110907,-.28215541611928785,-.2775009676380955,-.2728399966674612,-.2681726127606372,-.2634989256216111,-.2588190451025207,-.2541330812010789,-.24944114405798135,-.24474334395432432,-.24003979130900607,-.23533059667613823,-.23061587074244044,-.2258957243246447,-.22117026836688813,-.21643961393810288,-.21170387222941123,-.2069631545515055,-.20221757233203852,-.19746723711299774,-.19271226054809037,-.1879527544001122,-.18318883053832655,-.17842060093583256,-.1736481776669304,-.16887167290449245,-.16409119891732413,-.15930686806752234,-.15451879280784075,-.14972708567904036,-.1449318593072471,-.14013322640130713,-.13533129975013158,-.13052619222005168,-.1257180167521624,-.12090688635966958,-.11609291412523004,-.11127621319829996,-.10645689679246818,-.10163507818280229,-.09681087070317913,-.09198438774362797,-.08715574274765832,-.08232504920960054,-.0774924206719312,-.07265797072261047,-.06782181299240972,-.06298406115223794,-.0581448289104763,-.05330423001029832,-.04846237822700354,-.043619387365336194,-.038775371256817404,-.03393044375706254,-.02908471874311221,-.02423831011074855,-.019391331771824397,-.014543897651582293,-.009696121685978531,-.004848117819001606];r=__webpack_require__(949);class Yi extends r.Quaternion{setFromEuler(e,t){if(!e||!e.isEuler)throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var i=e.x,s=e.y,r=e.z,a=e.order,n=Qi.cos(i/2),o=Qi.cos(s/2),e=Qi.cos(r/2),i=Qi.sin(i/2),s=Qi.sin(s/2),r=Qi.sin(r/2);return"XYZ"===a?(this._x=i*o*e+n*s*r,this._y=n*s*e-i*o*r,this._z=n*o*r+i*s*e,this._w=n*o*e-i*s*r):"YXZ"===a?(this._x=i*o*e+n*s*r,this._y=n*s*e-i*o*r,this._z=n*o*r-i*s*e,this._w=n*o*e+i*s*r):"ZXY"===a?(this._x=i*o*e-n*s*r,this._y=n*s*e+i*o*r,this._z=n*o*r+i*s*e,this._w=n*o*e-i*s*r):"ZYX"===a?(this._x=i*o*e-n*s*r,this._y=n*s*e+i*o*r,this._z=n*o*r-i*s*e,this._w=n*o*e+i*s*r):"YZX"===a?(this._x=i*o*e+n*s*r,this._y=n*s*e+i*o*r,this._z=n*o*r-i*s*e,this._w=n*o*e-i*s*r):"XZY"===a&&(this._x=i*o*e-n*s*r,this._y=n*s*e-i*o*r,this._z=n*o*r+i*s*e,this._w=n*o*e+i*s*r),!1!==t&&this.onChangeCallback(),this}setFromAxisAngle(e,t){var i=t/2,t=Qi.sin(i);return this._x=e.x*t,this._y=e.y*t,this._z=e.z*t,this._w=Qi.cos(i),this.onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,i=t[0],s=t[4],r=t[8],a=t[1],n=t[5],o=t[9],h=t[2],l=t[6],c=t[10],u=i+n+c,d;return 0<u?(d=.5/Qi.sqrt(u+1),this._w=.25/d,this._x=(l-o)*d,this._y=(r-h)*d,this._z=(a-s)*d):n<i&&c<i?(d=2*Qi.sqrt(1+i-n-c),this._w=(l-o)/d,this._x=.25*d,this._y=(s+a)/d,this._z=(r+h)/d):c<n?(d=2*Qi.sqrt(1+n-i-c),this._w=(r-h)/d,this._x=(s+a)/d,this._y=.25*d,this._z=(o+l)/d):(d=2*Qi.sqrt(1+c-i-n),this._w=(a-s)/d,this._x=(r+h)/d,this._y=(o+l)/d,this._z=.25*d),this.onChangeCallback(),this}length(){return Qi.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);var i=this._x,s=this._y,r=this._z,a=this._w;let n=a*e._w+i*e._x+s*e._y+r*e._z;if(n<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,n=-n):this.copy(e),1<=n)return this._w=a,this._x=i,this._y=s,this._z=r,this;var o=1-n*n;if(o<=Number.EPSILON){var h=1-t;return this._w=h*a+t*this._w,this._x=h*i+t*this._x,this._y=h*s+t*this._y,this._z=h*r+t*this._z,this.normalize()}e=Qi.sqrt(o),h=Qi.atan2(e,n),o=Qi.sin((1-t)*h)/e,e=Qi.sin(t*h)/e;return this._w=a*o+this._w*e,this._x=i*o+this._x*e,this._y=s*o+this._y*e,this._z=r*o+this._z*e,this.onChangeCallback(),this}}var Ki,Ji,es,ts,is,r=__webpack_require__(949);class ss extends r.Vector3{applyEuler(e){return e&&e.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(rs.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(rs.setFromAxisAngle(e,t))}length(){return Qi.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}projectOnPlane(e){return as.copy(this).projectOnVector(e),this.sub(as)}reflect(e){return this.sub(as.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){e=this.dot(e)/Qi.sqrt(this.lengthSq()*e.lengthSq());return Qi.acos(W(e,-1,1))}distanceTo(e){return Qi.sqrt(this.distanceToSquared(e))}setFromSpherical(e){var t=Qi.sin(e.phi)*e.radius;return this.x=t*Qi.sin(e.theta),this.y=Qi.cos(e.phi)*e.radius,this.z=t*Qi.cos(e.theta),this}setFromCylindrical(e){return this.x=e.radius*Qi.sin(e.theta),this.y=e.y,this.z=e.radius*Qi.cos(e.theta),this}}const rs=new Yi,as=new ss;(r=Ki=Ki||{})[r.Combat=0]="Combat",r[r.Tech=1]="Tech",r[r.Resource=2]="Resource",r[r.Power=3]="Power",(r=Ji=Ji||{})[r.None=0]="None",r[r.BuildingType=1]="BuildingType",r[r.InfantryType=2]="InfantryType",r[r.UnitType=3]="UnitType",r[r.NavalUnitType=4]="NavalUnitType",r[r.AircraftType=5]="AircraftType";class ns extends Ii{parse(){super.parse(),this.owner=this.ini.getArray("Owner");var e=this.ini.getNumber("AIBasePlanningSide");this.aiBasePlanningSide=-1!==e&&void 0!==Xt[e]?e:void 0,this.requiredHouses=this.ini.getArray("RequiredHouses"),this.forbiddenHouses=this.ini.getArray("ForbiddenHouses"),this.requiresStolenAlliedTech=this.ini.getBool("RequiresStolenAlliedTech"),this.requiresStolenSovietTech=this.ini.getBool("RequiresStolenSovietTech"),this.techLevel=this.ini.getNumber("TechLevel",-1),this.cost=this.ini.getNumber("Cost"),this.points=this.ini.getNumber("Points"),this.power=this.ini.getNumber("Power"),this.powered=this.ini.getBool("Powered"),this.prerequisite=this.ini.getArray("Prerequisite"),this.soylent=this.ini.getNumber("Soylent"),this.crateGoodie=this.ini.getBool("CrateGoodie"),this.buildCat=this.ini.getEnum("BuildCat",Ki,Ki.Combat),this.adjacent=this.ini.getNumber("Adjacent",1),this.baseNormal=this.ini.getBool("BaseNormal",!0),this.buildLimit=this.ini.getNumber("BuildLimit",Number.POSITIVE_INFINITY),this.airRangeBonus=this.ini.getNumber("AirRangeBonus"),this.guardRange=this.ini.getNumber("GuardRange"),this.defaultToGuardArea=this.ini.getBool("DefaultToGuardArea"),this.eligibileForAllyBuilding=this.ini.getBool("EligibileForAllyBuilding"),this.numberImpassableRows=this.ini.getNumber("NumberImpassableRows"),this.bridgeRepairHut=this.ini.getBool("BridgeRepairHut"),this.constructionYard=this.ini.getBool("ConstructionYard"),this.refinery=this.ini.getBool("Refinery"),this.unitRepair=this.ini.getBool("UnitRepair"),this.unitReload=this.ini.getBool("UnitReload"),this.isBaseDefense=this.ini.getBool("IsBaseDefense"),this.superWeapon=this.parseWeaponName(this.ini.getString("SuperWeapon")),this.chargedAnimTime=this.ini.getNumber("ChargedAnimTime");var t=this.ini.getBool("Naval");this.naval=t,this.underwater=this.ini.getBool("Underwater"),this.waterBound=this.ini.getBool("WaterBound"),this.orePurifier=this.ini.getBool("OrePurifier"),this.cloning=this.ini.getBool("Cloning"),this.nukeSilo=this.ini.getBool("NukeSilo"),this.repairable=this.ini.getBool("Repairable",this.type===Bt.Building),this.clickRepairable=this.ini.getBool("ClickRepairable",this.type===Bt.Building),this.unsellable=this.ini.getBool("Unsellable"),this.gdiBarracks=this.ini.getBool("GDIBarracks"),this.nodBarracks=this.ini.getBool("NODBarracks"),this.numberOfDocks=this.ini.getNumber("NumberOfDocks"),this.unitRepair&&!this.numberOfDocks&&(this.numberOfDocks=1),this.factory=this.ini.getEnum("Factory",Ji,Ji.None),this.factory===Ji.UnitType&&t&&(this.factory=Ji.NavalUnitType),this.weaponsFactory=this.ini.getBool("WeaponsFactory"),this.helipad=this.ini.getBool("Helipad"),this.hospital=this.ini.getBool("Hospital"),this.landTargeting=this.ini.getEnumNumeric("LandTargeting",ai,ai.LandOk),this.navalTargeting=this.ini.getEnumNumeric("NavalTargeting",ni,ni.UnderwaterNever),this.tooBigToFitUnderBridge=this.ini.getBool("TooBigToFitUnderBridge",this.type===Bt.Building),this.canBeOccupied=this.ini.getBool("CanBeOccupied"),this.maxNumberOccupants=this.ini.getNumber("MaxNumberOccupants"),this.leaveRubble=this.ini.getBool("LeaveRubble"),this.undeploysInto=this.ini.getString("UndeploysInto"),this.deploysInto=this.ini.getString("DeploysInto"),this.capturable=this.ini.getBool("Capturable"),this.spyable=this.ini.getBool("Spyable"),this.needsEngineer=this.ini.getBool("NeedsEngineer"),this.c4=this.ini.getBool("C4"),this.canC4=this.ini.getBool("CanC4",!0),this.eligibleForDelayKill=this.ini.getBool("EligibleForDelayKill"),this.produceCashStartup=this.ini.getNumber("ProduceCashStartup"),this.produceCashAmount=this.ini.getNumber("ProduceCashAmount"),this.produceCashDelay=this.ini.getNumber("ProduceCashDelay"),this.explosion=this.ini.getArray("Explosion"),this.explodes=this.ini.getBool("Explodes"),this.ifvMode=this.ini.getNumber("IFVMode"),this.turretIndexesByIfvMode=this.parseTurretIndexes(),this.turret=this.ini.getBool("Turret"),this.turretCount=this.ini.getNumber("TurretCount",this.turret?1:0),this.turretAnim=this.ini.getString("TurretAnim"),this.turretAnimIsVoxel=this.ini.getBool("TurretAnimIsVoxel"),this.turretAnimX=this.ini.getNumber("TurretAnimX"),this.turretAnimY=this.ini.getNumber("TurretAnimY"),this.turretAnimZAdjust=this.ini.getNumber("TurretAnimZAdjust"),this.isChargeTurret=this.ini.getBool("IsChargeTurret"),this.overpowerable=this.ini.getBool("Overpowerable"),this.freeUnit=this.ini.getString("FreeUnit"),this.primary=this.parseWeaponName(this.ini.getString("Primary")),this.secondary=this.parseWeaponName(this.ini.getString("Secondary")),this.elitePrimary=this.parseWeaponName(this.ini.getString("ElitePrimary")),this.eliteSecondary=this.parseWeaponName(this.ini.getString("EliteSecondary")),this.weaponCount=this.ini.getNumber("WeaponCount"),this.deathWeapon=this.parseWeaponName(this.ini.getString("DeathWeapon")),this.deathWeaponDamageModifier=this.ini.getNumber("DeathWeaponDamageModifier",1),this.occupyWeapon=this.parseWeaponName(this.ini.getString("OccupyWeapon")),this.eliteOccupyWeapon=this.parseWeaponName(this.ini.getString("EliteOccupyWeapon")),this.veteranAbilities=new Set(this.ini.getEnumArray("VeteranAbilities",hi)),this.eliteAbilities=new Set([...this.veteranAbilities,...this.ini.getEnumArray("EliteAbilities",hi)]),this.selfHealing=this.ini.getBool("SelfHealing"),this.wall=this.ini.getBool("Wall"),this.gate=this.ini.getBool("Gate"),this.armor=this.ini.getEnum("Armor",ri,ri.None,!0),this.strength=Math.floor(this.ini.getNumber("Strength")),this.immune=this.ini.getBool("Immune"),this.immuneToRadiation=this.ini.getBool("ImmuneToRadiation"),this.immuneToPsionics=this.ini.getBool("ImmuneToPsionics"),this.typeImmune=this.ini.getBool("TypeImmune"),this.warpable=this.ini.getBool("Warpable",!0),this.isTilter=this.ini.getBool("IsTilter",!0),this.walkRate=this.ini.getNumber("WalkRate",1),this.idleRate=this.ini.getNumber("IdleRate",0),this.noSpawnAlt=this.ini.getBool("NoSpawnAlt"),this.crusher=this.ini.getBool("Crusher"),this.consideredAircraft=this.ini.getBool("ConsideredAircraft"),this.crashable=this.ini.getBool("Crashable");var i=this.ini.getBool("Landable");this.landable=i,this.airportBound=this.ini.getBool("AirportBound"),this.balloonHover=this.ini.getBool("BalloonHover"),this.hoverAttack=this.ini.getBool("HoverAttack"),this.omniFire=this.ini.getBool("OmniFire"),this.fighter=this.ini.getBool("Fighter"),this.flightLevel=this.ini.getNumber("FlightLevel")||void 0;var s=this.ini.getString("Locomotor"),e=this.type===Bt.Building?ii.Statue:ii.Chrono;if(s?(t=Xi.get(s))?this.locomotor=t:(console.warn(`Object rules "${this.name}" has invalid Locomotor "${s}"`),this.locomotor=e):this.locomotor=e,this.locomotor!==ii.Statue){let e=Zi.get(this.locomotor);void 0===e&&(this.type===Bt.Aircraft||this.consideredAircraft?e=Jt.Winged:this.type===Bt.Vehicle?e=this.crusher?Jt.Track:Jt.Wheel:this.type===Bt.Infantry&&(e=Jt.Foot)),this.speedType=this.ini.getEnum("SpeedType",Jt,e,!0)}e=[ii.Ship,ii.Vehicle,ii.Chrono].includes(this.locomotor)?65:100;this.speed=Ii.iniSpeedToLeptonsPerTick(this.ini.getNumber("Speed"),e),this.movementZone=this.ini.getEnum("MovementZone",si,si.Normal),this.fearless=this.ini.getBool("Fearless"),this.deployer=this.ini.getBool("Deployer"),this.deployFire=this.ini.getBool("DeployFire"),this.deployFireWeapon=this.ini.getNumber("DeployFireWeapon",oi.Secondary),this.undeployDelay=this.ini.getNumber("UndeployDelay"),this.fraidycat=this.ini.getBool("Fraidycat",!1),this.isHuman=!this.ini.getBool("NotHuman"),this.organic=this.type===Bt.Infantry||this.ini.getBool("Organic"),this.occupier=this.ini.getBool("Occupier"),this.engineer=this.ini.getBool("Engineer"),this.ivan=this.ini.getBool("Ivan"),this.civilian=this.ini.getBool("Civilian"),this.agent=this.ini.getBool("Agent"),this.infiltrate=this.ini.getBool("Infiltrate"),this.threatPosed=this.ini.getNumber("ThreatPosed"),this.specialThreatValue=this.ini.getNumber("SpecialThreatValue"),this.canPassiveAquire=this.ini.getBool("CanPassiveAquire",!0),this.canRetaliate=this.ini.getBool("CanRetaliate",!0),this.preventAttackMove=this.ini.getBool("PreventAttackMove"),this.opportunityFire=this.ini.getBool("OpportunityFire"),this.distributedFire=this.ini.getBool("DistributedFire"),this.radialFireSegments=this.ini.getNumber("RadialFireSegments"),this.attackCursorOnFriendlies=this.ini.getBool("AttackCursorOnFriendlies"),this.bombable=this.ini.getBool("Bombable",!0),this.trainable=this.ini.getBool("Trainable",this.type!==Bt.Building),this.crewed=this.ini.getBool("Crewed"),this.parasiteable=this.ini.getBool("Parasiteable",this.type!==Bt.Building),this.suppressionThreshold=this.ini.getNumber("SuppressionThreshold"),this.reselectIfLimboed=this.ini.getBool("ReselectIfLimboed"),this.rejoinTeamIfLimboed=this.ini.getBool("RejoinTeamIfLimboed"),this.weight=this.ini.getNumber("Weight"),this.accelerates=this.ini.getBool("Accelerates",!0),this.accelerationFactor=this.ini.getNumber("AccelerationFactor",.03),this.teleporter=this.ini.getBool("Teleporter"),this.canDisguise=this.ini.getBool("CanDisguise"),this.disguiseWhenStill=this.ini.getBool("DisguiseWhenStill"),this.permaDisguise=this.ini.getBool("PermaDisguise"),this.detectDisguise=this.ini.getBool("DetectDisguise"),this.detectDisguiseRange=this.ini.getNumber("DetectDisguiseRange"),this.cloakable=this.ini.getBool("Cloakable"),this.sensors=this.ini.getBool("Sensors"),this.sensorArray=this.ini.getBool("SensorArray"),this.sensorsSight=this.ini.getNumber("SensorsSight"),this.burstDelay=this.parseBurstDelay(),this.vhpScan=this.ini.getEnum("VHPScan",li,li.None,!0),this.pip=this.ini.getEnum("Pip",ti,ti.Green,!0),this.passengers=this.ini.getNumber("Passengers"),this.gunner=this.ini.getBool("Gunner"),this.ammo=this.ini.getNumber("Ammo",-1),this.initialAmmo=this.ini.getNumber("InitialAmmo",-1),this.manualReload=this.ini.getBool("ManualReload",this.type===Bt.Aircraft),this.storage=this.ini.getNumber("Storage"),this.spawned=this.ini.getBool("Spawned"),this.spawns=this.ini.getString("Spawns"),this.spawnsNumber=this.ini.getNumber("SpawnsNumber"),this.spawnRegenRate=this.ini.getNumber("SpawnRegenRate"),this.spawnReloadRate=this.ini.getNumber("SpawnReloadRate"),this.missileSpawn=this.ini.getBool("MissileSpawn"),this.size=this.ini.getNumber("Size",1),this.sizeLimit=this.ini.getNumber("SizeLimit"),this.sight=Math.min(ns.MAX_SIGHT,this.ini.getNumber("Sight",1)),this.spySat=this.ini.getBool("SpySat"),this.gapGenerator=this.ini.getBool("GapGenerator"),this.gapRadiusInCells=this.ini.getNumber("GapRadiusInCells"),this.psychicDetectionRadius=this.ini.getNumber("PsychicDetectionRadius"),this.hasRadialIndicator=this.ini.getBool("HasRadialIndicator"),this.harvester=this.ini.getBool("Harvester"),this.unloadingClass=this.ini.getString("UnloadingClass"),this.dock=this.ini.getArray("Dock"),this.radar=this.ini.getBool("Radar"),this.radarInvisible=this.ini.getBool("RadarInvisible"),this.revealToAll=this.ini.getBool("RevealToAll"),this.selectable=!(this.type===Bt.Aircraft&&!i)&&this.ini.getBool("Selectable",!0),this.isSelectableCombatant=this.ini.getBool("IsSelectableCombatant"),this.invisibleInGame=this.ini.getBool("InvisibleInGame"),this.moveToShroud=this.ini.getBool("MoveToShroud",this.type!==Bt.Aircraft),this.leadershipRating=this.ini.getNumber("LeadershipRating",5),this.allowedToStartInMultiplayer=this.ini.getBool("AllowedToStartInMultiplayer",!0),this.rot=Ii.iniRotToDegsPerTick(this.ini.getNumber("ROT",0)),this.jumpjetAccel=this.ini.getNumber("JumpJetAccel",2),this.jumpjetClimb=this.ini.getNumber("JumpjetClimb",5),this.jumpjetCrash=this.ini.getNumber("JumpjetCrash",5),this.jumpjetDeviation=this.ini.getNumber("JumpjetDeviation",40),this.jumpjetHeight=this.ini.getNumber("JumpjetHeight",500),this.jumpjetNoWobbles=this.ini.getBool("JumpjetNoWobbles"),this.jumpjetSpeed=this.ini.getNumber("JumpjetSpeed",14),this.jumpjetTurnRate=Ii.iniRotToDegsPerTick(this.ini.getNumber("JumpJetTurnRate",4)),this.jumpjetWobbles=this.ini.getNumber("JumpjetWobbles",.15),this.pitchSpeed=this.ini.getNumber("PitchSpeed",.25),this.pitchAngle=1<=this.pitchSpeed?0:20,this.damageParticleSystems=this.ini.getArray("DamageParticleSystems");i=this.ini.getNumberArray("DamageSmokeOffset",void 0,[0,0,0]);this.damageSmokeOffset=new ss(i[0],i[2]/Math.SQRT2,i[1]),this.minDebris=this.ini.getNumber("MinDebris"),this.maxDebris=this.ini.getNumber("MaxDebris"),this.debrisTypes=this.ini.getArray("DebrisTypes"),this.debrisAnims=this.ini.getArray("DebrisAnims"),this.isLightpost="GALITE"===this.imageName,this.lightVisibility=this.ini.getNumber("LightVisibility",5e3),this.lightIntensity=this.ini.getNumber("LightIntensity"),this.lightRedTint=this.ini.getNumber("LightRedTint",1),this.lightGreenTint=this.ini.getNumber("LightGreenTint",1),this.lightBlueTint=this.ini.getNumber("LightBlueTint",1),this.ambientSound=this.ini.getString("AmbientSound")||void 0,this.createSound=this.ini.getString("CreateSound")||void 0,this.deploySound=this.ini.getString("DeploySound")||void 0,this.undeploySound=this.ini.getString("UndeploySound")||void 0,this.voiceSelect=this.ini.getString("VoiceSelect")||void 0,this.voiceMove=this.ini.getString("VoiceMove")||void 0,this.voiceAttack=this.ini.getString("VoiceAttack")||void 0,this.voiceFeedback=this.ini.getString("VoiceFeedback")||void 0,this.voiceSpecialAttack=this.ini.getString("VoiceSpecialAttack")||void 0,this.voiceEnter=this.ini.getString("VoiceEnter")||void 0,this.voiceCapture=this.ini.getString("VoiceCapture")||void 0,this.voiceCrashing=this.ini.getString("VoiceCrashing")||void 0,this.crashingSound=this.ini.getString("CrashingSound")||void 0,this.impactLandSound=this.ini.getString("ImpactLandSound")||void 0,this.auxSound1=this.ini.getString("AuxSound1")||void 0,this.auxSound2=this.ini.getString("AuxSound2")||void 0,this.dieSound=this.ini.getString("DieSound")||void 0,this.moveSound=this.ini.getString("MoveSound")||void 0,this.enterWaterSound=this.ini.getString("EnterWaterSound")||void 0,this.leaveWaterSound=this.ini.getString("LeaveWaterSound")||void 0,this.turretRotateSound=this.ini.getString("TurretRotateSound")||void 0,this.workingSound=this.ini.getString("WorkingSound")||void 0,this.notWorkingSound=this.ini.getString("NotWorkingSound")||void 0,this.chronoInSound=this.ini.getString("ChronoInSound")||void 0,this.chronoOutSound=this.ini.getString("ChronoOutSound")||void 0,this.enterTransportSound=this.ini.getString("EnterTransportSound")||void 0,this.leaveTransportSound=this.ini.getString("LeaveTransportSound")||void 0}parseWeaponName(e){return e&&"none"!==e.toLowerCase()?e:void 0}parseTurretIndexes(){let i=new Map;return this.ini.getBool("Gunner")&&this.ini.entries.forEach((e,t)=>{t=t.match(/^(.*)TurretWeapon$/i);t&&(t=t[1]+"TurretIndex",this.ini.has(t)&&i.set(Number(e),this.ini.getNumber(t)))}),i}parseBurstDelay(){let t=[];for(let e=0;e<4;++e)t.push(this.ini.has(`BurstDelay${e}`)?this.ini.getNumber(`BurstDelay${e}`):void 0);return t}hasOwner(e){return!!this.owner.length&&-1!==this.owner.indexOf(e.name)}isAvailableTo(e){return(!this.requiredHouses.length||-1!==this.requiredHouses.indexOf(e.name))&&-1===this.forbiddenHouses.indexOf(e.name)}get proneWhenAttacked(){return!this.fearless&&this.isHuman}getWeaponAtIndex(e){return this.parseWeaponName(this.ini.getString(`Weapon${e+1}`))}getEliteWeaponAtIndex(e){return this.parseWeaponName(this.ini.getString(`EliteWeapon${e+1}`))}}ns.MAX_SIGHT=11;class os extends Ii{parse(){super.parse(),this.armor=this.ini.getEnum("Armor",ri,ri.None,!0),this.crate=this.ini.getBool("Crate");var e=this.ini.getBool("IsARock");this.isARock=e,this.isRubble=this.ini.getBool("IsRubble"),this.isVeinholeMonster=this.ini.getBool("IsVeinholeMonster"),this.isVeins=this.ini.getBool("IsVeins"),this.land=this.ini.getEnum("Land",Kt,Kt.Clear),this.noUseTileLandType=!!this.ini.getString("NoUseTileLandType"),this.strength=this.ini.getNumber("Strength"),this.tiberium=this.ini.getBool("Tiberium");var t=this.ini.getBool("Wall");this.wall=t,this.radarInvisible=this.ini.getBool("RadarInvisible",!t&&!e)}}(r=es=es||{})[r.All=7]="All",r[r.Right=1]="Right",r[r.Left=2]="Left",r[r.Bottom=4]="Bottom";class hs extends Ii{parse(){super.parse(),this.animationRate=this.ini.getNumber("AnimationRate"),this.animationProbability=this.ini.getNumber("AnimationProbability"),this.gate=this.ini.getBool("Gate"),this.immune=this.ini.getBool("Immune"),this.isAnimated=this.ini.getBool("IsAnimated"),this.snowOccupationBits=this.normalizeOccupationBits(this.ini.getNumber("SnowOccupationBits",es.All)),this.spawnsTiberium=this.ini.getBool("SpawnsTiberium"),this.strength=this.ini.getNumber("Strength"),this.radarInvisible=this.ini.getBool("RadarInvisible"),this.temperateOccupationBits=this.normalizeOccupationBits(this.ini.getNumber("TemperateOccupationBits",es.All))}normalizeOccupationBits(e){return(e+8*Math.abs(Math.floor(e/8)))%8}getOccupationBits(e){return e!==I.Snow?this.temperateOccupationBits:this.snowOccupationBits}getOccupiedSubCells(e){var t,i=this.getOccupationBits(e),e=[0,1,2,3,4];if(i===es.All)return e;let s=[];for(t of e)!function(e,t){switch(e){case 0:case 1:return 1;case 2:return 0!=(t&es.Right);case 3:return 0!=(t&es.Left);case 4:return 0!=(t&es.Bottom);default:throw new Error(`Invalid subCell "${e}`)}}(t,i)||s.push(t);return s}}class ls extends Ii{parse(){super.parse(),this.burn=this.ini.getBool("Burn"),this.crater=this.ini.getBool("Crater"),this.width=this.ini.getNumber("Width",1),this.height=this.ini.getNumber("Height",1)}}class cs extends Ii{parse(){super.parse(),this.damage=this.ini.getNumber("Damage"),this.damageRadius=this.ini.getNumber("DamageRadius"),this.duration=this.ini.getNumber("Duration"),this.elasticity=W(this.ini.getNumber("Elasticity",.75),0,1),this.expireAnim=this.ini.getString("ExpireAnim")||void 0,this.minAngularVelocity=this.ini.getNumber("MinAngularVelocity"),this.maxAngularVelocity=this.ini.getNumber("MaxAngularVelocity"),this.maxXYVel=this.ini.getNumber("MaxXYVel"),this.minZVel=this.ini.getNumber("MinZVel"),this.maxZVel=this.ini.getNumber("MaxZVel"),this.shareTurretData=this.ini.getBool("ShareTurretData"),this.shareBodyData=this.ini.getBool("ShareBodyData"),this.shareBarrelData=this.ini.getBool("ShareBarrelData"),this.shareSource=this.ini.get("ShareSource")||void 0,this.trailerAnim=this.ini.getString("TrailerAnim")||void 0,this.trailerSeparation=this.ini.getNumber("TrailerSeperation"),this.warhead=this.ini.getString("Warhead")||void 0}}class us{create(e,t,i){switch(e){case Bt.Aircraft:case Bt.Building:case Bt.Infantry:case Bt.Vehicle:return new ns(e,t,i);case Bt.Overlay:return new os(e,t,i);case Bt.Terrain:return new hs(e,t,i);case Bt.Smudge:return new ls(e,t,i);case Bt.VoxelAnim:return new cs(e,t,i);default:return new Ii(e,t,i)}}}class ds{readIni(e){this.ballisticScatter=e.getNumber("BallisticScatter"),this.bridgeStrength=e.getNumber("BridgeStrength"),this.c4Delay=e.getNumber("C4Delay"),this.c4Warhead=e.getString("C4Warhead"),this.deathWeapon=e.getString("DeathWeapon"),this.dMislEliteWarhead=e.getString("DMislEliteWarhead"),this.dMislWarhead=e.getString("DMislWarhead"),this.flameDamage=e.getString("FlameDamage"),this.ironCurtainDuration=e.getNumber("IronCurtainDuration"),this.ivanDamage=e.getNumber("IvanDamage"),this.ivanIconFlickerRate=e.getNumber("IvanIconFlickerRate"),this.ivanTimedDelay=e.getNumber("IvanTimedDelay"),this.ivanWarhead=e.getString("IvanWarhead"),this.splashList=e.getArray("SplashList"),this.v3EliteWarhead=e.getString("V3EliteWarhead"),this.v3Warhead=e.getString("V3Warhead")}}class ps{readIni(e){return this.value=e.getNumber("Value"),this}}class gs{readIni(e){this.buildPower=e.getArray("BuildPower"),this.buildRefinery=e.getArray("BuildRefinery"),this.buildTech=e.getArray("BuildTech"),this.tiberiumFarScan=e.getNumber("TiberiumFarScan",50),this.tiberiumNearScan=e.getNumber("TiberiumNearScan",5)}}class ms{readIni(e){return this.increment=e.getNumber("ElevationIncrement"),this.incrementBonus=e.getNumber("ElevationIncrementBonus",1),this.bonusCap=e.getNumber("ElevationBonusCap"),this}getBonus(e,t){return e<=t?0:Math.min(this.bonusCap,Math.floor((e-t)/this.increment))*this.incrementBonus}}class fs{readIni(e){this.radDurationMultiple=e.getNumber("RadDurationMultiple"),this.radApplicationDelay=e.getNumber("RadApplicationDelay"),this.radLevelMax=e.getNumber("RadLevelMax"),this.radLevelDelay=e.getNumber("RadLevelDelay"),this.radLightDelay=e.getNumber("RadLightDelay"),this.radLevelFactor=e.getNumber("RadLevelFactor"),this.radLightFactor=e.getNumber("RadLightFactor"),this.radTintFactor=e.getNumber("RadTintFactor"),this.radColor=e.getNumberArray("RadColor"),this.radSiteWarhead=e.getString("RadSiteWarhead")}}(r=ts=ts||{})[r.MultiMissile=0]="MultiMissile",r[r.IronCurtain=1]="IronCurtain",r[r.LightningStorm=2]="LightningStorm",r[r.ChronoSphere=3]="ChronoSphere",r[r.ChronoWarp=4]="ChronoWarp",r[r.ParaDrop=5]="ParaDrop",r[r.AmerParaDrop=6]="AmerParaDrop";class ys{constructor(e){this.index=e}readIni(e){return this.disableableFromShell=e.getBool("DisableableFromShell"),this.isPowered=e.getBool("IsPowered",!0),this.name=e.name,this.preClick=e.getBool("PreClick"),this.preDependent=e.getEnum("PreDependent",ts,void 0),this.postClick=e.getBool("PostClick"),this.rechargeTime=e.getNumber("RechargeTime",5),this.showTimer=e.getBool("ShowTimer"),this.sidebarImage=e.getString("SidebarImage").toLowerCase(),this.type=e.getEnum("Type",ts,void 0),this.uiName=e.getString("UIName"),this.weaponType=e.getString("WeaponType")||void 0,this}}class ws{readIni(e){this.crateMaximum=e.getNumber("CrateMaximum"),this.crateMinimum=e.getNumber("CrateMinimum"),this.crateRadius=e.getNumber("CrateRadius"),this.crateRegen=e.getNumber("CrateRegen");let t=e.getString("UnitCrateType");return this.unitCrateType="none"!==t.toLowerCase()?t:void 0,this.healCrateSound=e.getString("HealCrateSound"),this.crateImg=e.getString("CrateImg"),this.waterCrateImg=e.getString("WaterCrateImg"),this.freeMCV=e.getBool("FreeMCV"),this}}(r=is=is||{})[r.Cheer=0]="Cheer",r[r.UnitDeployUndeploy=1]="UnitDeployUndeploy",r[r.WeaponFire=2]="WeaponFire",r[r.ObjectDestroy=3]="ObjectDestroy",r[r.ObjectSpawn=4]="ObjectSpawn",r[r.ObjectUnspawn=5]="ObjectUnspawn",r[r.ObjectMorph=6]="ObjectMorph",r[r.ObjectLiftOff=7]="ObjectLiftOff",r[r.ObjectLand=8]="ObjectLand",r[r.ObjectCrashing=9]="ObjectCrashing",r[r.ObjectDisguiseChange=10]="ObjectDisguiseChange",r[r.ObjectCloakChange=11]="ObjectCloakChange",r[r.ObjectAttacked=12]="ObjectAttacked",r[r.ShipSubmergeChange=13]="ShipSubmergeChange",r[r.BridgeRepair=14]="BridgeRepair",r[r.BuildStatusChange=15]="BuildStatusChange",r[r.BuildingPlace=16]="BuildingPlace",r[r.BuildingFailedPlace=17]="BuildingFailedPlace",r[r.BuildingSell=18]="BuildingSell",r[r.BuildingRepairFull=19]="BuildingRepairFull",r[r.BuildingCapture=20]="BuildingCapture",r[r.BuildingInfiltration=21]="BuildingInfiltration",r[r.BuildingGarrison=22]="BuildingGarrison",r[r.BuildingEvacuate=23]="BuildingEvacuate",r[r.BuildingRepairStart=24]="BuildingRepairStart",r[r.UnitRepairStart=25]="UnitRepairStart",r[r.UnitRepairFinish=26]="UnitRepairFinish",r[r.UnitRecycle=27]="UnitRecycle",r[r.InflictDamage=28]="InflictDamage",r[r.HealthChange=29]="HealthChange",r[r.WarheadDetonate=30]="WarheadDetonate",r[r.PlayerDefeated=31]="PlayerDefeated",r[r.PlayerResigned=32]="PlayerResigned",r[r.PlayerDropped=33]="PlayerDropped",r[r.DeployNotAllowed=34]="DeployNotAllowed",r[r.PowerChange=35]="PowerChange",r[r.PowerLow=36]="PowerLow",r[r.PowerRestore=37]="PowerRestore",r[r.RadarOnOff=38]="RadarOnOff",r[r.ObjectOwnerChange=39]="ObjectOwnerChange",r[r.RadarEvent=40]="RadarEvent",r[r.InsufficientFunds=41]="InsufficientFunds",r[r.RallyPointChange=42]="RallyPointChange",r[r.PrimaryFactoryChange=43]="PrimaryFactoryChange",r[r.FactoryProduceUnit=44]="FactoryProduceUnit",r[r.ObjectTeleport=45]="ObjectTeleport",r[r.AllianceChange=46]="AllianceChange",r[r.UnitPromote=47]="UnitPromote",r[r.EnterTransport=48]="EnterTransport",r[r.LeaveTransport=49]="LeaveTransport",r[r.EnterObject=50]="EnterObject",r[r.EnterTile=51]="EnterTile",r[r.SuperWeaponReady=52]="SuperWeaponReady",r[r.SuperWeaponActivate=53]="SuperWeaponActivate",r[r.LightningStormManifest=54]="LightningStormManifest",r[r.LightningStormCloud=55]="LightningStormCloud",r[r.CratePickup=56]="CratePickup",r[r.PingLocation=57]="PingLocation",r[r.StalemateDetect=58]="StalemateDetect",r[r.TriggerSoundFx=59]="TriggerSoundFx",r[r.TriggerStopSoundFx=60]="TriggerStopSoundFx",r[r.TriggerEva=61]="TriggerEva",r[r.TriggerAnim=62]="TriggerAnim",r[r.TriggerText=63]="TriggerText",r[r.TimerExpire=64]="TimerExpire";class Ts{constructor(e,t,i,s){this.target=e,this.player=t,this.source=i,this.tile=s,this.type=is.CratePickup}}var bs,vs,r=__webpack_require__(949);class Ss extends r.Vector2{length(){return Qi.sqrt(this.x*this.x+this.y*this.y)}angle(){let e=Qi.atan2(this.y,this.x);return e<0&&(e+=2*Math.PI),e}distanceTo(e){return Qi.sqrt(this.distanceToSquared(e))}rotateAround(e,t){var i=Qi.cos(t),s=Qi.sin(t),r=this.x-e.x,t=this.y-e.y;return this.x=r*i-t*s+e.x,this.y=r*s+t*i+e.y,this}}class ks{static tileToWorld(e,t){return{x:e*ks.LEPTONS_PER_TILE,y:t*ks.LEPTONS_PER_TILE}}static vecWorldToGround(e){return new Ss(e.x,e.z)}static vecGroundToWorld(e){return new ss(e.x,0,e.y)}static tileHeightToWorld(e){return e*(ks.LEPTONS_PER_TILE/2)*ks.zScale}static worldToTileHeight(e){return e/(ks.LEPTONS_PER_TILE/2*ks.zScale)}static tile3dToWorld(e,t,i){t=ks.tileToWorld(e,t),i=ks.tileHeightToWorld(i);return new ss(t.x,i,t.y)}static screenDistanceToWorld(e,t){return{x:Math.floor((e+2*t)/2*ks.ISO_WORLD_SCALE),y:Math.floor((2*t-e)/2*ks.ISO_WORLD_SCALE)}}static getWorldTileSize(){return ks.LEPTONS_PER_TILE}}function Os(e){return[Kt.Water,Kt.Beach].includes(e)?bs.Water:bs.Ground}ks.ISO_TILE_SIZE=30,ks.LEPTONS_PER_TILE=256,ks.ISO_WORLD_SCALE=ks.LEPTONS_PER_TILE/ks.ISO_TILE_SIZE,ks.ISO_CAMERA_ALPHA=Math.PI/6,ks.ISO_CAMERA_BETA=Math.PI/4,ks.COS_ISO_CAMERA_BETA=Qi.cos(ks.ISO_CAMERA_BETA),ks.zScale=ks.COS_ISO_CAMERA_BETA/Qi.cos(ks.ISO_CAMERA_ALPHA),(r=bs=bs||{})[r.Ground=0]="Ground",r[r.Air=1]="Air",r[r.Water=2]="Water";const _s=e=>void 0!==e.position,Is=e=>void 0!==e.addScalar;class Cs{constructor(e){this.tileOccupation=e}isInWeaponRange(e,t,i,s,r){var a=r??e;if(i.rules.limboLaunch&&2<Math.abs((_s(a)?a.position.tileElevation+a.tile.z:a.z)-(_s(t)?t.position.tileElevation+t.tile.z:t.z)))return!1;var{minRange:r,range:s}=this.computeWeaponRangeVsTarget(a,t,i,s);return i.rules.cellRangefinding?this.isInTileRange(a,t,r,s):e.isUnit()&&e.rules.movementZone===si.Fly?this.isInRange2(a,t,r,s):this.isInRange3(a,t,r,s)}computeWeaponRangeVsTarget(e,t,i,s){let r=0;var a,n;return!_s(t)||!t.isBuilding()||i.projectileRules.arcing||i.projectileRules.vertical||i.warhead.rules.ivanBomb||1<(n=t.getFoundation()).width&&1<n.height&&(r+=Math.ceil(Math.min(n.width,n.height)/2)),!i.projectileRules.subjectToElevation||i.projectileRules.arcing&&!_s(t)||(a=_s(e)?e.tile.z+e.tileElevation:e.z,(n=_s(t)?t.tile.z+t.tileElevation:t.z)<a&&(r+=s.elevationModel.getBonus(a,n))),i.projectileRules.isAntiAir&&_s(e)&&e.isTechno()&&_s(t)&&t.isUnit()&&t.zone===bs.Air&&(r+=e.rules.airRangeBonus),{minRange:i.minRange,range:i.range+r}}isInRange(e,t,i,s,r=!1){return r?this.isInTileRange(e,t,i,s):e.isUnit()&&e.rules.movementZone===si.Fly?this.isInRange2(e,t,i,s):this.isInRange3(e,t,i,s)}isInRange3(e,t,i,s){return z(this.distance3(e,t)/ks.LEPTONS_PER_TILE,i,s)}isInRange2(e,t,i,s){return z(this.distance2(e,t)/ks.LEPTONS_PER_TILE,i,s)}distance3(e,t){let i=_s(e)?e.position.worldPosition:Is(e)?e:ks.tile3dToWorld(e.rx+.5,e.ry+.5,e.z);t=_s(t)?t.position.worldPosition:Is(t)?t:ks.tile3dToWorld(t.rx+.5,t.ry+.5,t.z);return i.distanceTo(t)}distance2(e,t){let i=_s(e)?new Ss(e.position.worldPosition.x,e.position.worldPosition.z):Is(e)?new Ss(e.x,e.z):new Ss(e.rx+.5,e.ry+.5).multiplyScalar(ks.LEPTONS_PER_TILE);t=_s(t)?new Ss(t.position.worldPosition.x,t.position.worldPosition.z):Is(t)?new Ss(t.x,t.z):new Ss(t.rx+.5,t.ry+.5).multiplyScalar(ks.LEPTONS_PER_TILE);return i.distanceTo(t)}isInTileRange(e,t,i,s){return z(this.tileDistance(e,t),i,s)}tileDistance(e,t){var i,e=_s(e)?this.tileOccupation.calculateTilesForGameObject(e.tile,e):Array.isArray(e)?e:[e],s=_s(t)?this.tileOccupation.calculateTilesForGameObject(t.tile,t):Array.isArray(t)?t:[t];let r=new Ss,a=new Ss,n=Number.POSITIVE_INFINITY;for(i of e)for(var o of s){r.set(i.rx,i.ry),a.set(o.rx,o.ry);o=r.distanceTo(a);o<=n&&(n=o)}return n}}const As=e=>"name"in e;(r=vs=vs||{})[r.Brutal=0]="Brutal",r[r.Medium=1]="Medium",r[r.Easy=2]="Easy";var Bs,xs,Es,Ps,Ns,Ms,Ds,Rs,Ls;(new Map).set(vs.Easy,"GUI:AIDummy").set(vs.Medium,"GUI:AIEasyBeta"),new Map;class Fs{static computeGameSpeed(e){let t;return t=6===e?60:5===e?45:60/(6-e),t/Fs.BASE_TICKS_PER_SECOND}}Fs.BASE_TICKS_PER_SECOND=15;class js{constructor(e,t,i,s,r,a,n,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.foundation=s,this.maxDistance=a,this.predicate=n,this.checkBounds=o,this.distance=r,this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){var s=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t))return t};do{var r=this.startTile.rx-this.distance,a=this.startTile.ry-this.distance,n=this.startTile.rx+this.foundation.width-1+this.distance,o=this.startTile.ry+this.foundation.height-1+this.distance;let e,t,i;if(0<this.distance){for(e=n;e>=r;e--)i=s(e,o),i&&(yield i);for(t=o-1;t>=a;t--)i=s(n,t),i&&(yield i);for(e=r;e<n;e++)i=s(e,a),i&&(yield i);for(t=1+a;t<o;t++)i=s(r,t),i&&(yield i)}else this.predicate(this.startTile)&&(yield this.startTile)}while(this.distance++,this.distance<=this.maxDistance)}}(r=Bs=Bs||{})[r.Armor=0]="Armor",r[r.Firepower=1]="Firepower",r[r.HealBase=2]="HealBase",r[r.Money=3]="Money",r[r.Reveal=4]="Reveal",r[r.Speed=5]="Speed",r[r.Veteran=6]="Veteran",r[r.Unit=7]="Unit",r[r.Invulnerability=8]="Invulnerability",r[r.IonStorm=9]="IonStorm",r[r.Gas=10]="Gas",r[r.Tiberium=11]="Tiberium",r[r.Pod=12]="Pod",r[r.Cloak=13]="Cloak",r[r.Darkness=14]="Darkness",r[r.Explosion=15]="Explosion",r[r.ICBM=16]="ICBM",r[r.Napalm=17]="Napalm",r[r.Squad=18]="Squad",(xs=xs||{}).onTick=Symbol(),(Es=Es||{}).onChange=Symbol();class Us{constructor(e){this.target=e,this.type=is.SuperWeaponReady}}(r=Ps=Ps||{})[r.Charging=0]="Charging",r[r.Paused=1]="Paused",r[r.Ready=2]="Ready";class Ws{constructor(e,t,i,s=!1){this.name=e,this.rules=t,this.owner=i,this.oneTimeOnly=s,this.status=Ps.Charging,this.isGift=!1,this.rechargeTicks=60*t.rechargeTime*Fs.BASE_TICKS_PER_SECOND,this.chargeTicks=this.rechargeTicks,s&&(this.status=Ps.Ready,this.chargeTicks=0)}update(e){0<this.chargeTicks&&this.status!==Ps.Paused&&(this.chargeTicks--,0===this.chargeTicks&&(this.status=Ps.Ready,e.events.dispatch(new Us(this))))}pauseTimer(){this.status=Ps.Paused}resumeTimer(){this.status=0<this.chargeTicks?Ps.Charging:Ps.Ready}resetTimer(){this.chargeTicks=this.rechargeTicks,this.status===Ps.Ready&&(this.status=Ps.Charging)}getTimerSeconds(){return this.chargeTicks/Fs.BASE_TICKS_PER_SECOND}getChargeProgress(){return(this.rechargeTicks-this.chargeTicks)/this.rechargeTicks}}(r=Ns=Ns||{})[r.NotStarted=0]="NotStarted",r[r.Running=1]="Running",r[r.Finished=2]="Finished";class zs{constructor(e,t,i){this.type=e,this.owner=t,this.tile=i,this.status=Ns.NotStarted}onStart(e){}onTick(e){return!0}}(r=Ms=Ms||{}).onPowerLow=Symbol(),r.onPowerRestore=Symbol(),r.onPowerChange=Symbol(),(Ds=Ds||{}).onActivate=Symbol();class Vs{constructor(e,t,i,s,r){this.target=e,this.owner=t,this.atTile=i,this.atTile2=s,this.noSfxWarning=r,this.type=is.SuperWeaponActivate}}(r=Rs=Rs||{})[r.None=0]="None",r[r.Guard=1]="Guard",r[r.Prone=2]="Prone",r[r.Deployed=3]="Deployed",r[r.Paradrop=4]="Paradrop",r[r.Cheer=5]="Cheer",(r=Ls=Ls||{})[r.NotStarted=0]="NotStarted",r[r.Running=1]="Running",r[r.Finished=2]="Finished",r[r.Cancelling=3]="Cancelling",r[r.Cancelled=4]="Cancelled";class Hs{constructor(){this.status=Ls.NotStarted,this.children=[],this.cancellable=!0,this.useChildTargetLines=!1,this.blocking=!0,this.waitingForChildrenToFinish=!1,this.preventOpportunityFire=!0,this.preventLanding=!0,this.isAttackMove=!1}isRunning(){return this.status===Ls.Running}isCancelling(){return this.status===Ls.Cancelling}setCancellable(e){return this.cancellable=e,this}onStart(e){}onEnd(e){}cancel(){if(this.cancellable)if(this.status===Ls.Running)this.status=Ls.Cancelling,this.children.length&&this.children.forEach(e=>e.cancel());else if(this.status===Ls.NotStarted&&(this.status=Ls.Cancelled,this.children.length))throw new Error("Should't have any children before starting a task")}getTargetLinesConfig(e){}}function Gs(t,i){for(let e=t.length-1;0<=e;e--)if(i(t[e],e,t))return e;return-1}class $s extends Hs{constructor(e){super(),this.ticks=e}onTick(){return!!this.isCancelling()||!(0<this.ticks--)}}class qs{constructor(e){this.map=e}findPositions(e,s,r,a){let n=new Map,t=this.clusterObjects(e);if(!t.length)throw new Error("We should have found at least one cluster");let i=t.reduce((e,t)=>t.objects.size>e.objects.size?t:e,t[0]);t.splice(t.indexOf(i),1);let o=[],h=this.findCenterTile([...i.objects]);i.objects.forEach(t=>{var i=this.map.tiles.getByMapCoords(s.rx+t.tile.rx-h.rx,s.ry+t.tile.ry-h.ry),e=i?.onBridgeLandType?this.map.tileOccupation.getBridgeOnTile(i):void 0;if(!i||!this.map.mapBounds.isWithinBounds(i)||n.has(i)&&!this.tileHasRoom(t,n.get(i))||t.rules.movementZone===si.Fly&&!(t.rules.airportBound||a&&t.rules.balloonHover&&!t.rules.hoverAttack)&&!this.map.terrain.getPassableSpeed(i,Jt.Amphibious,!!e)||t.rules.movementZone!==si.Fly&&!this.isEligibleTile(i,e,r,s))o.push(t);else{let e=n.get(i);void 0===e&&(e=[],n.set(i,e)),e.push(t)}}),t.forEach(e=>o.push(...e.objects));let l=new js(this.map.tiles,this.map.mapBounds,s,{width:1,height:1},1,5,()=>!0),c;for(;o.length&&(c=l.getNextTile());){var u=o[0],d=this.map.tileOccupation.getBridgeOnTile(c);if((!n.has(c)||this.tileHasRoom(u,n.get(c)))&&((u.rules.movementZone!==si.Fly||u.rules.airportBound||this.map.terrain.getPassableSpeed(c,Jt.Amphibious,!!d))&&(u.rules.movementZone===si.Fly||this.isEligibleTile(c,d,r,s)))){let e=n.get(c);void 0===e&&(e=[],n.set(c,e)),e.push(o.shift())}}let p=new Map;if(n.forEach((e,t)=>{e.forEach(e=>p.set(e,t))}),o.forEach(e=>p.set(e,s)),p.size!==e.length)throw new Error("We should have computed a number of positions equal to the number of input objects");return p}tileHasRoom(e,t){if(e.isInfantry()){if(t.find(e=>!e.isInfantry()))return!1;e=e.rules.movementZone===si.Fly?1:3;return t.filter(e=>e.isInfantry()).length>=e?!1:!0}return!t.length}isEligibleTile(e,t,i,s){return i?.isHighBridge()||t?.isHighBridge()?e.z+(t?.tileElevation??0)===s.z+(i?.tileElevation??0):!(!i&&!t)||Math.abs(e.z-s.z)<2}clusterObjects(e){let r=new Map;e.forEach(e=>{var t=e.tile.rx+"_"+e.tile.ry;r.set(t,[...r.get(t)||[],e])});let t=[],a=new Set(e);for(;a.size;){let e=new Set,s=[];var i=[...a][0].tile;for(r.get(i.rx+"_"+i.ry).forEach(e=>{s.push(e)});s.length;){var n=s.shift();e.add(n),a.delete(n);for(let i=-1;i<=1;i++)for(let t=-1;t<=1;t++)if(i||t){let e=r.get(n.tile.rx+i+"_"+(n.tile.ry+t));e&&e.length&&e.forEach(e=>{a.has(e)&&(a.delete(e),s.push(e))})}}t.push({objects:e})}return t}findCenterTile(e){let t=0,i=0;e.forEach(e=>{t+=e.tile.rx,i+=e.tile.ry}),t=Math.round(t/e.length),i=Math.round(i/e.length);let s=this.map.tiles.getByMapCoords(t,i);if(!s&&(s=e.find(e=>Math.abs(e.tile.rx-t)<=1&&Math.abs(e.tile.ry-i)<=1)?.tile,!s))throw new Error("At least one adjacent object should have been found");return s}}r=__webpack_require__(949);class Xs extends r.Matrix4{extractRotation(e){let t=this.elements;var i=e.elements,s=1/Zs.setFromMatrixColumn(e,0).length(),r=1/Zs.setFromMatrixColumn(e,1).length(),e=1/Zs.setFromMatrixColumn(e,2).length();return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=0,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=0,t[8]=i[8]*e,t[9]=i[9]*e,t[10]=i[10]*e,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){e&&e.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");let t=this.elements;var i,s,r,a,n,o,h,l,c,u,d,p=e.x,g=e.y,m=e.z,f=Qi.cos(p),y=Qi.sin(p),w=Qi.cos(g),T=Qi.sin(g),p=Qi.cos(m),g=Qi.sin(m);return"XYZ"===e.order?(i=f*p,r=f*g,s=y*p,m=y*g,t[0]=w*p,t[4]=-w*g,t[8]=T,t[1]=r+s*T,t[5]=i-m*T,t[9]=-y*w,t[2]=m-i*T,t[6]=s+r*T,t[10]=f*w):"YXZ"===e.order?(a=w*p,i=w*g,s=T*p,r=T*g,t[0]=a+r*y,t[4]=s*y-i,t[8]=f*T,t[1]=f*g,t[5]=f*p,t[9]=-y,t[2]=i*y-s,t[6]=r+a*y,t[10]=f*w):"ZXY"===e.order?(h=w*p,a=w*g,n=T*p,o=T*g,t[0]=h-o*y,t[4]=-f*g,t[8]=n+a*y,t[1]=a+n*y,t[5]=f*p,t[9]=o-h*y,t[2]=-f*T,t[6]=y,t[10]=f*w):"ZYX"===e.order?(n=f*p,o=f*g,l=y*p,h=y*g,t[0]=w*p,t[4]=l*T-o,t[8]=n*T+h,t[1]=w*g,t[5]=h*T+n,t[9]=o*T-l,t[2]=-T,t[6]=y*w,t[10]=f*w):"YZX"===e.order?(u=f*w,l=f*T,c=y*w,d=y*T,t[0]=w*p,t[4]=d-u*g,t[8]=c*g+l,t[1]=g,t[5]=f*p,t[9]=-y*p,t[2]=-T*p,t[6]=l*g+c,t[10]=u-d*g):"XZY"===e.order&&(c=f*w,u=f*T,d=y*w,e=y*T,t[0]=w*p,t[4]=-g,t[8]=T*p,t[1]=c*g+e,t[5]=f*p,t[9]=u*g-d,t[2]=d*g-u,t[6]=y*p,t[10]=e*g+c),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}lookAt(e,t,i){Qs.set(0,0,0),Ys.set(0,0,0),Ks.set(0,0,0);const s=this.elements;return Ks.subVectors(e,t),0===Ks.lengthSq()&&(Ks.z=1),Ks.normalize(),Qs.crossVectors(i,Ks),0===Qs.lengthSq()&&(1===Math.abs(i.z)?Ks.x+=1e-4:Ks.z+=1e-4,Ks.normalize(),Qs.crossVectors(i,Ks)),Qs.normalize(),Ys.crossVectors(Ks,Qs),s[0]=Qs.x,s[4]=Ys.x,s[8]=Ks.x,s[1]=Qs.y,s[5]=Ys.y,s[9]=Ks.y,s[2]=Qs.z,s[6]=Ys.z,s[10]=Ks.z,this}getMaxScaleOnAxis(){var e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],e=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Qi.sqrt(Math.max(t,i,e))}makeRotationX(e){var t=Qi.cos(e),e=Qi.sin(e);return this.set(1,0,0,0,0,t,-e,0,0,e,t,0,0,0,0,1),this}makeRotationY(e){var t=Qi.cos(e),e=Qi.sin(e);return this.set(t,0,e,0,0,1,0,0,-e,0,t,0,0,0,0,1),this}makeRotationZ(e){var t=Qi.cos(e),e=Qi.sin(e);return this.set(t,-e,0,0,e,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){var i=Qi.cos(t),s=Qi.sin(t),r=1-i,a=e.x,n=e.y,o=e.z,t=r*a,e=r*n;return this.set(t*a+i,t*n-s*o,t*o+s*n,0,t*n+s*o,e*n+i,e*o-s*a,0,t*o-s*n,e*o+s*a,r*o*o+i,0,0,0,0,1),this}decompose(e,t,i){var s=this.elements;let r=Zs.set(s[0],s[1],s[2]).length();var a=Zs.set(s[4],s[5],s[6]).length(),n=Zs.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),e.x=s[12],e.y=s[13],e.z=s[14],Js.copy(this);var o=1/r,e=1/a,s=1/n;return Js.elements[0]*=o,Js.elements[1]*=o,Js.elements[2]*=o,Js.elements[4]*=e,Js.elements[5]*=e,Js.elements[6]*=e,Js.elements[8]*=s,Js.elements[9]*=s,Js.elements[10]*=s,t.setFromRotationMatrix(Js),i.x=r,i.y=a,i.z=n,this}}const Zs=new ss,Qs=new ss,Ys=new ss,Ks=new ss,Js=new Xs;var er=__webpack_require__(949);function tr(e){return e*er.Math.RAD2DEG}function ir(e){return e*er.Math.DEG2RAD}const sr=new Ss;function rr(e,t){t=ir(Math.floor(t));return e.rotateAround(sr,t)}function ar(e){return Math.round(tr(e.angle()))}function nr(e,t){t=tr(2*Qi.acos(Math.abs(W(e.dot(t),-1,1))));return Math.round(t)}function or(e,t){e=ar(e),t=ar(t);return Math.min((e-t+360)%360,(t-e+360)%360)}function hr(e,t){return nr(lr(e,gr),lr(t,mr))}function lr(e,t=new Yi){return t.setFromRotationMatrix(cr.lookAt(e,ur,dr))}const cr=new Xs,ur=new ss(0,0,0),dr=new ss(0,1,0);function pr(e,t,i){var s=e.length(),r=lr(t,gr),t=lr(e,mr);!function(e,t,i){var s=nr(e,t);if(0!==s){s=Math.min(1,i/s);e.slerp(t,s)}}(t,r,i),e.set(0,0,1).applyQuaternion(t).setLength(s)}const gr=new Yi,mr=new Yi;class fr extends Hs{constructor(e,t){super(),this.game=e,this.fromDirection=t,this.resolved=!1,this.chainPushIssued=!1}onEnd(e){e.moveTrait.collisionState=Xr.Resolved}onTick(i){if(this.timeoutTicks=void 0===this.timeoutTicks?0:this.timeoutTicks+1,40<this.timeoutTicks||this.resolved||this.isCancelling())return!0;let s=this.game.map,t=new qs(s),r=i.onBridge?s.tileOccupation.getBridgeOnTile(i.tile):void 0,a,n;for(let e=0;e<360;e+=45)if((0!==e||this.chainPushIssued)&&180!==e){var o=rr(this.fromDirection.clone(),e).round(),o=s.tiles.getByMapCoords(i.tile.rx+Math.sign(o.x),i.tile.ry+Math.sign(o.y));if(o&&s.mapBounds.isWithinBounds(o)&&(n=!r||r.isHighBridge()?s.tileOccupation.getBridgeOnTile(o):void 0,i.rules.movementZone===si.Fly||!s.terrain.findObstacles({tile:o,onBridge:n},i).length&&t.isEligibleTile(o,n,r,i.tile))){a=o;break}}if(a)return this.resolved=!0,i.isInfantry()&&i.deployerTrait&&i.deployerTrait.isDeployed()&&i.deployerTrait.setDeployed(!1),!!i.moveTrait.isDisabled()||(this.children.push(new Sa(this.game,a,!!n,{closeEnoughTiles:0,strictCloseEnough:!0})),!1);{if(this.chainPushIssued)return this.children.push(new $s(5)),!1;let t=s.tiles.getByMapCoords(i.tile.rx+Math.sign(this.fromDirection.x),i.tile.ry+Math.sign(this.fromDirection.y));if(!t||!s.mapBounds.isWithinBounds(t))return!0;n=!r||r.isHighBridge()?s.tileOccupation.getBridgeOnTile(t):void 0;let e=s.tileOccupation.getGroundObjectsOnTile(t).filter(e=>e.isUnit()&&e.owner===i.owner&&e.tile===t&&e.onBridge===!!n&&!(e.isInfantry()&&e.stance===Rs.Paradrop)&&!(e.isAircraft()&&e.missileSpawnTrait));return e.find(e=>e.moveTrait.collisionState===Xr.Waiting||e.unitOrderTrait.hasTasks())?(this.children.push(new $s(5)),i.moveTrait.collisionState=Xr.Waiting,i.moveTrait.moveState=$r.PlanMove,!1):(e.forEach(e=>{e.unitOrderTrait.addTask(new fr(this.game,this.fromDirection))}),this.children.push(new $s(1)),i.moveTrait.collisionState=Xr.Waiting,i.moveTrait.moveState=$r.PlanMove,!(this.chainPushIssued=!0))}}}const yr=__webpack_require__(163);class wr{constructor(e){this.game=e,this.ignoresTerrain=!0,this.distanceToWaypoint=new Ss}onNewWaypoint(e,t){}tick(e,t,i,s){if(s)return{distance:new ss,done:!0};this.distanceToWaypoint.copy(t).sub(e.position.getMapPosition());s=this.game.rules.general;return s.chronoTrigger&&(s=(t=this.distanceToWaypoint.length())<s.chronoRangeMinimum?s.chronoMinimumDelay:t/s.chronoDistanceFactor,e.warpedOutTrait.setTimed(s,!1,this.game)),{distance:new ss(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!0,isTeleport:!0}}}class Tr{static tick(e,t,i){if(e===t)return{facing:e,delta:0};var s=(e-t+360)%360,r=(t-e+360)%360;if(Math.min(s,r)<i)return{facing:t,delta:0};i*=r<=s?1:-1;return{facing:(e+i+360)%360,delta:i}}static fromMapCoords(e){return(-ar(e)-90+720)%360}static toMapCoords(e){return rr(new Ss(1e3,0),Tr.toWorldDeg(e)).round().normalize()}static toWorldDeg(e){return-(e+90)}}class br extends Hs{constructor(e){super(),this.direction=e,this.cancellable=!1}onTick(e){if(e.direction===this.direction)return!(e.spinVelocity=0);var t=e.rules.rot,{facing:i,delta:t}=Tr.tick(e.direction,this.direction,t);return e.direction=i,e.spinVelocity=t,!1}}r=__webpack_require__(949);class vr extends r.LineCurve{constructor(e,t){super(e||new Ss,t||new Ss)}getPoint(e,t){return super.getPoint(e,t||new Ss)}}r=__webpack_require__(949);class Sr extends r.CurvePath{closePath(){let e=this.curves[0].getPoint(0);var t=this.curves[this.curves.length-1].getPoint(1);e.equals(t)||this.curves.push(new vr(t,e))}}var kr,Or,r=__webpack_require__(949);class _r extends r.QuadraticBezierCurve{constructor(e,t,i){super(e||new Ss,t||new Ss,i||new Ss)}getPoint(e,t){return super.getPoint(e,t||new Ss)}}(r=kr=kr||{})[r.None=0]="None",r[r.Start=1]="Start",r[r.Normal=2]="Normal",r[r.End=3]="End",r[r.Single=4]="Single";class Ir{constructor(e){this.game=e,this.hasMomentum=!1,this.moveOnCurve=!1,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=kr.None}selectNextWaypoint(i,s){if(this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==kr.End?kr.Normal:kr.Start,this.initialPosition=i.position.getMapPosition(),this.currentWaypointType!==kr.Start?i.moveTrait.speedPenalty=0:this.currentSpeed=0,1<s.length){var r=s[s.length-1],a=s[s.length-2],e=new Ss(r.tile.rx-i.tile.rx,r.tile.ry-i.tile.ry),n=Math.abs(ar(e)-ar(new Ss(a.tile.rx-r.tile.rx,a.tile.ry-r.tile.ry)));if(!Math.abs(Tr.fromMapCoords(e)-i.direction)&&0<n&&n<90&&this.hasMomentum){this.moveOnCurve=!0,this.currentWaypointType=2===s.length?this.currentWaypointType===kr.Start?kr.Single:kr.End:kr.Normal;let e=this.initialPosition;i=new Ss(r.tile.rx+.5,r.tile.ry+.5).multiplyScalar(ks.LEPTONS_PER_TILE);let t=new Ss(a.tile.rx+.5,a.tile.ry+.5).multiplyScalar(ks.LEPTONS_PER_TILE);n=e.clone().lerp(i,.5),r=t.clone().lerp(i,.5);return this.steerCurve=new Sr,this.steerCurve.add(new vr(e,n)),this.steerCurve.add(new _r(n,i,r)),this.steerCurve.add(new vr(r,t)),this.lastPosition=e,a}}else this.currentWaypointType=this.currentWaypointType===kr.Start?kr.Single:kr.End;return this.hasMomentum=!0,this.moveOnCurve=!1,s[s.length-1]}onNewWaypoint(e,t,i){let s=(new Ss).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=this.moveOnCurve?this.steerCurve.getLength():s.length();t=Tr.fromMapCoords(s);if(t!==e.direction&&(this.pointTurretToTarget(e,i),!this.moveOnCurve))return e.moveTrait.velocity.set(0,0,0),[new br(t)]}tick(i,s,r){this.pointTurretToTarget(i,r);let a=this.currentSpeed;a=i.rules.accelerates?(h=this.distanceTravelled/this.totalDistanceToTravel,this.currentSpeed=this.applyAcceleration(i,a,i.moveTrait.baseSpeed,h)):this.currentSpeed=i.moveTrait.baseSpeed,1<a&&(a=Math.floor(a));let e=this.game.map.terrain.getPassableSpeed(i.tile,i.rules.speedType,i.onBridge,void 0,!0);e?i.moveTrait.lastTileSpeed=e:e=i.moveTrait.lastTileSpeed,a*=e,1<a&&(a=Math.floor(a)),this.carryOverDistance&&(a=this.carryOverDistance);var n=i.position.getMapPosition();let o;if(this.moveOnCurve){var r=this.steerCurve.getLength(),h=Math.min(this.distanceTravelled+a,r);this.carryOverDistance=Math.max(0,this.distanceTravelled+a-r),this.distanceTravelled=h;let e=this.steerCurve.getPointAt(this.distanceTravelled/r),t=this.steerCurve.getTangentAt(this.distanceTravelled/r);h=t.clone().setLength(a);i.moveTrait.velocity.set(h.x,0,h.y);var r=i.rules.rot,{facing:h,delta:r}=Tr.tick(i.direction,Tr.fromMapCoords(t),r);i.direction=h,i.spinVelocity=r;r=this.lastPosition;this.lastPosition=e.clone(),o=e.sub(r)}else{let e=(new Ss).copy(s).sub(n);n=Math.min(e.length(),a);o=e.clone().setLength(n);let t=o.clone();this.carryOverDistance&&t.add(ks.vecWorldToGround(i.moveTrait.velocity)),i.moveTrait.velocity.set(t.x,0,t.y),this.distanceTravelled+=n,this.carryOverDistance=Math.max(0,a-e.length())}return{distance:new ss(o.x,0,o.y),done:!o.length()||!!this.carryOverDistance}}pointTurretToTarget(t,i){if(t.turretTrait){t.attackTrait?.currentTarget?.obj&&(i=t.attackTrait.currentTarget.obj.position.getMapPosition());var s=t.position.getMapPosition();let e=(new Ss).copy(i).sub(s);e.length()&&(s=Tr.fromMapCoords(e),t.turretTrait.desiredFacing=s)}}applyAcceleration(e,t,i,s){if(this.currentWaypointType===kr.Single)return i/2;if(this.currentWaypointType!==kr.End)return Math.min(t+e.rules.accelerationFactor*i,i);return V(1,i,1-(s=this.moveOnCurve&&this.currentWaypointType===kr.End?s<=.5?0:2*(s-.5):s))}}class Cr{constructor(e){this.game=e,this.currentMoveDirection=new Ss,this.distanceToWaypoint=new Ss,this.endPauseFrames=0}onNewWaypoint(e,t){this.currentMoveDirection.copy(t).sub(e.position.getMapPosition());t=Tr.fromMapCoords(this.currentMoveDirection);t!==e.direction&&(e.direction=t),this.endPauseFrames=1}onWaypointUpdate(e,t){this.onNewWaypoint(e,t)}tick(e,t,i){let s=e.moveTrait.baseSpeed;s=Math.floor(s),e.stance===Rs.Prone&&(s/=2),e.isPanicked&&(s*=2);let r=this.game.map.terrain.getPassableSpeed(e.tile,e.rules.speedType,e.onBridge,void 0,!0);r?this.lastTileSpeed=r:r=this.lastTileSpeed||1,s*=r,s=Math.floor(s),this.distanceToWaypoint.copy(t).sub(e.position.getMapPosition());let a=this.distanceToWaypoint.clone().setLength(s);(a.length()||t.equals(i))&&e.moveTrait.velocity.set(a.x,0,a.y);i=Math.min(this.distanceToWaypoint.length(),s),e=!i&&0<this.endPauseFrames--;return this.distanceToWaypoint.setLength(i),{distance:new ss(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!this.distanceToWaypoint.length()&&!e}}}(r=Or=Or||{})[r.None=0]="None",r[r.Start=1]="Start",r[r.Normal=2]="Normal",r[r.End=3]="End",r[r.Single=4]="Single";class Ar{constructor(e){this.hoverRules=e,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=Or.None,this.nextWaypointDir=new Ss}selectNextWaypoint(e,t){var i;return this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==Or.End?Or.Normal:Or.Start,this.initialPosition=e.position.getMapPosition(),this.currentWaypointType===Or.Start&&(this.currentSpeed=0),t.length<=1?(this.currentWaypointType=this.currentWaypointType===Or.Start?Or.Single:Or.End,(i=t[t.length-1])&&this.nextWaypointDir.set(i.tile.rx-e.tile.rx,i.tile.ry-e.tile.ry)):(i=t[t.length-1],e=t[t.length-2],this.nextWaypointDir.set(e.tile.rx-i.tile.rx,e.tile.ry-i.tile.ry)),t[t.length-1]}onNewWaypoint(e,t,i){let s=(new Ss).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=s.length();t=this.maxSpeed=e.moveTrait.baseSpeed,e=60*this.hoverRules.acceleration*Fs.BASE_TICKS_PER_SECOND;this.acceleration=t/e;e=60*this.hoverRules.brake*Fs.BASE_TICKS_PER_SECOND;this.deceleration=t/e}tick(e,t){var i=e.position.getMapPosition();let s=t.clone().sub(i);t=s.length(),i=this.maxSpeed;this.currentWaypointType===Or.Single?this.currentSpeed=i/2:this.currentWaypointType===Or.End?(r=this.computeBrakeDistance(this.currentSpeed,this.deceleration),this.totalDistanceToTravel-this.distanceTravelled<=r&&(this.currentSpeed=Math.max(0,this.currentSpeed-this.deceleration))):this.currentSpeed=Math.min(this.currentSpeed+this.acceleration,i);var r=Tr.fromMapCoords(s),i=Tr.fromMapCoords(this.nextWaypointDir);let a=r,n=e.rules.rot;this.currentWaypointType===Or.Normal&&r!==i&&(r=(o=or(this.nextWaypointDir,Tr.toMapCoords(e.direction)))/n,r=Math.max(this.currentSpeed*r,this.totalDistanceToTravel),this.totalDistanceToTravel-this.distanceTravelled<=r&&(a=i,n=o/((this.totalDistanceToTravel-this.distanceTravelled)/this.currentSpeed)));var o=Tr.tick(e.direction,a,n)["facing"];e.direction=o;let h=this.currentSpeed;this.carryOverDistance&&(h=this.carryOverDistance);o=Math.min(h,t);let l=s.clone().setLength(o),c=l.clone();return this.carryOverDistance&&c.add(ks.vecWorldToGround(e.moveTrait.velocity)),e.moveTrait.velocity.set(c.x,0,c.y),this.distanceTravelled+=o,this.carryOverDistance=Math.max(0,h-t),{distance:new ss(l.x,0,l.y),done:!l.length()||!!this.carryOverDistance}}computeBrakeDistance(e,t){var i=e/t;return Math.max(0,e*i-t*i*i/2)}}class Br{static computeInterceptPoint(e,t,i,s){let r=e.clone().sub(i);var a=s.length(),e=t*t-a*a,t=2*r.dot(s),a=-r.dot(r);if(t*t-4*e*a<0)return new ss;e=(-t+Qi.sqrt(t*t-4*e*a))/(2*e);return s.clone().multiplyScalar(e).add(i)}static computeTurnCircle(e,t,i,s){s/=ir(Math.abs(i));let r=rr(t.clone(),90*-Math.sign(i));return{center:isFinite(s)?r.setLength(s).add(e):e.clone(),radius:s}}}var xr=__webpack_require__(949);function Er(e,t){var i=e.center;return(i.x-t.x)*(i.x-t.x)+(i.y-t.y)*(i.y-t.y)<=e.radius*e.radius}function Pr(e,t){let i=new xr.Box2(new xr.Vector2(e.x,e.y),new xr.Vector2(e.x+e.width,e.y+e.height));return i.containsPoint(new xr.Vector2(t.x,t.y))}class Nr{constructor(e){this.gameObject=e,this.type=is.ObjectLiftOff}}class Mr{constructor(e){this.gameObject=e,this.type=is.ObjectLand}}class Dr{constructor(e){this.game=e,this.allowOutOfBounds=!0,this.currentMoveDir=new Ss,this.currentHorizSpeed=0}static tickStationary(t,i){if(t.zone===bs.Air){var s=t.tile.onBridgeLandType?i.map.tileOccupation.getBridgeOnTile(t.tile):void 0,r=!t.rules.balloonHover&&(!t.unitOrderTrait.getCurrentTask()?.preventLanding||!t.rules.hoverAttack)&&(i.map.getGroundObjectsOnTile(t.tile).find(e=>e.isBuilding()&&e.dockTrait?.isDocked(t))||i.map.getTileZone(t.tile)!==bs.Water&&0<i.map.terrain.getPassableSpeed(t.tile,Jt.Foot,!!t.tile.onBridgeLandType)&&0===i.map.terrain.findObstacles({tile:t.tile,onBridge:s},t).length);let e;e=r?(a=t.tile.z+(s?.tileElevation??0),ks.tileHeightToWorld(a)):(n=t.tile.z+i.map.getGroundObjectsOnTile(t.tile).filter(e=>!(e.isInfantry()&&e.stance===Rs.Paradrop)).reduce((e,t)=>Math.max(e,t.tileElevation+t.art.height),0),ks.tileHeightToWorld(n)+t.rules.jumpjetHeight);var a,n,o=t.position.worldPosition.y;e!==o?(a=t.rules.jumpjetClimb,n=Math.abs(e-o),a=Math.sign(e-o)*Math.min(a,n),n=t.tileElevation,t.position.moveByLeptons3(new ss(0,a,0)),t.moveTrait.handleElevationChange(n,i)):r&&(t.zone=bs.Ground,t.onBridge=!!s,i.events.dispatch(new Mr(t)),(s=i.map.tileOccupation.getGroundObjectsOnTile(t.tile).find(e=>e.isOverlay()&&e.rules.crate))&&i.crateGeneratorTrait.pickupCrate(t,s,i))}}static tickCrash(e,t,i){var s=2*e.rules.jumpjetCrash;return e.direction=(e.direction-6+360)%360,new ss(0,-s,0)}onNewWaypoint(e,t,i){this.currentMoveDir=Tr.toMapCoords(e.direction),this.cancelDestLeptons=void 0}tick(t,e,i,s){if(t.zone!==bs.Air&&(t.onBridge=!1,t.zone=bs.Air,this.game.events.dispatch(new Nr(t))),s){if(!this.cancelDestLeptons){let e=t.tile;this.game.map.isWithinBounds(e)||(e=this.game.map.clampWithinBounds(e)),this.cancelDestLeptons=this.computeCancelDest(e,i)}i=this.cancelDestLeptons}var r=t.position.getMapPosition();let a=i.clone().sub(r),n=this.findTilesToCheckForBlockers(t.tile,r,this.currentMoveDir,a.length());var o=n.map(e=>e.z+this.game.map.getGroundObjectsOnTile(e).filter(e=>!(e.isDestroyed||e.isInfantry()&&e.stance===Rs.Paradrop)).reduce((e,t)=>Math.max(e,t.tileElevation+t.art.height),0)).reduce((e,t)=>Math.max(e,t),0);let h=0;(void 0===this.lastClearZ||2<o-this.lastClearZ)&&(h=4);var l=ks.tileHeightToWorld(o),c=ks.tileHeightToWorld(o+h),u=t.position.worldPosition.y,d=Tr.fromMapCoords(a),p=a.length()<t.rules.jumpjetSpeed;let g=0;l<=u&&!p&&({facing:T,delta:s}=Tr.tick(t.direction,d,t.rules.jumpjetTurnRate),g=s,t.direction=T,this.currentMoveDir.copy(Tr.toMapCoords(t.direction))),t.isVehicle()&&(t.spinVelocity=g);let m,f=!1,y=0,w=0;var T=t.rules.jumpjetClimb;u<c?(y=Math.min(T,c-u),m=!1,this.currentHorizSpeed=0):(this.lastClearZ=o,o=l+t.rules.jumpjetHeight,m=!0,o!==u&&(l=Math.abs(o-u),y=Math.sign(o-u)*Math.min(T,l),m=l<=T),T=this.currentHorizSpeed,this.currentHorizSpeed=Math.min(this.currentHorizSpeed+2,t.rules.jumpjetSpeed),f=d===t.direction?(w=Math.min(T,a.length()),T>=a.length()):((r=T||g?Br.computeTurnCircle(r,this.currentMoveDir,Math.sign(g)*t.rules.jumpjetTurnRate,T):void 0)&&Er(r,i)?(w=0,this.currentHorizSpeed=0):w=T,!1));let b;b=p?(f=!0,a):this.currentMoveDir.clone().setLength(w);let v=new ss(b.x,y,b.y);p=v.clone();return t.moveTrait.velocity.copy(p),{distance:v,done:f&&m}}findTilesToCheckForBlockers(e,t,i,s){s=i.clone().setLength(Math.min(s,ks.LEPTONS_PER_TILE)).add(t).multiplyScalar(1/ks.LEPTONS_PER_TILE).floor(),t=this.game.map.tiles.getByMapCoords(s.x,s.y);if(!t||t===e)return[e];s=Math.sign(t.rx-e.rx),t=Math.sign(t.ry-e.ry);let r=[e],a;return s&&(a=this.game.map.tiles.getByMapCoords(e.rx+s,e.ry),a&&r.push(a)),t&&(a=this.game.map.tiles.getByMapCoords(e.rx,e.ry+t),a&&r.push(a)),s&&t&&(a=this.game.map.tiles.getByMapCoords(e.rx+s,e.ry+t),a&&r.push(a)),r}computeCancelDest(e,t){var i=t.clone().multiplyScalar(1/ks.LEPTONS_PER_TILE).floor().multiplyScalar(ks.LEPTONS_PER_TILE),i=t.clone().sub(i);return new Ss(e.rx,e.ry).multiplyScalar(ks.LEPTONS_PER_TILE).add(i)}}var Rr,Lr,Fr,jr,Ur,Wr,zr,Vr,Hr,Gr,$r,qr,Xr,Zr,Qr,Yr,Kr,Jr,ea,ta,ia,sa,ra,aa,na,oa,ha,la,ca,r=__webpack_require__(949);class ua extends r.CubicBezierCurve3{constructor(e,t,i,s){super(e||new ss,t||new ss,i||new ss,s||new ss)}getPoint(e,t){return super.getPoint(e,t||new ss)}}(r=Rr=Rr||{})[r.Boost=0]="Boost",r[r.Midcourse=1]="Midcourse",r[r.Terminal=2]="Terminal";class da{constructor(e,t){this.game=e,this.missileRules=t,this.flightPhase=Rr.Boost}selectNextWaypoint(e,t){var i=t[t.length-1],t=this.game.map.tileOccupation.getBridgeOnTile(i.tile),t=i.tile.z+(t?.tileElevation??0);return this.targetPosition=ks.tile3dToWorld(i.tile.rx+.5,i.tile.ry+.5,t),this.cruiseAltitude=ks.tileHeightToWorld(t)+this.missileRules.altitude,i}onNewWaypoint(e,t,i){}tick(i,e,t){let s=i.position.worldPosition.clone(),r=this.targetPosition.clone().sub(s);i.zone!==bs.Air&&(i.onBridge=!1,i.zone=bs.Air,this.game.events.dispatch(new Nr(i)));let a;var n;a=this.currentVelocity?(n=i.rules.speed,Math.min(this.currentVelocity.length()+this.missileRules.acceleration,n)):(p=this.missileRules.acceleration,this.missileRules.lazyCurve?this.currentVelocity=new ss(r.x,0,r.z):this.currentVelocity=ks.vecGroundToWorld(Tr.toMapCoords(i.direction)),pr(this.currentVelocity,new ss(this.currentVelocity.x,1e8,this.currentVelocity.z),i.pitch),p),this.currentVelocity.setLength(a);let o=!1;switch(this.flightPhase){case Rr.Boost:if(!(i.position.worldPosition.y>=this.cruiseAltitude)){o=!1;break}this.flightPhase=Rr.Midcourse;case Rr.Midcourse:var h,l=new Ss(r.x,r.z).length();if(!this.missileRules.lazyCurve){pr(this.currentVelocity,new ss(this.currentVelocity.x,0,this.currentVelocity.z),i.rules.rot),this.currentVelocity.y<1&&(h=this.currentVelocity.length(),this.currentVelocity.y=0,this.currentVelocity.setLength(h)),pr(this.currentVelocity,new ss(r.x,this.currentVelocity.y,r.z),i.rules.rot),i.direction=Tr.fromMapCoords(ks.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*hr(this.currentVelocity,new ss(this.currentVelocity.x,0,this.currentVelocity.z)),l/(s.y-this.targetPosition.y)<1&&(this.flightPhase=Rr.Terminal);break}this.flightPhase=Rr.Terminal;var c=s.clone().add(this.currentVelocity.clone().setLength(l/3/Qi.cos(ir(i.pitch)))),u=this.targetPosition.clone().lerp(s,.15).setY(c.y);this.descentCurve=new ua(s,c,u,this.targetPosition);case Rr.Terminal:c=this.missileRules.bodyLength;if(this.missileRules.lazyCurve){var d=this.descentCurve.getLength();this.descentTravelled??(this.descentTravelled=0),this.descentTravelled+=Math.min(a,d-c-this.descentTravelled);u=this.descentTravelled/d;let e=this.descentCurve.getPointAt(u),t=this.descentCurve.getTangentAt(u);this.currentVelocity.copy(e.sub(s));u=t.clone().setY(0);i.pitch=Math.sign(t.y-u.y)*hr(u,t),o=1<=(this.descentTravelled+c)/d}else{pr(this.currentVelocity,r,i.rules.rot),i.direction=Tr.fromMapCoords(ks.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*hr(this.currentVelocity,new ss(this.currentVelocity.x,0,this.currentVelocity.z));d=r.length()-c;(d<a||d<1)&&(this.currentVelocity.copy(r.clone().addScalar(-c)),o=!0)}break;default:throw new Error(`Unhandled flight phase "${this.flightPhase}"`)}var p=s.clone().add(this.currentVelocity);return this.game.map.isWithinHardBounds(p)?(i.moveTrait.velocity.copy(this.currentVelocity),{distance:this.currentVelocity,done:o}):(this.game.destroyObject(i),{done:!0,distance:new ss})}}class pa extends $s{constructor(e){super(Math.floor(Fs.BASE_TICKS_PER_SECOND*e*60))}}class ga extends Hs{constructor(e){super(),this.cb=e}onTick(e){return this.cb(e),!0}}(Lr=Lr||{}).onTick=Symbol(),(r=Fr=Fr||{})[r.Idle=0]="Idle",r[r.MoveToQueueingTile=1]="MoveToQueueingTile",r[r.WaitForTurn=2]="WaitForTurn",r[r.MoveToDock=3]="MoveToDock",r[r.Docking=4]="Docking",r[r.Docked=5]="Docked";class ma extends Hs{constructor(e,t){super(),this.game=e,this.target=t,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.dockingStatus=Fr.Idle}onStart(e){if(!this.target.dockTrait)throw new Error(`Target object "${this.target.name}" is not a valid dock`);var t;this.target.dockTrait.hasReservedDockForUnit(e)?this.dockingStatus=Fr.MoveToDock:void 0!==(t=this.target.dockTrait.getFirstAvailableDockNumber())?(this.target.dockTrait.reserveDockAt(e,t),this.dockingStatus=Fr.MoveToDock):this.target.helipadTrait?this.cancel():this.dockingStatus=Fr.MoveToQueueingTile}onEnd(e){this.dockingStatus!==Fr.Docked&&this.target.isSpawned&&(this.target.dockTrait.undockUnit(e),this.target.dockTrait.unreserveDockForUnit(e)),this.dockingStatus=Fr.Idle}onTick(e){if(this.isCancelling())return!0;if(!this.isValidTarget(this.target,e))return!0;if(this.dockingStatus===Fr.MoveToQueueingTile){var t=this.findReachableQueueingTile(e);if(!t)return!0;if(e.tile!==t)return this.children.push(new Sa(this.game,t,!1,{closeEnoughTiles:5}),new ga(()=>{e.moveTrait.lastMoveResult===qr.Fail?this.cancel():e.moveTrait.lastMoveResult===qr.CloseEnough&&(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)||(this.dockingStatus=Fr.WaitForTurn))})),!1;this.dockingStatus=Fr.WaitForTurn}if(this.dockingStatus===Fr.WaitForTurn){var i=this.target.dockTrait.getFirstAvailableDockNumber();if(void 0===i)return this.children.push(new pa(1/60)),!1;this.target.dockTrait.reserveDockAt(e,i),this.dockingStatus=Fr.MoveToDock}if(this.dockingStatus===Fr.MoveToDock){var s=this.target.dockTrait.getReservedDockForUnit(e),i=this.target.dockTrait.getDockTile(s),s=ks.vecWorldToGround(this.target.dockTrait.getDockOffset(s)).add(this.target.position.getMapPosition()).sub(new Ss(i.rx,i.ry).multiplyScalar(ks.LEPTONS_PER_TILE));if(e.tile!==i)return this.children.push(new Sa(this.game,i,!1,{targetOffset:e.isAircraft()?s:void 0,closeEnoughTiles:0,strictCloseEnough:!0}),new ga(()=>{e.moveTrait.lastMoveResult===qr.Fail&&this.cancel()})),this.game.afterTick(()=>e.unitOrderTrait[Lr.onTick](e,this.game)),!1;this.dockingStatus=Fr.Docking}if(this.dockingStatus!==Fr.Docking)return!1;s=this.target.dockTrait.getReservedDockForUnit(e);return this.target.dockTrait.unreserveDockForUnit(e),this.target.dockTrait.dockUnitAt(e,s),e.isAircraft()&&e.airportBoundTrait&&this.target.helipadTrait&&(e.airportBoundTrait.preferredAirport=this.target),this.dockingStatus=Fr.Docked,!0}isValidTarget(e,t){return e.isSpawned&&this.game.areFriendly(e,t)}findReachableQueueingTile(t){var e=this.target.getFoundation(),e=new Ss(this.target.tile.rx+e.width,this.target.tile.ry+e.height),e=this.game.map.tiles.getByMapCoords(e.x,e.y);return e&&this.isValidQueueingTile(e,t)?e:new js(this.game.map.tiles,this.game.map.mapBounds,this.target.tile,this.target.getFoundation(),1,1,e=>this.isValidQueueingTile(e,t)).getNextTile()}isValidQueueingTile(e,t){return(t.rules.movementZone===si.Fly||0<this.game.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&Math.abs(e.z-this.target.tile.z)<2&&!e.onBridgeLandType&&!this.game.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length)&&!this.game.map.tileOccupation.isTileOccupiedBy(e,this.target)}}(r=jr=jr||{})[r.None=0]="None",r[r.CircleStrafe=1]="CircleStrafe",r[r.HoverStrafe=2]="HoverStrafe";class fa{constructor(e){this.game=e,this.allowOutOfBounds=!0,this.lastDestLeptons=new Ss,this.currentMoveDir=new Ss,this.currentHorizSpeed=0,this.maneuverType=jr.None,this.deceleratingToTurn=!1}static tickStationary(r,a){if(r.zone===bs.Air){var n=r.tile.onBridgeLandType?a.map.tileOccupation.getBridgeOnTile(r.tile):void 0;let e=r.rules.landable&&!r.unitOrderTrait.getCurrentTask()?.preventLanding,i=r.spawnLinkTrait?.getParent();e&&i?e=!((!i.isUnit()||!i.onBridge)&&n||i.tile!==r.tile):e&&!r.airportBoundTrait&&(e=a.map.getTileZone(r.tile)!==bs.Water&&0<a.map.terrain.getPassableSpeed(r.tile,Jt.Foot,!!r.tile.onBridgeLandType)&&0===a.map.terrain.findObstacles({tile:r.tile,onBridge:n},r).length);let s;if(e){let e=r.airportBoundTrait?.preferredAirport?.dockTrait;var o=e?.isDocked(r)||e?.hasReservedDockForUnit(r);if(!r.airportBoundTrait||o){var h=o?0:270;if(r.direction!==h)return void(r.direction=Tr.tick(r.direction,h,r.rules.rot).facing)}if(r.airportBoundTrait){let e=r.airportBoundTrait.preferredAirport;if(!e?.dockTrait?.isDocked(r))return e?.dockTrait?.getAvailableDockCount()||(e=r.airportBoundTrait.findAvailableAirport(r),r.airportBoundTrait.preferredAirport=e,e&&(h=e.dockTrait.getFirstAvailableDockNumber(),e.dockTrait.reserveDockAt(r,h))),void(e?(r.unitOrderTrait.addTask(new ma(a,e)),r.unitOrderTrait[Lr.onTick](r,a)):r.crashableTrait.crash(void 0))}let t;t=i?i.tile.z+i.tileElevation:r.tile.z+(n?.tileElevation??0),s=ks.tileHeightToWorld(t)}else{var t=r.tile.z+(n?.tileElevation??0),l=r.rules.flightLevel??a.rules.general.flightLevel;s=ks.tileHeightToWorld(t)+l}t=r.position.worldPosition.y;s!==t?(l=Math.abs(s-t),t=Math.sign(s-t)*Math.min(30,l),l=r.tileElevation,r.position.moveByLeptons3(new ss(0,t,0)),r.moveTrait.handleElevationChange(l,a)):e&&(r.zone=bs.Ground,i?i.airSpawnTrait.storeAircraft(r,a):r.onBridge=!!n,a.events.dispatch(new Mr(r)),(n=a.map.tileOccupation.getGroundObjectsOnTile(r.tile).find(e=>e.isOverlay()&&e.rules.crate))&&a.crateGeneratorTrait.pickupCrate(r,n,a))}}static tickCrash(e,t,i){i.rollDelta??(i.rollDelta=t.generateRandomInt(-15,15)),i.pitchDelta??(i.pitchDelta=t.generateRandomInt(0,15)),e.roll+=i.rollDelta,e.pitch+=i.pitchDelta;e=ks.vecWorldToGround(e.moveTrait.velocity);return new ss(e.x,-30,e.y)}onNewWaypoint(e,t,i){this.currentHorizSpeed=ks.vecWorldToGround(e.moveTrait.velocity).length(),this.cancelDestLeptons=void 0}tick(t,e,i,s){if(s){if(!this.cancelDestLeptons){let e=t.tile;this.game.map.isWithinBounds(e)||(e=this.game.map.clampWithinBounds(e)),this.cancelDestLeptons=this.computeCancelDest(e,i)}i=this.cancelDestLeptons}var r=t.position.getMapPosition();let a=i.clone().sub(r);var n=a.length();this.lastDestLeptons.equals(i)||(this.lastDestLeptons.copy(i),s?this.maneuverType=jr.HoverStrafe:t.zone===bs.Air&&this.currentHorizSpeed<5?this.maneuverType=n>ks.LEPTONS_PER_TILE?jr.CircleStrafe:jr.HoverStrafe:this.maneuverType=jr.None,this.deceleratingToTurn=!1),t.zone!==bs.Air&&(t.onBridge=!1,t.zone=bs.Air,this.game.events.dispatch(new Nr(t)));var o=t.tile.onBridgeLandType?this.game.map.tileOccupation.getBridgeOnTile(t.tile):void 0,h=t.tile.z+(o?.tileElevation??0),l=t.rules.flightLevel??this.game.rules.general.flightLevel,s=ks.tileHeightToWorld(h)+l,o=t.position.worldPosition.y,c=Tr.fromMapCoords(a);t.direction===c&&this.maneuverType===jr.None&&n<=ks.LEPTONS_PER_TILE?this.maneuverType=jr.HoverStrafe:t.direction===c&&this.maneuverType===jr.CircleStrafe&&(this.maneuverType=jr.None);let u;switch(this.maneuverType){case jr.HoverStrafe:if(t.attackTrait?.currentTarget){let e=ks.vecWorldToGround(t.attackTrait.currentTarget.getWorldCoords());u=Tr.fromMapCoords(e.sub(r))}else u=t.airportBoundTrait?.preferredAirport?.dockTrait?.hasReservedDockForUnit(t)?0:270;break;case jr.CircleStrafe:case jr.None:u=c;break;default:throw new Error(`Unknown maneuver type "${this.maneuverType}`)}var{facing:d,delta:p}=Tr.tick(t.direction,u,t.rules.rot);t.direction=d,t.roll=Math.sign(p)*t.rules.pitchAngle;let g;switch(this.maneuverType){case jr.HoverStrafe:g=c;break;case jr.CircleStrafe:g=(d-90*Math.sign(p)+360)%360;break;case jr.None:g=d;break;default:throw new Error(`Unknown maneuver type "${this.maneuverType}`)}void 0===this.thrustFacing&&(this.thrustFacing=g);var h=5<this.currentHorizSpeed?t.rules.rot:Number.POSITIVE_INFINITY,{facing:l,delta:h}=Tr.tick(this.thrustFacing,g,h);this.thrustFacing=l,this.currentMoveDir.copy(Tr.toMapCoords(this.thrustFacing));let m=!1,f=0,y=0;let w=!0;s!==o&&(b=Math.abs(s-o),f=Math.sign(s-o)*Math.min(30,b),w=b<=30);let T=t.rules.speed;n<=ks.LEPTONS_PER_TILE&&this.maneuverType!==jr.CircleStrafe&&(T=V(1,T/2,Qi.sqrt(n/ks.LEPTONS_PER_TILE))),this.deceleratingToTurn?this.currentHorizSpeed=Math.max(0,this.currentHorizSpeed-2):this.currentHorizSpeed=Math.min(this.currentHorizSpeed+2,T);var b=this.currentHorizSpeed;this.deceleratingToTurn=!1,m=h?(h=b||h?Br.computeTurnCircle(r,this.currentMoveDir,Math.sign(h)*t.rules.rot,b):void 0,0!==b&&!Er(h,i)||(this.maneuverType===jr.HoverStrafe||n>ks.LEPTONS_PER_TILE?this.deceleratingToTurn=!0:this.maneuverType===jr.None&&(this.maneuverType=jr.HoverStrafe)),y=b,!1):(y=Math.min(b,n),n<=b);let v;v=n<1?(m=!0,a):m?a:this.currentMoveDir.clone().setLength(y);let S=new ss(v.x,f,v.y);n=S.clone();return t.moveTrait.velocity.copy(n),{distance:S,done:m&&w}}computeCancelDest(e,t){var i=t.clone().multiplyScalar(1/ks.LEPTONS_PER_TILE).floor().multiplyScalar(ks.LEPTONS_PER_TILE),i=t.clone().sub(i);return new Ss(e.rx,e.ry).multiplyScalar(ks.LEPTONS_PER_TILE).add(i)}}class ya{constructor(e){this.game=e}create(e){var t=e.rules.locomotor;switch(t){case ii.Infantry:return new Cr(this.game);case ii.Jumpjet:return new Dr(this.game);case ii.Vehicle:case ii.Ship:return new Ir(this.game);case ii.Chrono:return e.isVehicle()&&e.harvesterTrait&&e.rules.teleporter?new Ir(this.game):new wr(this.game);case ii.Aircraft:return new fa(this.game);case ii.Missile:return new da(this.game,this.game.rules.general.getMissileRules(e.name));case ii.Hover:return new Ar(this.game.rules.general.hover);default:throw new Error(`Unhandled locomotor type ${t}`)}}}class wa{constructor(e,t,i,s,r,a,n=!1,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=s,this.rng=r,this.predicate=a,this.includeStartTile=n,this.checkBounds=o,this.pool=[],this.pool=new Array(Qi.pow(2*this.maxDistance+1,2)).fill(0).map((e,t)=>t),this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){for(var e=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(this.includeStartTile||t!==this.startTile)return t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t)?t:void 0},t=2*this.maxDistance+1;this.pool.length;){var i=1<this.pool.length?this.rng.generateRandomInt(0,this.pool.length):0,s=this.pool.splice(i,1)[0],i=s%t,s=Math.floor(s/t),s=e(this.startTile.rx-this.maxDistance+i,this.startTile.ry-this.maxDistance+s);s&&(yield s)}}}class Ta{constructor(e,t,i){this.target=e,this.isChronoshift=t,this.prevTile=i,this.type=is.ObjectTeleport}}(Ur=Ur||{}).onBeforeTeleport=Symbol();class ba{constructor(e){this.game=e,this.movePositionHelper=new qs(e.map)}findPositions(e,t){let i=new Set,s=new Map;for(var r of e){var a=this.findFreeMovePosition(r,i,t);a&&(s.set(r,a),i.add(a.tile))}return s}findFreeMovePosition(i,e,{ignoredBlockers:t,excludedTiles:s,noSlopes:r}={}){let a=this.game.map,n=i.onBridge?a.tileOccupation.getBridgeOnTile(i.tile):void 0,o=new wa(a.tiles,a.mapBounds,i.tile,1,this.game,e=>{if(s?.includes(e))return!1;var t=a.tileOccupation.getBridgeOnTile(e);return(t&&this.movePositionHelper.isEligibleTile(e,t,n,i.tile)||this.movePositionHelper.isEligibleTile(e,void 0,n,i.tile))&&(!r||0===e.rampType)}),h,l;for(;;){var c=o.getNextTile();if(!c)break;if(h=c,l=a.tileOccupation.getBridgeOnTile(c),l&&!this.movePositionHelper.isEligibleTile(c,l,n,i.tile)&&(l=void 0),!e.has(c)){let e=a.terrain.findObstacles({tile:c,onBridge:l},i);if(t&&t.length&&(e=e.filter(e=>!t.includes(e.obj))),!e.length)break}}if(h)return{tile:h,onBridge:l}}}class va extends Hs{constructor(e,t,i){super(),this.game=e,this.target=t,this.options=i}onStart(i){if(!i.moveTrait.isDisabled()&&i.rules.movementZone!==si.Fly){let e,t;if(this.target)({tile:e,toBridge:t}=this.target);else{i=new ba(this.game).findPositions([i],this.options).get(i);if(!i)return;e=i.tile,t=!!i.onBridge}this.children.push(new Sa(this.game,e,t,{closeEnoughTiles:0,ignoredBlockers:this.options?.ignoredBlockers}))}}onTick(e){return!0}}class Sa extends Hs{constructor(e,t,i,s){super(),this.game=e,this.targetTile=t,this.toBridge=i,this.options=s,this.preventOpportunityFire=!1,this.logger=yr.get("move"),this.destinationLeptons=new Ss,this.currentWaypointLeptons=new Ss,this.needsPathUpdate=!1,this.targetChangeRequested=!1,this.allObstaclesAreBlockers=!1,this.blockedPathNodes=[],this.unreachableTargets=[],this.pushTried=!1,this.cancelProcessed=!1,this.cancelRepositionPending=!1,this.targetLinesConfig={pathNodes:[]}}duplicate(){return new Sa(this.game,this.targetTile,this.toBridge,this.options)}setForceMove(e){e?(this.options??(this.options={}),this.options.forceMove=!0):this.options?.forceMove&&(this.options.forceMove=void 0)}onStart(e){if(e.moveTrait.currentWaypoint)throw new Error("Nested move tasks are not supported");void 0===e.moveTrait.locomotor&&(e.moveTrait.locomotor=new ya(this.game).create(e)),e.moveTrait.lastTargetOffset?this.targetOffset=e.moveTrait.lastTargetOffset:this.targetOffset=this.computeTargetOffset(e),e.moveTrait.lastVelocity&&(e.moveTrait.velocity=e.moveTrait.lastVelocity),this.path||(this.computePath(e,e.moveTrait.locomotor),this.targetLinesConfig.isRecalc=!1),this.updateDestination(this.path,this.targetOffset),e.moveTrait.moveState=$r.ReachedNextWaypoint,e.moveTrait.lastMoveResult=void 0,e.moveTrait.lastTargetOffset=void 0,e.moveTrait.lastVelocity=void 0}computeTargetOffset(e){return this.options?.targetOffset??(e.isInfantry()?e.position.getTileOffset():e.position.computeSubCellOffset(0))}computePath(e,t){let i;i=this.options?.allowOutOfBoundsTarget||this.game.map.mapBounds.isWithinBounds(this.targetTile)?e.rules.movementZone===si.Fly?this.computeAirPath(e):t.ignoresTerrain?this.computeDirectJumpPath(e):(this.blockedPathNodes=this.blockedPathNodes.filter(e=>e.obj.isSpawned&&e.node.tile===e.obj.tile),this.computeGroundPath(e)):[],e.rules.movementZone===si.Fly?(this.targetLinesConfig.pathNodes=i.map(({tile:e,onBridge:t})=>({tile:e,onBridge:t})),i.length&&(this.targetLinesConfig.pathNodes[0].onBridge=this.toBridge?this.game.map.tileOccupation.getBridgeOnTile(this.targetTile):void 0)):this.targetLinesConfig.pathNodes=i,this.path=i}computeAirPath(e){return[{tile:this.targetTile,onBridge:void 0},{tile:e.tile,onBridge:void 0}]}computeDirectJumpPath(t){let i=this.game.map;var e=t.onBridge?i.tileOccupation.getBridgeOnTile(t.tile):void 0;let s=this.targetTile,r=this.toBridge?i.tileOccupation.getBridgeOnTile(this.targetTile):void 0,a=this.options?.ignoredBlockers;var n=new js(i.tiles,i.mapBounds,s,{width:1,height:1},0,5,e=>0<i.terrain.getPassableSpeed(e,t.rules.speedType,!!e.onBridgeLandType,a)&&!i.terrain.findObstacles({tile:e,onBridge:!!e.onBridgeLandType},t).find(e=>!a?.includes(e.obj))).getNextTile();return n?(n!==s&&(s=n,r=i.tileOccupation.getBridgeOnTile(s)),[{tile:s,onBridge:r},{tile:t.tile,onBridge:e}]):[]}computeGroundPath(t){let e=t.tile,i=t.onBridge?this.game.map.tileOccupation.getBridgeOnTile(e):void 0;t.moveTrait.moveState===$r.Moving&&t.moveTrait.currentWaypoint&&(e=t.moveTrait.currentWaypoint.tile,i=t.moveTrait.currentWaypoint.onBridge);let s;var r=this.toBridge?this.game.map.tileOccupation.getBridgeOnTile(this.targetTile):void 0,a=this.nodeIsBlockedForPathfinding({tile:this.targetTile,onBridge:r},t);if(Math.abs(e.rx-this.targetTile.rx)<=1&&Math.abs(e.ry-this.targetTile.ry)<=1&&new qs(this.game.map).isEligibleTile(e,i,r,this.targetTile)&&a)s=[];else{const o=this.game.map.getObjectsOnTile(e).find(e=>e.isBuilding());if(o&&!this.game.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)){this.options??(this.options={});var n=this.options?.ignoredBlockers?.includes(o);if(this.options.ignoredBlockers=[...new Set([...this.options?.ignoredBlockers??[],o])],!n&&o.dockTrait){let t=new Set(o.dockTrait?.getAllDockTiles()),e=this.game.map.tileOccupation.calculateTilesForGameObject(o.tile,o);e.filter(e=>!t.has(e)).forEach(e=>this.blockedPathNodes.push({node:{tile:e,onBridge:void 0},obj:o}))}}n=this.game.map.getGroundObjectsOnTile(this.targetTile).find(e=>(e.isInfantry()||e.isVehicle())&&e.disguiseTrait?.hasTerrainDisguise()&&!(this.game.alliances.haveSharedIntel(t.owner,e.owner)||e.owner.sharedDetectDisguiseTrait?.has(t)));n&&this.blockedPathNodes.push({node:{tile:this.targetTile,onBridge:r},obj:n}),s=this.game.map.terrain.computePath(t.rules.speedType,e,!!i,this.targetTile,this.toBridge,{maxExpandedNodes:this.allObstaclesAreBlockers?Math.min(300,this.options?.maxExpandedPathNodes??Number.POSITIVE_INFINITY):this.options?.maxExpandedPathNodes,bestEffort:!this.options?.strictCloseEnough,ignoredBlockers:[...new Set([...this.options?.ignoredBlockers??[],...this.options?.pathFinderIgnoredBlockers??[]])],excludeTiles:this.allObstaclesAreBlockers||this.blockedPathNodes.length?e=>this.nodeIsBlockedForPathfinding(e,t):void 0})}return s}nodeIsBlockedForPathfinding(t,e){return this.allObstaclesAreBlockers?!!this.game.map.terrain.findObstacles(t,e).find(e=>!this.options?.ignoredBlockers?.includes(e.obj)):!!this.blockedPathNodes.find(({node:e})=>e.tile===t.tile&&e.onBridge===t.onBridge)}updateDestination(e,t){e=e.length?e[0].tile:this.targetTile;this.destinationLeptons.set(e.rx*ks.LEPTONS_PER_TILE,e.ry*ks.LEPTONS_PER_TILE).add(t)}canStopAtTile(t,i,s){if(t.zone===bs.Air){if((!t.isAircraft()||!t.airportBoundTrait)&&!t.rules.spawned&&(!this.options?.forceMove||!t.rules.balloonHover||t.rules.hoverAttack)&&(!this.game.map.terrain.getPassableSpeed(i,Jt.Amphibious,s)||this.game.map.getObjectsOnTile(i).filter(e=>e.isBuilding()&&!e.isDestroyed&&!e.dockTrait?.hasReservedDockForUnit(t)&&!t.rules.dock.includes(e.name)||e.isUnit()&&e.tile===i&&e.moveTrait.moveState!==$r.Moving&&e!==t).length))return!1}else if(t.isInfantry()){let e=this.game.map.getGroundObjectsOnTile(i).filter(e=>e.isInfantry()&&e.tile===i&&e.onBridge===s&&e.moveTrait.moveState!==$r.Moving&&e!==t);if(2<e.length||e.find(e=>e.position.subCell===t.position.subCell))return!1}return!(t.zone!==bs.Air&&t.rules.tooBigToFitUnderBridge&&!s&&i.onBridgeLandType&&this.game.map.tileOccupation.getBridgeOnTile(i)?.isHighBridge())&&!(!this.isCancelling()&&this.options?.strictCloseEnough&&void 0!==this.options?.closeEnoughTiles&&!this.isCloseEnoughToDest(t,i,this.options.closeEnoughTiles))}isCloseEnoughToDest(e,t,i){if(void 0===i)return!0;let s=new Cs(this.game.map.tileOccupation);return!(s.tileDistance(this.targetTile,t)>i)}hasReachedDestination(e){return!this.path.length}updateTarget(e,t){this.targetTile=e,this.toBridge=t,this.needsPathUpdate=!0,this.targetChangeRequested=!0}onEnd(e){e.moveTrait.collisionState=Xr.Resolved,e.moveTrait.currentWaypoint=void 0,this.targetOffset.equals(this.computeTargetOffset(e))||(e.moveTrait.lastTargetOffset=this.targetOffset)}forceCancel(e){return!(!this.cancellable||this.children.some(e=>!e.cancellable))&&(!(!this.options?.allowOutOfBoundsTarget&&!this.game.map.isWithinBounds(e.tile))&&(this.status!==Ls.Running&&this.status!==Ls.Cancelling||(e.moveTrait.unreservePathNodes(),e.moveTrait.lastMoveResult=qr.Cancel,this.onEnd(e),e.moveTrait.lastTargetOffset=this.targetOffset,e.moveTrait.lastVelocity=e.moveTrait.velocity.clone()),this.status=Ls.Cancelled,!0))}onTick(r){if(r.moveTrait.isDisabled()&&r.moveTrait.moveState===$r.ReachedNextWaypoint)return!!this.isCancelling()&&(r.moveTrait.lastMoveResult=qr.Cancel,!0);this.needsPathUpdate&&(r.moveTrait.moveState===$r.PlanMove&&(this.inPlanningForTicks=void 0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.collisionState=Xr.Resolved,r.moveTrait.moveState=$r.ReachedNextWaypoint,r.moveTrait.velocity.set(0,0,0)),this.computePath(r,r.moveTrait.locomotor),this.path.length||this.unreachableTargets.push({tile:this.targetTile,toBridge:this.toBridge}),this.updateDestination(this.path,this.targetOffset),this.targetLinesConfig.isRecalc=!this.targetChangeRequested,this.targetChangeRequested=!1,this.needsPathUpdate=!1,this.allObstaclesAreBlockers=!1);let i=this.game.map;if(r.moveTrait.moveState===$r.ReachedNextWaypoint){r.moveTrait.unreservePathNodes();var s=this.path.findIndex(e=>e===r.moveTrait.currentWaypoint);if(-1!==s?this.path.splice(s):this.path.pop(),r.moveTrait.currentWaypoint=void 0,this.isCancelling()?!this.cancelProcessed:this.hasReachedDestination(r)){var a=!this.isCancelling()&&!this.isCloseEnoughToDest(r,r.tile,this.options?.closeEnoughTiles);if(!a&&this.canStopAtTile(r,r.tile,r.onBridge))return r.moveTrait.lastMoveResult=this.isCancelling()?qr.Cancel:qr.Success,!0;{if(5<this.unreachableTargets.length)return r.moveTrait.lastMoveResult=qr.Fail,this.log(r,"bail_max_unreachable_dest"),!0;let e=r.tile,t=r.onBridge?i.tileOccupation.getBridgeOnTile(e):void 0;a&&(e=this.targetTile,t=this.toBridge?i.tileOccupation.getBridgeOnTile(e):void 0);s=this.findRelocationTile(e,t,r);if(!s)return r.moveTrait.lastMoveResult=a?qr.Fail:qr.CloseEnough,this.log(r,"bail_no_free_dest"),!0;a=!t||t.isHighBridge()?i.tileOccupation.getBridgeOnTile(s):void 0;return this.updateTarget(s,!!a),this.isCancelling()&&(this.cancelProcessed=!0,this.cancelRepositionPending=!0),!1}}if(this.cancelProcessed&&!this.path.length)return r.moveTrait.lastMoveResult=qr.Cancel,!0;this.cancelProcessed=!1,r.moveTrait.moveState=$r.PlanMove;let e=r.moveTrait.locomotor;r.moveTrait.currentWaypoint=e.selectNextWaypoint?e.selectNextWaypoint(r,this.path):this.path[this.path.length-1],this.currentWaypointLeptons.set(r.moveTrait.currentWaypoint.tile.rx,r.moveTrait.currentWaypoint.tile.ry).multiplyScalar(ks.LEPTONS_PER_TILE).add(this.targetOffset);a=e.onNewWaypoint(r,this.currentWaypointLeptons,this.destinationLeptons);if(a)return this.children.push(...a),!1}if(r.moveTrait.moveState===$r.PlanMove){if(this.isCancelling()&&!this.cancelRepositionPending)return r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=$r.ReachedNextWaypoint,this.onTick(r);if(this.inPlanningForTicks=void 0===this.inPlanningForTicks?0:this.inPlanningForTicks+1,200<this.inPlanningForTicks)return this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,r.moveTrait.velocity.set(0,0,0),this.log(r,"repath_plan_timeout"),!1;if(r.rules.movementZone!==si.Fly&&!r.moveTrait.locomotor.ignoresTerrain){let t=this.path.slice(this.path.indexOf(r.moveTrait.currentWaypoint)).reverse();var n,e,o=r.moveTrait.velocity.length();for(n of t){if(!i.terrain.getPassableSpeed(n.tile,r.rules.speedType,!!n.onBridge,this.options?.ignoredBlockers))return this.options?.stopOnBlocker&&i.terrain.findObstacles(n,r).some(e=>e.obj===this.options.stopOnBlocker)?(r.moveTrait.lastMoveResult=qr.CloseEnough,!0):(this.needsPathUpdate=!0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=$r.ReachedNextWaypoint,this.onTick(r));if(!n.onBridge){var h=i.getGroundObjectsOnTile(n.tile).find(e=>e.isOverlay()&&e.rules.crate);if(h)if(this.game.crateGeneratorTrait.peekInsideCrate(h)===Bs.Unit){this.game.crateGeneratorTrait.pickupCrate(r,h,this.game);h=this.game.map.getGroundObjectsOnTile(n.tile).find(e=>e.isUnit()&&!e.onBridge);if(h)return this.needsPathUpdate=!0,this.blockedPathNodes.push({node:n,obj:h}),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=$r.ReachedNextWaypoint,this.onTick(r)}}for(e of i.terrain.findObstacles(n,r).filter(e=>!this.options?.ignoredBlockers?.includes(e.obj))){if(e.static)return this.needsPathUpdate=!0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=$r.ReachedNextWaypoint,this.onTick(r);if(e.obj.rules.crushable){if([Jt.Track,Jt.Hover].includes(r.rules.speedType)&&r.crusher&&(!e.obj.isTechno()||!this.game.areFriendly(e.obj,r)))continue;if(!e.obj.isTechno())return this.needsPathUpdate=!0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=$r.ReachedNextWaypoint,this.onTick(r)}if(e.obj.isTerrain()){if(!r.isInfantry())throw new Error(`Obstacle ${e.obj.name} should be a blocker for non infantry`);var l=this.findFreeSubCell(r,n);return void 0!==l?this.relocateToSubCell(r,l):(this.needsPathUpdate=!0,this.blockedPathNodes.push({node:n,obj:e.obj}),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=$r.ReachedNextWaypoint),this.onTick(r)}if(!e.obj.isTechno())throw new Error(`Unexpected obstacle of type ${e.obj.type}`);const f=e.obj;var c=f.isUnit()?f.moveTrait.velocity.length():0;if(!f.isAircraft()||f.zone!==bs.Ground||!this.options?.ignoredBlockers?.some(e=>e.isBuilding()&&e.dockTrait?.isDocked(f))){if(1===t.length&&f.isUnit()&&c&&o&&o<=c&&r.direction===f.direction&&f.tile===n.tile&&f.moveTrait.currentWaypoint?.tile!==n.tile)break;if(f.isBuilding()||f.moveTrait.moveState===$r.Idle||f.moveTrait.collisionState!==Xr.Resolved){if(!o&&r.moveTrait.collisionState!==Xr.Resolved&&f.isUnit()&&f.moveTrait.collisionState!==Xr.Resolved)return 200<this.inPlanningForTicks+1&&(this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,this.log(r,"repath_waited_too_long_blocker "+f.id),r.moveTrait.velocity.set(0,0,0)),!1;{if(f.isInfantry()&&r.isInfantry()&&f.moveTrait.collisionState===Xr.Resolved){var u=this.findFreeSubCell(r,n);if(void 0!==u)return this.relocateToSubCell(r,u),this.onTick(r)}l=Gs(this.path.slice(0,this.path.indexOf(n)),e=>!i.terrain.findObstacles(e,r).length);if(-1===l){if(this.canStopAtTile(r,r.tile,r.onBridge)&&this.isCloseEnoughToDest(r,r.tile,this.options?.closeEnoughTiles))return r.moveTrait.lastMoveResult=qr.CloseEnough,this.log(r,"bail_waypoints_blocked_close_enough"),!0;if(!(0===this.options?.closeEnoughTiles||Math.abs(r.tile.rx-this.targetTile.rx)<=1&&Math.abs(r.tile.ry-this.targetTile.ry)<=1))return this.needsPathUpdate=!0,this.blockedPathNodes.push(...this.path.slice(0,this.path.indexOf(n)+1).map(e=>({node:e,obj:i.terrain.findObstacles(e,r)[0].obj}))),r.moveTrait.velocity.set(0,0,0),this.log(r,"repath_waypoints_blocked_too_far"),!1}let e;if(e=-1!==l?(u=this.path[l],i.terrain.computePath(r.rules.speedType,r.tile,r.onBridge,u.tile,!!u.onBridge,{maxExpandedNodes:15,bestEffort:!1,excludeTiles:e=>!!i.terrain.findObstacles(e,r).length})):[],e.length||f.owner!==r.owner||1!==t.length)return e.length?(this.path.splice(l,this.path.length,...e),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=$r.ReachedNextWaypoint,this.onTick(r)):((d=this.selectWeaponVsObstacle(r,f))?(this.children.push(r.attackTrait.createAttackTask(this.game,f,f.tile,d,{passive:!0,holdGround:!0})),r.moveTrait.velocity.set(0,0,0)):this.options?.forceWaitOnPathBlocked?(this.children.push(new $s(40)),this.inPlanningForTicks=0,r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=Xr.Waiting):(this.needsPathUpdate=!0,this.blockedPathNodes.push({node:n,obj:f}),f.isBuilding()&&(this.allObstaclesAreBlockers=!0),this.log(r,"repath_unavoidable_blocker "+f.id),r.moveTrait.velocity.set(0,0,0)),!1);d=f.unitOrderTrait.hasTasks();if(this.pushTried||f.isBuilding()||f.moveTrait.collisionState===Xr.Waiting||d||f.isAircraft()&&f.missileSpawnTrait)return!this.options?.forceWaitOnPathBlocked&&(f.isBuilding()||d&&f.moveTrait.moveState===$r.Idle||200<this.inPlanningForTicks+40)?(this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,this.log(r,"repath_blocker_busy_wait_timeout "+f.id),r.moveTrait.velocity.set(0,0,0)):(this.children.push(new $s(40)),this.options?.forceWaitOnPathBlocked?this.inPlanningForTicks=0:this.inPlanningForTicks+=40,r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=Xr.Waiting),!1;d=new Ss(f.tile.rx-r.tile.rx,f.tile.ry-r.tile.ry);return this.pushTried=!0,f.unitOrderTrait.addTask(new fr(this.game,d)),this.children.push(new $s(1)),r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=Xr.Waiting,this.log(r,"push "+f.id),!1}}if(f.isInfantry()&&r.isInfantry()){var d=this.findFreeSubCell(r,n);if(void 0!==d)return this.relocateToSubCell(r,d),this.onTick(r)}if(!o)return 40<this.inPlanningForTicks&&(r.moveTrait.collisionState=Xr.Waiting),!1;if(180===Math.abs(r.direction-f.direction))return r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=Xr.Waiting,!1;if(Math.abs(r.direction-f.direction)<=45&&1.5*c<o){c=this.path.indexOf(n);if(5<=c){let e=Gs(this.path.slice(0,c-5),e=>!i.terrain.findObstacles(e,r).length);if(-1!==e){c=this.path[e],c=i.terrain.computePath(r.rules.speedType,r.tile,r.onBridge,c.tile,!!c.onBridge,{maxExpandedNodes:15,bestEffort:!1,excludeTiles:t=>!!i.terrain.findObstacles(t,r).length||this.path.findIndex(e=>e.tile===t.tile&&e.onBridge===t.onBridge)>e});if(c.length)return this.path.splice(e,this.path.length,...c),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=$r.ReachedNextWaypoint,this.onTick(r)}}return r.moveTrait.collisionState=Xr.Waiting,r.moveTrait.velocity.set(0,0,0),!1}return r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=Xr.Waiting,!1}}}if(r.rules.speedType===Jt.Track&&o){var p,g=this.path.indexOf(r.moveTrait.currentWaypoint);if(0<g){let t=this.path[g-1];for(p of i.getGroundObjectsOnTile(t.tile).filter(e=>e.isUnit()&&e.onBridge===!!t.onBridge&&e.rules.crushable&&e.veteranTrait?.hasVeteranAbility(hi.SCATTER)&&!this.game.areFriendly(e,r)))p.unitOrderTrait.hasTasks()||p.unitOrderTrait.addTask(new va(this.game))}}r.moveTrait.reservedPathNodes.length||(r.moveTrait.reservedPathNodes.push(...t),t.forEach(e=>{i.tileOccupation.occupySingleTile(e.tile,r)}))}r.moveTrait.moveState=$r.Moving,this.inPlanningForTicks=void 0,this.unreachableTargets.length=0,this.pushTried=!1,r.moveTrait.collisionState===Xr.Waiting&&(r.moveTrait.collisionState=Xr.Resolved)}if(r.moveTrait.moveState===$r.Moving){let e=r.moveTrait.locomotor,{distance:t,done:i,isTeleport:s}=e.tick(r,this.currentWaypointLeptons,this.destinationLeptons,(this.isCancelling()||!this.path.length)&&!this.cancelRepositionPending);if(s&&r.traits.filter(Ur).forEach(e=>{e[Ur.onBeforeTeleport](r,this.game,!0,!0)}),t.length()){a=r.tile,g=e.allowOutOfBounds;if(t.y?(m=r.tileElevation,r.position.moveByLeptons3(t,g),r.moveTrait.handleElevationChange(m,this.game)):r.position.moveByLeptons(t.x,t.z,g),r.tile!==a){var m=r.onBridge?this.game.map.tileOccupation.getBridgeOnTile(a):void 0,g=function(t,i){for(let e=t.length-1;0<=e;e--)if(i(t[e],e,t))return t[e]}(this.path,e=>e.tile===r.tile),m=g?g.onBridge:m||r.moveTrait.currentWaypoint.onBridge?this.game.map.tileOccupation.getBridgeOnTile(r.tile):void 0;if(r.moveTrait.handleTileChange(a,m,!1,this.game,s),s&&(r.moveTrait.lastTeleportTick=this.game.currentTick,this.game.events.dispatch(new Ta(r,!0,a))),r.isDestroyed)return!0}}if(i)return r.moveTrait.moveState=$r.ReachedNextWaypoint,this.onTick(r)}return!1}selectWeaponVsObstacle(e,t){let i;if(!this.game.areFriendly(t,e)&&e.attackTrait&&!e.attackTrait.isDisabled()&&e.attackTrait.isIdle()&&(i=e.attackTrait.selectWeaponVersus(e,t,this.game,!1,!0))&&i.name!==e.armedTrait?.deathWeapon?.name&&(!i.rules.limboLaunch||!i.warhead.rules.parasite)&&!i.warhead.rules.mindControl)return i}findRelocationTile(s,r,a){let n=this.game.map,i;if(a.rules.movementZone===si.Fly){var t=e=>!n.tileOccupation.getGroundObjectsOnTile(e).some(e=>e.isBuilding()&&!e.isDestroyed||e.isTerrain()||e.isOverlay()&&e.rules.isARock);let e=new wa(n.tiles,n.mapBounds,s,1,this.game,t);if(i=e.getNextTile(),!i){let e=new js(n.tiles,n.mapBounds,s,a.getFoundation(),2,15,t);i=e.getNextTile()}}else{let e=new qs(n),t=new js(n.tiles,n.mapBounds,s,{width:1,height:1},0,5,t=>{let i=!r||r.isHighBridge()?n.tileOccupation.getBridgeOnTile(t):void 0;return!this.unreachableTargets.find(e=>e.tile===t&&e.toBridge===!!i)&&(a.zone===bs.Air||!n.terrain.findObstacles({tile:t,onBridge:i},a).length&&e.isEligibleTile(t,i,r,s))&&this.canStopAtTile(a,t,!!i)});i=t.getNextTile()}return i}findFreeSubCell(t,i){let e=this.game.map.getGroundObjectsOnTile(i.tile);var s=e.filter(e=>e.isInfantry()&&e.onBridge===!!i.onBridge&&e!==t).map(e=>e.position.desiredSubCell),r=e.filter(e=>e.isTerrain()).map(e=>e.rules.getOccupiedSubCells(this.game.map.getTheaterType())).flat();let a=[...s,...r];return Da.SUB_CELLS.find(e=>-1===a.indexOf(e))}relocateToSubCell(e,t){e.position.desiredSubCell=t;t=e.position.computeSubCellOffset(t);this.targetOffset=t,this.currentWaypointLeptons.set(e.moveTrait.currentWaypoint.tile.rx,e.moveTrait.currentWaypoint.tile.ry).multiplyScalar(ks.LEPTONS_PER_TILE).add(this.targetOffset),this.updateDestination(this.path,this.targetOffset),e.moveTrait.locomotor.onWaypointUpdate?.(e,this.currentWaypointLeptons,this.destinationLeptons)}getTargetLinesConfig(e){var t;return this.path||((t=e.moveTrait).locomotor??(t.locomotor=new ya(this.game).create(e)),this.computePath(e,e.moveTrait.locomotor),this.targetLinesConfig.isRecalc=!1),this.targetLinesConfig}log(e,t){this.logger.debug(`<${e.id}>: ${t}`)}}(Wr=Wr||{}).onDestroy=Symbol(),(r=zr=zr||{})[r.None=0]="None",r[r.Normal=1]="Normal",r[r.Demolish=2]="Demolish",r[r.Crush=3]="Crush",r[r.Temporal=4]="Temporal",r[r.Sink=5]="Sink",(Vr=Vr||{}).onTileChange=Symbol(),(Hr=Hr||{}).onTileChange=Symbol();class ka{constructor(e,t){this.target=e,this.source=t,this.type=is.EnterTile}}(Gr=Gr||{}).onElevationChange=Symbol(),(r=$r=$r||{})[r.Idle=0]="Idle",r[r.ReachedNextWaypoint=1]="ReachedNextWaypoint",r[r.PlanMove=2]="PlanMove",r[r.Moving=3]="Moving",(r=qr=qr||{})[r.Success=0]="Success",r[r.Cancel=1]="Cancel",r[r.CloseEnough=2]="CloseEnough",r[r.Fail=3]="Fail",(r=Xr=Xr||{})[r.Waiting=0]="Waiting",r[r.Resolved=1]="Resolved";const Oa=e=>e instanceof Sa||e.children[0]&&Oa(e.children[0]);class _a{constructor(e,t){this.gameObject=e,this.tileOccupation=t,this.disabled=!1,this.speedPenalty=0,this.velocity=new ss,this.reservedPathNodes=[],this.moveState=$r.Idle,this.collisionState=Xr.Resolved}get baseSpeed(){return this.gameObject.rules.speed*(this.gameObject.veteranTrait?.getVeteranSpeedMultiplier()??1)*this.gameObject.crateBonuses.speed*(this.gameObject.isVehicle()&&this.gameObject.healthTrait.health<=50&&this.gameObject.rules.locomotor!==ii.Hover?.75:1)*(1-this.speedPenalty)}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}isMoving(){return this.moveState===$r.Moving}isIdle(){return this.moveState===$r.Idle}isWaiting(){return this.collisionState===Xr.Waiting}[Lr.onTick](e,t){var i;this.moveState!==$r.Idle&&this.collisionState===Xr.Resolved&&((i=e.unitOrderTrait.getCurrentTask())&&Oa(i)||(this.velocity.set(0,0,0),this.moveState=$r.Idle,this.locomotor=void 0,!i&&!e.attackTrait?.currentTarget&&e.isVehicle()&&e.turretTrait&&(e.turretTrait.desiredFacing=e.direction))),this.moveState===$r.Idle&&(e.rules.locomotor===ii.Jumpjet?Dr.tickStationary(e,t):e.isAircraft()&&e.rules.locomotor===ii.Aircraft&&fa.tickStationary(e,t))}[Wr.onDestroy](e,t){this.unreservePathNodes()}teleportUnitToTile(e,t,i,s,r){let a=this.gameObject;var n=a.tile;a.traits.filter(Ur).forEach(e=>{e[Ur.onBeforeTeleport](a,r,i,s)}),a.position.tileElevation=a.tileElevation,a.position.tile=e,a.position.subCell=a.position.desiredSubCell,this.handleTileChange(n,t,!0,r,!0),s||(this.unreservePathNodes(),this.speedPenalty=0,this.velocity.set(0,0,0),this.moveState=$r.Idle,this.collisionState=Xr.Resolved,this.locomotor=void 0,this.currentWaypoint=void 0,this.lastTargetOffset=void 0,this.lastVelocity=void 0,this.lastMoveResult=qr.Cancel,a.isVehicle()&&(a.spinVelocity=0,a.turretTrait&&(a.turretTrait.desiredFacing=a.direction))),this.lastTeleportTick=r.currentTick,r.events.dispatch(new Ta(a,i,n))}handleTileChange(t,e,i,s,r=!1){const a=this.gameObject;if(s.map.tileOccupation.unoccupyTileRange(t,a),s.map.tileOccupation.occupyTileRange(a.tile,a),s.map.technosByTile.updateObject(a),a.zone!==bs.Air){var n=a.onBridge?s.map.tileOccupation.getBridgeOnTile(t):void 0,o=a.onBridge?t.onBridgeLandType:t.landType,h=e?a.tile.onBridgeLandType:a.tile.landType;o!==h&&(0<s.rules.getLandRules(h).getSpeedModifier(a.rules.speedType)||a.rules.speedType===Jt.Amphibious||r)&&(a.zone=Os(h)),e!==n&&(a.position.tileElevation+=-(n?.tileElevation??0)+(e?.tileElevation??0),a.onBridge=!!e);var l,e=a.moveTrait.reservedPathNodes.findIndex(e=>e.tile===a.tile&&!!e.onBridge===a.onBridge);if(-1!==e&&a.moveTrait.reservedPathNodes.splice(e,1),a.crusher)for(l of s.map.getGroundObjectsOnTile(a.tile).filter(e=>(!e.isUnit()||e.onBridge===a.onBridge)&&e.rules.crushable&&!(e.isInfantry()&&e.stance===Rs.Paradrop)&&(!(e.isTechno()&&!i)||!s.areFriendly(e,a))))l.isDestroyed||(l.isInfantry()&&(l.infDeathType=ei.None),a.isVehicle()&&l.isOverlay()&&l.rules.wall&&a.applyRocking(0,.5),l.deathType=zr.Crush,s.destroyObject(l,{player:a.owner,obj:a}));a.onBridge||(e=s.map.tileOccupation.getGroundObjectsOnTile(a.tile).find(e=>e.isOverlay()&&e.rules.crate))&&s.crateGeneratorTrait.pickupCrate(a,e,s)}s.traits.filter(Vr).forEach(e=>{e[Vr.onTileChange](a,s,t,r)}),a.traits.filter(Hr).forEach(e=>{e[Hr.onTileChange](a,s,t,r)}),s.events.dispatch(new ka(a.tile,a))}handleElevationChange(t,i){i.traits.filter(Gr).forEach(e=>{e[Gr.onElevationChange](this.gameObject,i,t)})}unreservePathNodes(){this.reservedPathNodes.forEach(e=>{e.tile!==this.gameObject.tile&&this.tileOccupation.unoccupySingleTile(e.tile,this.gameObject)}),this.reservedPathNodes.length=0}dispose(){this.gameObject=void 0}}class Ia{constructor(){this.suppressionTicks=0,this.enabled=!0}disable(){this.enabled=!1}isSuppressed(){return this.enabled&&0<this.suppressionTicks}supress(){this.enabled&&(this.suppressionTicks=30)}[Lr.onTick](){0<this.suppressionTicks&&this.suppressionTicks--}}class Ca{constructor(){this.allTraits=[],this.traitsByTypeCache=new Map}add(e){this.allTraits.push(e),this.traitsByTypeCache.clear()}addToFront(e){this.allTraits.unshift(e),this.traitsByTypeCache.clear()}remove(e){e=this.allTraits.indexOf(e);-1!==e&&(this.allTraits.splice(e,1),this.traitsByTypeCache.clear())}filter(t){let e=this.traitsByTypeCache.get(t);return e||(e="function"==typeof t?this.allTraits.filter(e=>e instanceof t):this.allTraits.filter(e=>this.traitImplements(e,t)),this.traitsByTypeCache.set(t,e)),e}get(e){e=this.find(e);if(!e)throw new Error("No matching trait found");return e}find(e){return this.filter(e)[0]}getAll(){return this.allTraits}traitImplements(e,t){for(var i of Object.getOwnPropertyNames(t))if(void 0===e[t[i]])return!1;return!0}clear(){this.allTraits.length=0,this.traitsByTypeCache.clear()}dispose(){this.getAll().forEach(e=>e.dispose?.()),this.clear()}}(Zr=Zr||{}).onChange=Symbol(),(Qr=Qr||{}).onSpawn=Symbol(),(Yr=Yr||{}).onUnspawn=Symbol(),(Kr=Kr||{}).onAttack=Symbol();class Aa{constructor(e,t,i,s){this.traits=new Ca,this.cachedTraits={tick:[]},this.isCrashing=!1,this.isDestroyed=!1,this.deathType=zr.Normal,this.isDisposed=!1,this.isSpawned=!1,this.type=e,this.name=t,this.rules=i,this.art=s}get tile(){return this.position.tile}get tileElevation(){return this.position.tileElevation}getFoundation(){return{width:1,height:1}}isSmudge(){return this.type===Bt.Smudge}isOverlay(){return this.type===Bt.Overlay}isTerrain(){return this.type===Bt.Terrain}isProjectile(){return this.type===Bt.Projectile}isDebris(){return this.type===Bt.Debris}isBuilding(){return!1}isInfantry(){return!1}isVehicle(){return!1}isAircraft(){return!1}isUnit(){return!1}isTechno(){return!1}update(e){for(var t of this.cachedTraits.tick)t[Lr.onTick](this,e)}onSpawn(t){this.isSpawned=!0,this.traits.filter(Qr).forEach(e=>{e[Qr.onSpawn](this,t)})}onUnspawn(t){this.isSpawned=!1,this.traits.filter(Yr).forEach(e=>{e[Yr.onUnspawn](this,t)})}onDestroy(t,i,s){this.traits.filter(Wr).forEach(e=>{e[Wr.onDestroy](this,t,i,s)})}onOwnerChange(t,i){this.traits.filter(Zr).forEach(e=>{e[Zr.onChange](this,t,i)})}onAttack(t,i){this.traits.filter(Kr).forEach(e=>{e[Kr.onAttack](this,i,t)})}addTrait(e){this.traits.add(e),e[Lr.onTick]&&this.cachedTraits.tick.push(e)}getUiName(){return this.rules.uiName}getHash(){var e=this.position.worldPosition;return H([this.id,...new Uint8Array(new Float64Array([e.x,e.y,e.z]).buffer),...this.traits.getAll().map(e=>e.getHash?.()??0)])}debugGetState(){return{id:this.id,position:this.position.worldPosition.toArray(),traits:this.traits.getAll().reduce((e,t)=>{var i=t.debugGetState?.();return void 0!==i&&(e[t.constructor.name]=i),e},{})}}dispose(){this.isDisposed=!0,this.traits.dispose(),this.cachedTraits.tick.length=0}}(r=Jr=Jr||{})[r.None=0]="None",r[r.Veteran=1]="Veteran",r[r.Elite=2]="Elite";class Ba extends Aa{constructor(e,t,i,s){super(e,t,i,s),this.explodes=this.rules.explodes,this.radarInvisible=this.rules.radarInvisible,this.c4=this.rules.c4,this.crusher=this.rules.crusher,this.defaultToGuardArea=this.rules.defaultToGuardArea,this.guardMode=this.rules.defaultToGuardArea,this.purchaseValue=this.rules.cost}get primaryWeapon(){return this.armedTrait?.primaryWeapon}get secondaryWeapon(){return this.armedTrait?.secondaryWeapon}get ammo(){return this.ammoTrait?.ammo}get sight(){return Math.min(ns.MAX_SIGHT,this.rules.sight*(this.veteranTrait?.getVeteranSightMultiplier()??1))}get veteranLevel(){return this.veteranTrait?.veteranLevel??Jr.None}resetGuardModeToIdle(){this.guardMode=this.defaultToGuardArea,this.guardArea=void 0}update(e){if(this.warpedOutTrait.isActive())for(var t of this.cachedTraits.tick)t.ticksWhenWarpedOut&&t[Lr.onTick](this,e);else super.update(e)}isTechno(){return!0}}class xa{constructor(){this.cooldownTicks=Number.POSITIVE_INFINITY,this._actionDueThisTick=!1}[Lr.onTick](e,t){this._actionDueThisTick=!1;var i=!e.unitOrderTrait.hasTasks();i&&!this.idle?this.resetCooldown(t):i?0===this.cooldownTicks?(this.doIdleAction(e,t),this.resetCooldown(t)):this.cooldownTicks--:this.cooldownTicks=Number.POSITIVE_INFINITY,this.idle=i}doIdleAction(e,t){if(e.isInfantry()){if(e.rules.fraidycat)if(.5<t.generateRandom())return void e.unitOrderTrait.addTask(new va(t,void 0,{noSlopes:!0}));this._actionDueThisTick=!0}}actionDueThisTick(){return this._actionDueThisTick}resetCooldown(e){var t=e.rules.audioVisual.idleActionFrequency,e=e.generateRandom()*t*.5,e=Math.max(0,t-e);this.cooldownTicks=Math.floor(e*Fs.BASE_TICKS_PER_SECOND)}}class Ea{constructor(e){this.gameObject=e,this.type=is.ObjectCrashing}}(ea=ea||{}).onCrash=Symbol();class Pa{constructor(e){this.gameObject=e,this.crashingEvtSent=!1,this.crashState={}}[Lr.onTick](i,s){if(i.isCrashing){if(this.crashingEvtSent||(this.crashingEvtSent=!0,i.traits.filter(ea).forEach(e=>e[ea.onCrash](i,s)),s.events.dispatch(new Ea(i))),i.rules.locomotor!==ii.Jumpjet&&i.rules.locomotor!==ii.Aircraft)throw new Error(`Crashing logic not implemented for locomotor ${ii[i.rules.locomotor]}`);{let e;if(i.rules.locomotor===ii.Jumpjet)e=Dr.tickCrash(i,s,this.crashState);else{if(i.rules.locomotor!==ii.Aircraft)throw new Error(`Unhandled locomotor type "${i.rules.locomotor}"`);if(!i.isAircraft())throw new Error(`Obj "${i.name}#${i.id} is not an aircraft`);e=fa.tickCrash(i,s,this.crashState)}let t=!1;var r,a,n=e.clone().add(i.position.worldPosition);s.map.isWithinHardBounds(n)?(a=i.tile,r=i.tileElevation,i.position.moveByLeptons3(e),i.tile!==a&&i.moveTrait.handleTileChange(a,void 0,!1,s),a=(n=i.tile.onBridgeLandType?s.map.tileOccupation.getBridgeOnTile(i.tile):void 0)?.tileElevation??0,i.position.tileElevation=Math.max(i.position.tileElevation,a),i.position.tileElevation===a&&(i.zone=s.map.getTileZone(i.tile),i.onBridge=!!n,t=!0),i.tileElevation!==r&&i.moveTrait.handleElevationChange(r,s)):t=!0,t&&s.destroyObject(i,this.attackerInfo)}}}crash(e){this.attackerInfo=e,this.gameObject.isCrashing=!0,this.gameObject.cachedTraits.tick.length=0,this.gameObject.cachedTraits.tick=[this]}dispose(){this.gameObject=void 0}}class Na{infiltrate(e,t,i){var s;t.rules.radar&&![...t.owner.buildings].some(e=>e.rules.spySat)&&i.mapShroudTrait.resetShroud(t.owner,i),0<t.rules.power&&(s=i.rules.general.spyPowerBlackout,t.owner.powerTrait?.setBlackoutFor(s,i)),t.superWeaponTrait&&t.superWeaponTrait.getSuperWeapon(t)?.resetTimer(),0<t.rules.storage&&(s=W(i.rules.general.spyMoneyStealPercent,0,1),s=Math.floor(t.owner.credits*s),t.owner.credits-=s,e.owner.credits+=s),!i.rules.ai.buildTech.includes(t.name)||void 0!==(i=t.rules.aiBasePlanningSide)&&e.owner.production.addStolenTech(i),[Ji.InfantryType,Ji.UnitType].includes(t.factoryTrait?.type)&&e.owner.production?.addVeteranType(t.factoryTrait.type)}}class Ma{constructor(){this.firepower=1,this.armor=1,this.speed=1}}class Da extends Ba{constructor(e,t,i){super(Bt.Infantry,e,t,i),this.direction=0,this.onBridge=!1,this.zone=bs.Ground,this._stance=Rs.None,this.isFiring=!1,this.isPanicked=!1,this.infDeathType=ei.Gunfire,this.crateBonuses=new Ma}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,s){let r=new this(e,t,i);return r.moveTrait=new _a(r,s),r.traits.add(r.moveTrait),r.rules.crashable&&(r.crashableTrait=new Pa(r),r.traits.add(r.crashableTrait)),r.rules.proneWhenAttacked&&(r.suppressionTrait=new Ia,r.traits.add(r.suppressionTrait)),r.rules.agent&&(r.agentTrait=new Na,r.traits.add(r.agentTrait)),r.idleActionTrait=new xa,r.traits.add(r.idleActionTrait),r}get stance(){return this._stance===Rs.None&&this.suppressionTrait?.isSuppressed()?Rs.Prone:this._stance}set stance(e){this._stance=e,this.moveTrait.setDisabled([Rs.Deployed,Rs.Cheer].includes(e)),this.attackTrait?.setDisabled([Rs.Paradrop,Rs.Cheer].includes(e))}isUnit(){return!0}isInfantry(){return!0}}Da.SUB_CELLS=[2,4,3];class Ra extends Hs{constructor(e){super(),this.game=e}onTick(e){var t=Math.abs(this.game.rules.general.parachuteMaxFallRate),i=e.tile.onBridgeLandType?this.game.map.tileOccupation.getBridgeOnTile(e.tile).tileElevation:0,s=ks.tileHeightToWorld(i),r=e.tileElevation,a=ks.tileHeightToWorld(r);return s<Math.max(s,a-t)?(e.position.moveByLeptons3(new ss(0,-t,0)),e.moveTrait.handleElevationChange(r,this.game),!1):(e.position.tileElevation=i,e.stance=Rs.None,this.game.map.terrain.getPassableSpeed(e.tile,e.rules.speedType,e.onBridge)||(e.infDeathType=ei.None,this.game.destroyObject(e,void 0,!0)),!0)}}function La(i,s,r,a,n){let o=[];n=n||((e,t)=>{o.push({x:e,y:t})});var e=r-i,t=a-s,h=Math.abs(e),l=Math.abs(t);let c=0;var u=0<e?1:-1,d=0<t?1:-1;if(l<h)for(let e=i,t=s;u<0?e>=r:e<=r;e+=u)n(e,t),c+=l,c<<1>=h&&(t+=d,c-=h);else for(let e=i,t=s;d<0?t>=a:t<=a;t+=d)n(e,t),c+=h,c<<1>=l&&(e+=u,c-=l);return o}function Fa(e){return null!=e}class ja extends Hs{constructor(...e){super(),this.children.push(...e)}onTick(e){return!0}}class Ua{constructor(){this.enabled=!0}setEnabled(e){this.enabled=e}[Lr.onTick](e,t){var i;this.enabled&&(e.owner.isNeutral||e.name===t.rules.general.paradrop.paradropPlane)&&e.unitOrderTrait.isIdle()&&(i=this.chooseExitTile(e.tile,t),e.unitOrderTrait.addTask(new ja(new Sa(t,i,!1,{allowOutOfBoundsTarget:!0}),new ga(e=>t.unspawnObject(e))).setCancellable(!1)))}chooseExitTile(e,t){var i=t.map.tiles.getMapSize(),i=.5<t.generateRandom()?new Ss(Math.floor(i.width/2),0):new Ss(0,Math.floor(i.height/2)),e=new Ss(e.rx,e.ry),i=La(e.x,e.y,i.x,i.y).map(e=>t.map.tiles.getByMapCoords(e.x,e.y)).filter(Fa);if(!i.length)throw new Error("No valid exit tile found");return i[i.length-1]}}(r=ta=ta||{})[r.Spawning=0]="Spawning",r[r.EnRoute=1]="EnRoute",r[r.Dropping=2]="Dropping",r[r.TurningAround=3]="TurningAround";const Wa=5*Fs.BASE_TICKS_PER_SECOND;class za extends zs{constructor(e,t,i,s,r){super(e,t,i),this.paradropSquad=s,this.state=ta.Spawning,this.spawnDelay=r*Wa}onStart(e){this.passengerRules=e.rules.getObject(this.paradropSquad.inf,Bt.Infantry),this.passengerCount=this.paradropSquad.num}computeFlightPath(e,t,i){if(t.equals(e))throw new Error("Source and destination must be different");let s=e.clone().sub(t);e=i.rules.general.paradrop.paradropRadius/ks.LEPTONS_PER_TILE,e=t.clone().add(s.clone().setLength(s.length()+2*e)).floor();let r=La(t.x,t.y,e.x,e.y).map(e=>i.map.tiles.getByMapCoords(e.x,e.y)??i.map.tiles.getPlaceholderTile(e.x,e.y));for(;r.length;){var a=r[0],a=ks.tileToWorld(a.rx+.5,a.ry+.5);if(i.map.isWithinHardBounds(new Ss(a.x,a.y)))break;r.shift()}if(!r.length)throw new Error("No valid paradrop path found");return{fromTile:r[0],toTile:r[r.length-1]}}onTick(r){if(this.state===ta.Spawning){if(0<this.spawnDelay)return this.spawnDelay--,!1;var a=r.map.tiles.getMapSize(),n=[new Ss(0,0),new Ss(Math.floor(a.width/2),0),new Ss(0,Math.floor(a.height/2))][r.generateRandomInt(0,2)];let t=this.passengerRules.speedType,e=new js(r.map.tiles,r.map.mapBounds,this.tile,{width:1,height:1},0,50,e=>0<r.map.terrain.getPassableSpeed(e,t,!!e.onBridgeLandType));var o=this.targetTile=e.getNextTile();if(!o)return!0;let i=new Ss(o.rx,o.ry);var{fromTile:h,toTile:a}=this.computeFlightPath(i,n,r),o=r.rules.general.paradrop.paradropPlane,n=r.rules.getObject(o,Bt.Aircraft);let s=this.pdPlane=r.createUnitForPlayer(n,this.owner);r.spawnObject(s,h),s.direction=Tr.fromMapCoords(i.clone().sub(new Ss(h.rx,h.ry))),s.position.tileElevation=ks.worldToTileHeight(s.rules.flightLevel??r.rules.general.flightLevel),s.zone=bs.Air,s.onBridge=!1,s.unitOrderTrait.addTask(new Sa(r,a,!1,{allowOutOfBoundsTarget:!0})),s.traits.get(Ua).setEnabled(!1),this.state=ta.EnRoute}if(!this.pdPlane||this.pdPlane.isDestroyed||this.pdPlane.isCrashing)return!0;o=this.targetTile;if(!this.pdPlane.unitOrderTrait.hasTasks())return this.state=ta.TurningAround,this.pdPlane.unitOrderTrait.addTask(new Sa(r,o,!1,{allowOutOfBoundsTarget:!0})),!1;n=r.rules.general.paradrop.paradropRadius/ks.LEPTONS_PER_TILE;let e=new Cs(r.map.tileOccupation);h=e.isInTileRange(this.pdPlane.tile,o,0,n);if(this.state===ta.EnRoute&&h&&(this.state=ta.Dropping),this.state===ta.Dropping)if(h&&0<this.passengerCount){a=this.pdPlane.tile;let t=!!a.onBridgeLandType;if(!r.map.terrain.getPassableSpeed(a,this.passengerRules.speedType,t))return!1;let e=r.map.getGroundObjectsOnTile(a);if(e.some(e=>e.isVehicle()&&e.onBridge===t||e.isBuilding()&&!e.isDestroyed||e.isInfantry()&&e.stance===Rs.Paradrop))return!1;n=this.findFreeSubCell(r,a);if(!n)return!1;this.passengerCount--;let i=r.createUnitForPlayer(this.passengerRules,this.owner);i.stance=Rs.Paradrop,i.position.tileElevation=this.pdPlane.tileElevation,i.position.subCell=n,i.onBridge=t,i.rules.trainable&&this.owner.canProduceVeteran(i.rules)&&i.veteranTrait?.setVeteranLevel(Jr.Veteran),r.spawnObject(i,a),i.unitOrderTrait.addTask(new Ra(r).setCancellable(!1))}else{if(!(0<this.passengerCount))return this.pdPlane.unitOrderTrait.getCurrentTask().forceCancel(this.pdPlane),this.pdPlane.traits.get(Ua).setEnabled(!0),!0;this.state=ta.TurningAround,this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!!o.onBridgeLandType)}return this.state===ta.TurningAround&&h&&(o=this.computeFlightPath(new Ss(o.rx,o.ry),new Ss(this.pdPlane.tile.rx,this.pdPlane.tile.ry),r)["toTile"],this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!1),this.state=ta.EnRoute),!1}findFreeSubCell(t,e){let i=t.map.getGroundObjectsOnTile(e).filter(e=>e.isTerrain()).map(e=>e.rules.getOccupiedSubCells(t.map.getTheaterType())).flat();e=Da.SUB_CELLS.filter(e=>-1===i.indexOf(e));if(e.length)return 1<e.length?e[t.generateRandomInt(0,e.length-1)]:e[0]}}(r=ia=ia||{})[r.NotBridge=0]="NotBridge",r[r.Concrete=1]="Concrete",r[r.Wood=2]="Wood";class Va{static getOverlayBridgeType(e){return z(e,this.minHighBridgeConcreteId,this.maxHighBridgeConcreteId)||z(e,this.minLowBridgeConcreteId,this.maxLowBridgeConcreteId)?ia.Concrete:z(e,this.minHighBridgeWoodId,this.maxHighBridgeWoodId)||z(e,this.minLowBridgeWoodId,this.maxLowBridgeWoodId)?ia.Wood:ia.NotBridge}static isBridge(e){return this.isHighBridge(e)||this.isLowBridge(e)}static isBridgePlaceholder(e){return this.bridgePlaceholderIds.includes(e)}static isHighBridge(e){return z(e,this.minHighBridgeWoodId,this.maxHighBridgeWoodId)||z(e,this.minHighBridgeConcreteId,this.maxHighBridgeConcreteId)}static isLowBridge(e){return z(e,this.minLowBridgeWoodId,this.maxLowBridgeWoodId)||z(e,this.minLowBridgeConcreteId,this.maxLowBridgeConcreteId)}static isXBridge(e){return e===this.minHighBridgeWoodId||e===this.minHighBridgeConcreteId||z(e,this.minLowBridgeWoodId,this.minLowBridgeWoodId+8)||z(e,this.minLowBridgeWoodId+18,this.minLowBridgeWoodId+21)||z(e,this.minLowBridgeConcreteId,this.minLowBridgeConcreteId+8)||z(e,this.minLowBridgeConcreteId+18,this.minLowBridgeConcreteId+21)}static isLowBridgeHead(e){return z(e,this.minLowBridgeWoodId+18,this.minLowBridgeWoodId+25)||z(e,this.minLowBridgeConcreteId+18,this.minLowBridgeConcreteId+25)}static isLowBridgeHeadStart(e){return z(e,this.minLowBridgeWoodId+20,this.minLowBridgeWoodId+23)||z(e,this.minLowBridgeConcreteId+20,this.minLowBridgeConcreteId+23)}static calculateLowBridgeOverlayId(e,t){let i;if(e===ia.Concrete)i=this.minLowBridgeConcreteId;else{if(e!==ia.Wood)throw new Error("Not implemented");i=this.minLowBridgeWoodId}return i+(t?0:9)}static calculateHighBridgeOverlayId(e,t){let i;if(e===ia.Concrete)i=this.minHighBridgeConcreteId;else{if(e!==ia.Wood)throw new Error("Not implemented");i=this.minHighBridgeWoodId}return i+(t?0:1)}}Va.minLowBridgeWoodId=74,Va.maxLowBridgeWoodId=99,Va.minLowBridgeConcreteId=205,Va.maxLowBridgeConcreteId=230,Va.minHighBridgeConcreteId=24,Va.maxHighBridgeConcreteId=25,Va.minHighBridgeWoodId=237,Va.maxHighBridgeWoodId=238,Va.bridgePlaceholderIds=[100,101,231,232],(sa=sa||{}).onAttack=Symbol(),(r=ra=ra||{})[r.None=0]="None",r[r.Ground=1]="Ground",r[r.Wall=2]="Wall",r[r.Cliff=3]="Cliff",r[r.OnBridge=4]="OnBridge",r[r.UnderBridge=5]="UnderBridge",r[r.Shore=6]="Shore";class Ha{constructor(e,t,i,s){this.target=e,this.position=t,this.explodeAnim=i,this.isLightningStrike=s,this.type=is.WarheadDetonate}}(r=aa=aa||{})[r.Top=0]="Top",r[r.TopLeft=1]="TopLeft",r[r.TopRight=2]="TopRight",r[r.Left=3]="Left",r[r.Right=4]="Right",r[r.BottomLeft=5]="BottomLeft",r[r.Bottom=6]="Bottom",r[r.BottomRight=7]="BottomRight";class Ga{constructor(i,s,e,r){this.tileSets=s,this.generalRules=e;let a=this.rSize={width:0,height:0},n=this.dSize={width:0,height:0};for(let e=0,t=i.length;e<t;++e)a.width=Math.max(a.width,i[e].rx),a.height=Math.max(a.height,i[e].ry),n.width=Math.max(n.width,i[e].dx),n.height=Math.max(n.height,i[e].dy);a.width++,a.height++,n.width++,n.height++;let o=this.tilesByRxy=new Array(a.width*a.height);o.fill(void 0);let h=this.tilesByDxy=new Array(n.width*n.height);h.fill(void 0);let l=this.tiles=new Array(i.length),c=[],u=this.bridgeSetTiles=[],d=new Set(Object.values(Yt));this.minTileHeight=Number.POSITIVE_INFINITY;for(let e=this.maxTileHeight=0,t=i.length;e<t;++e){var p=i[e],g=s.getTileImage(p.tileNum,p.subTile,r),m=g.terrainType;if(!d.has(m))throw new Error(`Tile (${p.rx}, ${p.ry}) has unknown terrain type "${m}"`);var f={...p,terrainType:m,landType:Hi(m),onBridgeLandType:void 0,rampType:g.rampType,id:p.rx+"_"+p.ry,occluded:!1},y=f.rx,w=f.ry,T=f.dx,m=f.dy;l[e]=f,o[y+w*a.width]=f,h[T+m*n.width]=f,this.minTileHeight=Math.min(this.minTileHeight,f.z),this.maxTileHeight=Math.max(this.maxTileHeight,f.z),4!==g.height||f.terrainType!==Yt.Cliff&&!s.isCliffTile(f.tileNum)||c.push(f),s.isHighBridgeBoundaryTile(p.tileNum)&&u.push(f)}this.computeLandBehindCliffTiles(c),this.cutoffTileHeight=this.computeCutoffTileHeight()}computeLandBehindCliffTiles(t){if(!(this.generalRules.cliffBackImpassability<2)){let e=[[-2,-2],[-1,-1],[-1,1],[1,-1],[0,1],[1,0]];t.forEach(t=>{for(var[i,s]of e){let e=this.getByMapCoords(t.rx+i,t.ry+s);e&&e.z<t.z&&e.terrainType!==Yt.Cliff&&e.terrainType!==Yt.Rough&&0===e.rampType&&(e.landType=Kt.Rock)}})}}getTileRadarColor(e){let t=this.tileSets.getTileImage(e.tileNum,e.subTile,()=>0);return t.radarLeft.clone().multiplyScalar(.5)}getAll(){return[...this.tiles]}forEach(i){for(let e=0,t=this.tiles.length;e<t;++e)i(this.tiles[e],e)}reduce(t,e){let i=e;return this.forEach(e=>{i=t(i,e)}),i}getMinTileHeight(){return this.minTileHeight}getMaxTileHeight(){return this.maxTileHeight}getCutoffTileHeight(){return this.cutoffTileHeight}computeCutoffTileHeight(){var t=this.dSize.width-1;let i=this.dSize.height-1,s=0,r=!0;for(;r&&0<i;){for(let e=1;e<t-3;e++){var a=this.getByDisplayCoords(e,i);a&&(r=!1,a.z>s&&(s=a.z))}r&&i--}return s}getAllBridgeSetTiles(){return this.bridgeSetTiles}getAllNeighbourTiles(e){var t=e.rx,e=e.ry;return[this.getByMapCoords(t+1,e+1),this.getByMapCoords(t-1,e-1),this.getByMapCoords(t-1,e+1),this.getByMapCoords(t+1,e-1),this.getByMapCoords(t,e+1),this.getByMapCoords(t+1,e),this.getByMapCoords(t-1,e),this.getByMapCoords(t,e-1)].filter(Fa)}getNeighbourTile(e,t){var i=e.rx,s=e.ry;switch(t){case aa.Bottom:return this.getByMapCoords(i+1,s+1);case aa.Top:return this.getByMapCoords(i-1,s-1);case aa.Left:return this.getByMapCoords(i-1,s+1);case aa.Right:return this.getByMapCoords(i+1,s-1);case aa.BottomLeft:return this.getByMapCoords(i,s+1);case aa.BottomRight:return this.getByMapCoords(i+1,s);case aa.TopLeft:return this.getByMapCoords(i-1,s);case aa.TopRight:return this.getByMapCoords(i,s-1);default:throw new Error("Invalid direction")}}getByDisplayCoords(e,t){if(!(e>=this.dSize.width||t>=this.dSize.height))return this.tilesByDxy[e+t*this.dSize.width]}getByMapCoords(e,t){if(!(e>=this.rSize.width||t>=this.rSize.height))return this.tilesByRxy[e+t*this.rSize.width]}getMapSize(){return this.rSize}getDisplaySize(){return this.dSize}getInRectangle(e,t){let i,s,r,a;a=t?(i=e.rx,s=e.ry,r=t.width,t.height):(i=e.x,s=e.y,r=e.width,e.height);let n=[];for(let t=0;t<r;t++)for(let e=0;e<a;e++){var o=i+t,h=s+e,h=this.getByMapCoords(o,h);h&&n.push(h)}return n}getPlaceholderTile(e,t){var i=this.tiles[0],i=i.dx-i.rx+i.ry+1;return{rx:e,ry:t,dx:e-t+i-1,dy:e+t-i-1,z:0,id:`${e}_${t}`,landType:Kt.Rock,terrainType:Yt.Rock1,rampType:0,subTile:0,tileNum:0,occluded:!1,onBridgeLandType:void 0}}}(r=na=na||{})[r.NotSpecial=0]="NotSpecial",r[r.Riparius=1]="Riparius",r[r.Cruentus=2]="Cruentus",r[r.Vinifera=4]="Vinifera",r[r.Aboreus=8]="Aboreus",r[r.Ore=1]="Ore",r[r.Gems=2]="Gems",r[r.All=15]="All";class $a{static getOverlayTibType(e){return this.isRiparius(e)?na.Riparius:this.isCruentus(e)?na.Cruentus:this.isVinifera(e)?na.Vinifera:this.isAboreus(e)?na.Aboreus:na.NotSpecial}static isRiparius(e){return e>=this.minIdRiparius&&e<=this.maxIdRiparius}static isCruentus(e){return e>=this.minIdCruentus&&e<=this.maxIdCruentus}static isVinifera(e){return e>=this.minIdVinifera&&e<=this.maxIdVinifera}static isAboreus(e){return e>=this.minIdAboreus&&e<=this.maxIdAboreus}}$a.minIdRiparius=102,$a.maxIdRiparius=127,$a.minIdCruentus=27,$a.maxIdCruentus=38,$a.minIdVinifera=127,$a.maxIdVinifera=146,$a.minIdAboreus=147,$a.maxIdAboreus=166,(r=oa=oa||{})[r.Riparius=0]="Riparius",r[r.Cruentus=1]="Cruentus",r[r.Vinifera=2]="Vinifera",r[r.Aboreus=3]="Aboreus",r[r.Ore=0]="Ore",r[r.Gems=1]="Gems";class qa{constructor(e){this.gameObject=e}static canBePlacedOn(e,t){return[Kt.Clear,Kt.Road,Kt.Rough].includes(e.landType)&&!t.getGroundObjectsOnTile(e).find(e=>!e.isSmudge()&&!e.isUnit())}getTiberiumType(){var e=$a.getOverlayTibType(this.gameObject.overlayId);switch(e){case na.Ore:return oa.Ore;case na.Gems:return oa.Gems;case na.Vinifera:return oa.Ore;default:throw new Error(`Unsupported tiberium type ${e}`)}}collectBail(){var e=this.getBailCount();if(e<=0)throw new Error("Attempted to collect an ore bail, but there are none left");return this.gameObject.value--,1<e?this.getTiberiumType():void 0}spawnBails(e){this.gameObject.value=Math.min(qa.maxBails,this.gameObject.value+e)}removeBails(e){this.gameObject.value=Math.max(-1,this.gameObject.value-e)}getBailCount(){return this.gameObject.value+1}dispose(){this.gameObject=void 0}}qa.maxBails=11;class Xa{destroyOre(i,s,r){if(s.landType===Kt.Tiberium&&(r.art.hasObject(i,Bt.Animation)?r.art.getAnimation(i):void 0)?.crater){let t=r.map.getObjectsOnTile(s).find(e=>e.isOverlay()&&e.isTiberium());if(t){s=Math.ceil(qa.maxBails/2),s=i.startsWith("S_CLSN")?s:r.generateRandomInt(1,s);let e=t.traits.get(qa);e.removeBails(s),e.getBailCount()||r.unspawnObject(t)}}}spawnSmudges(e,r,a){if(r.landType===Kt.Clear&&0===r.rampType&&a.map.mapBounds.isWithinBounds(r)&&!a.map.getObjectsOnTile(r).find(e=>!e.isUnit())){e=a.art.hasObject(e,Bt.Animation)?a.art.getAnimation(e):void 0;if(e?.crater){let t=e?.forceBigCraters?2:1,i=e?.scorch,s=[aa.Bottom,aa.BottomLeft,aa.BottomRight].every(e=>a.map.tiles.getNeighbourTile(r,e));e=[...a.rules.smudgeRules.values()].filter(e=>(e.crater&&e.width===t&&e.height===t||i&&e.burn)&&!((1<e.width||1<e.height)&&!s));e.length&&(e=e[a.generateRandomInt(0,e.length-1)].name,e=a.createObject(Bt.Smudge,e),a.spawnObject(e,r))}}}}class Za{constructor(e,t,i){this.target=e,this.attacker=t,this.incidental=i,this.type=is.ObjectAttacked}}class Qa{constructor(e){this.rules=e}canDamage(e,t,i){return!(!e.isSpawned||e.isDisposed||e.isDestroyed||e.isCrashing)&&(!(e.isTechno()&&e.warpedOutTrait.isInvulnerable()&&!this.rules.temporal)&&((!e.isUnit()||!e.moveTrait.reservedPathNodes.find(e=>e.tile===t))&&(!!e.healthTrait&&((!e.isUnit()||e.zone!==bs.Air||i===bs.Air)&&(!(!e.isUnit()&&i===bs.Air)&&((!e.isBuilding()||!e.rules.invisibleInGame)&&(!((e.isTechno()||e.isTerrain())&&e.rules.immune&&!this.rules.temporal)&&(!(e.isTechno()&&!e.rules.warpable&&this.rules.temporal)&&(!(this.rules.radiation&&(!e.isUnit()||e.rules.immuneToRadiation))&&(!(this.rules.psychicDamage&&(!e.isUnit()||e.rules.immuneToPsionics))&&(!e.isOverlay()||!Va.isLowBridgeHead(e.overlayId))))))))))))}computeDamage(t,i,s=!1){let r=t;if(0<t&&i.isTechno()&&i.invulnerableTrait.isActive())return 0;if(i.isAircraft()&&i.missileSpawnTrait&&i.zone!==bs.Air)return 0;if(this.rules.radiation||this.rules.temporal||!i.isInfantry()||i.stance!==Rs.Prone||(r*=this.rules.proneDamage),i.isTechno()||i.isOverlay()||i.isTerrain()){let e=i.isTerrain()?ri.Wood:i.rules.armor;i.isOverlay()&&i.isBridge()&&((t=Va.getOverlayBridgeType(i.overlayId))===ia.Wood?e=ri.Wood:t===ia.Concrete&&(e=ri.Concrete)),s&&i.isOverlay()&&(i.isBridge()||i.rules.wall)||(r*=this.rules.verses.get(e)),0<r&&i.isTechno()&&i.veteranTrait&&(r/=i.veteranTrait.getVeteranArmorMultiplier()),0<r&&i.isUnit()&&(r/=i.crateBonuses.armor)}return(i.isOverlay()||i.isBuilding())&&i.rules.wall&&(this.rules.wallAbsoluteDestroyer?r=Number.POSITIVE_INFINITY:this.rules.wall||this.rules.wood&&i.rules.armor===ri.Wood||(r=0)),i.isOverlay()&&i.isBridge()&&(this.rules.wall||(r=0)),r=0<r?Math.floor(r):Math.ceil(r),r}inflictDamage(e,t,i,s,r=!1){let a=t.healthTrait;return e===Number.POSITIVE_INFINITY&&(e=a.getHitPoints()),a.inflictDamage(e,i,s),s.traits.filter(sa).forEach(e=>{e[sa.onAttack](t,i?.obj,s)}),t.onAttack(s,i),s.events.dispatch(new Za(t,i,r)),t.isTechno()&&!this.rules.temporal&&this.supressOrScatterTarget(t,s),!a.health&&(t.isInfantry()&&(t.infDeathType=this.rules.infDeath),this.rules.temporal&&(t.deathType=zr.Temporal),t.isUnit()&&t.crashableTrait&&t.zone===bs.Air&&!this.rules.temporal?t.crashableTrait.crash(i):s.destroyObject(t,i,void 0,r),!0)}supressOrScatterTarget(e,t){e.rules.fraidycat||e.isVehicle()&&!e.owner.isCombatant()&&e.rules.insignificant?e.unitOrderTrait.hasTasks()||(e.isInfantry()&&(e.isPanicked=!0),e.unitOrderTrait.addTask(new va(t)),e.isInfantry()&&e.unitOrderTrait.addTask(new ga(()=>e.isPanicked=!1).setCancellable(!1))):e.isInfantry()&&e.suppressionTrait?.supress()}createDummyWeaponInfo(){return{minRange:0,range:0,speed:Number.POSITIVE_INFINITY,type:oi.Primary,rules:new Ci(new h("Dummy")),projectileRules:new qi(Bt.Projectile,new h("Dummy")),warhead:this}}detonate(i,e,t,s,r,a,n,o,h,l,c,u,d,p=!1){var g,m,f,y=h?.weapon??this.createDummyWeaponInfo(),w=h?.obj,T=h?.player,b=d?d/ks.LEPTONS_PER_TILE:this.rules.cellSpread,v=this.rules.percentAtMax;let S=new Set,k=new Map,O=new Cs(i.map.tileOccupation),_=new js(i.map.tiles,i.map.mapBounds,t,{width:1,height:1},0,Math.ceil(b),()=>!0);for(;g=_.getNextTile();)for(m of i.map.getObjectsOnTile(g))if((!S.has(m)||m.isBuilding())&&(n!==ra.UnderBridge||!m.isUnit()||!m.onBridge)&&!(w&&m.isTechno()&&m.rules.typeImmune&&m.owner===T&&m.name===w.name)&&this.canDamage(m,g,a)&&(!m.isOverlay()||!(!n&&.1<Math.abs(m.tileElevation-s)||n===ra.OnBridge&&!m.isBridge()))){let e=m.isBuilding()?g===t?0:O.distance3(g,r)/ks.LEPTONS_PER_TILE:m.isTerrain()||m.isOverlay()?O.distance3(g,t)/ks.LEPTONS_PER_TILE:O.distance3(m,r)/ks.LEPTONS_PER_TILE;if(e<.001&&(e=0),!(l&&m.isInfantry()&&T)||m.owner!==T&&!i.alliances.areAllied(m.owner,T)){if(!b)if(m.isTerrain()){if(g!==t||!this.rules.wall)continue}else if(!l&&(g!==t||!m.isBuilding()&&m!==(o.obj||o.getBridge())))continue;b&&e>b||(S.add(m),k.set(m,m.isBuilding()?(k.get(m)||[]).concat(e):[e]))}}let I=!1,C;for(f of S)if(!f.isDestroyed&&!f.isCrashing){var A,B,x=this.computeDamage(e,f,c);if(x)for(var E of k.get(f)){let t=x;if(0<b&&Number.isFinite(t)&&(t=V(t,v*t,E/b)),Math.abs(t)<1&&(!b||.25<=t/x)&&(t=+Math.sign(t)),t=0<t?Math.floor(t):Math.ceil(t),t){let e=f.healthTrait;if(t<0){if(!w)throw new Error("Expected healer object to be set");if(e.healBy(-t,w,i),100===e.health)break}else{if(f===o.obj&&E<1&&(C=f),this.rules.causesDelayKill&&f.isBuilding()&&f.delayedKillTrait&&(A=f.healthTrait.getHitPoints(),t>=A&&(t=A-1,f.delayedKillTrait.isActive()||(A=this.rules.delayKillAtMax,B=V(B=this.rules.delayKillFrames,A*B,E/b),f.delayedKillTrait.activate(B,h)))),this.inflictDamage(t,f,h,i,!C))break;f.isVehicle()&&this.rules.rocker&&(0<(E=W(x/300,0,1))&&(B=Tr.fromMapCoords(f.position.getMapPosition().clone().sub(ks.vecWorldToGround(r)))-f.direction,f.applyRocking(B,E)))}}}else f.isTechno()&&f.invulnerableTrait.isActive()&&(I=!0)}y=y.rules.radLevel;y&&b&&i.mapRadiationTrait.createRadSite(t,y,b+1);p=p?void 0:I?i.rules.audioVisual.weaponNullifyAnim:this.pickExplodeAnim(e,C,a,i,c);if(!I&&a===bs.Ground){let e=new Xa;p&&e.destroyOre(p,t,i),u&&e.spawnSmudges(u,t,i),p&&e.spawnSmudges(p,t,i)}i.events.dispatch(new Ha(this,r,p,c))}pickExplodeAnim(t,i,s,r,a){if(t){if(a)return r.rules.audioVisual.weatherConBoltExplosion;if(this.rules.conventional&&s===bs.Water&&(!i||i.isBuilding()||i.isVehicle()&&i.submergibleTrait)){var n=r.rules.combatDamage.splashList;return n[W(Math.floor(t/50),0,n.length-1)]}n=this.rules.animList.length;let e;return n?(e=r.rules.combatDamage.c4Warhead===this.rules.name?n-1:this.rules.emEffect?r.generateRandomInt(0,n-1):W(Math.floor(t/25),0,n-1),this.rules.animList[e]):void 0}}}Qa.SPECIAL_WARHEAD_NAME="Special",Qa.HE_WARHEAD_NAME="HE";class Ya{constructor(e){this.forward=0,this.lateral=0,this.vertical=0,e&&3===e.length&&this.fromArray(e)}fromArray(e){return this.forward=e[0],this.lateral=e[1],this.vertical=e[2],this}clone(){return new Ya([this.forward,this.lateral,this.vertical])}}class Ka{constructor(e,t){this.weapon=e,this.gameObject=t,this.type=is.WeaponFire}}class Ja{constructor(e,t,i,s,r,a){this.weaponType=e,this.projectileRules=t,this.weaponRules=i,this.warheadRules=s,this.gameObject=r,this.generalRules=a,this.targetChecks=[],this.initConditions()}initConditions(){this.projectileRules.isAntiGround||this.targetChecks.push(e=>!!e);const a=this.generalRules.prism.type;this.gameObject.name===a&&this.weaponType===oi.Secondary?this.targetChecks.push((e,t,i,s,r)=>!(!r||!e?.isBuilding()||e.name!==a||e.owner!==this.gameObject.owner)):this.warheadRules.electricAssault?this.targetChecks.push((e,t,i,s,r)=>!(!s&&!r||!e?.isBuilding()||!e.overpoweredTrait||e.owner!==this.gameObject.owner)):this.weaponRules.damage<0?this.targetChecks.push((e,t,i)=>!!(e!==this.gameObject&&e?.isUnit()&&i.areFriendly(e,this.gameObject)&&e.healthTrait.health<100&&this.gameObject.isAircraft()===e.isAircraft())):(this.gameObject.rules.attackCursorOnFriendlies||this.warheadRules.bombDisarm?this.targetChecks.push((e,t,i,s,r)=>!r&&!!(!this.warheadRules.bombDisarm||e?.isTechno()&&e.tntChargeTrait?.hasCharge())):this.targetChecks.push((e,t,i,s)=>!((!s||this.warheadRules.mindControl)&&e?.isTechno()&&i.areFriendly(e,this.gameObject))),this.targetChecks.push((e,t,i)=>!(e?.isTechno()&&e.cloakableTrait?.isCloaked()&&!i.alliances.haveSharedIntel(this.gameObject.owner,e.owner))),this.weaponRules.limboLaunch&&this.targetChecks.push((e,t,i,s,r)=>!(r&&e&&(e.isVehicle()||e.isAircraft())&&e.parasiteableTrait?.isInfested())),this.gameObject.rules.ivan&&this.targetChecks.push(e=>!(!e?.isTechno()||!e.tntChargeTrait||e.tntChargeTrait.hasCharge())),this.warheadRules.parasite&&this.targetChecks.push((e,t,i,s)=>!!(!e&&s||e?.isInfantry()||(e?.isVehicle()||e?.isAircraft())&&e.parasiteableTrait)),this.warheadRules.mindControl&&this.targetChecks.push(e=>!(!e?.isTechno()||!e.mindControllableTrait)),this.warheadRules.temporal||this.targetChecks.push((e,t,i,s,r)=>!(r&&e?.isTechno()&&e.warpedOutTrait.isInvulnerable()))),this.targetChecks.push((e,t)=>this.canTargetZone(e,t))}canTarget(t,i,s,r,a){return this.targetChecks.every(e=>e(t,i,s,r,a))}canTargetZone(e,t){let i;if(e?.isUnit()){if(e?.isInfantry()&&e.stance===Rs.Paradrop)return this.projectileRules.isAntiAir&&(this.projectileRules.isAntiGround||this.weaponType===oi.Secondary);if(e.zone===bs.Air)return this.projectileRules.isAntiAir;if(this.weaponType===oi.Secondary&&this.projectileRules.isAntiAir)return!1;i=e.zone}else i=t.landType===Kt.Water?bs.Water:bs.Ground;return i===bs.Water?this.canTargetNaval(this.gameObject.rules.navalTargeting,this.gameObject,e,this.weaponType):this.canTargetLand(this.gameObject.rules.landTargeting,this.weaponType)}canTargetLand(e,t){switch(e){case ai.LandOk:return!0;case ai.LandNotOk:return!1;case ai.LandSecondary:return t===oi.Secondary;default:throw new Error(`Unhandled LandTargeting value "${e}"`)}}canTargetNaval(e,t,i,s){switch(e){case ni.UnderwaterNever:return!i||!(i.isVehicle()&&i.submergibleTrait?.isSubmerged());case ni.UnderwaterSecondary:return i&&i.isVehicle()&&i.submergibleTrait&&!t.rules.spawned?s===oi.Secondary:s===oi.Primary;case ni.UnderwaterOnly:return!!(i&&i.isVehicle()&&i.submergibleTrait);case ni.OrganicSecondary:return i?.isTechno()&&i.rules.organic?s===oi.Secondary:s===oi.Primary;case ni.SealSpecial:return i?.isTechno()&&i.rules.naval&&!i.rules.organic&&(i.isBuilding()||i.rules.speedType===Jt.Float)?s===oi.Secondary:s===oi.Primary;case ni.NavalAll:return!0;case ni.NavalNone:return!1;default:throw new Error(`Unhandled NavalTargeting value "${e}"`)}}}class en{constructor(e,t,i,s,r,a,n){this.type=e,this.gameObject=t,this.rules=i,this.warhead=s,this.projectileRules=r,this.flh=a,this.targeting=n,this.cooldownTicks=0,this.burstsLeft=0,this.burstIndex=0,this.useBurstDelay=!1,this.lateralMuzzleMult=1,this.distributedFireAngle=t.rules.distributedFire&&t.rules.radialFireSegments?-90:0}static factory(e,t,i,s,r){var a=s.getWeapon(e);let n=a.warhead;n===Qa.SPECIAL_WARHEAD_NAME&&(n=en.findSpecialWarheadName(a,i,s));var o=new Qa(s.getWarhead(n)),e=s.getProjectile(a.projectile),s=new Ja(t,e,a,o.rules,i,s.general);return new this(t,i,a,o,e,r||new Ya,s)}static findSpecialWarheadName(e,t,i){let s;if(!e.spawner)throw new Error(`Weapon "${e.name} can't use "Special" warhead without Spawner=yes`);if(t.rules.spawns===i.general.v3Rocket.type)s=i.combatDamage.v3Warhead;else if(t.rules.spawns===i.general.dMisl.type)s=i.combatDamage.dMislWarhead;else{if(!t.rules.spawns)throw new Error(`Can't use "Special" warhead on unit type "${t.name}" without "Spawns"`);t=i.getObject(t.rules.spawns,Bt.Aircraft);if(!t.primary)throw new Error(`Spawned unit "${t.name}" doesn't have a primary weapon`);s=i.getWeapon(t.primary).warhead}return s}static computeSpeed(e,t){return t.arcing?.75*Ii.iniSpeedToLeptonsPerTick(50,100):!t.rot||t.inviso||e.isLaser||e.isElectricBolt?Number.POSITIVE_INFINITY:e.speed}get name(){return this.rules.name}get minRange(){return this.rules.minimumRange}get range(){return this.gameObject.isBuilding()&&!this.gameObject.overpoweredTrait&&this.type===oi.Secondary&&this.gameObject.primaryWeapon?Math.min(this.gameObject.primaryWeapon.rules.range,this.rules.range):this.rules.range}get speed(){return en.computeSpeed(this.rules,this.projectileRules)}get rof(){let e=this.rules.rof;return this.gameObject.isBuilding()&&this.gameObject.garrisonTrait?.isOccupied()&&(e/=this.gameObject.garrisonTrait.units.length),this.gameObject.veteranTrait&&(e*=this.gameObject.veteranTrait.getVeteranRofMultiplier()),Math.floor(e)}getCooldownTicks(){return this.cooldownTicks}expireCooldown(){this.cooldownTicks=0}resetCooldown(){this.cooldownTicks=this.rof}hasBurstsLeft(){return 0<this.burstsLeft}resetBursts(){this.burstsLeft=0,this.burstIndex=0,this.resetCooldown(),this.gameObject.ammoTrait&&0<this.gameObject.ammoTrait.ammo&&this.gameObject.ammoTrait.ammo--}tick(){0<this.cooldownTicks&&this.cooldownTicks--}getBurstsFired(){return this.burstIndex}fire(r,a,n=1){let o=this.gameObject,e,t=0;if(!o.airSpawnTrait||!this.rules.spawner||(e=o.airSpawnTrait.prepareLaunch(o,r,a),t=o.airSpawnTrait.availableSpawns,e)){this.burstsLeft?(this.burstsLeft--,this.burstIndex++,this.lateralMuzzleMult*=-1):(this.useBurstDelay=!1,this.burstIndex=0,e?this.burstsLeft=t:this.gameObject.isAircraft()?this.burstsLeft=this.projectileRules.iniRot<=1?4:this.gameObject.rules.fighter?0:1:(this.burstsLeft=this.rules.burst-1,this.useBurstDelay=!0),this.lateralMuzzleMult=1),0<this.burstsLeft&&(e&&0<t?this.cooldownTicks=this.rules.iniSpeed:this.gameObject.isAircraft()?this.cooldownTicks=this.rules.rof:this.cooldownTicks=this.useBurstDelay&&void 0!==this.gameObject.rules.burstDelay[this.burstIndex]?this.gameObject.rules.burstDelay[this.burstIndex]:a.generateRandomInt(3,5)),this.burstsLeft||this.resetBursts(),this.rules.limboLaunch&&(a.limboObject(this.gameObject,{selected:a.getUnitSelection().isSelected(this.gameObject),controlGroup:a.getUnitSelection().getOrCreateSelectionModel(this.gameObject).getControlGroupNumber()}),this.warhead.rules.parasite&&(r.obj?.isVehicle()||r.obj?.isAircraft())&&r.obj.parasiteableTrait&&(r.obj.parasiteableTrait.beingBoarded=!0));let i=e??a.createProjectile(this.projectileRules.name,this.gameObject,this,r,!1);i.isAircraft()||(i.baseDamageMultiplier=n*(this.gameObject.isUnit()?this.gameObject.crateBonuses.firepower:1));let s=this.flh.clone();s.lateral*=this.lateralMuzzleMult;var h=o.position.getMapPosition();if(a.map.isWithinHardBounds(h)){i.position.moveToLeptons(h),i.position.tileElevation=o.position.tileElevation;let e=new Ss(s.lateral,s.forward);n=this.getMuzzleFacing()+this.distributedFireAngle;e=rr(e,n);var h=rr(h=new Ss(0,o.art.turretOffset),o.direction);e.add(h),o.rules.radialFireSegments&&o.rules.distributedFire&&(h=Math.floor(180/o.rules.radialFireSegments),this.distributedFireAngle=(this.distributedFireAngle+h+90)%180-90),i.direction=n,o.isBuilding()&&o.rules.turretAnim&&(l=ks.screenDistanceToWorld(o.rules.turretAnimX,o.rules.turretAnimY),n=o.getFoundationCenterOffset(),i.position.moveByLeptons(-n.x+l.x,-n.y+l.y));let t=new ss(e.x,s.vertical,-e.y);var l=t.clone().add(i.position.worldPosition);if(a.map.isWithinHardBounds(l)&&i.position.moveByLeptons3(t),i.tileElevation<0&&(i.position.tileElevation=0),i.isAircraft()?a.unlimboObject(i,i.position.tile):a.spawnObject(i,i.position.tile),this.rules.revealOnFire&&r.obj?.isTechno()){let e=a.mapShroudTrait.getPlayerShroud(r.obj.owner);e?.isShrouded(o.tile,o.tileElevation)&&e.revealTemporarily(o)}this.rules.decloakToFire&&this.gameObject.cloakableTrait?.uncloak(a),a.events.dispatch(new Ka(this,this.gameObject))}else e&&(e.owner.removeOwnedObject(e),e.dispose())}}getMuzzleFacing(){let e=this.gameObject,t;return t=!e.isInfantry()&&!e.isAircraft()&&(e.isBuilding()||e.isVehicle())&&e.turretTrait?e.turretTrait.facing:e.direction,t}}en.NUKE_PAYLOAD_NAME="NukePayload";class tn extends zs{constructor(e,t,i,s){super(e,t,i),this.weaponType=s}onStart(t){var i=t.rules.getWeapon(this.weaponType),s=t.createTarget(void 0,this.tile),r=this.owner.getOwnedObjectsByType(Bt.Building).find(e=>e.rules.nukeSilo);if(r){let e=en.factory(i.name,oi.Primary,r,t.rules);e.fire(s,t)}else this.fireLooseNuke(i,s,t)}fireLooseNuke(t,i,s){var r=new Ss(this.tile.rx+.5,this.tile.ry+.5).multiplyScalar(ks.LEPTONS_PER_TILE);if(s.map.isWithinHardBounds(r)){let e=s.createLooseProjectile(t.name,this.owner,i);e.position.moveToLeptons(r),e.position.tileElevation=ks.worldToTileHeight(e.rules.detonationAltitude),s.spawnObject(e,e.position.tile)}}onTick(e){return!0}}class sn{constructor(e){this.position=e,this.type=is.LightningStormCloud}}class rn{constructor(e){this.target=e,this.type=is.LightningStormManifest}}(r=ha=ha||{})[r.Approaching=0]="Approaching",r[r.Manifesting=1]="Manifesting";class an extends zs{constructor(){super(...arguments),this.state=ha.Approaching,this.clouds=[]}onStart(e){e=e.rules.general.lightningStorm;this.manifestStartTimer=e.deferment,this.manifestEndTimer=e.duration,this.nextDirectHitTimer=0,this.nextRandomHitTimer=0}onTick(t){if(this.state===ha.Approaching&&(0<this.manifestStartTimer?this.manifestStartTimer--:(this.state=ha.Manifesting,t.events.dispatch(new rn(this.tile)))),this.state===ha.Manifesting){var i,r=t.rules.general.lightningStorm;if(0<this.manifestEndTimer&&(this.manifestEndTimer--,0<this.nextDirectHitTimer&&this.nextDirectHitTimer--,this.nextDirectHitTimer<=0&&(this.nextDirectHitTimer=r.hitDelay,this.spawnCloudAt(this.tile,t)),0<this.nextRandomHitTimer&&this.nextRandomHitTimer--,this.nextRandomHitTimer<=0)){this.nextRandomHitTimer=r.scatterDelay;var a=Math.floor(r.cellSpread/2);let i=r.separation,s=new Cs(t.map.tileOccupation),e=new wa(t.map.tiles,t.map.mapBounds,this.tile,a,t,t=>!this.clouds.some(e=>s.tileDistance(t,e.tile)<i),!1);a=e.getNextTile();a&&this.spawnCloudAt(a,t)}for(i of this.clouds.slice())if(0<i.ticksLeft){if(i.ticksLeft--,i.ticksLeft===Math.floor(i.durationTicks/2)){var s=r.warhead;let e=new Qa(t.rules.getWarhead(s));var n=i.tile,o=t.map.tileOccupation.getBridgeOnTile(n),h=o?.tileElevation??0,s=t.map.getTileZone(n);e.detonate(t,r.damage,n,h,ks.tile3dToWorld(n.rx+.5,n.ry+.5,n.z+h),s,o?ra.OnBridge:ra.None,t.createTarget(o,n),{player:this.owner,weapon:void 0},!1,!0,void 0)}}else this.clouds.splice(this.clouds.indexOf(i),1);if(!this.clouds.length&&this.manifestEndTimer<=0)return!0}return!1}spawnCloudAt(e,t){var i=t.rules.audioVisual.weatherConClouds,i=t.generateRandomInt(0,i.length-1);let s=t.art.getAnimation(t.rules.audioVisual.weatherConClouds[i]);i=s.art.getNumber("Rate",60*Fs.BASE_TICKS_PER_SECOND)/60,i=Math.floor(Fs.BASE_TICKS_PER_SECOND/i*60);this.clouds.push({tile:e,durationTicks:i,ticksLeft:i});i=(t.map.tileOccupation.getBridgeOnTile(e)?.tileElevation??0)+ks.worldToTileHeight(t.rules.general.flightLevel),i=ks.tile3dToWorld(e.rx+.5,e.ry+.5,e.z+i);t.events.dispatch(new sn(i))}}class nn extends zs{onStart(e){var t,i,s=e.rules.combatDamage.ironCurtainDuration,r={player:this.owner};let a=new js(e.map.tiles,e.map.mapBounds,this.tile,{width:1,height:1},0,1,()=>!0);for(;t=a.getNextTile();)for(i of e.map.getGroundObjectsOnTile(t))!i.isTechno()||i.isUnit()&&i.tile!==t||i.rules.missileSpawn||(i.rules.organic?i.isDestroyed||e.destroyObject(i,r):(i.invulnerableTrait.setActiveFor(s,e.currentTick),(i.isVehicle()||i.isAircraft())&&i.parasiteableTrait?.isInfested()&&i.parasiteableTrait.destroyParasite(r,e)))}onTick(e){return!0}}class on extends zs{constructor(e,t,i,s){super(e,t,i),this.tile2=s,this.objectsToTeleport=[]}onStart(i){this.delayTicks=i.rules.general.chronoDelay;let s=i.map.tiles;for(let t=-1;t<=1;t++)for(let e=-1;e<=1;e++){var r=s.getByMapCoords(this.tile.rx+t,this.tile.ry+e);if(r){var a,n=!!r.onBridgeLandType,o=s.getByMapCoords(this.tile2.rx+t,this.tile2.ry+e);for(a of i.map.getGroundObjectsOnTile(r))!a.isUnit()||a.tile!==r||a.onBridge!==n||a.isInfantry()&&a.stance===Rs.Paradrop||a.isDisposed||a.invulnerableTrait.isActive()||(a.rules.organic&&!a.rules.teleporter||!o?i.destroyObject(a,{player:this.owner}):a.warpedOutTrait.isActive()||(a.warpedOutTrait.setActive(!0,!0,i),this.objectsToTeleport.push({obj:a,destTile:o})))}}}onTick(l){if(0<this.delayTicks&&this.delayTicks--,this.delayTicks)return!1;for(let{obj:o,destTile:h}of this.objectsToTeleport)if(o.isSpawned){let i=!1,s=h?l.map.tileOccupation.getBridgeOnTile(h):void 0,r=l.map.getGroundObjectsOnTile(h),a=r.find(e=>e.isBuilding());var c=r.some(e=>l.rules.general.padAircraft.includes(e.name)),t=l.rules.general.padAircraft.includes(o.name)&&!!a?.helipadTrait&&!!a.dockTrait?.getAllDockTiles().includes(h)&&!a.dockTrait.hasReservedDockAt(a.dockTrait.getDockNumberByTile(h))&&a.owner===o.owner;let e=!1,n=o.rules.speedType;o.rules.movementZone===si.Fly&&(n=Jt.Wheel);var u=l.map.mapBounds.isWithinBounds(h);if(!(t||l.map.terrain.getPassableSpeed(h,n,!!s)&&u)){let t=!1;if(!c&&(0<l.map.terrain.getPassableSpeed(h,n,!!s,void 0,!0)||!u)){a&&(i=!0);let e=new js(l.map.tiles,l.map.mapBounds,h,{width:1,height:1},1,15,e=>0<l.map.terrain.getPassableSpeed(e,n,!!e.onBridgeLandType)&&!l.map.terrain.findObstacles({tile:e,onBridge:!!e.onBridgeLandType},o).length);u=e.getNextTile();u&&(h=u,s=l.map.tileOccupation.getBridgeOnTile(h),r=l.map.getGroundObjectsOnTile(h),t=!0)}t||(o.moveTrait.teleportUnitToTile(h,s,!0,!1,l),o.warpedOutTrait.setActive(!1,!0,l),l.map.getTileZone(h)===bs.Water&&(o.deathType=zr.Sink),l.destroyObject(o,{player:this.owner}),e=!0)}if(!e||c)for(let t of r)t.isDisposed||t.isUnit()&&(this.objectsToTeleport.some(({obj:e})=>e===t)||t.onBridge!==!!s&&t.tile===h||2<Math.abs(t.tileElevation-o.tileElevation)||(t.isInfantry()&&t.stance!==Rs.Paradrop&&(t.deathType=zr.Crush),l.destroyObject(t,{player:this.owner,obj:o})));if(!e){if(o.moveTrait.teleportUnitToTile(h,s,!0,!1,l),t&&a?.dockTrait){t=a.dockTrait.getAllDockTiles().indexOf(h);if(a.dockTrait.undockUnitAt(t),a.dockTrait.hasReservedDockAt(t))throw new Error("Target building dock is already reserved by another unit");a.dockTrait.dockUnitAt(o,t)}i?o.warpedOutTrait.setTimed(l.rules.general.chronoDelay,!1,l):o.warpedOutTrait.setActive(!1,!0,l)}}return!0}}(la=la||{}).onDeactivate=Symbol();class hn{constructor(){this.effects=[]}[xs.onTick](i){for(var e of i.getCombatants()){var t;for(t of e.superWeaponsTrait.getAll())t.update(i)}for(let t of this.effects)t.status===Ns.NotStarted&&(t.onStart(i),t.status=Ns.Running),t.onTick(i)&&(t.status=Ns.Finished,i.traits.filter(la).forEach(e=>{e[la.onDeactivate](t.type,t.owner,i)}));this.effects=this.effects.filter(e=>e.status!==Ns.Finished)}[Ms.onPowerLow](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!1)})}[Ms.onPowerRestore](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!0)})}[Ms.onPowerChange](e,t){}[Es.onChange](e,t){var i;e.owner.powerTrait&&e.isBuilding()&&e.superWeaponTrait&&((i=e.superWeaponTrait.getSuperWeapon(e))&&this.updateTimer(i,!e.owner.powerTrait.isLowPower()))}updateTimer(e,t){var i=this.superWeaponHasValidBuilding(e);t&&i?e.resumeTimer():e.pauseTimer()}superWeaponHasValidBuilding(t){return[...t.owner.buildings].find(e=>!(e.superWeaponTrait?.getSuperWeapon(e)!==t||e.warpedOutTrait.isActive()&&t.rules.isPowered))}addEffect(e){this.effects.push(e)}activateSuperWeapon(t,e,i,s,r){let a=e.superWeaponsTrait?.getAll().find(e=>e.rules.type===t);if(a&&a.status===Ps.Ready){if(a.oneTimeOnly){e.superWeaponsTrait.remove(a.name);for(var n of e.buildings)n.rules.superWeapon===a.name&&n.superWeaponTrait&&n.superWeaponTrait.addSuperWeaponToPlayerIfNeeded(e,i)}else a.resetTimer();this.activateEffect(a.rules,e,i,s,r)}}activateEffect(e,i,s,r,a,n=!1){const o=e.type;if(void 0!==o){let t=[];switch(o){case ts.AmerParaDrop:for(var[h,l]of s.rules.general.paradrop.amerParaDrop.entries())s.rules.hasObject(l.inf,Bt.Infantry)?t.push(new za(o,i,r,l,h)):console.warn(`Can't paradrop unknown infantry type "${l.inf}"`);break;case ts.ParaDrop:{let e=s.rules.general.paradrop.getParadropSquads(i.country.side);for(var[c,u]of e.entries())s.rules.hasObject(u.inf,Bt.Infantry)?t.push(new za(o,i,r,u,c)):console.warn(`Can't paradrop unknown infantry type "${u.inf}"`);break}case ts.MultiMissile:if(!e.weaponType)throw new Error("Missing WeaponType in super weapon rules");t.push(new tn(o,i,r,e.weaponType));break;case ts.LightningStorm:t.push(new an(o,i,r));break;case ts.IronCurtain:t.push(new nn(o,i,r));break;case ts.ChronoSphere:if(!a)throw new Error("Missing tile2 action param");t.push(new on(o,i,r,a))}for(var d of t)this.addEffect(d);s.traits.filter(Ds).forEach(e=>{e[Ds.onActivate](o,i,s,r,a)}),s.events.dispatch(new Vs(o,i,r,a,n))}}}class ln{constructor(e){this.target=e,this.type=is.ObjectCloakChange}}(ca=ca||{}).onDamage=Symbol();class cn{constructor(e,t){this.gameObject=e,this.cloakDelayMinutes=t,this.isActive=!1,this.resetCloakCooldown()}isCloaked(){return this.isActive}uncloak(e){var t=this.isActive;this.resetCloakCooldown(),t&&(this.isActive=!1,e.events.dispatch(new ln(this.gameObject)))}resetCloakCooldown(){this.cooldownTicks=Math.floor(60*this.cloakDelayMinutes*Fs.BASE_TICKS_PER_SECOND)}[Qr.onSpawn](e,t){this.resetCloakCooldown()}[Lr.onTick](e,t){0<this.cooldownTicks&&this.cooldownTicks--,!(this.cooldownTicks<=0)||this.isActive||e.isVehicle()&&e.submergibleTrait&&!e.submergibleTrait.isSubmerged()||e.temporalTrait.getTarget()||(this.isActive=!0,t.events.dispatch(new ln(this.gameObject)))}[ca.onDamage](e,t){this.uncloak(t)}dispose(){this.gameObject=void 0}}class un{static calculateOverlayId(e,t){if(e!==na.NotSpecial){var i=t.dx,t=t.dy,i=Math.floor((t-9)/2%12*((t-8)/2%12)%12-(i-13)/2%12*((i-12)/2%12)%12+12e4);return i%=12,e===na.Ore?$a.minIdRiparius+i:e===na.Gems?$a.minIdCruentus+i:e===na.Vinifera?$a.minIdVinifera+i:e===na.Aboreus?$a.minIdAboreus+i:void 0}}}var dn,pn,gn,mn,fn,yn,wn,Tn,bn,vn,Sn,kn,On,_n,In,Cn,An,Bn,xn,En,Pn,Nn,Mn,Dn,Rn,Ln,r=__webpack_require__(949);class Fn extends r.Box2{}const jn=[Bs.IonStorm,Bs.Gas,Bs.Pod,Bs.Squad];class Un{constructor(e){this.randomCrateSpawn=e,this.crates=[],this.availEdgeTiles=[],this.allTiles=[]}init(n){var o=n.map.tiles.getMapSize();let h=n.map.tiles,e=[],l=0;for(let a=0;a<o.width;++a){let t,i,s=!1,r=!1;for(let e=0;e<o.height;++e){var c=h.getByMapCoords(a,e);if(c&&this.canPlaceCrateOnTile(n,c)){var u=n.map.getTileZone(c)===bs.Water;t?(u||(i=c),r=u):u?s=r=!0:t=i=c}else if(t&&!c)break}t&&(e.push(t),i&&i!==t&&e.push(i),s||r||l++)}this.availEdgeTiles=e,this.allTiles=h.getAll(),this.mapEdgeIsWater=0===l,this.minCrates=n.rules.crateRules.crateMinimum*n.gameOpts.humanPlayers.filter(e=>-3!==e.countryId).length}[xs.onTick](t){for(var e of this.crates)e.ticksLeft--,e.ticksLeft<=0&&(t.unspawnObject(e.obj),e.obj.dispose());if(this.crates=this.crates.filter(e=>0<e.ticksLeft),this.randomCrateSpawn)for(let e=0;e<this.minCrates-this.crates.length&&this.spawnCrateAtRandom(this.allTiles,t);e++);}spawnCrateAtRandom(e,t){e=this.chooseSpawnTile(e,t);if(e)return this.spawnRandomCrateAt(e,t)}spawnRandomCrateAt(e,t){if(this.canPlaceCrateOnTile(t,e)){var i=t.map.getTileZone(e,!0)===bs.Water,i=this.choosePowerup(i,t.rules.powerups.powerups,t);if(i)return this.spawnCrateAt(e,i,t)}}spawnCrateAt(t,i,s){if(this.canPlaceCrateOnTile(s,t)){var r=s.map.getTileZone(t,!0)===bs.Water,a=s.rules.crateRules,r=r?a.waterCrateImg:a.crateImg;let e=s.createObject(Bt.Overlay,r);e.overlayId=s.rules.getOverlayId(r),e.value=0,s.spawnObject(e,t);s=60*a.crateRegen*Fs.BASE_TICKS_PER_SECOND*(.5+1.5*s.generateRandom());return this.crates.push({obj:e,powerup:i,ticksLeft:s}),e}}chooseSpawnTile(e,t){return t.generateRandom()<(this.mapEdgeIsWater?1/3:2/3)&&this.availEdgeTiles.length&&(e=this.availEdgeTiles),this.chooseRandomTile(e,t)}chooseRandomTile(e,t){let i;let s=0;for(;i=e[t.generateRandomInt(0,e.length-1)],s++,s<100&&!this.canPlaceCrateOnTile(t,i););if(100<=s){var r=t.map.tileOccupation.getEmptyTiles();if(!r.length)return;i=r[t.generateRandomInt(0,r.length-1)]}return i}canPlaceCrateOnTile(e,t){return e.map.mapBounds.isWithinBounds(t)&&!e.map.getGroundObjectsOnTile(t).length&&0<e.map.terrain.getPassableSpeed(t,Jt.Amphibious,!1)&&t.terrainType!==Yt.Shore&&0===t.rampType}choosePowerup(t,i,s){if((i=t?i.filter(e=>e.waterAllowed):i).length){var r,t=i.reduce((e,t)=>e+t.probShares,0),a=s.generateRandomInt(0,t);let e=0;for(r of i)if(e+=r.probShares,a<e)return r}}peekInsideCrate(t){return this.crates.find(e=>e.obj===t)?.powerup.type}pickupCrate(e,t,i){let s=this.crates.find(e=>e.obj===t);if(s){this.crates.splice(this.crates.indexOf(s),1),i.unspawnObject(s.obj),s.obj.dispose();let t=this.grantPowerup(e,s.powerup,s.obj.tile,i);var r;return void 0!==t&&(e.owner.cratesPickedUp++,r=i.rules.powerups.powerups.find(e=>e.type===t),i.events.dispatch(new Ts(r,e.owner,e,s.obj.tile))),this.randomCrateSpawn&&this.spawnCrateAtRandom(this.allTiles,i),t}}grantPowerup(t,i,s,r){let a=t.owner,n=!1;if(a.isCombatant()){if(i.type===Bs.Unit){let e;if(![...a.buildings].some(e=>e.rules.constructionYard)&&r.rules.crateRules.freeMCV){let t=r.rules.general.baseUnit;if(!a.getOwnedObjects(!0).some(e=>t.includes(e.name))&&a.credits>=[...r.rules.ai.buildPower,...r.rules.ai.buildRefinery].map(e=>r.rules.getBuilding(e)).filter(e=>e.aiBasePlanningSide===a.country.side).reduce((e,t)=>e+t.cost,0)){var o=t.find(e=>{let t=r.rules.getObject(e,Bt.Vehicle);return t.isAvailableTo(a.country)&&t.hasOwner(a.country)});if(!o)throw new Error(`No suitable MCV found for player country ${a.country}`);e=r.rules.getObject(o,Bt.Vehicle)}}if(e||(h=(h=r.rules.crateRules.unitCrateType)?r.rules.hasObject(h,Bt.Vehicle)?[r.rules.getObject(h,Bt.Vehicle)]:[]:[...r.rules.vehicleRules.values()].filter(e=>e.crateGoodie&&0<r.map.terrain.getPassableSpeed(s,e.speedType,!1))).length&&(e=h[r.generateRandomInt(0,h.length-1)]),e){let t=r.createUnitForPlayer(e,a);var h=new js(r.map.tiles,r.map.mapBounds,s,{width:1,height:1},0,3,e=>0<r.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&!r.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length).getNextTile();h?(r.spawnObject(t,h),n=!0):(a.removeOwnedObject(t),t.dispose())}}else if(i.type===Bs.Money){if(!i.data)throw new Error("Money powerup missing data field");a.credits=Math.max(0,a.credits+Math.floor(Number(i.data)*(.55+2*r.generateRandom()*.45))),n=!0}else if(i.type===Bs.HealBase){var e;for(e of a.getOwnedObjects(!0))e.isDestroyed||e.healthTrait.healToFull(void 0,r);n=!0}else if(i.type===Bs.Reveal)r.mapShroudTrait.revealMap(a,r),n=!0;else if(i.type===Bs.Darkness)r.mapShroudTrait.resetShroud(a,r),n=!0;else if(i.type===Bs.Veteran){if(t.veteranTrait&&!t.veteranTrait.isMaxLevel()){n=!0;var l,c=Number(i.data);for(l of this.getUnitsInCrateRadius(r,s,a))l.veteranTrait?.promote(c,r)}}else if(i.type===Bs.Armor){if(1===t.crateBonuses.armor){n=!0;var u,d=Number(i.data);for(u of this.getUnitsInCrateRadius(r,s,a))1===u.crateBonuses.armor&&(u.crateBonuses.armor=d)}}else if(i.type===Bs.Firepower){if(1===t.crateBonuses.firepower){n=!0;var p,g=Number(i.data);for(p of this.getUnitsInCrateRadius(r,s,a))1===p.crateBonuses.firepower&&(p.crateBonuses.firepower=g)}}else if(i.type===Bs.Speed){if(1===t.crateBonuses.speed){n=!0;var m,f=Number(i.data);for(m of this.getUnitsInCrateRadius(r,s,a))1===m.crateBonuses.speed&&(m.crateBonuses.speed=f)}}else if(i.type===Bs.Cloak){if(!t.cloakableTrait){n=!0;for(var y of this.getUnitsInCrateRadius(r,s,a))y.cloakableTrait||(y.cloakableTrait=new cn(y,r.rules.general.cloakDelay),r.addObjectTrait(y,y.cloakableTrait))}}else if(i.type===Bs.ICBM){var w=[...r.rules.superWeaponRules.values()].find(e=>e.type===ts.MultiMissile);if(w&&a.superWeaponsTrait&&!a.superWeaponsTrait.has(w.name)){let e=r.createSuperWeapon(w.name,a,!0);e.isGift=!0,a.superWeaponsTrait.add(e),n=!0}}else if(i.type===Bs.Invulnerability){var T=[...r.rules.superWeaponRules.values()].find(e=>e.type===ts.IronCurtain);T&&(r.traits.get(hn).activateEffect(T,a,r,s,void 0,!0),n=!0)}else if(i.type===Bs.Explosion||i.type===Bs.Napalm){n=!0;w=Number(i.data),T=i.type===Bs.Napalm?r.rules.combatDamage.flameDamage:r.rules.combatDamage.c4Warhead;let e=new Qa(r.rules.getWarhead(T));e.detonate(r,w,t.tile,t.tileElevation,t.position.worldPosition,t.zone,ra.None,r.createTarget(t,t.tile),{player:t.owner,weapon:void 0},!1,!1,void 0,0)}else{if(i.type!==Bs.Tiberium)return void console.warn(`Unhandled powerup type "${Bs[i.type]}"`);{let e=new wa(r.map.tiles,r.map.mapBounds,s,2,r,e=>qa.canBePlacedOn(e,r.map)),t,i=0;for(;i++<6&&(t=e.getNextTile());){var b=un.calculateOverlayId(na.Ore,t);if(void 0===b)throw new Error("Expected an overlayId");let e=r.createObject(Bt.Overlay,r.rules.getOverlayName(b));e.overlayId=b,e.value=3,r.spawnObject(e,t),n=!0}}}if(n)return i.type;i=r.rules.powerups.powerups.find(e=>e.type===Bs.Money&&0<e.probShares);return i?this.grantPowerup(t,i,s,r):void 0}}getUnitsInCrateRadius(e,t,i){let s=e.rules.crateRules.crateRadius,r=new Cs(e.map.tileOccupation);return e.map.technosByTile.queryRange((new Fn).setFromCenterAndSize(new Ss(t.rx,t.ry),new Ss(s,s))).filter(e=>e.owner===i&&e.isUnit()&&r.tileDistance(e,t)<=s)}}class Wn{constructor(){this.powerups=[]}readIni(e){for(var[r,a]of e.entries){let[e,t,i,s]=a.split(",");var n=Number(e),a=Bs[r];void 0!==a?jn.includes(a)||this.powerups.push({type:a,probShares:n,animName:"<none>"!==t.toLowerCase()?t:void 0,waterAllowed:"yes"===i,data:s}):console.warn(`Unknown powerup "${r}". Skipping.`)}return this}}const zn=["Gold","DarkRed","DarkBlue","DarkGreen","Orange","DarkSky","Purple","Magenta"];class Vn{constructor(e,t){this.ini=e,this.logger=t,this.buildingTypes=new Map,this.vehicleTypes=new Map,this.infantryTypes=new Map,this.aircraftTypes=new Map,this.terrainTypes=new Map,this.overlayTypes=new Map,this.overlayIdsByType=new Map,this.animationTypes=new Map,this.animationNames=new Set,this.voxelAnimTypes=new Map,this.smudgeTypes=new Map,this.warheadTypes=new Map,this.tiberiumTypes=new Map,this.superWeaponTypes=new Map,this.countryTypes=new Map,this.weaponTypes=new Map,this.allObjectRules=new Map,this.buildingRules=new Map,this.infantryRules=new Map,this.vehicleRules=new Map,this.aircraftRules=new Map,this.terrainRules=new Map,this.overlayRules=new Map,this.smudgeRules=new Map,this.voxelAnimRules=new Map,this.countryRules=new Map,this.warheadRules=new Map,this.powerups=new Wn,this.colors=new Map,this.general=new zi,this.ai=new gs,this.crateRules=new ws,this.elevationModel=new ms,this.mpDialogSettings=new kt,this.audioVisual=new Ai,this.combatDamage=new ds,this.radiation=new fs,this.landRules=new Map,this.tiberiumRules=new Map,this.superWeaponRules=new Map,this.cachedWeaponRules=new Map,this.cachedProjectileRules=new Map,this.init()}hasObject(e,t){return this.allObjectRules.get(t)?.has(e)}getObject(e,t){t=this.allObjectRules.get(t)?.get(e);if(!t)throw new Error(`Missing rules for object "${e}"`);return t}getTechnoByInternalId(e,t){let i;if(t===Bt.Building)i=this.buildingTypes.get(e);else if(t===Bt.Infantry)i=this.infantryTypes.get(e);else if(t===Bt.Vehicle)i=this.vehicleTypes.get(e);else{if(t!==Bt.Aircraft)throw new Error(`Type ${Bt[t]} is not a techno type`);i=this.aircraftTypes.get(e)}if(void 0===i)throw new Error(`Object type "${Bt[t]}" with ID "${e}" not found`);return this.getObject(i,t)}getBuilding(e){var t=this.buildingRules.get(e);if(!t)throw new Error(`Missing rules for building "${e}"`);return t}getWeapon(e){let t=this.cachedWeaponRules.get(e);if(!t){var i=this.ini.getSection(e);if(!i)throw new Error(`Weapon ${e} is missing ini section`);t=new Ci(i),this.cachedWeaponRules.set(e,t)}return t}getWeaponByInternalId(e){var t=this.weaponTypes.get(e);if(!t)throw new RangeError(`Weapon with internal ID "${e}" not found`);return this.getWeapon(t)}getWarhead(e){let t=this.warheadRules.get(e.toLowerCase());var i;if(t||(i=this.ini.getSection(e))&&(t=new $i(i),this.warheadRules.set(e.toLowerCase(),t)),!t)throw new Error(`Unknown warhead ${e}`);return t}getProjectile(e){let t=this.cachedProjectileRules.get(e);if(!t){var i=this.ini.getSection(e);if(!i)throw new Error(`Projectile ${e} is missing ini section`);t=new qi(Bt.Projectile,i),this.cachedProjectileRules.set(e,t)}return t}getOverlayName(e){var t=this.overlayTypes.get(e);if(!t)throw new Error(`Invalid overlay id ${e}`);return t}hasOverlayId(e){return this.overlayTypes.has(e)}getOverlayId(e){var t=this.overlayIdsByType.get(e);if(void 0===t)throw new Error(`Invalid overlay name ${e}`);return t}getOverlay(e){var t=this.overlayRules.get(e);if(!t)throw new Error(`Missing rules for overlay "${e}"`);return t}getAnimationName(e){return this.animationTypes.get(e)}getCountry(e){if(!this.countryRules.has(e))throw new Error(`Unknown country ${e}`);return this.countryRules.get(e)}getMultiplayerCountries(){return[...this.countryRules.values()].filter(e=>e.multiplay)}getMultiplayerColors(){let t=new Map;return zn.forEach(e=>{if(!this.colors.has(e))throw new Error(`Multiplayer color "${e}" does not exist in the rules [Colors] section.`);t.set(e,this.colors.get(e))}),t}getLandRules(e){let t=this.landRules.get(e);var i;return t||(i=e===Kt.Cliff?"Rock":Kt[e],t=(new Gi).readIni(this.ini.getOrCreateSection(i)),this.landRules.set(e,t)),t}getTiberium(e){var t=this.tiberiumTypes.get(e);if(!t)throw new Error(`Unknown tiberium type ${e}`);return this.tiberiumRules.get(t)}getSuperWeapon(e){if(!this.superWeaponRules.has(e))throw new Error(`Unknown superweapon type "${e}"`);return this.superWeaponRules.get(e)}getIni(){return this.ini}applySpecialFlags(e){e.initialVeteran&&(this.general.veteran.initialVeteran=!0)}init(){this.readAudioVisual(),this.readCombatDamage(),this.readRadiation(),this.readGeneral(),this.readAi(),this.readCrateRules(),this.readElevationModel(),this.readMpDialogSettings(),this.readObjectTypes("BuildingTypes",this.buildingTypes),this.readObjectTypes("InfantryTypes",this.infantryTypes),this.readObjectTypes("VehicleTypes",this.vehicleTypes),this.readObjectTypes("AircraftTypes",this.aircraftTypes),this.readObjectTypes("TerrainTypes",this.terrainTypes),this.readObjectTypes("SmudgeTypes",this.smudgeTypes),this.readObjectTypes("Animations",this.animationTypes),this.animationNames=new Set(this.animationTypes.values()),this.readObjectTypes("VoxelAnims",this.voxelAnimTypes),this.readObjectTypes("OverlayTypes",this.overlayTypes),this.overlayTypes.forEach((e,t)=>this.overlayIdsByType.set(e,t)),this.readColors(),this.readObjectTypes("Countries",this.countryTypes),this.readObjectTypes("Warheads",this.warheadTypes),this.readObjectTypes("Tiberiums",this.tiberiumTypes),this.readObjectTypes("SuperWeaponTypes",this.superWeaponTypes),this.allObjectRules.set(Bt.Building,this.buildingRules).set(Bt.Infantry,this.infantryRules).set(Bt.Vehicle,this.vehicleRules).set(Bt.Aircraft,this.aircraftRules).set(Bt.Terrain,this.terrainRules).set(Bt.Overlay,this.overlayRules).set(Bt.Smudge,this.smudgeRules).set(Bt.VoxelAnim,this.voxelAnimRules),this.readObjects(Bt.Building,this.buildingTypes,this.buildingRules),this.readObjects(Bt.Infantry,this.infantryTypes,this.infantryRules),this.readObjects(Bt.Vehicle,this.vehicleTypes,this.vehicleRules),this.readObjects(Bt.Aircraft,this.aircraftTypes,this.aircraftRules),this.readObjects(Bt.Terrain,this.terrainTypes,this.terrainRules),this.readObjects(Bt.Overlay,this.overlayTypes,this.overlayRules),this.readObjects(Bt.Smudge,this.smudgeTypes,this.smudgeRules),this.readObjects(Bt.VoxelAnim,this.voxelAnimTypes,this.voxelAnimRules),this.readCountries(),this.readWarheads(),this.readPowerups(),this.readTiberiums(),this.readSuperWeapons(),this.buildWeaponsList()}readAudioVisual(){var e=this.ini.getSection("AudioVisual");if(!e)throw new Error("Missing [AudioVisual] section");this.audioVisual.readIni(e)}readCombatDamage(){var e=this.ini.getSection("CombatDamage");if(!e)throw new Error("Missing [CombatDamage] section");this.combatDamage.readIni(e)}readRadiation(){var e=this.ini.getSection("Radiation");if(!e)throw new Error("Missing [Radiation] section");this.radiation.readIni(e)}readGeneral(){var e=this.ini.getSection("General");if(!e)throw new Error("Missing [General] section");this.general.readIni(e)}readAi(){var e=this.ini.getSection("AI");if(!e)throw new Error("Missing [AI] section");this.ai.readIni(e)}readCrateRules(){var e=this.ini.getSection("CrateRules");if(!e)throw new Error("Missing [CrateRules] section");this.crateRules.readIni(e)}readElevationModel(){var e=this.ini.getSection("ElevationModel");if(!e)throw new Error("Missing [ElevationModel] section");this.elevationModel.readIni(e)}readMpDialogSettings(){var e=this.ini.getSection("MultiplayerDialogSettings");if(!e)throw new Error("Missing [MultiplayerDialogSettings] section");this.mpDialogSettings.readIni(e)}readObjectTypes(i,s){let e=this.ini.getSection(i);if(!e)throw new Error(`Missing [${i}] section`);let r=0,a=new Set;e.entries.forEach((e,t)=>{Number.isNaN(Number(t))?this.logger?.debug(`Non-numeric id "${t}" found in rules section [${i}]. Skipping.`):a.has(e)?this.logger?.debug(`Duplicate type "${e}" in rules section [${i}]. Skipping.`):(s.set(r++,e),a.add(e))})}readColors(){let e=this.ini.getSection("Colors");if(!e)throw new Error("Missing [Colors] section");e.entries.forEach((e,t)=>{var[i,s,e]=e.split(","),e=U.fromHsv(parseInt(i,10),parseInt(s,10),parseInt(e,10));this.colors.set(t,e)})}readObjects(s,e,r){e.forEach((e,t)=>{var i=this.ini.getSection(e);i?(t=(new us).create(s,i,t),r.set(e,t)):this.logger?.debug(`${Bt[s]} type "${e}" has no rules section`)})}readCountries(){this.countryTypes.forEach((e,t)=>{var i=this.ini.getSection(e);if(!i)throw new Error(`Missing ini section for country ${e}`);let s=new _i(t);s.readIni(i),this.countryRules.set(e,s)})}readWarheads(){this.warheadTypes.forEach(e=>{var t=this.ini.getSection(e);t?(t=new $i(t),this.warheadRules.set(e.toLowerCase(),t)):this.logger?.debug(`Warhead "${e}" has no rules section`)})}readPowerups(){var e=this.ini.getSection("Powerups");if(!e)throw new Error("Missing [Powerups] section");this.powerups.readIni(e)}readTiberiums(){this.tiberiumTypes.forEach(e=>{var t=this.ini.getSection(e);if(!t)throw new Error(`Missing rules section for tiberium type ${e}`);this.tiberiumRules.set(e,(new ps).readIni(t))})}readSuperWeapons(){this.superWeaponTypes.forEach((e,t)=>{var i=this.ini.getSection(e);if(!i)throw new Error(`Missing rules section for superweapon type ${e}`);this.superWeaponRules.set(e,new ys(t).readIni(i))})}buildWeaponsList(){let e=new Set;e.add(this.general.dropPodWeapon);for(var t of this.superWeaponRules.values())t.weaponType&&e.add(t.weaponType);var s,i;e.add(en.NUKE_PAYLOAD_NAME);for(let i of[...this.buildingRules.values(),...this.aircraftRules.values(),...this.vehicleRules.values(),...this.infantryRules.values()])for(s of[i.deathWeapon,i.primary,i.secondary,i.elitePrimary,i.eliteSecondary,i.occupyWeapon,i.eliteOccupyWeapon,...i.weaponCount?new Array(i.weaponCount).fill(0).map((e,t)=>[i.getWeaponAtIndex(t),i.getEliteWeaponAtIndex(t)]).flat():[]].filter(Fa).filter(e=>""!==e))e.add(s);let r=0;for(i of e)this.weaponTypes.set(r++,i)}}(r=dn=dn||{})[r.Ready=0]="Ready",r[r.Guard=1]="Guard",r[r.Prone=2]="Prone",r[r.Walk=3]="Walk",r[r.FireUp=4]="FireUp",r[r.Down=5]="Down",r[r.Crawl=6]="Crawl",r[r.Up=7]="Up",r[r.FireProne=8]="FireProne",r[r.Idle1=9]="Idle1",r[r.Idle2=10]="Idle2",r[r.Die1=11]="Die1",r[r.Die2=12]="Die2",r[r.Hover=13]="Hover",r[r.Fly=14]="Fly",r[r.FireFly=15]="FireFly",r[r.Tumble=16]="Tumble",r[r.AirDeathStart=17]="AirDeathStart",r[r.AirDeathFalling=18]="AirDeathFalling",r[r.AirDeathFinish=19]="AirDeathFinish",r[r.Tread=20]="Tread",r[r.Swim=21]="Swim",r[r.WetAttack=22]="WetAttack",r[r.WetIdle1=23]="WetIdle1",r[r.WetIdle2=24]="WetIdle2",r[r.WetDie1=25]="WetDie1",r[r.WetDie2=26]="WetDie2",r[r.Deploy=27]="Deploy",r[r.Deployed=28]="Deployed",r[r.DeployedFire=29]="DeployedFire",r[r.DeployedIdle=30]="DeployedIdle",r[r.Undeploy=31]="Undeploy",r[r.Paradrop=32]="Paradrop",r[r.Cheer=33]="Cheer",r[r.Panic=34]="Panic";const Hn=new Map([["E",5],["S",3],["W",1],["N",7]]);class Gn{readIni(e){let t=new Map;for(var[i,s]of e.entries){i=dn[i];void 0!==i&&(s=s.split(","),s={type:i,startFrame:Number(s[0]),frameCount:Number(s[1]),facingMult:Number(s[2]),onlyFacing:s[3]?Hn.get(s[3]):void 0},t.set(i,s))}return t}}(r=pn=pn||{})[r.None=0]="None",r[r.Global=1]="Global",r[r.Level=2]="Level",r[r.Ambient=3]="Ambient",r[r.Full=4]="Full",r[r.Default=5]="Default";class $n{constructor(e,t,i){this.sequences=new Map,this.dockingOffsets=[],this.type=e,this.rules=t,this.art=i,this.init()}static getDefaultPalette(e){switch(e){case Bt.Building:case Bt.Aircraft:case Bt.Infantry:case Bt.Vehicle:case Bt.Projectile:case Bt.VoxelAnim:return _.Unit;case Bt.Overlay:return _.Overlay;case Bt.Smudge:case Bt.Terrain:return _.Iso;default:Bt.Animation;return _.Anim}}static getDefaultLighting(e){switch(e){case Bt.Animation:return pn.None;case Bt.Aircraft:case Bt.Building:case Bt.Infantry:case Bt.Vehicle:return pn.Ambient;case Bt.Projectile:case Bt.VoxelAnim:return pn.Global;case Bt.Overlay:case Bt.Smudge:case Bt.Terrain:default:return pn.Full}}static getDefaultRemapability(e){switch(e){case Bt.Aircraft:case Bt.Building:case Bt.Infantry:case Bt.Vehicle:return!0;case Bt.Overlay:case Bt.Smudge:case Bt.Terrain:case Bt.Animation:case Bt.Projectile:case Bt.VoxelAnim:return!1;default:throw new Error(`Unknown object type ${e}`)}}static getDefaultDrawOffset(e){switch(e){case Bt.Animation:case Bt.Building:case Bt.Vehicle:case Bt.Infantry:case Bt.Overlay:case Bt.Smudge:case Bt.Projectile:case Bt.VoxelAnim:return new Ss(0,0);case Bt.Terrain:case Bt.Aircraft:return new Ss(0,(ks.ISO_TILE_SIZE+1)/2);default:throw new Error(`Unknown object type ${e}`)}}static getDefaultShadow(e){switch(e){case Bt.Overlay:case Bt.Building:case Bt.Infantry:case Bt.Terrain:case Bt.Vehicle:case Bt.Aircraft:return!0;default:case Bt.Smudge:case Bt.Animation:case Bt.Projectile:case Bt.VoxelAnim:return!1}}static getDefaultHeight(e){switch(e){case Bt.Building:return 2;case Bt.Infantry:case Bt.Vehicle:case Bt.Aircraft:return 1;default:return 0}}static factory(e,t,i,s){let r=new this(e,t,s);return e===Bt.Infantry&&(!(s=s.getString("Sequence"))||(s=i.getSection(s))&&(r.sequences=(new Gn).readIni(s))),r}init(){this.image=[Bt.Infantry,Bt.Vehicle,Bt.Aircraft].includes(this.type)?"":this.art.getString("Image"),this.report=this.art.getString("Report")||void 0,this.readRotors(),this.noHva=this.art.getBool("NoHVA"),this.startSound=this.art.getString("StartSound")||void 0,this.readMuzzleFlash(),this.readPaletteAndLightingTypes(),this.readRemapability(),this.readFlatness(),this.readDockingOffsets();var e=this.art.getNumberArray("QueueingCell");this.queueingCell=e.length?new Ss(e[0],e[1]):void 0,this.demandLoad=this.art.getBool("DemandLoad");var t=this.art.getBool("UseLineTrail"),i=this.art.getNumberArray("LineTrailColor"),e=this.art.getNumber("LineTrailColorDecrement",$n.DEFAULT_LINE_TRAIL_DEC);t&&i.length?(this.useLineTrail=!0,this.lineTrailColor=i,this.lineTrailColorDecrement=e):this.useLineTrail=!1,this.crater=this.art.getBool("Crater"),this.forceBigCraters=this.art.getBool("ForceBigCraters"),this.scorch=this.art.getBool("Scorch"),this.height=this.art.getNumber("Height",$n.getDefaultHeight(this.type)),this.isVoxel=this.art.getBool("Voxel"),this.occupyHeight=this.art.getNumber("OccupyHeight",this.height),this.type===Bt.Building?this.canHideThings=this.art.getBool("CanHideThings",!0):this.canHideThings=!1,this.canBeHidden=this.art.getBool("CanBeHidden",!0),this.addOccupy=this.readAddRemoveOccupy("AddOccupy"),this.removeOccupy=this.readAddRemoveOccupy("RemoveOccupy"),this.rotates=this.art.getBool("Rotates")}get imageName(){return(this.image||this.rules.imageName)+(this.rules.alternateArcticArt?"A":"")}get cameo(){let e=this.art.getString("Cameo")||$n.MISSING_CAMEO;return e.toLowerCase()}get altCameo(){let e=this.art.getString("AltCameo")||$n.MISSING_CAMEO;return e.toLowerCase()}get useTheaterExtension(){return this.art.getBool("Theater")}readPaletteAndLightingTypes(){this.paletteType=_.Default,this.lightingType=pn.Default,(this.rules instanceof os?this.rules.noUseTileLandType:void 0)&&(this.paletteType=_.Iso,this.lightingType=pn.Full),this.art.getBool("TerrainPalette")||this.art.getBool("ShouldUseCellDrawer")?this.paletteType=_.Iso:this.art.getBool("AnimPalette")?(this.paletteType=_.Anim,this.lightingType=pn.None):this.art.getString("Palette")&&(this.paletteType=_.Custom,this.customPaletteName=this.art.getString("Palette")),this.art.getBool("AltPalette")&&(this.paletteType=_.Unit),(this.rules instanceof os||this.rules instanceof ns)&&this.rules.wall&&(this.paletteType=_.Unit,this.lightingType=pn.Ambient),(this.rules instanceof hs||this.rules instanceof ns)&&this.rules.gate&&(this.paletteType=_.Unit),this.rules instanceof hs&&this.rules.spawnsTiberium&&(this.paletteType=_.Unit,this.lightingType=pn.None),this.rules instanceof os&&(this.rules.isVeins&&(this.paletteType=_.Unit,this.lightingType=pn.None),this.rules.isVeinholeMonster&&(this.paletteType=_.Unit,this.lightingType=pn.None),this.rules.tiberium&&(this.lightingType=pn.None),this.rules.land===Kt.Railroad&&(this.paletteType=_.Iso,this.lightingType=pn.Full),this.rules.crate&&(this.paletteType=_.Iso,this.lightingType=pn.Full)),this.paletteType===_.Default&&(this.paletteType=$n.getDefaultPalette(this.type)),this.lightingType===pn.Default&&(this.lightingType=$n.getDefaultLighting(this.type))}readRemapability(){this.remapable=$n.getDefaultRemapability(this.type),this.art.getBool("TerrainPalette")||this.art.getBool("AnimPalette")?this.remapable=!1:this.rules instanceof qi&&this.rules.firersPalette&&(this.remapable=!0)}readFlatness(){let e=!1;this.type===Bt.Building||this.type===Bt.Animation?e=this.art.getBool("Flat"):this.type===Bt.Smudge&&(e=!0),this.rules instanceof os&&(this.rules.wall||this.rules.crate||this.rules.isARock||(e=!0)),this.flat=e}readRotors(){var i=this.art.getArray("Rotors");if(i.length){let t=[];for(let e=0;e<i.length;++e){var s=this.art.getNumberArray(`Rotor${e+1}Axis`,void 0,[0,1,0]),s=new ss(-s[2],-s[0],s[1]).normalize();t.push({name:i[e],axis:s,speed:this.art.getNumber(`Rotor${e+1}Rate`)||void 0,idleSpeed:this.art.getNumber(`Rotor${e+1}IdleRate`)||void 0})}t.length&&(this.rotors=t)}}readMuzzleFlash(){let e=0,t=`MuzzleFlash${e}`,i=[];for(;this.art.has(t);){var[s,r]=this.art.getNumberArray(t);i.push({x:s,y:r}),e++,t=`MuzzleFlash${e}`}this.muzzleFlash=i.length?i:void 0}readDockingOffsets(){if(this.type===Bt.Building){var t=this.rules.numberOfDocks;for(let e=0;e<t;e++){var[i,s,r]=this.art.getNumberArray(`DockingOffset${e}`,/\,\s*/,[0,0,0]);this.dockingOffsets.push(new ss(i,r,s))}}}readAddRemoveOccupy(e){let t=0,i=[];for(;;){var s=this.art.getNumberArray(e+ ++t);if(!s.length)break;i.push(new Ss(s[0],s[1]))}return i}get bibShape(){return this.art.getString("BibShape")}get foundation(){let e=this.art.getString("Foundation","1x1");var[t,i]=e.split("x");return{width:parseInt(t,10),height:parseInt(i,10)}}get foundationCenter(){return new Ss(Math.floor(this.foundation.width/2-.5),Math.floor(this.foundation.height/2-.5))}getDrawOffset(){if(this.rules instanceof hs&&this.rules.spawnsTiberium)return new Ss(0,0);let e=$n.getDefaultDrawOffset(this.type);return this.rules instanceof os&&this.rules.isARock&&(e.y+=(ks.ISO_TILE_SIZE+1)/2),e}get hasShadow(){return this.art.getBool("Shadow",$n.getDefaultShadow(this.type))&&!this.rules.noShadow}get turretOffset(){return this.art.getNumber("TurretOffset")}get walkFrames(){return this.art.getNumber("WalkFrames")}get firingFrames(){return this.art.getNumber("FiringFrames")}get isFlamingGuy(){return this.art.getBool("IsFlamingGuy")}get runningFrames(){return this.art.getNumber("RunningFrames")}get primaryFireFlh(){return new Ya(this.art.getNumberArray("PrimaryFireFLH"))}get elitePrimaryFireFlh(){var e=this.art.getNumberArray("ElitePrimaryFireFLH");return e.length?new Ya(e):this.primaryFireFlh}get primaryFirePixelOffset(){return this.art.getNumberArray("PrimaryFirePixelOffset")}get secondaryFirePixelOffset(){return this.art.getNumberArray("SecondaryFirePixelOffset")}get secondaryFireFlh(){return new Ya(this.art.getNumberArray("SecondaryFireFLH"))}get eliteSecondaryFireFlh(){var e=this.art.getNumberArray("EliteSecondaryFireFLH");return e.length?new Ya(e):this.secondaryFireFlh}getSpecialWeaponFlh(e){return new Ya(this.art.getNumberArray(`Weapon${e+1}FLH`))}get fireUp(){return this.art.getNumber("FireUp")||this.art.getNumber("DelayedFireDelay")}get isAnimDelayedFire(){return this.art.getBool("IsAnimDelayedFire")}get zShapePointMove(){return this.art.getNumberArray("ZShapePointMove")}get zAdjust(){return this.art.getNumber("ZAdjust")}get trailer(){return this.art.getString("Trailer")}get spawnDelay(){return this.art.getNumber("SpawnDelay",1)}get translucent(){return this.art.getBool("Translucent")}get translucency(){var e=(e=this.art.getNumber("Translucency",0))/25*25;return e/=100}}$n.DEFAULT_LINE_TRAIL_DEC=16,$n.MISSING_CAMEO="xxicon";class qn{constructor(e,t,i,s){this.rules=e,this.artIni=t,this.mapFile=i,this.logger=s,this.objectArt=new Map,this.parse()}hasObject(e,t){return this.objectArt.get(t)?.has(e)}getObject(e,t){if(!e)throw new Error(`Must specify an art name for type "${Bt[t]}"`);var i=this.objectArt.get(t)?.get(e);return i||(this.logger?.debug(`Missing art for object "${e}"`),new $n(t,this.rules.hasObject(e,t)?this.rules.getObject(e,t):new Ii(t,new h(e)),new h(e)))}getAnimation(e){return this.getObject(e,Bt.Animation)}getProjectile(e){var t=this.rules.getProjectile(e),i=t.imageName;let s=this.artIni.getSection(i);return s||(this.logger?.debug(`Image ${i} (Projectile: ${e}) has no section in art.ini`),s=new h(i)),$n.factory(t.type,t,this.artIni,s)}getIni(){return this.artIni}parse(){this.rules.allObjectRules.forEach((e,t)=>{let s=new Map;this.objectArt.set(t,s),e.forEach(e=>{var t=this.artIni.getSection(e.imageName),i=this.artIni.getSection(e.name);(t=this.applyUnitMapOverrides(e,this.mapFile,i,t))?(t=$n.factory(e.type,e,this.artIni,t),s.set(e.name,t)):this.logger?.debug(`${Bt[e.type]} "${e.name}" has no art section "${e.imageName}"`)})});let e=[[Bt.Animation,this.rules.animationNames]];e.forEach(([s,e])=>{let r=new Map;this.objectArt.set(s,r),e.forEach(e=>{var t,i=this.artIni.getSection(e);i?(t=new Ii(s,new h(e)),i=new $n(s,t,i),r.set(e,i)):this.logger?.debug(`${Bt[s]} "${e}" has no art section`)})})}applyUnitMapOverrides(e,t,s,r){if([Bt.Infantry,Bt.Vehicle,Bt.Aircraft].includes(e.type)&&!!t?.getSection(e.name)?.getString("Image")&&s){let i=s.clone();r?.entries.forEach((e,t)=>{i.set(t,e)}),r=i,this.logger?.debug(`${Bt[e.type]} "${e.name}": `+`Using merged art sections ${e.name} and ${e.imageName}`)}return r}}class Xn{constructor(e){this.rules=e}static factory(e,t){return new this(t.getCountry(e))}get id(){return this.rules.id}get side(){return this.rules.side}get name(){return this.rules.name}isPlayable(){return this.rules.multiplay&&!this.rules.multiplayPassive}hasVeteranUnit(e,t){let i=[];switch(e){case Bt.Aircraft:i=this.rules.veteranAircraft;break;case Bt.Infantry:i=this.rules.veteranInfantry;break;case Bt.Vehicle:i=this.rules.veteranUnits;break;default:throw new Error(`Unsupported object type "${Bt[e]}"`)}return i.includes(t)}}class Zn{constructor(e,t){this.target=e,this.player=t,this.type=is.BuildingEvacuate}}class Qn{constructor(e,t,i){this.building=e,this.evacThreshold=t,this.maxOccupants=i,this.units=[]}isOccupied(){return!!this.units.length}canBeOccupied(){return this.building.healthTrait.health>100*this.evacThreshold}[ca.onDamage](e,t){e.healthTrait.health<=100*this.evacThreshold&&this.evacuate(t)}[Wr.onDestroy](e,t,i,s){if(s){for(var r of this.units)t.destroyObject(r,i,!0);this.units=[]}else this.evacuate(t)}getHash(){return H(this.units.map(e=>e.getHash()))}debugGetState(){return{units:this.units.map(e=>e.debugGetState())}}dispose(){this.building=void 0}evacuate(s,r=!1){let a=this.building,n=this.units;if(n.length){let e=new Map;for(var t of n)e.set(t.rules.speedType,(e.get(t.rules.speedType)||[]).concat(t));for(let[t,i]of e){var o,h=new js(s.map.tiles,s.map.mapBounds,a.tile,a.art.foundation,1,1,e=>0<s.map.terrain.getPassableSpeed(e,t,!1)&&Math.abs(e.z-a.tile.z)<2&&!s.map.terrain.findObstacles({tile:e,onBridge:void 0},i[0]).length).getNextTile();for(o of i){var l=n.indexOf(o);h?(n.splice(l,1),s.unlimboObject(o,h),o.unitOrderTrait.addTask(new va(s))):r||(s.destroyObject(o,{player:o.owner}),n.splice(l,1))}}var i=a.owner;n.length||a.isDestroyed||s.changeObjectOwner(a,s.getCivilianPlayer()),s.events.dispatch(new Zn(a,i))}}}class Yn{constructor(){this.facing=0,this.desiredFacing=0}isRotating(){return this.facing!==this.desiredFacing}[Lr.onTick](e){this.desiredFacing!==this.facing&&(e=e.rules.rot,this.facing=Tr.tick(this.facing,this.desiredFacing,e||Number.POSITIVE_INFINITY).facing)}}class Kn{constructor(e,t){this.target=e,this.status=t,this.type=is.BuildStatusChange}}class Jn{constructor(e){this.target=e,this.type=is.PowerLow}}class eo{constructor(e){this.target=e,this.type=is.PowerRestore}}class to{constructor(e,t,i){this.target=e,this.power=t,this.drain=i,this.type=is.PowerChange}}(r=gn=gn||{})[r.Low=0]="Low",r[r.Normal=1]="Normal";class io{constructor(e){this.player=e,this.power=0,this.drain=0,this.level=gn.Normal,this.blackoutFrames=0,this.powerByObject=new Map}isLowPower(){return this.level===gn.Low}setBlackoutFor(e,t){var i=0<this.blackoutFrames;this.blackoutFrames=e,i||this.updateLevel(t)}updateBlackout(e){0<this.blackoutFrames&&(this.blackoutFrames--,this.blackoutFrames<=0&&this.updateLevel(e))}getBlackoutDuration(){return this.blackoutFrames}updateFrom(t,i,s){var r=t.rules.power;if(r){if(r<0)"add"!==i&&"remove"!==i||(this.drain+="add"===i?-r:r);else{let e=0;if("add"===i){var a=Math.ceil(r*t.healthTrait.health/100);this.powerByObject.set(t,a),e=a}else if("update"===i||"remove"===i){a=this.powerByObject.get(t);if(void 0===a)throw new Error("Cannot update power before add.");e="update"===i?(r=Math.ceil(r*t.healthTrait.health/100),this.powerByObject.set(t,r),r-a):(this.powerByObject.delete(t),-a)}this.power+=e}this.updateLevel(s),s.traits.filter(Ms).forEach(e=>{e[Ms.onPowerChange](this.player,s)}),s.events.dispatch(new to(this.player,this.power,this.drain))}}updateLevel(t){var e=this.level;this.level=this.power>=this.drain&&!this.blackoutFrames?gn.Normal:gn.Low,this.level!==e&&(e===gn.Normal&&this.level===gn.Low&&(t.traits.filter(Ms).forEach(e=>{e[Ms.onPowerLow](this.player,t)}),t.events.dispatch(new Jn(this.player))),e===gn.Low&&this.level===gn.Normal&&(t.traits.filter(Ms).forEach(e=>{e[Ms.onPowerRestore](this.player,t)}),t.events.dispatch(new eo(this.player))))}getHash(){return H([this.power,this.drain])}debugGetState(){return{power:this.power,drain:this.drain}}dispose(){this.player=void 0,this.powerByObject.clear()}}class so{constructor(e){this.obj=e,this.turnedOn=!0}setTurnedOn(e){this.turnedOn=e}isCharged(){return!!this.obj.isBuilding()&&!!this.obj.overpoweredTrait?.hasChargersToPowerOn()}isPoweredOn(e=!1){return!(!this.obj||!this.turnedOn)&&(!(e||!this.isCharged())||(!this.obj.rules.power&&this.obj.rules.needsEngineer?!this.obj.owner.isNeutral:!!this.obj.owner.powerTrait&&this.obj.owner.powerTrait?.level!==gn.Low))}dispose(){this.obj=void 0}}class ro{constructor(){this.listeners=new Set}subscribe(e){this.listeners.add(e)}subscribeOnce(i){let s=(e,t)=>{i(e,t),this.unsubscribe(s),s=void 0};this.subscribe(s)}unsubscribe(e){this.listeners.delete(e)}dispatch(t,i){this.listeners.forEach(e=>e(i,t))}asEvent(){return this}}(r=mn=mn||{})[r.Structures=0]="Structures",r[r.Armory=1]="Armory",r[r.Infantry=2]="Infantry",r[r.Vehicles=3]="Vehicles",r[r.Aircrafts=4]="Aircrafts",r[r.Ships=5]="Ships",(r=fn=fn||{})[r.Idle=0]="Idle",r[r.Active=1]="Active",r[r.OnHold=2]="OnHold",r[r.Ready=3]="Ready";class ao{constructor(e,t,i){this.type=e,this._maxSize=t,this.maxItemQuantity=i,this.items=[],this.size=0,this._status=fn.Idle,this._onUpdate=new ro}get onUpdate(){return this._onUpdate.asEvent()}get status(){return this._status}set status(e){var t=this._status;(this._status=e)!==t&&this._onUpdate.dispatch(this)}get maxSize(){return this._maxSize}set maxSize(e){var t=this.size;this.size=Math.min(e,this.size);let i=0,s=0;for(;i<=this.size&&s<this.items.length;){let e=this.items[s];i+=e.quantity,i>this.size&&(e.quantity-=i-this.size),0<e.quantity&&s++}this._maxSize=e,this.items[s]&&this.items.splice(s),t!==this.size&&(this.size||(this._status=fn.Idle),this._onUpdate.dispatch(this))}get currentSize(){return this.size}find(t){return this.items.filter(e=>e.rules===t)}getFirst(){return this.items[0]}getAll(){return[...this.items]}push(e,t,i){t=Math.min(this.maxSize-this.size,t);var s=this.find(e).reduce((e,t)=>e+t.quantity,0);t=Math.min(this.maxItemQuantity-s,t),this.items[this.items.length-1]?.rules===e?this.items[this.items.length-1].quantity+=t:this.items.push({rules:e,quantity:t,creditsEach:i,creditsSpent:0,creditsSpentLeftover:0,progress:0}),this.size+=t,t&&(this._status===fn.Idle&&(this._status=fn.Active),this._onUpdate.dispatch(this))}pop(e,t){this.remove(e,t,!1)}shift(e,t){this.remove(e,t,!0)}remove(e,t,i){let s=this.find(e);if(!s.length)throw new Error(`Can't remove non-existent item ${e.name} from queue ${mn[this.type]}`);var r;if(s.reduce((e,t)=>e+t.quantity,0)<t)throw new Error(`Attempted to remove a quantity larger than the one in queue (${e.name})`);let a=t;for(;0<a;){let e=i?s.shift():s.pop();e.quantity<=a?(r=this.getFirst()===e,this.items.splice(this.items.indexOf(e),1),r&&(this._status=fn.Active),a-=e.quantity):(e.quantity-=a,a=0)}this.size-=t,t&&(this.size||(this._status=fn.Idle),this._onUpdate.dispatch(this))}notifyUpdated(){this._onUpdate.dispatch(this)}}const no=e=>void 0!==e.position;class oo{constructor(e,t){this.tiles=e,this.tileOccupation=t}hasLineOfSight(t,i,s){var r=s.warhead.rules.wall||!s.projectileRules.subjectToWalls,a=s.projectileRules.subjectToCliffs,n=s.rules.spawner;let o=0,h=!1;if(!r||a||n){var l,c,s=no(t)?t.tile:t,i=no(i)?i.isBuilding()?i.centerTile:i.tile:i;let e=s.z;a&&no(t)&&t.isUnit()&&t.onBridge&&(e+=this.tileOccupation.getBridgeOnTile(s)?.tileElevation??0);for({x:l,y:c}of La(s.rx,s.ry,i.rx,i.ry)){var u=this.tiles.getByMapCoords(l,c);if(!u)return!1;if(!r&&u.landType===Kt.Wall)return!1;if(a)if(u.landType===Kt.Cliff){if(u.z>e)return!1;h=!0}else{if(u.z>e&&h)return!1;h=!1}if(n&&o<2&&this.tileOccupation.getBridgeOnTile(u)?.isHighBridge())return!1;o++}}return!0}}class ho extends Sa{constructor(e,t,i,s){super(e,t instanceof Aa?t.isBuilding()?t.centerTile:t.tile:t,i,{pathFinderIgnoredBlockers:t instanceof Aa&&0<s.range?[t]:void 0}),this.target=t,this.weapon=s,this.recalcMinRange=!0,this.cancelRequested=!1,this.bomberInitialLock=!1,this.rangeHelper=new Cs(e.map.tileOccupation),this.losHelper=new oo(e.map.tiles,e.map.tileOccupation)}onStart(i){let e=this.target,s=this.game.map;if(e instanceof Aa&&e.isBuilding()&&i.rules.movementZone!==si.Fly){let t=e.tile;var r=e instanceof Aa?e.getFoundation():{width:1,height:1},r=new js(s.tiles,s.mapBounds,t,r,1,5,e=>0<s.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&Math.abs(e.z-t.z)<2).getNextTile();r&&this.rangeHelper.tileDistance(e,r)>Math.SQRT2&&this.updateTarget(r,!1)}this.bomberInitialLock=this.isCloseEnoughToDest(i,i.tile),super.onStart(i)}cancel(){this.bomberManeuverTile?this.cancelRequested=!0:super.cancel()}shouldAirStrafe(e){return e.rules.movementZone===si.Fly&&e.rules.locomotor===ii.Aircraft&&e.rules.fighter&&1<this.weapon.projectileRules.iniRot}isBombingRun(e){return e.rules.movementZone===si.Fly&&e.rules.locomotor===ii.Aircraft&&this.weapon.projectileRules.iniRot<=1}isAirStrafeCloseEnough(e){return this.rangeHelper.tileDistance(e,this.targetTile)<Math.min(this.weapon.range,2)}bomberCanReturn(e){return!this.bomberManeuverTile||this.rangeHelper.tileDistance(e,this.bomberManeuverTile)<=1}findStrafeDestination(t,i){let e=new wa(this.game.map.tiles,this.game.map.mapBounds,i,this.weapon.range,this.game,e=>this.rangeHelper.isInWeaponRange(t,i,this.weapon,this.game.rules,e));return e.getNextTile()}hasReachedDestination(e){return super.hasReachedDestination(e)||this.canStopAtTile(e,e.tile,e.onBridge)}canStopAtTile(t,e,i){if(t.zone!==bs.Air&&this.target instanceof Aa&&this.game.map.tileOccupation.isTileOccupiedBy(e,this.target)&&(!this.target.isUnit()||this.target.tile===e&&this.target.moveTrait.moveState!==$r.Moving))return!1;if(t.zone!==bs.Air){if(!super.canStopAtTile(t,e,i))return!1}else if(this.game.map.tileOccupation.getAirObjectsOnTile(e).filter(e=>e.isUnit()&&e.moveTrait.moveState!==$r.Moving&&e!==t).length)return!1;return!(this.isBombingRun(t)&&!this.bomberCanReturn(e))&&(!!this.isCancelling()||this.isCloseEnoughToDest(t,e))}isCloseEnoughToDest(e,t){if(e.rules.balloonHover&&!e.rules.hoverAttack)return this.rangeHelper.isInTileRange(t,this.target,0,0);if(this.weapon.rules.cellRangefinding||!e.isInfantry())return this.rangeHelper.isInWeaponRange(e,this.target,this.weapon,this.game.rules,t)&&this.losHelper.hasLineOfSight(t,this.target,this.weapon);var i=e.zone===bs.Air?e.position.computeSubCellOffset(e.position.desiredSubCell):e.position.getTileOffset(),{minRange:s,range:r}=this.rangeHelper.computeWeaponRangeVsTarget(t,this.target,this.weapon,this.game.rules),i=ks.tile3dToWorld(t.rx+i.x/ks.LEPTONS_PER_TILE,t.ry+i.y/ks.LEPTONS_PER_TILE,t.z+e.position.tileElevation);return(e.isUnit()&&e.rules.movementZone===si.Fly?this.rangeHelper.isInRange2(i,this.target,s,r):this.rangeHelper.isInRange3(i,this.target,s,r))&&this.losHelper.hasLineOfSight(t,this.target,this.weapon)}findRelocationTile(t,i,s){if(s.rules.movementZone!==si.Fly)return super.findRelocationTile(t,i,s);{i=this.game.map;let e=new wa(i.tiles,i.mapBounds,t,1,this.game,e=>this.isCancelling()||this.isCloseEnoughToDest(s,e));return e.getNextTile()}}retarget(e,t){var i=e instanceof Aa?e.isBuilding()?e.centerTile:e.tile:e;this.bomberManeuverTile?this.bomberQueuedTargetTile=i:(this.updateTarget(i,t),this.recalcMinRange=!0),this.target=e,this.options?.ignoredBlockers&&(this.options.ignoredBlockers=e instanceof Aa?[e]:void 0),this.options??(this.options={}),this.options.pathFinderIgnoredBlockers=e instanceof Aa?[e]:void 0}onTick(r){if(this.recalcMinRange){this.recalcMinRange=!1;var e=this.findMinRangeRelocationTile(r,this.targetTile);if(e!==this.targetTile){if(!e)return this.cancel(),!1;this.updateTarget(e,!!e.onBridgeLandType)}}if(this.shouldAirStrafe(r)&&!this.isCancelling()&&(this.updateTarget(this.target instanceof Aa?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target,!1),!this.isAirStrafeCloseEnough(r)||(a=this.findStrafeDestination(r,this.targetTile))&&this.updateTarget(a,!1)),this.isBombingRun(r)&&!this.isCancelling()&&(!r.ammo||this.weapon.getBurstsFired()||this.bomberInitialLock)&&!this.bomberManeuverTile){this.bomberInitialLock=!1;let e=r.position.getMapPosition();var a=this.target instanceof Aa?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target;let t=new Ss(a.rx+.5,a.ry+.5).clone().multiplyScalar(ks.LEPTONS_PER_TILE).sub(e),i=t.length();i||(t.copy(Tr.toMapCoords(r.direction)),i=Number.EPSILON);let s=e.clone().add(t.setLength(i+7*ks.LEPTONS_PER_TILE));a=s.multiplyScalar(1/ks.LEPTONS_PER_TILE).floor(),a=La(a.x,a.y,r.tile.rx,r.tile.ry);if(!a.length)throw new Error("Bresenham returned no tiles");a=a[0];this.bomberManeuverTile=this.game.map.tiles.getByMapCoords(a.x,a.y)??this.game.map.tiles.getPlaceholderTile(a.x,a.y),this.options.allowOutOfBoundsTarget=!0,this.updateTarget(this.bomberManeuverTile,!1)}return this.bomberManeuverTile&&this.bomberCanReturn(r.tile)&&(this.bomberManeuverTile=void 0,this.bomberQueuedTargetTile&&(this.updateTarget(this.bomberQueuedTargetTile,!1),this.recalcMinRange=!0,this.bomberQueuedTargetTile=void 0)),this.cancelRequested&&(this.bomberManeuverTile||(this.cancelRequested=!1,this.cancel())),!!(this.isBombingRun(r)&&this.isCancelling()&&this.forceCancel(r))||super.onTick(r)}forceCancel(e){return!this.bomberManeuverTile&&super.forceCancel(e)}findMinRangeRelocationTile(e,t){var{minRange:i,range:s}=this.rangeHelper.computeWeaponRangeVsTarget(e,this.target,this.weapon,this.game.rules);return e.rules.locomotor===ii.Chrono?this.rangeHelper.isInRange(e,this.target,s-1,s,this.weapon.rules.cellRangefinding)?t:this.findTileInRange(e,t,s-1,2*s)??t:this.rangeHelper.isInRange(e,this.target,i,Number.POSITIVE_INFINITY,this.weapon.rules.cellRangefinding)?t:this.findTileInRange(e,t,2*i,s-i)}findTileInRange(t,e,i,s){let r=this.game.map;var a,i=new Ss(t.tile.rx-e.rx,t.tile.ry-e.ry).setLength(i).floor().add(new Ss(e.rx,e.ry));let n;for(a of La(i.x,i.y,e.rx,e.ry))if(n=r.tiles.getByMapCoords(a.x,a.y),n)break;if(n){let e=new js(r.tiles,r.mapBounds,n,{width:1,height:1},0,s,e=>this.rangeHelper.isInWeaponRange(t,this.target,this.weapon,this.game.rules,e)&&this.losHelper.hasLineOfSight(e,this.target,this.weapon)&&0<r.terrain.getPassableSpeed(e,t.rules.speedType,!!e.onBridgeLandType)&&!r.terrain.findObstacles({tile:e,onBridge:!!e.onBridgeLandType},t).length);return e.getNextTile()}}}class lo{tick(e,t){this.tickChildren(e,t)}startTask(e,t){if(e.status!==Ls.NotStarted)throw new Error(`Attempted to start a task with status ${e.status}`);e.status=Ls.Running,e.onStart(t)}tickTask(e,t){let i=this.tickChildren(e.children,t);var s=e.children.find(e=>e.blocking);if(!i&&s)return!1;if(!t.isSpawned)return!1;if(e.status===Ls.NotStarted)throw new Error("Attempted tick on a non-started task");if(e.isRunning()||e.isCancelling()){var r=e.isCancelling(),a=!!e.waitingForChildrenToFinish||e.onTick(t);e.children.length&&!s&&a&&(i=e.children.every(e=>e.status===Ls.Cancelled||e.status===Ls.Finished),e.waitingForChildrenToFinish=!i);a=a&&i;return a&&(e.onEnd(t),e.status=r?Ls.Cancelled:Ls.Finished),a}return!0}tickChildren(s,r){let a=!0;if(s.length){let t=new Set,i;for(;r.isSpawned&&(i=s.find(e=>!t.has(e)));){let e;if(i.status===Ls.NotStarted&&this.startTask(i,r),i.status===Ls.Running||i.status===Ls.Cancelling)e=!0===this.tickTask(i,r);else{if(i.status!==Ls.Cancelled)throw new Error(`Unhandled task status ${Ls[i.status]}`);e=!0}if(e){var n=s.indexOf(i);-1!==n&&s.splice(n,1)}else{if(a=!1,i.blocking)break;t.add(i)}}}return a}}class co{constructor(e,t,i){this.tileOccupation=i,this.isOre=!1,e?e.isOverlay()&&e.isBridge()?(this.bridge=e,this.tile=t):e.isOverlay()&&e.isTiberium()?(this.isOre=!0,this.tile=e.tile):(this.obj=e,this.tile=e.isBuilding()?e.centerTile:e.tile):(t.landType===Kt.Tiberium&&(this.isOre=!0),this.tile=t)}equals(e){return this.obj===e.obj&&this.tile===e.tile&&this.bridge===e.bridge&&this.isOre===e.isOre}getWorldCoords(){return this.obj?this.obj.position.worldPosition:ks.tile3dToWorld(this.tile.rx+.5,this.tile.ry+.5,this.tile.z+(this.bridge?.tileElevation??0))}isBridge(){return!this.obj&&!!this.bridge}getBridge(){return this.bridge||(this.obj?.isUnit()&&this.obj.onBridge?this.tileOccupation.getBridgeOnTile(this.obj.tile):void 0)}}(r=yn=yn||{})[r.Idle=0]="Idle",r[r.CheckRange=1]="CheckRange",r[r.PrepareToFire=2]="PrepareToFire",r[r.FireUp=3]="FireUp",r[r.Firing=4]="Firing",r[r.JustFired=5]="JustFired";class uo{constructor(e,t){this.disabled=!1,this.attackState=yn.Idle,this.passiveScanCooldownTicks=0,this.taskRunner=new lo,this.distributedFireHistory=new Map,this.rangeHelper=new Cs(t),this.losHelper=new oo(e,t)}isIdle(){return this.attackState===yn.Idle}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}isOnCooldown(e){let t=[e.primaryWeapon,e.secondaryWeapon],i=e.armedTrait?.getDeployFireWeapon();return i?.rules.areaFire&&!i.rules.fireOnce&&(t=t.filter(e=>e!==i)),t.some(e=>0<(e?.getCooldownTicks()??0))}expirePassiveScanCooldown(){this.passiveScanCooldownTicks=0}increasePassiveScanCooldown(e){this.passiveScanCooldownTicks+=e}cancelOpportunityFire(){this.opportunityFireTask?.cancel()}selectDefaultWeapon(e){let i;if((e.isInfantry()||e.isVehicle())&&e.rules.deployFire){let t=e.armedTrait?.getDeployFireWeapon();i=e.deployerTrait?.isDeployed()?t&&!t.rules.areaFire?t:void 0:[e.primaryWeapon,e.secondaryWeapon].find(e=>e!==t)}else i=e.isBuilding()&&e.garrisonTrait?e.garrisonTrait.isOccupied()?e.owner.country.side===Xt.GDI?e.primaryWeapon:e.secondaryWeapon??e.primaryWeapon:void 0:e.isBuilding()&&e.overpoweredTrait?e.overpoweredTrait.getWeapon():e.primaryWeapon;return i}selectWeaponVersus(e,t,i,s=!1,r=!1){var a=t.tile;const n=t instanceof co?t.obj:t;t=this.getAvailableWeapons(e,r,n?.isOverlay()||s&&!n);return this.selectWeaponFromList(e,n,a,t,i,s,r,!1)}selectWeaponFromList(e,t,i,s,r,a,n,o){if((!t?.isInfantry()&&!t?.isVehicle()||!t.disguiseTrait||this.canAttackThroughDisguise(e,t,t.disguiseTrait,r,a,n,o))&&(t?.isBuilding()&&t.overpoweredTrait&&t.owner===e.owner&&s.find(e=>e.warhead.rules.electricAssault)&&(s=s.filter(e=>e.warhead.rules.electricAssault)),!(n&&t?.isAircraft()&&t.missileSpawnTrait&&t.zone!==bs.Air))){var h=t?.isTechno()?t.rules.armor:void 0;for(const l of s)if(l.targeting.canTarget(t,i,r,a,n)&&(void 0===h||this.checkArmor(l.warhead.rules,h,n)))return l}}getAvailableWeapons(e,t,i){let s;var r;return s=(e.isInfantry()||e.isVehicle())&&e.rules.deployFire&&e.armedTrait?(r=e.armedTrait.getDeployFireWeapon(),[e.deployerTrait?.isDeployed()?r.rules.areaFire?void 0:r:r===e.secondaryWeapon?e.primaryWeapon:e.secondaryWeapon]):e.isBuilding()&&e.garrisonTrait?e.garrisonTrait.isOccupied()?[e.owner.country.side===Xt.GDI?e.primaryWeapon:e.secondaryWeapon??e.primaryWeapon]:[]:e.isBuilding()&&e.overpoweredTrait?[e.overpoweredTrait.getWeapon()]:i||t?[e.primaryWeapon,!i&&t&&e.secondaryWeapon&&(e.secondaryWeapon.projectileRules.isAntiAir||e.secondaryWeapon.rules.spawner||e.secondaryWeapon.warhead.rules.electricAssault)?e.secondaryWeapon:void 0]:[e.primaryWeapon,e.secondaryWeapon],s.filter(e=>e&&!e.rules.neverUse)}canAttackThroughDisguise(e,t,i,s,r,a,n){if(!r&&i.hasTerrainDisguise()&&!s.areFriendly(e,t)&&!e.owner.sharedDetectDisguiseTrait?.has(t))return!1;if(a){if(n&&t.moveTrait.isIdle()&&!e.rules.detectDisguise&&!e.owner.sharedDetectDisguiseTrait?.has(t)&&!s.areFriendly(t,e))return!1;i=i.getDisguise();if(i?.owner&&!e.rules.detectDisguise&&!e.owner.sharedDetectDisguiseTrait?.has(t)&&(i.owner===e.owner||s.alliances.areAllied(e.owner,i.owner)))return!1}return!0}checkArmor(e,t,i){var s=e.ivanBomb||e.bombDisarm||e.nukeMaker?1:e.verses.get(t);return void 0===s?(console.warn(`Unhandled ArmorType ${ri[t]} in warhead ${e.name} verses`),!1):!(100*s<=(i?1:0))}createAttackTask(e,t,i,s,r){return new po(e,e.createTarget(t,i),s,r)}[Lr.onTick](a,n){if(!this.isDisabled()){var e;if(this.opportunityFireTask&&(!a.unitOrderTrait.hasTasks()||a.isUnit()&&!a.unitOrderTrait.getTasks()[0].preventOpportunityFire||(a.unitOrderTrait.getTasks()[0]instanceof po?this.opportunityFireTask=void 0:this.opportunityFireTask.cancel()),this.opportunityFireTask&&(e=[this.opportunityFireTask],this.taskRunner.tick(e,a),e.length||(this.opportunityFireTask=void 0))),!this.opportunityFireTask&&this.retaliateTarget){var o=this.retaliateTarget;this.retaliateTarget=void 0;let e;!a.unitOrderTrait.hasTasks()&&n.isValidTarget(o)&&(e=this.selectWeaponVersus(a,o,n,!1))&&a.unitOrderTrait.addTask(this.createAttackTask(n,o,o.tile,e,{holdGround:a.rules.movementZone===si.Fly}))}if(!this.opportunityFireTask&&this.shouldPassiveAcquire(a))if(0<this.passiveScanCooldownTicks)this.passiveScanCooldownTicks--;else{this.passiveScanCooldownTicks=a.guardMode?n.rules.general.guardAreaTargetingDelay:n.rules.general.normalTargetingDelay;let e=this.selectDefaultWeapon(a);o=a.unitOrderTrait.hasTasks();let t=void 0,i,s;!o&&a.guardMode&&e&&a.owner.isCombatant()&&(t=a.armedTrait?.computeGuardScanRange(e),i=a.guardArea?.tile,s=50);let r=!1;if(e){var h=this.scanForTarget(a,e,n,t,i);if(h.target){let{target:e,weapon:t}=h;var l=this.createAttackTask(n,e,e.tile,t,{holdGround:o||a.rules.movementZone===si.Fly&&!a.guardMode||a.rules.movementZone!==si.Fly&&e.isUnit()&&e.zone===bs.Air||(a.isInfantry()||a.isVehicle())&&!!a.disguiseTrait||!a.owner.isCombatant(),disallowTurning:o,leashTiles:s,passive:!0});o?this.opportunityFireTask=l:a.unitOrderTrait.addTask(l),r=!0,o||!a.guardMode||a.guardArea||(a.guardArea={tile:a.tile,onBridge:!!a.isUnit()&&a.onBridge})}}r||o||!a.secondaryWeapon?.warhead.rules.electricAssault||(e=a.secondaryWeapon,(h=this.scanForTarget(a,e,n,void 0,void 0,!0)).target&&({target:l,weapon:h}=h,h=this.createAttackTask(n,l,l.tile,h,{passive:!0}),a.unitOrderTrait.addTask(h),r=!0)),!r&&!o&&a.guardArea&&a.isUnit()&&a.moveTrait&&!a.moveTrait.isDisabled()&&a.guardArea.tile!==a.tile&&a.unitOrderTrait.addTasks(new Sa(n,a.guardArea.tile,a.guardArea.onBridge),new ga(()=>{[qr.Success,qr.CloseEnough].includes(a.moveTrait.lastMoveResult)||a.resetGuardModeToIdle(),a.guardArea=void 0}))}}}[ca.onDamage](e,t,i,s){this.isDisabled()||!this.retaliateTarget&&!this.opportunityFireTask&&s&&s.obj&&s.weapon&&this.shouldRetaliate(e,t,i,s.obj,s.weapon.warhead)&&(this.retaliateTarget=s.obj)}[Ur.onBeforeTeleport](e,t,i,s){s||(this.attackState=yn.Idle,this.currentTarget=void 0,this.retaliateTarget=void 0,this.opportunityFireTask=void 0)}shouldPassiveAcquire(e){if(!e.owner.isCombatant()&&e.rules.needsEngineer||!e.rules.canPassiveAquire||!e.primaryWeapon)return!1;if(e.mindControllerTrait?.isAtCapacity())return!1;var t=e.rules.opportunityFire||e.rules.balloonHover&&e.unitOrderTrait.getCurrentTask()?.isAttackMove;if(e.isUnit()&&t){if(e.unitOrderTrait.hasTasks()&&e.unitOrderTrait.getTasks()[0].preventOpportunityFire)return!1}else if(e.unitOrderTrait.hasTasks())return!1;return!0}shouldRetaliate(e,t,i,s,r){return!(i<1||t.areFriendly(e,s)||!e.rules.canRetaliate||!e.primaryWeapon||r.rules.temporal||s.rules.missileSpawn||e.unitOrderTrait.hasTasks()||!t.isValidTarget(s)||(s.isInfantry()||s.isVehicle())&&s.disguiseTrait&&!e.rules.detectDisguise||e.mindControllerTrait?.isAtCapacity()||!this.selectWeaponVersus(e,s,t,!1)||(e.isBuilding()||s.isBuilding()?this.rangeHelper.tileDistance(e,s):this.rangeHelper.distance2(e,s)/ks.LEPTONS_PER_TILE)>e.sight)}scanForTarget(e,t,i,s,r,a=!1){let n={},o=Number.NEGATIVE_INFINITY;var h=this.getAvailableWeapons(e,!0,!1),t=s??(e.rules.guardRange||t.range)+1+3+i.rules.elevationModel.bonusCap+(t.projectileRules.isAntiAir?e.rules.airRangeBonus:0);for(const u of this.scanTechnosAround(e,t,i)){var l,c=this.selectWeaponFromList(e,u,u.tile,h,i,!1,!0,!0);c&&this.canPassiveAcquire(u,i)&&i.isValidTarget(u)&&(s?this.rangeHelper.isInRange(e,u,c.minRange,s,c.rules.cellRangefinding)&&(!r||this.rangeHelper.isInRange2(r,u,0,s)):this.rangeHelper.isInWeaponRange(e,u,c,i.rules))&&(a||this.losHelper.hasLineOfSight(e,u,c))&&(l=this.rangeHelper.distance3(e,u)/ks.LEPTONS_PER_TILE,(l=this.computeThreat(u,e,c,l,i.rules.general.threat))>o&&(n={target:u,weapon:c},o=l))}return n.target&&e.rules.distributedFire&&this.updateDistributedFireHistory(n),n}scanTechnosAround(e,t,i){var s=e.getFoundation();const r=new Ss(e.tile.rx,e.tile.ry),a=new Ss(e.tile.rx+s.width-1,e.tile.ry+s.height-1);r.addScalar(-t),a.addScalar(t);t=new Fn(r,a);return i.map.technosByTile.queryRange(t)}canPassiveAcquire(e,t){return!e.owner.isNeutral&&!e.rules.civilian&&!e.rules.insignificant&&(1<e.rules.threatPosed||0<e.rules.specialThreatValue&&!e.isBuilding()||e.rules.harvester||e.name===t.rules.general.paradrop.paradropPlane)}computeThreat(e,t,i,s,r){let a=[e.primaryWeapon,e.secondaryWeapon].filter(Fa).map(e=>e.warhead.rules.verses.get(t.rules.armor)??0).reduce((e,t)=>Math.max(e,t),0)*r.targetEffectivenessCoefficientDefault;return e.attackTrait?.currentTarget?.obj===t&&(a*=-1),a+=e.rules.specialThreatValue*r.targetSpecialThreatCoefficientDefault,a+=(i.warhead.rules.verses.get(e.rules.armor)??0)*r.myEffectivenessCoefficientDefault,a+=e.healthTrait.health/100*r.targetStrengthCoefficientDefault,a+=s*r.targetDistanceCoefficientDefault,t.rules.distributedFire&&(a-=1e6*(this.distributedFireHistory.get(e)??0)),t.rules.vhpScan===li.Strong&&e.healthTrait.getProjectedHitPoints()<=0&&(a-=1e6),a}updateDistributedFireHistory(e){if(50!==this.distributedFireHistory.get(e.target)){for(var[t,i]of this.distributedFireHistory)i--,i<=0?this.distributedFireHistory.delete(t):this.distributedFireHistory.set(t,i);this.distributedFireHistory.set(e.target,50)}}dispose(){this.distributedFireHistory.clear()}}class po extends Hs{constructor(e,t,i,s={}){super(),this.game=e,this.target=t,this.weapon=i,this.options=s,this.moveExecuted=!1,this.moveAttempts=0,this.rangeCheckCooldown=0,this.lastInRangeTargetPosition=new ss,this.lastInRangeSelfPosition=new ss,this.initialIndirectTarget=!1,this.forceDropTarget=!1,this.rangeHelper=new Cs(e.map.tileOccupation),this.losHelper=new oo(e.map.tiles,e.map.tileOccupation),this.targetLinesConfig={pathNodes:[]},this.updateTargetLines(this.target,!0)}duplicate(){return new po(this.game,this.target,this.weapon,this.options)}getWeapon(){return this.weapon}setWeapon(e){this.weapon=e}setForceAttack(e){this.options.force=e}requestTargetUpdate(e){this.target.equals(e)||(this.needsTargetUpdate=e)}onTargetChange(e){let t=e.attackTrait,i=this.target;t.currentTarget=i,this.lastValidTargetPosition=i.obj?{tile:i.tile,onBridge:i.getBridge()}:void 0,this.initialTargetOwner=i.obj?.isTechno()?i.obj.owner:void 0,this.initialIndirectTarget=!i.obj&&this.game.map.tileOccupation.getObjectsOnTile(i.tile).some(e=>e.isOverlay()&&!e.isBridgePlaceholder()||e.isTerrain()),this.updateTargetLines(i,!0)}updateTargetLines(e,t){this.targetLinesConfig.target=e.obj,this.targetLinesConfig.pathNodes=e.obj?[]:[{tile:e.tile,onBridge:e.getBridge()}],this.targetLinesConfig.isAttack=t}onStart(t){if(!t.attackTrait)throw new Error(`Object ${t.name} has no attack trait`);if(0!==t.ammo){let e=this.game.map.tileOccupation;var i,s;t.attackTrait.attackState=yn.CheckRange,this.onTargetChange(t),this.initialSelfPosition={tile:t.tile,onBridge:t.isUnit()&&t.onBridge?e.getBridgeOnTile(t.tile):void 0},this.weapon.rules.limboLaunch&&t.isUnit()&&!this.target.obj&&(this.forceDropTarget=!0,{reachable:i,fallback:s}=this.findReachableMeleePosition(this.target.tile,!!this.target.getBridge(),{width:1,height:1},t),!i&&s&&(this.lastValidTargetPosition=s,this.updateTargetLines(this.game.createTarget(s.onBridge,s.tile),!1))),this.weapon.rules.limboLaunch&&this.target.obj?.isTechno()&&t.isUnit()&&!this.rangeHelper.isInWeaponRange(t,this.target.obj,this.weapon,this.game.rules)&&({reachable:i,fallback:s}=this.findReachableMeleePosition(this.target.obj.tile,this.target.obj.isUnit()&&this.target.obj.onBridge,this.target.obj.getFoundation(),t),i||(1<(t.unitOrderTrait.waypointPath?.waypoints?.length??0)?this.cancel():(this.forceDropTarget=!0,s&&(this.lastValidTargetPosition=s,this.updateTargetLines(this.game.createTarget(s.onBridge,s.tile),!1))))),this.rangeHelper.isInWeaponRange(t,this.target.obj??this.target.tile,this.weapon,this.game.rules)&&t.isUnit()&&t.rules.movementZone===si.Fly&&t.zone!==bs.Air&&(t.rules.hoverAttack||t.isAircraft())&&this.children.push(new Sa(this.game,t.tile,!1).setCancellable(!1))}else this.cancel()}findReachableMeleePosition(s,e,t,r){let i=this.game.map,a=i.tileOccupation,n=e?a.getBridgeOnTile(s):void 0,o=new qs(i),h=r.rules.movementZone===si.Fly,l=(e,t)=>h||0<i.terrain.getPassableSpeed(e,r.rules.speedType,!!t)&&o.isEligibleTile(e,t,n,s)&&!i.terrain.findObstacles({tile:e,onBridge:t},r).length,c,u=new js(i.tiles,i.mapBounds,s,t,1,Math.ceil(this.weapon.rules.range),e=>{let t=!1;var i;return l(e,void 0)&&(c=c??{tile:e,onBridge:void 0},t=!0),void 0!==e.onBridgeLandType&&(i=a.getBridgeOnTile(e),l(e,i)&&(c=c??{tile:e,onBridge:i},t=!0)),!!t&&this.rangeHelper.isInWeaponRange(r,s,this.weapon,this.game.rules,e)});return{reachable:u.getNextTile(),fallback:c}}onEnd(e){e.isVehicle()&&e.turretTrait&&(e.turretTrait.desiredFacing=e.direction),e.attackTrait.attackState=yn.Idle,e.attackTrait.currentTarget=void 0;var t=this.game.rules.general.prism.type;e.isBuilding()&&e.name===t&&this.weapon.type!==oi.Secondary&&this.countSupportBeamsAndFireDownTowers(e,t),this.weapon.rules.limboLaunch&&e.attackTrait.expirePassiveScanCooldown(),(e.isInfantry()||e.isVehicle())&&(e.isFiring=!1),this.weapon.hasBurstsLeft()&&this.weapon.resetBursts()}forceCancel(t){if(t.rules.movementZone!==si.Fly)return!1;if(!this.cancellable||this.children.some(e=>!e.cancellable))return!1;if(this.status===Ls.Running||this.status===Ls.Cancelling){if(this.children.filter(e=>e instanceof Sa).some(e=>!e.forceCancel(t)))return!1;this.onEnd(t),(t.isInfantry()||t.isVehicle())&&(t.isFiring=!1)}return this.status=Ls.Cancelled,!0}onTick(i){let s=i.attackTrait;(i.isInfantry()||i.isVehicle())&&s.attackState!==yn.Firing&&(i.isFiring=!1);let r=this.target.obj,a=this.children.find(e=>e instanceof ho);if(this.isCancelling()&&s.attackState!==yn.FireUp)return!i.airSpawnTrait?.isLaunchingMissiles()&&(a?.cancel(),!0);let n=!1;if(s.attackState===yn.FireUp){if(s.isDisabled())return!0;s.attackState=yn.Firing,n=!0}if(s.attackState===yn.Firing){if(this.initialIndirectTarget&&!this.game.map.getObjectsOnTile(this.target.tile).find(e=>e.isOverlay()&&!e.isBridgePlaceholder()||e.isTerrain()))return this.cancel(),this.onTick(i);if(n){var o=this.target.obj||this.target.tile;if(!this.game.isValidTarget(this.target.obj)||this.shouldDropTarget(this.target.obj)||!this.weapon.targeting.canTarget(this.target.obj,this.target.tile,this.game,!!this.options.force,!!this.options.passive)||!this.rangeHelper.isInWeaponRange(i,o,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(i,o,this.weapon))return s.attackState=yn.CheckRange,this.onTick(i)}if(this.weapon.rules.limboLaunch){if((r?.isVehicle()||r?.isAircraft())&&r.parasiteableTrait?.isInfested())return!0;if(i.rules.movementZone!==si.Fly&&r?.isUnit()&&r.zone===bs.Air)return!0}if(this.target.tile.onBridgeLandType&&i.tile.onBridgeLandType&&i.isUnit()&&(this.game.map.tileOccupation.getBridgeOnTile(this.target.tile)?.isHighBridge()||this.game.map.tileOccupation.getBridgeOnTile(i.tile)?.isHighBridge()))if((r?r.isUnit()&&(r.zone===bs.Air||r.onBridge):this.target.isBridge())!==(i.zone===bs.Air||i.onBridge)&&this.game.map.bridges.findHighBridgeBoundary(i.tile)?.tile===this.game.map.bridges.findHighBridgeBoundary(this.target.tile)?.tile)return!0;let e=1;o=this.game.rules.general.prism.type;if(i.isBuilding()&&i.name===o&&this.weapon.type!==oi.Secondary&&(o=this.countSupportBeamsAndFireDownTowers(i,o),e=1+o*this.game.rules.general.prism.supportModifier),this.weapon.rules.spawner&&(i.isVehicle()||i.isAircraft())&&i.parasiteableTrait?.isParalyzed())return!0;if(0===i.ammo)return i.isAircraft()&&(i.rules.fighter||i.rules.spawned)&&a?.cancel(),!0;let t=!1;if(this.weapon.rules.limboLaunch&&a){if(!a.forceCancel(i))return!1;i.moveTrait.lastTargetOffset=void 0,i.moveTrait.lastVelocity=void 0,t=!0}return(this.weapon.fire(this.target,this.game,e),t)?!0:!!this.weapon.rules.fireOnce||(!(!this.options.passive||!i.rules.distributedFire)||(s.attackState=yn.JustFired,!1))}if(s.attackState===yn.JustFired)return s.attackState=yn.PrepareToFire,this.onTick(i);this.needsTargetUpdate&&(this.target=this.needsTargetUpdate,r=this.target.obj,this.needsTargetUpdate=void 0,this.onTargetChange(i),r||a?.retarget(this.target.tile,!!this.target.getBridge())),r?.isTechno()&&r.replacedBy&&(h=this.game.createTarget(r.replacedBy,r.replacedBy.tile),this.target=h,r=r.replacedBy,this.onTargetChange(i));let t=this.game.isValidTarget(r)&&!this.shouldDropTarget(r);if(t){let e=this.weapon.targeting.canTarget(r,this.target.tile,this.game,!!this.options.force,!!this.options.passive);if(!e||!i.armedTrait.isEquippedWithWeapon(this.weapon)){var h=s.selectWeaponVersus(i,this.target,this.game,this.options.force,this.options.passive);if(h){if(this.setWeapon(h),s.attackState!==yn.CheckRange)return s.attackState=yn.CheckRange,this.onTick(i);e=!0}else e=!1}t=e}if(t&&(l=this.lastTargetTpCheck,r?.isUnit()&&l&&r.moveTrait.lastTeleportTick>=l?(t=!1,this.rangeCheckCooldown=0):this.lastTargetTpCheck=this.game.currentTick),t&&r&&(this.lastValidTargetPosition={tile:r.tile,onBridge:this.target.getBridge()}),t||(this.targetLinesConfig.isAttack=!1),s.attackState===yn.CheckRange){if(0<this.rangeCheckCooldown)return this.rangeCheckCooldown--,!1;let e=this.target.obj?t?this.target.obj:this.lastValidTargetPosition.tile:this.target.tile;var l=this.target.obj?t?this.target.obj.isBuilding()?this.target.obj.centerTile:this.target.obj.tile:this.lastValidTargetPosition.tile:this.target.tile;if(!this.rangeHelper.isInWeaponRange(i,e,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(i,e,this.weapon)||i.isUnit()&&i.rules.balloonHover&&!i.rules.hoverAttack&&!a&&i.tile!==l&&!this.options.holdGround||i.isAircraft()&&this.weapon.projectileRules.iniRot<=1&&!a){if(i.isUnit()&&!this.options.holdGround&&this.game.map.isWithinBounds(l)){if(a){if(a.target!==this.target.obj||t)if(t&&this.target.obj&&this.rangeHelper.tileDistance(this.target.obj,this.lastSelfMoveTargetTile)>this.weapon.range)a.retarget(this.target.obj,!!this.target.getBridge()),this.lastSelfTileBeforeMove=i.tile,this.lastSelfMoveTargetTile=this.target.obj?.tile??this.target.tile;else{if(void 0!==this.options.leashTiles&&this.rangeHelper.tileDistance(this.initialSelfPosition.tile,i.tile)>this.options.leashTiles)return a.cancel(),!0;var c=e instanceof Aa&&e.isUnit()?e.moveTrait.baseSpeed:0,u=Math.ceil((this.rangeHelper.tileDistance(i,e)-(this.weapon.range+1))/((i.moveTrait.baseSpeed+c)/ks.LEPTONS_PER_TILE));0<u&&(this.rangeCheckCooldown=Math.min(Fs.BASE_TICKS_PER_SECOND,u))}else{let e;e=void 0!==this.options.leashTiles?this.game.createTarget(this.initialSelfPosition.onBridge,this.initialSelfPosition.tile):this.game.createTarget(this.lastValidTargetPosition.onBridge,this.lastValidTargetPosition.tile),s.currentTarget=e,a.retarget(e.tile,e.isBridge()),this.updateTargetLines(e,!1)}return!1}if(!i.moveTrait||i.moveTrait.isDisabled())return!0;if(this.isCancelling())return!0;if(i.tile===this.lastSelfTileBeforeMove||this.moveExecuted&&i.moveTrait.lastMoveResult===qr.Fail?this.moveAttempts++:this.moveAttempts=0,this.weapon.rules.limboLaunch&&i.defaultToGuardArea&&r&&this.moveExecuted&&i.moveTrait.lastMoveResult===qr.Fail&&this.rangeHelper.isInRange(i,r,0,i.armedTrait.computeGuardScanRange(this.weapon),!0))return!0;if(3<this.moveAttempts)return!0;0<this.moveAttempts&&this.children.push(new pa(1/60));c=e,u=r&&!t?this.lastValidTargetPosition.onBridge:this.target.getBridge();return a=new ho(this.game,c,!!u,this.weapon),a.blocking=!1,this.children.push(a),this.moveExecuted=!0,this.lastSelfTileBeforeMove=i.tile,this.lastSelfMoveTargetTile=c instanceof Aa?c.tile:c,this.onTick(i)}return!0}if(this.moveExecuted=!1,this.moveAttempts=0,a&&(i.rules.balloonHover&&!i.rules.hoverAttack||i.rules.fighter||i.rules.spawned||i.rules.movementZone===si.Fly&&!this.rangeHelper.isInRange2(i,this.target.obj??this.target.tile,this.weapon.minRange,this.weapon.range-1)||a.cancel()),a&&(i.isInfantry()&&!i.rules.balloonHover||this.weapon.rules.spawner))return!1;if(a?.children.some(e=>!e.cancellable)&&this.weapon.rules.limboLaunch)return!1;if(a&&a.shouldAirStrafe(i)&&this.target.obj?.isUnit()&&this.target.obj.moveTrait.isMoving()&&1<this.weapon.range&&!this.rangeHelper.isInRange2(i,this.target.obj,this.weapon.minRange,this.weapon.range-1))return!1;s.attackState=yn.PrepareToFire}if(s.attackState!==yn.PrepareToFire)return!1;if(!t||s.isDisabled())return a?.cancel(),!0;u=this.target.getWorldCoords(),c=i.position.worldPosition;if(!(this.lastInRangeTargetPosition.length()&&this.lastInRangeTargetPosition.equals(u)&&this.lastInRangeSelfPosition.length()&&this.lastInRangeSelfPosition.equals(c)))return this.lastInRangeTargetPosition.copy(u),this.lastInRangeSelfPosition.copy(c),s.attackState=yn.CheckRange,this.onTick(i);if(!(this.weapon.rules.omniFire||i.rules.omniFire&&i.rules.fighter)){var c=(new ss).copy(u).sub(c),e=Tr.fromMapCoords(new Ss(c.x,c.z)),c=this.weapon.projectileRules.rot?45:11.25;if((i.isVehicle()||i.isBuilding())&&i.turretTrait){if(i.turretTrait.desiredFacing=e,Math.abs(e-i.turretTrait.facing)>=c)return!1}else if(Math.abs(e-i.direction)>=c){if(i.isAircraft())return i.direction=Tr.tick(i.direction,e,i.rules.rot).facing,!1;if(a)return!1;if(this.options.disallowTurning)return!0;if(i.isVehicle())return this.children.push(new br(e)),!1;i.direction=e}}if(!this.losHelper.hasLineOfSight(i,this.target.obj||this.target.tile,this.weapon))return s.attackState=yn.CheckRange,this.onTick(i);if(s.isOnCooldown(i))return!1;if(this.weapon.warhead.rules.temporal&&i.temporalTrait.getTarget()===this.target.obj)return!1;if(this.weapon.rules.suicide&&this.weapon.type!==oi.DeathWeapon)return this.game.destroyObject(i,{player:i.owner,obj:i,weapon:this.weapon}),!0;e=this.game.rules.general.prism.type;return i.isBuilding()&&i.name===e&&this.weapon.type!==oi.Secondary&&this.fireUpPrismSupportTowers(i,e),(i.isInfantry()||i.isVehicle())&&(i.isFiring=!0),i.art.fireUp?(this.children.push(new $s(i.art.fireUp).setCancellable(!1)),s.attackState=yn.FireUp,!1):(s.attackState=yn.Firing,this.onTick(i))}shouldDropTarget(e){return this.forceDropTarget||e?.isTechno()&&(this.weapon.rules.limboLaunch&&((e.isVehicle()||e.isAircraft())&&e.parasiteableTrait?.isInfested()||e.invulnerableTrait.isActive())||e.warpedOutTrait.isInvulnerable()&&!this.weapon.warhead.rules.temporal||this.initialTargetOwner!==e.owner)}fireUpPrismSupportTowers(t,i){var e;for(e of t.owner.getOwnedObjectsByType(Bt.Building).filter(e=>e.name===i&&e.secondaryWeapon&&!e.unitOrderTrait.hasTasks()&&e.attackTrait&&!e.attackTrait.isDisabled()&&!e.attackTrait.isOnCooldown(e)).filter(e=>this.rangeHelper.isInWeaponRange(e,t,e.secondaryWeapon,this.game.rules)).slice(0,this.game.rules.general.prism.supportMax))e.unitOrderTrait.addTask(e.attackTrait.createAttackTask(this.game,t,t.centerTile,e.secondaryWeapon,{passive:!0}))}countSupportBeamsAndFireDownTowers(t,i){var e,s=t.owner.getOwnedObjectsByType(Bt.Building).filter(e=>e.name===i&&e.attackTrait?.currentTarget?.obj===t);for(e of s)e.unitOrderTrait.getCurrentTask()?.cancel();return Math.min(this.game.rules.general.prism.supportMax,s.length)}getTargetLinesConfig(){return this.targetLinesConfig}}class go extends po{constructor(e,t,i){if(super(e,t,i),this.isAttackMove=!0,this.attackPerformed=!1,this.passedFirstWaypoint=!1,this.internalTargetUpdateRequested=!1,this.scanCooldownTicks=0,!t.obj?.isTechno())throw new Error("Target must be a techno object");this.initialTarget=t,this.initialWeapon=i,this.requestedTarget=t}duplicate(){return new go(this.game,this.initialTarget,this.initialWeapon)}requestTargetUpdate(e){this.internalTargetUpdateRequested?(this.requestedTarget=e,this.internalTargetUpdateRequested=!1):(this.requestedTarget===this.initialTarget?this.requestedTarget=e:this.attackPerformed=!0,this.initialTarget=e),super.requestTargetUpdate(e)}onTargetChange(e){super.onTargetChange(e);e=e.attackTrait.currentTarget;e&&e.obj!==this.initialTarget.obj&&e.obj!==this.requestedTarget.obj&&(this.requestedTarget===this.initialTarget&&(this.requestedTarget=e),this.initialTarget=e)}onTick(t){if(t.moveTrait.moveState===$r.Moving&&(this.passedFirstWaypoint=!0),this.scanCooldownTicks=Math.max(0,this.scanCooldownTicks-1),t.attackTrait&&!t.attackTrait.isDisabled()&&!this.isCancelling()&&(this.requestedTarget===this.initialTarget||this.attackPerformed)){if(!(t.moveTrait.isIdle()||t.tile===this.lastScanTile&&this.scanCooldownTicks)){this.lastScanTile=t.tile,this.scanCooldownTicks=this.game.rules.general.normalTargetingDelay;let e=t.attackTrait.selectDefaultWeapon(t);if(e&&(this.passedFirstWaypoint||!e.getCooldownTicks())){var i=t.attackTrait.scanForTarget(t,e,this.game);if(i.target){let{target:e,weapon:t}=i;if(!t.getCooldownTicks()){this.options.holdGround=!0,this.options.passive=!0,this.setWeapon(t);var s=this.game.createTarget(e,e.tile);return this.internalTargetUpdateRequested=!0,this.requestTargetUpdate(s),this.attackPerformed=!1}}}}if(this.attackPerformed){if(!t.isSpawned){if(!this.forceCancel(t))throw new Error("Force cancel failed");return!0}this.attackPerformed=!1,this.passedFirstWaypoint=!1,this.options.holdGround=!1,this.options.passive=!1,this.setWeapon(this.initialWeapon),this.internalTargetUpdateRequested=!0,this.requestTargetUpdate(this.initialTarget)}}s=super.onTick(t);return s&&this.requestedTarget!==this.initialTarget?(this.attackPerformed=!0,this.isCancelling()||t.attackTrait.isDisabled()):s}}class mo extends Sa{constructor(){super(...arguments),this.isAttackMove=!0,this.attackPerformed=!1,this.passedFirstWaypoint=!1}duplicate(){return new mo(this.game,this.targetTile,this.toBridge,this.options)}onTick(i){if(i.moveTrait.moveState===$r.Moving&&(this.passedFirstWaypoint=!0),i.moveTrait.moveState===$r.ReachedNextWaypoint&&i.attackTrait&&!i.attackTrait.isDisabled()&&(i.rules.movementZone!==si.Fly||!i.rules.balloonHover)&&!this.isCancelling()){let e=i.attackTrait.selectDefaultWeapon(i);if(e&&(this.passedFirstWaypoint||e&&!e.getCooldownTicks())){var s=i.attackTrait.scanForTarget(i,e,this.game);if(s.target){let{target:e,weapon:t}=s;if(!t.getCooldownTicks()){s=i.attackTrait.createAttackTask(this.game,e,e.tile,t,{holdGround:!0,passive:!0});return this.children.push(s),this.useChildTargetLines=!0,this.attackPerformed=!0,i.moveTrait.velocity.set(0,0,0),i.moveTrait.currentWaypoint=void 0,i.moveTrait.collisionState=Xr.Waiting,!1}}}if(this.attackPerformed){if(!i.isSpawned){if(!this.forceCancel(i))throw new Error("Force cancel failed");return!0}this.attackPerformed=!1,this.passedFirstWaypoint=!1,this.useChildTargetLines=!1,i.moveTrait.collisionState=Xr.Resolved,this.updateTarget(this.targetTile,this.toBridge)}}return super.onTick(i)}}class fo extends Sa{constructor(e,t,i,s){super(e,i,!1,{ignoredBlockers:[t],closeEnoughTiles:0,strictCloseEnough:!0,forceWaitOnPathBlocked:t.factoryTrait?.type!==Ji.InfantryType}),this.factory=t,this.rallyPoint=s,this.preventOpportunityFire=!0,this.rampBlockersPushed=!1,this.cancellable=!1}onStart(t){super.onStart(t),this.factory.factoryTrait?.type===Ji.UnitType&&(this.checkRampTiles=this.game.map.tileOccupation.calculateTilesForGameObject(this.factory.tile,this.factory).filter(e=>0<this.game.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)))}canStopAtTile(e,t,i){return!this.game.map.tileOccupation.isTileOccupiedBy(t,this.factory)&&super.canStopAtTile(e,t,i)}onTick(e){if(this.checkRampTiles){for(var t of this.checkRampTiles){var i,s;for(i of this.game.map.tileOccupation.getGroundObjectsOnTile(t))if(i.isUnit()){if(this.rampBlockersPushed)return!1;let e=new va(this.game,void 0,{excludedTiles:this.checkRampTiles});e.setCancellable(!1);let t=i.unitOrderTrait.getCurrentTask();t?t.constructor!==Sa&&t.constructor!==po&&t.constructor!==mo&&t.constructor!==go||(s=t.duplicate(),t.cancel(),i.unitOrderTrait.addTaskNext(s),i.unitOrderTrait.addTaskNext(e)):i.unitOrderTrait.addTask(e)}}if(!this.rampBlockersPushed)return!(this.rampBlockersPushed=!0);this.checkRampTiles=void 0}return e.moveTrait.moveState===$r.ReachedNextWaypoint&&this.options?.ignoredBlockers&&!this.game.map.terrain.isBlockerObject(this.factory,e.tile,!1,e.rules.speedType)&&(this.options.ignoredBlockers=void 0,this.preventOpportunityFire=!1,this.rallyPoint&&(this.updateTarget(this.rallyPoint.tile,!!this.rallyPoint.onBridge),this.cancellable=!0,this.options.closeEnoughTiles=this.game.rules.general.closeEnough,this.options.strictCloseEnough=!1,this.options.forceWaitOnPathBlocked=!1)),super.onTick(e)}}class yo{constructor(e,t,i,s,r,a=()=>!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=r,this.predicate=a,this.dirVec=new Ss(10,0),this.finished=!1,this.diagonal=!0,this.distance=s}getNextTile(){if(!this.finished){let t;do{let e={x:this.startTile.rx,y:this.startTile.ry};e.x+=this.distance*Math.sign(this.dirVec.x),e.y+=this.distance*Math.sign(this.dirVec.y),this.dirVec.rotateAround(new Ss,Math.PI/4*(this.diagonal?1:2)).round();var i=this.tiles.getByMapCoords(e.x,e.y);if(i&&this.mapBounds.isWithinBounds(i)&&this.predicate(i)&&(t=i),!this.dirVec.angle()){if(this.maxDistance&&this.distance>=this.maxDistance)return this.finished=!0,t;this.distance++}}while(!t);return t}}}(wn=wn||{}).onSell=Symbol();class wo{[Yr.onUnspawn](e){this.undock(e),this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[Zr.onChange](e){e.owner!==this.dock?.owner&&this.undock(e),e.owner!==this.reservedDock?.owner&&this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[Ur.onBeforeTeleport](e,t,i,s){s||this.undock(e)}undock(e){this.dock&&!this.dock.isDisposed&&this.dock.dockTrait.undockUnit(e)}dispose(){this.dock=void 0,this.reservedDock=void 0}}class To{constructor(e,t,i,s){this.building=e,this.tiles=t,this.numberOfDocks=i,this.dockingOffsets=s,this.ticksWhenWarpedOut=!0,this.unitsByDockNumber=new Array(i).fill(void 0),this.reservedDocks=new Array(i).fill(void 0)}[Qr.onSpawn](){this.dockTiles=[];for(let e=0;e<this.numberOfDocks;e++){var t=this.findDockTile(e);if(!t)throw new Error(`Docking tile ${e} not found for object "${this.building.name}"`);this.dockTiles[e]=t}}[Yr.onUnspawn](){for(let e=0;e<this.numberOfDocks;e++)this.unreserveDockAt(e)}[Lr.onTick](){for(let e=0;e<this.numberOfDocks;e++){var t=this.unitsByDockNumber[e];t&&t.tile!==this.getDockTile(e)&&this.undockUnit(t)}}[Wr.onDestroy](e,t,i,s){var r=(e.rules.unitRepair||e.helipadTrait)&&!e.rules.naval&&!i?.weapon?.warhead.rules.temporal;if(r)for(var a of this.unitsByDockNumber)a&&!a.isDestroyed&&(r?t.destroyObject(a,i,s):this.undockUnit(a))}[wn.onSell](s,r){if(s.helipadTrait&&this.hasDockedUnits()){var a,e,n;let t=[],i=0;for(a of[...s.owner.buildings].filter(e=>e.helipadTrait&&(e.dockTrait?.getAvailableDockCount()??!1)&&e!==s)){let e=a.dockTrait?.getAvailableDockCount()??0;for(;0<e&&i<this.unitsByDockNumber.length;)t.push(a),e--,i++;if(i===this.unitsByDockNumber.length)break}i=0;for(e of this.unitsByDockNumber)e&&((n=t[i])?e.unitOrderTrait.addTask(new ma(r,n)):e.unitOrderTrait.addTask(new ja(new Sa(r,e.tile,!1),new ga(e=>{e.crashableTrait?e.crashableTrait.crash({player:s.owner}):r.destroyObject(e,{player:s.owner})})).setCancellable(!1))),i++}else{var t,i=s.rules.unitRepair&&!s.rules.naval;for(t of this.unitsByDockNumber)t&&(i?r.sellTrait.sell(t):this.undockUnit(t))}}[Zr.onChange](e,t,i){for(var s of this.unitsByDockNumber)s&&i.changeObjectOwner(s,e.owner)}getFirstAvailableDockNumber(){if(!this.building?.warpedOutTrait.isActive()){var e=this.unitsByDockNumber.findIndex((e,t)=>!e&&!this.reservedDocks[t]);if(-1!==e)return e}}getAvailableDockCount(){return this.building?.warpedOutTrait.isActive()?0:this.unitsByDockNumber.filter((e,t)=>!e&&!this.reservedDocks[t]).length}getFirstEmptyDockNumber(){if(!this.building?.warpedOutTrait.isActive()){var e=this.unitsByDockNumber.findIndex(e=>!e);if(-1!==e)return e}}getDockOffset(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);return this.dockingOffsets[e]}getDockTile(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);return this.dockTiles[e]}getDockNumberByTile(e){e=this.dockTiles.indexOf(e);if(-1!==e)return e}getAllDockTiles(){return[...this.dockTiles]}findDockTile(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);var t=this.building.position.getMapPosition(),e=this.getDockOffset(e);return this.tiles.getByMapCoords(Math.floor((t.x+e.x)/ks.LEPTONS_PER_TILE),Math.floor((t.y+e.z)/ks.LEPTONS_PER_TILE))}isValidUnitForDock(e){return(this.building.unitRepairTrait&&e.isVehicle()&&!this.building.helipadTrait&&(!e.rules.consideredAircraft||e.rules.landable)||e.rules.dock.includes(this.building.name)&&!(e.isAircraft()&&!this.building.helipadTrait))&&this.building.rules.naval===e.rules.naval}dockUnitAt(e,t){if(t>this.numberOfDocks-1)throw new RangeError(`Index ${t} exceeds available docks (${this.numberOfDocks})`);if(this.unitsByDockNumber[t])throw new Error(`Another unit is already docked at dock #${t}`);let i=e.traits.find(wo);if(!i)throw new Error(`Unit "${e.name}" cannot be docked to ${this.building.name}`);this.unitsByDockNumber[t]=e,i.dock=this.building}undockUnitAt(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);let t=this.unitsByDockNumber[e];t&&(this.unitsByDockNumber[e]=void 0,t.traits.get(wo).dock=void 0)}undockUnit(e){e=this.unitsByDockNumber.indexOf(e);-1!==e&&this.undockUnitAt(e)}isDocked(e){return this.unitsByDockNumber.includes(e)}hasDockedUnits(){return!!this.unitsByDockNumber.find(e=>e)}getDockedUnits(){return this.unitsByDockNumber.filter(Fa)}reserveDockAt(e,t){if(t>this.numberOfDocks-1)throw new RangeError(`Index ${t} exceeds available docks (${this.numberOfDocks})`);if(this.reservedDocks[t])throw new Error(`Dock #${t} is already reserved by ${this.reservedDocks[t].name}`);(this.reservedDocks[t]=e).traits.get(wo).reservedDock?.dockTrait.unreserveDockForUnit(e),e.traits.get(wo).reservedDock=this.building}unreserveDockAt(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);let t=this.reservedDocks[e];t&&(this.reservedDocks[e]=void 0,t.traits.get(wo).reservedDock=void 0)}unreserveDockForUnit(e){e=this.reservedDocks.indexOf(e);-1!==e&&this.unreserveDockAt(e)}hasReservedDockForUnit(e){return!!this.reservedDocks.includes(e)}hasReservedDockAt(e){return!!this.reservedDocks[e]}getReservedDockForUnit(e){e=this.reservedDocks.indexOf(e);if(-1!==e)return e}dispose(){this.building=void 0}}class bo{constructor(e){this.target=e,this.type=is.FactoryProduceUnit}}(r=Tn=Tn||{})[r.All=0]="All",r[r.Ground=1]="Ground",r[r.Air=2]="Air";class vo{constructor(e){this.tiles=e,this.tileOccupation=[],this.emptyTiles=new Set,this._onChange=new ro;let t=this.tileOccupation;for(var i of e.getAll())t[i.rx]=t[i.rx]||[],t[i.rx][i.ry]=new Set,this.emptyTiles.add(i)}get onChange(){return this._onChange.asEvent()}occupyTileRange(e,t){let i=this.calculateTilesForGameObject(e,t);i.forEach(e=>this.occupyTile(e,t)),this._onChange.dispatch(this,{tiles:i,object:t,type:"added"})}unoccupyTileRange(e,t){let i=this.calculateTilesForGameObject(e,t);i.forEach(e=>this.unoccupyTile(e,t)),this._onChange.dispatch(this,{tiles:i,object:t,type:"removed"})}occupySingleTile(e,t){this.occupyTile(e,t),this._onChange.dispatch(this,{tiles:[e],object:t,type:"added"})}unoccupySingleTile(e,t){this.unoccupyTile(e,t),this._onChange.dispatch(this,{tiles:[e],object:t,type:"removed"})}calculateTilesForGameObject(e,t){return this.tiles.getInRectangle(e,t.getFoundation())}occupyTile(e,t){let i=this.tileOccupation[e.rx]?.[e.ry];i&&(i.add(t),this.emptyTiles.delete(e),e.landType=this.computeTileLandType(e),e.onBridgeLandType=this.computeOnBridgeLandType(e))}unoccupyTile(e,t){let i=this.tileOccupation[e.rx]?.[e.ry];i&&(i.delete(t),i.size||this.emptyTiles.add(e),e.landType=this.computeTileLandType(e),e.onBridgeLandType=this.computeOnBridgeLandType(e))}isTileOccupiedBy(e,t){return!!this.tileOccupation[e.rx]?.[e.ry]?.has(t)}computeTileLandType(e){if(e.landType===Kt.Rock)return Kt.Rock;var t,i=Hi(e.terrainType);for(t of this.tileOccupation[e.rx]?.[e.ry]??[]){if((t.isOverlay()||t.isBuilding())&&t.rules.wall)return Kt.Wall;if(t.isOverlay()&&t.isTiberium())return Kt.Tiberium;if(t.isOverlay()&&t.rules.land!==Kt.Clear&&!t.isBridge()&&!t.isBridgePlaceholder())return t.rules.land}return i}computeOnBridgeLandType(e){for(var t of this.tileOccupation[e.rx]?.[e.ry]??[])if(t.isOverlay()&&t.isBridge())return t.isHighBridge()?Kt.Road:t.rules.land}getTileZone(e,t=!1){return Os(t?e.landType:e.onBridgeLandType??e.landType)}getBridgeOnTile(e){for(var t of this.tileOccupation[e.rx]?.[e.ry]??[])if(t.isOverlay()&&t.isBridge())return t}getObjectsOnTile(e){return[...this.tileOccupation[e.rx]?.[e.ry]??[]]}getGroundObjectsOnTile(e){let t=[];for(var i of this.tileOccupation[e.rx]?.[e.ry]??[])i.isTechno()&&!i.isBuilding()&&i.zone===bs.Air||t.push(i);return t}getAirObjectsOnTile(e){let t=[];for(var i of this.tileOccupation[e.rx]?.[e.ry]??[])i.isUnit()&&i.zone===bs.Air&&t.push(i);return t}getObjectsOnTileByLayer(e,t){if(t===Tn.Ground)return this.getGroundObjectsOnTile(e);if(t===Tn.Air)return this.getAirObjectsOnTile(e);if(t===Tn.All)return this.getObjectsOnTile(e);throw new Error(`Unhandled layer type "${t}"`)}getEmptyTiles(){return[...this.emptyTiles]}}(bn=bn||{}).onChange=Symbol(),(vn=vn||{}).onProduce=Symbol(),(r=Sn=Sn||{})[r.Idle=0]="Idle",r[r.Delivering=1]="Delivering";class So{constructor(e,t=!1){this.type=e,this.isCloningVats=t,this.status=Sn.Idle}[Qr.onSpawn](e,t){this.resetRallyPoint(e,t)}resetRallyPoint(e,t){var i;[Ji.BuildingType,Ji.AircraftType].includes(this.type)||(i=this.computeDefaultRallyPoint(e,this.type,t.map),e.rallyTrait?.changeRallyPoint(i,e,t))}[bn.onChange](t,e,i){if(t.owner.production){let e=[];e=this.type===Ji.BuildingType?[mn.Structures,mn.Armory]:[t.owner.production.getQueueTypeForFactory(this.type)];for(var s of e)t.owner.production.getQueue(s).notifyUpdated()}}[Lr.onTick](i,s){if(this.status===Sn.Delivering){if(!this.deliveringUnit||this.deliveringUnit.isDestroyed){if(this.buildingProductionTicks=this.buildingProductionTicks??1,0<this.buildingProductionTicks--)return;this.buildingProductionTicks=void 0}else if(s.map.tileOccupation.isTileOccupiedBy(this.deliveringUnit.tile,i)){if(!this.deliveringUnit.rules.consideredAircraft)return;if(this.deliveringUnit.position.tileElevation<i.art.height)return}return this.status=Sn.Idle,void(this.deliveringUnit=void 0)}if(i.owner.production&&!i.warpedOutTrait.isActive()){let e=i.owner.production.getPrimaryFactory(this.type);if((e?.warpedOutTrait.isActive()||e===i||e?.factoryTrait?.deliveringUnit&&e.factoryTrait.type===Ji.UnitType)&&this.type!==Ji.BuildingType){let e=i.owner.production.getQueueForFactory(this.type);if(e&&e.status===fn.Ready){let t=e.getFirst();if(this.type===Ji.AircraftType){let e=this.produceAircraftAt(i,t,s);var r;if(!e)for(r of[...i.owner.buildings].filter(e=>e.factoryTrait?.type===Ji.AircraftType&&e.helipadTrait)){if(e)break;e=this.produceAircraftAt(r,t,s)}if(!e)return}else if(this.produceGroundUnitAt(i,t,s),!this.isCloningVats&&this.type===Ji.InfantryType){let e=[...i.owner.buildings].find(e=>e.factoryTrait&&e.rules.cloning);e?.factoryTrait.status===Sn.Idle&&e?.factoryTrait.produceGroundUnitAt(e,t,s)}i.owner.addUnitsBuilt(t.rules.type,1),t.creditsSpent=0,t.progress=0,e.shift(t.rules,1),e.currentSize&&(e.status=fn.Active)}}}}produceGroundUnitAt(e,t,i){let s=i.createUnitForPlayer(t.rules,e.owner);t.rules.trainable&&e.owner.canProduceVeteran(s.rules)&&s.veteranTrait?.setVeteranLevel(Jr.Veteran),s.isInfantry()&&(s.position.subCell=Da.SUB_CELLS[0]);let r=this.computeInternalRallyPoint(e,this.type,e.rallyTrait.getRallyPoint(),i.map);this.type!==Ji.UnitType&&(r=e.rallyTrait.findRallyPointforUnit(s,r,i.map,!1,e.tile.z));let a;var n;a=this.type===Ji.NavalUnitType?r:(n=this.computeExitCoords(e,this.type),i.map.tiles.getByMapCoords(Math.floor(n.rx),Math.floor(n.ry))),s.rules.consideredAircraft&&(r=a);let o;if(e.rallyTrait.getRallyPoint()!==r&&(o=e.rallyTrait.findRallyNodeForUnit(s,i.map)),s.isInfantry()){let t=i.map.tileOccupation.getObjectsOnTileByLayer(o?.tile??r,s.rules.consideredAircraft?Tn.Air:Tn.Ground).filter(e=>e.isInfantry()&&e.moveTrait.moveState!==$r.Moving).map(e=>e.position.subCell);s.position.subCell=Da.SUB_CELLS.find(e=>!t.includes(e))??Da.SUB_CELLS[0]}s.direction=270,i.spawnObject(s,a),i.traits.filter(vn).forEach(e=>{e[vn.onProduce](s,i)}),i.events.dispatch(new bo(s)),s.rules.consideredAircraft?(n=o??{tile:r,onBridge:void 0},s.unitOrderTrait.addTask(new Sa(i,n.tile,!!n.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))):s.unitOrderTrait.addTask(new fo(i,e,r,o)),this.status=Sn.Delivering,this.deliveringUnit=s}produceAircraftAt(e,t,i){let s=e.traits.find(To);if(!s)return!1;var r=s.getFirstAvailableDockNumber();if(void 0===r)return!1;let a=i.createUnitForPlayer(t.rules,e.owner);t.rules.trainable&&e.owner.canProduceVeteran(a.rules)&&a.veteranTrait?.setVeteranLevel(Jr.Veteran);t=s.getDockOffset(r);return a.position.moveToLeptons(e.position.getMapPosition()),a.position.moveByLeptons3(t),i.spawnObject(a,a.position.tile),s.dockUnitAt(a,r),a.isAircraft()&&a.airportBoundTrait&&(a.airportBoundTrait.preferredAirport=e),i.traits.filter(vn).forEach(e=>{e[vn.onProduce](a,i)}),i.events.dispatch(new bo(a)),!0}computeExitCoords(e,t){if(t===Ji.InfantryType)return this.computeBarracksDefaultExitCoords(e);if(t===Ji.UnitType)return this.computeWarFactoryExitCoords(e);throw new Error(`Unsupported factory type ${Ji[t]}`)}computeInternalRallyPoint(e,t,i,s){let r,a;if(t===Ji.NavalUnitType)a=this.computeNavalInternalRallyPoint(e,i,s);else{if(t===Ji.InfantryType)r=this.computeBarracksInternalRallyCoords(e);else{if(t!==Ji.UnitType)throw new Error(`Unsupported factory type ${Ji[t]}`);r=this.computeWarFactoryInternalRallyCoords(e)}a=s.tiles.getByMapCoords(r.rx,r.ry)}return a??this.findTileAdjacentToBuilding(e,s)}computeDefaultRallyPoint(e,t,i){let s,r;if(t===Ji.NavalUnitType)r=this.computeNavalDefaultRallyPoint(e,i);else{if(t===Ji.InfantryType)s=this.computeBarracksInternalRallyCoords(e);else{if(t!==Ji.UnitType)throw new Error(`Unsupported factory type ${Ji[t]}`);s=this.computeWarFactoryDefaultRallyCoords(e)}r=i.tiles.getByMapCoords(s.rx,s.ry)}return r??this.findTileAdjacentToBuilding(e,i)}findTileAdjacentToBuilding(e,t){return new js(t.tiles,t.mapBounds,e.tile,e.getFoundation(),1,1,()=>!0).getNextTile()}computeBarracksDefaultExitCoords(e){var t=e.getFoundation();let i,s;return t.width<=2||t.height<=2?(i=t.width-1,s=t.height-1,e.rules.gdiBarracks&&2<t.width&&(i=Math.floor(t.width/2))):(i=0,s=t.height-1),{rx:e.tile.rx+i,ry:e.tile.ry+s}}computeBarracksInternalRallyCoords(e){var t=e.getFoundation();let{rx:i,ry:s}=this.computeBarracksDefaultExitCoords(e);return!(t.width<=2||t.height<=2)||e.rules.gdiBarracks?s+=1:e.rules.nodBarracks&&(i+=t.width<=2?1:0,s+=t.height<=2?1:0),{rx:i,ry:s}}computeWarFactoryExitCoords(e){var t=e.getFoundation();return{rx:e.tile.rx+Math.floor(t.width/2),ry:e.tile.ry+Math.floor(t.height/2)}}computeWarFactoryInternalRallyCoords(e){var t=e.getFoundation();return{rx:e.tile.rx+t.width-1,ry:e.tile.ry+Math.floor(t.height/2)}}computeWarFactoryDefaultRallyCoords(e){var t=e.getFoundation();return{rx:e.tile.rx+t.width,ry:e.tile.ry+Math.floor(t.height/2)}}computeNavalDefaultRallyPoint(e,t){let i=new yo(t.tiles,t.mapBounds,e.centerTile,5,5,e=>e.terrainType===Yt.Water&&!t.getObjectsOnTile(e).find(e=>e.isBuilding()||e.isOverlay()&&e.isBridge()));return i.diagonal=!1,i.getNextTile()??t.tiles.getByMapCoords(e.tile.rx+e.getFoundation().width,e.tile.ry+e.getFoundation().height)}computeNavalInternalRallyPoint(e,t,i){t=new Ss(t.rx,t.ry).sub(new Ss(e.centerTile.rx,e.centerTile.ry));return i.tiles.getByMapCoords(e.centerTile.rx+Math.sign(t.x)*(Math.floor(e.getFoundation().width/2)+1),e.centerTile.ry+Math.sign(t.y)*(Math.floor(e.getFoundation().height/2)+1))}}class ko{constructor(e,t,i,s,r,a,n,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.foundation=s,this.maxDistance=a,this.predicate=n,this.checkBounds=o,this.distance=r,this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){var s=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t))return t};do{var r=this.startTile.rx-this.distance,a=this.startTile.ry-this.distance,n=this.startTile.rx+this.foundation.width-1+this.distance,o=this.startTile.ry+this.foundation.height-1+this.distance;let e,t,i;if(0<this.distance){for(t=1+a;t<o;t++)i=s(r,t),i&&(yield i);for(e=r;e<n;e++)i=s(e,a),i&&(yield i);for(t=o-1;t>=a;t--)i=s(n,t),i&&(yield i);for(e=n;e>=r;e--)i=s(e,o),i&&(yield i)}else this.predicate(this.startTile)&&(yield this.startTile)}while(this.distance++,this.distance<=this.maxDistance)}}class Oo{[Qr.onSpawn](r,a){if(!r.owner.isNeutral){let e;if(a.rules.hasObject(r.rules.freeUnit,Bt.Vehicle))e=a.rules.getObject(r.rules.freeUnit,Bt.Vehicle);else{if(!a.rules.hasObject(r.rules.freeUnit,Bt.Infantry))return void console.warn(`Free unit "${r.rules.freeUnit}" is not a vehicle or infantry type.`);e=a.rules.getObject(r.rules.freeUnit,Bt.Infantry)}let i=a.createUnitForPlayer(e,r.owner),s;var t=new ko(a.map.tiles,a.map.mapBounds,r.tile,r.getFoundation(),1,1,e=>{var t=0<a.map.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&Math.abs(e.z-r.tile.z)<2&&!a.map.terrain.findObstacles({tile:e,onBridge:void 0},i).length;return!s&&t&&(s=e),t&&!a.map.getObjectsOnTile(e).find(e=>e.isOverlay())}).getNextTile()??s;if(!t)return r.owner.removeOwnedObject(i),i.dispose(),void(r.owner.credits+=i.purchaseValue);a.spawnObject(i,t)}}}class _o{[wn.onSell](e,t){this.spawnSurvivors(e,t)}[Wr.onDestroy](e,t,i,s){s||i?.obj===e&&i.weapon?.rules.suicide||e.isVehicle()&&e.moveTrait.isMoving()||e.crashableTrait||this.spawnSurvivors(e,t)}spawnSurvivors(s,r){var e=r.rules.general.crew,t=s.owner.country.side;let i,a;if(t===Xt.GDI)i=e.alliedSurvivorDivisor,a=e.alliedCrew;else{if(t!==Xt.Nod)return;i=e.sovietSurvivorDivisor,a=e.sovietCrew}let n=r.sellTrait.computeRefundValue(s)/i;n=0<n&&n<1?1:Math.floor(n),n=s.isVehicle()?Math.min(1,n):Math.min(5,n);let o=[];for(let e=0;e<n;e++)o.push(a);if(0<o.length){s.rules.constructionYard&&(o[o.length-1]=r.rules.general.engineer);var h,l=r.map.tiles.getInRectangle(s.tile,s.getFoundation()).filter(e=>r.map.isWithinBounds(e));let i=[...l];for(h of o){var c=r.rules.getObject(h,Bt.Infantry);if(r.map.terrain.getPassableSpeed(s.tile,c.speedType,!s.isBuilding()&&s.onBridge,void 0,!0)){let e=r.createUnitForPlayer(c,s.owner),t=i.length?i.splice(r.generateRandomInt(0,i.length-1),1)[0]:void 0;t=t||l[r.generateRandomInt(0,l.length-1)],e.isInfantry()&&(e.position.subCell=Da.SUB_CELLS[0]),e.veteranTrait&&s.owner.canProduceVeteran(e.rules)&&e.veteranTrait.setVeteranLevel(Jr.Veteran),r.spawnObject(e,t),s.isBuilding()&&e.unitOrderTrait.addTask(new va(r,void 0,{ignoredBlockers:s.isDestroyed?void 0:[s]}))}}}}}class Io{constructor(e,t){this.gameObject=e,this.bridges=t,this.checkedClosestBridge=!1}canRepairBridge(){var e=this.findClosestBridgeBounds();return e?this.bridges.canBeRepaired(e):(console.warn(`No bridge associated with hut at ${this.gameObject.tile.rx}, ${this.gameObject.tile.ry}.`),!1)}repairBridge(t,i){var s=this.findClosestBridgeBounds();if(!s)throw new Error("No bridge bounds found");var e=this.bridges.findDestroyedPieceTiles(s),r=s.start.rx!==s.end.rx;let a;a=s.isHigh?Va.calculateHighBridgeOverlayId(s.type,r):Va.calculateLowBridgeOverlayId(s.type,r);var n,o,h=t.rules.getOverlayName(a);for(n of e){let e=t.createObject(Bt.Overlay,h);e.overlayId=a,e.value=0,e.position.tileElevation=s.isHigh?4:0,t.spawnObject(e,n),this.updateUnitsUnderBridgePiece(n,s,t,i)}for(o of this.bridges.findBridgePieces(s))o.obj.bridgeTrait.bridgeSpec=s}updateUnitsUnderBridgePiece(e,i,s,r){var a;for(let t of this.bridges.getPieceTiles(this.bridges.getPieceAtTile(e)))if(i.isHigh){let e=s.map.getGroundObjectsOnTile(t).filter(e=>e.tile===t&&e.isUnit()&&!e.unitOrderTrait.hasTasks()&&e.rules.tooBigToFitUnderBridge);e.forEach(e=>e.unitOrderTrait.addTask(new va(s)))}else for(a of s.map.getGroundObjectsOnTile(t))a.isUnit()&&(s.map.terrain.getPassableSpeed(t,a.rules.speedType,!0)?(a.zone=bs.Ground,a.onBridge=!0):a.isDestroyed||s.destroyObject(a,{player:r}))}demolishBridge(e,t){var i=this.getBridgePieces();if(i)for(var s of i)s.obj.isLowBridge()&&e.map.getTileZone(s.obj.tile,!0)!==bs.Water||s.obj.isDestroyed||(s.obj.deathType=zr.Demolish,e.destroyObject(s.obj,t,!0))}getBridgePieces(){var e=this.findClosestBridgeBounds();if(e)return this.bridges.findBridgePieces(e)}findClosestBridgeBounds(){return this.checkedClosestBridge||(this.checkedClosestBridge=!0,this.closestBridge=this.bridges.findClosestBridgeSpec(this.gameObject.tile)),this.closestBridge}dispose(){this.gameObject=void 0}}class Co{constructor(){this.isActive=!1,this.produceCashCooldown=0}[Qr.onSpawn](e){e.owner.isNeutral||(this.isActive=!0)}[Zr.onChange](e,t){t.isNeutral&&!e.owner.isNeutral&&(e.owner.credits=Math.max(0,e.owner.credits+e.rules.produceCashStartup),this.isActive=!0,this.produceCashCooldown=e.rules.produceCashDelay)}[Lr.onTick](e){this.isActive&&(this.produceCashCooldown--,this.produceCashCooldown<=0&&(this.produceCashCooldown=e.rules.produceCashDelay,e.owner.credits=Math.max(0,e.owner.credits+e.rules.produceCashAmount)))}}class Ao{constructor(){this.linkedDamageHandled=!1}[ca.onDamage](e,t,i,s){if(!this.linkedDamageHandled){var r=Math.floor(i/2);if(r)for(var a of t.map.tiles.getAllNeighbourTiles(e.tile))if(a.landType===Kt.Wall){let e=t.map.getObjectsOnTile(a).find(e=>(e.isBuilding()||e.isOverlay())&&e.wallTrait);e.wallTrait.linkedDamageHandled=!0,e.healthTrait.inflictDamage(r,s,t),e.wallTrait.linkedDamageHandled=!1,e.healthTrait.health||t.destroyObject(e,s)}}}}class Bo{constructor(e){this.obj=e,this.chargers=new Set}isOverpowered(){let e=1;return this.obj?.poweredTrait?.isPoweredOn(!0)||(e+=2),this.chargers.size>=e}hasChargersToPowerOn(){return 2<=this.chargers.size}chargeFrom(e){this.chargers.add(e),this.swapAttackTaskWeapon()}[Lr.onTick](i){if(0<this.chargers.size){let t=!1;this.chargers.forEach(e=>{(e.isDestroyed||e.isCrashing||e.owner!==i.owner||e.attackTrait?.currentTarget?.obj!==i)&&(this.chargers.delete(e),t=!0)}),t&&this.swapAttackTaskWeapon()}}swapAttackTaskWeapon(){let e=this.obj?.unitOrderTrait.getCurrentTask();var t;e instanceof po&&((t=this.getWeapon())?e.setWeapon(t):e.cancel())}getWeapon(){return this.isOverpowered()?this.obj?.secondaryWeapon:this.obj?.primaryWeapon}dispose(){this.obj=void 0,this.chargers.clear()}}class xo{constructor(e,t){this.target=e,this.from=t,this.type=is.UnitRepairFinish}}class Eo{constructor(e){this.target=e,this.type=is.UnitRepairStart}}(r=kn=kn||{})[r.Idle=0]="Idle",r[r.Repairing=1]="Repairing";class Po{constructor(){this.status=kn.Idle,this.cooldownTicks=0,this.lastRepairTickSuccessful=!1}[Qr.onSpawn](e,t){this.resetRallyPoint(e,t)}resetRallyPoint(e,t){var i;e.factoryTrait||(i=this.computeDefaultRallyPoint(e,t.map),e.rallyTrait.changeRallyPoint(i,e,t))}[Lr.onTick](t,i){if(t.dockTrait&&(!t.rules.needsEngineer||!t.owner.isNeutral))if(!t.dockTrait.hasDockedUnits()||t.dockTrait.getDockedUnits().some(e=>e.zone===bs.Air)||t.poweredTrait&&!t.poweredTrait.isPoweredOn())this.status=kn.Idle;else if(this.cooldownTicks<=0){var s,r,a=i.rules.general.repair,a=t.rules.unitReload?a.reloadRate:a.uRepairRate;this.cooldownTicks+=Fs.BASE_TICKS_PER_SECOND*a*60;let e=!1;for(s of t.dockTrait.getDockedUnits())s.zone!==bs.Air&&(s.healthTrait.health<100&&i.areFriendly(s,t)?(this.tickRepair(s,i,t)&&(e=!0),!e||this.status!==kn.Idle&&this.lastRepairTickSuccessful||t.helipadTrait||i.events.dispatch(new Eo(s))):((r=t.rallyTrait.findRallyNodeForUnit(s,i.map))&&(t.dockTrait.undockUnit(s),s.unitOrderTrait.addTask(new Sa(i,r.tile,!!r.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))),t.helipadTrait||i.events.dispatch(new xo(s,t))));this.lastRepairTickSuccessful=e,this.status=e?kn.Repairing:kn.Idle}else this.cooldownTicks--}tickRepair(e,t,i){var s=t.rules.general.repair,r=Math.floor(s.repairStep),a=s.repairPercent;let n;if(a){s=a*e.purchaseValue/e.healthTrait.maxHitPoints,a=Math.min(i.owner.credits,Math.max(1,Math.floor(s*r)));if(n=s&&a?Math.floor(a/s):r,!a)return!1;i.owner.credits-=a}else n=r;return n=Math.min(n,e.healthTrait.maxHitPoints-e.healthTrait.getHitPoints()),!!n&&(e.healthTrait.healBy(n,i,t),!0)}computeDefaultRallyPoint(e,t){var i=e.getFoundation(),i=new Ss(e.tile.rx,e.tile.ry+i.height);return t.tiles.getByMapCoords(i.x,i.y)??e.tile}}class No{getRallyPoint(){return this.rallyPoint}changeRallyPoint(e,t,i){i=this.findValidRallyPoint(t,e,i.map);i&&(this.rallyPoint=i)}findValidRallyPoint(i,e,s){let t=new js(s.tiles,s.mapBounds,e,{width:1,height:1},0,20,e=>i.rules.naval===(e.terrainType===Yt.Water)&&!s.tileOccupation.isTileOccupiedBy(e,i)),r=t.getNextTile();if(!r&&i.factoryTrait?.type===Ji.NavalUnitType){var{width:a,height:n}=i.getFoundation();for(let t=0;t<a;t++)for(let e=0;e<n;e++){var o=s.tiles.getByMapCoords(i.tile.rx+t,i.tile.ry+e);if(!o)break;if(0<s.terrain.getPassableSpeed(o,Jt.Float,!1)){r=o;break}}}return r}findRallyNodeForUnit(e,t){if(this.rallyPoint){var i=this.findRallyPointforUnit(e,this.rallyPoint,t,!0);return{tile:i,onBridge:e.rules.naval?void 0:t.tileOccupation.getBridgeOnTile(i)}}}findRallyPointforUnit(i,e,s,r,a){let n=i.rules.naval?void 0:s.tileOccupation.getBridgeOnTile(e),o=i.rules.movementZone===si.Fly,t=new js(s.tiles,s.mapBounds,e,{width:1,height:1},0,5,e=>{var t=!n||n.isHighBridge()?s.tileOccupation.getBridgeOnTile(e):void 0;return!(o?[]:s.terrain.findObstacles({tile:e,onBridge:t},i)).length&&(void 0===a||Math.abs(a-(e.z+(t?.tileElevation??0)))<4)&&(!r||!s.getObjectsOnTile(e).find(e=>e.isBuilding()&&!e.isDestroyed))&&(o||0<s.terrain.getPassableSpeed(e,i.rules.speedType,!!t))});return t.getNextTile()??e}}class Mo{constructor(){this.activeTicks=0}isActive(){return 0<this.activeTicks}setActiveFor(e,t){this.activeTicks=e,this.activeFor=e,this.activeSince=t}reset(){this.activeTicks=0,this.activeSince=void 0,this.activeFor=void 0}getTicksLeft(){return this.activeTicks}getInitialTicks(){return this.activeFor??0}tick(e){return 0<this.activeTicks&&(this.activeTicks--,this.activeTicks<=0||void 0!==this.activeSince&&e-this.activeSince>this.activeFor)&&(this.reset(),!0)}}class Do{constructor(){this.timer=new Mo}hasCharge(){return this.timer.isActive()}setCharge(e,t){this.hasCharge()||(this.timer.setActiveFor(e),this.attackerInfo=t)}[Lr.onTick](e,t){this.timer.isActive()&&!0===this.timer.tick(t.currentTick)&&(e.invulnerableTrait.isActive()||(e.isBuilding()&&e.cabHutTrait?e.cabHutTrait.demolishBridge(t,this.attackerInfo):(e.deathType=zr.Demolish,t.destroyObject(e,this.attackerInfo,!0))))}}class Ro{[Zr.onChange](e,t,i){this.checkAircraftsForPlayer(t,i)}[Yr.onUnspawn](e,t){this.checkAircraftsForPlayer(e.owner,t)}checkAircraftsForPlayer(e,t){let i=t.rules.general.padAircraft;var s;for(s of e.getOwnedObjectsByType(Bt.Aircraft).filter(e=>i.includes(e.name)))s.airportBoundTrait&&(s.airportBoundTrait.preferredAirport=void 0)}}class Lo{[Lr.onTick](t,i){if(t.dockTrait&&t.dockTrait.hasDockedUnits()&&!t.dockTrait.getDockedUnits().every(e=>!this.canReloadUnit(e)))if(void 0===this.cooldownTicks&&(this.cooldownTicks=Fs.BASE_TICKS_PER_SECOND*i.rules.general.repair.reloadRate*60),this.cooldownTicks<=0){this.cooldownTicks=Fs.BASE_TICKS_PER_SECOND*i.rules.general.repair.reloadRate*60;let e=t.dockTrait.getDockedUnits();var s;for(s of 0===e[0].ammo?e.slice(0,1):e)this.canReloadUnit(s)&&s.ammoTrait.ammo++}else this.cooldownTicks--}canReloadUnit(e){return!(!e.ammoTrait||!e.rules.manualReload||e.ammoTrait.isFull()||e.zone===bs.Air)}}class Fo extends ja{constructor(e){super(new pa(e),new ga(e=>e.buildStatus=In.Ready)),this.cancellable=!1}}class jo{constructor(e){this.name=e}getSuperWeapon(e){return e.owner.superWeaponsTrait?.get(this.name)}[Qr.onSpawn](e,t){this.addSuperWeaponToPlayerIfNeeded(e.owner,t)}[Yr.onUnspawn](e,t){this.removeSuperWeaponFromPlayerIfNeeded(e.owner)}[Zr.onChange](e,t,i){this.removeSuperWeaponFromPlayerIfNeeded(t),this.addSuperWeaponToPlayerIfNeeded(e.owner,i)}addSuperWeaponToPlayerIfNeeded(t,i){if(t.superWeaponsTrait&&!t.superWeaponsTrait.has(this.name)){let e=i.createSuperWeapon(this.name,t);t.superWeaponsTrait.add(e),e.rules.isPowered&&t.powerTrait?.isLowPower()&&e.pauseTimer()}}removeSuperWeaponFromPlayerIfNeeded(e){let t=e.superWeaponsTrait;t&&(e.getOwnedObjectsByType(Bt.Building).some(e=>e.superWeaponTrait?.name===this.name)||(e=t.get(this.name))&&!e.isGift&&t.remove(this.name))}}(r=On=On||{})[r.Unexplored=0]="Unexplored",r[r.TemporaryReveal=1]="TemporaryReveal",r[r.Explored=2]="Explored",_n=_n||{},_n[_n.Darken=8]="Darken";class Uo{constructor(){this.invalidations=new Map,this.temporaryReveals=new Map,this.fullInvalidation=!1,this._onChange=new ro}get onChange(){return this._onChange.asEvent()}fromTiles(e){var t,i=e.getMapSize(),s=e.getMaxTileHeight(),s=this.padding=(s+s%2)/2;this.size={width:i.width+s,height:i.height+s},this.tiles=new Uint8Array(this.size.width*this.size.height),this.tiles.fill(On.Unexplored),this.tileElevation=new Uint8Array(this.size.width*this.size.height);for(t of e.getAll()){var r=this.getTileIndex(t);this.tileElevation[r]=Math.max(this.tileElevation[r],t.terrainType===Yt.Cliff&&0<t.z?t.z-1:t.z)}return this}getSize(){return this.size}getTileIndex(e){var{sx:t,sy:e}=this.rxyzToSxy(e.rx,e.ry,e.z);return t+e*this.size.width}rxyzToSxy(e,t,i){i=(i|=0)+i%2;return{sx:e-i/2+this.padding,sy:t-i/2+this.padding}}sxyzToRxy(e,t,i){return{rx:e+Math.ceil(i/2)-this.padding,ry:t+Math.ceil(i/2)-this.padding}}shroudCoordsToWorld({sx:e,sy:t}){return this.sxyzToRxy(e,t,0)}findTilesAtShroudCoords({sx:t,sy:i},s){var e=s.getMaxTileHeight(),r=e+e%2;let a=[];for(let e=0;e<=r;e+=2){var n=e+e%2,{rx:o,ry:n}=this.sxyzToRxy(t,i,n),n=s.getByMapCoords(o,n);n?.z===e&&a.push(n)}return a}clone(){let e=new Uo;return e.tiles=this.tiles.slice(),e.size=this.size,e.padding=this.padding,e.tileElevation=this.tileElevation,e}copy(e){this.tiles=e.tiles.slice(),this.size=e.size,this.padding=e.padding,this.tileElevation=e.tileElevation}merge(e){if(this.size.width!==e.size.width||this.size.height!==e.size.height)throw new Error("Size mismatch");var i=e.tiles;for(let e=0,t=this.tiles.length;e<t;e++)this.tiles[e]=Math.max(7&i[e],7&this.tiles[e])|(i[e]|this.tiles[e])>>3<<3}isShrouded(e,t=0){t=this.rxyzToSxy(e.rx,e.ry,e.z+t);return this.getShroudTypeByShroudCoords(t)===On.Unexplored}getShroudType(e){return 7&this.tiles[this.getTileIndex(e)]}isFlagged(e,t){return 0!=(this.tiles[this.getTileIndex(e)]&t)}getShroudTypeByTileCoords(e,t,i){return this.getShroudTypeByShroudCoords(this.rxyzToSxy(e,t,i))}getShroudTypeByShroudCoords({sx:e,sy:t}){return e<0||t<0||e>=this.size.width||t>=this.size.height?On.Unexplored:7&this.tiles[e+t*this.size.width]??On.Unexplored}invalidateFull(){this.fullInvalidation=!0}invalidate(e,t,i){var s=e.sx+e.sy*this.size.width;let r=this.invalidations.get(s);r||(r={center:e,elevation:0,radius:0},this.invalidations.set(s,r)),r.elevation=Math.max(r.elevation,t),r.radius=Math.max(r.radius,i)}revealFrom(e){var t,i;e.isBuilding()&&e.wallTrait||(t=e.sight)&&(i=e.tile.z+e.tileElevation,e=this.rxyzToSxy(e.tile.rx,e.tile.ry,i),this.invalidate(e,i,t))}revealAround(e,t){e=this.rxyzToSxy(e.rx,e.ry,e.z);this.invalidate(e,Number.POSITIVE_INFINITY,t)}unrevealAround(e,t){var i=[],e=this.rxyzToSxy(e.rx,e.ry,e.z);this.setValueAround(e,t,Number.POSITIVE_INFINITY,i,On.Unexplored,On.Explored),this._onChange.dispatch(this,{type:"incremental",coords:i})}revealTemporarily(e){e=this.rxyzToSxy(e.tile.rx,e.tile.ry,e.tile.z+e.tileElevation);this.temporaryReveals.set(e,5*Fs.BASE_TICKS_PER_SECOND)}revealObject(e){e=this.rxyzToSxy(e.tile.rx,e.tile.ry,e.tile.z+e.tileElevation);this.invalidate(e,Number.POSITIVE_INFINITY,4.25)}toggleFlagsAround(e,t,i,s){var r=[],e=this.rxyzToSxy(e.rx,e.ry,e.z);this.setValueAround(e,t,Number.POSITIVE_INFINITY,r,void 0,void 0,s?{setFlags:i}:{clearFlags:i}),this._onChange.dispatch(this,{type:"incremental",coords:r})}update(){let i=[];if(this.invalidations.size){for(var e of this.invalidations.values())this.setValueAround(e.center,e.radius,e.elevation,i,On.Explored,[On.Unexplored,On.TemporaryReveal]);this.invalidations.clear()}this.temporaryReveals.size&&this.temporaryReveals.forEach((e,t)=>{e<=0?(this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,On.Unexplored,On.TemporaryReveal),this.temporaryReveals.delete(t)):(e===5*Fs.BASE_TICKS_PER_SECOND&&this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,On.TemporaryReveal,On.Unexplored),this.temporaryReveals.set(t,e-1))}),this.fullInvalidation?(this.fullInvalidation=!1,this._onChange.dispatch(this,{type:"full"})):i.length&&this._onChange.dispatch(this,{type:"incremental",coords:i})}setValueAround(s,r,a,n,o,h=void 0,{setFlags:l,clearFlags:c}={}){var e=Math.ceil(r),t=W(s.sx-e,0,this.size.width-1),u=W(s.sx+e,0,this.size.width-1),d=W(s.sy-e,0,this.size.height-1),p=W(s.sy+e,0,this.size.height-1),g=this.size.width;for(let i=t;i<=u;i++)for(let t=d;t<=p;t++){var m=i+t*g,f=7&this.tiles[m],y=this.tiles[m]>>3<<3;let e=y;void 0!==l&&(e|=l),void 0!==c&&(e&=~c),void 0!==h&&("number"!=typeof h?!h.includes(f):h!==f)||((i-s.sx)*(i-s.sx)+(t-s.sy)*(t-s.sy)>r*r+1||this.tileElevation[m]>=a+4||(this.tiles[m]=(o??f)|e,f===o&&y===e||n.push({sx:i,sy:t})))}}revealAll(){this.tiles.fill(On.Explored),this._onChange.dispatch(this,{type:"clear"})}reset(){this.tiles.fill(On.Unexplored),this._onChange.dispatch(this,{type:"cover"})}}class Wo{constructor(e){this.radiusTiles=e,this.refreshTicks=0}[Lr.onTick](e,t){0<this.refreshTicks&&this.refreshTicks--,this.refreshTicks<=0&&this.update(e,t)}[Qr.onSpawn](e,t){this.markGapTilesForFriendlies(e,e.owner,t,!0)}[Yr.onUnspawn](e,t){this.markGapTilesForFriendlies(e,e.owner,t,!1),this.update(e,t)}[Zr.onChange](e,t,i){this.markGapTilesForFriendlies(e,t,i,!1),this.markGapTilesForFriendlies(e,e.owner,i,!0),this.update(e,i)}[bn.onChange](e,t,i){this.markGapTilesForFriendlies(e,e.owner,t,!i),i&&this.update(e,t)}markGapTilesForFriendlies(i,e,s,t){let r=[e,...s.alliances.getAllies(e)],a;for(var n of r){let e=s.mapShroudTrait.getPlayerShroud(n);if(e&&(e.toggleFlagsAround(i.tile,this.radiusTiles,_n.Darken,t),!t)){if(!a){let t=new Cs(s.map.tileOccupation);a=r.map(e=>[...e.buildings]).flat().filter(e=>e.gapGeneratorTrait&&e!==i&&t.tileDistance(e,i)<=e.gapGeneratorTrait.radiusTiles+this.radiusTiles)}for(var o of a)e.toggleFlagsAround(o.tile,o.gapGeneratorTrait.radiusTiles,_n.Darken,!0)}}}update(t,i){this.refreshTicks=5*Fs.BASE_TICKS_PER_SECOND;let s;var r,a,n,o,h=t.owner.buildings.has(t)&&t.poweredTrait?.isPoweredOn();for(r of i.getCombatants())if(r!==t.owner&&!i.alliances.areAllied(t.owner,r)){let e=i.mapShroudTrait.getPlayerShroud(r);if(e)if(h){e.unrevealAround(t.tile,this.radiusTiles),s||(n=this.radiusTiles+ns.MAX_SIGHT,a=new Ss(t.tile.rx,t.tile.ry).addScalar(-n),n=new Ss(t.tile.rx,t.tile.ry).addScalar(n),s=i.map.technosByTile.queryRange(new Fn(a,n)));for(o of s)o.owner===r||i.alliances.areAllied(o.owner,r)?e.revealFrom(o):o.rules.revealToAll&&e.revealObject(o)}else[...r.buildings].some(e=>e.rules.spySat)&&e.revealAround(t.tile,this.radiusTiles)}}}const zo=Fs.BASE_TICKS_PER_SECOND;class Vo{constructor(e){this.radiusTiles=e,this.detectionLines=[],this.nextScan=zo}[Lr.onTick](e,t){e.owner.powerTrait?.isLowPower()?this.disable():(0<this.nextScan&&this.nextScan--,this.nextScan<=0&&(this.nextScan=zo,this.detectionLines=this.scan(e,t)))}[bn.onChange](e,t,i){i&&this.disable()}disable(){this.detectionLines.length&&(this.detectionLines=[],this.nextScan=0)}scan(t,i){var e=i.getCombatants().filter(e=>e!==t.owner&&!i.alliances.areAllied(e,t.owner));let s=[],r=new Cs(i.map.tileOccupation);var a,n,o,h=e=>r.distance2(e,t)/ks.LEPTONS_PER_TILE<=this.radiusTiles;for(a of e)for(var l of a.getOwnedObjects())l.attackTrait?.currentTarget?h((n=l.attackTrait.currentTarget).obj??n.tile)&&s.push({source:l,target:n}):l.isUnit()&&l.unitOrderTrait.targetLinesConfig&&((o=l.unitOrderTrait.targetLinesConfig).target?h(o.target)&&(n=i.createTarget(o.target,o.target.tile),s.push({source:l,target:n})):(o=o.pathNodes[0])&&h(o.tile)&&(o=i.createTarget(o.onBridge,o.tile),s.push({source:l,target:o})));return s}}class Ho{constructor(){this.healQueue=[]}addToHealQueue(e){return this.healQueue.push(e),this.healQueue.length-1}unitIsFirstInHealQueue(e){return this.healQueue[0]===e}removeFromHealQueue(e){e=this.healQueue.indexOf(e);-1!==e&&this.healQueue.splice(e,1)}startHealing(e){if(this.unit)throw new Error(`Already busy healing unit ${Bt[this.unit.type]}#${this.unit.id}}`);this.unit=e,this.healTicks=5*Fs.BASE_TICKS_PER_SECOND}[Lr.onTick](e,t){var i;this.healQueue=this.healQueue.filter(e=>!e.isDestroyed&&!e.isCrashing),this.unit&&void 0!==this.healTicks&&(0<this.healTicks&&this.healTicks--,this.healTicks<=0&&(this.healTicks=void 0,this.removeFromHealQueue(this.unit),this.unit.healthTrait.healToFull(e,t),e.ammoTrait&&e.ammoTrait.ammo--,this.evacuate(this.unit,e,t),i=this.unit,this.unit=void 0,t.events.dispatch(new xo(i,e))))}[Wr.onDestroy](e,t,i){this.unit&&(t.destroyObject(this.unit,i,!0),this.unit=void 0)}evacuate(t,i,s){let e;var r={x:i.tile.rx,y:i.tile.ry+i.art.foundation.height},r=s.map.tiles.getByMapCoords(r.x,r.y);r&&s.map.isWithinBounds(r)&&this.canEvacuateTo(r,t,i,s)&&(e=r),e=e||new js(s.map.tiles,s.map.mapBounds,i.tile,i.art.foundation,1,1,e=>this.canEvacuateTo(e,t,i,s)).getNextTile(),e?(s.unlimboObject(t,e),t.unitOrderTrait.addTask(new va(s))):s.destroyObject(t,{player:t.owner})}canEvacuateTo(e,t,i,s){return 0<s.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&Math.abs(e.z-i.tile.z)<2&&!s.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length}}class Go{constructor(){this.timer=new Mo}isActive(){return this.timer.isActive()}activate(e,t){this.isActive()||(this.timer.setActiveFor(e),this.attackerInfo=t)}[Lr.onTick](e,t){this.timer.isActive()&&!0===this.timer.tick(t.currentTick)&&(e.invulnerableTrait.isActive()||e.isBuilding()&&e.cabHutTrait||t.destroyObject(e,this.attackerInfo,!0,!0))}}(r=In=In||{})[r.BuildUp=0]="BuildUp",r[r.Ready=1]="Ready",r[r.BuildDown=2]="BuildDown";class $o extends Ba{constructor(e,t,i){super(Bt.Building,e,t,i),this.showWeaponRange=!1,this.wallType=[0,0,0,0],this.direction=0,this.buildStatus=In.BuildUp,this.lastBuildStatus=this.buildStatus}static factory(e,t,i,s,r,a){let n=new this(e,t,s);return t.canBeOccupied&&(n.garrisonTrait=new Qn(n,i.audioVisual.conditionRed,t.maxNumberOccupants),n.traits.add(n.garrisonTrait)),t.canC4&&!t.wall&&(n.c4ChargeTrait=new Do,n.traits.add(n.c4ChargeTrait)),t.eligibleForDelayKill&&(n.delayedKillTrait=new Go,n.traits.add(n.delayedKillTrait)),t.bridgeRepairHut&&(n.cabHutTrait=new Io(n,a),n.traits.add(n.cabHutTrait)),t.crewed&&(n.crewedTrait=new _o,n.traits.add(n.crewedTrait)),t.turret&&(n.turretTrait=new Yn,n.traits.add(n.turretTrait)),t.overpowerable&&(n.overpoweredTrait=new Bo(n),n.traits.add(n.overpoweredTrait)),(t.powered&&0!==t.power||t.needsEngineer)&&(n.poweredTrait=new so(n),n.traits.add(n.poweredTrait)),(t.factory||t.cloning)&&(n.factoryTrait=new So(t.cloning?Ji.InfantryType:t.factory,t.cloning),n.traits.add(n.factoryTrait)),t.superWeapon&&(n.superWeaponTrait=new jo(t.superWeapon),n.traits.add(n.superWeaponTrait)),t.numberOfDocks&&(n.dockTrait=new To(n,r,t.numberOfDocks,s.dockingOffsets),n.traits.add(n.dockTrait),t.helipad&&(n.helipadTrait=new Ro,n.traits.add(n.helipadTrait)),(t.unitRepair||t.unitReload)&&(n.unitRepairTrait=new Po,n.traits.add(n.unitRepairTrait)),t.unitReload&&(n.unitReloadTrait=new Lo,n.traits.add(n.unitReloadTrait))),t.hospital&&(n.hospitalTrait=new Ho,n.traits.add(n.hospitalTrait)),(t.factory||t.cloning||t.numberOfDocks)&&(n.rallyTrait=new No,n.traits.add(n.rallyTrait)),t.freeUnit&&n.traits.add(new Oo),t.produceCashStartup&&n.traits.add(new Co),t.wall&&(n.wallTrait=new Ao,n.traits.add(n.wallTrait)),t.gapGenerator&&(n.gapGeneratorTrait=new Wo(t.gapRadiusInCells),n.traits.add(n.gapGeneratorTrait)),t.psychicDetectionRadius&&(n.psychicDetectorTrait=new Vo(t.psychicDetectionRadius),n.traits.add(n.psychicDetectorTrait)),n}isBuilding(){return!0}getFoundation(){return this.art.foundation}getFoundationCenterOffset(){var e=this.getFoundation();return new Ss(e.width/2*ks.LEPTONS_PER_TILE,e.height/2*ks.LEPTONS_PER_TILE)}update(e){this.buildStatus!==In.BuildUp||this.unitOrderTrait.hasTasks()||this.unitOrderTrait.addTask(new Fo(e.rules.general.buildupTime)),this.buildStatus!==this.lastBuildStatus&&(this.lastBuildStatus=this.buildStatus,e.events.dispatch(new Kn(this,this.buildStatus))),this.attackTrait?.setDisabled(this.buildStatus!==In.Ready||!!this.poweredTrait&&!this.poweredTrait.isPoweredOn()),super.update(e)}}class qo extends Aa{constructor(e,t,i){super(Bt.Terrain,e,t,i),this.radarInvisible=this.rules.radarInvisible}static factory(e,t,i){return new this(e,t,i)}}class Xo extends Aa{constructor(e,t,i){super(Bt.Overlay,e,t,i),this.radarInvisible=this.rules.radarInvisible}static factory(e,t,i){let s=new this(e,t,i);return t.wall&&(s.wallTrait=new Ao,s.traits.add(s.wallTrait)),s}isTiberium(){return $a.getOverlayTibType(this.overlayId)!==na.NotSpecial}isBridge(){return Va.isBridge(this.overlayId)}isXBridge(){return Va.isXBridge(this.overlayId)}isHighBridge(){return Va.isHighBridge(this.overlayId)}isLowBridge(){return Va.isLowBridge(this.overlayId)}isBridgePlaceholder(){return Va.isBridgePlaceholder(this.overlayId)}getFoundation(){let e={width:1,height:1};return this.isBridge()&&(this.isXBridge()?e.height+=2:e.width+=2),e}}class Zo extends Aa{constructor(e,t,i){super(Bt.Smudge,e,t,i)}static factory(e,t,i){return new this(e,t,i)}getFoundation(){return{width:this.rules.width,height:this.rules.height}}}class Qo extends Sa{constructor(e,t,i,s){super(e,i??t,!1,{closeEnoughTiles:i?void 0:0,strictCloseEnough:!i}),this.teleportTile=t,this.teleportCondition=s}onStart(e){if(super.onStart(e),!e.harvesterTrait||e.rules.locomotor!==ii.Chrono)throw new Error(`Vehicle ${e.name} is not a chrono miner`)}onTick(e){return!e.moveTrait.isDisabled()&&(!(this.isCancelling()||e.moveTrait.moveState!==$r.ReachedNextWaypoint||e.tile===this.teleportTile||!this.tryTeleportToRefinery(e))||!0===super.onTick(e)&&(this.isCancelling()||e.tile===this.teleportTile||this.tryTeleportToRefinery(e),!0))}tryTeleportToRefinery(e){return(!this.teleportCondition||!1!==this.teleportCondition(e,this.teleportTile))&&(!this.game.map.terrain.findObstacles({tile:this.teleportTile,onBridge:void 0},e).length&&(e.moveTrait.teleportUnitToTile(this.teleportTile,void 0,!0,!0,this.game),e.zone===bs.Air&&(e.zone=bs.Ground,e.position.tileElevation=0),!0))}}const Yo=[[8,5,6],[3,0,2],[7,4,1]];class Ko extends Hs{constructor(e,t,i=!1){super(),this.game=e,this.initialTarget=t,this.explicitOrder=i,this.forceMoveTried=!1,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.rangeHelper=new Cs(e.map.tileOccupation),this.scanNearRadius=e.rules.ai.tiberiumNearScan,this.scanFarRadius=e.rules.ai.tiberiumFarScan,this.strictTarget=i}onStart(e){if(!e.isVehicle()||!e.harvesterTrait)throw new Error(`Unit ${e.name} is not a harvester.`);e.harvesterTrait.status=Bn.MovingToOreSite,e.harvesterTrait.lastGatherExplicit=this.explicitOrder}onEnd(e){e.harvesterTrait.status!==Bn.LookingForOreSite&&(e.harvesterTrait.status=Bn.Idle)}onTick(i){if(this.isCancelling())return!0;let s=i.harvesterTrait;if(s.status===Bn.MovingToOreSite){if(this.target=this.initialTarget?.landType===Kt.Tiberium?this.initialTarget:this.findClosestReachableOreSite(i,s.lastOreSite??i.tile,!0),s.lastOreSite=this.target,!this.target){s.status=Bn.LookingForOreSite;let e=this.getRefineryOnTile(i.tile);if(e&&1===i.unitOrderTrait.getTasks().length){let t=i.rules.movementZone===si.Fly;var r=new js(this.game.map.tiles,this.game.map.mapBounds,e.tile,e.getFoundation(),1,5,e=>t||0<this.game.map.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&Math.abs(e.z-i.tile.z)<2&&!this.game.map.terrain.findObstacles({tile:e,onBridge:void 0},i).length).getNextTile();r&&i.unitOrderTrait.addTasks(new Sa(this.game,r,!1),new ga(()=>{[qr.Success,qr.CloseEnough,qr.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new pa(1/60))}))}return!0}var a=this.game.rules.general.closeEnough,r=this.rangeHelper.tileDistance(i.tile,this.target)<=a;if(i.tile!==this.target&&(i.tile.landType!==Kt.Tiberium||!r||this.strictTarget)){if(i.tile!==this.target&&r&&i.tile.landType!==Kt.Tiberium){r=this.findClosestReachableOreSite(i,i.tile,!1,!0);if(r)this.target=r,s.lastOreSite=this.target;else{if(!this.forceMoveTried)return this.forceMoveTried=!0,this.children.push(new Sa(this.game,this.target,!1,{closeEnoughTiles:0,strictCloseEnough:!0})),!1;if(this.forceMoveTried=!1,!s.isEmpty())return this.returnOreIfPossible(i),!0;r=this.findClosestReachableOreSite(i,i.tile,!0,!0);if(!r)return s.status=Bn.LookingForOreSite,!0;this.target=r,s.lastOreSite=this.target}}return this.children.push(new Sa(this.game,this.target,!1,{closeEnoughTiles:a}),new ga(()=>{[qr.Success,qr.CloseEnough,qr.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new pa(5/60))})),!1}this.target=i.tile,s.lastOreSite=this.target,s.status=Bn.Harvesting,this.forceMoveTried=!1,this.strictTarget=!1}if(s.status!==Bn.Harvesting)return!1;{if(s.isFull())return this.returnOreIfPossible(i),!0;let e=this.game.map.getObjectsOnTile(i.tile).find(e=>e.isOverlay()&&e.isTiberium());if(!e)return this.findClosestReachableOreSite(i,s.lastOreSite??i.tile,!1)||s.isEmpty()?(s.status=Bn.MovingToOreSite,this.onTick(i)):(this.returnOreIfPossible(i),!0);let t=e.traits.get(qa);a=t.collectBail();if(t.getBailCount()||this.game.unspawnObject(e),void 0!==a)if(a===oa.Ore)s.ore++;else{if(a!==oa.Gems)throw new Error(`Unsupported tiberium type ${a}`);s.gems++}return[...i.owner.buildings].some(e=>e.rules.refinery)||this.explicitOrder?(this.children.push(new pa(1/60)),!1):!0}}findClosestReachableOreSite(t,i,e,s=!1){let r=t.rules.movementZone===si.Fly;var a,n=e=>e.landType===Kt.Tiberium&&(!s||(r||!this.game.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length));if(n(i))return i;let o=1;if(!e){let e=new js(this.game.map.tiles,this.game.map.mapBounds,i,{width:1,height:1},o,o,n),t=[];for(;a=e.getNextTile();)t.push(a);if(t.length){let e=t.map(e=>{var t=this.game.map.getObjectsOnTile(e).find(e=>e.isOverlay()&&e.isTiberium());if(!t)throw new Error(`Ore should exist on tile ${e.rx},${e.ry} b/c of landType`);return{tile:e,ore:t}});return e.sort((e,t)=>1e3*(t.ore.value-e.ore.value)+(Yo[1+t.tile.ry-i.ry][1+t.tile.rx-i.rx]-Yo[1+e.tile.ry-i.ry][1+e.tile.rx-i.rx])),e[0].tile}o=2}e=e?this.scanFarRadius:this.scanNearRadius;let h=new js(this.game.map.tiles,this.game.map.mapBounds,i,{width:1,height:1},o,e,n);return h.getNextTile()}getRefineryOnTile(e){return this.game.map.getObjectsOnTile(e).find(e=>e.isBuilding()&&e.rules.refinery)}returnOreIfPossible(e){1===e.unitOrderTrait.getTasks().length&&e.unitOrderTrait.addTask(new Jo(this.game))}getTargetLinesConfig(e){return{pathNodes:this.initialTarget?[{tile:this.initialTarget,onBridge:void 0}]:[]}}}class Jo extends Hs{constructor(e,t,i=!1,s=!1){super(),this.game=e,this.forceTarget=t,this.resetLastOreSite=i,this.explicitOrder=s,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.rangeHelper=new Cs(e.map.tileOccupation)}onStart(e){if(!e.isVehicle()||!e.harvesterTrait)throw new Error(`Unit ${e.name} is not a harvester.`);e.harvesterTrait.status=Bn.MovingToRefinery,this.resetLastOreSite&&(e.harvesterTrait.lastOreSite=void 0)}onEnd(e){this.target?.isSpawned&&(this.target.dockTrait.undockUnit(e),this.target.dockTrait.unreserveDockForUnit(e)),e.harvesterTrait.status!==Bn.LookingForRefinery&&(e.harvesterTrait.status=Bn.Idle)}onTick(s){if(this.isCancelling())return!0;let r=s.harvesterTrait;if(r.status===Bn.LookingForRefinery)return!0;if(r.status===Bn.MovingToRefinery){if(!this.target||!this.isValidTargetRefinery(this.target,s)||s.tile!==this.findRefineryDockingTile(this.target)){var a=this.forceTarget??this.findClosestReachableRefinery(s);if(!a)return r.status=Bn.LookingForRefinery,!0;this.target&&this.target!==a&&this.target.dockTrait.hasReservedDockForUnit(s)&&this.target.dockTrait.unreserveDockForUnit(s),this.target=a}let e=this.target.dockTrait.getFirstAvailableDockNumber(),t=!1;void 0===e&&(e=this.target.dockTrait.getFirstEmptyDockNumber(),void 0!==e&&(t=!this.target.dockTrait.hasReservedDockForUnit(s)));let i=this.findRefineryDockingTile(this.target);var n=this.rangeHelper.tileDistance(s,i);if(void 0===e||t||n>this.game.rules.general.harvesterTooFarDistance&&!this.explicitOrder){var o=this.findReachableQueueingTile(s);return o?(s.tile!==o&&this.children.push(s.rules.teleporter?new Qo(this.game,i,o,()=>this.chronoMinerCanTeleport(s,i,this.target)):new Sa(this.game,o,!1),new ga(()=>{s.moveTrait.lastMoveResult===qr.Fail?r.status=Bn.LookingForRefinery:s.moveTrait.lastMoveResult===qr.CloseEnough?this.children.push(new pa(5/60)):s.moveTrait.lastMoveResult===qr.Success&&this.children.push(new pa(2/60))})),!1):!0}if(this.target.dockTrait.hasReservedDockForUnit(s)||this.target.dockTrait.reserveDockAt(s,e),void 0===this.reservedDockNumber&&(this.reservedDockNumber=this.target.dockTrait.getReservedDockForUnit(s)),s.tile!==i)return this.children.push(s.rules.teleporter?new Qo(this.game,i,void 0,()=>this.chronoMinerCanTeleport(s,i,this.target)):new Sa(this.game,i,!1,{closeEnoughTiles:0,strictCloseEnough:!0}),new ga(()=>{s.moveTrait.lastMoveResult===qr.Fail&&(r.status=Bn.LookingForRefinery)})),!1;r.status=Bn.Docking}if(!this.isValidTargetRefinery(this.target,s))return r.status=Bn.MovingToRefinery,this.forceTarget=void 0,this.onTick(s);if(r.status===Bn.Docking){if(270!==s.direction)return this.children.push(new br(270)),!1;this.target.dockTrait.dockUnitAt(s,this.reservedDockNumber),this.reservedDockNumber=void 0,r.status=Bn.PreparingToUnload}if(r.status===Bn.PreparingToUnload)return this.preventOpportunityFire=!0,this.children.push(new pa(2/60)),r.status=Bn.Unloading,!1;if(r.status!==Bn.Unloading)return!1;a=r.ore*this.game.rules.getTiberium(oa.Ore).value+r.gems*this.game.rules.getTiberium(oa.Gems).value;this.target.owner.credits+=a;n=[...this.target.owner.buildings].filter(e=>e.rules.orePurifier&&(!e.poweredTrait||!this.target.owner.powerTrait?.isLowPower())).length,o=this.game.rules.general.purifierBonus;return this.target.owner.credits+=n*Math.floor(a*o),r.ore=0,r.gems=0,1===s.unitOrderTrait.getTasks().length&&s.unitOrderTrait.addTask(new Ko(this.game)),!0}isValidTargetRefinery(e,t){return e.isSpawned&&this.game.areFriendly(e,t)&&!e.warpedOutTrait.isActive()}findClosestReachableRefinery(i){let s=this.rangeHelper,e=[...i.owner.buildings].filter(e=>e.rules.refinery&&e.dockTrait&&!e.warpedOutTrait.isActive()).sort((e,t)=>s.distance2(i,e)-s.distance2(i,t));var t=e[0],r=e.find(e=>0<e.dockTrait.getAvailableDockCount());return!r||t&&s.tileDistance(i,r.centerTile)-s.tileDistance(i,t.centerTile)>this.game.rules.general.harvesterTooFarDistance?t:r}findReachableQueueingTile(t){if(this.target.art.queueingCell){var e=new Ss(this.target.tile.rx,this.target.tile.ry).add(this.target.art.queueingCell),e=this.game.map.tiles.getByMapCoords(e.x,e.y);if(e&&this.isValidQueueingTile(e,t))return e}return new js(this.game.map.tiles,this.game.map.mapBounds,this.target.tile,this.target.getFoundation(),1,1,e=>this.isValidQueueingTile(e,t)).getNextTile()}isValidQueueingTile(e,t){return t.zone===bs.Air||0<this.game.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&Math.abs(e.z-this.target.tile.z)<2&&!e.onBridgeLandType}findRefineryDockingTile(e){e={x:e.tile.rx+e.getFoundation().width-1,y:e.tile.ry+Math.floor(e.getFoundation().height/2)};return this.game.map.tiles.getByMapCoords(e.x,e.y)}chronoMinerCanTeleport(e,t,i){let s=this.rangeHelper;t=s.tileDistance(e,t);return!(!this.forceTarget&&t>this.game.rules.general.chronoHarvTooFarDistance)&&(!(t<=1)&&(!!this.isValidTargetRefinery(i,e)&&!(0===i.dockTrait.getAvailableDockCount()&&!i.dockTrait.hasReservedDockForUnit(e))))}}(Cn=Cn||{}).onPush=Symbol(),(r=An=An||{})[r.Move=0]="Move",r[r.ForceMove=1]="ForceMove",r[r.Attack=2]="Attack",r[r.ForceAttack=3]="ForceAttack",r[r.AttackMove=4]="AttackMove",r[r.Guard=5]="Guard",r[r.GuardArea=6]="GuardArea",r[r.Capture=7]="Capture",r[r.Occupy=8]="Occupy",r[r.Deploy=9]="Deploy",r[r.DeploySelected=10]="DeploySelected",r[r.Stop=11]="Stop",r[r.Cheer=12]="Cheer",r[r.Dock=13]="Dock",r[r.Gather=14]="Gather",r[r.Repair=15]="Repair",r[r.Scatter=16]="Scatter",r[r.EnterTransport=17]="EnterTransport",r[r.PlaceBomb=18]="PlaceBomb",(r=Bn=Bn||{})[r.Idle=0]="Idle",r[r.LookingForOreSite=1]="LookingForOreSite",r[r.MovingToOreSite=2]="MovingToOreSite",r[r.Harvesting=3]="Harvesting",r[r.LookingForRefinery=4]="LookingForRefinery",r[r.MovingToRefinery=5]="MovingToRefinery",r[r.Docking=6]="Docking",r[r.PreparingToUnload=7]="PreparingToUnload",r[r.Unloading=8]="Unloading";class eh{constructor(e){this.storage=e,this.ore=0,this.gems=0,this.status=Bn.Idle,this.lastGatherExplicit=!1,this.autoGatherOnNextIdle=!1,this.ticksSinceLastRefineryCheck=0,this.ticksSinceLastOreCheck=0}[Qr.onSpawn](e,t){e.owner.isCombatant()&&(t.afterTick(()=>{e.unitOrderTrait.addTask(new Ko(t))}),e.attackTrait?.increasePassiveScanCooldown(1))}[Zr.onChange](e,t,i){!t.isCombatant()&&e.owner.isCombatant()&&i.afterTick(()=>{e.unitOrderTrait.addTask(new Ko(i))})}[Lr.onTick](e,t){this.status===Bn.LookingForRefinery?this.ticksSinceLastRefineryCheck++>5*Fs.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastRefineryCheck=0,e.unitOrderTrait.hasTasks()?this.ticksSinceLastRefineryCheck=-25*Fs.BASE_TICKS_PER_SECOND:[...e.owner.buildings].some(e=>e.rules.refinery)||this.lastGatherExplicit?e.unitOrderTrait.addTask(new Jo(t)):this.status=Bn.Idle):this.status===Bn.LookingForOreSite?this.ticksSinceLastOreCheck++>20*Fs.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastOreCheck=0,e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new Ko(t))):this.status===Bn.Idle&&this.autoGatherOnNextIdle&&e.unitOrderTrait.isIdle()&&e.tile.landType===Kt.Tiberium&&(this.autoGatherOnNextIdle=!1,e.unitOrderTrait.addTask(new Ko(t,e.tile,!0)))}[Ur.onBeforeTeleport](e,t,i,s){!s&&e.owner.isCombatant()&&(this.status=Bn.Idle,this.lastOreSite=void 0,i&&e.rules.teleporter&&t.afterTick(()=>{e.unitOrderTrait.addTask(new(this.isFull()?Jo:Ko)(t))}))}[Cn.onPush](e,t){this.autoGatherOnNextIdle=[An.AttackMove,An.Move,An.ForceMove,An.Scatter].includes(t),[Bn.LookingForRefinery,Bn.LookingForOreSite].includes(this.status)&&(this.status=Bn.Idle)}isFull(){return this.ore+this.gems>=this.storage}isEmpty(){return!this.ore&&!this.gems}getHash(){return 100*this.ore+this.gems}debugGetState(){return{ore:this.ore,gems:this.gems}}}class th{constructor(e){this.target=e,this.type=is.LeaveTransport}}class ih{constructor(e){this.obj=e,this.units=[],this.loadQueue=[]}unitFitsInside(e){return e.rules.size<=this.obj.rules.sizeLimit&&e.rules.size<=this.getAvailableCapacity()}getOccupiedCapacity(){return this.units.reduce((e,t)=>e+t.rules.size,0)}getMaxCapacity(){return this.obj.rules.passengers}getAvailableCapacity(){return this.getMaxCapacity()-this.getOccupiedCapacity()}addToLoadQueue(e){return this.loadQueue.push(e),this.loadQueue.length-1}unitIsFirstInLoadQueue(e){return this.loadQueue[0]===e}removeFromLoadQueue(e){e=this.loadQueue.indexOf(e);-1!==e&&this.loadQueue.splice(e,1)}[Lr.onTick](e,t){this.loadQueue=this.loadQueue.filter(e=>!e.isDestroyed&&!e.isCrashing)}[Wr.onDestroy](e,t,i,s){var r=!!e.armedTrait?.deathWeapon,a=i?.weapon?.warhead.rules.parasite;if(s||r||e.zone===bs.Air||a)for(var n of this.units)r&&n.armedTrait&&(n.armedTrait.deathWeapon=void 0),n.position.tileElevation=e.position.tileElevation,n.zone=e.zone,n.onBridge=e.onBridge,n.position.tile=e.tile,t.destroyObject(n,i,!0);else this.spawnSurvivors(t);this.units=[]}spawnSurvivors(e){var t=this.obj;if(this.units.length){for(var i of this.units)0<e.map.terrain.getPassableSpeed(t.tile,i.rules.speedType,t.onBridge)?(i.owner.addOwnedObject(i),i.position.tileElevation=t.onBridge?e.map.tileOccupation.getBridgeOnTile(t.tile).tileElevation:0,i.onBridge=t.onBridge,i.zone=e.map.getTileZone(t.tile,!t.onBridge),e.unlimboObject(i,t.tile),i.unitOrderTrait.addTask(new va(e))):(i.position.tileElevation=t.position.tileElevation,i.zone=t.zone,i.onBridge=t.onBridge,i.position.tile=t.tile,e.destroyObject(i,{player:i.owner}));e.events.dispatch(new th(t))}}getHash(){return H(this.units.map(e=>e.getHash()))}debugGetState(){return this.units.map(e=>e.debugGetState())}dispose(){this.obj=void 0}}class sh{[Lr.onTick](e){var t,i;!!e.transportTrait.units.length!==this.lastHadGunner&&(this.lastHadGunner=!!e.transportTrait.units.length,i=t=e.transportTrait.units[0]?.rules.ifvMode??0,(t=e.rules.turretIndexesByIfvMode.get(t)??0)<e.rules.turretCount&&(e.turretNo=t,e.armedTrait?.selectSpecialWeapon(i,e.veteranLevel===Jr.Elite)))}getUiNameForIfvMode(e,t){switch(e){case 0:return"tip:rocket";case 1:return"tip:repair";case 2:case 4:case 5:return"tip:machinegun";default:return t?"name:"+t.toLowerCase():void 0}}}(xn=xn||{}).onHeal=Symbol();class rh{constructor(e){this.gameObject=e,this.beingBoarded=!1}infest(e,t){this.beingBoarded=!1,this.parasite=e,this.parasiteWeapon=t,e.rules.organic?this.damageTickCooldown=lh+2:this.damageTickCooldown=0,this.lastExternalDamageInflicted=void 0,this.lastExternalDamageTick=void 0,t.warhead.rules.paralyzes&&this.gameObject.moveTrait.setDisabled(!0)}isInfested(){return!(!this.parasite||this.parasite.isDestroyed)||this.beingBoarded}isParalyzed(){return!!this.parasiteWeapon?.warhead.rules.paralyzes}uninfest(){this.parasite&&(this.parasiteWeapon.warhead.rules.paralyzes&&this.gameObject.moveTrait.setDisabled(!1),this.parasite=void 0,this.parasiteWeapon=void 0)}getParasite(){return this.parasite}[Lr.onTick](s,r){if(this.parasite)if(this.parasite.isDestroyed)this.uninfest();else if(0<this.damageTickCooldown)this.damageTickCooldown--;else{let e=this.parasiteWeapon;this.damageTickCooldown=this.parasite.rules.organic?lh+2:e.getCooldownTicks();let t=e.rules.damage;this.parasite.veteranTrait&&(t*=this.parasite.veteranTrait.getVeteranDamageMultiplier());let i=e.warhead.computeDamage(t,s);this.canBeCulled(s,this.parasite,e,r)&&(i=s.healthTrait.getHitPoints()),e.warhead.inflictDamage(i,s,{player:this.parasite.owner,obj:this.parasite,weapon:e},r),s.isCrashing?(this.parasiteWeapon.expireCooldown(),this.evictOrDestroyParasite(s,r)):!s.isDestroyed&&s.isVehicle()&&s.zone!==bs.Air&&e.warhead.rules.rocker&&s.applyRocking(90*(.5<=r.generateRandom()?1:-1),1)}}canBeCulled(e,t,i,s){if(!i.warhead.rules.culling)return!1;s=s.rules.audioVisual,s=t.veteranTrait?.isElite()?s.conditionYellow:s.conditionRed;return e.healthTrait.health<=100*s}[xn.onHeal](e,t,i,s){var r;!this.parasite||this.parasite.isDestroyed||s===e||e.isAircraft()&&s?.rules.unitReload||(this.parasite.rules.organic?(r=this.parasite,this.evictOrDestroyParasite(e,t),this.stunParasite(r,t)):(this.parasite.deathType=zr.None,t.destroyObject(this.parasite,s?{player:s.owner,obj:s}:void 0),this.uninfest()))}[ca.onDamage](e,t,i,s){s?.obj!==this.parasite&&(this.lastExternalDamageInflicted=i,this.lastExternalDamageTick=t.currentTick)}[Kr.onAttack](i,s,r){if(this.parasite&&!this.parasite.isDestroyed&&s?.weapon?.warhead.rules.sonic){var a=this.parasite;this.evictOrDestroyParasite(i,r),this.stunParasite(a,r);let e=s.weapon.warhead;e.canDamage(a,a.tile,a.zone)&&(i=e.computeDamage(s.weapon.rules.damage,a),e.inflictDamage(i,a,s,r));let t=s.obj?.unitOrderTrait.getCurrentTask();t instanceof po&&t.getWeapon().warhead.rules.sonic&&t.cancel()}}[Wr.onDestroy](e,t,i,s){this.parasite&&!this.parasite.isDestroyed&&(s||!this.parasite.invulnerableTrait.isActive()&&this.shouldSupressParasite(t,this.parasite,i)?(this.parasite.deathType=zr.None,t.destroyObject(this.parasite,i,s),this.uninfest()):(this.parasiteWeapon.expireCooldown(),this.evictOrDestroyParasite(e,t)))}shouldSupressParasite(e,t,i){return i?.obj!==t||this.lastExternalDamageInflicted&&this.lastExternalDamageInflicted>t.rules.suppressionThreshold&&e.currentTick-this.lastExternalDamageTick<2*this.lastExternalDamageInflicted}[Ur.onBeforeTeleport](e,t,i,s){i&&s&&this.parasite&&!this.parasite.isDestroyed&&(this.parasiteWeapon.expireCooldown(),s=this.parasite,this.evictOrDestroyParasite(e,t,!0),s.isDestroyed||this.stunParasite(s,t))}stunParasite(e,t){e.unitOrderTrait.addTaskToFront(new pa(10/60).setCancellable(!1)),e.isVehicle()&&e.submergibleTrait&&(e.submergibleTrait.emerge(e,t),e.cloakableTrait?.uncloak(t),e.submergibleTrait.setCooldown(10*Fs.BASE_TICKS_PER_SECOND))}evictOrDestroyParasite(s,r,a=!1){if(this.parasite&&!this.parasite.isDestroyed){var e=s.zone===bs.Air;if(e&&this.parasite.rules.movementZone!==si.Fly||!e&&!r.map.terrain.getPassableSpeed(s.tile,this.parasite.rules.speedType,s.onBridge)&&!r.map.getObjectsOnTile(s.tile).find(e=>e.isBuilding()))this.parasite.deathType=zr.None,r.destroyObject(this.parasite,{player:s.owner,obj:s});else{let t=s.tile,i=s.onBridge;if(!a&&!s.isDestroyed||this.parasite.rules.organic){let e=new js(r.map.tiles,r.map.mapBounds,t,{width:1,height:1},1,1,e=>0<r.map.terrain.getPassableSpeed(e,this.parasite.rules.speedType,i)&&!r.map.terrain.findObstacles({tile:e,onBridge:i},this.parasite).length);a=e.getNextTile();if(!a)return this.parasite.deathType=zr.None,r.destroyObject(this.parasite,{player:s.owner,obj:s}),void this.uninfest();t=a}this.parasite.onBridge=i,this.parasite.position.subCell=this.parasite.isInfantry()?s.position.subCell:0,this.parasite.zone=r.map.getTileZone(t,!i),this.parasite.position.tileElevation=i?r.map.tileOccupation.getBridgeOnTile(t).tileElevation:0,this.parasite.resetGuardModeToIdle(),r.unlimboObject(this.parasite,t,!0)}this.uninfest()}}destroyParasite(e,t){this.parasite&&(this.parasite.deathType=zr.None,t.destroyObject(this.parasite,e),this.uninfest())}dispose(){this.gameObject=void 0}}class ah{constructor(e){this.target=e,this.type=is.ShipSubmergeChange}}class nh{constructor(){this.isActive=!1}isSubmerged(){return this.isActive}setCooldown(e){this.cooldownTicks=e}[Lr.onTick](e,t){this.isActive||e.parasiteableTrait?.isInfested()||(e.attackTrait&&e.attackTrait.attackState!==yn.Idle&&!e.moveTrait.isMoving()?this.cooldownTicks=Math.max(this.cooldownTicks??0,5*Fs.BASE_TICKS_PER_SECOND):this.cooldownTicks??(this.cooldownTicks=Math.floor(60*t.rules.general.cloakDelay*Fs.BASE_TICKS_PER_SECOND)),0<this.cooldownTicks&&this.cooldownTicks--,this.cooldownTicks<=0&&(this.isActive=!0,t.events.dispatch(new ah(e))))}[ca.onDamage](e,t){this.emerge(e,t)}emerge(e,t){this.isActive&&(this.isActive=!1,this.cooldownTicks=void 0,t.events.dispatch(new ah(e)))}}class oh{constructor(){this.prevHoverBobLeptons=0,this.spawnTick=0}[Qr.onSpawn](e,t){this.setBaseElevation(e,t),this.spawnTick=t.currentTick}[Hr.onTileChange](e,t,i,s){s&&(this.prevHoverBobLeptons=0,this.setBaseElevation(e,t))}setBaseElevation(e,t){e.position.tileElevation=(e.onBridge?t.map.tileOccupation.getBridgeOnTile(e.tile)?.tileElevation??0:0)+ks.worldToTileHeight(t.rules.general.hover.height)}[Lr.onTick](e,t){var i=this.computeHoverBobLeptons(t.currentTick,t.rules.general.hover),t=i-this.prevHoverBobLeptons;this.prevHoverBobLeptons=i;i=ks.tileHeightToWorld(e.position.tileElevation);e.position.tileElevation=ks.worldToTileHeight(i+t)}computeHoverBobLeptons(e,t){e=(e-this.spawnTick)/Fs.BASE_TICKS_PER_SECOND/(60*t.bob);return.1*t.height*Qi.sin(2*e*Math.PI)}}class hh{constructor(){this.tilt={pitch:0,yaw:0}}[Qr.onSpawn](e){this.tilt=this.computeTilt(e.tile.rampType)}[Hr.onTileChange](e){this.tilt=this.computeTilt(e.tile.rampType)}computeTilt(e){let t,i;return 0===e||17<=e?t=i=0:i=e<=4?(t=25,-90*e):(t=25,225-(e-1)%4*90),{pitch:t,yaw:i}}}const lh=34;class ch extends Ba{constructor(e,t,i){super(Bt.Vehicle,e,t,i),this.direction=0,this.spinVelocity=0,this.crateBonuses=new Ma,this.turretNo=0,this.onBridge=!1,this.isSinker=!1,this.isFiring=!1,this.zone=t.naval?bs.Water:bs.Ground}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,s,r){let a=new this(e,t,i);return a.isSinker=!t.underwater&&(t.weight>=s.general.shipSinkingWeight||!t.naval),a.moveTrait=new _a(a,r),a.traits.add(a.moveTrait),t.crashable&&(a.crashableTrait=new Pa(a),a.traits.add(a.crashableTrait)),t.crewed&&(a.crewedTrait=new _o,a.traits.add(a.crewedTrait)),t.harvester&&(a.harvesterTrait=new eh(t.storage),a.traits.add(a.harvesterTrait)),t.passengers&&(a.transportTrait=new ih(a),a.traits.add(a.transportTrait),t.gunner&&(a.gunnerTrait=new sh,a.traits.add(a.gunnerTrait))),t.turret&&(a.turretTrait=new Yn,a.traits.add(a.turretTrait)),t.consideredAircraft&&!t.landable||a.traits.add(new wo),t.parasiteable&&(a.parasiteableTrait=new rh(a),a.traits.add(a.parasiteableTrait)),t.naval&&t.underwater&&(a.submergibleTrait=new nh,a.traits.add(a.submergibleTrait)),t.locomotor===ii.Hover&&a.traits.add(new oh),[ii.Vehicle,ii.Chrono].includes(t.locomotor)&&i.isVoxel&&(a.tilterTrait=new hh,a.traits.add(a.tilterTrait)),a}isUnit(){return!0}isVehicle(){return!0}getUiName(){if(this.gunnerTrait){var e=this.armedTrait.getSpecialWeaponIndex(),t=this.gunnerTrait.getUiNameForIfvMode(e,this.transportTrait?.units[0]?.name),e=`name:${this.name}`;return t?`{${t}} {${e}}`:e}return super.getUiName()}update(e){this.rocking&&(this.rocking.ticksLeft--,this.rocking.ticksLeft||(this.rocking=void 0)),super.update(e)}applyRocking(e,t){this.rocking={ticksLeft:this.rocking?.ticksLeft??lh,facing:e,factor:t}}}class uh{constructor(e){this.airportNames=e}findAvailableAirport(e){return[...e.owner.buildings].find(e=>e.dockTrait&&this.airportNames.includes(e.name)&&0<e.dockTrait.getAvailableDockCount())}}class dh{setParent(e){this.parent=e}getParent(){return this.parent}[Lr.onTick](s,r){if(this.parent&&s.attackTrait&&s.primaryWeapon){let e=this.parent.attackTrait?.currentTarget,t=s.unitOrderTrait.getCurrentTask(),i=new Cs(r.map.tileOccupation);var a=this.parent.armedTrait?.getWeapons().find(e=>e.rules.spawner);s.ammo&&!(e&&s.attackTrait.currentTarget?e.equals(s.attackTrait.currentTarget):e===s.attackTrait.currentTarget||!e&&this.parent.isUnit()&&(this.parent.unitOrderTrait.getCurrentTask()instanceof Sa||this.parent.unitOrderTrait.getCurrentTask()instanceof po))&&(!e||a&&i.isInWeaponRange(this.parent,e.obj??e.tile,a,r.rules))?e&&s.primaryWeapon.targeting.canTarget(e.obj,e.tile,r,!0,!1)?!t||t instanceof Sa?(s.unitOrderTrait.cancelAllTasks(),s.unitOrderTrait.addTask(s.attackTrait.createAttackTask(r,e.obj,e.tile,s.primaryWeapon,{force:!0}))):s.attackTrait.attackState!==yn.Idle&&t.requestTargetUpdate(e):t?t instanceof Sa||t.cancel():this.tryMoveToParent(s,this.parent,r):this.tryMoveToParent(s,this.parent,r)}}tryMoveToParent(t,i,s){if(t.tile!==i.tile){let e=t.unitOrderTrait.getCurrentTask();e?e instanceof Sa&&e.updateTarget(i.tile,!!i.isUnit()&&i.onBridge):t.unitOrderTrait.addTask(new Sa(s,i.tile,!!i.isUnit()&&i.onBridge,{closeEnoughTiles:0,strictCloseEnough:!0}))}}}class ph{setWarhead(e){return this.warhead=e,this}setDamage(e){return this.damage=e,this}setLauncher(e){return this.launcher=e,this}[Wr.onDestroy](e,t){this.warhead&&this.damage&&this.launcher&&this.warhead.detonate(t,this.damage,e.tile,e.tileElevation,e.position.worldPosition,e.zone,ra.None,t.createTarget(void 0,e.tile),{player:e.owner,obj:this.launcher,weapon:void 0},!1,!1,void 0)}dispose(){this.launcher=void 0}}class gh extends Ba{constructor(e,t,i){super(Bt.Aircraft,e,t,i),this.pitch=0,this.yaw=0,this.roll=0,this.onBridge=!1,this.zone=bs.Ground,this.crateBonuses=new Ma}get direction(){return this.yaw}set direction(e){this.yaw=e}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,s,r){let a=new this(e,t,i);return a.rules.airportBound&&a.rules.dock.length&&(a.airportBoundTrait=new uh(a.rules.dock),a.traits.add(a.airportBoundTrait)),a.rules.missileSpawn||(a.crashableTrait=new Pa(a),a.traits.add(a.crashableTrait)),a.rules.spawned&&(a.rules.missileSpawn?(a.missileSpawnTrait=new ph,a.traits.add(a.missileSpawnTrait)):(a.spawnLinkTrait=new dh,a.traits.add(a.spawnLinkTrait))),a.moveTrait=new _a(a,r),a.traits.add(a.moveTrait),t.dock.length&&a.traits.add(new wo),t.landable&&e!==s.general.paradrop.paradropPlane||a.traits.add(new Ua),t.parasiteable&&(a.parasiteableTrait=new rh(a),a.traits.add(a.parasiteableTrait)),a}isUnit(){return!0}isAircraft(){return!0}}class mh{constructor(e){this.gameObject=e,this.orders=[],this.queuedOrders=new Set,this.tasks=[],this.taskRunner=new lo}[Lr.onTick](i,e){if(i.isSpawned){var s=this.hasTasks(),t=this.tasks.find(e=>!e.isCancelling());s&&this.taskRunner.tick(this.tasks,i);var r,a=this.orders.length;if(a&&(!s||!t)){let e,t=!1;for(;e=this.orders[0];)if(e.isValid()&&e.isAllowed()&&((r=e.process())&&(this.queuedOrders.has(e)&&(this.tasks.push(new $s(5)),this.tasks.push(new ga(()=>{i.resetGuardModeToIdle()}))),this.tasks.push(...r),s||this.taskRunner.tick(this.tasks,i)),t=!0),this.orders.shift(),this.queuedOrders.delete(e),this.waypointPath&&(this.currentWaypoint?(this.cleanupWaypoint(this.currentWaypoint,this.waypointPath),this.currentWaypoint=this.currentWaypoint?.next):this.currentWaypoint=this.waypointPath.waypoints[0],this.currentWaypoint||this.cleanupWaypointPath()),t)break}!a&&!s&&this.waypointPath&&this.currentWaypoint&&(this.cleanupWaypoint(this.currentWaypoint,this.waypointPath),this.cleanupWaypointPath());let e=t;for(;e?.useChildTargetLines;){var n=e.children.find(e=>!e.isCancelling());if(!n)break;e=n}this.targetLinesTask!==e&&(this.targetLinesTask=e,this.targetLinesConfig=e?.getTargetLinesConfig(this.gameObject))}}[Zr.onChange](){this.clearOrders(),this.cancelAllTasks()}[Ur.onBeforeTeleport](e,t,i,s){i&&!s&&(this.clearOrders(),this.tasks.length=0)}addOrder(t,e=!1){!1!==t.onAdd(this.tasks,e)?(e||(this.clearOrders(),this.tasks=this.tasks.filter(e=>e.status!==Ls.NotStarted),this.tasks.forEach(e=>e.cancel())),this.orders.push(t),e&&this.queuedOrders.add(t),this.gameObject.traits.filter(Cn).forEach(e=>{e[Cn.onPush](this.gameObject,t.orderType)})):this.targetLinesTask=void 0}clearOrders(){this.orders.length=0,this.queuedOrders.clear(),this.currentWaypoint&&this.waypointPath&&this.cleanupWaypoint(this.currentWaypoint,this.waypointPath),this.cleanupWaypointPath(),this.gameObject.resetGuardModeToIdle()}unmarkNextQueuedOrder(){this.orders.length&&this.queuedOrders.delete(this.orders[0])}hasTasks(){return!!this.tasks.length}isIdle(){return!this.orders.length&&!this.tasks.length}getCurrentTask(){return this.tasks[0]}cancelAllTasks(){this.tasks.forEach(e=>e.cancel())}addTask(e){this.tasks.push(e)}addTasks(...e){e.forEach(e=>this.addTask(e))}addTaskToFront(e){this.tasks.unshift(e)}addTaskNext(e){this.tasks.splice(1,0,e)}getTasks(){return[...this.tasks]}dispose(){this.clearOrders(),this.tasks.length=0,this.gameObject=void 0}cleanupWaypointPath(){this.waypointPath&&(this.waypointPath.units.splice(this.waypointPath.units.indexOf(this.gameObject),1),this.waypointPath.units.length||(this.waypointPath.waypoints.forEach(e=>e.next=void 0),this.waypointPath.waypoints.length=0),this.waypointPath=void 0),this.currentWaypoint=void 0}cleanupWaypoint(t,e){if(!e.units.find(e=>e!==this.gameObject&&(e.unitOrderTrait.currentWaypoint??e.unitOrderTrait.waypointPath?.waypoints[0])===t)&&!e.waypoints.find(e=>e.next===t)){var i=e.waypoints.indexOf(t);if(-1===i)throw new Error("Given waypoint not found in waypoint path");e.waypoints.splice(i,1)}}}const fh=[[0,0,0,0],[0,0,1,1],[1,0,0,1],[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,0,0],[0,1,0,0],[0,0,1,0],[1,0,1,1],[1,1,0,1],[1,1,1,0],[0,1,1,1],[1,0,1,2],[2,1,0,1],[1,2,1,0],[0,1,2,1],[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]];class yh{constructor(e,t){this.tiles=e,this.tileOccupation=t,this._worldPosition=new ss,this._tileOffset=new Ss,this._centerOffset=new Ss,this.desiredSubCell=0,this._tileElevation=0,this._onPositionChange=new ro}get onPositionChange(){return this._onPositionChange.asEvent()}get worldPosition(){return this._worldPosition}get tile(){return this._tile}set tile(e){var t=!!this._tile&&e!==this._tile;(this._tile=e)&&(this.updateWorldPosition(e,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:t}))}get tileElevation(){return void 0===this._tileElevation?(void 0===this._computedTileElevation&&(this._computedTileElevation=this.computeTileElevationFromWorldPos()),this._computedTileElevation):this._tileElevation}set tileElevation(e){this._absoluteElevation=void 0,this._tileElevation=e,this._tile&&(this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:!1}))}get subCell(){if(!this._tileOffset.x&&!this._tileOffset.y)return 0;var e=Math.sign(this._tileOffset.x/ks.LEPTONS_PER_TILE-.5),t=Math.sign(this._tileOffset.y/ks.LEPTONS_PER_TILE-.5);return e&&t?t+1+(e+1)/2+1:0}set subCell(e){this._tileOffset=this.computeSubCellOffset(e),this.desiredSubCell=e,this._tile&&(this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:!1}))}getTileOffset(){return this._tileOffset.clone()}setTileOffset(e){this._tileOffset.copy(e),this._tile&&(this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:!1}))}setCenterOffset(e){this._centerOffset.copy(e),this._tile&&(this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:!1}))}getMapPosition(){if(this._tile)return new Ss(this._tile.rx*ks.LEPTONS_PER_TILE+this._tileOffset.x+this._centerOffset.x,this._tile.ry*ks.LEPTONS_PER_TILE+this._tileOffset.y+this._centerOffset.y)}getBridgeBelow(){return this._tile?.onBridgeLandType?this.tileOccupation.getBridgeOnTile(this._tile):void 0}moveToTileCell(e,t=0){if(!this._tile)throw new Error("Tile is not set");var i=e!==this._tile;this._tile=e,this._tileOffset=this.computeSubCellOffset(t),this.desiredSubCell=t,this.updateWorldPosition(e,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:i})}moveToTileCoords(e,t,i=!1){var s=Math.floor(e),r=Math.floor(t),a=!this._tile||this._tile.rx!==s||this._tile.ry!==r;if(a){let e=this.tiles.getByMapCoords(s,r);if(!e){if(!i)throw new RangeError(`Attempted move to a non-existent tile: [${s},${r}]`);e=this.tiles.getPlaceholderTile(s,r)}this._tile=e}this._tileOffset.set((e-s)*ks.LEPTONS_PER_TILE,(t-r)*ks.LEPTONS_PER_TILE),this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:a})}moveToLeptons(e,t=!1){this.moveToTileCoords(e.x/ks.LEPTONS_PER_TILE,e.y/ks.LEPTONS_PER_TILE,t)}moveByLeptons(e,t,i=!1){if(!this._tile)throw new Error("Tile is not set");this.moveToTileCoords(this._tile.rx+(this._tileOffset.x+e)/ks.LEPTONS_PER_TILE,this._tile.ry+(this._tileOffset.y+t)/ks.LEPTONS_PER_TILE,i)}moveByLeptons3(e,t=!1){var i=this._worldPosition.y;this.moveByLeptons(e.x,e.z,t),this.setAbsoluteElevationWorld(i+e.y)}setAbsoluteElevationWorld(e){this._absoluteElevation=e,this._tileElevation=void 0,this._tile&&(this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:!1}))}computeSubCellOffset(e){let t={width:0,height:0};var i;e&&(i=(e-1)%2*2-1,s=2*Math.floor((e-1)/2)-1,t={width:i*ks.LEPTONS_PER_TILE/4,height:s*ks.LEPTONS_PER_TILE/4});var s=ks.LEPTONS_PER_TILE/2;return new Ss(s+t.width,s+t.height)}interpolateRampHeight(e,t,i){var s=fh[i],r=s[1],i=s[0];return r*(1-e)*(1-t)+s[2]*e*(1-t)+i*(1-e)*t+s[3]*e*t}updateWorldPosition(t,i){var e=i.x+this._centerOffset.x,s=i.y+this._centerOffset.y,r=e/ks.LEPTONS_PER_TILE,i=s/ks.LEPTONS_PER_TILE;let a;if(void 0!==this._tileElevation){let e=0;0!==t.rampType&&(e=this.interpolateRampHeight(r,i,t.rampType)),a=ks.tileHeightToWorld(t.z+e+this._tileElevation)}else a=this._absoluteElevation;this._worldPosition.set(t.rx*ks.LEPTONS_PER_TILE+e,a,t.ry*ks.LEPTONS_PER_TILE+s),void 0===this._tileElevation&&(this._computedTileElevation=this.computeTileElevationFromWorldPos())}computeTileElevationFromWorldPos(){if(!this._tile)return 0;var e=(t=ks.worldToTileHeight(this._worldPosition.y),i=14,t&&(i=10**i,Math.round(t*i)/i)),t=(this._tileOffset.x+this._centerOffset.x)/ks.LEPTONS_PER_TILE,i=(this._tileOffset.y+this._centerOffset.y)/ks.LEPTONS_PER_TILE;let s=0;return 0!==this._tile.rampType&&(s=this.interpolateRampHeight(t,i,this._tile.rampType)),e-this._tile.z-s}clone(){let e=new yh(this.tiles,this.tileOccupation);return e._worldPosition=this._worldPosition.clone(),e._tile=this._tile,e._tileOffset=this._tileOffset.clone(),e._centerOffset=this._centerOffset.clone(),e._tileElevation=this._tileElevation,e._absoluteElevation=this._absoluteElevation,e._computedTileElevation=this._computedTileElevation,e}}class wh{constructor(e){this.tileOccupation=e}checkCollisions(e,t,i){var s,r=e.tile;let a,n,o;for(s of this.tileOccupation.getObjectsOnTile(r))s.isOverlay()&&s.isBridge()&&(a=s),s.isOverlay()&&s.wallTrait&&(o=s),s.isTechno()&&!s.isDestroyed&&(n=s);if(i.walls){if(e.tileElevation<=2&&r.landType===Kt.Wall)return{type:ra.Wall,target:o};if(i.units&&n?.tile===r&&(!n.isUnit()||n.zone===bs.Ground)&&e.tileElevation<=1.1&&i.units(n.owner))return{type:ra.Wall,target:n}}if(i.shore&&r.landType!==Kt.Water)return{type:ra.Shore};if(i.ground&&e.tileElevation<0)return{type:ra.Ground};var h=e.tileElevation+r.z,l=t.tileElevation+t.tile.z;if(a?.isHighBridge()){var c=a.tile.z+a.tileElevation;if(c<l&&h<=c||l<c&&c-1<=h)return l<c?{type:ra.UnderBridge,target:a}:{type:ra.OnBridge,target:a}}else if(a?.isLowBridge()&&i.shore)return{type:ra.UnderBridge,target:a};if(i.cliffs){t=r.z-t.tile.z;if(e.tileElevation<0&&4<=t)return{type:ra.Cliff}}return{type:ra.None}}computeDetonationZone(e,t,i){let s=this.tileOccupation.getBridgeOnTile(e);return i===ra.None&&t>1.5+(s?.tileElevation??0)?bs.Air:s&&1.5<t||e.terrainType!==Yt.Water||s?.isLowBridge()?bs.Ground:bs.Water}}(r=En=En||{})[r.Travel=0]="Travel",r[r.Impact=1]="Impact",r[r.Detonation=2]="Detonation";class Th extends Aa{constructor(e,t,i,s){super(Bt.Projectile,e,t,i),this.tileOccupation=s,this.state=En.Travel,this.detonationTimer=0,this.collisionType=ra.None,this.direction=0,this.zone=bs.Air,this.isShrapnel=!1,this.isNuke=!1,this.baseDamageMultiplier=1,this.veteranDamageMult=1,this.snapToTarget=!1,this.targetLockLost=!1,this.limboTravelTicks=0,this.homingTravelDistance=0,this.homingTravelTicks=0,this.velocity=new ss,this.sonicVisitedObjects=new Map,this.collisionHelper=new wh(s)}get fromObject(){return this._fromObject}set fromObject(e){(this._fromObject=e)&&e.veteranTrait&&!e.isDestroyed&&(this.veteranDamageMult=e.veteranTrait.getVeteranDamageMultiplier())}get rot(){return this.fromWeapon.rules.isSonic?Ii.iniRotToDegsPerTick(this.iniRot):this.rules.rot}get iniRot(){return this.fromWeapon.rules.isSonic?10:this.rules.iniRot}static factory(e,t,i,s){return new this(e,t,i,s)}onSpawn(a){var e;if(super.onSpawn(a),this.initialSelfPosition=this.position.worldPosition.clone(),!this.target.obj||this.fromWeapon.type===oi.DeathWeapon||this.fromWeapon.rules.limboLaunch||!this.isHoming()&&this.fromWeapon.speed===Number.POSITIVE_INFINITY||this.rules.inaccurate||this.rules.arcing||this.rules.flakScatter||0<(e=this.computeBaseDamage(a))&&(e=this.fromWeapon.warhead.computeDamage(e,this.target.obj),this.target.obj.healthTrait?.projectDamage(e)),a.afterTick(()=>{let e=new Cs(this.tileOccupation);var t=e.distance2(this.target.getWorldCoords(),this)/ks.LEPTONS_PER_TILE;this.initialTileDistToTarget=t,this.maxSpeed=this.computeMaxSpeed(this.fromWeapon.speed,t,a.rules.audioVisual.gravity)}),this.isHoming()){if(1===this.iniRot&&(this.homingMoveDir=this.target.getWorldCoords().clone().sub(this.position.worldPosition)),this.fromObject?.isAircraft()&&this.rules.isAntiGround&&!this.rules.isAntiAir){let e=this.target.obj;!e?.isVehicle()||e.isDestroyed||e.veteranLevel!==Jr.Elite||e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new va(a))}}else if(this.rules.vertical){let e=this.position.clone();e.tileElevation=this.fromWeapon.warhead.rules.nukeMaker?ks.worldToTileHeight(this.fromWeapon.projectileRules.detonationAltitude):0,this.aimPoint=e.worldPosition.clone()}else{let r=this.target.getWorldCoords().clone();a.afterTick(()=>{let e=this.target.getWorldCoords().clone().sub(r);var t=e.length()>ks.LEPTONS_PER_TILE;let i=t?r:this.target.obj?.isUnit()&&this.target.obj.moveTrait.velocity.length()&&isFinite(this.maxSpeed)?this.computeAimPointVersusMovingTarget(this.target.obj,this.maxSpeed,this.position.worldPosition,a.map):this.target.getWorldCoords().clone();this.aimPoint=i,this.snapToTarget=!t&&isFinite(this.maxSpeed)&&!this.fromWeapon.warhead.rules.sonic,(this.rules.inaccurate||this.rules.flakScatter)&&(this.adjustAimForBallisticScatter(a,i),this.snapToTarget=!1),!t&&this.rules.arcing&&(this.rules.inaccurate?(this.overshootTiles=this.calculateInaccurateBallisticOvershoot(a),this.snapToTarget=!1):this.target.obj?.isVehicle()&&this.target.obj.moveTrait.isMoving()&&(this.overshootTiles=this.calculateBallisticOvershootVsMoving(a,this.target.obj),this.overshootTiles&&(this.snapToTarget=!1)));let s=i.clone().sub(this.position.worldPosition);s.length()<this.fromWeapon.speed&&this.update(a)})}}adjustAimForBallisticScatter(e,t){let i=e.rules.combatDamage.ballisticScatter,s;s=this.rules.flakScatter?(this.rules.inviso&&(i*=2),e.generateRandom()*i):i/2+e.generateRandom()*(i/2);let r=s*ks.LEPTONS_PER_TILE;this.rules.flakScatter&&(n=t.clone().sub(this.initialSelfPosition).length(),r*=n/(this.fromWeapon.range*ks.LEPTONS_PER_TILE));var a=rr(new Ss(r,0),e.generateRandomInt(0,360)),n=ks.vecWorldToGround(t).add(a).multiplyScalar(1/ks.LEPTONS_PER_TILE).floor();e.map.tiles.getByMapCoords(n.x,n.y)&&t.add(new ss(a.x,0,a.y))}calculateBallisticOvershootVsMoving(e,t){let i=this.target.getWorldCoords().clone().sub(this.initialSelfPosition);var s=or(ks.vecWorldToGround(i),ks.vecWorldToGround(t.moveTrait.velocity)),t=(90<s?180-s:s)/90,s=i.length()/ks.LEPTONS_PER_TILE,t=t*s/5;return e.generateRandom()<=t?2*Math.min(1,s/5):0}calculateInaccurateBallisticOvershoot(e){return e.generateRandom()<=.5?2:0}update(o){if(void 0!==this.maxSpeed)if(super.update(o),this.state!==En.Impact){var r=this.velocity.clone(),h=this.position.clone();if(this.velocity.set(0,0,0),this.fromWeapon.rules.limboLaunch){if(!this.fromObject)throw new Error("Limbo launch projectile must be fired from a unit");if(this.fromObject.isDestroyed)return void o.destroyObject(this)}var l=this.updateSpeed(this.maxSpeed);this.speed=l;let n=this.target.getWorldCoords();if(this.lastTargetLockPosition&&(this.targetLockLost||n.clone().sub(this.lastTargetLockPosition).length()>=ks.LEPTONS_PER_TILE)?(n=this.lastTargetLockPosition,this.targetLockLost=!0):this.lastTargetLockPosition=n.clone(),this.isHoming()){if(this.target.obj?.isUnit()&&(this.target.obj.isDestroyed||this.target.obj.isCrashing||!this.target.obj.isSpawned)&&(this.fromWeapon.rules.limboLaunch||this.homingTravelDistance>=2*ks.LEPTONS_PER_TILE))return void this.detonate(o);if(this.homingMoveDir||(u=Tr.toMapCoords(this.direction),this.homingMoveDir=new ss(u.x,0,u.y),this.fromObject?.isAircraft()&&(this.homingMoveDir.y=-9999999,this.homingMoveDir.normalize())),this.fromWeapon.rules.limboLaunch){if(!this.targetLockLost){if(10<this.limboTravelTicks)return this.position.moveToLeptons(this.target.obj.position.getMapPosition()),this.position.tileElevation=this.target.obj.position.tileElevation,void this.detonate(o);this.limboTravelTicks++}}else if(!this.isInHomingRange(n,o))return void this.detonate(o);let e=new Cs(this.tileOccupation);var c=Math.floor(e.distance2(n,this)/ks.LEPTONS_PER_TILE),u=2<c&&1<this.iniRot;let t=n.clone().sub(this.position.worldPosition),i=0;this.homingTravelTicks<this.rules.courseLockDuration||(u?(pr(this.homingMoveDir,new ss(t.x,this.homingMoveDir.y,t.z),this.rot),this.rules.level||(c=W(Math.floor(this.initialTileDistToTarget)-1,0,2)+W(c-2,0,3),d=this.tileOccupation.getBridgeOnTile(this.tile)?.tileElevation??0,(d=c-(this.position.tileElevation-d))&&(p=.25+6/this.iniRot*.1,i=ks.tileHeightToWorld(Math.sign(d)*Math.min(Math.abs(d),p))))):pr(this.homingMoveDir,t,this.rot)),this.direction=Tr.fromMapCoords(new Ss(this.homingMoveDir.x,this.homingMoveDir.z));var d=t.length(),p=Math.min(d,l);this.homingTravelDistance+=p,this.homingTravelTicks++;let s=!1,r=ra.None,a;if(1<=p){let e=this.homingMoveDir.clone().setLength(p);i&&(e.y+=i),p===l&&this.velocity.copy(e);var g=e.clone().add(this.position.worldPosition);o.map.mapBounds.isWithinHardBounds(g)?this.position.moveByLeptons3(e):s=!0;var m=this.checkObstacles(h,o);r=m.type,a=m.target,(r||p<l)&&(s=!0)}else this.position.moveByLeptons3(t),s=!0;if(s){if(a&&r===ra.Wall){let e=a.position.worldPosition;this.position.moveByLeptons3(e.clone().sub(this.position.worldPosition))}this.collisionType=r,this.detonate(o,r)}}else{let t=this.aimPoint.clone().sub(this.position.worldPosition);this.rules.vertical||(this.direction=Tr.fromMapCoords(new Ss(t.x,t.z))),this.rules.arcing&&(t.y=0);d=Math.min(t.length(),l);if(t.setLength(d),this.rules.arcing){let e=ks.vecWorldToGround(this.position.worldPosition.clone().sub(this.initialSelfPosition).add(t));var g=this.aimPoint.clone().sub(this.initialSelfPosition),a=e.length(),m=ks.vecWorldToGround(g).length(),p=g.y,g=o.rules.audioVisual.gravity;t.y=(p/m*l+g/2*m/l)*a/l-g*(a/l)*(a/l)/2+this.initialSelfPosition.y-this.position.worldPosition.y}let e=!1;a=t.clone().add(this.position.worldPosition);o.map.isWithinHardBounds(a)?this.position.moveByLeptons3(t):e=!0;let i=ra.None,s;if(1<=d?(d!==l&&!this.overshootTiles||this.velocity.copy(t),h=this.checkObstacles(h,o),i=h.type,s=h.target,(i||d<l)&&(e=!0)):e=!0,e){if(i){if(s&&i===ra.Wall){let e=s.isBuilding()?ks.tile3dToWorld(s.tile.rx+.5,s.tile.ry+.5,s.tile.z):s.position.worldPosition;this.position.moveByLeptons3(e.clone().sub(this.position.worldPosition))}}else if(this.overshootTiles){var f=ks.vecWorldToGround(r).setLength(this.overshootTiles*ks.LEPTONS_PER_TILE);if(rr(f,o.generateRandomInt(-45,45)),a=ks.vecGroundToWorld(f).add(this.position.worldPosition),!o.map.isWithinHardBounds(a))return void o.unspawnObject(this);this.position.moveByLeptons(f.x,f.y)}else if(this.snapToTarget&&!this.targetLockLost){if(!o.map.isWithinHardBounds(n))return void o.unspawnObject(this);this.position.moveByLeptons3(n.clone().sub(this.position.worldPosition))}this.collisionType=i,this.isNuke?(this.state=En.Impact,this.detonationTimer=2.5*Fs.BASE_TICKS_PER_SECOND):this.detonate(o,i)}}let e=this.fromWeapon.warhead;if(e.rules.sonic){var t,i,f=11/30*ks.LEPTONS_PER_TILE,f=this.position.worldPosition.clone().add(this.velocity.clone().setLength(f)),f=ks.vecWorldToGround(f).multiplyScalar(1/ks.LEPTONS_PER_TILE).floor(),s=o.map.tiles.getByMapCoords(f.x,f.y);if(s&&s!==this.fromObject?.tile){var y,w=o.map.getTileZone(s);for(y of o.map.getGroundObjectsOnTile(s))if((!y.isUnit()||!y.onBridge)&&(!y.isTechno()||!y.rules.typeImmune||y.owner!==this.fromPlayer||y.name!==this.fromObject?.name)&&(!y.isAircraft()||!y.rules.spawned)&&e.canDamage(y,s,w)){let e=this.sonicVisitedObjects.get(y)??new Set;e.add(s),this.sonicVisitedObjects.set(y,e)}}for([t,i]of this.sonicVisitedObjects)for(var T of i)o.map.tileOccupation.isTileOccupiedBy(T,t)&&t.isSpawned&&(T=this.fromWeapon.rules.ambientDamage*this.veteranDamageMult*this.baseDamageMultiplier,T=e.computeDamage(T,t),e.inflictDamage(T,t,{player:this.fromPlayer,weapon:this.fromWeapon,obj:this.fromObject},o,t!==this.target.obj))}}else 0<this.detonationTimer?this.detonationTimer--:this.detonate(o,this.collisionType)}isHoming(){return!!this.rot&&!this.rules.arcing}isInHomingRange(t,i){let s=!0,r=this.target.obj;if(r?.isUnit()&&this.fromObject){let e=new Cs(this.tileOccupation);i=e.computeWeaponRangeVsTarget(this.fromObject,r,this.fromWeapon,i.rules).range;this.fromWeapon.rules.limboLaunch?s=e.isInRange3(this.initialSelfPosition,t,0,i+.5):(t=r.moveTrait.velocity.length())&&(this.fromObject.rules.movementZone===si.Fly?5<this.speed/t&&(s=e.isInRange2(this.initialSelfPosition,this.position.worldPosition,0,i)):isFinite(this.fromWeapon.speed)&&3.5<this.fromWeapon.speed/r.rules.speed&&(s=e.isInRange3(this.initialSelfPosition,this.position.worldPosition,0,i)))}return s}updateSpeed(e){let t;return t=this.isHoming()||this.rules.vertical?void 0===this.speed?Math.min(e,this.rules.acceleration):Math.min(e,this.speed+this.rules.acceleration):e,t}computeMaxSpeed(e,t,i){let s=e;return this.rules.arcing&&(s*=(1+i/6)/2,t=Math.floor(t),s*=t<=8?1:1+t/8*.5),this.fromWeapon.warhead.rules.sonic&&(s=Math.ceil(t*ks.LEPTONS_PER_TILE/21)),s}checkObstacles(e,t){return this.fromWeapon.rules.limboLaunch?{type:ra.None}:this.collisionHelper.checkCollisions(this.position,e,{cliffs:this.rules.subjectToCliffs,ground:this.isHoming(),shore:this.rules.level,walls:this.rules.subjectToWalls,units:!this.rules.inaccurate&&(e=>this.fromPlayer!==e&&!t.alliances.areAllied(this.fromPlayer,e))})}computeBaseDamage(e){var t=this.fromWeapon,i=t.warhead;let s=t.rules.damage;t.type===oi.DeathWeapon&&i.rules.ivanBomb&&(s=e.rules.combatDamage.ivanDamage);let r=s*this.baseDamageMultiplier;return t.type===oi.DeathWeapon&&this.fromObject&&(r*=this.fromObject.rules.deathWeaponDamageModifier),r*=this.veteranDamageMult,r}detonate(n,e=ra.None){var i=this.fromWeapon;let s=i.warhead;var t,r=this.zone=this.collisionHelper.computeDetonationZone(this.tile,this.tileElevation,e);let o=this.tile;i.type===oi.DeathWeapon&&s.rules.ivanBomb&&(s=new Qa(n.rules.getWarhead(n.rules.combatDamage.ivanWarhead)));let a=this.computeBaseDamage(n);n.destroyObject(this),this.state=En.Detonation;let h=this.target.obj,l=!1;if(s.rules.parasite&&h?.isUnit()&&o===h.tile&&s.canDamage(h,o,r))if(h.isInfantry())a=Number.POSITIVE_INFINITY;else if(h.parasiteableTrait&&this.fromObject?.isUnit()){if(!(this.fromWeapon instanceof en))throw new Error("Projectile with parasite warhead must have a weapon reference");h.parasiteableTrait.infest(this.fromObject,this.fromWeapon),l=!0}let c=!0;if(l&&(c=!1),s.rules.sonic&&(c=!1),s.rules.ivanBomb&&(c=!1,!h?.isTechno()||!h.tntChargeTrait||h.tntChargeTrait.hasCharge()||h.isDestroyed||h.warpedOutTrait.isInvulnerable()||(t=n.rules.combatDamage.ivanTimedDelay,h.tntChargeTrait.setCharge(t,n.currentTick,{player:this.fromPlayer}))),s.rules.bombDisarm&&(c=!1,h?.isTechno()&&h.tntChargeTrait?.hasCharge()&&!h.isDestroyed&&h.tntChargeTrait.removeCharge()),s.rules.mindControl&&(c=!1,this.fromObject&&!this.fromObject.isDestroyed&&h?.isTechno()&&h.mindControllableTrait&&!h.mindControllableTrait?.isActive()&&!n.areFriendly(h,this.fromObject)&&s.canDamage(h,o,r)&&!h.invulnerableTrait.isActive()&&this.fromObject.mindControllerTrait.control(h,n)),s.rules.temporal&&(c=!1,this.fromObject&&!this.fromObject.isDestroyed&&h?.isTechno()&&s.canDamage(h,o,r)&&!h.invulnerableTrait.isActive()&&(s.inflictDamage(0,h,{player:this.fromPlayer,weapon:i,obj:this.fromObject},n),this.fromObject.temporalTrait.updateTarget(h,i,n))),s.rules.makesDisguise&&(c=!1,this.fromObject&&!this.fromObject.isDestroyed&&(this.fromObject.isInfantry()||this.fromObject.isVehicle())&&h?.isUnit()&&h.type===this.fromObject.type&&this.fromObject.disguiseTrait?.disguiseAs(h,this.fromObject,n)),s.rules.electricAssault&&(this.fromObject?.isUnit()&&!this.fromObject.isDestroyed&&h?.isBuilding()&&!h.isDestroyed&&h.overpoweredTrait&&h.owner===this.fromPlayer&&h.overpoweredTrait.chargeFrom(this.fromObject),c=!1),c&&s.detonate(n,a,o,this.tileElevation,this.position.worldPosition,r,e,this.target,{player:this.fromPlayer,weapon:i,obj:this.fromObject},this.isShrapnel,!1,this.impactAnim),s.rules.nukeMaker){let e;e=this.fromObject?(u=en.factory(en.NUKE_PAYLOAD_NAME,oi.Primary,this.fromObject,n.rules),n.createProjectile(u.projectileRules.name,this.fromObject,u,this.target,!1)):n.createLooseProjectile(en.NUKE_PAYLOAD_NAME,this.fromPlayer,this.target),e.isNuke=!0,e.impactAnim="NUKEBALL";var u=this.target.tile;e.position.moveToTileCoords(u.rx+.5,u.ry+.5),e.position.tileElevation=this.position.tileElevation,n.spawnObject(e,u)}if(this.rules.shrapnelCount&&this.rules.shrapnelWeapon&&((this.target.obj?!this.target.obj.isBuilding():n.map.getGroundObjectsOnTile(this.target.tile).some(e=>e.isTerrain())&&!i.projectileRules.isAntiAir)||this.isShrapnel)){let t=n.rules.getWeapon(this.rules.shrapnelWeapon);var d,p=n.rules.getProjectile(t.projectile);let i=this.rules.shrapnelCount,s=new Cs(n.map.tileOccupation),e=new js(n.map.tiles,n.map.mapBounds,o,{width:1,height:1},1,t.range,e=>s.isInTileRange(o,e,t.minimumRange,t.range)),r=new Set;for(;0<Math.floor(i);){var g,m=e.getNextTile();if(!m)break;for(g of n.map.tileOccupation.getObjectsOnTileByLayer(m,p.isAntiAir?Tn.Air:Tn.Ground).filter(e=>n.isValidTarget(e)&&(e.isTerrain()||e.isTechno()&&e.owner!==this.fromPlayer&&!n.alliances.areAllied(e.owner,this.fromPlayer)&&!(e.isInfantry()&&e.stance===Rs.Paradrop))))if(!r.has(g)&&(r.add(g),i=Math.max(0,i-1-(g.isTechno()?.5:0)),Math.floor(i)<=0))break}for(d of r){var f=n.createTarget(d.isTerrain()?void 0:d,d.tile);this.createShrapnel(n,f,t.name)}i=Math.floor(i);let a=new wa(n.map.tiles,n.map.mapBounds,o,t.range,n,e=>s.isInTileRange(o,e,t.minimumRange,t.range));for(let e=0;e<i;e++){var y=a.getNextTile();if(!y)break;y=n.createTarget(void 0,y);this.createShrapnel(n,y,t.name)}}if(i.rules.limboLaunch&&!l&&this.fromObject?.isUnit()){let r=this.fromObject;s.rules.parasite&&(this.target.obj.isVehicle()||this.target.obj?.isAircraft())&&this.target.obj.parasiteableTrait&&(this.target.obj.parasiteableTrait.beingBoarded=!1);let t,a;i=r.rules.movementZone===si.Fly;if(i)t=o,a=!1;else{let i=this.target.obj.isUnit()&&this.target.obj.tile.onBridgeLandType&&!this.target.obj.onBridge?void 0:n.map.tileOccupation.getBridgeOnTile(o),s=new qs(n.map),e=new js(n.map.tiles,n.map.mapBounds,o,{width:1,height:1},0,1,e=>{var t=n.map.tileOccupation.getBridgeOnTile(e);return 0<n.map.terrain.getPassableSpeed(e,r.rules.speedType,!!t)&&s.isEligibleTile(e,t,i,o)&&(e===o||!n.map.terrain.findObstacles({tile:e,onBridge:i},r).length)});t=e.getNextTile(),a=!!t?.onBridgeLandType}t?(!i&&this.target.obj.isUnit()&&(r.onBridge=a,r.position.tileElevation=a?n.map.tileOccupation.getBridgeOnTile(t)?.tileElevation??0:0),n.unlimboObject(r,t),r.isInfantry()&&(r.position.subCell=this.target.obj.position.subCell),r.direction=this.direction):r.owner.removeOwnedObject(r)}}createShrapnel(e,t,i){let s=e.createLooseProjectile(i,this.fromPlayer,t);s.isShrapnel=!0,s.veteranDamageMult=this.veteranDamageMult,s.position.moveToLeptons(this.position.getMapPosition()),s.position.tileElevation=this.position.tileElevation,e.spawnObject(s,s.position.tile)}computeAimPointVersusMovingTarget(t,i,e,s){let r=t.position.worldPosition,a=r.clone();var n=i,i=t.moveTrait.velocity.length();if(n<3*i)return r.clone();let o=Br.computeInterceptPoint(e,n,r,t.moveTrait.velocity);if(o.length()){let e=o.clone().sub(r);n=e.length(),i=i,n=i?Math.ceil(n/i):0;if(o=r.clone().add(e.setLength(n*i)),s.isWithinHardBounds(o))if(t.zone!==bs.Air){o.multiplyScalar(1/ks.LEPTONS_PER_TILE);let e=t.position.clone();e.moveToTileCoords(o.x,o.z),a=e.worldPosition}else a=o;else a=r}return a.clone()}}(r=Pn=Pn||{})[r.None=0]="None",r[r.PreparingToFire=1]="PreparingToFire",r[r.FiringUp=2]="FiringUp",r[r.Firing=3]="Firing";class bh{constructor(e){this.gameObject=e,this.deployed=!1,this.deployFireDelay=0,this.deployFireState=Pn.None,this.fireUpDelay=0,this.deployFireCount=0}isDeployed(){return this.deployed}setDeployed(t){var e=this.deployed;if((this.deployed=t)!==e){let e=this.gameObject;e.isInfantry()&&(e.stance=t?Rs.Deployed:Rs.None),t?(this.deployFireState=Pn.PreparingToFire,t=this.gameObject.armedTrait?.getDeployFireWeapon(),this.deployWeapon=t?.rules.areaFire?t:void 0,this.deployFireDelay=15+((t===e.primaryWeapon?e.secondaryWeapon:e.primaryWeapon)?.getCooldownTicks()??0),this.deployFireCount=0,this.undeployDelay=this.gameObject.rules.undeployDelay||void 0):(this.deployFireState===Pn.FiringUp&&(e.isFiring=!1),this.deployFireState=Pn.None,this.deployWeapon=void 0)}}toggleDeployed(){this.setDeployed(!this.isDeployed())}[Lr.onTick](e,t){if(void 0!==this.undeployDelay&&(0<this.undeployDelay&&this.undeployDelay--,this.undeployDelay<=0&&[Pn.None,Pn.PreparingToFire].includes(this.deployFireState)))return this.undeployDelay=void 0,void this.setDeployed(!1);if(this.deployWeapon&&this.deployFireState!==Pn.None){if(this.deployFireState===Pn.PreparingToFire){if(0<this.deployFireDelay--||0===e.ammo)return;if(0<this.computeDeployFireCooldown(this.deployWeapon,t))return;this.fireUpDelay=Math.max(1,e.art.fireUp),this.deployFireState=Pn.FiringUp}if(this.deployFireState===Pn.FiringUp){if(e.isFiring=!0,0<this.fireUpDelay--)return;this.deployFireState=Pn.Firing}var i;this.deployFireState===Pn.Firing&&(e.isFiring=!1,i=e.onBridge?t.map.tileOccupation.getBridgeOnTile(e.tile):void 0,this.deployWeapon.fire(t.createTarget(i,e.tile),t),this.deployFireCount++,(this.deployWeapon===e.primaryWeapon?e.secondaryWeapon:e.primaryWeapon)?.resetCooldown(),this.deployWeapon.rules.fireOnce?(this.deployFireState=Pn.None,this.deployWeapon=void 0):this.deployFireState=Pn.PreparingToFire)}}computeDeployFireCooldown(t,i){if(t.rules.radLevel&&t.rules.areaFire){var s=this.gameObject.tile,s=i.mapRadiationTrait.getRadSiteLevel(s);if(!s)return 0;i=i.rules.radiation;let e=Math.max(0,s*i.radDurationMultiple-i.radLevelDelay);return 1===this.deployFireCount&&(i=i.radDurationMultiple*t.rules.radLevel,e=Math.max(0,e-Math.floor(.25*i))),e}return t.getCooldownTicks()}getHash(){return this.deployed?1:0}debugGetState(){return{deployed:this.deployed}}dispose(){this.gameObject=void 0}}(Nn=Nn||{}).onChange=Symbol();class vh{constructor(e,t,i,s,r){this.target=e,this.attacker=t,this.damageHitPoints=i,this.currentHealth=s,this.prevHealth=r,this.type=is.InflictDamage}}(Mn=Mn||{}).onChange=Symbol(),(r=Dn=Dn||{})[r.Green=0]="Green",r[r.Yellow=1]="Yellow",r[r.Red=2]="Red";class Sh{constructor(e,t,i){this.target=e,this.currentHealth=t,this.prevHealth=i,this.type=is.HealthChange}}class kh{constructor(e,t,i,s){this.maxHitPoints=e,this.gameObject=t,this.conditionYellow=i,this.conditionRed=s,this.setHitPoints(e),this.projectedHitPoints=this.hitPoints}get health(){return this._computedHealth}set health(e){this.setHitPoints(0<e?Math.max(1,Math.floor(e*this.maxHitPoints/100)):0),this.projectedHitPoints=this.hitPoints}get level(){return this.health>100*this.conditionYellow?Dn.Green:this.health>100*this.conditionRed?Dn.Yellow:Dn.Red}setHitPoints(e){if(e!==Math.floor(e))throw new Error(`Value ${e} is not an integer`);this.hitPoints=W(e,0,this.maxHitPoints),this._computedHealth=this.hitPoints/this.maxHitPoints*100}getHitPoints(){return this.hitPoints}getProjectedHitPoints(){return this.projectedHitPoints}inflictDamage(t,i,s){var e=this.hitPoints,r=this.health;this.applyHitPoints(e-t,s),e!==this.hitPoints&&0<t&&(this.gameObject.traits.filter(ca).forEach(e=>{e[ca.onDamage](this.gameObject,s,t,i)}),s.events.dispatch(new vh(this.gameObject,i,t,this.health,r)))}healBy(e,i,s){if(e<0)throw new Error(`Can't heal by negative value ${e}`);if(this.hitPoints<this.maxHitPoints){var r=this.hitPoints;this.applyHitPoints(this.hitPoints+e,s),this.projectedHitPoints=this.hitPoints;let t=this.hitPoints-r;this.gameObject.traits.filter(xn).forEach(e=>{e[xn.onHeal]?.(this.gameObject,s,t,i)})}}healToFull(i,s){if(this.hitPoints<this.maxHitPoints){var e=this.hitPoints;this.applyHitPoints(this.maxHitPoints,s),this.projectedHitPoints=this.hitPoints;let t=this.hitPoints-e;this.gameObject.traits.filter(xn).forEach(e=>{e[xn.onHeal]?.(this.gameObject,s,t,i)})}}applyHitPoints(e,t){let i=this.health;this.setHitPoints(e),i!==this.health&&(t.traits.filter(Nn).forEach(e=>{e[Nn.onChange](this.gameObject,t,i)}),this.gameObject.traits.filter(Mn).forEach(e=>{e[Mn.onChange](this.gameObject,t,i)}),t.events.dispatch(new Sh(this.gameObject,this.health,i)))}projectDamage(e){if(e<0)throw new Error("Projected damage must be positive");this.projectedHitPoints=Math.max(-30,this.projectedHitPoints-e)}[Lr.onTick](e,t){t.currentTick%4==0&&(this.projectedHitPoints=Math.min(this.projectedHitPoints+1,this.hitPoints))}getHash(){return this.hitPoints}debugGetState(){return{hitPoints:this.hitPoints}}dispose(){this.gameObject=void 0}}class Oh{constructor(e){this.bridges=e,this.needsImageUpdate=!1,this.dominoHandled=!1}[ca.onDamage](){this.needsImageUpdate=!0}[Lr.onTick](e){this.needsImageUpdate&&(this.needsImageUpdate=!1,this.bridges.handlePieceHealthChange(this.bridges.getPieceAtTile(e.tile)))}[Wr.onDestroy](s,r,a){var e=this.bridges.getPieceAtTile(s.tile);this.dominoHandled||this.bridges.findDominoPieces(e).filter(e=>!e.obj.isDestroyed).forEach(e=>{e.obj.traits.get(Oh).dominoHandled=!0,r.destroyObject(e.obj,a)});let t=r.map.tileOccupation.calculateTilesForGameObject(s.tile,s);t.forEach(e=>{let t=Hi(e.terrainType),i=r.rules.getLandRules(t);r.map.getGroundObjectsOnTile(e).forEach(e=>{e.isUnit()&&e.onBridge&&!e.isDestroyed&&(s.isLowBridge()&&0<i.getSpeedModifier(e.rules.speedType)||e.isInfantry()&&e.stance===Rs.Paradrop?(e.onBridge=!1,e.zone=Os(t)):(e.isInfantry()&&(e.infDeathType=ei.None),r.destroyObject(e,a,!0)))})})}}(r=Rn=Rn||{})[r.Idle=0]="Idle",r[r.Spawning=1]="Spawning";class _h{constructor(e){this.rules=e,this.ticksSinceLastSpawn=0,this.cooldownTicks=Math.floor(1/this.rules.animationProbability),this.status=Rn.Idle}[Lr.onTick](e,t){this.status=Rn.Idle,this.ticksSinceLastSpawn++>this.cooldownTicks&&(this.ticksSinceLastSpawn=0,this.status=Rn.Spawning,this.spawnTiberium(e.tile,t))}spawnTiberium(s,r){for(let i=1;i<=2;i++){let e=new js(r.map.tiles,r.map.mapBounds,s,{width:1,height:1},i,i,e=>qa.canBePlacedOn(e,r.map));var a=e.getNextTile();if(a){var n=un.calculateOverlayId(na.Ore,a);if(void 0===n)throw new Error("Expected an overlayId");let e=r.createObject(Bt.Overlay,r.rules.getOverlayName(n));return e.overlayId=n,e.value=3,void r.spawnObject(e,a)}e=new js(r.map.tiles,r.map.mapBounds,s,{width:1,height:1},i,i,e=>e.landType===Kt.Tiberium);let t;for(;!t;){var o=e.getNextTile();if(!o)break;t=r.map.getObjectsOnTile(o).find(e=>e.isOverlay()&&e.isTiberium()&&e.traits.get(qa).getBailCount()+1<=qa.maxBails)}if(t)return void t.traits.get(qa).spawnBails(1)}}}class Ih{constructor(e=!1){this.freeRepair=e,this.disabled=!0,this.cooldownTicks=0,this.healLeftover=0}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}[Lr.onTick](t,i){if(!this.isDisabled())if(100===t.healthTrait.health&&this.setDisabled(!0),this.cooldownTicks<=0){var s=i.rules.general.repair,r=t.isInfantry()?s.iRepairRate:t.isBuilding()?s.repairRate:s.uRepairRate;this.cooldownTicks+=Fs.BASE_TICKS_PER_SECOND*r*60;var a=t.isInfantry()?s.iRepairStep:s.repairStep,r=this.freeRepair?0:s.repairPercent;let e;r?(s=r*t.purchaseValue/t.healthTrait.maxHitPoints,(r=Math.min(t.owner.credits,Math.max(1,Math.floor(s*a))))?(e=s?r/s:a,t.owner.credits-=r):(e=0,this.setDisabled(!0))):e=a,e&&(e+=this.healLeftover,e=Math.min(t.healthTrait.maxHitPoints-t.healthTrait.getHitPoints(),e),e&&(a=Math.floor(e),this.healLeftover=e-a,a&&t.healthTrait.healBy(a,t,i)))}else this.cooldownTicks--}[Zr.onChange](){this.setDisabled(!0)}}(Ln=Ln||{}).onDestroy=Symbol();class Ch{constructor(e){this.target=e,this.type=is.UnitPromote}}class Ah{constructor(){this.cooldownTicks=0}[Lr.onTick](e,t){100!==e.healthTrait.health&&(this.cooldownTicks<=0?(this.cooldownTicks+=Fs.BASE_TICKS_PER_SECOND*t.rules.general.repair.repairRate*60,e.healthTrait.healBy(1,e,t)):this.cooldownTicks--)}}class Bh{constructor(e,t){this.gameObject=e,this.rules=t,this.specialWeaponIndex=0;t=e.veteranLevel===Jr.Elite;e.rules.weaponCount?(this.selectSpecialWeapon(0,t),this.guardWeaponRangeOverride=this.primaryWeapon?.range):this.selectStandardWeapons(t)}selectStandardWeapons(e=!1){var t=this.gameObject,i=e&&t.rules.elitePrimary||t.rules.primary;i?(r=e?t.art.elitePrimaryFireFlh:t.art.primaryFireFlh,this.primaryWeapon=en.factory(i,oi.Primary,t,this.rules,r)):this.primaryWeapon=void 0;var s,r=e&&t.rules.eliteSecondary||t.rules.secondary;r?(s=e?t.art.eliteSecondaryFireFlh:t.art.secondaryFireFlh,this.secondaryWeapon=en.factory(r,oi.Secondary,t,this.rules,s)):this.secondaryWeapon=void 0,(t.explodes||t.crashableTrait)&&(s=t.rules.deathWeapon||!!t.crashableTrait&&this.secondaryWeapon?.rules.name||this.primaryWeapon?.rules.name||this.rules.combatDamage.deathWeapon,this.deathWeapon=en.factory(s,oi.DeathWeapon,t,this.rules))}selectSpecialWeapon(e,t=!1){let i=this.gameObject;var s=i.rules.weaponCount;if(s<1)throw new Error(`Object "${i.name}" doesn't support special weapons`);if(s-1<e)throw new RangeError(`Weapon index ${e} out of bounds (max ${s}) for object ${i.name}`);s=t&&i.rules.getEliteWeaponAtIndex(e)||i.rules.getWeaponAtIndex(e);if(!s)throw new Error(`Missing weapon at index ${e} for object "${i.name}"`);t=i.art.getSpecialWeaponFlh(e);this.primaryWeapon=en.factory(s,oi.Primary,i,this.rules,t),this.secondaryWeapon=void 0,this.specialWeaponIndex=e,this.deathWeapon=this.primaryWeapon.rules.suicide?en.factory(i.rules.deathWeapon||this.primaryWeapon.name,oi.DeathWeapon,i,this.rules):void 0}toggleEliteWeapons(e){this.gameObject.rules.weaponCount?this.selectSpecialWeapon(this.specialWeaponIndex,e):this.selectStandardWeapons(e)}getSpecialWeaponIndex(){return this.specialWeaponIndex}computeGuardScanRange(t){var e=this.guardWeaponRangeOverride??[this.primaryWeapon,this.secondaryWeapon].filter(e=>e===t||e?.rules.neverUse).reduce((e,t)=>Math.max(e,t.range),0),e=Math.max(e,this.gameObject.rules.guardRange);return Math.min(15,2*e-1)}getDeployFireWeapon(){if(this.gameObject.rules.deployFire)return this.gameObject.rules.deployFireWeapon===oi.Primary?this.primaryWeapon:this.secondaryWeapon}isEquippedWithWeapon(e){return[this.primaryWeapon,this.secondaryWeapon].includes(e)}getWeapons(){return[this.primaryWeapon,this.secondaryWeapon].filter(Fa)}[Lr.onTick](){this.primaryWeapon&&this.primaryWeapon.tick(),this.secondaryWeapon&&this.secondaryWeapon.tick()}[Wr.onDestroy](t,e,i){!this.deathWeapon||i?.weapon?.warhead.rules.temporal||t.crashableTrait&&!t.isCrashing||i?.obj?.isVehicle()&&i.weapon?.rules.suicide&&i.obj.transportTrait?.units.find(e=>e===t)||this.deathWeapon.fire(e.createTarget(t,t.tile),e)}dispose(){this.gameObject=void 0,this.primaryWeapon=void 0,this.secondaryWeapon=void 0,this.deathWeapon=void 0}}class xh{}class Eh{constructor(e,t){this.gameObject=e,this.veteranRules=t,this.veteranLevel=Jr.None,this.xp=0,this.promotionThresh=e.rules.cost*t.veteranRatio+1}[Ln.onDestroy](e,t,i,s){e.isDestroyed&&!e.isCrashing||t.isTechno()&&(t.rules.dontScore||t.rules.insignificant||(i&&(i.warhead.rules.temporal||i.warhead.rules.parasite&&e.rules.organic)||!s.areFriendly(e,t))&&(this.veteranLevel>=this.veteranRules.veteranCap||this.gainXP(t.rules.cost*(t.veteranLevel+1))&&this.handlePromotion(e,s)))}setRelativeXP(e){this.gainXP(Math.floor(e*this.promotionThresh))}gainXP(e){if(this.xp+=e,this.xp>=this.promotionThresh){var t=Math.min(this.veteranLevel+Math.floor(this.xp/this.promotionThresh),this.veteranRules.veteranCap),e=t-this.veteranLevel;if(e)return this.xp-=e*this.promotionThresh,this.setVeteranLevel(t),!0}return!1}promote(e,t){e=Math.min(this.veteranLevel+e,this.veteranRules.veteranCap);e-this.veteranLevel&&(this.setVeteranLevel(e),this.handlePromotion(this.gameObject,t))}isMaxLevel(){return this.veteranLevel===this.veteranRules.veteranCap}isElite(){return this.veteranLevel===Jr.Elite}setVeteranLevel(e){this.veteranLevel=e,this.veteranLevel===Jr.Elite&&this.gameObject.armedTrait?.toggleEliteWeapons(!0)}handlePromotion(e,t){this.hasVeteranAbility(hi.SELF_HEAL)&&(e.traits.find(Ah)||t.addObjectTrait(e,new Ah)),this.hasVeteranAbility(hi.CLOAK)&&(e.cloakableTrait||(e.cloakableTrait=new cn(e,t.rules.general.cloakDelay),t.addObjectTrait(e,e.cloakableTrait))),this.hasVeteranAbility(hi.EXPLODES)&&(e.explodes||(e.explodes=!0,e.armedTrait||(e.armedTrait=new Bh(e,t.rules),t.addObjectTrait(e,e.armedTrait)))),this.hasVeteranAbility(hi.RADAR_INVISIBLE)&&(e.radarInvisible||(e.radarInvisible=!0)),this.hasVeteranAbility(hi.SENSORS)&&(e.sensorsTrait||(e.sensorsTrait=new xh,t.addObjectTrait(e,e.sensorsTrait))),e.isInfantry()&&this.hasVeteranAbility(hi.FEARLESS)&&e.suppressionTrait?.disable(),this.hasVeteranAbility(hi.C4)&&(e.c4||(e.c4=!0)),this.hasVeteranAbility(hi.GUARD_AREA)&&(e.defaultToGuardArea||(e.defaultToGuardArea=!0,e.unitOrderTrait.isIdle()&&e.resetGuardModeToIdle())),this.hasVeteranAbility(hi.CRUSHER)&&(e.crusher||(e.crusher=!0)),t.events.dispatch(new Ch(e))}getVeteranSightMultiplier(){return this.getVeteranAbilityMultiplier(hi.SIGHT)}getVeteranSpeedMultiplier(){return this.getVeteranAbilityMultiplier(hi.FASTER)}getVeteranArmorMultiplier(){return this.getVeteranAbilityMultiplier(hi.STRONGER)}getVeteranDamageMultiplier(){return this.getVeteranAbilityMultiplier(hi.FIREPOWER)}getVeteranRofMultiplier(){return this.getVeteranAbilityMultiplier(hi.ROF)}hasVeteranAbility(e){return this.veteranLevel===Jr.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=Jr.Elite&&this.gameObject.rules.eliteAbilities.has(e)}getVeteranAbilityMultiplier(e){let t=1;return(this.veteranLevel===Jr.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=Jr.Elite&&this.gameObject.rules.eliteAbilities.has(e))&&(t=this.getVeteranRulesMultiplier(e)),t}getVeteranRulesMultiplier(e){switch(e){case hi.FASTER:return this.veteranRules.veteranSpeed;case hi.STRONGER:return this.veteranRules.veteranArmor;case hi.FIREPOWER:return this.veteranRules.veteranCombat;case hi.ROF:return this.veteranRules.veteranROF;case hi.SIGHT:return this.veteranRules.veteranSight;default:throw new Error(`Unhandled VeteranAbility ${e}`)}}dispose(){this.gameObject=void 0}}class Ph{constructor(e,t=e){this.maxAmmo=e,this.ammo=t}get ammo(){return this._ammo}set ammo(e){this._ammo=W(e,0,this.maxAmmo)}isFull(){return this.ammo===this.maxAmmo}}class Nh{constructor(e){this.target=e,this.type=is.ObjectDisguiseChange}}class Mh{constructor(){this.isActive=!1,this.cooldownTicks=0}isDisguised(){return this.isActive}getDisguise(){return this.isActive?this.disguisedAs:void 0}hasTerrainDisguise(){return this.getDisguise()?.rules.type===Bt.Terrain}disguiseAs(e,t,i){this.disguisedAs={rules:e.rules,owner:e.owner},this.isActive=!0,i.events.dispatch(new Nh(t))}revealDisguise(e,t){this.cooldownTicks=t.rules.general.infantryBlinkDisguiseTime,this.isActive=!1,t.events.dispatch(new Nh(e))}[Qr.onSpawn](e,t){var i;!this.disguisedAs&&e.rules.permaDisguise&&e.isInfantry()&&e.owner.country&&((i=this.getDefaultInfantryDisguise(e.owner.country.side,t.rules.general))&&(i=t.rules.getObject(i,Bt.Infantry),this.disguisedAs={rules:i,owner:e.owner},this.isActive=!0))}getDefaultInfantryDisguise(e,t){switch(e){case Xt.GDI:return t.alliedDisguise;case Xt.Nod:return t.sovietDisguise;default:return}}[Lr.onTick](e,t){e.rules.permaDisguise||(e.attackTrait?.attackState===yn.JustFired||e.moveTrait.moveState!==$r.Idle?this.revealDisguise(e,t):0<this.cooldownTicks?this.cooldownTicks--:!this.isActive&&e.rules.disguiseWhenStill&&(this.isActive=!0,this.disguisedAs={rules:this.selectRandomMirageDisguise(t),owner:void 0},t.events.dispatch(new Nh(e))))}[ca.onDamage](e,t){this.revealDisguise(e,t)}selectRandomMirageDisguise(e){var t=e.rules.general.defaultMirageDisguises;if(!t.length)throw new Error("No default mirage disguises are defined");t=t[e.generateRandomInt(0,t.length-1)];return e.rules.getObject(t,Bt.Terrain)}}class Dh{constructor(){this.timer=new Mo}isActive(){return this.timer.isActive()}setActiveFor(e,t){this.timer.setActiveFor(e,t)}[Lr.onTick](e,t){this.timer.tick(t.currentTick)}}class Rh{constructor(e){this.gameObject=e,this.ticksWhenWarpedOut=!0,this.remainingTicks=0,this.invulnerable=!1}isActive(){return 0<this.remainingTicks}setActive(e,t,i){this.remainingTicks=e?Number.POSITIVE_INFINITY:0,this.invulnerable=t,this.notifyChange(e,i)}setTimed(e,t,i){this.remainingTicks=e,this.invulnerable=t,this.notifyChange(!0,i)}debugSetActive(e){this.remainingTicks=e?Number.POSITIVE_INFINITY:0}notifyChange(t,i){i.traits.filter(Es).forEach(e=>{e[Es.onChange](this.gameObject,i,t)}),this.gameObject.traits.filter(bn).forEach(e=>{e[bn.onChange](this.gameObject,i,t)})}expire(e){this.remainingTicks=0,this.notifyChange(!1,e)}isInvulnerable(){return this.isActive()&&this.invulnerable}[Lr.onTick](e,t){0<this.remainingTicks&&(this.remainingTicks--,this.remainingTicks<=0&&this.notifyChange(!1,t))}dispose(){this.gameObject=void 0}}class Lh{constructor(){this.timer=new Mo}hasCharge(){return this.timer.isActive()}setCharge(e,t,i){this.hasCharge()||(this.timer.setActiveFor(e,t),this.attackerInfo=i)}getChargeOwner(){return this.attackerInfo?.player}removeCharge(){this.timer.reset()}getTicksLeft(){return this.timer.getTicksLeft()}getInitialTicks(){return this.timer.getInitialTicks()}[Lr.onTick](e,t){this.timer.isActive()&&!0===this.timer.tick(t.currentTick)&&(e.isBuilding()&&e.cabHutTrait&&e.cabHutTrait.demolishBridge(t,this.attackerInfo),this.detonateIvanWarhead(t,e))}[Wr.onDestroy](e,t,i){this.timer.isActive()&&!i?.weapon?.warhead.rules.ivanBomb&&e.deathType!==zr.None&&e.deathType!==zr.Temporal&&(this.timer.reset(),this.detonateIvanWarhead(t,e))}detonateIvanWarhead(e,t){var i=e.rules.combatDamage.ivanDamage;let s=new Qa(e.rules.getWarhead(e.rules.combatDamage.ivanWarhead));var r=t.tile,a=t.tileElevation,n=t.isUnit()?t.zone:e.map.getTileZone(r),o=!!t.isUnit()&&t.onBridge;s.detonate(e,i,r,a,t.isBuilding()?ks.tile3dToWorld(r.rx+.5,r.ry+.5,r.z+a):t.position.worldPosition,n,o?ra.OnBridge:ra.None,e.createTarget(t,r),{...this.attackerInfo,weapon:void 0},!1,!1,void 0)}}class Fh{constructor(e){this.gameObject=e}getOriginalOwner(){return this.prevOwner}isActive(){return!!this.controller}getController(){return this.controller}controlBy(e,t){if(this.controller)throw new Error(`Object "${this.gameObject?.name}" is already mind controlled by "${e.name}"`);this.controller=e,this.prevOwner=this.gameObject.owner,t.changeObjectOwner(this.gameObject,e.owner)}restore(e){this.prevOwner&&(e.changeObjectOwner(this.gameObject,this.prevOwner),this.prevOwner=void 0,this.controller=void 0)}[Yr.onUnspawn](e,t){this.controller&&(this.controller.mindControllerTrait.cleanTarget(e),!e.isDestroyed&&e.limboData&&this.restore(t))}dispose(){this.gameObject=void 0}}class jh{constructor(e,t=1){this.gameObject=e,this.maxCapacity=t,this.targets=[]}isActive(){return 0<this.targets.length}isAtCapacity(){return this.targets.length===this.maxCapacity}getTargets(){return this.targets}control(e,t){if(!this.gameObject)throw new Error("Trait already disposed");if(!e.mindControllableTrait)throw new Error(`Target "${e.name}" cannot be mind controlled`);if(e.isDisposed)throw new Error(`Target "${e.name}" is disposed`);for(e.mindControllableTrait.controlBy(this.gameObject,t),this.targets.push(e);this.targets.length>this.maxCapacity;){let e=this.targets.shift();e.mindControllableTrait.restore(t)}}cleanTarget(e){e=this.targets.indexOf(e);-1!==e&&this.targets.splice(e,1)}[Yr.onUnspawn](e,t){for(var i of this.targets)i.mindControllableTrait.restore(t);this.targets.length=0}dispose(){this.gameObject=void 0}}class Uh{constructor(e){this.gameObject=e,this.ticksWhenWarpedOut=!0,this.attackers=new Set}[Lr.onTick](e,t){if(e.attackTrait&&(e.attackTrait.currentTarget&&!e.warpedOutTrait.isActive()||this.releaseCurrentTarget(t)),void 0!==this.eraseTicks)for(var i of this.attackers){var s=i.temporalTrait.currentWeapon;if(!s)throw new Error(`Attacker "${i.name}" is no longer targeting "${e.name}"`);var r=s.rules.damage;if(this.eraseTicks-=r,this.eraseTicks<=0){e.deathType=zr.Temporal,t.destroyObject(e,{player:i.owner,obj:i,weapon:s},!0),this.eraseTicks=void 0;break}}}getTarget(){return this.currentTarget}updateTarget(t,e,i){if(this.currentTarget!==t){this.releaseCurrentTarget(i),this.currentTarget=t,this.currentWeapon=e;e=t.temporalTrait.attackers.size;if(t.temporalTrait.attackers.add(this.gameObject),!e){t.warpedOutTrait.setActive(!0,!0,i);let e=t.unitOrderTrait.getCurrentTask();(e&&e instanceof po||e instanceof Sa)&&e.cancel(),t.temporalTrait.eraseTicks=10*t.healthTrait.maxHitPoints}}}releaseCurrentTarget(t){if(this.currentTarget){if(!this.currentTarget.isDisposed){let e=this.currentTarget.temporalTrait.attackers;e.delete(this.gameObject),e.size||(this.currentTarget.warpedOutTrait.expire(t),this.currentTarget.temporalTrait.eraseTicks=void 0)}this.currentTarget=void 0,this.currentWeapon=void 0}}[Wr.onDestroy](e,t){this.releaseCurrentTarget(t)}dispose(){this.gameObject=void 0,this.attackers.clear()}}class Wh{constructor(){this.spawns=[],this.storage=[],this.missileLaunches=[],this.nextRegenTicks=[]}get availableSpawns(){return this.storage.length}debugSetStorage(e,t){this.storage.length=t,this.storage.fill(e,0,t)}isLaunchingMissiles(){return 0<this.missileLaunches.length}[Qr.onSpawn](t,i){var s=i.rules.getObject(t.rules.spawns,Bt.Aircraft);for(let e=0;e<t.rules.spawnsNumber;e++)this.pushNewSpawn(s,i,t)}[Yr.onUnspawn](e,t){this.destroySpawns(e,t)}[Wr.onDestroy](e,t,i,s){this.destroySpawns(e,t,i,s)}pushNewSpawn(e,t,i){let s=t.createUnitForPlayer(e,i.owner);s.limboData={selected:!1,controlGroup:void 0},e.missileSpawn&&(s.pitch=90*t.rules.general.getMissileRules(e.name).pitchInitial),this.spawns.push(s),this.storage.push(s)}destroySpawns(e,t,i,s){for(var r of this.spawns)r.isDestroyed||(r.isSpawned&&!r.rules.missileSpawn&&r.crashableTrait?r.crashableTrait.crash(i):(r.isSpawned||(r.armedTrait&&(r.armedTrait.deathWeapon=void 0),r.position.tileElevation=e.position.tileElevation,r.zone=e.isUnit()?e.zone:bs.Ground,r.onBridge=!!e.isUnit()&&e.onBridge,r.position.tile=e.tile),t.destroyObject(r,i,s)));this.spawns.length=0,this.storage.length=0,this.missileLaunches.length=0}[Lr.onTick](r,a){var t;if(this.spawns=this.spawns.filter(e=>!e.isDestroyed),this.missileLaunches=this.missileLaunches.filter(e=>!e.missile.isDestroyed),this.spawns.length<r.rules.spawnsNumber){var i=r.rules.spawnsNumber-this.spawns.length,s=a.rules.getObject(r.rules.spawns,Bt.Aircraft);for(let e=0;e<i;e++)s.missileSpawn&&e&&void 0===this.nextRegenTicks[e]?this.nextRegenTicks[e]=this.nextRegenTicks[0]:((t=this.nextRegenTicks)[e]??(t[e]=r.rules.spawnRegenRate),0<this.nextRegenTicks[e]&&this.nextRegenTicks[e]--),this.nextRegenTicks[e]<=0&&this.pushNewSpawn(s,a,r);this.nextRegenTicks=this.nextRegenTicks.filter(e=>0<e)}if(this.storage.length){if(this.nextReloadTicks??(this.nextReloadTicks=r.rules.spawnReloadRate),0<this.nextReloadTicks&&this.nextReloadTicks--,this.nextReloadTicks<=0){for(var e of this.storage)e.ammoTrait&&e.ammoTrait.ammo<e.ammoTrait.maxAmmo&&e.ammoTrait.ammo++;this.nextReloadTicks=r.rules.spawnReloadRate}}else this.nextReloadTicks=void 0;for(let s of this.missileLaunches.slice()){var n=a.rules.general.getMissileRules(s.missile.name);if(s.pauseFrames??(s.pauseFrames=n.pauseFrames),0<s.pauseFrames&&s.pauseFrames--,s.pauseFrames<=0){var o=90*n.pitchFinal,n=90*(n.pitchFinal-n.pitchInitial)/n.tiltFrames;let i=s.missile;if(i.pitch<o)i.pitch=Math.min(o,i.pitch+n);else{i.unitOrderTrait.addTask(new ja(new Sa(a,s.targetTile,!!s.targetBridge),new ga(()=>{var e,t;i.isDestroyed||(a.unspawnObject(i),i.dispose(),t=ks.vecGroundToWorld(Tr.toMapCoords(i.direction).multiplyScalar(1)),e=s.targetWorldPos.clone().add(t),t=a.map.getTileZone(s.targetTile),s.warhead.detonate(a,s.damage,s.targetTile,s.targetBridge?.tileElevation??0,e,t,s.targetBridge?ra.OnBridge:ra.None,s.target,{player:i.owner,obj:r,weapon:void 0},!1,!1,void 0))})).setCancellable(!1));n=this.spawns.indexOf(i);if(-1===n)throw new Error("Missile not found in spawns list");this.spawns.splice(n,1),this.missileLaunches.splice(this.missileLaunches.indexOf(s),1)}}}}[Zr.onChange](e,t,i){for(var s of this.spawns)s.isDestroyed||i.changeObjectOwner(s,e.owner)}[bn.onChange](e,t,i){i&&this.removeMissileLaunches(t)}[Ur.onBeforeTeleport](e,t,i,s){s||this.removeMissileLaunches(t)}removeMissileLaunches(e){if(this.missileLaunches.length){for(var t of this.missileLaunches){e.unspawnObject(t.missile),t.missile.dispose();t=this.spawns.indexOf(t.missile);if(-1===t)throw new Error("Missile not found in spawns list");this.spawns.splice(t,1)}this.missileLaunches.length=0}}prepareLaunch(s,r,a){if(this.storage.length){let i=this.storage[0];if(!i.ammo)return;if(this.storage.shift(),i.missileSpawnTrait){let e,t;var n=s.veteranTrait?.isElite(),o=a.rules;if(s.rules.spawns===o.general.v3Rocket.type)e=n?o.combatDamage.v3EliteWarhead:o.combatDamage.v3Warhead,t=n?o.general.v3Rocket.eliteDamage:o.general.v3Rocket.damage;else{if(s.rules.spawns!==o.general.dMisl.type)throw new Error(`Unhandled missile type "${s.rules.spawns}"`);e=n?o.combatDamage.dMislEliteWarhead:o.combatDamage.dMislWarhead,t=n?o.general.dMisl.eliteDamage:o.general.dMisl.damage}a=new Qa(a.rules.getWarhead(e));i.missileSpawnTrait.setDamage(t).setWarhead(a).setLauncher(s),this.missileLaunches.push({missile:i,targetTile:(r.obj?.isUnit()?r.obj:r).tile,targetBridge:r.getBridge(),targetWorldPos:r.getWorldCoords().clone(),target:r,warhead:a,damage:t,pauseFrames:void 0})}else{if(!i.spawnLinkTrait)throw new Error(`Aircraft "${i.name}" must have Spawned=yes to be launchable`);i.spawnLinkTrait.setParent(s)}return i}}storeAircraft(e,t){if(!this.spawns.includes(e))throw new Error(`Object "${e.name}#${e.id}" not found in list of linked spawns`);if(e.limboData)throw new Error(`Object "${e.name}#${e.id}" is already in limbo`);t.limboObject(e,{selected:!1,controlGroup:void 0}),this.storage.push(e)}}class zh{[ea.onCrash](e,t){this.handleDestroy(e,t)}[Wr.onDestroy](e,t,i){i?.weapon?.warhead.rules.temporal||e.isCrashing||e.deathType!==zr.Sink&&e.isSpawned&&this.handleDestroy(e,t)}handleDestroy(e,t){var i,s;(e.isVehicle()||e.isBuilding()||e.isOverlay())&&(i=e.isOverlay()?0:e.rules.minDebris,s=e.isOverlay()?t.rules.general.bridgeVoxelMax:e.rules.maxDebris,0<(s=t.generateRandomInt(i,s))&&this.spawnDebris(e,t,s))}spawnDebris(t,i,s){let r=t.position.getMapPosition();if(i.map.isWithinHardBounds(r)){let e=t.isOverlay()?[]:t.isVehicle()?t.rules.debrisTypes:t.rules.debrisAnims;e.length||(e=i.rules.audioVisual.metallicDebris),e=e.filter(e=>i.rules.hasObject(e,Bt.VoxelAnim)||i.art.hasObject(e,Bt.Animation)),new Array(s).fill(0).map(()=>e[i.generateRandomInt(0,e.length-1)]).map(e=>i.createObject(Bt.Debris,e)).forEach(e=>{e.position.moveToLeptons(r),e.position.tileElevation=t.position.tileElevation,i.spawnObject(e,e.position.tile)})}}}class Vh extends Aa{constructor(e,t,i,s){super(Bt.Debris,e,t,i),this.age=0,this.direction=0,this.rotationAxis=new ss,this.angularVelocity=0,this.zone=bs.Air,this.velocity=new ss,this.collisionHelper=new wh(s)}static factory(e,t,i,s){return new this(e,t,i,s)}onSpawn(e){super.onSpawn(e),this.direction=e.generateRandomInt(0,359),this.xySpeed=V(0,this.rules.maxXYVel,e.generateRandom()),this.zSpeed=V(this.rules.minZVel,this.rules.maxZVel||1.5*this.rules.minZVel,e.generateRandom()),this.rotationAxis.set(e.generateRandom(),e.generateRandom(),e.generateRandom()).normalize(),this.angularVelocity=V(this.rules.minAngularVelocity,this.rules.maxAngularVelocity,e.generateRandom())}update(t){if(super.update(t),this.age++,this.rules.duration&&this.age>this.rules.duration)return this.velocity.set(0,0,0),void this.detonate(t);--this.zSpeed;var i=Tr.toMapCoords(this.direction).setLength(this.xySpeed);let s=new ss(i.x,this.zSpeed,i.y);var r=this.position.clone(),i=s.clone().add(this.position.worldPosition);if(t.map.isWithinHardBounds(i)){this.position.moveByLeptons3(s);let e=!1;var{type:i,target:r}=this.collisionHelper.checkCollisions(this.position,r,{cliffs:!0,ground:!0,shore:!1,walls:!0,units:!1});if(i&&(!([ra.Ground,ra.OnBridge].includes(i)&&0<this.rules.elasticity&&t.map.getTileZone(this.tile)!==bs.Water)||Math.abs(this.zSpeed)<1?e=!0:(this.zSpeed=-this.zSpeed*this.rules.elasticity,this.velocity.y=-this.velocity.y*this.rules.elasticity,this.rotationAxis.negate())),e){if(this.velocity.set(0,0,0),r&&i===ra.Wall){let e=r.position.worldPosition;this.position.moveByLeptons3(e.clone().sub(this.position.worldPosition))}this.detonate(t,i)}else this.velocity.copy(s)}else t.unspawnObject(this)}detonate(t,i=ra.None){var e,s=this.rules.warhead?t.rules.getWarhead(this.rules.warhead):void 0,r=this.zone=this.collisionHelper.computeDetonationZone(this.tile,this.tileElevation,i);let a;r===bs.Water?(e=t.rules.combatDamage.splashList,a=e[0]):(e=this.rules.expireAnim)&&t.rules.animationNames.has(e)&&(a=e),this.explodeAnim=a;let n=new Xa;if(a&&n.spawnSmudges(a,this.tile,t),t.destroyObject(this),s){let e=new Qa(s);e.detonate(t,this.rules.damage,this.tile,this.tileElevation,this.position.worldPosition,r,i,t.createTarget(void 0,this.tile),void 0,!1,!1,void 0,this.rules.damageRadius||void 0,!0)}}}class Hh{constructor(e,t,i,s){this.tiles=e,this.tileOccupation=t,this.bridges=i,this.nextObjectId=s}create(e,t,i,s){let r,a;e===Bt.Debris?r=i.hasObject(t,Bt.VoxelAnim)?(a=s.getObject(t,Bt.VoxelAnim),i.getObject(t,Bt.VoxelAnim)):(a=s.getAnimation(t),new cs(Bt.Debris,s.getIni().getOrCreateSection(t))):a=e===Bt.Projectile?(r=i.getProjectile(t),r.inviso?new $n(Bt.Projectile,r,new h(t)):s.getProjectile(t)):(r=i.getObject(t,e),s.getObject(t,e));let n;switch(e){case Bt.Building:n=$o.factory(t,r,i,a,this.tiles,this.bridges);break;case Bt.Infantry:n=Da.factory(t,r,a,this.tileOccupation);break;case Bt.Vehicle:n=ch.factory(t,r,a,i,this.tileOccupation);break;case Bt.Aircraft:n=gh.factory(t,r,a,i,this.tileOccupation);break;case Bt.Terrain:n=qo.factory(t,r,a);break;case Bt.Overlay:n=Xo.factory(t,r,a);break;case Bt.Smudge:n=Zo.factory(t,r,a);break;case Bt.Projectile:n=Th.factory(t,r,a,this.tileOccupation);break;case Bt.Debris:n=Vh.factory(t,r,a,this.tileOccupation);break;default:throw new Error("Not implemented")}if(n.id=this.nextObjectId.value++,n.position=new yh(this.tiles,this.tileOccupation),n.isUnit()?n.position.subCell=0:n.isBuilding()&&n.position.setCenterOffset(n.getFoundationCenterOffset()),n.isTechno()&&((n.rules.primary||n.rules.secondary||n.rules.weaponCount||n.rules.explodes)&&(n.armedTrait=new Bh(n,i),n.traits.add(n.armedTrait)),-1!==n.rules.ammo&&(o=n.rules.initialAmmo,n.ammoTrait=new Ph(n.rules.ammo,-1!==o?o:void 0),n.traits.add(n.ammoTrait)),n.unitOrderTrait=new mh(n),n.traits.addToFront(n.unitOrderTrait),(n.primaryWeapon||n.secondaryWeapon)&&(n.attackTrait=new uo(this.tiles,this.tileOccupation),n.traits.add(n.attackTrait)),(n.isInfantry()||n.isVehicle())&&n.rules.deployer&&(n.deployerTrait=new bh(n),n.traits.add(n.deployerTrait)),(n.isInfantry()||n.isVehicle())&&n.rules.canDisguise&&(n.disguiseTrait=new Mh,n.traits.add(n.disguiseTrait)),n.rules.cloakable&&(n.cloakableTrait=new cn(n,i.general.cloakDelay),n.traits.add(n.cloakableTrait)),n.rules.sensors&&(n.sensorsTrait=new xh,n.traits.add(n.sensorsTrait)),n.autoRepairTrait=new Ih(!n.isBuilding()),n.traits.add(n.autoRepairTrait),n.rules.trainable&&(n.veteranTrait=new Eh(n,i.general.veteran),n.traits.add(n.veteranTrait)),n.rules.selfHealing&&n.traits.add(new Ah),n.invulnerableTrait=new Dh,n.traits.add(n.invulnerableTrait),n.warpedOutTrait=new Rh(n),n.traits.add(n.warpedOutTrait),n.temporalTrait=new Uh(n),n.traits.add(n.temporalTrait),n.rules.bombable&&(n.tntChargeTrait=new Lh,n.traits.add(n.tntChargeTrait)),n.rules.immuneToPsionics||n.isBuilding()||(n.mindControllableTrait=new Fh(n),n.traits.add(n.mindControllableTrait)),[n.primaryWeapon,n.secondaryWeapon].some(e=>e?.warhead.rules.mindControl)&&(n.mindControllerTrait=new jh(n),n.traits.add(n.mindControllerTrait)),n.rules.spawns&&(n.airSpawnTrait=new Wh,n.traits.add(n.airSpawnTrait)),n.rules.maxDebris&&n.traits.add(new zh)),n.isTechno()||n.isOverlay()||n.isTerrain()){var o=n.isOverlay()&&Va.isBridge(i.getOverlayId(n.name));let e=n.rules.strength;!e&&n.isTerrain()&&(e=i.general.treeStrength),o&&(e=i.combatDamage.bridgeStrength),(e||n.isTechno())&&(n.healthTrait=new kh(e,n,i.audioVisual.conditionYellow,i.audioVisual.conditionRed),n.traits.add(n.healthTrait)),n.isOverlay()&&o&&(n.bridgeTrait=new Oh(this.bridges),n.traits.add(n.bridgeTrait),Va.getOverlayBridgeType(i.getOverlayId(n.name))===ia.Concrete&&n.traits.add(new zh))}return n.isOverlay()&&n.isOverlay()&&$a.getOverlayTibType(i.getOverlayId(n.name))!==na.NotSpecial&&n.traits.add(new qa(n)),n.isTerrain()&&n.rules.spawnsTiberium&&n.traits.add(new _h(n.rules)),n.cachedTraits.tick.push(...n.traits.filter(Lr)),n}}class Gh{constructor(){this.allObjects=new Map,this._onObjectSpawned=new ro,this._onObjectRemoved=new ro}get onObjectSpawned(){return this._onObjectSpawned.asEvent()}get onObjectRemoved(){return this._onObjectRemoved.asEvent()}spawnObject(e){if(this.allObjects.has(e.id))throw new Error("Trying to add an already existing object");this.allObjects.set(e.id,e),this._onObjectSpawned.dispatch(this,e)}removeObject(e){if(!this.allObjects.has(e.id))throw new Error("Trying to remove non-existent object");this.allObjects.delete(e.id),this._onObjectRemoved.dispatch(this,e)}hasObjectId(e){return this.allObjects.has(e)}getObjectById(e){if(!this.allObjects.has(e))throw new Error(`Object with id ${e} doesn't exist`);return this.allObjects.get(e)}getAllObjects(){return[...this.allObjects.values()]}}var $h,qh,Xh,Zh,Qh,Yh,Kh,Jh,el,r=__webpack_require__(495),tl=__webpack_require__.n(r),il=__webpack_require__(45);class sl{constructor(e,t,i,s,r){this.tiles=e,this.theaterType=t,this.mapBounds=i,this.tileOccupation=s,this.rules=r,this.passabilityGraphs=new Map,this.invalidatedTiles=new Map,this.handleTileOccupationUpdate=({tiles:e,object:i})=>{e=e.filter(e=>{let t=Jt.Foot;return i.isTerrain()&&i.rules.getOccupationBits(this.theaterType)!==es.All&&(t=Jt.Wheel),i.isOverlay()&&(i.isBridge()||i.isTiberium())||this.isBlockerObject(i,e,!1,t)||this.isBlockerObject(i,e,!0,t)||i.isBuilding()&&i.rules.leaveRubble});e.length&&this.invalidateTiles(e)},this.handleMapBoundsResize=()=>{this.passabilityGraphs.clear()},s.onChange.subscribe(this.handleTileOccupationUpdate),i.onLocalResize.subscribe(this.handleMapBoundsResize)}invalidateTiles(i){i.length&&[...this.passabilityGraphs.keys()].forEach(e=>{let t=this.invalidatedTiles.get(e);t?i.forEach(e=>t.add(e)):this.invalidatedTiles.set(e,new Set(i))})}computePath(t,e,i,s,r,{maxExpandedNodes:a=Number.POSITIVE_INFINITY,bestEffort:n=!0,excludeTiles:o,ignoredBlockers:h=[]}={}){let l=this.computePassabilityGraph(t);var c=h.map(e=>this.tileOccupation.calculateTilesForGameObject(e.tile,e)).reduce((e,t)=>e.concat(t),[]);if(c.length&&this.updatePassability(c,t,l,h),!this.getPassableSpeed(e,t,i,h))return c.length&&this.updatePassability(c,t,l),[];var u=this.getNodeId(s,r),d=!!l.hasNode(u);d||((h=new js(this.tiles,this.mapBounds,s,{width:1,height:1},1,5,e=>0<this.getPassableSpeed(e,t,!1)&&Math.abs(e.z-s.z)<2&&!o?.({tile:e,onBridge:void 0,speed:100})).getNextTile())?(s=h,r=!1):(l.addNode(u,{tile:s,onBridge:void 0,speed:100}),a=Math.min(a,500)));let p=(0,il.aStar)(l,{bestEffort:n,maxExpandedNodes:a,distance(e,t){if(o?.(t.data)||!t.data.speed)return Number.POSITIVE_INFINITY;var i=Math.abs(e.data.tile.rx-t.data.tile.rx),t=Math.abs(e.data.tile.ry-t.data.tile.ry);return i+t+(Math.SQRT2-2)*Math.min(i,t)},heuristic(e,t,i){if(o?.(t.data)||!t.data.speed)return Number.POSITIVE_INFINITY;var s=Math.abs(e.data.tile.rx-t.data.tile.rx),t=Math.abs(e.data.tile.ry-t.data.tile.ry);let r=s+t+(Math.SQRT2-2)*Math.min(s,t);return i?.parent&&(t=(s=i.parent.node).data.tile.rx-e.data.tile.rx,e=s.data.tile.ry-e.data.tile.ry,i.dirX=t,i.dirY=e,t===i.parent.dirX&&e===i.parent.dirY||(r+=.2)),r}}),g=p.find(this.getNodeId(e,i),this.getNodeId(s,r)).map(e=>({tile:e.data.tile,onBridge:e.data.onBridge}));return(g.length<2||o&&g.length&&(!n&&g[0].tile!==s||g[g.length-1].tile!==e))&&(g=[]),!d&&l.hasNode(u)&&l.removeNode(u),c.length&&this.updatePassability(c,t,l),g}computeAllPassabilityGraphs(){Object.keys(Jt).forEach(e=>{e=Number(e);isNaN(e)||e===Jt.Winged||this.computePassabilityGraph(e)})}computePassabilityGraph(t){let i=this.passabilityGraphs.get(t);if(i){let e=this.invalidatedTiles.get(t);e?.size&&(this.updatePassability([...e],t,i),e.clear())}else i=tl()({multigraph:!0}),this.passabilityGraphs.set(t,i),this.tiles.forEach(e=>{this.computePassability(e,t,i)});return i}updatePassability(e,t,i,s=[]){let r=new Set;e.forEach(e=>{[e,this.tiles.getNeighbourTile(e,aa.Right),this.tiles.getNeighbourTile(e,aa.BottomRight),this.tiles.getNeighbourTile(e,aa.Bottom),this.tiles.getNeighbourTile(e,aa.BottomLeft)].filter(Fa).forEach(e=>r.add(e))}),e.forEach(e=>{i.removeNode(this.getNodeId(e,!1)),i.removeNode(this.getNodeId(e,!0))}),r.forEach(e=>{this.computePassability(e,t,i,s)})}computePassability(e,t,i,s=[]){var r=[aa.Left,aa.TopLeft,aa.Top,aa.TopRight];let a=this.getPassableSpeed(e,t,!1,s);if(a){var n,o=this.getNodeId(e,!1);i.hasNode(o)||i.addNode(o,{speed:a,tile:e,onBridge:void 0});for(n of r)this.connectTiles(e,void 0,n,t,i,s)}var h=this.tileOccupation.getBridgeOnTile(e);if(h&&(a=this.getPassableSpeed(e,t,!0,s),a)){var l,o=this.getNodeId(e,!0);i.hasNode(o)||i.addNode(o,{speed:a,tile:e,onBridge:h});for(l of r)this.connectTiles(e,h,l,t,i,s)}}connectTiles(t,i,s,r,a,n=[]){var o=this.tiles.getNeighbourTile(t,s);if(o){let e=this.tileOccupation.getBridgeOnTile(o);s=i||e?0:1;if(Math.abs(t.z+(i?.tileElevation??0)-(o.z+(e?.tileElevation??0)))>s){if(!e?.isHighBridge()&&!i?.isHighBridge()||0!==Math.abs(t.z-o.z)||!a.hasNode(this.getNodeId(t,!1)))return;i=e=void 0}r=this.getPassableSpeed(o,r,!!e,n);r&&(n=this.getNodeId(o,!!e),a.hasNode(n)||a.addNode(n,{speed:r,tile:o,onBridge:e}),i=this.getNodeId(t,!!i),a.getLink(i,n)||a.addLink(i,n))}}getNodeId(e,t){return e.id+(t?"_bridge":"")}getPassableSpeed(e,t,i,s=[],r=!1){if(!this.mapBounds.isWithinBounds(e))return 0;let a=i?e.onBridgeLandType:e.landType;if(void 0===a)return 0;a===Kt.Wall&&t===Jt.Track&&(a=Hi(e.terrainType));let n=this.rules.getLandRules(a);var o,h=n.getSpeedModifier(t);if(!h)return 0;if(!r)for(o of this.tileOccupation.getObjectsOnTile(e))if(this.isBlockerObject(o,e,i,t)&&!s.includes(o))return 0;return h}isBlockerObject(t,i,e,s){if(t.isTerrain()&&s===Jt.Foot&&t.rules.getOccupationBits(this.theaterType)!==es.All)return!1;if(t.isBuilding()){if(t.rules.invisibleInGame)return!1;if(t.isDestroyed&&t.rules.leaveRubble)return!1;if(t.rules.gate)return!1;var r=t.art.foundation;let e=t.rules.numberImpassableRows;return s===Jt.Foot?e=r.width:t.rules.weaponsFactory&&!e&&(e=r.width-1),Pr({x:t.tile.rx,y:t.tile.ry,width:(e||r.width)-1,height:r.height-1},{x:i.rx,y:i.ry})}return!(t.isAircraft()||t.isInfantry()||t.isVehicle()||t.isSmudge()||t.isOverlay()&&(e&&t.isBridge()||!e&&t.isHighBridge()||t.isTiberium()||t.rules.crate||t.isBridgePlaceholder())||[Jt.Track,Jt.Hover].includes(s)&&t.rules.crushable)}findObstacles(t,e){var i,s,r=e.rules.speedType;let a=[];for(i of this.tileOccupation.getGroundObjectsOnTile(t.tile))i!==e&&(((s=this.isBlockerObject(i,t.tile,!!t.onBridge,r))||i.isUnit()&&(i.tile===t.tile&&i.onBridge===!!t.onBridge||i.moveTrait.reservedPathNodes.find(e=>e.tile===t.tile&&!!e.onBridge==!!t.onBridge))||[Jt.Track,Jt.Hover].includes(r)&&i.rules.crushable||r===Jt.Foot&&i.isTerrain()||i.isBuilding()&&i.rules.gate)&&(s={obj:i,static:s},i.isInfantry()&&e.isInfantry()?i.position.desiredSubCell===e.position.desiredSubCell&&a.push(s):i.isTerrain()&&e.isInfantry()&&!i.rules.getOccupiedSubCells(this.theaterType).includes(e.position.desiredSubCell)||a.push(s)));return a}dispose(){this.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate),this.mapBounds.onLocalResize.unsubscribe(this.handleMapBoundsResize)}}class rl{constructor(){this.mapCutoffHeight=0,this.mapBuildableSize={x:0,y:0,width:0,height:0},this.localSize={x:0,y:0,width:0,height:0},this.fullSize={width:0,height:0},this.clampedFullSize={x:0,y:0,width:0,height:0},this.rawLocalSize={x:0,y:0,width:0,height:0},this._onLocalResize=new ro}get onLocalResize(){return this._onLocalResize.asEvent()}fromMapFile(e,t){this.fullSize={width:2*e.fullSize.width,height:2*e.fullSize.height},this.clampedFullSize={x:1,y:2,width:2*(e.fullSize.width-1)-1/ks.ISO_TILE_SIZE,height:2*(e.fullSize.height-1)+1-1/ks.ISO_TILE_SIZE},this.mapCutoffHeight=Math.max(9,t.getCutoffTileHeight());t=Math.max(2,e.localSize.x),e={x:t,y:e.localSize.y,width:Math.min(e.fullSize.width-2-t,e.localSize.width),height:e.localSize.height};return this.updateRawLocalSize(e),this}updateRawLocalSize(e){var t,i;this.rawLocalSize.width&&this.rawLocalSize.height&&!function(e,t){let i=new xr.Box2(new xr.Vector2(e.x,e.y),new xr.Vector2(e.x+e.width,e.y+e.height));return t=new xr.Box2(new xr.Vector2(t.x,t.y),new xr.Vector2(t.x+t.width,t.y+t.height)),i.containsBox(t)}(e,this.rawLocalSize)?console.warn("New map limits must be outside old limits. Skipping."):(t=e,i=this.rawLocalSize,t.x===i.x&&t.y===i.y&&t.width===i.width&&t.height===i.height||(this.localSize=this.computeLocalSize(e,this.fullSize.height/2,this.mapCutoffHeight),this.rawLocalSize={...e},this.mapBuildableSize={x:this.localSize.x,y:this.localSize.y+4,width:this.localSize.width-2,height:this.localSize.height-8},this._onLocalResize.dispatch(this)))}computeLocalSize(e,t,i){return{x:2*e.x,y:2*e.y-4,height:Math.min(2*(e.height+5)-1,2*t-2*(e.y-3)-i),width:2*e.width}}getLocalSize(){return this.localSize}getRawLocalSize(){return this.rawLocalSize}getFullSize(){return this.fullSize}getClampedFullSize(){return this.clampedFullSize}isWithinBounds(e){return Pr(this.mapBuildableSize,{x:e.dx,y:e.dy-e.z})}clampWithinBounds(e){let{x:t,y:i}=function(e,t){let i=new xr.Box2(new xr.Vector2(e.x,e.y),new xr.Vector2(e.x+e.width,e.y+e.height));return i.clampPoint(new xr.Vector2(t.x,t.y),new xr.Vector2)}(this.mapBuildableSize,{x:e.dx,y:e.dy-e.z});return i+=t%2-i%2,i>this.mapBuildableSize.y+this.mapBuildableSize.height&&(i-=2),{dx:t,dy:i}}isWithinHardBounds(e){var t=e.x/ks.LEPTONS_PER_TILE,i=(e.z??e.y)/ks.LEPTONS_PER_TILE,e=t-i+this.fullSize.width/2-1,i=t+i-this.fullSize.width/2-1;return Pr(this.clampedFullSize,{x:++e,y:++i})}}class al{constructor(e,t,i,s,r,a,n,o=()=>!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=r,this.dirX=a,this.dirY=n,this.predicate=o,this.finished=!1,this.distance=s}getNextTile(){if(!this.finished){let t;do{let e={x:this.startTile.rx,y:this.startTile.ry};e.x+=this.distance*Math.sign(this.dirX),e.y+=this.distance*Math.sign(this.dirY);var i=this.tiles.getByMapCoords(e.x,e.y);if(i&&this.mapBounds.isWithinBounds(i)&&this.predicate(i)&&(t=i),this.maxDistance&&this.distance>=this.maxDistance)return this.finished=!0,t}while(this.distance++,!t);return t}}}(r=$h=$h||{})[r.None=0]="None",r[r.Start=1]="Start",r[r.End=2]="End";class nl{constructor(e,t,i,s,r){this.tileSets=e,this.tiles=t,this.tileOccupation=i,this.mapBounds=s,this.rules=r,this.pieces=new Set,this.piecesByTile=new Map,this.handleTileOccupationUpdate=({object:t,type:i})=>{if(t.isOverlay()&&t.isBridge()){var s=t.tile;let e=this.piecesByTile.get(s);if("added"===i){if(e)throw new Error(`A bridge piece already exists at tile (${s.rx},${s.ry})`);var r=this.findBridgeAdjacentTiles(t);e={obj:t,prev:void 0,next:void 0,headType:this.computeHead(t,r.prev,r.next)},this.piecesByTile.set(s,e),this.pieces.add(e),this.connectPiece(e,r.prev,r.next),this.updateOverlayData(e),e.prev&&this.updateOverlayData(e.prev),e.next&&this.updateOverlayData(e.next)}else{if(!e)throw new Error(`Bridge piece was alredy removed at tile (${s.rx},${s.ry})`);t=e.prev,r=e.next;this.disconnectPiece(e),this.piecesByTile.delete(s),this.pieces.delete(e),t&&this.updateOverlayData(t),r&&this.updateOverlayData(r)}}},i.onChange.subscribe(this.handleTileOccupationUpdate)}getPieceAtTile(e){return this.piecesByTile.get(e)}handlePieceHealthChange(e){this.updateOverlayData(e),e.prev&&this.updateOverlayData(e.prev),e.next&&this.updateOverlayData(e.next)}findDominoPieces(t){let i=[],s=!1,e=t.next;if(t.headType===$h.None||e)for(;e;){if(i.push(e),e.headType!==$h.None){s=!0;break}e=e.next}else s=!0;if(s){s=!1,i.length=0;let e=t.prev;if(t.headType===$h.None||e)for(;e;){if(i.push(e),e.headType!==$h.None){s=!0;break}e=e.prev}else s=!0;if(s)return[]}return i}findBridgeAdjacentTiles(e){var t=e.isXBridge(),t=new Ss(Number(t),Number(!t));let i=new Ss(e.tile.rx,e.tile.ry);e=i.clone().sub(t),e=this.tiles.getByMapCoords(e.x,e.y),t=i.clone().add(t);return{prev:e,next:this.tiles.getByMapCoords(t.x,t.y)}}connectPiece(e,t,i){t&&(e.prev=this.getPieceAtTile(t),e.prev&&(e.prev.next=e)),i&&(e.next=this.getPieceAtTile(i),e.next&&(e.next.prev=e))}disconnectPiece(e){e.next&&(e.next.prev=void 0,e.next=void 0),e.prev&&(e.prev.next=void 0,e.prev=void 0)}computeHead(e,t,i){var s=e.tile;if(e.isHighBridge()){s=s.z+e.tileElevation;return t?.z===s?$h.Start:i?.z===s?$h.End:$h.None}return Va.isLowBridgeHead(e.overlayId)?Va.isLowBridgeHeadStart(e.overlayId)?$h.Start:$h.End:$h.None}updateOverlayData(t){let i=t.obj,s=t.prev,r=t.next,a=!1;var n=i.isXBridge(),o=Va.getOverlayBridgeType(i.overlayId);if(Va.isLowBridgeHead(i.overlayId)){let e=0;Va.isLowBridgeHeadStart(i.overlayId)?(e=n?20:22,r||e++):(e=n?18:24,s||e++),i.overlayId=(o===ia.Wood?Va.minLowBridgeWoodId:Va.minLowBridgeConcreteId)+e,i.value=e,a=!0}else{let e;var h,l=(i.healthTrait?.health??100)<=50;e=t.headType!==$h.None?t.headType===$h.Start?r?l?6:(r.obj.healthTrait?.health??100)<=50?5:0:n?8:7:s?l?6:(s.obj.healthTrait?.health??100)<=50?4:0:n?7:8:(n||(h=s,s=r,r=h),s||r?s?r?(t=(s.obj.healthTrait?.health??100)<=50,h=(r.obj.healthTrait?.health??100)<=50,l||t&&h?6:t?4:h?5:0):8:7:0),n||(e+=9),i.isHighBridge()?i.value=e:(i.overlayId=(o===ia.Wood?Va.minLowBridgeWoodId:Va.minLowBridgeConcreteId)+e,i.value=e,a=!0)}a&&(i.name=this.rules.getOverlayName(i.overlayId))}findClosestBridgeSpec(i){let e=new js(this.tiles,this.mapBounds,i,{width:1,height:1},1,3,e=>{if(e.z!==i.z)return!1;let t=this.tileOccupation.getBridgeOnTile(e);return!(!t?.isLowBridge()||this.getPieceAtTile(t.tile)?.headType===$h.None)||!!this.tileSets.isHighBridgeBoundaryTile(e.tileNum)});var o=e.getNextTile();if(o){let s,t,r,a;var h=!this.tileOccupation.getBridgeOnTile(o);let e;if(h){var l=this.findHighBridgeBoundary(o);if(!l)return;s=l.tile,t=ia.Concrete,this.tileSets.getSetNum(o.tileNum)===this.tileSets.getGeneralValue("WoodBridgeSet")&&(t=ia.Wood),r=l.headType===O.TopLeft||l.headType===O.BottomRight,a=l.headType===O.TopLeft||l.headType===O.TopRight,e=l.headType}else{s=this.tileOccupation.getBridgeOnTile(o).tile;let e=this.getPieceAtTile(s);if(!e)throw new Error("Bridge head is not defined");var c=Va.getOverlayBridgeType(e.obj.overlayId);if(c===ia.NotBridge)throw new Error("Expected a bridge type");t=c,r=e.obj.isXBridge(),a=e.headType===$h.Start}var u=Number(r)*(a?1:-1),d=Number(!r)*(a?1:-1);let n;if(h){o=new al(this.tiles,this.mapBounds,s,1,100,u,d,e=>e.z===s.z&&this.tileSets.isHighBridgeBoundaryTile(e.tileNum)).getNextTile(),c=this.tileSets.getSetNum(s.tileNum);if(!o||this.tileSets.getSetNum(o.tileNum)!==c)return;o=this.findHighBridgeBoundary(o);if(!o)return;if(e!==this.tileSets.getOppositeHighBridgeHeadType(o.headType))return;n=o.tile}else{let t,i=1;for(var p=s.rx,g=s.ry;!t;){var m=this.tiles.getByMapCoords(p+u*i,g+d*i);if(!m)return;let e=this.getPieceAtTile(m);if(e&&e.obj.isXBridge()!==r)return;e?.headType===(a?$h.End:$h.Start)&&(t=e),i++}n=t.obj.tile}return{start:a?s:n,end:a?n:s,type:t,isHigh:h}}}findHighBridgeBoundary(r){var a,e=this.tileSets.getTile(r.tileNum),n=this.tileSets.getHighBridgeHeadType(e.index);if(void 0!==n){let i=0,s=0;switch(n){case O.TopLeft:i=1,s=0;break;case O.BottomRight:i=-1,s=0;break;case O.TopRight:i=0,s=1;break;case O.BottomLeft:i=0,s=-1;break;case O.MiddleTlBr:i=1,s=0;break;case O.MiddleTrBl:i=0,s=1;break;default:throw new Error(`Unhandled head type "${n}"`)}let e=new js(this.tiles,this.mapBounds,r,{width:1,height:1},0,5,e=>e.terrainType===Yt.Pavement&&e.z>=r.z&&e.tileNum===r.tileNum),t=[];for(;a=e.getNextTile();)t.push(a);if(t.sort((e,t)=>100*(i?i*(t.rx-e.rx):s*(t.ry-e.ry))+(i?e.ry-t.ry:e.rx-t.rx)),t.length)return{tile:t[0],headType:n}}else console.warn(`Couldn't find a valid bridge type for index "${e.index}" @ ${r.rx},${r.ry}`)}canBeRepaired(i){let e=this.createBridgePieceTileFinder(i,e=>!(this.getPieceAtTile(e)||this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===i.start.z)),s=!1,r;for(var a=i.start.rx!==i.end.rx?aa.BottomLeft:aa.BottomRight;r=e.getNextTile();){s=!0;let e=this.tiles.getNeighbourTile(r,a),t=this.tiles.getNeighbourTile(e,a);if(i.isHigh){if([r,e,t].find(e=>this.tileOccupation.getGroundObjectsOnTile(e).some(e=>e.isBuilding()&&!e.rules.invisibleInGame)))return!1}else if([r,e,t].find(e=>this.tileOccupation.getGroundObjectsOnTile(e).some(e=>!(e.isUnit()||e.isSmudge()||e.isOverlay()&&e.isBridgePlaceholder()))))return!1}return s}getPieceTiles(e){var t=e.obj.tile,i=e.obj.isXBridge()?aa.BottomLeft:aa.BottomRight,e=this.tiles.getNeighbourTile(t,i);return[t,e,this.tiles.getNeighbourTile(e,i)]}findMapHighBridgeHeadTiles(){var e,t=this.tiles.getAllBridgeSetTiles();let i=new Set;for(e of t){var s=this.findHighBridgeBoundary(e);s&&i.add(s.tile)}return i}findBridgeSpecsForHeadTiles(e){let t=new Map;for(var i of e){i=this.findClosestBridgeSpec(i);i&&t.set(i.start.id+":"+i.end.id,i)}return[...t.values()]}findAllBridgeTiles(e){let t=[];var i,s=e.start.rx!==e.end.rx?aa.BottomLeft:aa.BottomRight;for(i of this.findNonBuildablePieceTiles(e)){var r=this.tiles.getNeighbourTile(i,s),a=this.tiles.getNeighbourTile(r,s);t.push(i,r,a)}return t}findBridgePieces(e){let t=this.createBridgePieceTileFinder(e,e=>!!this.getPieceAtTile(e)),i=[];for(var s;s=t.getNextTile();)i.push(this.getPieceAtTile(s));return i}findDestroyedPieceTiles(t){let e=this.createBridgePieceTileFinder(t,e=>!(this.getPieceAtTile(e)||this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===t.start.z)),i=[];for(var s;s=e.getNextTile();)i.push(s);return i}findNonBuildablePieceTiles(t){let e=this.createBridgePieceTileFinder(t,e=>!(this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===t.start.z)),i=[];for(var s;s=e.getNextTile();)i.push(s);return i}createBridgePieceTileFinder(e,t){var i=e.start.rx!==e.end.rx;return new al(this.tiles,this.mapBounds,e.start,1,(i?e.end.rx-e.start.rx:e.end.ry-e.start.ry)-1,Number(i),Number(!i),t)}dispose(){this.pieces.forEach(e=>{e.prev=void 0,e.next=void 0}),this.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate)}}const ol=new(__webpack_require__(949).Vector2);class hl{constructor(e,t){this.box=e,this.config=t,this.parentMap=new Map,this.objects=[]}add(e,t=!0){var i=this.config.getKey(e);if(this.box.containsPoint(i)){if(!this.regions)return this.parentMap.get(e)?.remove(e),this.parentMap.set(e,this),this.objects.push({key:i,value:e}),t&&this.update(),!0;for(var s of this.regions)if(s.add(e,t))return!0}return!1}remove(t,e=!0){let i=this.parentMap.get(t);i&&(i===this?(this.parentMap.delete(t),this.objects.splice(this.objects.findIndex(e=>e.value===t),1),e&&this.parent?.update()):i.remove(t,e))}updateObject(t){let i=this.parentMap.get(t);if(i){var e=this.config.getKey(t);if(i.box.containsPoint(e))i.objects.find(e=>e.value===t).key=e;else{i.remove(t,!1);let e=i.parent;for(;e&&!e.add(t,!1);)e=e.parent}}}queryRange(e,t=[]){if(this.box.intersectsBox(e))if(this.regions)for(var i of this.regions)i.queryRange(e,t);else for(var s of this.objects)e.containsPoint(s.key)&&t.push(s.value);return t}update(){let e=0;if(this.regions){for(var t of this.regions)e+=t.update();e<=this.config.joinThreshold&&this.join()}else e=this.objects.length,e>=this.config.splitThreshold&&this.split()&&this.update();return e}split(){if(this.regions||this.config.maxDepth<=1)return!1;var t,e,i={getKey:this.config.getKey,joinThreshold:this.config.joinThreshold,splitThreshold:this.config.splitThreshold,maxDepth:this.config.maxDepth-1},s=this.generateRegions(),r=this.objects;this.objects=[],this.regions=[];for(t of s){let e=new hl(t,i);e.parentMap=this.parentMap,this.regions.push(e),e.parent=this}for(e of r)this.parentMap.delete(e.value),this.add(e.value,!1);return!0}join(){if(!this.regions)return!1;for(var e of this.regions){e.join(),e.parent=void 0;for(var t of e.objects)this.objects.push(t),this.parentMap.set(t.value,this)}return!(this.regions=void 0)}generateRegions(){let i=[this.box.clone()];var s=this.box.getCenter(ol);let r=i[0],a=r.clone();r.max.x=s.x,a.min.x=s.x,i.push(a);for(let e=0,t=i.length;e<t;e++)r=i[e],a=r.clone(),r.max.y=s.y,a.min.y=s.y,i.push(a);return i}}class ll{constructor(e){this.tiles=e,this.tileOcclusion=[];let t=this.tileOcclusion;for(var i of e.getAll())t[i.rx]=t[i.rx]||[],t[i.rx][i.ry]=new Set}addOccluder(t){let e=this.calculateTilesForGameObject(t);e.forEach(e=>this.occludeTile(e,t))}removeOccluder(t){let e=this.calculateTilesForGameObject(t);e.forEach(e=>this.unoccludeTile(e,t))}calculateTilesForGameObject(e){var t=e.art.occupyHeight,i=Math.max(0,t-2);let s=[];var r=e.getFoundation();for(let t=1;t<=i;t++)for(let e=0;e<r.width;e++)s.push(new Ss(e-t,-t));for(let t=1;t<=i;t++)for(let e=1;e<r.height;e++)s.push(new Ss(-t,e-t));s.push(...e.art.addOccupy);for(let{x:t,y:i}of e.art.removeOccupy){var a=s.findIndex(e=>e.x===t&&e.y===i);-1!==a&&s.splice(a,1)}var n,o,h=e.tile;let l=[];for({x:n,y:o}of s){var c=this.tiles.getByMapCoords(h.rx+n,h.ry+o);c&&l.push(c)}return l}occludeTile(e,t){this.tileOcclusion[e.rx][e.ry].add(t),e.occluded=!0}unoccludeTile(e,t){let i=this.tileOcclusion[e.rx][e.ry];i.delete(t),e.occluded=0<i.size}isTileOccluded(e){return 0<this.tileOcclusion[e.rx][e.ry].size}}class cl{static calculate(u,d){let p=new Map;u.forEach(e=>{var t=d.getSetNum(e.tileNum);p.set(e,t),d.isCLAT(t)&&(t=d.getLAT(t),p.set(e,t),e.tileNum=d.getTileNumFromSet(t))}),u.forEach(t=>{var i=p.get(t);if(d.isLAT(i)){let e=0;var s=u.getNeighbourTile(t,aa.TopRight),r=u.getNeighbourTile(t,aa.BottomRight),a=u.getNeighbourTile(t,aa.BottomLeft),n=u.getNeighbourTile(t,aa.TopLeft);s&&d.canConnectTiles(i,p.get(s))&&(e+=1),r&&d.canConnectTiles(i,p.get(r))&&(e+=2),a&&d.canConnectTiles(i,p.get(a))&&(e+=4),n&&d.canConnectTiles(i,p.get(n))&&(e+=8),0<e&&(n=d.getCLATSet(i),t.tileNum=d.getTileNumFromSet(n,e))}else if(i===d.getGeneralValue("RampBase")&&!(t.rampType<1||4<t.terrainType)){let e=-1;var o=u.getNeighbourTile(t,aa.TopRight),h=u.getNeighbourTile(t,aa.BottomRight),l=u.getNeighbourTile(t,aa.BottomLeft),c=u.getNeighbourTile(t,aa.TopLeft);switch(t.rampType){case 1:c&&0===c.rampType&&e++,h&&0===h.rampType&&(e+=2);break;case 2:o&&0===o.rampType&&e++,l&&0===l.rampType&&(e+=2);break;case 3:h&&0===h.rampType&&e++,c&&0===c.rampType&&(e+=2);break;case 4:l&&0===l.rampType&&e++,o&&0===o.rampType&&(e+=2)}-1!==e&&(t.tileNum=d.getTileNumFromSet(d.getGeneralValue("RampSmooth"),3*(t.rampType-1)+e))}})}}class ul{constructor(e,t,i,s){this.mapFile=e,this.tiles=new Ga(this.mapFile.tiles,t,i.general,s),this.mapBounds=(new rl).fromMapFile(this.mapFile,this.tiles),this.tileOccupation=new vo(this.tiles),this.tileOcclusion=new ll(this.tiles),this.terrain=new sl(this.tiles,this.mapFile.theaterType,this.mapBounds,this.tileOccupation,i),this.bridges=new nl(t,this.tiles,this.tileOccupation,this.mapBounds,i);let r=this.mapFile.tags;for(let t of this.mapFile.cellTags){let e=this.tiles.getByMapCoords(t.coords.x,t.coords.y);e&&(e.tag=r.find(e=>e.id===t.tagId))}s=this.tiles.getMapSize(),i=Math.max(s.width,s.height)/5;this.technosByTile=new hl(new Fn(new Ss(0,0),new Ss(s.width,s.height)),{getKey:e=>{e=e.isBuilding()?e.centerTile:e.tile;return new Ss(e.rx,e.ry)},maxDepth:this.computeQuadDepth(i),splitThreshold:10,joinThreshold:5}),this.mapFile.theaterType!==I.Snow&&cl.calculate(this.tiles,t)}get startingLocations(){return this.mapFile.startingLocations}computeQuadDepth(e){if(e<=1)return 1;let t=0;for(;1<=e/2;)e/=2,t++;return t+(1<e?1:0)}getLighting(){return this.mapFile.lighting}getIonLighting(){return this.mapFile.ionLighting}getTheaterType(){return this.mapFile.theaterType}getTags(){return this.mapFile.tags}getTriggers(){return this.mapFile.triggers}getCellTags(){return this.mapFile.cellTags}getVariables(){return this.mapFile.variables}getWaypoint(t){return this.mapFile.waypoints.find(e=>e.number===t)}getTileAtWaypoint(e){e=this.getWaypoint(e);if(e){e=this.tiles.getByMapCoords(e.rx,e.ry);if(e)return e}}isWithinBounds(e){return this.mapBounds.isWithinBounds(e)}clampWithinBounds(e){var t=this.mapBounds.clampWithinBounds(e);let i=this.tiles.getByDisplayCoords(t.dx,t.dy);if(i&&this.mapBounds.isWithinBounds(i)){let e=i,t=i.z;for(;0<=t&&e&&this.mapBounds.isWithinBounds(e);)i=e,e=this.tiles.getByDisplayCoords(e.dx,e.dy+2),t-=2}else{let e=0;for(;!i||!this.mapBounds.isWithinBounds(i);){if(30<e)throw new Error("Exceeded max elevation while trying to clamp tile to map bounds");i=this.tiles.getByDisplayCoords(t.dx,t.dy+e),e+=2}}return i}isWithinHardBounds(e){return this.mapBounds.isWithinHardBounds(e)}getInitialMapObjects(){return{terrains:this.mapFile.terrains,overlays:this.mapFile.overlays,smudges:this.mapFile.smudges,technos:[...this.mapFile.structures,...this.mapFile.infantries,...this.mapFile.vehicles,...this.mapFile.aircrafts]}}getObjectsOnTile(e){return this.tileOccupation.getObjectsOnTile(e)}getGroundObjectsOnTile(e){return this.tileOccupation.getGroundObjectsOnTile(e)}getTileZone(e,t=!1){return this.tileOccupation.getTileZone(e,t)}dispose(){this.terrain.dispose(),this.bridges.dispose()}}class dl{constructor(e,t){this.first=e,this.second=t}has(e){return this.first===e||this.second===e}equals(e){return this.first===e.first&&this.second===e.second||this.first===e.second&&this.second===e.first}}(r=qh=qh||{})[r.Requested=0]="Requested",r[r.Formed=1]="Formed";class pl{constructor(e){this.playerList=e,this.alliances=[]}findByPlayers(e,t){let i=new dl(e,t);return this.alliances.find(e=>e.players.equals(i))}filterByPlayer(t){return this.alliances.filter(e=>e.players.first===t||e.players.second===t)}request(e,t){if(!this.canRequestAlliance(t))throw new Error(`Player ${t.name} is not a human combatant.`);if(this.canFormAlliance(e,t)){if(this.findByPlayers(e,t))throw new Error("Can't request alliance because an alliance is already pending or formed between "+`${e.name} and ${t.name}.`);return this.setAlliance(e,t,qh.Requested)}}cancelRequest(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==qh.Requested)throw new Error(`There is no pending alliance request for player ${t.name} from player ${e.name}`);if(i.players.first!==e)throw new Error(`Can't cancel request initiated by the other player (${t.name})`);this.alliances.splice(this.alliances.indexOf(i),1)}acceptRequest(t,i){if(this.canFormAlliance(t,i)){let e=this.findByPlayers(t,i);if(!e||e.status!==qh.Requested)throw new Error(`There is no pending alliance request for player ${i.name} from player ${t.name}`);if(e.players.first!==t)throw new Error(`Can't accept own alliance request for player ${i.name}`);e.status=qh.Formed}}setAlliance(e,t,i){if(!this.canFormAlliance(e,t))throw new Error(`Can't form alliance between players "${e.name}" and "${t.name}"`);var s;if(s=this.findByPlayers(e,t))throw new Error(`An alliance already exists between players ${e.name} and ${t.name}`);return s={players:new dl(e,t),status:i},this.alliances.push(s),s}breakAlliance(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==qh.Formed)throw new Error(`There is no alliance between player ${e.name} and player ${t.name}`);this.alliances.splice(this.alliances.indexOf(i),1)}areAllied(e,t){t=this.findByPlayers(e,t);return!!t&&t.status===qh.Formed}getAllies(t){return this.filterByPlayer(t).filter(e=>e.status===qh.Formed).map(e=>e.players.first===t?e.players.second:e.players.first)}haveSharedIntel(e,t){return e.isObserver||t.isObserver||e===t||this.areAllied(e,t)}canRequestAlliance(e){return e.isCombatant()&&!e.isAi}canFormAlliance(t,i){let e=this.getHostilePlayers();if(0===e.filter(e=>e.has(t)&&!e.has(i)).length)return!1;if(0===e.filter(e=>e.has(i)&&!e.has(t)).length)return!1;let s=new dl(t,i);return!!e.filter(e=>!e.equals(s)).length}getHostilePlayers(){var i,s=this.playerList.getCombatants();let r=[];for(let t=0;t<s.length;t++)for(let e=t+1;e<s.length;e++)this.getAllies(s[t]).includes(s[e])||(i=new dl(s[t],s[e]),r.push(i));return r}getHash(){return H(this.alliances.map(e=>[this.playerList.getPlayerNumber(e.players.first),this.playerList.getPlayerNumber(e.players.second),e.status]).flat())}debugGetState(){return this.alliances.map(e=>({first:e.players.first,second:e.players.second,status:e.status}))}}class gl{constructor(){this.players=[]}addPlayer(e){this.players.push(e)}getPlayerAt(e){if(e>=this.players.length)throw new RangeError(`Player #${e} out of bounds`);return this.players[e]}getPlayerByName(t){var e=this.players.find(e=>e.name===t);if(!e)throw new Error(`Player with name "${t}" not found`);return e}getPlayerNumber(e){var t=this.players.indexOf(e);if(-1===t)throw new Error(`Player ${e.name} not found`);return t}getCombatants(){return this.players.filter(e=>e.isCombatant())}getNonNeutral(){return this.players.filter(e=>!e.isNeutral)}getCivilian(){return this.players.find(e=>e.country?.side===Xt.Civilian)}getAll(){return this.players}}(r=Xh=Xh||{})[r.None=0]="None",r[r.Hover=1]="Hover",r[r.Selected=2]="Selected",r[r.SelectedHover=3]="SelectedHover";class ml{constructor(e){this.selectionLevel=Xh.None,e.isBuilding()&&e.rules.wall?this.maxSelectionLevel=Xh.None:this.maxSelectionLevel=e.rules.selectable?Xh.Selected|Xh.Hover:Xh.Hover}getSelectionLevel(){return this.selectionLevel}setSelectionLevel(e){this.selectionLevel=Math.min(this.maxSelectionLevel,e)}setHover(e){this.setSelectionLevel(e?this.selectionLevel|Xh.Hover:this.selectionLevel&~Xh.Hover)}setSelected(e){this.setSelectionLevel(e?this.selectionLevel|Xh.Selected:this.selectionLevel&~Xh.Selected)}isHovered(){return this.selectionLevel>>Xh.Hover&1}isSelected(){return this.selectionLevel>=Xh.Selected}getControlGroupNumber(){return this.controlGroupNumber}setControlGroupNumber(e){this.controlGroupNumber=e}}class fl{constructor(){this.selectedUnits=new Set,this.selectionModelsByUnit=new Map,this.groups=new Map,this.hashNeedsUpdate=!0}getOrCreateSelectionModel(e){let t=this.selectionModelsByUnit.get(e);return t||(t=new ml(e),this.selectionModelsByUnit.set(e,t)),t}deselectAll(){this.selectedUnits.forEach(e=>this.selectionModelsByUnit.get(e)?.setSelected(!1)),this.selectedUnits.clear(),this.hashNeedsUpdate=!0}addToSelection(e){this.selectedUnits.add(e),this.getOrCreateSelectionModel(e).setSelected(!0),this.hashNeedsUpdate=!0}removeFromSelection(e){e.forEach(e=>{this.selectedUnits.delete(e),this.getOrCreateSelectionModel(e).setSelected(!1)}),this.hashNeedsUpdate=!0}getSelectedUnits(){return[...this.selectedUnits].filter(e=>!e.isDestroyed&&!e.isCrashing&&!e.isDisposed&&e.isSpawned)}isSelected(e){return this.selectedUnits.has(e)}cleanupUnit(e){this.selectionModelsByUnit.delete(e),this.selectedUnits.delete(e),this.unassignUnitsFromGroup([e]),this.hashNeedsUpdate=!0}updateHash(){this.hash=H([...this.selectedUnits].map(e=>e.id))}getHash(){return this.hashNeedsUpdate&&(this.updateHash(),this.hashNeedsUpdate=!1),this.hash}createGroup(e){this.addUnitsToGroup(e,this.getSelectedUnits())}addUnitsToGroup(e,t,i=!0){this.unassignUnitsFromGroup(t);let s=this.groups.get(e);s||(s=new Set,this.groups.set(e,s)),i&&([...s.values()].forEach(e=>this.selectionModelsByUnit.get(e)?.setControlGroupNumber(void 0)),s.clear());for(var r of t)s.add(r),this.getOrCreateSelectionModel(r).setControlGroupNumber(e)}addGroupToSelection(e){if(this.groups.has(e))for(var t of[...this.groups.get(e)])this.addToSelection(t)}selectGroup(e){this.deselectAll(),this.addGroupToSelection(e)}getGroupUnits(e){return[...this.groups.get(e)??[]]}unassignUnitsFromGroup(e){for(var t of this.groups.values())for(var i of e)t.delete(i)}}class yl{constructor(e){this._onChange=new ro,this.value=e}get value(){return this._value}set value(e){var t=e!==this._value;this._value=e,t&&this._onChange.dispatch(this,e)}get onChange(){return this._onChange.asEvent()}}class wl{constructor(e,t=void 0,i=0,s=new U(255,0,0)){this.name=e,this.country=t,this.startLocation=i,this.color=s,this.isAi=!1,this.defeated=!1,this.resigned=!1,this.dropped=!1,this.objectsByType=new Map,this.objectsById=new Map,this.traits=new Ca,this._credits=0,this.score=0,this.unitsBuiltByType=new Map,this.unitsKilledByType=new Map,this.unitsLostByType=new Map,this.buildingsCaptured=0,this.cratesPickedUp=0,this.cheerCooldownTicks=0,this.isObserver=!t,this.isNeutral=!!t&&!t.isPlayable()}get credits(){return this._credits}set credits(e){if(e<0)throw new RangeError("Can't set credits to a negative value");this._credits=e}getOrCreateObjectsForType(e){let t=this.objectsByType.get(e);return t||(t=new Set,this.objectsByType.set(e,t)),t}addOwnedObject(e){let t=this.getOrCreateObjectsForType(e.type);t.add(e),(e.owner=this).objectsById.set(e.id,e)}removeOwnedObject(e){let t=this.objectsByType.get(e.type);if(!t||!t.has(e))throw new Error(`GameObject ${e.name} does not belong to player ${this.name}`);t.delete(e),this.objectsById.delete(e.id)}getOwnedObjectById(e){return this.objectsById.get(e)}getOwnedObjectsByType(e,t=!1){let i=[];return i=[...this.objectsByType.get(e)||new Set],t||(i=i.filter(e=>!e.limboData)),i}getOwnedObjects(e=!1){let t=[];return[...this.objectsByType.values()].forEach(e=>{e.forEach(e=>t.push(e))}),e||(t=t.filter(e=>!e.limboData)),t}removeAllOwnedObjects(){this.objectsByType.forEach(e=>e.clear()),this.objectsById.clear()}get buildings(){return this.getOrCreateObjectsForType(Bt.Building)}addUnitsBuilt(e,t){this.unitsBuiltByType.set(e,(this.unitsBuiltByType.get(e)??0)+t)}getUnitsBuilt(e){return void 0!==e?this.unitsBuiltByType.get(e)??0:[...this.unitsBuiltByType.values()].reduce((e,t)=>e+t,0)}addUnitsKilled(e,t){this.unitsKilledByType.set(e,(this.unitsKilledByType.get(e)??0)+t)}getUnitsKilled(e){return void 0!==e?this.unitsKilledByType.get(e)??0:[...this.unitsKilledByType.values()].reduce((e,t)=>e+t,0)}addUnitsLost(e,t){this.unitsLostByType.set(e,(this.unitsLostByType.get(e)??0)+t)}getUnitsLost(e){return void 0!==e?this.unitsLostByType.get(e)??0:[...this.unitsLostByType.values()].reduce((e,t)=>e+t,0)}isCombatant(){return!this.isNeutral&&!this.isObserver&&!this.defeated}canProduceVeteran(e){if(!this.production||!this.country)throw new Error("Non-combatants can't produce units");var t=this.production.getQueueTypeForObject(e),t=this.production.getFactoryTypeForQueueType(t);return this.production.hasVeteranType(t)||this.country.hasVeteranUnit(e.type,e.name)}getHash(){return H([this.credits,...this.traits.getAll().map(e=>e.getHash?.()??0)])}debugGetState(){return{name:this.name,credits:this.credits,traits:this.traits.getAll().reduce((e,t)=>{var i=t.debugGetState?.();return void 0!==i&&(e[t.constructor.name]=i),e},{})}}dispose(){this.traits.dispose(),this.production?.dispose()}}class Tl{constructor(){this.disabled=!0,this.activeEvents=[]}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}}const bl=(new Map).set("POWER",Qt.Power).set("FACTORY",Qt.Factory).set("BARRACKS",Qt.Barracks).set("RADAR",Qt.Radar).set("TECH",Qt.Tech).set("PROC",Qt.Proc);class vl{constructor(e,t,i,s,r){this.player=e,this.maxTechLevel=t,this.gameOpts=i,this.rules=s,this.allAvailableObjects=r,this.buildSpeedModifier=1,this.queues=new Map,this._onQueueUpdate=new ro,this.primaryFactories=new Map,this.factoryCounts=new Map,this.veteranTypes=new Set,this.stolenTech=new Set}static factory(e,t,i,s){let r=new vl(e,t.mpDialogSettings.techLevel,i,t,s);t=t.general.maximumQueuedObjects+1;return r.addQueue(mn.Structures,new ao(mn.Structures,1,1)),r.addQueue(mn.Armory,new ao(mn.Armory,1,1)),r.addQueue(mn.Infantry,new ao(mn.Infantry,t,t)),r.addQueue(mn.Vehicles,new ao(mn.Vehicles,t,t)),r.addQueue(mn.Ships,new ao(mn.Ships,t,t)),r.addQueue(mn.Aircrafts,new ao(mn.Aircrafts,0,t)),r}get onQueueUpdate(){return this._onQueueUpdate.asEvent()}addQueue(e,t){this.queues.set(e,t),t.onUpdate.subscribe(()=>this._onQueueUpdate.dispatch(this,t))}getQueue(e){var t=this.queues.get(e);if(!t)throw new Error(`No queue found with type ${mn[e]}`);return t}getAllQueues(){return[...this.queues.values()]}getQueueTypeForObject(e){if(e.type===Bt.Building)return e.buildCat===Ki.Combat?mn.Armory:mn.Structures;if(e.type===Bt.Infantry)return mn.Infantry;if(e.type===Bt.Vehicle)return e.naval?mn.Ships:mn.Vehicles;if(e.type===Bt.Aircraft)return mn.Aircrafts;throw new Error(`Unsupported object type ${Bt[e.type]}`)}getQueueForObject(e){return this.getQueue(this.getQueueTypeForObject(e))}getQueueTypeForFactory(e){if(e===Ji.InfantryType)return mn.Infantry;if(e===Ji.UnitType)return mn.Vehicles;if(e===Ji.AircraftType)return mn.Aircrafts;if(e===Ji.NavalUnitType)return mn.Ships;throw new Error(`Unsupported factory type ${Ji[e]}`)}getFactoryTypeForQueueType(e){if(e===mn.Structures||e===mn.Armory)return Ji.BuildingType;if(e===mn.Infantry)return Ji.InfantryType;if(e===mn.Vehicles)return Ji.UnitType;if(e===mn.Aircrafts)return Ji.AircraftType;if(e===mn.Ships)return Ji.NavalUnitType;throw new Error(`Unsupported queue type ${mn[e]}`)}getQueueForFactory(e){return this.getQueue(this.getQueueTypeForFactory(e))}isAvailableForProduction(e){return e.isAvailableTo(this.player.country)&&-1!==e.techLevel&&e.techLevel<=this.maxTechLevel&&!(0===e.buildLimit&&!this.player.isAi)&&!(e.superWeapon&&this.rules.getSuperWeapon(e.superWeapon).disableableFromShell&&!this.gameOpts.superWeapons)&&this.hasFactoryFor(e)&&this.meetsPrerequisites(e)&&this.meetsStolenTech(e)}getAvailableObjects(){return this.allAvailableObjects.filter(e=>this.isAvailableForProduction(e))}hasFactoryFor(i){if(i.owner.length){let t=this.getFactoryTypeFor(i);return!![...this.player.buildings].find(e=>e.factoryTrait?.type===t&&(t!==Ji.UnitType||e.rules.naval===i.naval)&&!!e.rules.owner.find(e=>i.owner.includes(e)))}return!0}meetsStolenTech(e){return e.requiresStolenAlliedTech?this.stolenTech.has(Xt.GDI):!e.requiresStolenSovietTech||this.stolenTech.has(Xt.Nod)}getFactoryTypeFor(e){return e.type===Bt.Building?Ji.BuildingType:e.type===Bt.Infantry?Ji.InfantryType:e.type===Bt.Aircraft?Ji.AircraftType:e.naval?Ji.NavalUnitType:Ji.UnitType}meetsPrerequisites(e){let t=[...this.player.buildings].map(e=>e.name);var i;for(i of e.prerequisite)if(i=i.toUpperCase(),bl.has(i)){var s=bl.get(i);if(void 0===s)throw new Error(`Unknown prereqName ${i}`);var r,a=this.rules.general.prereqCategories.get(s);if(void 0===a)throw new Error(`Missing prerequisite category ${s} in rules`);let e=!1;for(r of a)if(-1!==t.indexOf(r)){e=!0;break}if(!e)return!1}else if(-1===t.indexOf(i))return!1;return!0}getPrimaryFactory(e){return this.primaryFactories.get(e)}setPrimaryFactory(e){e.rules.factory&&this.primaryFactories.set(e.rules.factory,e)}isPrimaryFactory(e){return this.getPrimaryFactory(e.rules.factory)===e}incrementFactoryCount(e){this.factoryCounts.set(e,(this.factoryCounts.get(e)??0)+1)}decrementFactoryCount(e){if(!this.factoryCounts.get(e))throw new Error(`Can't decrement factory count ${Ji[e]}. Already 0`);this.factoryCounts.set(e,this.factoryCounts.get(e)-1)}getFactoryCount(e){return this.factoryCounts.get(e)??0}crownPrimaryFactoryHeir(t){var e=[...this.player.buildings].find(e=>e.rules.factory===t);e?this.primaryFactories.set(t,e):this.primaryFactories.delete(t)}hasAnyFactory(){return 0<this.primaryFactories.size}addVeteranType(e){this.veteranTypes.add(e)}hasVeteranType(e){return this.veteranTypes.has(e)}addStolenTech(e){this.stolenTech.add(e)}dispose(){this.queues.clear(),this.player=void 0}}class Sl{constructor(){this.superWeapons=new Map}getAll(){return[...this.superWeapons.values()]}add(e){this.superWeapons.set(e.name,e)}has(e){return this.superWeapons.has(e)}get(e){return this.superWeapons.get(e)}remove(e){this.superWeapons.delete(e)}}class kl{constructor(){this.objects=new Set}add(e){this.objects.add(e)}delete(e){this.objects.delete(e)}has(e){return this.objects.has(e)}dispose(){this.objects.clear()}}class Ol{constructor(e,t,i){this.rules=e,this.gameOpts=t,this.allAvailableObjects=i}createCombatant(e,t,i,s,r,a){let n=new wl(e,t,i,s);return n.isAi=r,n.aiDifficulty=a,n.powerTrait=new io(n),n.traits.add(n.powerTrait),n.radarTrait=new Tl,n.traits.add(n.radarTrait),n.superWeaponsTrait=new Sl,n.traits.add(n.superWeaponsTrait),n.production=vl.factory(n,this.rules,this.gameOpts,this.allAvailableObjects),n.sharedDetectDisguiseTrait=new kl,n}createObserver(e,t){let i=new wl(e,void 0,void 0,t.colors.get("LightGrey"));return i.radarTrait=new Tl,i.traits.add(i.radarTrait),i.radarTrait.setDisabled(!1),i}createNeutral(e,t){var i=[...e.countryRules.values()].find(e=>e.side===Xt.Civilian);if(!i)throw new Error("Missing neutral country. No country found in rules with Civilian side");i=new Xn(i);let s=new wl(t,i,void 0,e.colors.get("LightGrey"));return s.powerTrait=new io(s),s.traits.add(s.powerTrait),s}}(Zh=Zh||{}).onSpawn=Symbol(),(Qh=Qh||{}).onUnspawn=Symbol(),(Yh=Yh||{}).onChange=Symbol();class _l{[Zh.onSpawn](e,t){e.isTechno()&&e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"add",t)}[Qh.onUnspawn](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"remove",t)}[Nn.onChange](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"update",t)}[Yh.onChange](e,t,i){e.rules.power&&!e.warpedOutTrait.isActive()&&(this.isCapturablePower(e,t)||t.powerTrait?.updateFrom(e,"remove",i),this.isCapturablePower(e,e.owner)||e.owner.powerTrait?.updateFrom(e,"add",i))}[Es.onChange](e,t,i){e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,i?"remove":"add",t)}[xs.onTick](e){for(var t of e.getCombatants())t.powerTrait.updateBlackout(e)}isCapturablePower(e,t){return 0<e.rules.power&&t.isNeutral&&e.rules.needsEngineer}}class Il{constructor(e){this.target=e,this.type=is.BuildingSell}}class Cl{constructor(e,t){this.game=e,this.generalRules=t}sell(t){if(!t.rules.unsellable){let e=this.computeRefundValue(t);e&&(t.rules.wall&&(e=0),t.traits.filter(wn).forEach(e=>{e[wn.onSell](t,this.game)}),t.isBuilding()?this.game.getConstructionWorker(t.owner).unplace(t,()=>this.afterObjectUnspawned(t,e)):(this.game.unspawnObject(t),this.afterObjectUnspawned(t,e)))}}afterObjectUnspawned(e,t){e.owner.credits+=t,e.isBuilding()&&this.game.events.dispatch(new Il(e)),e.dispose()}computeRefundValue(e){let t=0;return 0<e.rules.soylent?t=e.rules.soylent:e.rules.cost&&(t=e.purchaseValue,e.owner.isAi||(t=Math.floor(t*this.generalRules.refundPercent))),t}computePurchaseValue(e,t){return e.cost}dispose(){this.game=void 0}}class Al{constructor(e,t){this.target=e,this.radarEnabled=t,this.type=is.RadarOnOff}}class Bl{constructor(e,t,i){this.target=e,this.radarEventType=t,this.tile=i,this.type=is.RadarEvent}}class xl{constructor(){this.activeLightningStrikes=new Map}[Zh.onSpawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Qh.onUnspawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Ms.onPowerLow](e,t){this.updateRadarForPlayer(e,t)}[Ms.onPowerRestore](e,t){this.updateRadarForPlayer(e,t)}[Ms.onPowerChange](){}[Yh.onChange](e,t,i){e.rules.radar&&(this.updateRadarForPlayer(t,i),this.updateRadarForPlayer(e.owner,i))}[Es.onChange](e,t){e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Ds.onActivate](e,t,i){if(e===ts.LightningStorm){this.activeLightningStrikes.set(t,(this.activeLightningStrikes.get(t)??0)+1);for(var s of i.getCombatants())s===t||i.alliances.areAllied(s,t)||this.updateRadarForPlayer(s,i)}}[la.onDeactivate](e,t,i){if(e===ts.LightningStorm){e=(this.activeLightningStrikes.get(t)??0)-1;if(0<e?this.activeLightningStrikes.set(t,e):this.activeLightningStrikes.delete(t),e<=0)for(var s of i.getCombatants())this.updateRadarForPlayer(s,i)}}updateRadarForPlayer(i,s){var e,t;i.radarTrait&&(e=i.radarTrait?.isDisabled(),t=![...i.buildings].find(e=>e.rules.radar&&!e.warpedOutTrait.isActive())||i.powerTrait.level===gn.Low||[...this.activeLightningStrikes.entries()].some(([e,t])=>t&&e!==i&&!s.alliances.areAllied(e,i)),i.radarTrait.setDisabled(t),e!==t&&s.events.dispatch(new Al(i,!t)))}[sa.onAttack](e,t,i){e.isTechno()&&(!e.isBuilding()||e.rules.canBeOccupied||e.rules.needsEngineer?e.isVehicle()&&e.harvesterTrait&&this.addEventForPlayer(Zt.HarvesterUnderAttack,e.owner,e.tile,i):this.addEventForPlayer(Zt.BaseUnderAttack,e.owner,e.tile,i))}addEventForPlayer(s,e,r,a){let n=e.radarTrait;if(n){let t=a.rules.general.radar;n.activeEvents=n.activeEvents.filter(e=>a.currentTick-e.startTick<t.getEventDuration(e.type));let i=new Cs(a.map.tileOccupation);!!n.activeEvents.find(e=>e.type===s&&i.isInTileRange(r,e.tile,0,t.getEventSuppresionDistance(e.type)))||(n.activeEvents.push({startTick:a.currentTick,tile:r,type:s}),a.events.dispatch(new Bl(e,s,r)))}}}class El{constructor(e){this.target=e,this.type=is.InsufficientFunds}}class Pl{constructor(e,t){this.rules=e,this.speedCheat=t,this.availableObjectRules=new Set;t=60*e.general.buildSpeed*Fs.BASE_TICKS_PER_SECOND;this.baseBuildSpeed=1/(t/1e3),[...e.buildingRules.values(),...e.infantryRules.values(),...e.vehicleRules.values(),...e.aircraftRules.values()].forEach(e=>{e.owner.length&&this.availableObjectRules.add(e)})}[xs.onTick](e){for(var t of e.getCombatants())for(var i of t.production.getAllQueues())this.tickQueue(i,t,e)}[Zh.onSpawn](e,t){var i;e.isBuilding()&&e.owner.production?(i=e.rules.factory)&&(e.owner.production.getPrimaryFactory(i)||e.owner.production.setPrimaryFactory(e),e.owner.production.incrementFactoryCount(i),i===Ji.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t)):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[Qh.onUnspawn](e,t){var i;e.isBuilding()&&e.owner.production?(this.ensurePrerequisites(e.owner),(i=e.rules.factory)&&(e.owner.production.getPrimaryFactory(i)===e&&e.owner.production.crownPrimaryFactoryHeir(i),e.owner.production.decrementFactoryCount(i),i===Ji.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t))):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[Yh.onChange](e,t,i){var s;e.isBuilding()?(this.ensurePrerequisites(t),(s=e.rules.factory)&&(t.production?.getPrimaryFactory(s)===e&&t.production.crownPrimaryFactoryHeir(s),e.owner.production&&!e.owner.production.getPrimaryFactory(s)&&e.owner.production.setPrimaryFactory(e),t.production?.decrementFactoryCount(s),e.owner.production?.incrementFactoryCount(s),s===Ji.AircraftType&&(this.updateAircraftQueueMaxSize(e.owner,i),this.updateAircraftQueueMaxSize(t,i)))):e.isAircraft()&&this.rules.general.padAircraft.includes(e.name)&&(this.updateAircraftQueueMaxSize(e.owner,i),this.updateAircraftQueueMaxSize(t,i))}[Ms.onPowerLow](e){e.production&&(e.production.buildSpeedModifier=this.computeLowPowerBuildSpeedModifier(e.powerTrait.power,e.powerTrait.drain))}[Ms.onPowerRestore](e){e.production&&(e.production.buildSpeedModifier=1)}[Ms.onPowerChange](e){e.powerTrait?.level===gn.Low&&e.production&&(e.production.buildSpeedModifier=this.computeLowPowerBuildSpeedModifier(e.powerTrait.power,e.powerTrait.drain))}computeLowPowerBuildSpeedModifier(e,t){e=1-Math.min(1,e/t),t=this.rules.general;return W(1-.3*t.lowPowerPenaltyModifier*e/.15,t.minLowPowerProductionSpeed,t.maxLowPowerProductionSpeed)}updateAircraftQueueMaxSize(i,s){i.production&&s.afterTick(()=>{var e=[...i.buildings].filter(e=>e.helipadTrait).reduce((e,t)=>e+t.dockTrait.numberOfDocks,0),t=i.getOwnedObjectsByType(Bt.Aircraft,!0).filter(e=>s.rules.general.padAircraft.includes(e.name)).length;i.production.getQueueForFactory(Ji.AircraftType).maxSize=Math.max(0,e-t)})}tickQueue(i,s,r){if(i.status===fn.Active){let e=!1,t=i.getFirst();var a,n=s.production.getFactoryTypeForQueueType(i.type),o=s.production.getFactoryCount(n),h=s.production.buildSpeedModifier,n=1/Qi.pow(this.rules.general.multipleFactory,o-1),o=t.rules.wall?1/this.rules.general.wallBuildSpeedCoefficient:1,n=this.baseBuildSpeed*h*n*o,o=t.creditsEach,n=o&&!this.speedCheat.value?(l=o/n,c=54,Math.floor(l/c)*c):54,n=Math.max(54,n),l=s.credits,c=t.creditsEach-t.creditsSpent,c=Math.min(s.credits,o/n+t.creditsSpentLeftover,c);0<c?(a=Math.floor(c),t.creditsSpentLeftover=c-a,a&&(t.creditsSpent+=a,t.progress=t.creditsSpent/t.creditsEach,s.credits-=a,e=!0)):t.creditsEach||(a=t.progress*n,t.progress=Math.min(1,(1+a)/n),e=!0),e&&1===t.progress&&(i.status=fn.Ready),0<l&&!s.credits&&r.events.dispatch(new El(s)),e&&i.notifyUpdated()}}ensurePrerequisites(e){if(e.production)for(var t of e.production.getAllQueues()){var i;for(i of t.getAll().map(e=>({rules:e.rules,quantity:e.quantity,creditsSpent:e.creditsSpent})))e.production.isAvailableForProduction(i.rules)||(t.pop(i.rules,i.quantity),e.credits+=i.creditsSpent)}}getAvailableObjects(){return[...this.availableObjectRules]}}(Kh=Kh||{}).onChange=Symbol();class Nl{constructor(e,t){this.map=e,this.alliances=t,this.shroudByPlayer=new Map,this.revealedToAll=new Set,this.gapGenerators=new Set,this.handleTileOccupationUpdate=({object:e,type:t})=>{if("removed"!==t&&e.isTechno()){var i,t=e.owner;for(i of[t,...this.alliances.getAllies(t)])this.shroudByPlayer.get(i)?.revealFrom(e)}}}getPlayerShroud(e){return this.shroudByPlayer.get(e)}init(t){t.map.tileOccupation.onChange.subscribe(this.handleTileOccupationUpdate);let i=(new Uo).fromTiles(this.map.tiles);for(var s of t.getCombatants()){let e=i.clone();this.shroudByPlayer.set(s,e),this.revealObjects(e,s,t),e.update()}}[Gr.onElevationChange](e,t,i){if(Math.floor(e.tileElevation)!==Math.floor(i)){var s,i=e.owner;for(s of[i,...this.alliances.getAllies(i)])this.shroudByPlayer.get(s)?.revealFrom(e)}}[xs.onTick](e){for(var[t,i]of this.shroudByPlayer)t.defeated&&!t.isObserver?this.shroudByPlayer.delete(t):i.update()}[Yh.onChange](e,t,i){if(e.isBuilding()&&e.rules.spySat&&(this.revealMap(e.owner,i),t.getOwnedObjectsByType(Bt.Building).find(e=>e.rules.spySat)||this.resetShroud(t,i)),e.isSpawned)for(var s of[e.owner,...i.alliances.getAllies(e.owner)])this.shroudByPlayer.get(s)?.revealFrom(e)}[Kh.onChange](t,e,i){if(e){let e=this.getPlayerShroud(t.players.first);var s,r,t=i.alliances.getAllies(t.players.first).map(e=>this.getPlayerShroud(e)).filter(Fa);for(s of t)e.merge(s);e.invalidateFull();for(r of t)r.copy(e),r.invalidateFull()}}[Zh.onSpawn](e,t){if(e.isBuilding()){if(e.rules.spySat&&this.revealMap(e.owner,t),e.rules.revealToAll){this.revealedToAll.add(e);for(var i of t.getCombatants())i===e.owner||t.alliances.areAllied(e.owner,i)||(this.shroudByPlayer.get(i)?.revealObject(e),t.traits.get(xl).addEventForPlayer(Zt.EnemyObjectSensed,i,e.centerTile,t))}e.gapGeneratorTrait&&this.gapGenerators.add(e)}}[Qh.onUnspawn](e,t){e.isBuilding()&&(e.rules.spySat&&(e.owner.getOwnedObjectsByType(Bt.Building).find(e=>e.rules.spySat)||this.resetShroud(e.owner,t)),e.rules.revealToAll&&this.revealedToAll.delete(e),e.gapGeneratorTrait&&this.gapGenerators.delete(e))}[Ms.onPowerLow](e,t){this.updateGaps(t,e)}[Ms.onPowerRestore](e,t){this.updateGaps(t,e)}[Ms.onPowerChange](e,t){}revealMap(e,t){this.shroudByPlayer.get(e)?.revealAll(),this.markOwnGapTiles(t,e),this.updateGaps(t)}resetShroud(e,t){let i=this.shroudByPlayer.get(e);i&&(i.reset(),this.markOwnGapTiles(t,e),this.revealObjects(i,e,t))}revealObjects(t,e,i){var s;for(s of[...e.getOwnedObjects(),...i.alliances.getAllies(e).map(e=>e.getOwnedObjects()).flat()])t.revealFrom(s);this.revealedToAll.forEach(e=>t.revealObject(e))}updateGaps(e,t){for(var i of this.gapGenerators)t&&i.owner!==t||i.gapGeneratorTrait.update(i,e)}markOwnGapTiles(e,t){for(var i of this.gapGenerators)i.owner!==t&&!e.alliances.areAllied(i.owner,t)||this.getPlayerShroud(t)?.toggleFlagsAround(i.tile,i.gapGeneratorTrait.radiusTiles,_n.Darken,!0)}dispose(){this.map.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate)}}class Ml extends Hs{onTick(e){return!(e.buildStatus!==In.BuildDown&&(e.buildStatus=In.BuildDown,!e.rules.wall))||(this.children.push(new pa(.035)),!1)}}class Dl{constructor(){this.disposables=new Set}add(...e){e.map(e=>this.disposables.add("function"==typeof e?{dispose:e}:e))}remove(...e){e.map(e=>this.disposables.delete(e))}dispose(){this.disposables.forEach(e=>{"function"==typeof e?e():e.dispose?e.dispose():e.destroy()}),this.disposables.clear()}}class Rl{constructor(e,t,i,s,r){this.player=e,this.rules=t,this.art=i,this.map=s,this.game=r,this.adjacencyMaps=new Map,this.disposables=new Dl;let a=({object:e})=>{e.isBuilding()&&this.adjacencyMaps.clear()};this.map.tileOccupation.onChange.subscribe(a),this.disposables.add(()=>this.map.tileOccupation.onChange.unsubscribe(a)),this.disposables.add(this.game.events.subscribe(is.AllianceChange,()=>this.adjacencyMaps.clear()),this.game.events.subscribe(is.ObjectOwnerChange,e=>{e.target.isBuilding()&&this.adjacencyMaps.clear()}),this.game.events.subscribe(is.ObjectDestroy,e=>{e.target.isBuilding()&&e.target.rules.leaveRubble&&this.adjacencyMaps.clear()}))}getAdjacentRect(e,t,i){return{x:e.rx-i,y:e.ry-i,width:t.width+2*i,height:t.height+2*i}}getAdjacencyMap(e){var t;let i=[];for(t of[...this.player.buildings,...this.game.gameOpts.buildOffAlly?this.game.alliances.getAllies(this.player).map(e=>[...e.buildings].filter(e=>e.rules.eligibileForAllyBuilding)).flat():[]])t.rules.baseNormal&&i.push(this.getAdjacentRect(t.tile,t.art.foundation,e));return i}meetsAdjacency(e,t){let i=this.adjacencyMaps.get(t);i||(i=this.getAdjacencyMap(t),this.adjacencyMaps.set(t,i));for(var s of i)if(r=e,s=s,r.x<=s.x+s.width&&s.x<=r.x+r.width&&r.y<=s.y+s.height&&s.y<=r.y+r.height)return!0;var r;return!1}getPlacementPreview(e,t,i={}){var{normalizedTile:s=!1,ignoreObjects:r,ignoreAdjacent:i=!1}=i,a=this.rules.getBuilding(e),e=this.art.getObject(e,Bt.Building);let n=[];var o=e.foundation,h=s?t:this.normalizePlacementTileCoords(e,t);let l=!0;t={x:h.rx,y:h.ry,width:o.width,height:o.height};a.constructionYard||i||this.meetsAdjacency(t,a.adjacent)||(l=!1);for(let t=0;t<o.width;t++)for(let e=0;e<o.height;e++){var c={x:h.rx+t,y:h.ry+e},u=this.map.tiles.getByMapCoords(c.x,c.y);u&&n.push({rx:c.x,ry:c.y,buildable:l&&this.isTileBuildable(u,a,r)})}if(a.wall&&n[0].buildable){let e=this.getWallConnectingTiles(h,a);e.forEach(e=>{n.push({rx:e.rx,ry:e.ry,buildable:!0})})}return n}canPlaceAt(e,t,i={}){var{normalizedTile:s=!1,ignoreObjects:r,ignoreAdjacent:i=!1}=i,a=this.rules.getBuilding(e),e=this.art.getObject(e,Bt.Building),n=e.foundation,o=s?t:this.normalizePlacementTileCoords(e,t),t={x:o.rx,y:o.ry,width:n.width,height:n.height};if(!a.constructionYard&&!i&&!this.meetsAdjacency(t,a.adjacent))return!1;for(let t=0;t<n.width;t++)for(let e=0;e<n.height;e++){var h={x:o.rx+t,y:o.ry+e},h=this.map.tiles.getByMapCoords(h.x,h.y);if(!h||!this.isTileBuildable(h,a,r))return!1}return!0}placeAt(e,t,i=!1){let s=[],r=this.rules.getBuilding(e),a=i?t:this.normalizePlacementTile(e,t);if(r.wall){let t=[[a,r]],e=this.getWallConnectingTiles(a,r);e.forEach(e=>{e!==a&&t.push([e,r])});for(var n of t)s.push(this.executePlacement(n[0],n[1]));e.forEach(e=>{e=this.map.getObjectsOnTile(e).find(e=>e.isBuilding()&&e.name===r.name&&e.owner===this.player);this.connectWall(e)})}else{var o,t=this.executePlacement(a,r);s.push(t);for(o of this.map.tileOccupation.calculateTilesForGameObject(a,t)){var h=this.map.getObjectsOnTile(o).find(e=>e.isSmudge());h&&this.game.unspawnObject(h)}}return s}normalizePlacementTileCoords(e,t){e=e.foundationCenter;return{rx:t.rx-e.x,ry:t.ry-e.y}}normalizePlacementTile(e,t){e=this.art.getObject(e,Bt.Building),e=this.normalizePlacementTileCoords(e,t),t=this.map.tiles.getByMapCoords(e.rx,e.ry);if(!t)throw new Error(`Can't build outside map (${e.rx}, ${e.ry})`);return t}unplace(e,t){e.unitOrderTrait.cancelAllTasks(),e.unitOrderTrait.addTasks(new ja(new Ml,new ga(()=>{this.game.unspawnObject(e),e.rules.wall&&this.updateAdjacentWalls(e),t()})).setCancellable(!1))}executePlacement(e,t){let i=this.game.createObject(Bt.Building,t.name);return this.game.changeObjectOwner(i,this.player),i.purchaseValue=this.game.sellTrait.computePurchaseValue(t,this.player),this.game.spawnObject(i,e),i}getWallConnectingTiles(i,s){var r,a=s.guardRange+1;let n=[];for(r of[[0,1],[0,-1],[1,0],[-1,0]]){let t=[];for(let e=0;e<a;++e){var o={x:i.rx+r[0]*e,y:i.ry+r[1]*e},o=this.map.tiles.getByMapCoords(o.x,o.y);if(!o)break;if(this.map.getObjectsOnTile(o).find(e=>e.isBuilding()&&e.name===s.name&&e.owner===this.player)){n=n.concat(t);break}if(!this.isTileBuildable(o,s))break;t.push(o)}}return n}getAdjacentBuildingData(e,t){var i;let s=[];for(i of[[0,1],[0,-1],[1,0],[-1,0]]){var r={x:e.rx+i[0],y:e.ry+i[1]},a=this.map.tiles.getByMapCoords(r.x,r.y);a&&((r=this.map.getObjectsOnTile(a).find(e=>e.isBuilding()&&e.name===t&&e.owner===this.player))&&s.push({direction:i,tile:a,building:r}))}return s}updateAdjacentWalls(t){let e=new yo(this.map.tiles,this.map.mapBounds,t.tile,1,1);for(e.diagonal=!1;i=e.getNextTile();){var i=this.map.getObjectsOnTile(i).find(e=>e.isBuilding()&&e.name===t.rules.name&&e.owner===this.player);i&&this.connectWall(i)}}connectWall(e){let t=this.getAdjacentBuildingData(e.tile,e.name);this.updateWallType(e,t.map(e=>e.direction)),t.forEach(e=>{let t=this.getAdjacentBuildingData(e.tile,e.building.name);this.updateWallType(e.building,t.map(e=>e.direction))})}updateWallType(e,t){e.wallType=[0,0,0,0];for(var i of t)0===i[0]&&-1===i[1]&&(e.wallType[0]=1),1===i[0]&&0===i[1]&&(e.wallType[1]=1),0===i[0]&&1===i[1]&&(e.wallType[2]=1),-1===i[0]&&0===i[1]&&(e.wallType[3]=1)}isTileBuildable(e,t,i){return!!this.map.isWithinBounds(e)&&(!this.game.mapShroudTrait.getPlayerShroud(this.player)?.isShrouded(e)&&(!this.map.getGroundObjectsOnTile(e).some(e=>!(i?.includes(e)||e.isBuilding()&&e.rules.invisibleInGame||e.isSmudge()))&&(t.waterBound?0<this.rules.getLandRules(e.landType).getSpeedModifier(Jt.Float):0===e.rampType&&this.rules.getLandRules(e.landType).buildable)))}dispose(){this.disposables.dispose()}}class Ll{static generate(e,t,i,s){var r,a=i.reduce((e,t)=>e+t.cost,0)/i.length*e;let n=[],o=a,h=(i=i.filter(e=>e.isAvailableTo(s)&&e.hasOwner(s))).filter(e=>t.includes(e.name));for(r of h){if(o<=0)break;var l=2/3/h.length,l=Math.ceil(l*a/r.cost);o-=l*r.cost,n.push({name:r.name,type:Bt.Vehicle,count:l})}var c,i=i.filter(e=>!h.includes(e)),u=o/i.length;for(c of i){if(o<=0)break;var d=Math.ceil(u/c.cost);o-=d*c.cost,n.push({name:c.name,type:Bt.Infantry,count:d})}return n}}class Fl{constructor(){this.dispatcher=new ro,this.dispatchersByType=new Map}dispatch(e){this.dispatcher.dispatch(void 0,e),this.dispatchersByType.get(e.type)?.dispatch(void 0,e)}subscribe(e,t){let i=void 0,s;return s="function"==typeof e?e:(i=e,t),void 0===i?(this.dispatcher.subscribe(s),()=>this.unsubscribe(s)):this.subscribeType(i,s)}unsubscribe(e,t){let i=void 0,s;s="function"==typeof e?e:(i=e,t),void 0===i?this.dispatcher.unsubscribe(s):this.unsubscribeType(i,s)}subscribeType(e,t){let i=this.dispatchersByType.get(e);return i||(i=new ro,this.dispatchersByType.set(e,i)),i.subscribe(t),()=>this.unsubscribeType(e,t)}unsubscribeType(e,t){this.dispatchersByType.get(e)?.unsubscribe(t)}}class jl{constructor(e,t,i){this.target=e,this.attackerInfo=t,this.incidental=i,this.type=is.ObjectDestroy}}class Ul{constructor(e){this.target=e,this.type=is.PlayerDefeated}}(Jh=Jh||{}).onDestroy=Symbol();class Wl{constructor(e,t){this.target=e,this.prevOwner=t,this.type=is.ObjectOwnerChange}}class zl{constructor(e){this.gameObject=e,this.type=is.ObjectUnspawn}}class Vl{constructor(e){this.gameObject=e,this.type=is.ObjectSpawn}}(r=el=el||{})[r.Requested=0]="Requested",r[r.Formed=1]="Formed",r[r.Broken=2]="Broken";class Hl{constructor(e,t,i){this.alliance=e,this.changeType=t,this.from=i,this.type=is.AllianceChange}}var Gl,$l,ql,Xl,Zl,Ql,Yl,Kl,Jl,ec,tc,r=__webpack_require__(948),ic=__webpack_require__.n(r);class sc{constructor(e){this.prng=new(ic())(e)}generateRandomInt(e,t){var i=this.prng.random();return this.lastRandom=i,Math.round(i*(t-e))+e}generateRandom(){var e=this.prng.random();return this.lastRandom=e}getLastRandom(){return this.lastRandom}}class rc{constructor(e,t){this.action=e,this.trigger=t}getDebugName(){return`${this.action.triggerId}[${this.action.index}] (${this.trigger.name}).`}}class ac extends rc{constructor(e,t,i){super(e,t),this.oneTimeOnly=i,this.superWeaponIdx=Number(e.params[1])}execute(i){var s=[...i.rules.superWeaponRules.values()].find(e=>e.index===this.superWeaponIdx);if(s){let t=i.getAllPlayers().find(e=>e.country?.name===this.trigger.houseName);if(t&&t.superWeaponsTrait&&!t.superWeaponsTrait.has(s.name)){let e=i.createSuperWeapon(s.name,t,this.oneTimeOnly);e.isGift=!0,t.superWeaponsTrait.add(e)}}else console.warn(`No superweapon found with index "${this.superWeaponIdx}". `+`Skipping action ${this.getDebugName()}.`)}}class nc extends rc{constructor(e,t,i){super(e,t),this.damage=i}execute(t){var e=Number(this.action.params[1]),i=t.map.getTileAtWaypoint(e);if(i){var s=t.rules.getWarhead(Qa.HE_WARHEAD_NAME);let e=new Qa(s);var r=t.map.tileOccupation.getBridgeOnTile(i),a=r?.tileElevation??0,s=t.map.getTileZone(i);e.detonate(t,this.damage,i,a,ks.tile3dToWorld(i.rx+.5,i.ry+.5,i.z+a),s,r?ra.OnBridge:ra.None,t.createTarget(r,i),void 0,!1,!1,void 0)}else console.warn(`No valid location found for waypoint ${e}. `+`Skipping action ${this.getDebugName()}.`)}}class oc extends rc{execute(e){let i=e.getAllPlayers().find(e=>e.country?.name===this.trigger.houseName);if(i){let t=Number(this.action.params[1]);var s=e.getAllPlayers().find(e=>e.country?.id===t);if(s)for(var r of i.getOwnedObjects(!0))e.changeObjectOwner(r,s)}}}class hc extends rc{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}execute(e,t){var i=e.getAllPlayers().find(e=>e.country?.id===this.houseId);if(i)for(var s of t)s instanceof Aa&&s.isSpawned&&e.changeObjectOwner(s,i)}}class lc extends Hs{constructor(){super(),this.executed=!1,this.cancellable=!1}onTick(e){return this.executed?(e.stance=Rs.None,!0):!e.isInfantry()||!e.art.sequences.has(dn.Cheer)||(e.stance!==Rs.None&&e.stance!==Rs.Guard||(e.stance=Rs.Cheer,this.children.push(new pa(1/60).setCancellable(!1)),!(this.executed=!0)))}}class cc extends rc{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}execute(e){let t=e.getAllPlayers().filter(e=>e.country&&!e.defeated);if(-1!==this.houseId&&(t=t.filter(e=>e.country?.id===this.houseId)),t.length)for(var i of t[0].getOwnedObjectsByType(Bt.Infantry))i.unitOrderTrait.isIdle()&&i.unitOrderTrait.addTask(new lc)}}const uc=new Map([[0,e=>{e=e.rules.powerups.powerups.find(e=>e.type===Bs.Money);return e?{...e,data:"5000"}:void 0}],[1,Bs.Unit],[2,Bs.HealBase],[3,Bs.Cloak],[4,Bs.Explosion],[5,Bs.Napalm],[6,Bs.Money],[7,Bs.Darkness],[8,Bs.Reveal],[9,Bs.Armor],[10,Bs.Speed],[11,Bs.Firepower],[12,Bs.ICBM],[13,void 0],[14,Bs.Veteran],[15,void 0],[16,Bs.Gas],[17,Bs.Tiberium],[18,void 0]]);class dc extends rc{execute(e){var t=Number(this.action.params[1]),i=this.action.params[6],s=e.map.getTileAtWaypoint(i);if(s)if(uc.has(t)){const r=uc.get(t);t="function"==typeof r?r(e):e.rules.powerups.powerups.find(e=>e.type===r);t&&e.crateGeneratorTrait.spawnCrateAt(s,t,e)}else e.crateGeneratorTrait.spawnRandomCrateAt(s,e);else console.warn(`No valid location found for waypoint ${i}. `+`Skipping action ${this.getDebugName()}.`)}}class pc extends rc{execute(e){var t=Number(this.action.params[1])-1;if(Object.values(Zt).includes(t)){var i=this.action.params[6],s=e.map.getTileAtWaypoint(i);if(s)for(var r of e.getCombatants())e.traits.get(xl).addEventForPlayer(t,r,s,e);else console.warn(`No valid location found for waypoint ${i}. `+`Skipping action ${this.getDebugName()}.`)}else console.warn(`Unknown radar event type "${1+t}". Skipping action ${this.getDebugName()}.`)}}class gc extends rc{execute(e,t){for(var i of t)i instanceof Aa&&i.isSpawned&&e.destroyObject(i)}}class mc extends rc{execute(e){var t=this.action.params[1];e.triggers.destroyTag(t)}}class fc extends rc{execute(e){var t=this.action.params[1];e.triggers.destroyTrigger(t)}}class yc extends rc{execute(s){var r=Number(this.action.params[1]),e=this.action.params[6],a=s.map.getTileAtWaypoint(e);if(a){let t;try{t=s.rules.getWeaponByInternalId(r)}catch(e){if(e instanceof RangeError)return void console.warn(`Weapon with internal ID "${r}" not found. `+`Skipping action ${this.getDebugName()}.`);throw e}let e;try{e=s.rules.getWarhead(t.warhead)}catch(e){return void console.warn(`Warhead "${t.warhead}" not found. `+`Skipping action ${this.getDebugName()}.`)}let i=new Qa(e);var n=s.map.tileOccupation.getBridgeOnTile(a),o=n?.tileElevation??0,r=s.map.getTileZone(a);i.detonate(s,t.damage,a,o,ks.tile3dToWorld(a.rx+.5,a.ry+.5,a.z+o),r,n?ra.OnBridge:ra.None,s.createTarget(n,a),void 0,!1,!1,void 0)}else console.warn(`No valid location found for waypoint ${e}. `+`Skipping action ${this.getDebugName()}.`)}}class wc extends rc{execute(e,t){for(var i of t)i instanceof Aa&&i.isBuilding()&&i.garrisonTrait&&!i.isDestroyed&&i.garrisonTrait.evacuate(e)}}class Tc extends rc{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}execute(e){var t=e.getAllPlayers().find(e=>e.country?.id===this.houseId);if(t)for(var i of t.buildings)e.sellTrait.sell(i)}}class bc extends rc{execute(e){e.end()}}class vc extends rc{execute(e){var t=this.action.params[1];e.triggers.forceTrigger(t,e)}}class Sc extends rc{constructor(e,t,i){super(e,t),this.value=i,this.variableIdx=Number(e.params[1])}execute(e){e.triggers.toggleGlobalVariable(this.variableIdx,this.value)}}class kc extends rc{execute(e){var t,i,s=this.action.params[6],r=e.map.getTileAtWaypoint(s);r?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===ts.IronCurtain))&&e.traits.get(hn).activateEffect(i,t,e,r,void 0,!0):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class Oc extends rc{execute(e){var t,i,s=this.action.params[6],r=e.map.getTileAtWaypoint(s);r?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===ts.LightningStorm))&&e.traits.get(hn).activateEffect(i,t,e,r,void 0,!0):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class _c extends rc{constructor(e,t,i){super(e,t),this.value=i,this.variableIdx=Number(e.params[1])}execute(e){e.triggers.toggleLocalVariable(this.variableIdx,this.value)}}class Ic extends rc{execute(){}}class Cc extends rc{execute(e){var t,i,s=this.action.params[6],r=e.map.getTileAtWaypoint(s);r?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===ts.MultiMissile))&&e.traits.get(hn).activateEffect(i,t,e,r,void 0,!0):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class Ac{constructor(e,t){this.name=e,this.tile=t,this.type=is.TriggerAnim}}class Bc extends rc{execute(e){var t,i=this.action,s=Number(i.params[1]),r=e.rules.getAnimationName(s);void 0!==r?(t=i.params[6],(i=e.map.getTileAtWaypoint(t))?e.events.dispatch(new Ac(r,i)):console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)):console.warn(`No animation found for index "${s}". Skipping action ${this.getDebugName()}`)}}class xc{constructor(e,t){this.soundId=e,this.tile=t,this.type=is.TriggerSoundFx}}class Ec extends rc{execute(e){var t=this.action,i=t.params[1],s=t.params[6],t=e.map.getTileAtWaypoint(s);t?e.events.dispatch(new xc(i,t)):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class Pc extends rc{execute(e){e.events.dispatch(new xc(this.action.params[1]))}}class Nc{constructor(e){this.soundId=e,this.type=is.TriggerEva}}class Mc extends rc{execute(e){e.events.dispatch(new Nc(this.action.params[1]))}}class Dc extends rc{execute(e){for(var t of e.getCombatants())e.mapShroudTrait.resetShroud(t,e)}}class Rc extends rc{execute(e){var[t,i,s,r]=this.action.params.slice(2,6).map(Number);e.map.mapBounds.updateRawLocalSize({x:t,y:i,width:s,height:r})}}class Lc extends rc{execute(e){var t=Number(this.action.params[1]),i=e.map.getTileAtWaypoint(t);if(i)for(var s of e.getCombatants())e.mapShroudTrait.getPlayerShroud(s)?.revealAround(i,e.rules.general.revealTriggerRadius);else console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class Fc extends rc{execute(e){for(var t of e.getCombatants())e.mapShroudTrait.revealMap(t,e)}}class jc extends rc{execute(e,t){for(var i of t)i instanceof Aa&&i.isBuilding()&&!i.isDestroyed&&e.sellTrait.sell(i)}}class Uc extends rc{execute(e){var t=Number(this.action.params[1])/100;e.mapLightingTrait.setTargetAmbientIntensity(t)}}function Wc(e){let t=new DataView(new ArrayBuffer(4));return t.setInt32(0,e),t.getFloat32(0)}class zc extends rc{execute(e){var t=Wc(Number(this.action.params[1]));e.mapLightingTrait.setAmbientChangeRate(t)}}class Vc extends rc{execute(e){var t=Wc(Number(this.action.params[1]));e.mapLightingTrait.setAmbientChangeStep(t)}}class Hc{constructor(e){this.tile=e,this.type=is.TriggerStopSoundFx}}class Gc extends rc{execute(e){var t=this.action.params[6],i=e.map.getTileAtWaypoint(t);i?e.events.dispatch(new Hc(i)):console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class $c{constructor(e){this.label=e,this.type=is.TriggerText}}class qc extends rc{execute(e){e.events.dispatch(new $c(this.action.params[1]))}}class Xc extends rc{execute(e){e.countdownTimer.addSeconds(Number(this.action.params[1]))}}class Zc extends rc{execute(e){e.countdownTimer.setSeconds(Number(this.action.params[1]))}}class Qc extends rc{execute(e){e.countdownTimer.addSeconds(-Number(this.action.params[1]))}}class Yc extends rc{execute(e){e.countdownTimer.start()}}class Kc extends rc{execute(e){e.countdownTimer.stop()}}class Jc extends rc{execute(e){e.countdownTimer.text=this.action.params[1]}}class eu extends rc{constructor(e,t,i){super(e,t),this.triggerEnable=i}execute(e){var t=this.action.params[1];e.triggers.setTriggerEnabled(t,this.triggerEnable)}}class tu extends rc{constructor(e,t,i){super(e,t),this.turnOn=i}execute(e,t){for(var i of t)i instanceof Aa&&i.isBuilding()&&i.poweredTrait?.setTurnedOn(this.turnOn)}}class iu extends rc{execute(e){var t=Number(this.action.params[1]),i=e.map.getTileAtWaypoint(t);if(i)for(var s of e.getCombatants())e.mapShroudTrait.getPlayerShroud(s)?.unrevealAround(i,e.rules.general.revealTriggerRadius);else console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class su{create(e,t){switch(e.type){case qt.NoAction:return new Ic(e,t);case qt.FireSale:return new Tc(e,t);case qt.TextTrigger:return new qc(e,t);case qt.DestroyTrigger:return new fc(e,t);case qt.ChangeHouse:return new hc(e,t);case qt.RevealMap:return new Fc(e,t);case qt.RevealAroundWaypoint:return new Lc(e,t);case qt.PlaySoundFx:return new Pc(e,t);case qt.PlaySpeech:return new Mc(e,t);case qt.ForceTrigger:return new vc(e,t);case qt.TimerStart:return new Yc(e,t);case qt.TimerStop:return new Kc(e,t);case qt.TimerExtend:return new Xc(e,t);case qt.TimerShorten:return new Qc(e,t);case qt.TimerSet:return new Zc(e,t);case qt.GlobalSet:return new Sc(e,t,!0);case qt.GlobalClear:return new Sc(e,t,!1);case qt.DestroyObject:return new gc(e,t);case qt.AddOneTimeSuperWeapon:return new ac(e,t,!0);case qt.AddRepeatingSuperWeapon:return new ac(e,t,!1);case qt.AllChangeHouse:return new oc(e,t);case qt.ResizePlayerView:return new Rc(e,t);case qt.PlayAnimAt:return new Bc(e,t);case qt.DetonateWarhead:return new yc(e,t);case qt.ReshroudMap:return new Dc(e,t);case qt.EnableTrigger:return new eu(e,t,!0);case qt.DisableTrigger:return new eu(e,t,!1);case qt.CreateRadarEvent:return new pc(e,t);case qt.LocalSet:return new _c(e,t,!0);case qt.LocalClear:return new _c(e,t,!1);case qt.SellBuilding:return new jc(e,t);case qt.TurnOffBuilding:return new tu(e,t,!1);case qt.TurnOnBuilding:return new tu(e,t,!0);case qt.ApplyOneHundredDamage:return new nc(e,t,100);case qt.ForceEnd:return new bc(e,t);case qt.DestroyTag:return new mc(e,t);case qt.SetAmbientStep:return new Vc(e,t);case qt.SetAmbientRate:return new zc(e,t);case qt.SetAmbientLight:return new Uc(e,t);case qt.NukeStrike:return new Cc(e,t);case qt.PlaySoundFxAt:return new Ec(e,t);case qt.UnrevealAroundWaypoint:return new iu(e,t);case qt.LightningStrike:return new Oc(e,t);case qt.TimerText:return new Jc(e,t);case qt.CreateCrate:return new dc(e,t);case qt.IronCurtainAt:return new kc(e,t);case qt.EvictOccupiers:return new wc(e,t);case qt.Cheer:return new cc(e,t);case qt.StopSoundsAt:return new Gc(e,t);default:throw new Error(`Unhandled action type "${qt[e.type]}"`)}}}class ru{constructor(e,t){this.event=e,this.trigger=t,this.blocking=!1,this.targets=[]}init(e){e=e.getAllPlayers().find(e=>e.country?.name===this.trigger.houseName);e&&(this.player=e)}setTargets(e){this.targets=e}reset(){}getDebugName(){return`${this.event.triggerId}[${this.event.eventIndex}] (${this.trigger.name}).`}}class au extends ru{constructor(e,t,i){super(e,t),this.type=i,this.threshold=Number(e.params[1])/100}check(e){var t=this.previousAmbient,e=e.mapLightingTrait.getAmbient().ambient;return this.previousAmbient=e,void 0!==t&&t!==e&&("above"===this.type?e>=this.threshold&&t<this.threshold:e<=this.threshold&&t>this.threshold)}}class nu extends ru{check(e){return!0}}class ou extends ru{check(s,e){return e.filter(e=>{if(e.type!==is.ObjectAttacked)return!1;let t=e.target;if(!t.isTechno()||!this.targets.includes(t))return!1;var i=e.attacker?.player;return(!i||!s.alliances.areAllied(i,t.owner)&&i!==t.owner)&&!e.incidental}).map(e=>e.target)}}class hu extends ru{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==is.ObjectAttacked)return!1;let t=e.target;if(!t.isTechno()||!this.targets.includes(t))return!1;e=e.attacker?.player;return e&&(-1===this.houseId||e?.country?.id===this.houseId)}).map(e=>e.target)}}class lu extends ru{constructor(e,t,i=!1){super(e,t),this.negate=i,this.objectIndex=Number(e.params[1])}check(){if(!this.player)return!1;for(var e of this.player.buildings)if(e.rules.index===this.objectIndex)return!this.negate;return this.negate}}class cu extends ru{constructor(e,t,i){super(e,t),this.objectType=i,this.objectIndex=Number(e.params[1])}check(e,t){return t.some(e=>e.type===is.ObjectSpawn&&e.gameObject.type===this.objectType&&e.gameObject.rules.index===this.objectIndex)}}class uu extends ru{constructor(e,t){super(e,t)}init(e){super.init(e);var t=Number(this.event.params[1]);this.waypointTile=e.map.getTileAtWaypoint(t),this.waypointTile||console.warn(`No valid location found for waypoint ${t}. `+`Skipping event ${this.getDebugName()}.`)}check(t,e){if(!this.waypointTile||!this.player)return!1;for(var i of e)if(i.type===is.EnterTile&&i.source.owner===this.player){let e=new Cs(t.map.tileOccupation);if(e.tileDistance(i.target,this.waypointTile)<2)return!0}return!1}}class du extends ru{constructor(e,t){super(e,t),this.threshold=Number(e.params[1])}check(e,t){return!!this.player&&this.player.credits<this.threshold}}class pu extends ru{constructor(e,t){super(e,t),this.threshold=Number(e.params[1])}check(e,t){return!!this.player&&this.player.credits>this.threshold}}class gu extends ru{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(t=>t.type===is.EnterTile&&t.source.zone!==bs.Air&&this.targets.some(e=>e.ry===t.target.ry)&&(-1===this.houseId||t.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class mu extends ru{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(t=>t.type===is.EnterTile&&t.source.zone!==bs.Air&&this.targets.some(e=>e.rx===t.target.rx)&&(-1===this.houseId||t.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class fu extends ru{constructor(e,t){super(e,t),this.allDestroyed=!1,this.houseId=Number(e.params[1])}check(e,t){return!!this.allDestroyed||!!t.some(e=>{if(e.type!==is.ObjectDestroy)return!1;let t=e.target;return!(!t.isBuilding()||t.owner.country?.id!==this.houseId)&&!t.owner.buildings.size})&&(this.allDestroyed=!0)}}class yu extends ru{constructor(e,t){super(e,t),this.allDestroyed=!1,this.houseId=Number(e.params[1])}check(e,t){return!!this.allDestroyed||!!t.some(e=>{if(e.type!==is.ObjectDestroy)return!1;let t=e.target;return!(!t.isTechno()||t.owner.country?.id!==this.houseId)&&!t.owner.getOwnedObjects(!0).length})&&(this.allDestroyed=!0)}}class wu extends ru{constructor(e,t){super(e,t),this.allDestroyed=!1,this.houseId=Number(e.params[1])}check(e,t){return!!this.allDestroyed||!!t.some(e=>{if(e.type!==is.ObjectDestroy)return!1;let t=e.target;return!(!t.isUnit()||t.owner.country?.id!==this.houseId)&&!this.hasUnitsLeft(t.owner)})&&(this.allDestroyed=!0)}hasUnitsLeft(e){var t;for(t of[Bt.Aircraft,Bt.Vehicle,Bt.Infantry])if(e.getOwnedObjectsByType(t,!0).length)return!0;return!1}}class Tu extends ru{constructor(e,t){super(e,t),this.allDestroyed=!1,this.houseId=Number(e.params[1])}check(e,t){return!!this.allDestroyed||!!t.some(e=>{if(e.type!==is.ObjectDestroy)return!1;let t=e.target;return!(!t.isUnit()||t.owner.country?.id!==this.houseId)&&!this.hasLandUnitsLeft(t.owner)})&&(this.allDestroyed=!0)}hasLandUnitsLeft(e){var t;for(t of[Bt.Vehicle,Bt.Infantry])if(e.getOwnedObjectsByType(t,!0).filter(e=>!e.rules.naval).length)return!0;return!1}}class bu extends ru{constructor(e,t){super(e,t),this.allDestroyed=!1,this.houseId=Number(e.params[1])}check(e,t){return!!this.allDestroyed||!!t.some(e=>{if(e.type!==is.ObjectDestroy)return!1;let t=e.target;return!(!t.isVehicle()||t.owner.country?.id!==this.houseId)&&!t.owner.getOwnedObjectsByType(Bt.Vehicle,!0).filter(e=>e.rules.naval).length})&&(this.allDestroyed=!0)}}class vu extends ru{check(s,e){return e.filter(e=>{if(e.type!==is.ObjectDestroy)return!1;let t=e.target;if(!t.isOverlay()||!t.isBridge())return!1;e=t.bridgeTrait?.bridgeSpec;if(!e)return!1;let i=s.map.bridges.findAllBridgeTiles(e);return i.find(e=>this.targets.includes(e))}).map(e=>e.target.tile)}}class Su extends ru{constructor(e,t){super(e,t),this.count=0,this.threshold=Number(e.params[1])}check(e,t){if(!this.player)return!1;if(this.count>=this.threshold)return!0;for(var i of t)if(i.type===is.ObjectDestroy){let e=i.target;e.isBuilding()&&e.owner.country?.id===this.houseId&&this.count++}return this.count>=this.threshold}}class ku extends ru{check(s,e){return e.filter(e=>{if(e.type!==is.ObjectDestroy)return!1;let t=e.target;if(!t.isTechno()||!this.targets.includes(t))return!1;var i=e.attackerInfo?.player;return(!i||!s.alliances.areAllied(i,t.owner)&&i!==t.owner)&&!e.incidental}).map(e=>e.target)}}class Ou extends ru{check(e,t){return t.filter(e=>{if(e.type!==is.ObjectDestroy&&e.type!==is.ObjectOwnerChange)return!1;let t=e.target;return!(!t.isTechno()||!this.targets.includes(t))}).map(e=>e.target)}}class _u extends ru{constructor(){super(...arguments),this.eventsFilter=[is.ObjectDestroy,is.ObjectOwnerChange,is.BuildingInfiltration]}check(e,t){return t.filter(e=>{if(!this.eventsFilter.includes(e.type))return!1;let t=e.target;return!(!t.isTechno()||!this.targets.includes(t))}).map(e=>e.target)}}class Iu extends ru{constructor(e,t){super(e,t),this.count=0,this.threshold=Number(e.params[1])}check(e,t){if(!this.player)return!1;if(this.count>=this.threshold)return!0;for(var i of t)if(i.type===is.ObjectDestroy){let e=i.target;e.isUnit()&&e.owner.country?.id===this.houseId&&this.count++}return this.count>=this.threshold}}class Cu extends ru{constructor(e,t){super(e,t),this.timerTicks=Number(this.event.params[1])*Fs.BASE_TICKS_PER_SECOND}check(e){return e.currentTick>this.timerTicks}}class Au extends ru{constructor(e,t){super(e,t),this.elapsedTicks=0,this.timerTicks=Number(this.event.params[1])*Fs.BASE_TICKS_PER_SECOND}check(e){return this.elapsedTicks++>this.timerTicks}reset(){this.elapsedTicks=0}}class Bu extends ru{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(e=>(e.type===is.EnterObject||e.type===is.EnterTile)&&this.targets.includes(e.target)&&(e.type!==is.EnterTile||e.source.zone!==bs.Air)&&(-1===this.houseId||e.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class xu extends ru{constructor(e,t,i){super(e,t),this.value=i,this.blocking=!0,this.variableIdx=Number(e.params[1])}check(e){return e.triggers.getGlobalVariable(this.variableIdx)===this.value}}class Eu extends ru{constructor(e,t,i){super(e,t),this.threshold=i}check(e,t){return t.filter(e=>{if(e.type!==is.HealthChange)return!1;let t=e.target;return!(!t.isTechno()||!this.targets.includes(t))&&(e.currentHealth<this.threshold&&e.prevHealth>this.threshold)}).map(e=>e.target)}}class Pu extends ru{constructor(e,t,i){super(e,t),this.threshold=i}check(e,t){return t.filter(e=>{if(e.type!==is.InflictDamage)return!1;let t=e.target;return!(!t.isTechno()||!this.targets.includes(t))&&(e.currentHealth<this.threshold&&e.prevHealth>this.threshold)}).map(e=>e.target)}}class Nu extends ru{constructor(e,t,i){super(e,t),this.value=i,this.blocking=!0,this.variableIdx=Number(e.params[1])}check(e){return e.triggers.getLocalVariable(this.variableIdx)===this.value}}class Mu extends ru{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}init(e){super.init(e),this.targetPlayer=e.getAllPlayers().find(e=>e.country?.id===this.houseId)}check(){return!!this.targetPlayer?.powerTrait?.isLowPower()}}class Du extends ru{check(e){return!1}}class Ru extends ru{check(){if(!this.player)return!1;for(var e of this.player.buildings)if(e.factoryTrait)return!1;return!0}}class Lu extends ru{check(e,t){return t.some(e=>e.type===is.CratePickup)}}class Fu extends ru{check(e,t){return t.filter(e=>e.type===is.CratePickup&&this.targets.includes(e.source)).map(e=>e.source)}}class ju extends ru{constructor(){super(...arguments),this.elapsedTicks=0}check(e){return this.timerTicks??(this.timerTicks=Math.floor(e.generateRandomInt(50,150)/100*Number(this.event.params[1]))*Fs.BASE_TICKS_PER_SECOND),this.elapsedTicks++>this.timerTicks}reset(){this.timerTicks=void 0,this.elapsedTicks=0}}class Uu extends ru{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(e=>e.type===is.BuildingInfiltration&&this.targets.includes(e.target)&&(-1===this.houseId||e.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class Wu extends ru{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==is.BuildingInfiltration)return!1;var t=e.target;return!!this.targets.includes(t)&&(-1===this.houseId||e.source.disguiseTrait?.getDisguise()?.owner?.country?.id===this.houseId)}).map(e=>e.target)}}class zu extends ru{constructor(e,t){super(e,t),this.infantryIdx=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==is.BuildingInfiltration)return!1;var t=e.target;return!!this.targets.includes(t)&&e.source.disguiseTrait?.getDisguise()?.rules.index===this.infantryIdx}).map(e=>e.target)}}class Vu extends ru{check(e,t){return t.some(e=>e.type===is.TimerExpire)}}class Hu{create(e,t){switch(e.type){case $t.NoEvent:return new Du(e,t);case $t.EnteredBy:return new Bu(e,t);case $t.SpiedBy:return new Uu(e,t);case $t.AttackedByAny:return new ou(e,t);case $t.DestroyedByAny:return new ku(e,t);case $t.AnyEvent:return new nu(e,t);case $t.DestroyedAllUnits:return new wu(e,t);case $t.DestroyedAllBuildings:return new fu(e,t);case $t.DestroyedAll:return new yu(e,t);case $t.CreditsExceed:return new pu(e,t);case $t.ElapsedTime:return new Au(e,t);case $t.MissionTimerExpired:return new Vu(e,t);case $t.DestroyedBuildings:return new Su(e,t);case $t.DestroyedUnits:return new Iu(e,t);case $t.NoFactoriesLeft:return new Ru(e,t);case $t.BuildBuilding:return new cu(e,t,Bt.Building);case $t.BuildUnit:return new cu(e,t,Bt.Vehicle);case $t.BuildInfantry:return new cu(e,t,Bt.Infantry);case $t.BuildAircraft:return new cu(e,t,Bt.Aircraft);case $t.CrossesHorizontalLine:return new gu(e,t);case $t.CrossesVerticalLine:return new mu(e,t);case $t.GlobalIsSet:return new xu(e,t,!0);case $t.GlobalIsCleared:return new xu(e,t,!1);case $t.DestroyedOrCaptured:return new Ou(e,t);case $t.LowPower:return new Mu(e,t);case $t.DestroyedBridge:return new vu(e,t);case $t.BuildingExists:return new lu(e,t);case $t.ComesNearWaypoint:return new uu(e,t);case $t.LocalIsSet:return new Nu(e,t,!0);case $t.LocalIsCleared:return new Nu(e,t,!1);case $t.FirstDamagedCombat:return new Pu(e,t,100);case $t.HalfHealthCombat:return new Pu(e,t,50);case $t.QuarterHealthCombat:return new Pu(e,t,25);case $t.FirstDamagedAny:return new Eu(e,t,100);case $t.HalfHealthAny:return new Eu(e,t,50);case $t.QuarterHealthAny:return new Eu(e,t,25);case $t.AttackedByHouse:return new hu(e,t);case $t.AmbientLightBelow:return new au(e,t,"below");case $t.AmbientLightAbove:return new au(e,t,"above");case $t.ElapsedScenarioTime:return new Cu(e,t);case $t.DestroyedOrCapturedOrInfiltrated:return new _u(e,t);case $t.PickupCrate:return new Fu(e,t);case $t.PickupCrateAny:return new Lu(e,t);case $t.RandomDelay:return new ju(e,t);case $t.CreditsBelow:return new du(e,t);case $t.SpyEnteringAsHouse:return new Wu(e,t);case $t.SpyEnteringAsInfantry:return new zu(e,t);case $t.DestroyedAllUnitsNaval:return new bu(e,t);case $t.DestroyedAllUnitsLand:return new Tu(e,t);case $t.BuildingNotExists:return new lu(e,t,!0);default:throw new Error(`Unhandled trigger event type "${$t[e.type]}"`)}}}class Gu{constructor(){this.disposables=new Dl,this.triggerInstances=new Map,this.targetsByTag=new Map,this.conditionFactory=new Hu,this.executorFactory=new su,this.pendingGameEvents=[],this.globalVariables=new Map,this.localVariables=new Map}init(i){var t,e,s,r,a=i.map.getInitialMapObjects()["technos"];for(let t of a)if(t.tag){let e=this.targetsByTag.get(t.tag);e||(e=[],this.targetsByTag.set(t.tag,e));var n=i.map.tiles.getByMapCoords(t.rx,t.ry);!n||(n=i.map.getObjectsOnTile(n).find(e=>e.name===t.name&&e.type===t.type))&&e.push(n)}for(t of i.map.getCellTags()){var o=i.map.tiles.getByMapCoords(t.coords.x,t.coords.y);if(o){let e=this.targetsByTag.get(t.tagId);e||(e=[],this.targetsByTag.set(t.tagId,e)),e.push(o)}else console.warn(`CellTag out of bounds at (${t.coords.x}, ${t.coords.y}). Skipping.`)}for([e,s]of i.map.getVariables())this.localVariables.set(e,s.clone());for(r of i.map.getTriggers())this.triggerInstances.set(r.id,this.createTriggerInstance(r,i));this.disposables.add(i.events.subscribe(e=>this.pendingGameEvents.push(e)))}createTriggerInstance(i,s){let r=this.targetsByTag.get(i.tag.id)??[];return{trigger:i,conditions:i.events.map(e=>{let t=this.conditionFactory.create(e,i);return t.setTargets(r),t.init(s),t}).sort((e,t)=>Number(t.blocking)-Number(e.blocking)),targets:r,remainingTargets:new Set(i.tag.repeatType===Gt.OnceAll?r:[]),disabled:i.disabled,finished:!1}}update(i){var s,r=this.pendingGameEvents.splice(0,this.pendingGameEvents.length);for(s of this.triggerInstances.values())if(!s.finished&&!s.disabled){let e=!0,t=[];for(var a of s.conditions){var n=a.check(i,r);if("boolean"==typeof n?n||(e=!1):n.length?t.push(...n):e=!1,a.blocking&&!e)break}if(e){var o=s.trigger;s.conditions.forEach(e=>e.reset?.());let e=[];if(o.tag.repeatType===Gt.OnceAll){for(var h of t)s.remainingTargets.delete(h);if(s.remainingTargets.size)continue;e=t.length?[t[t.length-1]]:[]}else e=s.targets;this.executeActions(o,e,i),o.tag.repeatType!==Gt.Repeat&&(s.finished=!0)}}}executeActions(t,i,s){for(var r of t.actions){let e=this.executorFactory.create(r,t);e.execute(s,i)}}setTriggerEnabled(e,t){let i=this.triggerInstances.get(e);i&&(i.disabled=!t)}forceTrigger(e,t){e=this.triggerInstances.get(e);e&&this.executeActions(e.trigger,e.targets,t)}destroyTrigger(e){this.triggerInstances.delete(e)}destroyTag(e){let t=[];for(var[i,s]of this.triggerInstances)s.trigger.tag.id===e&&t.push(i);for(var r of t)this.destroyTrigger(r)}getGlobalVariable(e){return!!this.globalVariables.get(e)?.value}toggleGlobalVariable(e,t){let i=this.globalVariables.get(e);void 0===i?this.globalVariables.set(e,new bi("No name",t)):i.value=t}getLocalVariable(e){return!!this.localVariables.get(e)?.value}toggleLocalVariable(e,t){let i=this.localVariables.get(e);void 0===i?this.localVariables.set(e,new bi("No name",t)):i.value=t}dispose(){this.disposables.dispose()}}class $u{constructor(e){this.target=e,this.type=is.TimerExpire}}class qu{constructor(){this.ticks=0,this.running=!1}getSeconds(){return Math.floor(this.ticks/Fs.BASE_TICKS_PER_SECOND)}setSeconds(e){this.ticks=Math.max(0,Math.floor(Fs.BASE_TICKS_PER_SECOND*e))}addSeconds(e){this.ticks=Math.max(0,this.ticks+Math.floor(Fs.BASE_TICKS_PER_SECOND*e))}start(){this.running=!0}stop(){this.running=!1}isRunning(){return this.running}update(e){this.running&&(0<this.ticks?this.ticks--:(this.running=!1,e.events.dispatch(new $u(this))))}}(Gl=Gl||{}).onAdd=Symbol(),(r=$l=$l||{})[r.NotStarted=0]="NotStarted",r[r.Started=1]="Started",r[r.Ended=2]="Ended";class Xu{constructor(e,t,i,s,r,a,n,o,h,l,c,u,d,p,g){this.updatableObjects=new Set,this.constructionWorkers=new Map,this.currentTick=0,this.currentTime=0,this.countdownTimer=new qu,this._onEnd=new ro,this.afterTickCallbacks=[],this.events=new Fl,this.traits=new Ca,this.debugText=new yl(""),this.world=e,this.map=t,this.rules=i,this.art=s,this.ai=r,this.id=a,this.startTimestamp=n,this.prng=new sc(Number(a+""+n)),this.gameOpts=o,this.gameModeType=h,this.playerList=l,this.unitSelection=c,this.alliances=u,this.desiredSpeed=new yl(Fs.computeGameSpeed(o.gameSpeed)),this.speed=new yl(this.desiredSpeed.value),this.nextObjectId=d,this.objectFactory=p,this.botManager=g,this.triggers=new Gu}get onEnd(){return this._onEnd.asEvent()}addPlayer(e){this.playerList.addPlayer(e),this.constructionWorkers.set(e,this.createConstructionWorker(e))}getPlayer(e){return this.playerList.getPlayerAt(e)}getPlayerByName(e){return this.playerList.getPlayerByName(e)}getAiPlayerName(e){let t;return t="number"==typeof e?e:this.gameOpts.aiPlayers.indexOf(e),`@@AI${t+1}@@`}getPlayerNumber(e){return this.playerList.getPlayerNumber(e)}getCombatants(){return this.playerList.getCombatants()}getCivilianPlayer(){return this.playerList.getCivilian()}getAllPlayers(){return this.playerList.getAll()}getNonNeutralPlayers(){return this.playerList.getNonNeutral()}areFriendly(e,t){return e.owner===t.owner||this.alliances.areAllied(e.owner,t.owner)}getWorld(){return this.world}createConstructionWorker(e){return new Rl(e,this.rules,this.art,this.map,this)}getConstructionWorker(e){var t=this.constructionWorkers.get(e);if(!t)throw new Error(`No construction worker found for player "${e.name}"`);return t}getUnitSelection(){return this.unitSelection}init(e){this.localPlayer=e,this.createMapObjects(),this.createPlayerInitialUnits(),this.map.terrain.computeAllPassabilityGraphs(),this.mapShroudTrait.init(this),this.crateGeneratorTrait.init(this),this.playerList.getAll().forEach(e=>e.credits=this.gameOpts.credits),this.rules.mpDialogSettings.alliesAllowed&&this.createInitialTeams()}start(){this.status=$l.Started,this.currentTick=0,this.currentTime=0,this.botManager.init(this),this.triggers.init(this)}createInitialTeams(){for(let t=0;t<this.gameOpts.maxSlots;t++){var i=[...this.gameOpts.humanPlayers,...this.gameOpts.aiPlayers].filter(e=>e?.teamId===t&&-3!==e.countryId).map(e=>As(e)?e.name:this.getAiPlayerName(e));if(1<i.length)for(let t=0;t<i.length-1;t++)for(let e=t+1;e<i.length;e++){var s=this.getPlayerByName(i[t]),r=this.getPlayerByName(i[e]),r=this.alliances.setAlliance(s,r,qh.Formed);this.onAllianceChange(r,s,!0)}}}createMapObjects(){var e=this.rules.general.harvesterUnit.every(e=>!z(this.rules.getObject(e,Bt.Vehicle).techLevel,0,this.rules.mpDialogSettings.techLevel)),t=this.map.getInitialMapObjects();this.createInitialMapTerrains(t.terrains,e),this.createInitialMapOverlays(t.overlays,e),this.createInitialMapSmudges(t.smudges),this.createInitialMapTechnos(t.technos)}createInitialMapTerrains(e,t){for(var i of e){var s,r,a=i.name;this.validateMapObjectRulesAndArt(a,Bt.Terrain)&&((s=this.map.tiles.getByMapCoords(i.rx,i.ry))?(r=this.rules.getObject(a,Bt.Terrain),t&&r.spawnsTiberium||(a=this.createObject(Bt.Terrain,a),this.spawnObject(a,s))):console.warn(`Invalid map object location (${i.rx},${i.ry})`,i))}}createInitialMapOverlays(e,s){let r=new Map,a=new Map;for(var n of e){var o=this.rules.getOverlayName(n.id);if(this.validateMapObjectRulesAndArt(o,Bt.Overlay)){let e=this.createObject(Bt.Overlay,o);e.overlayId=n.id,e.value=n.value;let t=n.rx,i=n.ry;e.isBridge()&&e.isHighBridge()&&(e.position.tileElevation=4,t+=e.isXBridge()?0:-1,i+=e.isXBridge()?-1:0);var h=this.map.tiles.getByMapCoords(t,i);if(h)if(e.rules.tiberium&&(o=$a.getOverlayTibType(n.id),void 0!==(o=un.calculateOverlayId(o,h))&&o!==n.id&&(e.dispose(),e=this.createObject(Bt.Overlay,this.rules.getOverlayName(o)),e.overlayId=o,e.value=n.value)),Va.isLowBridge(n.id))Va.isBridgePlaceholder(n.id)||(r.set(h,n.value),1===n.value?a.set(h,e):e.dispose());else{if(e.isTiberium()){if(![na.Ore,na.Gems,na.Vinifera].includes($a.getOverlayTibType(e.overlayId))){console.warn(`Found unsupported TS tiberium overlay ${e.overlayId} @${h.rx},${h.ry}. Skipping.`);continue}if(this.map.getObjectsOnTile(h).find(e=>e.isTerrain())){e.dispose();continue}}s&&e.isTiberium()?e.dispose():this.spawnObject(e,h)}else console.warn(`Invalid map object location (${t},${i})`,n),e.dispose()}}for(var[t,i]of a){var l=i.isXBridge(),c=this.map.tiles.getByMapCoords(t.rx+(l?0:-1),t.ry+(l?-1:0)),l=this.map.tiles.getByMapCoords(t.rx+(l?0:1),t.ry+(l?1:0));c&&l&&(0===r.get(c)||2===r.get(l))?(i.value=0,this.spawnObject(i,c)):(i.dispose(),console.warn(`Invalid bridge segment @${t.rx},${t.ry}. Skipping.`))}var u,d=[...a.keys()].filter(e=>this.map.bridges.getPieceAtTile(e)?.headType!==$h.None),e=this.map.bridges.findMapHighBridgeHeadTiles();let p=this.map.bridges.findBridgeSpecsForHeadTiles([...d,...e]);for(u of p)for(var g of this.map.bridges.findBridgePieces(u))g.obj.bridgeTrait.bridgeSpec=u;var m,e=p.map(e=>this.map.bridges.findAllBridgeTiles(e)).flat(),f=Va.bridgePlaceholderIds[0],y=this.rules.getOverlayName(f);for(m of e){let e=this.createObject(Bt.Overlay,y);e.overlayId=f,this.spawnObject(e,m)}}createInitialMapSmudges(e){for(var t of e){var i=t.name,s=this.map.tiles.getByMapCoords(t.rx,t.ry);s?(i=this.createObject(Bt.Smudge,i),this.spawnObject(i,s)):console.warn(`Invalid map object location (${t.rx},${t.ry})`,t)}}createInitialMapTechnos(e){let t=new Map(this.playerList.getAll().filter(e=>!!e.country).map(e=>[e.country.name,e])),s=this.map.getTags();for(let i of e){var r=i.name;if(this.validateMapObjectRulesAndArt(r,i.type)){var a=this.map.tiles.getByMapCoords(i.rx,i.ry);if(a){var n=t.get(i.owner);if(n){if(n.isNeutral){let t=this.createObject(i.type,r);i.tag&&(t.tag=s.find(e=>e.id===i.tag)),t.healthTrait.health=i.health/256*100;let e=!1;if(!t.healthTrait.health){if(!t.isBuilding()||!t.rules.leaveRubble){t.dispose();continue}e=!0}if(i.isInfantry()||i.isVehicle()||i.isAircraft()){t.direction=(-i.direction/256*360+360)%360,i.isInfantry()&&(t.position.subCell=i.subCell);let e=!1;i.onBridge&&(void 0===a.onBridgeLandType?console.warn(`Cannot place unit "${i.name}" on a bridge because `+`no bridge was found at ${a.rx}, ${a.ry}`):e=!0),t.onBridge=e,t.zone=Os(e?a.onBridgeLandType:a.landType),e&&(t.position.tileElevation+=this.map.tileOccupation.getBridgeOnTile(a)?.tileElevation??0),i.veterancy&&t.veteranTrait?.setRelativeXP(i.veterancy)}else t.poweredTrait?.setTurnedOn(i.poweredOn);this.changeObjectOwner(t,n),this.spawnObject(t,a),e&&this.destroyObject(t,void 0,!0)}}else console.warn(`Invalid owner "${i.owner}" for map object`,i)}else console.warn(`Invalid map object location (${i.rx},${i.ry})`,i)}}}validateMapObjectRulesAndArt(e,t){return this.rules.hasObject(e,t)?!!this.art.hasObject(e,t)||(console.warn(`Map object '${e}' has no art section. Skipping.`),!1):(console.warn(`Map object '${e}' has no rules section. Skipping.`),!1)}createPlayerInitialUnits(){let e=this.playerList.getCombatants().map(e=>e.country);var i=[...this.rules.infantryRules.values(),...this.rules.vehicleRules.values()].filter(t=>t.allowedToStartInMultiplayer&&!t.naval&&-1!==t.techLevel&&t.techLevel<=this.rules.mpDialogSettings.techLevel&&!this.rules.general.baseUnit.includes(t.name)&&e.some(e=>t.isAvailableTo(e)&&t.hasOwner(e)));for(let h of this.playerList.getCombatants()){var l=this.map.startingLocations[h.startLocation],c=this.map.tiles.getByMapCoords(l.x,l.y);let t=this.rules.general.baseUnit.find(e=>{let t=this.rules.getObject(e,Bt.Vehicle);return t.isAvailableTo(h.country)&&t.hasOwner(h.country)});if(!t)throw new Error(`No suitable MCV found for player country ${h.country}`);l=this.rules.getObject(t,Bt.Vehicle),l=this.createUnitForPlayer(l,h);this.spawnObject(l,c);let e=Ll.generate(this.gameOpts.unitCount,[...this.rules.vehicleRules.keys()],i,h.country);this.gameModeType===St.Unholy&&e.push(...this.rules.general.baseUnit.filter(e=>e!==t).map(e=>({name:e,type:Bt.Vehicle,count:1})));var u,d,p;let s=[],r=!1,a=new yo(this.map.tiles,this.map.mapBounds,c,4,4,e=>!this.map.getGroundObjectsOnTile(e).find(e=>!(e.isSmudge()||e.isOverlay()&&e.isTiberium()))&&0<this.map.terrain.getPassableSpeed(e,Jt.Foot,!1)),n=new Map,o=0;for({name:u,type:d,count:p}of e){let i=p;for(;0<i;){let t;if(r||(t=a.getNextTile(),t?s.push(t):r=!0),r&&s.length){var g=s[o];let e=n.get(g);e||(e=new yo(this.map.tiles,this.map.mapBounds,g,1,0,e=>!this.map.getGroundObjectsOnTile(e).find(e=>!(e.isSmudge()||e.isOverlay()&&e.isTiberium()))&&0<this.map.terrain.getPassableSpeed(e,Jt.Foot,!1)),n.set(g,e)),o=(o+1)%s.length,t=e.getNextTile()}if(t){var m,f=this.rules.getObject(u,d);if(d===Bt.Vehicle){g=this.createUnitForPlayer(f,h);this.applyInitialVeteran(g,h),this.spawnObject(g,t),i--}else{if(d!==Bt.Infantry)throw new Error("Should not reach this line");for(m of Da.SUB_CELLS.slice(0,i)){let e=this.createUnitForPlayer(f,h);e.position.subCell=m,this.applyInitialVeteran(e,h),this.spawnObject(e,t),i--}}}else i--}}}}applyInitialVeteran(e,t){e.veteranTrait&&(this.rules.general.veteran.initialVeteran?e.veteranTrait.setVeteranLevel(Jr.Elite):t.country.hasVeteranUnit(e.type,e.name)&&e.veteranTrait.setVeteranLevel(Jr.Veteran))}createObject(e,t){return this.objectFactory.create(e,t,this.rules,this.art)}createUnitForPlayer(e,t){if(![Bt.Aircraft,Bt.Vehicle,Bt.Infantry].includes(e.type))throw new Error(`Attempted to create an invalid unit type "${e.type}"`);let i=this.createObject(e.type,e.name);return this.changeObjectOwner(i,t),i.purchaseValue=this.sellTrait.computePurchaseValue(i.rules,t),i}createProjectile(e,t,i,s,r){let a=this.createObject(Bt.Projectile,e);return a.fromWeapon=i,a.fromObject=t,a.fromPlayer=t.owner,a.target=s,a.isShrapnel=r,a}createLooseProjectile(e,t,i){var s=this.rules.getWeapon(e),r=s.projectile,a=this.rules.getProjectile(r),e=this.rules.getWarhead(s.warhead),e={minRange:0,projectileRules:a,range:Number.POSITIVE_INFINITY,rules:s,speed:en.computeSpeed(s,a),type:oi.Primary,warhead:new Qa(e)};let n=this.createObject(Bt.Projectile,r);return n.fromWeapon=e,n.fromObject=void 0,n.fromPlayer=t,n.target=i,n}createSuperWeapon(e,t,i=!1){var s=this.rules.getSuperWeapon(e);return new Ws(e,s,t,i)}createTarget(e,t){return new co(e,t,this.map.tileOccupation)}isValidTarget(e){if(e){if(!e.isSpawned||e.isCrashing)return!1;if(!(e.rules.legalTarget||e.isBuilding()&&e.rules.hospital))return!1;if(e.isBuilding()&&e.rules.invisibleInGame)return!1}return!0}spawnObject(e,t){if(e.isTechno()&&e.limboData)throw new Error(`Object ${e.name}#${e.id} is in limbo. Use unlimboObject instead or clear limboData first`);this.doSpawnObject(e,t)}unspawnObject(e){e.isTechno()&&e.owner&&e.owner.removeOwnedObject(e),this.doUnspawnObject(e)}limboObject(e,t){e.limboData=t,this.doUnspawnObject(e)}unlimboObject(e,t,i=!1){var s=e.limboData;if(!s)throw new Error(`Object ${e.name}#${e.id} has no limboData attached`);e.limboData=void 0,this.doSpawnObject(e,t);let r=this.getUnitSelection();s.selected&&!i&&r.addToSelection(e),void 0!==s.controlGroup&&r.addUnitsToGroup(s.controlGroup,[e],!1)}doSpawnObject(t,e){var i,s;t.position.tile=e,t.isBuilding()&&(s=t.art.foundationCenter,i=e.rx+s.x,s=e.ry+s.y,t.centerTile=this.map.tiles.getByMapCoords(i,s)??this.map.tiles.getPlaceholderTile(i,s)),this.world.spawnObject(t),(t.cachedTraits.tick.length||t.isProjectile()||t.isDebris()||t.isTechno())&&this.updatableObjects.add(t),t.isTechno()&&this.map.technosByTile.add(t),t.isProjectile()||t.isDebris()||this.map.tileOccupation.occupyTileRange(e,t),t.art.canHideThings&&this.map.tileOcclusion.addOccluder(t),t.onSpawn(this),this.traits.filter(Zh).forEach(e=>{e[Zh.onSpawn](t,this)}),this.events.dispatch(new Vl(t))}doUnspawnObject(t){var e=t.tile;t.isProjectile()||t.isDebris()||this.map.tileOccupation.unoccupyTileRange(e,t),t.art.canHideThings&&this.map.tileOcclusion.removeOccluder(t),t.isTechno()&&(this.unitSelection.cleanupUnit(t),this.map.technosByTile.remove(t)),this.world.removeObject(t),this.updatableObjects.delete(t),t.onUnspawn(this),this.traits.filter(Qh).forEach(e=>{e[Qh.onUnspawn](t,this)}),this.events.dispatch(new zl(t))}destroyObject(t,i,e=!1,s=!1){if(t.isDestroyed)throw new Error(`Object with ID "${t.id}" is already destroyed`);if(t.isTechno()){let e=t.mindControllableTrait?.getOriginalOwner()??t.owner;!i||t.isBuilding()&&!e.isCombatant()||(i.player.addUnitsKilled(t.type,1),i.player===e||this.alliances.areAllied(i.player,e)||(i.player.score+=t.rules.points)),e.isNeutral||e.addUnitsLost(t.type,1)}if(t.isDestroyed=!0,t.healthTrait&&(t.healthTrait.health=0),t.onDestroy(this,i,e),this.traits.filter(Jh).forEach(e=>{e[Jh.onDestroy](t,this,i)}),i?.obj?.traits.filter(Ln).forEach(e=>{e[Ln.onDestroy](i.obj,t,i.weapon,this)}),this.events.dispatch(new jl(t,i,s)),t.isBuilding()&&t.rules.leaveRubble&&t.deathType!==zr.Temporal){t.owner.removeOwnedObject(t),this.unitSelection.cleanupUnit(t);s=this.map.tileOccupation.calculateTilesForGameObject(t.tile,t);this.map.terrain.invalidateTiles(s),t.art.canHideThings&&this.map.tileOcclusion.removeOccluder(t),this.updatableObjects.delete(t),t.onUnspawn(this),this.traits.filter(Qh).forEach(e=>{e[Qh.onUnspawn](t,this)}),this.events.dispatch(new zl(t))}else if(t.isSpawned)this.unspawnObject(t);else if(t.isTechno()&&t.owner){if(!t.limboData)throw new Error(`Object with ID "${t.id}" should be in limbo but has no limboData`);t.owner.removeOwnedObject(t)}t.dispose()}getObjectById(e){return this.world.getObjectById(e)}changeObjectOwner(t,e){const i=t.owner;i&&i.removeOwnedObject(t),e.addOwnedObject(t),i&&i!==e&&(this.traits.filter(Yh).forEach(e=>{e[Yh.onChange](t,i,this)}),t.onOwnerChange(i,this),this.events.dispatch(new Wl(t,i)))}addObjectTrait(t,i){t.addTrait(i),this.traits.filter(Gl).forEach(e=>{e[Gl.onAdd](t,i,this)})}onAllianceChange(t,e,i){this.events.dispatch(new Hl(t,i?el.Formed:el.Broken,e)),this.traits.filter(Kh).forEach(e=>{e[Kh.onChange](t,i,this)})}update(){if(this.status!==$l.NotStarted){this.botManager.update(this),this.status!==$l.Ended&&(void 0===this.lastGameEndCheck||1e3<=this.currentTime-this.lastGameEndCheck)&&(this.checkGameEndConditions(),this.lastGameEndCheck=this.currentTime);for(var e of[...this.updatableObjects])e.isSpawned&&e.update(this);if(this.playerList.getCombatants().forEach(e=>e.cheerCooldownTicks=Math.max(0,e.cheerCooldownTicks-1)),this.traits.filter(xs).forEach(e=>{e[xs.onTick](this)}),this.localPlayer&&!this.localPlayer.isObserver&&!this.localPlayer.defeated){var t=this.unitSelection.getSelectedUnits();if(1===t.length){let i=t[0];if(i.isTechno()&&i.owner!==this.localPlayer){let t=this.mapShroudTrait.getPlayerShroud(this.localPlayer);this.map.tileOccupation.calculateTilesForGameObject(i.tile,i).find(e=>!t.isShrouded(e,i.tileElevation))||(this.unitSelection.deselectAll(),this.unitSelection.cleanupUnit(i))}}}for(var i of this.afterTickCallbacks)i();this.afterTickCallbacks.length=0,this.triggers.update(this),this.countdownTimer.update(this),this.currentTick++,this.currentTime+=1e3/Fs.BASE_TICKS_PER_SECOND}}afterTick(e){this.afterTickCallbacks.push(e)}checkGameEndConditions(){this.updateDefeatedPlayers(this.playerList.getCombatants()),(this.localPlayer?.defeated&&!this.localPlayer.isObserver||!this.alliances.getHostilePlayers().length&&1<this.gameOpts.humanPlayers.length+this.gameOpts.aiPlayers.length)&&this.end()}end(){this.status!==$l.Ended&&(this.status=$l.Ended,this._onEnd.dispatch(this,void 0))}updateDefeatedPlayers(e){let s=this.stalemateDetectTrait?.isStale()&&0===this.stalemateDetectTrait.getCountdownTicks(),r=this.gameOpts.shortGame;e.forEach(t=>{let i;if(s)i=!0;else{let e;e=r?(e=[...t.getOwnedObjectsByType(Bt.Building,!0)].some(e=>!e.rules.insignificant),e||t.getOwnedObjects(!0).some(e=>this.rules.general.baseUnit.includes(e.name))):t.getOwnedObjects(!0).some(e=>!e.rules.insignificant&&!e.limboData?.inTransport),i=!e}var e;i&&(t.defeated=!0,(e=this.alliances.getHostilePlayers().some(e=>!e.first.isAi||!e.second.isAi))&&(t.isObserver=!0),this.removeAllPlayerAssets(t),this.events.dispatch(new Ul(t)),e&&(this.mapShroudTrait.getPlayerShroud(t)?.revealAll(),e=t.radarTrait.isDisabled(),t.radarTrait.setDisabled(!1),e&&this.events.dispatch(new Al(t,!0))))})}removeAllPlayerAssets(e){e.getOwnedObjects().forEach(e=>{e.isDestroyed||e.isBuilding()&&e.wallTrait||this.destroyObject(e,void 0,!0)}),e.getOwnedObjects(!0).forEach(e=>{e.isDestroyed||(e.limboData?.inTransport||e.isBuilding()&&e.wallTrait?this.changeObjectOwner(e,this.getCivilianPlayer()):this.destroyObject(e,void 0,!0))})}generateRandomInt(e,t){return this.prng.generateRandomInt(e,t)}generateRandom(){return this.prng.generateRandom()}getHash(){return H([...new Uint8Array(new Float64Array([this.prng.getLastRandom()]).buffer),this.nextObjectId.value,...this.world.getAllObjects().map(e=>e.getHash()),...this.playerList.getAll().map(e=>e.getHash()),this.alliances.getHash(),...this.traits.getAll().map(e=>e.getHash?.()??0)])}debugGetState(){return{currentTick:this.currentTick,lastRandom:this.prng.getLastRandom(),nextObjectId:this.nextObjectId.value,objects:this.world.getAllObjects().map(e=>e.debugGetState()),players:this.playerList.getAll().map(e=>e.debugGetState()),alliances:this.alliances.debugGetState(),traits:this.traits.getAll().reduce((e,t)=>{var i=t.debugGetState?.();return void 0!==i&&(e[t.constructor.name]=i),e},{})}}dispose(){this.world.getAllObjects().forEach(e=>e.dispose()),this.playerList.getAll().forEach(e=>e.dispose()),this.constructionWorkers.forEach(e=>e.dispose()),this.botManager.dispose(),this.triggers.dispose(),this.map.dispose(),this.traits.dispose()}}class Zu{constructor(e){this.map=e,this.radSites=new Map,this.radLevelByTile=new Map,this._onChange=new ro}get onChange(){return this._onChange.asEvent()}getRadLevel(e){return this.radLevelByTile.get(e)}[xs.onTick](e){var t;this.radLevelByTile.size&&(t=e.rules.radiation,void 0===this.nextDamage?this.nextDamage=Math.max(0,t.radApplicationDelay-1):this.nextDamage<=0?(this.applyDamage(e),this.nextDamage=Math.max(0,t.radApplicationDelay)):this.nextDamage--,void 0===this.nextDecay?this.nextDecay=Math.max(0,t.radLevelDelay-1):this.nextDecay<=0?(this.applyDecay(Math.ceil(t.radLevelDelay/t.radDurationMultiple)),this.radLevelByTile.size?this.nextDecay=Math.max(0,t.radLevelDelay):this.nextDecay=void 0):this.nextDecay--)}applyDamage(a){let n=a.rules.radiation,o=new Qa(a.rules.getWarhead(n.radSiteWarhead));this.radLevelByTile.forEach((e,t)=>{var i,s,r=Math.min(n.radLevelMax,e)*n.radLevelFactor;for(i of a.map.getGroundObjectsOnTile(t).filter(e=>e.isUnit()&&!(e.isInfantry()&&e.stance===Rs.Paradrop&&1<e.tileElevation)))o.canDamage(i,t,i.zone)&&(0<(s=o.computeDamage(r,i))&&o.inflictDamage(s,i,void 0,a,!0))})}applyDecay(s){var e=new Set(this.radLevelByTile.keys());this.radLevelByTile.clear(),this.radSites.forEach(({radLevel:e,radius:t},i)=>{e-=s;e<=0?this.radSites.delete(i):(this.radSites.set(i,{radLevel:e,radius:t}),this.setRadLevelAround(i,t,e))}),this._onChange.dispatch(this,e)}createRadSite(e,t,i){(t-=this.radSites.get(e)?.radLevel??0)<=0||(this.radSites.set(e,{radLevel:(this.radSites.get(e)?.radLevel??0)+t,radius:i}),(t=this.setRadLevelAround(e,i,t)).size&&this._onChange.dispatch(this,t))}setRadLevelAround(e,t,i){let s=new Cs(this.map.tileOccupation),r=new js(this.map.tiles,this.map.mapBounds,e,{width:1,height:1},0,t,e=>!!e,!1);var a;let n=new Set;for(;a=r.getNextTile();){var o=s.tileDistance(e,a);o<=t&&(o=Math.ceil(V(i,0*i,o/t)),this.radLevelByTile.set(a,Math.min(1e3,(this.radLevelByTile.get(a)??0)+o)),n.add(a))}return n}getRadSiteLevel(e){return this.radSites.get(e)?.radLevel}}class Qu{constructor(){this.factories=new Map}registerFactory(e,t){this.factories.set(e,t)}create(e){let t=this.factories.get(e);if(!t)throw new Error(`No factory registered for action type ${e}`);return t.create()}}class Yu{constructor(e){this.player=e,this.selectedUnits=new Set}update(e){var t,i=[...e].reverse().find(e=>e.owner!==this.player);i&&(e=[i]),this.selectedUnits.clear();for(t of e)t.rules.selectable&&this.selectedUnits.add(t)}getSelectedUnits(){return[...this.selectedUnits].filter(e=>!e.isDestroyed&&!e.isCrashing)}isSelected(e){return this.selectedUnits.has(e)}}class Ku{constructor(){this.unitSelectionByPlayer=new Map}getOrCreateSelection(e){let t=this.unitSelectionByPlayer.get(e);return t||(t=new Yu(e),this.unitSelectionByPlayer.set(e,t)),t}}(r=ql=ql||{})[r.NoAction=0]="NoAction",r[r.DropPlayer=1]="DropPlayer",r[r.ObserveGame=2]="ObserveGame",r[r.ResignGame=3]="ResignGame",r[r.DebugCommand=4]="DebugCommand",r[r.PlaceBuilding=5]="PlaceBuilding",r[r.SellBuilding=6]="SellBuilding",r[r.ToggleRepair=7]="ToggleRepair",r[r.SelectUnits=8]="SelectUnits",r[r.OrderUnits=9]="OrderUnits",r[r.UpdateQueue=10]="UpdateQueue",r[r.ToggleAlliance=11]="ToggleAlliance",r[r.ActivateSuperWeapon=12]="ActivateSuperWeapon",r[r.PingLocation=13]="PingLocation";class Ju{constructor(e){this.actionType=e}unserialize(e){}serialize(){return new Uint8Array}print(){return""}}class ed extends Ju{constructor(){super(ql.NoAction)}process(){}}class td{create(){return new ed}}class id{constructor(e){this.target=e,this.type=is.BuildingPlace}}class sd{constructor(e,t,i){this.name=e,this.player=t,this.tile=i,this.type=is.BuildingFailedPlace}}(Xl=Xl||{}).onPlace=Symbol();class rd extends Ju{constructor(e){super(ql.PlaceBuilding),this.game=e}unserialize(e){let t=new b(e);this.buildingRules=this.game.rules.getTechnoByInternalId(t.readUint32(),Bt.Building),this.tile={x:t.readUint16(),y:t.readUint16()}}serialize(){let e=new b(8);return e.writeUint32(this.buildingRules.index),e.writeUint16(this.tile.x),e.writeUint16(this.tile.y),e.toUint8Array()}print(){return`Place building ${this.buildingRules.name} at tile (${this.tile.x}, ${this.tile.y})`}process(){var e=this.game.map.tiles.getByMapCoords(this.tile.x,this.tile.y);if(e){var t=this.player;const i=this.tryPlaceBuilding(t,e);i?(this.game.traits.filter(Xl).forEach(e=>{e[Xl.onPlace](i,this.game)}),this.game.events.dispatch(new id(i))):this.game.events.dispatch(new sd(this.buildingRules.name,t,e))}else console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}tryPlaceBuilding(s,r){var a=this.buildingRules;if(s.production){let i=s.production.getQueueForObject(a);if(i.status===fn.Ready&&i.getFirst().rules===a){let t=this.game.getConstructionWorker(s);if(s.production.isAvailableForProduction(a)&&t.canPlaceAt(a.name,r,{normalizedTile:!0})){r=t.placeAt(a.name,r,!0);s.addUnitsBuilt(Bt.Building,1),i.shift(a,1);let e=s.production.getPrimaryFactory(Ji.BuildingType);return e&&(e.factoryTrait.status=Sn.Delivering),r[0]}}}}}class ad{constructor(e){this.game=e}create(){return new rd(this.game)}}class nd extends Ju{constructor(e){super(ql.SellBuilding),this.game=e}unserialize(e){this.buildingId=new b(e).readUint32()}serialize(){return new b(4).writeUint32(this.buildingId).toUint8Array()}print(){return`Sell building ${this.buildingId}`}process(){var t=this.player;if(this.game.getWorld().hasObjectId(this.buildingId)){let e=this.game.getObjectById(this.buildingId);e.isBuilding()&&(t!==e.owner||e.isDestroyed||e.buildStatus!==In.Ready||e.warpedOutTrait.isActive()||this.game.sellTrait.sell(e))}}}class od{constructor(e){this.game=e}create(){return new nd(this.game)}}const hd=[An.Occupy,An.Dock,An.Attack,An.Capture,An.Repair,An.EnterTransport,An.PlaceBomb,An.Deploy,An.Gather];(r=Zl=Zl||{})[r.Default=0]="Default",r[r.Mini=1]="Mini",r[r.Scroll=2]="Scroll",r[r.NoScroll=10]="NoScroll",r[r.Select=18]="Select",r[r.Move=31]="Move",r[r.NoMove=41]="NoMove",r[r.MoveMini=42]="MoveMini",r[r.NoActionMini=52]="NoActionMini",r[r.AttackRange=53]="AttackRange",r[r.AttackNoRange=58]="AttackNoRange",r[r.AttackMini=63]="AttackMini",r[r.Guard=68]="Guard",r[r.GuardMini=73]="GuardMini",r[r.Unknown1=78]="Unknown1",r[r.Unknown2=88]="Unknown2",r[r.Occupy=89]="Occupy",r[r.NoOccupy=99]="NoOccupy",r[r.OccupyMini=100]="OccupyMini",r[r.Deploy=110]="Deploy",r[r.NoDeploy=119]="NoDeploy",r[r.Unknown3=120]="Unknown3",r[r.Sell=129]="Sell",r[r.SellMini=139]="SellMini",r[r.NoSell=149]="NoSell",r[r.RepairMove=150]="RepairMove",r[r.SideRepair=170]="SideRepair",r[r.NoRepair=190]="NoRepair",r[r.Unknown4=191]="Unknown4",r[r.Unknown5=199]="Unknown5",r[r.Dynamite=204]="Dynamite",r[r.Unknown6=209]="Unknown6",r[r.Unknown7=214]="Unknown7",r[r.Unknown8=219]="Unknown8",r[r.Unknown9=224]="Unknown9",r[r.Unknown10=229]="Unknown10",r[r.Unknown11=234]="Unknown11",r[r.Unknwon12=239]="Unknwon12",r[r.Unknown13=249]="Unknown13",r[r.Para=259]="Para",r[r.Unknown14=269]="Unknown14",r[r.Storm=279]="Storm",r[r.Unknown15=299]="Unknown15",r[r.C4=309]="C4",r[r.Nuke=319]="Nuke",r[r.Unknown16=329]="Unknown16",r[r.Power=339]="Power",r[r.Unknown17=345]="Unknown17",r[r.Iron=346]="Iron",r[r.Unknown18=351]="Unknown18",r[r.Unknown19=356]="Unknown19",r[r.Chrono=357]="Chrono",r[r.DefuseBomb=369]="DefuseBomb",r[r.NoAction=384]="NoAction",r[r.Pan=385]="Pan",r[r.Unknown21=394]="Unknown21",r[r.AttackMove=404]="AttackMove",r[r.Unknown23=413]="Unknown23",r[r.Unknown24=422]="Unknown24",r[r.Unknown25=431]="Unknown25",r[r.Unknown26=432]="Unknown26",r[r.Unknown27=433]="Unknown27",r[r.Unknown28=434]="Unknown28",r[r.Beacon=435]="Beacon",(r=Ql=Ql||{})[r.None=0]="None",r[r.Move=1]="Move",r[r.Attack=2]="Attack",r[r.Enter=3]="Enter",r[r.Capture=4]="Capture",r[r.SpecialAttack=5]="SpecialAttack";class ld{constructor(e){this.orderType=e,this.targetOptional=!0,this.minimapAllowed=!0,this.singleSelectionRequired=!1,this.terminal=!1,this.feedbackType=Ql.None}getPointerType(e,t){return e?Zl.Mini:Zl.Default}set(e,t){return this.sourceObject=e,this.target=t,this}isValid(){return!0}isAllowed(){return!0}onAdd(e,t){return!0}}class cd{constructor(e,t){this.from=e,this.to=t,this.type=is.ObjectMorph}}class ud extends Hs{constructor(e){super(),this.game=e}onStart(e){if(!this.morphInto)throw new Error("morphInto not set");e.isBuilding()&&e.buildStatus!==In.BuildDown&&this.morphInto.type!==Bt.Building&&this.children.push(new Ml),e.isVehicle()&&this.morphInto.type===Bt.Building&&this.children.push(new br(180))}onTick(t){if(!this.morphInto)throw new Error("morphInto not set");let e=this.game.getUnitSelection();var i=e.isSelected(t),s=e.getOrCreateSelectionModel(t).getControlGroupNumber(),r=this.morphInto;let a;if(r.type===Bt.Building){if(t.isVehicle()&&t.parasiteableTrait?.isInfested())return!0;var n=t.tile;let e=this.game.getConstructionWorker(t.owner);if(!e.canPlaceAt(this.morphInto.name,n,{ignoreAdjacent:!0,ignoreObjects:[t]}))return!0;this.game.unspawnObject(t),t.dispose(),[a]=e.placeAt(this.morphInto.name,n),a.healthTrait.health=t.healthTrait.health}else{let e=t.unitOrderTrait.getTasks().filter(e=>e instanceof Sa);this.game.unspawnObject(t),t.dispose(),a=this.game.createUnitForPlayer(this.morphInto,t.owner),a.direction=180,a.healthTrait.health=t.healthTrait.health;n=t.art.foundationCenter;this.game.spawnObject(a,this.game.map.tiles.getByMapCoords(t.tile.rx+n.x,t.tile.ry+n.y)),e.forEach(e=>a.unitOrderTrait.addTask(e))}return a.purchaseValue=t.purchaseValue,t.replacedBy=a,i&&e.addToSelection(a),void 0!==s&&e.addUnitsToGroup(s,[a],!1),this.game.events.dispatch(new cd(t,a)),!0}}class dd extends ud{onStart(e){var t=e.rules.undeploysInto;if(!t)throw new Error(`Object type "${e.name}" doesn't undeploy into anything`);this.morphInto=this.game.rules.getObject(t,Bt.Vehicle),super.onStart(e)}}class pd{constructor(e){this.target=e,this.type=is.RallyPointChange}}class gd extends Hs{constructor(e,t){super(),this.game=e,this.target=t,this.preventOpportunityFire=!1,this.useChildTargetLines=!0,this.attackPerformed=!1}onStart(e){this.children.push(new Sa(this.game,this.target.centerTile,!1,{closeEnoughTiles:1,pathFinderIgnoredBlockers:[this.target],stopOnBlocker:this.target}))}onTick(e){if(this.attackPerformed||this.isCancelling()||!e.attackTrait||e.attackTrait.isDisabled())return!0;if(e.moveTrait.lastMoveResult!==qr.CloseEnough)return!0;var t=e.attackTrait.selectWeaponVersus(e,this.target,this.game,!0);return!t||(this.children.push(e.attackTrait.createAttackTask(this.game,this.target,this.target.tile,t,{force:!0})),!(this.attackPerformed=!0))}}class md extends ld{constructor(e,t,i,s=!1){super(s?An.ForceMove:An.Move),this.game=e,this.map=t,this.unitSelection=i,this.forceMove=s,this.targetOptional=!1,this.feedbackType=Ql.Move}getPointerType(e){let t=this.isAllowed();var i,s,r,a;return!t||this.forceMove||this.sourceObject.isBuilding()||this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)||(i=!!this.target.getBridge(),s=this.sourceObject.rules.speedType,r=this.sourceObject.rules.movementZone===si.Fly,a=this.map.getObjectsOnTile(this.target.tile).some(e=>(e.isInfantry()||e.isVehicle())&&e.disguiseTrait?.hasTerrainDisguise()),t=r?this.sourceObject.rules.airportBound||this.target.tile.landType===Kt.Cliff||0<this.map.terrain.getPassableSpeed(this.target.tile,Jt.Amphibious,i)&&!a:0<this.map.terrain.getPassableSpeed(this.target.tile,s,i)&&!a&&!(this.target.obj?.isTechno()&&!this.game.areFriendly(this.target.obj,this.sourceObject))),e?t?Zl.MoveMini:Zl.NoActionMini:t?Zl.Move:Zl.NoMove}isValid(){return!(this.sourceObject.isBuilding()&&(!this.sourceObject.rules.undeploysInto||this.sourceObject.rules.constructionYard&&!this.game.gameOpts.mcvRepacks)&&!this.sourceObject.rallyTrait?.getRallyPoint())&&(this.forceMove||!this.target.obj||(this.target.obj.isOverlay()||this.target.obj.isBuilding())&&this.target.obj.rules.wall||this.target.obj.isTechno()&&this.target.obj.owner===this.sourceObject.owner&&this.unitSelection.isSelected(this.target.obj)||(this.target.obj.isInfantry()||this.target.obj.isVehicle())&&!!this.target.obj.disguiseTrait?.hasTerrainDisguise()||this.target.obj.isTechno()&&!this.game.areFriendly(this.target.obj,this.sourceObject))}isAllowed(){return(!this.sourceObject.isUnit()||!this.sourceObject.moveTrait.isDisabled())&&(this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)?this.sourceObject.rules.moveToShroud:!(!this.forceMove&&this.target.obj?.isTechno()&&this.target.obj.owner===this.sourceObject.owner&&this.unitSelection.isSelected(this.target.obj)))}process(){const e=this.sourceObject;if(!e.isBuilding()||!e.rallyTrait?.getRallyPoint()){var t=this.game.rules.general.closeEnough;return e.isBuilding()&&e.rules.undeploysInto?[new dd(this.game),new Sa(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:t,forceMove:this.forceMove})]:e.isUnit()?this.isEnemyBuildingBlock()?[new gd(this.game,this.target.obj)]:[new Sa(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:t,forceMove:this.forceMove})]:void 0}}isEnemyBuildingBlock(){return this.forceMove&&this.sourceObject.isVehicle()&&!this.sourceObject.rules.consideredAircraft&&this.target.obj?.isBuilding()&&!this.game.areFriendly(this.sourceObject,this.target.obj)}onAdd(t,e){var i=this.sourceObject.isBuilding()&&this.sourceObject.rules.undeploysInto;if(i&&this.sourceObject.buildStatus===In.BuildUp)return this.sourceObject.unitOrderTrait.getTasks().find(e=>e instanceof Fo)?.setCancellable(!0),!0;if(!i&&this.sourceObject.isBuilding()&&this.sourceObject.rallyTrait?.getRallyPoint())return this.sourceObject.rallyTrait.changeRallyPoint(this.target.tile,this.sourceObject,this.game),this.game.events.dispatch(new pd(this.sourceObject)),!1;if(!this.isEnemyBuildingBlock()&&!e&&this.isValid()&&this.isAllowed()){this.sourceObject.attackTrait?.cancelOpportunityFire();let e=t.find(e=>e.constructor===Sa&&!e.isCancelling());if(e)return e.setForceMove(this.forceMove),e.updateTarget(this.target.tile,!!this.target.getBridge()),e.children.length&&e.children[0]instanceof po&&e.children[0].cancel(),t.splice(t.indexOf(e)+1),this.sourceObject.unitOrderTrait.clearOrders(),!1;if(this.sourceObject.isUnit()&&this.sourceObject.rules.movementZone===si.Fly){let e=t.find(e=>[po,mo,go].includes(e.constructor)&&!e.isCancelling());e&&e.forceCancel(this.sourceObject)&&t.splice(t.indexOf(e))}}return!0}}class fd extends ud{onStart(e){var t=e.rules.deploysInto;if(!t)throw new Error(`Object type "${e.name}" doesn't deploy into anything`);this.morphInto=this.game.rules.getObject(t,Bt.Building),super.onStart(e)}onTick(e){return!!this.isCancelling()||super.onTick(e)}}class yd{constructor(e,t){this.unit=e,this.deployType=t,this.type=is.UnitDeployUndeploy}}class wd{constructor(e){this.target=e,this.type=is.PrimaryFactoryChange}}(r=Yl=Yl||{})[r.None=0]="None",r[r.OnlyPassengers=1]="OnlyPassengers",r[r.All=2]="All";class Td extends Hs{constructor(e,t){super(),this.game=e,this.soft=t,this.evacState=Yl.None,this.evacTries=0,this.turnPerformed=!1,this.preventLanding=!1}forceEvac(){this.evacState=Yl.All}onStart(e){if(!e.transportTrait)throw new Error(`Object "${e.name}" is not a valid transport`);var t=e.transportTrait;0<t.units.length&&(this.evacState=this.evacState!==Yl.OnlyPassengers&&1!==t.units.length||!e.rules.gunner?Yl.OnlyPassengers:Yl.All)}onTick(e){if(this.isCancelling()||this.evacState===Yl.None)return!0;if(e.zone===bs.Air)return this.children.push(new ga(()=>e.zone!==bs.Air)),!1;let t=e.transportTrait.units;if(!t.length||e.rules.gunner&&1===t.length&&this.evacState!==Yl.All)return!0;var i=t[t.length-1],s=this.findValidEvacTarget(e,i);if(s&&!this.turnPerformed){this.turnPerformed=!0;var r=(s.dir+180)%360;if(e.direction!==r)return this.children.push(new br(r)),!1}return this.evacuateUnit(i,e,s)?(t.pop(),this.children.push(new pa(1/60)),!1):!(++this.evacTries<=3)||(this.children.push(new pa(.05)),!1)}evacuateUnit(e,t,i){if(!i)return!this.soft&&(e.position.tile=t.tile,e.position.tileElevation=t.tileElevation,e.onBridge=t.onBridge,e.zone=t.zone,this.game.destroyObject(e,{player:e.owner}),!0);var{spawnNode:s,moveNode:i}=i;return e.position.tileElevation=s.onBridge?.tileElevation??0,e.onBridge=!!s.onBridge,e.zone=this.game.map.getTileZone(s.tile,!s.onBridge),this.game.unlimboObject(e,s.tile),e.unitOrderTrait.unmarkNextQueuedOrder(),i?e.unitOrderTrait.addTask(new Sa(this.game,i.tile,!!i.onBridge)):e.unitOrderTrait.addTask(new va(this.game)),this.game.events.dispatch(new th(t)),!0}findValidEvacTarget(a,n){let o=this.game.map,h=new qs(o);var l,c,u,d,p,t=a.onBridge?o.tileOccupation.getBridgeOnTile(a.tile):void 0,i=(a.direction+180)%360;let g;for(let e=0;e<=180;e+=45)for(l of e&&e<180?[i+e,i-e]:[i]){var m=Tr.toMapCoords(l);let i=a.tile,s=t,r;for(let t=1;t<=2;t++){if(2===t){if(!r)break;i=r.tile,s=r.onBridge}var f,y=a.tile.rx+Math.sign(m.x)*t,w=a.tile.ry+Math.sign(m.y)*t,T=o.tiles.getByMapCoords(y,w);if(!T||!o.mapBounds.isWithinBounds(T))break;let e=[o.tileOccupation.getBridgeOnTile(T)];e[0]&&e.push(void 0);for(f of e)if(c=T,u=f,d=s,p=i,0<o.terrain.getPassableSpeed(c,n.rules.speedType,!!u)&&h.isEligibleTile(c,u,d,p)&&!o.terrain.findObstacles({tile:c,onBridge:u},n).length){if(1!==t)return{spawnNode:r,moveNode:{tile:T,onBridge:f},dir:l};r={tile:T,onBridge:f},g={spawnNode:r,moveNode:void 0,dir:l}}}}if(g)return g}}class bd extends ld{constructor(e,t){super(t?An.Deploy:An.DeploySelected),this.game=e,this.targeted=t,this.minimapAllowed=!1,this.getPointerType=()=>this.isAllowed()?Zl.Deploy:Zl.NoDeploy,this.targetOptional=!t,this.singleSelectionRequired=t}isValid(){if(this.targeted&&(!this.target.obj||this.target.obj!==this.sourceObject))return!1;let e=this.sourceObject;return!!(e.isInfantry()&&e.deployerTrait&&![Rs.Cheer].includes(e.stance)||e.isVehicle()&&e.deployerTrait||e.isVehicle()&&e.rules.deploysInto||e.isVehicle()&&e.transportTrait||e.isBuilding()&&e.rules.factory&&!e.owner.production?.isPrimaryFactory(e)||e.isBuilding()&&e.garrisonTrait?.units.length)}isAllowed(){let t=this.sourceObject;if(t.isVehicle()&&t.transportTrait)return!!(t.transportTrait.units.length&&0<this.game.map.terrain.getPassableSpeed(t.tile,Jt.Foot,t.onBridge));if((t.isInfantry()||t.isVehicle())&&t.deployerTrait)return!0;if(t.isVehicle()&&t.rules.deploysInto){if(t.parasiteableTrait?.isInfested())return!1;let e=this.game.getConstructionWorker(t.owner);if(t.moveTrait.currentWaypoint?.onBridge)return!1;var i=t.moveTrait.currentWaypoint?.tile??t.tile;return e.canPlaceAt(t.rules.deploysInto,i,{ignoreObjects:[t],ignoreAdjacent:!0})}if(t.isBuilding()&&t.rules.factory)return!0;if(t.isBuilding()&&t.garrisonTrait?.units.length)return!0;throw new Error("Shouldn't reach this point. Missed a case.")}process(){const e=this.sourceObject;return e.isVehicle()&&e.transportTrait?[new Td(this.game,!0)]:e.isBuilding()&&e.rules.factory?void 0:e.isVehicle()&&e.rules.deploysInto?[new fd(this.game)]:(e.isInfantry()||e.isVehicle())&&e.deployerTrait?[new ga(()=>{e.deployerTrait.toggleDeployed(),this.game.events.dispatch(new yd(e,e.deployerTrait.isDeployed()?"undeploy":"deploy"))})]:e.isBuilding()&&e.garrisonTrait?.units.length?[new ga(()=>{e.garrisonTrait.evacuate(this.game,!0)})]:void 0}onAdd(t,e){let i=this.sourceObject;if(i.isBuilding()&&i.rules.factory)return i.owner.production.setPrimaryFactory(i),this.game.events.dispatch(new wd(i)),!1;if(i.isVehicle()&&i.transportTrait&&!e&&this.isValid()&&this.isAllowed()){let e=t.find(e=>e.constructor===Td&&!e.isCancelling());if(e)return e.forceEvac(),!1}return!0}}class vd{constructor(e){this.player=e,this.type=is.Cheer}}class Sd{constructor(e){this.target=e,this.type=is.DeployNotAllowed}}class kd extends Ju{constructor(e,t,i,s){super(ql.OrderUnits),this.game=e,this.map=t,this.orderActionContext=i,this.orderFactory=s,this.queue=!1,this.isInvalid=!1}unserialize(t){let i=new b(t);this.orderType=i.readUint8();var s=i.readUint8();if(0!==s){var r=i.readUint16(),t=i.readUint16();this.queue=2<s&&Boolean(i.readUint8());let e;if(3<s){s=i.readUint32();if(!this.game.getWorld().hasObjectId(s))return void(this.isInvalid=!0);e=this.game.getObjectById(s)}else e=void 0;t=this.map.tiles.getByMapCoords(r,t);t?this.target=this.game.createTarget(e,t):this.isInvalid=!0}}serialize(){let e=new b(11);e.dynamicSize=!1,e.writeUint8(this.orderType);let t=0;e.writeUint8(t),this.target&&(e.writeUint16(this.target.tile.rx),e.writeUint16(this.target.tile.ry),t+=2,i=(this.target.obj||this.target.getBridge())?.id,!this.queue&&void 0===i||(e.writeUint8(Number(this.queue)),t+=1),void 0!==i&&(e.writeUint32(i),t+=1));var i=e.position;return 0<t&&(e.seek(1),e.writeUint8(t)),new Uint8Array(e.buffer,e.byteOffset,i)}print(){return this.isInvalid?"":`${An[this.orderType]} order `+(this.target?`[obj: ${(this.target.obj||this.target.getBridge())?.name||"<none>"}, `+`tile: ${this.target.tile.rx},${this.target.tile.ry}]`+(this.queue?"(queue)":""):"")}process(){if(!this.isInvalid){let n=this.player;const l=this.game.mapShroudTrait.getPlayerShroud(n);if(l){const c=this.target?.obj;if(c){let e=this.game.map.tileOccupation.calculateTilesForGameObject(c.tile,c);if(!e.find(e=>!l.isShrouded(e,c.tileElevation)))return}let e=this.validateOrders(n).slice(0,128),a=[],t=[],s=[],i=[],r=[];if(e.forEach(e=>{(e instanceof md?t:e.orderType===An.Scatter?s:e.orderType===An.DeploySelected?i:e.orderType===An.Cheer?r:a).push(e)}),t.length&&this.target)if(t[0].isEnemyBuildingBlock())t.forEach(e=>a.push(e));else{let s=this.target.getBridge();var o=t[0].forceMove,h=t.map(e=>e.sourceObject);let r=new qs(this.map).findPositions(h,this.target.tile,s,o);t.forEach(e=>{var t=r.get(e.sourceObject),i=!s||s.isHighBridge()?this.map.tileOccupation.getBridgeOnTile(t):s,t=this.game.createTarget(i,t);e.target=t,a.push(e)})}if(s.length){o=s.map(e=>e.sourceObject).filter(e=>e.isInfantry()||e.isVehicle());let i=new ba(this.game).findPositions(o);s.forEach(e=>{var t=i.get(e.sourceObject);t&&(t=this.game.createTarget(t.onBridge,t.tile),e.target=t,a.push(e))})}if(i.length){let t=[];i.forEach(e=>{((e.sourceObject.isInfantry()||e.sourceObject.isVehicle())&&e.sourceObject.deployerTrait?t:a).push(e)});let e=t.filter(e=>!e.sourceObject.deployerTrait.isDeployed());e.length?e.forEach(e=>a.push(e)):t.forEach(e=>a.push(e))}r.length&&(n.cheerCooldownTicks||(n.cheerCooldownTicks=this.game.rules.general.maximumCheerRate,a.push(...r),this.game.events.dispatch(new vd(n)))),a.forEach(e=>e.sourceObject.unitOrderTrait.addOrder(e,this.queue)),this.updateWaypointPaths(a)}}}validateOrders(e){let i=this.orderActionContext.getOrCreateSelection(e);var s,r=i.getSelectedUnits();let t=this.orderFactory.create(this.orderType,i);t.target=this.target;let a=[];for(s of r)if(!(s.owner!==e||s.rules.spawned||s.isDestroyed||s.isCrashing||s.isDisposed||s.warpedOutTrait.isActive()||(t.sourceObject=s,t instanceof bd&&t.isValid()&&!t.isAllowed()&&this.game.events.dispatch(new Sd(s)),t.singleSelectionRequired&&1<r.length)))if(t.isValid()&&t.isAllowed()){let e=this.orderFactory.create(this.orderType,i);e.set(s,this.target),a.push(e)}else{let t=!1;for(var n of hd){let e=this.orderFactory.create(n,i);if(e.set(s,this.target),!(e.singleSelectionRequired&&1<r.length)&&(e.targetOptional===!this.target&&e.isValid()&&e.isAllowed())){a.push(e),t=!0;break}}if(!t&&this.target&&this.orderType!==An.Deploy){let e=this.orderFactory.create(An.Move,i);e.set(s,this.target),e.isValid()&&e.isAllowed()&&a.push(e)}}return a}updateWaypointPaths(i){if(this.queue&&this.target){let e=i.map(e=>e.sourceObject);var t=[...new Set(e.map(e=>e.unitOrderTrait.waypointPath).filter(Fa))];if(t.length<=1){i={orderType:this.orderType,target:this.target,terminal:i.some(e=>e.terminal),next:void 0};if(0===t.length){let t={units:e,waypoints:[i]};e.forEach(e=>{e.unitOrderTrait.waypointPath=t})}else{let e=t[0];e.waypoints[e.waypoints.length-1].next=i,e.waypoints.push(i)}}}}}class Od extends Ju{constructor(e,t){super(ql.SelectUnits),this.orderActionContext=t}get unitIds(){return this._unitIds}set unitIds(e){this._unitIds=e.slice(0,128)}unserialize(t){let i=new b(t);this.unitIds=new Array(t.byteLength/4);for(let e=0;e<t.byteLength/4;e++)this.unitIds[e]=i.readUint32()}serialize(){let e=new b(4*this.unitIds.length);e.dynamicSize=!1;for(var t of this.unitIds)e.writeUint32(t);return e.toUint8Array()}print(){return`Select unit(s) [${this.unitIds.join(",")}]`}process(){let e=this.player,t=[];for(var i of this.unitIds){i=e.getOwnedObjectById(i);i&&t.push(i)}this.orderActionContext.getOrCreateSelection(e).update(t)}}class _d{constructor(e,t){this.game=e,this.orderActionContext=t}create(){return new Od(this.game,this.orderActionContext)}}class Id extends Sa{constructor(e,t){super(e,t.tile,!1,{ignoredBlockers:[t]}),this.target=t,this.cancellable=!1}canStopAtTile(e,t,i){return!this.game.map.tileOccupation.isTileOccupiedBy(t,this.target)&&super.canStopAtTile(e,t,i)}}class Cd extends Sa{constructor(e,t){super(e,Cd.chooseTargetFoundationTile(t,e),!1,{ignoredBlockers:[t],closeEnoughTiles:0}),this.target=t}static chooseTargetFoundationTile(t,i){if(t.isBuilding()){let e=t.centerTile;return i.map.mapBounds.isWithinBounds(e)||(e=i.map.tileOccupation.calculateTilesForGameObject(t.tile,t).find(e=>i.map.mapBounds.isWithinBounds(e))??t.tile),e}return t.tile}hasReachedDestination(e){return super.hasReachedDestination(e)||this.canStopAtTile(e,e.tile,e.onBridge)}canStopAtTile(e,t,i){t=this.game.map.tileOccupation.isTileOccupiedBy(t,this.target);return(!this.isCancelling()||!t)&&!(!this.isCancelling()&&!t)}isCloseEnoughToDest(e,t,i){return this.game.map.tileOccupation.isTileOccupiedBy(t,this.target)}}class Ad{constructor(e){this.target=e,this.type=is.BuildingGarrison}}class Bd{constructor(e,t){this.target=e,this.source=t,this.type=is.EnterObject}}class xd extends Hs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1,this.preventOpportunityFire=!1}isAllowed(e){return!this.target.isDestroyed&&this.target.garrisonTrait?.canBeOccupied()&&this.target.garrisonTrait.units.length<this.target.garrisonTrait.maxOccupants&&!(this.target.garrisonTrait.units.length&&this.target.garrisonTrait.units[0].owner!==e.owner)&&!e.mindControllableTrait?.isActive()}onTick(e){if(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())return!0;let t=this.target.garrisonTrait;return this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)?!this.isAllowed(e)||this.isCancelling()?(this.children.push(new Id(this.game,this.target)),!(this.aborted=!0)):(this.game.limboObject(e,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(e).getControlGroupNumber()}),t.units.length||(e.owner.buildingsCaptured++,this.game.changeObjectOwner(this.target,e.owner),this.game.events.dispatch(new Ad(this.target))),this.game.events.dispatch(new Bd(this.target,e)),t.units.push(e),!0):!!this.movePerformed||(this.children.push(new Cd(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Ed{constructor(e){this.target=e,this.type=is.UnitRecycle}}class Pd extends Hs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1}isAllowed(e){return e.rules.movementZone!==si.Fly&&e.rules.locomotor!==ii.Chrono&&0<this.game.sellTrait.computeRefundValue(e)&&this.target.rules.cloning&&!this.target.isDestroyed&&this.target.buildStatus===In.Ready&&e.owner===this.target.owner}onTick(e){return!!(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())||(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)?!this.isAllowed(e)||this.isCancelling()?(this.children.push(new Id(this.game,this.target)),!(this.aborted=!0)):(this.game.sellTrait.sell(e),this.game.events.dispatch(new Ed(e)),this.game.events.dispatch(new Bd(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Cd(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Nd{constructor(e,t){this.target=e,this.source=t,this.type=is.BuildingInfiltration}}class Md extends Hs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1}isAllowed(e){return e.rules.infiltrate&&this.target.rules.spyable&&!this.target.isDestroyed&&this.target.buildStatus!==In.BuildDown&&!this.game.areFriendly(e,this.target)}onTick(e){return!!(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())||(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)?!this.isAllowed(e)||this.isCancelling()?(this.children.push(new Id(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),e.agentTrait?.infiltrate(e,this.target,this.game),this.game.events.dispatch(new Nd(this.target,e)),this.game.events.dispatch(new Bd(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Cd(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}(r=Kl=Kl||{})[r.MoveToQueueingTile=0]="MoveToQueueingTile",r[r.WaitForTurn=1]="WaitForTurn",r[r.MoveToTarget=2]="MoveToTarget",r[r.EnterTarget=3]="EnterTarget",r[r.ClearTarget=4]="ClearTarget";class Dd extends Hs{constructor(e,t){super(),this.game=e,this.target=t,this.movePerformed=!1}isAllowed(e){return e.rules.movementZone!==si.Fly&&e.healthTrait.health<100&&this.target.hospitalTrait&&!this.target.isDestroyed&&!this.target.warpedOutTrait.isActive()&&this.game.areFriendly(e,this.target)&&(!this.target.ammoTrait||0<this.target.ammoTrait.ammo)}onStart(e){if(!this.target.hospitalTrait)throw new Error(`Target ${this.target.name} is not a valid hospital`);0<this.target.hospitalTrait.addToHealQueue(e)?this.state=Kl.MoveToQueueingTile:this.state=Kl.MoveToTarget}onEnd(e){!this.target.isDestroyed&&e.isSpawned&&this.target.hospitalTrait.removeFromHealQueue(e)}onTick(i){if(this.isCancelling()&&this.state!==Kl.EnterTarget||this.state===Kl.ClearTarget||i.moveTrait.isDisabled())return!0;if(this.state===Kl.MoveToQueueingTile){let t=new qs(this.game.map);var e=new js(this.game.map.tiles,this.game.map.mapBounds,this.target.tile,this.target.getFoundation(),1,1,e=>0<this.game.map.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&t.isEligibleTile(e,void 0,void 0,this.target.tile)).getNextTile();return!e||(this.children.push(new Sa(this.game,e,!1,{closeEnoughTiles:5})),this.children.push(new ga(()=>{[qr.Success,qr.CloseEnough].includes(i.moveTrait.lastMoveResult)||this.cancel()})),this.state=Kl.WaitForTurn,this.queueingTile=e,!1)}if(this.state===Kl.WaitForTurn){if(!this.target.hospitalTrait.unitIsFirstInHealQueue(i))return!1;this.queueingTile=void 0,this.state=Kl.MoveToTarget}if(this.state===Kl.MoveToTarget){if(!this.isAllowed(i))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(i.tile,this.target))return!!this.movePerformed||(this.children.push(new Cd(this.game,this.target)),!(this.movePerformed=!0));this.state=Kl.EnterTarget}return this.state===Kl.EnterTarget&&(!this.isAllowed(i)||this.isCancelling()?(this.children.push(new Id(this.game,this.target)),this.state=Kl.ClearTarget,!1):(this.game.limboObject(i,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(i).getControlGroupNumber()}),this.target.hospitalTrait.startHealing(i),this.game.events.dispatch(new Bd(this.target,i)),!0))}getTargetLinesConfig(e){return{target:this.queueingTile?void 0:this.target,pathNodes:this.queueingTile?[{tile:this.queueingTile,onBridge:void 0}]:[]}}}class Rd extends ld{constructor(e){super(An.Occupy),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Ql.Capture}getPointerType(e){return e?this.isAllowed()?Zl.OccupyMini:Zl.NoActionMini:this.isAllowed()?Zl.Occupy:Zl.NoOccupy}isValid(){return!!(this.target.obj?.isSpawned&&this.target.obj?.isBuilding()&&this.sourceObject.isInfantry())&&(!!this.isInfantryRecycle(this.sourceObject,this.target.obj)||(this.target.obj.isBuilding()&&this.target.obj.hospitalTrait?this.game.areFriendly(this.sourceObject,this.target.obj)&&this.sourceObject.isInfantry():this.target.obj.garrisonTrait?this.target.obj.garrisonTrait.canBeOccupied()&&this.sourceObject.rules.occupier&&!(this.target.obj.garrisonTrait.units.length&&this.target.obj.garrisonTrait.units[0].owner!==this.sourceObject.owner)&&!this.sourceObject.mindControllableTrait?.isActive()&&!this.sourceObject.mindControllerTrait?.isActive():!(!this.target.obj.rules.spyable||!this.sourceObject.rules.infiltrate||this.game.areFriendly(this.sourceObject,this.target.obj))))}isInfantryRecycle(e,t){return t.rules.cloning&&e.owner===t.owner}isAllowed(){var e=this.target.obj,t=this.sourceObject;return this.isInfantryRecycle(t,e)?t.rules.movementZone!==si.Fly&&t.rules.locomotor!==ii.Chrono&&0<this.game.sellTrait.computeRefundValue(t):e.hospitalTrait?t.healthTrait.health<100&&t.rules.movementZone!==si.Fly:!e.garrisonTrait||e.garrisonTrait.units.length<e.rules.maxNumberOccupants}process(){var e=this.target.obj,t=this.sourceObject;return this.isInfantryRecycle(t,e)?[new Pd(this.game,e)]:e.hospitalTrait?[new Dd(this.game,e)]:e.garrisonTrait?[new xd(this.game,e)]:[new Md(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof xd||e instanceof Md);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Cs(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Ld extends Hs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1,this.preventOpportunityFire=!1}isAllowed(e){return!this.target.isDestroyed&&!this.target.invulnerableTrait.isActive()}onTick(e){if(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target))return!!this.movePerformed||(this.children.push(new Cd(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));if(!this.isAllowed(e)||this.isCancelling())return this.children.push(new Id(this.game,this.target)),!(this.aborted=!0);var t=Math.floor(60*this.game.rules.combatDamage.c4Delay*Fs.BASE_TICKS_PER_SECOND);return this.target.c4ChargeTrait.setCharge(t,{player:e.owner,obj:e}),this.game.events.dispatch(new Bd(this.target,e)),this.children.push(new Id(this.game,this.target)),!(this.aborted=!0)}getTargetLinesConfig(e){return{target:this.target,pathNodes:[],isAttack:!0}}}class Fd extends ld{constructor(e,{forceAttack:t,noIvanBomb:i}={}){super(t?An.ForceAttack:An.Attack),this.game=e,this.isC4=!1,this.forceAttack=!!t,this.ivanBombAllowed=!i||!!t,this.targetOptional=!1,this.feedbackType=Ql.None,this.rangeHelper=new Cs(this.game.map.tileOccupation),this.losHelper=new oo(this.game.map.tiles,e.map.tileOccupation)}getPointerType(e,t){if(!this.isAllowed())return e?Zl.NoActionMini:Zl.NoAction;if(this.isC4)return Zl.C4;var i=this.sourceObject.attackTrait?.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);if(i?.rules.sabotageCursor)return Zl.C4;if(this.ivanBombAllowed&&this.sourceObject.rules.ivan&&i?.warhead.rules.ivanBomb)return Zl.Dynamite;if(i?.warhead.rules.bombDisarm)return Zl.DefuseBomb;if(i&&i.rules.damage<0)return Zl.RepairMove;t=t.every(e=>{if(!e.attackTrait)return!0;var t=e.attackTrait.selectWeaponVersus(e,this.target,this.game,this.forceAttack);return!t||this.rangeHelper.isInWeaponRange(e,this.target.obj||this.target.tile,t,this.game.rules)&&this.losHelper.hasLineOfSight(e,this.target.obj||this.target.tile,t)});return e?Zl.AttackMini:t?Zl.AttackRange:Zl.AttackNoRange}isValid(){if(!this.sourceObject.attackTrait)return!1;if(this.forceAttack&&this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)&&!this.sourceObject.isBuilding())return!1;let e=this.target.obj;var t=this.game.map.getGroundObjectsOnTile(this.target.tile).find(e=>e.isTerrain());if(this.terminal=!e&&!t,this.sourceObject.c4&&e?.isBuilding()&&e.c4ChargeTrait&&(this.forceAttack||!this.game.areFriendly(e,this.sourceObject)||e.cabHutTrait))return this.isC4=!0,this.feedbackType=Ql.SpecialAttack,!0;if(this.isC4=!1,this.feedbackType=Ql.Attack,!this.game.isValidTarget(e))return!1;if(!e&&t?.rules.immune)return!1;if(!(e||this.target.tile!==this.sourceObject.tile||this.sourceObject.isUnit()&&this.sourceObject.zone===bs.Air))return!1;if(e===this.sourceObject)return!1;t=this.sourceObject.attackTrait.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);return!!t&&(!(!this.ivanBombAllowed&&t.warhead.rules.ivanBomb)&&(!(e?.isBuilding()&&e.cabHutTrait&&!t.warhead.rules.ivanBomb&&!t.warhead.rules.bombDisarm)&&(!!(this.sourceObject.isUnit()&&this.sourceObject.moveTrait&&!this.sourceObject.moveTrait.isDisabled()||this.rangeHelper.isInWeaponRange(this.sourceObject,e||this.target.tile,t,this.game.rules))&&(!(this.sourceObject.airSpawnTrait&&t.rules.spawner&&!this.game.map.isWithinBounds(this.target.tile))&&(!!this.forceAttack||(!e?.isBuilding()||!e.hospitalTrait)&&(!(!e||!e.healthTrait)&&(!e.isDestroyed&&!e.isCrashing&&(!(!e.isOverlay()||!(t.warhead.rules.wall||t.warhead.rules.wood&&e.rules.armor===ri.Wood))||e.isTechno()))))))))}isAllowed(){return!this.sourceObject.attackTrait.isDisabled()}process(){if(this.isC4)return[new Ld(this.game,this.target.obj)];var e=this.sourceObject.attackTrait.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);return[new po(this.game,this.target,e,{force:this.forceAttack})]}onAdd(t,e){let i=this.sourceObject;if(!e&&i.isUnit()&&this.isValid()&&this.isAllowed())if(i.rules.movementZone===si.Fly){let e=t.find(e=>(e.constructor===Sa||e.constructor===po)&&!e.isCancelling());e&&(i.moveTrait.currentWaypoint?.tile===this.target.tile||i.isAircraft()||e.constructor===po)&&e.forceCancel(i)&&t.splice(t.indexOf(e))}else{t.length&&i.isUnit()&&(i.rules.locomotor===ii.Vehicle||i.rules.locomotor===ii.Ship)&&(i.moveTrait.speedPenalty=.5);let e=t.find(e=>e.constructor===po&&!e.isCancelling());if(e?.getWeapon().warhead.rules.temporal)return e.setForceAttack(this.forceAttack),e.requestTargetUpdate(this.target),!1}return!0}}class jd extends ld{constructor(e){super(An.Stop),this.game=e,this.getPointerType=()=>Zl.NoAction}isValid(){return this.sourceObject.isTechno()}isAllowed(){return!0}process(){return[new ga(e=>{!e.isUnit()||e.rules.locomotor!==ii.Vehicle&&e.rules.locomotor!==ii.Ship||(e.moveTrait.speedPenalty=0)})]}onAdd(e,t){let i=this.sourceObject;return t||!e.length||!i.isUnit()||i.rules.locomotor!==ii.Vehicle&&i.rules.locomotor!==ii.Ship||(i.moveTrait.speedPenalty=.5),i.isBuilding()&&i.rallyTrait?.getRallyPoint()&&(i.unitRepairTrait?.resetRallyPoint(i,this.game),i.factoryTrait?.resetRallyPoint(i,this.game)),!0}}class Ud extends ld{constructor(){super(An.Cheer),this.getPointerType=()=>Zl.NoAction}isValid(){return this.sourceObject.isInfantry()&&[Rs.None,Rs.Guard].includes(this.sourceObject.stance)}isAllowed(){return!0}process(){return[new lc]}}class Wd extends ld{constructor(e){super(An.Dock),this.game=e,this.targetOptional=!1,this.feedbackType=Ql.Move}getPointerType(e){return e?this.isAllowed()?Zl.OccupyMini:Zl.NoActionMini:this.isAllowed()?Zl.Occupy:Zl.NoOccupy}isValid(){if(!this.target.obj?.isBuilding()||this.target.obj.isDestroyed||!this.target.obj.dockTrait||this.target.obj.buildStatus!==In.Ready||!this.sourceObject.isUnit()||this.target.obj.warpedOutTrait.isActive())return!1;var e=!(this.target.obj.rules.refinery||this.target.obj.unitRepairTrait);return this.game.areFriendly(this.target.obj,this.sourceObject)&&this.target.obj.dockTrait.isValidUnitForDock(this.sourceObject)&&!this.target.obj.dockTrait.isDocked(this.sourceObject)&&!(this.target.obj.unitRepairTrait&&!this.sourceObject.rules.dock.includes(this.target.obj.name)&&100===this.sourceObject.healthTrait.health)&&(!e||(0<(this.target.obj.dockTrait.getAvailableDockCount()??0)||this.target.obj.dockTrait.hasReservedDockForUnit(this.sourceObject)))}isAllowed(){return!0}process(){var e=this.target.obj;return e.rules.refinery&&this.sourceObject.isVehicle()&&this.sourceObject.harvesterTrait?[new Jo(this.game,e,!0,!0)]:e.unitRepairTrait||this.sourceObject.rules.dock.includes(e.name)?[new ma(this.game,e)]:[]}}class zd extends ld{constructor(e){super(An.Gather),this.game=e,this.targetOptional=!1,this.feedbackType=Ql.Move}getPointerType(e){return e?Zl.AttackMini:Zl.AttackNoRange}isValid(){return!(!this.sourceObject.isVehicle()||!this.sourceObject.harvesterTrait||this.sourceObject.moveTrait.isDisabled()||this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation))&&this.target.isOre}isAllowed(){return!0}process(){return[new Ko(this.game,this.target.tile,!0)]}}class Vd extends Fd{constructor(e,t){super(e),this.map=t,this.orderType=An.AttackMove,this.targetOptional=!1,this.feedbackType=Ql.Move}getPointerType(t,i){if(this.isTargetted()){let e=super.getPointerType(t,i);return e!==Zl.AttackRange&&e!==Zl.AttackNoRange||(e=Zl.AttackMove),e}let e=this.isAllowed();var s,r;return e&&(s=!!this.target.getBridge(),r=this.sourceObject.rules.speedType,i=this.sourceObject.rules.movementZone===si.Fly,e=i||0<this.map.terrain.getPassableSpeed(this.target.tile,r,s)||!!this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)),t?e?Zl.AttackMini:Zl.NoActionMini:e?Zl.AttackMove:Zl.NoMove}isValid(){var e=this.sourceObject.isUnit()&&!!this.sourceObject.attackTrait&&!this.sourceObject.rules.preventAttackMove&&!(this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)&&!this.sourceObject.rules.moveToShroud)&&(!this.isTargetted()||super.isValid());return this.feedbackType=Ql.Move,e}isAllowed(){return!(!this.isTargetted()&&this.sourceObject.moveTrait.isDisabled())&&super.isAllowed()}process(){if(this.isTargetted()){if(this.isC4)return[new Ld(this.game,this.target.obj)];var e=this.sourceObject.attackTrait.selectWeaponVersus(this.sourceObject,this.target,this.game);return[new go(this.game,this.target,e)]}return[new mo(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})]}isTargetted(){return this.target.obj?.isTechno()}onAdd(t,e){let i=this.sourceObject;if(!e&&i.isUnit()&&this.isValid()&&this.isAllowed())if(i.rules.movementZone===si.Fly){let e=t.find(e=>[Sa,po,mo,go].includes(e.constructor)&&!e.isCancelling());if(e)if(this.isTargetted())(i.moveTrait.currentWaypoint?.tile===this.target.tile||i.isAircraft()||e.constructor!==Sa)&&e.forceCancel(i)&&t.splice(t.indexOf(e));else{if(e.constructor===mo)return e.updateTarget(this.target.tile,!!this.target.getBridge()),t.splice(t.indexOf(e)+1),i.unitOrderTrait.clearOrders(),!1;e.forceCancel(i)&&t.splice(t.indexOf(e))}}else this.isTargetted()&&t.length&&i.isUnit()&&(i.rules.locomotor===ii.Vehicle||i.rules.locomotor===ii.Ship)&&(i.moveTrait.speedPenalty=.5);return!0}}class Hd{constructor(e,t){this.target=e,this.source=t,this.type=is.BuildingRepairFull}}class Gd{constructor(e,t){this.source=e,this.tile=t,this.type=is.BridgeRepair}}class $d extends Hs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1}isAllowed(e){return this.target.cabHutTrait?this.target.cabHutTrait.canRepairBridge():e.rules.engineer&&!this.target.isDestroyed&&this.target.rules.repairable&&this.target.healthTrait.health<100&&(!this.target.owner.isCombatant()||this.game.areFriendly(e,this.target))}onTick(e){return!!(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())||(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)?!this.isAllowed(e)||this.isCancelling()?(this.children.push(new Id(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),this.target.cabHutTrait?(this.target.cabHutTrait.repairBridge(this.game,e.owner),this.game.events.dispatch(new Gd(e.owner,this.target.centerTile))):(this.target.healthTrait.healToFull(e,this.game),this.game.events.dispatch(new Hd(this.target,e.owner))),this.game.events.dispatch(new Bd(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Cd(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class qd extends ld{constructor(e){super(An.Repair),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Ql.Capture}getPointerType(e){return e?this.isAllowed()?Zl.OccupyMini:Zl.NoActionMini:this.isAllowed()?Zl.RepairMove:Zl.NoRepair}isValid(){return!!this.target.obj?.isBuilding()&&!this.target.obj.isDestroyed&&this.sourceObject.isInfantry()&&this.sourceObject.rules.engineer}isAllowed(){let e=this.target.obj;return e.cabHutTrait?e.cabHutTrait.canRepairBridge():!(!(e.rules.repairable&&e.healthTrait.health<100)||e.owner.isCombatant()&&!this.game.areFriendly(e,this.sourceObject))}process(){var e=this.target.obj;return[new $d(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof $d);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Cs(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Xd extends ld{constructor(e,t){super(t?An.GuardArea:An.Guard),this.game=e,this.targeted=t,this.getPointerType=e=>e?this.isAllowed()?Zl.GuardMini:Zl.NoActionMini:this.isAllowed()?Zl.Guard:Zl.NoMove,this.terminal=!0,this.targetOptional=!t,this.minimapAllowed=t,this.feedbackType=t?Ql.Move:Ql.None}isValid(){return this.sourceObject.isUnit()&&(!!this.targetOptional||!this.sourceObject.moveTrait.isDisabled())&&!(this.target&&this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)&&!this.sourceObject.rules.moveToShroud)}isAllowed(){return!0}process(){let t=this.targeted?this.target.tile:void 0;const e=this.sourceObject;let i=[];return t&&i.push(new Sa(this.game,t,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})),e.isVehicle()&&e.harvesterTrait?i.push(new ga(()=>e.harvesterTrait.lastOreSite=void 0),new Ko(this.game,void 0,!0)):i.push(new ga(e=>{t&&![qr.Success,qr.CloseEnough].includes(this.sourceObject.moveTrait?.lastMoveResult)||(this.sourceObject.guardMode=!0)})),i}}class Zd extends ld{constructor(e){super(An.Scatter),this.game=e,this.getPointerType=()=>Zl.NoAction}isValid(){return(this.sourceObject.isInfantry()||this.sourceObject.isVehicle())&&this.sourceObject.rules.movementZone!==si.Fly&&!this.sourceObject.moveTrait.isDisabled()}isAllowed(){return!0}process(){if(!this.target)throw new Error("Target should be set for executing a scatter order. See OrderUnitsAction.");return[new va(this.game,{tile:this.target.tile,toBridge:!!this.target.getBridge()})]}}class Qd{constructor(e){this.target=e,this.type=is.EnterTransport}}(r=Jl=Jl||{})[r.MoveToQueueingTile=0]="MoveToQueueingTile",r[r.WaitForTurn=1]="WaitForTurn",r[r.MoveToTransport=2]="MoveToTransport",r[r.EnterTransport=3]="EnterTransport",r[r.ClearTransport=4]="ClearTransport";class Yd extends Hs{constructor(e,t){super(),this.game=e,this.target=t,this.movePerformed=!1,this.preventOpportunityFire=!1}isAllowed(e){return!this.target.isDestroyed&&!this.target.isCrashing&&this.game.areFriendly(this.target,e)&&e.zone!==bs.Air&&this.target.zone!==bs.Air&&this.target.transportTrait.unitFitsInside(e)&&this.target.moveTrait.moveState===$r.Idle&&!this.target.warpedOutTrait.isActive()&&!e.mindControllableTrait?.isActive()&&!e.mindControllerTrait?.isActive()}onStart(e){if(!this.target.transportTrait)throw new Error(`Unit ${this.target.name} is not a valid transport`);this.initialTargetTile=this.target.tile,0<this.target.transportTrait.addToLoadQueue(e)?this.state=Jl.MoveToQueueingTile:this.state=Jl.MoveToTransport}onEnd(e){this.target.isDestroyed||this.target.transportTrait?.removeFromLoadQueue(e)}onTick(n){if(this.isCancelling()&&this.state!==Jl.EnterTransport||this.state===Jl.ClearTransport||n.moveTrait.isDisabled())return!0;if(this.target.tile!==this.initialTargetTile||this.target.moveTrait.moveState!==$r.Idle)return!0;if(this.state===Jl.MoveToQueueingTile){let s=new qs(this.game.map),r=this.target.onBridge?this.game.map.tileOccupation.getBridgeOnTile(this.target.tile):void 0,a;var e=new js(this.game.map.tiles,this.game.map.mapBounds,this.target.tile,this.target.getFoundation(),1,1,e=>{let t=[this.game.map.tileOccupation.getBridgeOnTile(e)];t[0]&&t.push(void 0);for(var i of t)if(0<this.game.map.terrain.getPassableSpeed(e,n.rules.speedType,!!i)&&s.isEligibleTile(e,i,r,this.target.tile))return a=i,!0;return!1}).getNextTile();return!e||(this.children.push(new Sa(this.game,e,!!a,{closeEnoughTiles:5})),this.children.push(new ga(()=>{[qr.Success,qr.CloseEnough].includes(n.moveTrait.lastMoveResult)||this.cancel()})),this.queueingNode={tile:e,onBridge:a},this.state=Jl.WaitForTurn,!1)}if(this.state===Jl.WaitForTurn){if(!this.target.transportTrait.unitIsFirstInLoadQueue(n))return!1;this.queueingNode=void 0,this.state=Jl.MoveToTransport}if(this.state===Jl.MoveToTransport){if(!this.isAllowed(n))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(n.tile,this.target))return!!this.movePerformed||(this.children.push(new Cd(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));this.state=Jl.EnterTransport}return this.state===Jl.EnterTransport&&(!this.isAllowed(n)||this.isCancelling()?(this.children.push(new Id(this.game,this.target)),this.state=Jl.ClearTransport,!1):(this.game.limboObject(n,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(n).getControlGroupNumber(),inTransport:!0}),this.game.events.dispatch(new Qd(this.target)),this.game.events.dispatch(new Bd(this.target,n)),this.target.transportTrait.units.push(n),!0))}getTargetLinesConfig(e){return{target:this.queueingNode?void 0:this.target,pathNodes:this.queueingNode?[this.queueingNode]:[]}}}class Kd extends ld{constructor(e){super(An.EnterTransport),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Ql.Enter}getPointerType(e){return e?this.isAllowed()?Zl.OccupyMini:Zl.NoActionMini:this.isAllowed()?Zl.Occupy:Zl.NoOccupy}isValid(){return!(!this.target.obj?.isVehicle()||!this.target.obj.transportTrait||this.target.obj.isDestroyed||this.target.obj===this.sourceObject||!this.game.areFriendly(this.target.obj,this.sourceObject)||!this.sourceObject.isVehicle()&&!this.sourceObject.isInfantry())}isAllowed(){let e=this.target.obj,t=this.sourceObject;return t.zone!==bs.Air&&e.zone!==bs.Air&&e.transportTrait.unitFitsInside(t)&&e.moveTrait.moveState===$r.Idle&&!e.warpedOutTrait.isActive()&&!t.mindControllableTrait?.isActive()&&!t.mindControllerTrait?.isActive()}process(){let e=this.sourceObject,t=this.target.obj;return this.game.map.terrain.getPassableSpeed(t.tile,e.rules.speedType,e.onBridge)?[new Yd(this.game,t)]:[new ga(()=>{t.unitOrderTrait.addTask(new Sa(this.game,e.tile,e.onBridge)),t.unitOrderTrait.addTask(new ga(()=>{this.game.map.terrain.getPassableSpeed(t.tile,e.rules.speedType,e.onBridge)&&e.unitOrderTrait.addTask(new Yd(this.game,t))}))})]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof Yd);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Cs(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Jd{constructor(e){this.target=e,this.type=is.BuildingCapture}}class ep extends Hs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1}isAllowed(e){return e.rules.engineer&&this.target.rules.capturable&&!this.target.isDestroyed&&this.target.buildStatus!==In.BuildDown&&!this.game.areFriendly(e,this.target)}onTick(e){return!!(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())||(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)?!this.isAllowed(e)||this.isCancelling()?(this.children.push(new Id(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),e.owner.buildingsCaptured++,this.game.changeObjectOwner(this.target,e.owner),this.game.events.dispatch(new Jd(this.target)),this.game.events.dispatch(new Bd(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Cd(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class tp extends ld{constructor(e){super(An.Capture),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Ql.Capture}getPointerType(e){return e?this.isAllowed()?Zl.OccupyMini:Zl.NoActionMini:this.isAllowed()?Zl.Occupy:Zl.NoOccupy}isValid(){return!(this.target.obj?.isDestroyed||!this.target.obj?.isBuilding()||!this.sourceObject.isInfantry())&&(this.target.obj.rules.capturable&&this.sourceObject.rules.engineer&&!this.game.areFriendly(this.sourceObject,this.target.obj))}isAllowed(){return!0}process(){return[new ep(this.game,this.target.obj)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof ep);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Cs(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class ip{constructor(e,t){this.game=e,this.map=t}create(e,t){switch(e){case An.Deploy:return new bd(this.game,!0);case An.DeploySelected:return new bd(this.game,!1);case An.ForceMove:return new md(this.game,this.map,t,!0);case An.Move:return new md(this.game,this.map,t);case An.ForceAttack:return new Fd(this.game,{forceAttack:!0});case An.Attack:return new Fd(this.game,{noIvanBomb:!0});case An.PlaceBomb:return new Fd(this.game);case An.AttackMove:return new Vd(this.game,this.map);case An.Capture:return new tp(this.game);case An.Occupy:return new Rd(this.game);case An.Stop:return new jd(this.game);case An.Cheer:return new Ud;case An.Dock:return new Wd(this.game);case An.Gather:return new zd(this.game);case An.Repair:return new qd(this.game);case An.Guard:return new Xd(this.game,!1);case An.GuardArea:return new Xd(this.game,!0);case An.Scatter:return new Zd(this.game);case An.EnterTransport:return new Kd(this.game);default:throw new Error(`Unhandled order type ${An[e]}`)}}}class sp{constructor(e,t,i){this.game=e,this.map=t,this.orderActionContext=i}create(){return new kd(this.game,this.map,this.orderActionContext,new ip(this.game,this.map))}}(r=ec=ec||{})[r.Add=0]="Add",r[r.Cancel=1]="Cancel",r[r.Pause=2]="Pause",r[r.Resume=3]="Resume";class rp extends Ju{constructor(e){super(ql.UpdateQueue),this.game=e}unserialize(e){let t=new b(e);var i;this.queueType=t.readUint8(),this.updateType=t.readUint8(),this.updateType!==ec.Add&&this.updateType!==ec.Cancel||(i=t.readUint32(),e=t.readUint8(),this.item=this.game.rules.getTechnoByInternalId(i,e),this.quantity=t.readUint16())}serialize(){let e=new b(9);if(e.dynamicSize=!1,e.writeUint8(this.queueType),e.writeUint8(this.updateType),this.updateType===ec.Add||this.updateType===ec.Cancel){if(void 0===this.quantity)throw new Error("Missing quantity");if(65535<this.quantity)throw new Error("Maximum quantity exceeded");e.writeUint32(this.item.index),e.writeUint8(this.item.type),e.writeUint16(this.quantity)}return new Uint8Array(e.buffer,e.byteOffset,e.position)}print(){return this.updateType===ec.Resume?`Resume queue ${mn[this.queueType]}`:this.updateType===ec.Add?`Add to queue ${this.item.name} x ${this.quantity}`:this.updateType===ec.Pause?`Put queue ${mn[this.queueType]} on hold.`:this.updateType===ec.Cancel?`Cancel ${this.item.name} x ${this.quantity}`:`Unhandled queue update type ${this.updateType}`}process(){let t=this.player,i=this.item,s=t.production.getQueue(this.queueType);if(this.updateType===ec.Resume)s.status===fn.OnHold&&(s.status=fn.Active);else if(this.updateType===ec.Add){let e=s.find(i);var r,a;(s.status===fn.Active||s.status===fn.Idle||s.status===fn.OnHold&&e[0]!==s.getFirst()||s.status===fn.Ready&&i.type!==Bt.Building)&&(r=e.reduce((e,t)=>e+t.quantity,0),a=t.getOwnedObjectsByType(i.type,!0).filter(e=>e.name===i.name).length,(a=Number.isFinite(i.buildLimit)?Math.max(0,i.buildLimit-(a+r)):Number.POSITIVE_INFINITY)&&t.production.isAvailableForProduction(i)&&(n=Math.min(s.maxSize-s.currentSize,s.maxItemQuantity-r,a),0<(o=Math.min(this.quantity,n))&&s.push(i,o,i.cost)))}else if(this.updateType===ec.Cancel){if([fn.Ready,fn.OnHold,fn.Active].includes(s.status)){let e=s.find(i);var n,o;e.length&&(n=e.reduce((e,t)=>e+t.quantity,0),0<(o=Math.min(n,this.quantity))&&(s.pop(i,o),o===n&&(t.credits+=e[0].creditsSpent)))}}else this.updateType===ec.Pause&&s.status===fn.Active&&(s.status=fn.OnHold)}}class ap{constructor(e){this.game=e}create(){return new rp(this.game)}}class np{constructor(e){this.target=e,this.type=is.PlayerDropped}}class op extends Ju{constructor(e,t){super(ql.DropPlayer),this.game=e,this.localPlayerName=t}process(){if(this.localPlayerName!==this.player.name){let e=this.player;e.defeated||(this.game.removeAllPlayerAssets(e),e.dropped=!0,this.game.events.dispatch(new np(e)))}}}class hp{constructor(e,t){this.game=e,this.localPlayerName=t}create(){return new op(this.game,this.localPlayerName)}}class lp{constructor(e){this.target=e,this.type=is.BuildingRepairStart}}class cp extends Ju{constructor(e){super(ql.ToggleRepair),this.game=e}unserialize(e){this.buildingId=new b(e).readUint32()}serialize(){return new b(4).writeUint32(this.buildingId).toUint8Array()}print(){return`Toggle repair ${this.buildingId}`}process(){var e=this.player;if(this.game.getWorld().hasObjectId(this.buildingId)){let t=this.game.getObjectById(this.buildingId);if(t.isBuilding()&&e===t.owner&&!t.isDestroyed&&t.rules.repairable&&t.rules.clickRepairable&&100!==t.healthTrait.health){let e=t.traits.get(Ih);e.setDisabled(!e.isDisabled()),e.isDisabled()||this.game.events.dispatch(new lp(t))}}}}class up{constructor(e){this.game=e}create(){return new cp(this.game)}}class dp extends Ju{constructor(e){super(ql.ToggleAlliance),this.game=e}unserialize(e){this.toPlayer=this.game.getPlayer(e[0]),this.toggle=Boolean(e[1])}serialize(){return new Uint8Array([this.game.getPlayerNumber(this.toPlayer),this.toggle?1:0])}print(){return`Toggle alliance ${this.toggle?"on":"off"} with ${this.toPlayer.name}`}process(){var e=this.game.rules.mpDialogSettings;if(e.alliesAllowed&&e.allyChangeAllowed){var a,n=this.player,t=this.toPlayer,e=this.toggle;let i=n,s=t,r=this.game.alliances;if(!n.defeated&&r.canRequestAlliance(s)){let t=r.findByPlayers(i,s);t?t.status===qh.Formed?e||(r.breakAlliance(i,s),this.game.onAllianceChange(t,i,!1)):t.status===qh.Requested&&(t.players.first===s?e&&r.canFormAlliance(i,s)&&(r.acceptRequest(s,i),this.game.onAllianceChange(t,i,!0),1!==(n=this.game.getCombatants().filter(e=>e!==i&&!r.areAllied(i,e))).length||(a=r.findByPlayers(n[0],i))&&r.cancelRequest(a.players.first,a.players.second),1!==(a=this.game.getCombatants().filter(e=>e!==s&&!r.areAllied(s,e))).length||(a=r.findByPlayers(a[0],s))&&r.cancelRequest(a.players.first,a.players.second)):e||(r.cancelRequest(i,s),this.game.events.dispatch(new Hl(t,el.Broken,i)),this.game.traits.filter(Kh).forEach(e=>{e[Kh.onChange](t,!1,this.game)}))):e&&r.canFormAlliance(i,s)&&((e=r.request(i,s))&&this.game.events.dispatch(new Hl(e,el.Requested,i)))}}}}class pp{constructor(e){this.game=e}create(){return new dp(this.game)}}class gp extends Ju{constructor(e){super(ql.ActivateSuperWeapon),this.game=e}unserialize(e){let t=new b(e);this.superWeaponType=t.readUint8();e=t.readUint8();this.tile={x:t.readUint16(),y:t.readUint16()},this.tile2=2<e?{x:t.readUint16(),y:t.readUint16()}:void 0}serialize(){let e=new b(6+(this.tile2?4:0));return e.dynamicSize=!1,e.writeUint8(this.superWeaponType),e.writeUint8(this.tile2?4:2),e.writeUint16(this.tile.x),e.writeUint16(this.tile.y),this.tile2&&(e.writeUint16(this.tile2.x),e.writeUint16(this.tile2.y)),e.toUint8Array()}print(){return`Activate SuperW ${ts[this.superWeaponType]} at tile (${this.tile.x}, ${this.tile.y})`+(this.tile2?`, (${this.tile2.x}, ${this.tile2.y})`:"")}process(){var e,t=this.player,i=this.game.map.tiles.getByMapCoords(this.tile.x,this.tile.y);i?(e=this.tile2?this.game.map.tiles.getByMapCoords(this.tile2.x,this.tile2.y):void 0,this.game.traits.get(hn).activateSuperWeapon(this.superWeaponType,t,this.game,i,e)):console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}}class mp{constructor(e){this.game=e}create(){return new gp(this.game)}}class fp{constructor(e,t){this.tile=e,this.player=t,this.type=is.PingLocation}}class yp extends Ju{constructor(e){super(ql.PingLocation),this.game=e}unserialize(e){let t=new b(e);this.tile={x:t.readUint16(),y:t.readUint16()}}serialize(){let e=new b(4);return e.writeUint16(this.tile.x),e.writeUint16(this.tile.y),e.toUint8Array()}print(){return`Ping location at tile (${this.tile.x}, ${this.tile.y})`}process(){var e=this.player,t=this.game.map.tiles.getByMapCoords(this.tile.x,this.tile.y);if(t){this.game.events.dispatch(new fp(t,e));for(var i of[e,...this.game.alliances.getAllies(e)])this.game.events.dispatch(new Bl(i,Zt.GenericNonCombat,t))}else console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}}class wp{constructor(e){this.game=e}create(){return new yp(this.game)}}class Tp{constructor(e){this.target=e,this.type=is.PlayerResigned}}class bp extends Ju{constructor(e){super(ql.ObserveGame),this.game=e}process(){let e=this.player;var t;this.game.removeAllPlayerAssets(e),!e.isCombatant()||e.defeated||e.isObserver||(e.resigned=!0,e.defeated=!0,e.isObserver=!0,this.game.events.dispatch(new Tp(e)),this.game.events.dispatch(new Ul(e)),this.game.mapShroudTrait.getPlayerShroud(e)?.revealAll(),t=e.radarTrait.isDisabled(),e.radarTrait.setDisabled(!1),t&&this.game.events.dispatch(new Al(e,!0)))}}class vp{constructor(e){this.game=e}create(){return new bp(this.game)}}class Sp extends Ju{constructor(e,t){super(ql.ResignGame),this.game=e,this.localPlayerName=t}process(){if(this.localPlayerName!==this.player.name){let e=this.player;this.game.removeAllPlayerAssets(e),e.isCombatant()&&(e.resigned=!0,this.game.events.dispatch(new Tp(e)))}}}class kp{constructor(e,t){this.game=e,this.localPlayerName=t}create(){return new Sp(this.game,this.localPlayerName)}}(r=tc=tc||{})[r.SetGlobalDebugText=0]="SetGlobalDebugText",r[r.SetUnitDebugText=1]="SetUnitDebugText";class Op{constructor(e,t){this.type=e,this.params=t}}class _p extends Ju{constructor(e){super(ql.DebugCommand),this.game=e}unserialize(e){let t=new b(e);e=t.readUint8();e===tc.SetUnitDebugText?this.command=new Op(e,{unitId:t.readUint32(),label:t.readCString()||void 0}):e===tc.SetGlobalDebugText?this.command=new Op(e,{text:t.readCString()}):console.warn(`Debug command ${e} not implemented`)}serialize(){let e=new b;if(e.writeUint8(this.command.type),this.command.type===tc.SetUnitDebugText){var t=this.command.params;e.writeUint32(t.unitId),e.writeCString(t.label||"")}else{if(this.command.type!==tc.SetGlobalDebugText)throw new Error(`Debug command ${this.command.type} not implemented`);t=this.command.params;e.writeCString(t.text)}return e.toUint8Array()}process(){if(this.command.type===tc.SetUnitDebugText){var{unitId:t,label:i}=this.command.params;if(this.game.getWorld().hasObjectId(t)){let e=this.game.getObjectById(t);e.isTechno()&&(e.debugLabel=i)}}else this.command.type===tc.SetGlobalDebugText?(i=this.command.params["text"],this.game.debugText.value=i):console.warn(`Debug command ${this.command.type} not implemented`)}}class Ip{constructor(e){this.game=e}create(){return new _p(this.game)}}class Cp{register(e,t,i){var s=new Ku;e.registerFactory(ql.NoAction,new td),e.registerFactory(ql.PlaceBuilding,new ad(t)),e.registerFactory(ql.SellBuilding,new od(t)),e.registerFactory(ql.ToggleRepair,new up(t)),e.registerFactory(ql.SelectUnits,new _d(t,s)),e.registerFactory(ql.OrderUnits,new sp(t,t.map,s)),e.registerFactory(ql.UpdateQueue,new ap(t)),e.registerFactory(ql.ToggleAlliance,new pp(t)),e.registerFactory(ql.ActivateSuperWeapon,new mp(t)),e.registerFactory(ql.PingLocation,new wp(t)),e.registerFactory(ql.DropPlayer,new hp(t,i)),e.registerFactory(ql.ObserveGame,new vp(t)),e.registerFactory(ql.ResignGame,new kp(t,i)),e.registerFactory(ql.DebugCommand,new Ip(t))}}class Ap{constructor(){this.detectors=new Set}[Zh.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.detect(e,t)}[Qh.onUnspawn](e,t){e.isTechno()&&(this.isGlobalDetector(e)&&(this.detectors.delete(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.undetect(e,t))}[Yh.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isDisguisable(e)&&(this.undetect(e,i),this.detect(e,i))}[Vr.onTileChange](e,t,i){this.isGlobalDetector(e)&&(this.updateAroundDetector(e,t,i),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&(this.undetect(e,t),this.detect(e,t))}[Ms.onPowerLow](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait&&!e.poweredTrait.isPoweredOn());this.updateAroundDetectors(i,e)}[Ms.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[Ms.onPowerChange](e,t){}updateAroundDetectors(e,t){let i=new Set;for(var s of e)for(var r of this.findTechnosAroundDetector(s,t,s.tile))i.add(r);for(var a of i)this.isDisguisable(a)&&(this.undetect(a,t),this.detect(a,t))}updateAroundDetector(e,t,i=e.tile){var s;for(s of this.findTechnosAroundDetector(e,t,i))this.isDisguisable(s)&&(this.undetect(s,t),this.detect(s,t))}findTechnosAroundDetector(e,t,i){var s=e.getFoundation(),s=Math.max(s.width,s.height),e=e.rules.detectDisguiseRange+s,s=new Ss(i.rx,i.ry).addScalar(-e),e=new Ss(i.rx,i.ry).addScalar(e);return t.map.technosByTile.queryRange(new Fn(s,e))}detect(e,t){let i=new Set,s=new Cs(t.map.tileOccupation);for(var r of this.detectors)if(!t.areFriendly(r,e)){var a=r.owner,n=r.rules.detectDisguiseRange;if(!i.has(a))if(!(r.isBuilding()&&r.poweredTrait&&!r.poweredTrait.isPoweredOn())&&s.tileDistance(e,r.tile)<=n)for(var o of[a,...t.alliances.getAllies(a)])i.add(o)}for(var h of i)h.sharedDetectDisguiseTrait?.add(e)}undetect(e,t){for(var i of t.getCombatants())i.sharedDetectDisguiseTrait?.delete(e)}isGlobalDetector(e){return!(!e.isTechno()||!e.rules.detectDisguiseRange)}isDisguisable(e){return!(!e.isInfantry()&&!e.isVehicle()||!e.disguiseTrait)}}class Bp{constructor(){this.detectors=new Set}[Zh.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isCloakable(e)&&this.detect(e,t)}[Qh.onUnspawn](e,t){e.isTechno()&&this.isGlobalDetector(e)&&this.detectors.delete(e)}[Yh.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isCloakable(e)&&this.detect(e,i)}[Vr.onTileChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,t),this.isCloakable(e)&&this.detect(e,t)}[Gl.onAdd](e,t,i){e.isTechno()&&(t instanceof cn?this.isCloakable(e)&&this.detect(e,i):t instanceof xh&&this.isGlobalDetector(e)&&this.updateAroundDetector(e,i))}[Ms.onPowerLow](e,t){}[Ms.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[Ms.onPowerChange](e,t){}[xs.onTick](e){for(var t of e.getCombatants()){var i;for(i of t.getOwnedObjects())i.cloakableTrait&&!i.cloakableTrait.isCloaked()&&this.detect(i,e)}}updateAroundDetectors(e,t){let i=new Set;for(var s of e)for(var r of this.findTechnosAroundDetector(s,t))i.add(r);for(var a of i)this.isCloakable(a)&&this.detect(a,t)}updateAroundDetector(e,t){var i;for(i of this.findTechnosAroundDetector(e,t))this.isCloakable(i)&&this.detect(i,t)}findTechnosAroundDetector(e,t){var i=e.getFoundation(),s=Math.max(i.width,i.height),i=e.rules.sensorsSight+s,s=new Ss(e.tile.rx,e.tile.ry).addScalar(-i),i=new Ss(e.tile.rx,e.tile.ry).addScalar(i);return t.map.technosByTile.queryRange(new Fn(s,i))}detect(e,t){let i=new Cs(t.map.tileOccupation);for(var s of this.detectors)if(!t.areFriendly(s,e)){var r=s.rules.sensorsSight;if(!(s.isBuilding()&&s.poweredTrait&&!s.poweredTrait.isPoweredOn())&&i.tileDistance(e,s.tile)<=r){r=e.cloakableTrait?.isCloaked();if(e.cloakableTrait.uncloak(t),r)for(var a of[s.owner,...t.alliances.getAllies(s.owner)])t.traits.get(xl).addEventForPlayer(Zt.GenericNonCombat,a,e.tile,t);break}}}isGlobalDetector(e){return!(!e.isTechno()||!e.sensorsTrait&&!e.rules.sensorArray||!e.rules.sensorsSight)}isCloakable(e){return e.isTechno()&&!!e.cloakableTrait}}class xp{constructor(){this.type=is.StalemateDetect}}class Ep{constructor(){this.stale=!1,this.allPlayersCredits=new Map,this.resetCountdown()}isStale(){return this.stale}getCountdownTicks(){return this.countdownTicks}resetCountdown(){this.countdownTicks=Math.floor(60*Ep.graceMinutes*Fs.BASE_TICKS_PER_SECOND)}clearStale(){this.stale=!1,this.resetCountdown()}[xs.onTick](e){0<this.countdownTicks?this.countdownTicks--:this.stale||(this.stale=!0,this.resetCountdown(),e.events.dispatch(new xp));for(var t of e.getCombatants()){var i=this.allPlayersCredits.get(t);i!==t.credits&&(this.allPlayersCredits.set(t,t.credits),t.credits>(i??0)&&t.production.hasAnyFactory()&&this.clearStale())}}[vn.onProduce](){this.clearStale()}[Xl.onPlace](e){e.wallTrait||this.clearStale()}[Jh.onDestroy](e,t,i){!e.isBuilding()||e.owner.isNeutral||e.wallTrait||e.rules.insignificant||i?.obj&&t.areFriendly(e,i.obj)||this.clearStale()}[Yh.onChange](e,t,i){e.isBuilding()&&!t.isNeutral&&(i.alliances.areAllied(e.owner,t)||this.clearStale())}}Ep.graceMinutes=5;class Pp{constructor(e){this.prng=e}static factory(e,t){return new this(new sc(Number(e+""+t)))}generateColors(e){let t=[...e.humanPlayers,...e.aiPlayers].filter(Fa),i=t.map(e=>e.colorId).filter(e=>-2!==e);e=zn.length;let s=new Array(e).fill(0).map((e,t)=>t).filter(e=>!i.includes(e)),r=new Map;return t.forEach(e=>{if(-3!==e.countryId&&-2===e.colorId){if(s.length<1)throw new Error("Out of available colors to choose from");var t=this.prng.generateRandomInt(0,s.length-1);r.set(e,s[t]),s.splice(t,1)}}),r}generateCountries(e,t){let i=t.getMultiplayerCountries().length,s=[...e.humanPlayers,...e.aiPlayers].filter(Fa),r=new Map;return s.forEach(e=>{-2===e.countryId&&r.set(e,this.prng.generateRandomInt(0,i-1))}),r}generateStartLocations(i,s){let e=[...i.humanPlayers,...i.aiPlayers].filter(Fa),t=e.filter(e=>-2!==e.startPos).map(e=>e.startPos),r=[...s.keys()].filter(e=>!t.includes(e)),a=[];for(;r.length;){var n=r.length?this.prng.generateRandomInt(0,r.length-1):0;a.push(...r.splice(n,1))}if(a.unshift(...t),3<=a.length)for(var o of[1,2])if(!(t.length-1>=o)){let e=a.map(e=>s[e]),t=this.findFarthestPointFrom(e.slice(0,o),e.slice(o));var h=e.findIndex(e=>e.x===t.x&&e.y===t.y);a.splice(o,0,...a.splice(h,1))}if(4<=a.length)if(t.length-1<3){let e=a.map(e=>s[e]),t=this.findFarthestPointFrom(e.slice(2,3),e.slice(3));i=e.findIndex(e=>e.x===t.x&&e.y===t.y);a.splice(3,0,...a.splice(i,1))}a.splice(0,t.length);let l=new Map,c=-1;return e.forEach(e=>{if(-3!==e.countryId&&-2===e.startPos){if(c>=a.length-1)throw new RangeError("Map has fewer starting locations than players");l.set(e,a[++c])}}),l}findFarthestPointFrom(e,t){let s=e.map(e=>new Ss(e.x,e.y)),r,a=0;if(!t.length)throw new Error("Search array must have at least one element");for(var n of t){let i=new Ss(n.x,n.y);var o=s.reduce((e,t)=>e+i.distanceTo(t),0);o>=a&&(r=n,a=o)}return r}}class Np{constructor(e,t){this.mapLighting=new wi,this._onChange=new ro,this.ambientChangeRate=e.ambientChangeRate,this.ambientChangeStep=e.ambientChangeStep,t&&this.mapLighting.copy(t)}get onChange(){return this._onChange.asEvent()}setAmbientChangeRate(e){this.ambientChangeRate=e}setAmbientChangeStep(e){this.ambientChangeStep=e}setTargetAmbientIntensity(e){this.targetAmbient=e}getAmbient(){return this.mapLighting}[xs.onTick](){var e;void 0!==this.targetAmbient&&(this.ambientUpdateTicks??(this.ambientUpdateTicks=Math.floor(60*Fs.BASE_TICKS_PER_SECOND*this.ambientChangeRate)),this.ambientUpdateTicks<=0?(this.ambientUpdateTicks=void 0,e=this.mapLighting.ambient,(e=this.targetAmbient-e)?(e=Math.sign(e)*Math.min(this.ambientChangeStep,Math.abs(e)),this.mapLighting.ambient+=e,this._onChange.dispatch(this,this.mapLighting)):this.targetAmbient=void 0):this.ambientUpdateTicks--)}}class Mp{constructor(e){this.ini=e}getIni(){return this.ini}}var Dp,Rp,Lp=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},Fp=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};class jp{constructor(e,t){this.name=e,this.country=t,Dp.set(this,!1)}setGameApi(e){this.gameApi=e}setActionsApi(e){this.actionsApi=e}setProductionApi(e){this.productionApi=e}setLogger(e){this.logger=e,this.logger.setDebugLevel(Lp(this,Dp,"f"))}setDebugMode(e){return Fp(this,Dp,e,"f"),this.logger?.setDebugLevel(e),this}getDebugMode(){return Lp(this,Dp,"f")}onGameStart(e){}onGameTick(e){}onGameEvent(e,t){}}Dp=new WeakMap,(r=Rp=Rp||{})[r.Initial=0]="Initial",r[r.Deployed=1]="Deployed",r[r.Attacking=2]="Attacking",r[r.Defeated=3]="Defeated";class Up extends jp{constructor(){super(...arguments),this.botState=Rp.Initial}onGameStart(t){var e=t.getTickRate();this.tickRatio=Math.ceil(e/5),this.enemyPlayers=t.getPlayers().filter(e=>e!==this.name&&!t.areAlliedPlayers(this.name,e))}onGameTick(e){if(e.getCurrentTick()%this.tickRatio==0)switch(this.botState){case Rp.Initial:{const i=e.getGeneralRules().baseUnit;if(e.getVisibleUnits(this.name,"self",e=>e.constructionYard).length){this.botState=Rp.Deployed;break}var t=e.getVisibleUnits(this.name,"self",e=>i.includes(e.name));t.length&&this.actionsApi.orderUnits([t[0]],An.DeploySelected);break}case Rp.Deployed:break;case Rp.Attacking:e.getVisibleUnits(this.name,"self",e=>e.isSelectableCombatant).length||(this.botState=Rp.Defeated,this.actionsApi.quitGame())}}}class Wp{constructor(e){this.botsLib=e}create(e){if(!e.isAi)throw new Error(`Player "${e.name}" is not an AI`);switch(e.aiDifficulty){case vs.Easy:return new Up(e.name,e.country.name);case vs.Medium:if(this.botsLib.SupalosaBot)return new this.botsLib.SupalosaBot(e.name,e.country.name);default:throw new Error(`Unsupported AI difficulty "${e.aiDifficulty}"`)}}}class zp{constructor(){this.actions=[]}push(...e){this.actions.push(...e)}getLast(){return this.actions[this.actions.length-1]}dequeueAll(){var e=[...this.actions];return this.actions.length=0,e}dequeueLast(){return this.actions.pop()}clear(){this.actions.length=0}}var Vp=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},Hp=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Gp{constructor(e,t,i,s,r){Kp.add(this),qp.set(this,void 0),Xp.set(this,void 0),Zp.set(this,void 0),Qp.set(this,void 0),Yp.set(this,void 0),Vp(this,qp,t,"f"),Vp(this,Xp,i,"f"),Vp(this,Zp,e,"f"),Vp(this,Qp,s,"f"),Vp(this,Yp,r,"f")}placeBuilding(t,i,s){Hp(this,Kp,"m",Jp).call(this,ql.PlaceBuilding,e=>{e.buildingRules=Hp(this,Zp,"f").rules.getBuilding(t),e.tile={x:i,y:s}})}sellBuilding(t){Hp(this,Kp,"m",Jp).call(this,ql.SellBuilding,e=>{e.buildingId=t})}toggleRepairWrench(t){Hp(this,Kp,"m",Jp).call(this,ql.ToggleRepair,e=>{e.buildingId=t})}toggleAlliance(t,i){Hp(this,Kp,"m",Jp).call(this,ql.ToggleAlliance,e=>{e.toPlayer=Hp(this,Zp,"f").getPlayerByName(t),e.toggle=i})}pauseProduction(t){Hp(this,Kp,"m",Jp).call(this,ql.UpdateQueue,e=>{e.queueType=t,e.updateType=ec.Pause})}resumeProduction(t){Hp(this,Kp,"m",Jp).call(this,ql.UpdateQueue,e=>{e.queueType=t,e.updateType=ec.Resume})}queueForProduction(t,e,i,s){let r=Hp(this,Zp,"f").rules.getObject(e,i);Hp(this,Kp,"m",Jp).call(this,ql.UpdateQueue,e=>{e.queueType=t,e.updateType=ec.Add,e.item=r,e.quantity=s})}unqueueFromProduction(t,e,i,s){let r=Hp(this,Zp,"f").rules.getObject(e,i);Hp(this,Kp,"m",Jp).call(this,ql.UpdateQueue,e=>{e.queueType=t,e.updateType=ec.Cancel,e.item=r,e.quantity=s})}activateSuperWeapon(t,i,s){Hp(this,Kp,"m",Jp).call(this,ql.ActivateSuperWeapon,e=>{e.superWeaponType=t,e.tile={x:i.rx,y:i.ry},e.tile2=s?{x:s.rx,y:s.ry}:void 0})}orderUnits(t,i,s,r,a){Hp(this,Kp,"m",Jp).call(this,ql.SelectUnits,e=>{e.unitIds=t});let n;if(s){let e,t;if(r){e=void 0;var o=Hp(this,Zp,"f").map.tiles.getByMapCoords(s,r);if(!o)throw new Error(`No tile found at rx,ry=${s},${r}`);t=o,a&&(e=Hp(this,Zp,"f").map.tileOccupation.getBridgeOnTile(o))}else{if(!Hp(this,Zp,"f").getWorld().hasObjectId(s))return;e=Hp(this,Zp,"f").getObjectById(s),t=e.tile}n=Hp(this,Zp,"f").createTarget(e,t)}Hp(this,Kp,"m",Jp).call(this,ql.OrderUnits,e=>{e.orderType=i,e.target=n})}sayAll(e){Hp(this,Yp,"f")?.sayAll(Hp(this,Qp,"f").name,e)}setGlobalDebugText(t){Hp(this,Qp,"f").getDebugMode()&&Hp(this,Kp,"m",Jp).call(this,ql.DebugCommand,e=>{e.command=new Op(tc.SetGlobalDebugText,{text:t||""})})}setUnitDebugText(t,i){Hp(this,Qp,"f").getDebugMode()&&Hp(this,Kp,"m",Jp).call(this,ql.DebugCommand,e=>{e.command=new Op(tc.SetUnitDebugText,{unitId:t,label:i})})}quitGame(){Hp(this,Kp,"m",Jp).call(this,ql.ResignGame)}}var $p,qp=new WeakMap,Xp=new WeakMap,Zp=new WeakMap,Qp=new WeakMap,Yp=new WeakMap,Kp=new WeakSet,Jp=function(e,t){let i=Hp(this,qp,"f").create(e);i.player=Hp(this,Zp,"f").getPlayerByName(Hp(this,Qp,"f").name),t?.(i),Hp(this,Xp,"f").push(i)},eg=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},tg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};(r=$p=$p||{})[r.ObjectOwnerChange=0]="ObjectOwnerChange",r[r.ObjectSpawn=1]="ObjectSpawn",r[r.ObjectUnspawn=2]="ObjectUnspawn",r[r.ObjectDestroy=3]="ObjectDestroy";class ig{constructor(e){ag.add(this),sg.set(this,void 0),rg.set(this,[]),eg(this,sg,e,"f")}subscribe(e,t){let i=void 0,s;s="function"==typeof e?e:(i=e,t);t=tg(this,sg,"f").subscribe(e=>{e=tg(this,ag,"m",ng).call(this,e);!e||void 0!==i&&i!==e.type||s(e)});return tg(this,rg,"f").push(t),t}dispose(){for(var e of tg(this,rg,"f"))e();tg(this,rg,"f").length=0}}var sg=new WeakMap,rg=new WeakMap,ag=new WeakSet,ng=function(t){switch(t.type){case is.ObjectOwnerChange:return{type:$p.ObjectOwnerChange,prevOwnerName:t.prevOwner.name,newOwnerName:t.target.owner.name,target:t.target.id};case is.ObjectSpawn:return{type:$p.ObjectSpawn,target:t.gameObject.id};case is.ObjectUnspawn:return{type:$p.ObjectUnspawn,target:t.gameObject.id};case is.ObjectDestroy:{let e=t;return e.target.isProjectile()?void 0:{type:$p.ObjectDestroy,target:e.target.id,attackerInfo:e.attackerInfo?{playerName:e.attackerInfo.player.name,objId:e.attackerInfo.obj?.id,weaponName:e.attackerInfo.weapon?.rules.name}:void 0}}default:return}},og=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},hg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class lg{constructor(e){dg.add(this),cg.set(this,void 0),ug.set(this,void 0),og(this,cg,e,"f"),og(this,ug,e.map,"f")}getRealMapSize(){return hg(this,ug,"f").tiles.getMapSize()}getStartingLocations(){return hg(this,ug,"f").startingLocations.map(e=>new Ss(e.x,e.y))}getTheaterType(){return hg(this,ug,"f").getTheaterType()}getTile(e,t){t=hg(this,ug,"f").tiles.getByMapCoords(e,t);if(t&&hg(this,ug,"f").mapBounds.isWithinBounds(t))return t}getTilesInRect(e,t){let i=t?hg(this,ug,"f").tiles.getInRectangle(e,t):hg(this,ug,"f").tiles.getInRectangle(e);return i.filter(e=>hg(this,ug,"f").mapBounds.isWithinBounds(e))}getObjectsOnTile(e){return hg(this,ug,"f").getObjectsOnTile(e).map(e=>e.id)}hasBridgeOnTile(e){return!!e.onBridgeLandType}hasHighBridgeOnTile(e){return!!hg(this,ug,"f").tileOccupation.getBridgeOnTile(e)?.isHighBridge()}isPassableTile(e,t,i){return 0<hg(this,ug,"f").terrain.getPassableSpeed(e,t,i)}findPath(e,t,i,s){let r=hg(this,cg,"f").map.terrain.computePath(e,t.tile,t.onBridge,i.tile,i.onBridge,{bestEffort:s?.bestEffort,excludeTiles:s?.excludeNodes?e=>s.excludeNodes({tile:e.tile,onBridge:!!e.onBridge}):void 0,maxExpandedNodes:s?.maxExpandedNodes});return r.map(e=>({tile:e.tile,onBridge:!!e.onBridge}))}isVisibleTile(e,t,i=0){var s=hg(this,cg,"f").getPlayerByName(t);if(!s)throw new Error(`Player "${t}" doesn't exist`);return!hg(this,cg,"f").mapShroudTrait.getPlayerShroud(s)?.isShrouded(e,i)}getTileResourceData(e){e=hg(this,ug,"f").getObjectsOnTile(e).find(e=>e.isOverlay()&&e.isTiberium()||e.isTerrain()&&e.rules.spawnsTiberium);return e?hg(this,dg,"m",pg).call(this,e):void 0}getAllTilesResourceData(){var e;let t=[];for(e of hg(this,cg,"f").getWorld().getAllObjects()){var i=hg(this,dg,"m",pg).call(this,e);i&&t.push(i)}return t}}var cg=new WeakMap,ug=new WeakMap,dg=new WeakSet,pg=function(t){let i;if(t.isOverlay()&&t.isTiberium()){let e=t.traits.get(qa);var s=e.getTiberiumType(),r=e.getBailCount();i={tile:t.tile,ore:s===oa.Ore?r:0,gems:s===oa.Gems?r:0,spawnsOre:!1}}else t.isTerrain()&&t.rules.spawnsTiberium&&(i={tile:t.tile,ore:0,gems:0,spawnsOre:!0});return i},gg=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},mg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class fg{constructor(e){yg.set(this,void 0),gg(this,yg,e,"f")}get allObjectRules(){return mg(this,yg,"f").allObjectRules}get buildingRules(){return mg(this,yg,"f").buildingRules}get infantryRules(){return mg(this,yg,"f").infantryRules}get vehicleRules(){return mg(this,yg,"f").vehicleRules}get aircraftRules(){return mg(this,yg,"f").aircraftRules}get terrainRules(){return mg(this,yg,"f").terrainRules}get overlayRules(){return mg(this,yg,"f").overlayRules}get countryRules(){return mg(this,yg,"f").countryRules}get general(){return mg(this,yg,"f").general}get ai(){return mg(this,yg,"f").ai}get crateRules(){return mg(this,yg,"f").crateRules}get combatDamage(){return mg(this,yg,"f").combatDamage}get radiation(){return mg(this,yg,"f").radiation}hasObject(e,t){return mg(this,yg,"f").hasObject(e,t)}getObject(e,t){return mg(this,yg,"f").getObject(e,t)}getBuilding(e){return mg(this,yg,"f").getBuilding(e)}getWeapon(e){return mg(this,yg,"f").getWeapon(e)}getWarhead(e){return mg(this,yg,"f").getWarhead(e)}getProjectile(e){return mg(this,yg,"f").getProjectile(e)}getOverlayName(e){return mg(this,yg,"f").getOverlayName(e)}getOverlayId(e){return mg(this,yg,"f").getOverlayId(e)}getOverlay(e){return mg(this,yg,"f").getOverlay(e)}getCountry(e){return mg(this,yg,"f").getCountry(e)}getMultiplayerCountries(){return mg(this,yg,"f").getMultiplayerCountries()}getIni(){return mg(this,yg,"f").getIni()}}var yg=new WeakMap,wg=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},Tg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class bg{constructor(e,t){kg.add(this),vg.set(this,void 0),Sg.set(this,void 0),wg(this,vg,e,"f"),wg(this,Sg,t,"f"),this.mapApi=new lg(e),this.rulesApi=new fg(e.rules)}isPlayerDefeated(e){return Tg(this,vg,"f").getPlayerByName(e).defeated}areAlliedPlayers(e,t){var i=Tg(this,vg,"f").getPlayerByName(e);if(!i)throw new Error(`Player "${e}" doesn't exist`);e=Tg(this,vg,"f").getPlayerByName(t);if(!e)throw new Error(`Player "${t}" doesn't exist`);return Tg(this,vg,"f").alliances.areAllied(i,e)}canPlaceBuilding(e,t,i){var s=Tg(this,vg,"f").getPlayerByName(e);if(!s)throw new Error(`Player "${e}" doesn't exist`);return Tg(this,vg,"f").getConstructionWorker(s).canPlaceAt(t,i,{normalizedTile:!0})}getBuildingPlacementData(e){e=Tg(this,vg,"f").art.getObject(e,Bt.Building);return{foundation:e.foundation,foundationCenter:e.foundationCenter}}getPlayers(){return Tg(this,vg,"f").getNonNeutralPlayers().map(e=>e.name)}getPlayerData(e){let t=Tg(this,vg,"f").getPlayerByName(e);if(!t)throw new Error(`Player "${e}" doesn't exist`);return{name:t.name,country:t.country,startLocation:this.mapApi.getStartingLocations()[t.startLocation],isObserver:t.isObserver,isAi:t.isAi,isCombatant:t.isCombatant(),credits:t.credits,power:{total:t.powerTrait?.power??0,drain:t.powerTrait?.drain??0,isLowPower:t.powerTrait?.level===gn.Low},radarDisabled:!!t.radarTrait?.isDisabled()}}getAllTerrainObjects(){return Tg(this,vg,"f").getWorld().getAllObjects().filter(e=>e.isTerrain()).map(e=>e.id)}getAllUnits(t=()=>!0){return Tg(this,vg,"f").getWorld().getAllObjects().filter(e=>e.isTechno()&&t(e.rules)).map(e=>e.id)}getNeutralUnits(t=()=>!0){return Tg(this,vg,"f").getCivilianPlayer().getOwnedObjects().filter(e=>t(e.rules)).map(e=>e.id)}getUnitsInArea(e){return Tg(this,vg,"f").map.technosByTile.queryRange(e).map(e=>e.id)}getVisibleUnits(e,s,t=()=>!0){const r=Tg(this,vg,"f").getPlayerByName(e);if(!r)throw new Error(`Player "${e}" doesn't exist`);if("self"===s)return r.getOwnedObjects().filter(e=>t(e.rules)).map(e=>e.id);let a;if("allied"===s)a=e=>e.owner===r||Tg(this,vg,"f").alliances.areAllied(e.owner,r);else{if("hostile"!==s&&"enemy"!==s)throw new Error(`Unexpected type ${s}`);{let i=Tg(this,vg,"f").mapShroudTrait.getPlayerShroud(r);a=t=>Tg(this,vg,"f").map.tileOccupation.calculateTilesForGameObject(t.tile,t).some(e=>!i?.isShrouded(e,t.tileElevation))&&t.owner!==r&&!Tg(this,vg,"f").alliances.areAllied(t.owner,r)&&("enemy"!==s||t.owner.isCombatant())}}return Tg(this,vg,"f").getWorld().getAllObjects().filter(e=>e.isTechno()&&!e.isDestroyed&&a(e)&&t(e.rules)).map(e=>e.id)}getGameObjectData(t){if(Tg(this,vg,"f").getWorld().hasObjectId(t)){let e=Tg(this,vg,"f").getObjectById(t);return{id:e.id,type:e.type,name:e.name,rules:e.rules,tile:e.tile,tileElevation:e.tileElevation,worldPosition:e.position.worldPosition.clone(),foundation:e.getFoundation(),hitPoints:e.healthTrait?.getHitPoints(),maxHitPoints:e.healthTrait?.maxHitPoints,owner:e.isTechno()?e.owner.name:void 0}}}getUnitData(t){var i=this.getGameObjectData(t);if(i){let e=Tg(this,vg,"f").getObjectById(t);if(!e.isTechno())throw new Error(`Game object with id ${t} is not a Techno type`);return{...i,owner:e.owner.name,sight:e.sight,veteranLevel:e.veteranLevel,guardMode:e.guardMode,purchaseValue:e.purchaseValue,primaryWeapon:e.primaryWeapon?Tg(this,kg,"m",Og).call(this,e.primaryWeapon):void 0,secondaryWeapon:e.secondaryWeapon?Tg(this,kg,"m",Og).call(this,e.secondaryWeapon):void 0,deathWeapon:e.armedTrait?.deathWeapon?Tg(this,kg,"m",Og).call(this,e.armedTrait.deathWeapon):void 0,attackState:e.attackTrait?.attackState,direction:e.direction,onBridge:e.isInfantry()||e.isVehicle()?e.onBridge:void 0,zone:e.isUnit()?e.zone:void 0,buildStatus:e.isBuilding()?e.buildStatus:void 0,factory:e.isBuilding()&&e.factoryTrait?{deliveringUnit:e.factoryTrait.deliveringUnit?.id,status:e.factoryTrait.status}:void 0,rallyPoint:e.isBuilding()?e.rallyTrait?.getRallyPoint():void 0,isPoweredOn:e.isBuilding()&&e.poweredTrait?.isPoweredOn(),hasWrenchRepair:e.isBuilding()&&!e.autoRepairTrait.isDisabled(),turretFacing:e.isBuilding()||e.isVehicle()?e.turretTrait?.facing:void 0,turretNo:e.isVehicle()?e.turretNo:void 0,garrisonUnitCount:e.isBuilding()?e.garrisonTrait?.units.length:void 0,garrisonUnitsMax:e.isBuilding()?e.garrisonTrait?.maxOccupants:void 0,passengerSlotCount:e.isVehicle()?e.transportTrait?.getOccupiedCapacity():void 0,passengerSlotMax:e.isVehicle()?e.transportTrait?.getMaxCapacity():void 0,isIdle:!e.unitOrderTrait.hasTasks(),canMove:e.isUnit()?!e.moveTrait.isDisabled():void 0,velocity:e.isUnit()?e.moveTrait.velocity.clone():void 0,stance:e.isInfantry()?e.stance:void 0,harvestedOre:e.isVehicle()?e.harvesterTrait?.ore:void 0,harvestedGems:e.isVehicle()?e.harvesterTrait?.gems:void 0,ammo:e.isAircraft()?e.ammo:void 0,isWarpedOut:e.warpedOutTrait.isActive(),mindControlledBy:e.mindControllableTrait?.getController()?.id,tntTimer:e.tntChargeTrait?.getTicksLeft()}}}getAllSuperWeaponData(){return Tg(this,vg,"f").getCombatants().map(t=>t.superWeaponsTrait.getAll().map(e=>({playerName:t.name,type:e.rules.type,status:e.status,timerSeconds:e.getTimerSeconds()}))).flat()}getGeneralRules(){return Tg(this,vg,"f").rules.general}getRulesIni(){return Tg(this,vg,"f").rules.getIni()}getArtIni(){return Tg(this,vg,"f").art.getIni()}getAiIni(){return Tg(this,vg,"f").ai.getIni()}generateRandomInt(e,t){if(Tg(this,Sg,"f"))return Tg(this,vg,"f").generateRandomInt(e,t);var i=this.generateRandom();return Math.round(i*(t-e))+e}generateRandom(){return Tg(this,Sg,"f")?Tg(this,vg,"f").generateRandom():Math.random()}getTickRate(){return Tg(this,vg,"f").speed.value*Fs.BASE_TICKS_PER_SECOND}getBaseTickRate(){return Fs.BASE_TICKS_PER_SECOND}getCurrentTick(){return Tg(this,vg,"f").currentTick}getCurrentTime(){return Tg(this,vg,"f").currentTime/1e3}}var vg=new WeakMap,Sg=new WeakMap,kg=new WeakSet,Og=function(e){return{type:e.type,rules:e.rules,projectileRules:e.projectileRules,warheadRules:e.warhead.rules,minRange:e.minRange,maxRange:e.range,speed:e.speed,cooldownTicks:e.getCooldownTicks()}},_g=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},Ig=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Cg{constructor(e,t){Ng.add(this),Eg.set(this,void 0),Pg.set(this,void 0),_g(this,Eg,e,"f"),_g(this,Pg,t,"f")}setDebugLevel(e){Ig(this,Eg,"f").setLevel(e?yr.DEBUG:yr.WARN)}debug(...e){Ig(this,Eg,"f").debug(Ig(this,Ng,"m",Mg).call(this),...e)}info(...e){Ig(this,Eg,"f").info(Ig(this,Ng,"m",Mg).call(this),...e)}log(...e){Ig(this,Eg,"f").log(Ig(this,Ng,"m",Mg).call(this),...e)}warn(...e){Ig(this,Eg,"f").warn(Ig(this,Ng,"m",Mg).call(this),...e)}error(...e){Ig(this,Eg,"f").error(Ig(this,Ng,"m",Mg).call(this),...e)}time(e){Ig(this,Eg,"f").time(e)}timeEnd(e){Ig(this,Eg,"f").timeEnd(e)}}var Ag,Bg,xg,Eg=new WeakMap,Pg=new WeakMap,Ng=new WeakSet,Mg=function(){return"["+function(e,t=!1){var i=Math.floor(e/3600);e-=3600*i;var s=Math.floor(e/60),e=e-=60*s;return[...i||!t?[i]:[],N(s,"00"),N(e,"00")].join(":")}(Math.floor(Ig(this,Pg,"f").getCurrentTime()))+"]"},Dg=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},Rg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Lg{constructor(e){Ag.set(this,void 0),Dg(this,Ag,e,"f")}isAvailableForProduction(e){return Rg(this,Ag,"f").isAvailableForProduction(e)}getAvailableObjects(t){let e=Rg(this,Ag,"f").getAvailableObjects();return void 0!==t&&(e=e.filter(e=>this.getQueueTypeForObject(e)===t)),e}getQueueTypeForObject(e){return Rg(this,Ag,"f").getQueueTypeForObject(e)}getQueueData(e){let t=Rg(this,Ag,"f").getQueue(e);return{size:t.currentSize,maxSize:t.maxSize,status:t.status,type:t.type,items:t.getAll().map(e=>({rules:e.rules,quantity:e.quantity}))}}}Ag=new WeakMap;class Fg{constructor(e,t,i,s,r,a){this.game=e,this.inputActions=t,this.replayRecorder=i,this.actionSerializer=s,this.actionFactory=r,this.actionLogger=a,this.errorState=!1}init(){this.gameTurnMillis=1e3/(this.game.speed.value*Fs.BASE_TICKS_PER_SECOND)}setErrorState(){this.errorState=!0}getErrorState(){return this.errorState}getTurnMillis(){return this.gameTurnMillis}doGameTurn(){if(!this.errorState){if(this.game.status!==$l.Ended){var t,e=this.inputActions.dequeueAll();const s=new Map;for(t of e){var i=this.actionSerializer.getActionPayload(t);let e=s.get(t.player);e||(e=[],s.set(t.player,e)),e.push(i)}this.replayRecorder.recordActions(this.game.currentTick,new Map([...s].map(([e,t])=>[this.game.getPlayerNumber(e),t]))),s.forEach((t,i)=>{if(!t.length){let e=new ed;e.player=i,t.push(this.actionSerializer.getActionPayload(e))}}),this.processActions(s)}this.game.update()}}processActions(e){[...e].forEach(([i,e])=>e.forEach(e=>{let t=this.actionFactory.create(e.id);t.player=i,t.unserialize(e.params),t.process();e=t.print();e&&this.actionLogger?.debug(`(${i.name})@${this.game.currentTick}: ${e}`)}))}dispose(){}}(r=Bg=Bg||{})[r.Closed=0]="Closed",r[r.Open=1]="Open",r[r.OpenObserver=2]="OpenObserver",r[r.Player=3]="Player",r[r.Ai=4]="Ai";class jg{encode(e){let s=[],r=0;return e.split("").forEach((e,t)=>{var i=e.charCodeAt(0)<<2*t-7*r,e=127&i,t=i>>7&127,i=i>>14&127;i&&r++,s.push(e,t),i&&s.push(i)}),s.push(0,0),2<=e.length&&s.push(0),s=s.map(e=>128^e),s.map(e=>String.fromCharCode(e)).join("")}decode(e){let i=e.split("").map(e=>e.charCodeAt(0));for(i=i.map(e=>128^e);0===i[i.length-1];)i.pop();let s=[],r=0,a=0;for(;i.length;){var n=s.length,o=i.shift(),h=i.shift();let e=0,t=!1;(-1!==[1,2,3].indexOf(i[0])||n>r+3)&&(e=i.shift(),r=n,t=!0);n=(e<<14|h<<7|o)>>2*n-7*a;s.push(127&n),t&&a++}return s.map(e=>String.fromCharCode(e)).join("")}}class Ug{encode(e){return e.match(/^[a-z0-9-_]+\.[a-z]{3}$/i)?e:P.encode(F(e))}decode(e){return e.match(/\.[a-z]{3}$/i)?e:j(P.decode(e))}}class Wg{serializeOptions(e,t=!1){let i=e.gameMode,s=t?(new jg).encode(e.mapTitle):P.encode(F(e.mapTitle)),r=(new Ug).encode(e.mapName);t=["0","0",6-e.gameSpeed,e.credits,e.unitCount,Number(e.shortGame),Number(e.superWeapons),Number(e.buildOffAlly),Number(e.mcvRepacks),Number(e.cratesAppear),i,Number(e.hostTeams??!1),s,e.maxSlots,Number(e.mapOfficial),e.mapSizeBytes,r,e.mapDigest].join(",");return`${t}:${e.humanPlayers.map(e=>`${e.name},${e.countryId},${e.colorId},${e.startPos},${e.teamId},0,0,0`).join(",")}:@:${this.serializeAiOpts(e.aiPlayers)},`}serializeAiOpts(e){return e.map(e=>e?`${e.difficulty},${e.countryId},${e.colorId},${e.startPos},${e.teamId}`:"0,-1,-1,-1,-1").join(",")}serializePingData(e){return e.length+","+e.map(e=>`${e.playerName},${e.ping}`).join(",")}serializeSlotData(e){return e.map(e=>{if(e.type===Bg.Closed)return"@Closed@";if(e.type===Bg.Open)return"@Open@";if(e.type===Bg.OpenObserver)return"@OpenObserver@";if(e.type===Bg.Ai){if(e.difficulty===vs.Easy)return"@EasyAI@";if(e.difficulty===vs.Medium)return"@MediumAI@";if(e.difficulty===vs.Brutal)return"@HardAI@"}else if(e.type===Bg.Player)return e.name;throw new Error(`Unexpected slot info with type ${Bg[e.type]}`)}).join(",")+","}serializeLoadInfo(e){return e.map(e=>[e.name,e.status,e.loadPercent,e.ping,e.lagAllowanceMillis].join(",")).join(",")}serializePlayerActions(e){let t=new b;t.writeUint8(e.length);for(var{id:i,params:s}of e)if(t.writeUint8(i),t.writeUint16(s.byteLength),0<s.byteLength){if(s.byteLength>Wg.MAX_ACTION_PAYLOAD_SIZE-t.position)throw console.error(`Action #${i} payload exceeds max data size`,s),new RangeError("Maximum payload data size exceeded");t.writeUint8Array(s)}return t.toUint8Array()}serializeAllPlayerActions(e,t){e.writeUint8(t.size);for(var[i,s]of t){e.writeUint8(i);var r=this.serializePlayerActions(s);if(e.writeUint16(r.byteLength),0<r.byteLength){if(r.byteLength>Wg.MAX_ACTION_PAYLOAD_SIZE)throw console.error(`Player #${i} actions payload exceeds max data size`,s),new RangeError("Maximum payload data size exceeded");e.writeUint8Array(r)}}}serializeMapData(e){return D(e)}}Wg.MAX_ACTION_PAYLOAD_SIZE=65536;class zg{parseOptions(e){let t={},[i,s,,r]=e.split(":"),a=i.split(",");a.shift(),a.shift(),t.gameSpeed=6-Number(a.shift()),t.credits=Number(a.shift()),t.unitCount=Number(a.shift()),t.shortGame=Boolean(Number(a.shift())),t.superWeapons=Boolean(Number(a.shift())),t.buildOffAlly=Boolean(Number(a.shift())),t.mcvRepacks=Boolean(Number(a.shift())),t.cratesAppear=Boolean(Number(a.shift())),t.gameMode=Number(a.shift()),t.hostTeams=Boolean(Number(a.shift()));e=a.shift();return t.mapTitle=P.isBase64(e)?j(P.decode(e)):(new jg).decode(e),t.maxSlots=Number(a.shift()),t.mapOfficial=Boolean(Number(a.shift())),t.mapSizeBytes=Number(a.shift()),t.mapName=(new Ug).decode(a.shift()),t.mapDigest=a.shift(),t.humanPlayers=this.parsePlayerOpts(s),t.aiPlayers=this.parseAiOpts(r?.slice(0,-1)),t}parsePlayerOpts(e){var i=e.split(",");if(i.length%8!=0)throw new Error(`Couldn't parse gameopt: unexpected players data length ${i.length}`);let s=[];for(let e=0,t=Math.floor(i.length/8);e<t;++e){var r={name:i[8*e],countryId:Number(i[8*e+1]),colorId:Number(i[8*e+2]),startPos:Number(i[8*e+3]),teamId:Number(i[8*e+4])};s.push(r)}return s}parseAiOpts(e){let i=[];if(e){var s=e.split(",");if(s.length%5!=0)throw new Error(`Couldn't parse gameopt: unexpected ai data length ${s.length}`);for(let e=0,t=Math.floor(s.length/5);e<t;++e){var r={difficulty:Number(s[5*e]),countryId:Number(s[5*e+1]),colorId:Number(s[5*e+2]),startPos:Number(s[5*e+3]),teamId:Number(s[5*e+4])};i.push(-1!==r.countryId?r:void 0)}}return i}parseTopic(e){var t=e.split(",");if(!(t.length<6)){var i=t[0],s=Number(t[1]),r=i[2],a=t[2],n=t[3],e=t[4],i=(new Ug).decode(t[5]);return{description:t[6]?j(P.decode(t[6])):"",modHash:s,modName:t[7]?j(P.decode(t[7])):void 0,aiPlayers:Number(a),maxPlayers:Number(r),observers:Number(n),observable:Boolean(Number(e)),mapName:i}}}parsePingData(e){var i=e.split(",").slice(1);if(i.length%2)throw new Error(`Couldn't parse gameopt: unexpected ping data length ${i.length}`);let s=[];for(let e=0,t=Math.floor(i.length/2);e<t;++e)s.push({playerName:i[2*e],ping:Number(i[2*e+1])});return s}parseSlotData(e){var i;let s=[];for(i of e.slice(1,-1).split(",")){let t={};if("@Closed@"===i)t.type=Bg.Closed;else if("@Open@"===i)t.type=Bg.Open;else if("@OpenObserver@"===i)t.type=Bg.OpenObserver;else if(-1!==["@EasyAI@","@MediumAI@","@HardAI@"].indexOf(i)){t.type=Bg.Ai;let e;if("@EasyAI@"===i)e=vs.Easy;else if("@MediumAI@"===i)e=vs.Medium;else{if("@HardAI@"!==i)throw new Error(`Couldn't parse gameopt: unknown slot type ${i}`);e=vs.Brutal}t.difficulty=e}else t.type=Bg.Player,t.name=i;s.push(t)}return s}parsePlayerActions(e){let t=new b(e);var i=t.readUint8();let s=[];for(let e=0;e<i;++e){var r=t.readUint8(),a=t.readUint16(),a=0<a?t.readUint8Array(a):new Uint8Array;s.push({id:r,params:a})}return s}parseAllPlayerActions(t){var i=t.readUint8();let s=new Map;for(let e=0;e<i;++e){var r=t.readUint8(),a=t.readUint16(),a=0<a?t.readUint8Array(a):new Uint8Array,a=this.parsePlayerActions(a);s.set(r,a)}return s}parseMapData(e){return L(e)}}class Vg{constructor(e,t){this.type=e,this.tickNo=t}}(r=xg=xg||{})[r.TurnActions=0]="TurnActions",r[r.ChatMessage=1]="ChatMessage",r[r.Taunt=2]="Taunt";class Hg extends Vg{constructor(e){super(xg.ChatMessage,e)}serialize(){return this.payload.playerId+":"+P.encode(F(this.payload.message))}unserialize(e){var[t,e]=e.split(":"),t=Number(t),e=j(P.decode(e));this.payload={playerId:t,message:e}}}class Gg extends Vg{constructor(e){super(xg.Taunt,e)}serialize(){return this.payload.playerId+":"+this.payload.tauntNo}unserialize(e){var[t,e]=e.split(":"),t=Number(t),e=Number(e);this.payload={playerId:t,tauntNo:e}}}class $g extends Vg{constructor(e,t,i){super(xg.TurnActions,i),this.gameOptsParser=e,this.gameOptsSerializer=t}serialize(){let e=new b;return this.gameOptsSerializer.serializeAllPlayerActions(e,new Map(this.payload)),t=e.toUint8Array(),P.encode(L(t));var t}unserialize(e){e=new b(R(e)),e=this.gameOptsParser.parseAllPlayerActions(e);this.payload=[...e]}}class qg{constructor(e,t){this.gameOptsParser=e,this.gameOptsSerializer=t}create(e,t){switch(e){case xg.TurnActions:return new $g(this.gameOptsParser,this.gameOptsSerializer,t);case xg.ChatMessage:return new Hg(t);case xg.Taunt:return new Gg(t);default:throw new Error(`Unsupported replay event type "${e}" at game tick "${t}"`)}}}const Xg=[5,6];class Zg{constructor(){this.name="",this.events=[]}static sanitizeFileName(e,t="_"){return e.replace(/[\/\?<>\\:\*\|"]/g,t).replace(/[\x00-\x1f\x7f\x80-\x9f]/g,t).slice(0,this.maxNameLength)}init(e,t,i,s,r){this.gameId=e,this.gameTimestamp=t,this.gameOpts=i,this.engineVersion=s,this.modHash=r,this.name=Zg.sanitizeFileName(this.gameOpts.mapTitle+" "+(new Date).toISOString().replace(/(\.|,)\d+Z$/,"Z")),this.timestamp=Date.now()}writeEvent(...e){this.events.push(...e)}finish(e){this.endTick=e}getEvents(){return this.events}*flush(){if(!this.gameOpts)throw new Error("Game options must be set first");if(!this.engineVersion)throw new Error("Engine version is not set");if(void 0===this.modHash)throw new Error("Mod hash is not set");let e=new Wg,t=this.getHeaderTag()+"\n";for(t+=`ENGINE ${this.engineVersion} ${this.modHash}\n`,t+=[this.gameId,this.gameTimestamp,e.serializeOptions(this.gameOpts)].join(" ")+"\n",yield t,t="";void 0===this.endTick||this.events.length;){for(var i of this.events)t+=i.tickNo+"="+i.type+"|"+i.serialize()+"\n";this.events.length=0,yield t,t=""}t+=this.getEndTag()+" "+this.endTick+"\n",this.debugInfo&&(t+=P.encode(F(this.debugInfo))+"\n"),yield t}serialize(){if(void 0===this.endTick)throw new Error("Replay is not finished");let e="";var t,i=this.events.slice();for(t of this.flush())e+=t;return this.events=i,e}async parseHeader(e){let t=0,i,s,r,a,n,o;var h;for await(h of"string"==typeof e?e.split("\n"):async function*(e){const t=new TextDecoder("utf-8");let i=e.stream().getReader(),{value:s,done:r}=await i.read();s=s?t.decode(s,{stream:!0}):"";let a=/\r\n|\n|\r/gm,n=0;for(;;){var o=a.exec(s);if(o)yield s.substring(n,o.index),n=a.lastIndex;else{if(r)break;o=s.substr(n);({value:s,done:r}=await i.read()),s=o+(s?t.decode(s,{stream:!0}):""),n=a.lastIndex=0}}n<s.length&&(yield s.substr(n))}(e)){if(0===t)i=this.readReplayVersion(h);else if(1===t){if(!h.match(Zg.engineLineRegex))throw new Error("Missing or invalid game engine version line");var l=h.split(" ");s=l[1],r=Number(i<4?"0":l[2])}else{if(2!==t)break;if(!h.match(/^\d+ \d+ .*$/))throw new Error("Missing or invalid game id/time/opts line");var[c,u,l]=h.split(" ");a=Number(c),n=Number(u),o=i<6?P.decode(l):l}t++}if(t<3)throw new Error("Bad replay header");return{replayVersion:i,engineVersion:s,modHash:r,gameId:a,gameTimestamp:n,gameOptsSerialized:o}}unserialize(e,t){let i=e.split("\n");var s=this.readReplayVersion(i.shift()||"");if(!Xg.includes(s))throw new Error(`Unsupported replay version ${s}`);let r=new zg,a=i.shift();if(!a||!a.match(Zg.engineLineRegex))throw new Error("Missing or invalid game engine version line");var[,n,o]=a.split(" ");let h=i.shift();if(!h)throw new Error("Missing game id/time/opts line");e=h.match(/^(\d+) (\d+) (.*)$/);if(!e)throw new Error("Invalid game id/time/opts line");let[,l,c,u]=e;s<6&&(u=P.decode(u));s=r.parseOptions(u);this.init(Number(l),Number(c),s,n,Number(o)),this.name=t.name,this.timestamp=t.timestamp;let d,p=!1;for(;d=i.shift();){if(d.startsWith(this.getEndTag())){p=!0;break}var g=d.match(/^(\d+)=(\d+)\|(.+)$/);if(!g)throw new Error(`Invalid event line "${d}"`);var[,m,f,g]=g,m=Number(m),f=Number(f);let e=new qg(r,new Wg).create(f,m);e.unserialize(g),this.writeEvent(e)}if(!p)throw new Error("Incomplete replay data");t=d.match(new RegExp(`^${this.getEndTag()} (\\d+)$`));if(!t)throw new Error("Invalid end tag");this.endTick=Number(t[1]),1<=i.length&&(this.debugInfo=j(P.decode(i[0])))}getHeaderTag(){return"RA2TSREPL_v6"}readReplayVersion(e){e=e.match(/^RA2TSREPL_v(\d+)$/);if(!e||e.length<2)throw new Error("Unknown replay format");return Number(e[1])}getEndTag(){return"END"}}Zg.extension=".rpl",Zg.maxNameLength=128,Zg.engineLineRegex=/^ENGINE \d+\.\d+( \d+)?$/;class Qg{constructor(e,t,i,s){this.replay=e,this.playerId=t,this.humanPlayers=i,this.actionSerializer=s}recordActions(t,i){if(Array.isArray(i)){let e=new $g(new zg,new Wg,t);e.payload=[[this.playerId,i.map(e=>this.actionSerializer.getActionPayload(e))]],this.replay.writeEvent(e)}else if(this.hasActualActions(i)){let e=new $g(new zg,new Wg,t);e.payload=[...i].map(([e,t])=>[e,t]),this.replay.writeEvent(e)}}recordChatMessage(e,t,i){let s=new Hg(e);s.payload={playerId:this.humanPlayers.findIndex(e=>e.name===t),message:i},this.replay.writeEvent(s)}recordTaunt(e,t,i){let s=new Gg(e);s.payload={playerId:this.humanPlayers.findIndex(e=>e.name===t),tauntNo:i},this.replay.writeEvent(s)}hasActualActions(e){return!![...e.values()].find(e=>e.find(e=>e.id!==ql.NoAction))}}class Yg{getActionPayload(e){return{id:e.actionType,params:e.serialize()}}}async function Kg(t){return new Promise(e=>{setTimeout(()=>e(),t)})}class Jg{constructor(e,t){this.options=e,this.logger=t,this.timeout=5,this._onMessage=new ro,this._onError=new ro,this._onClose=new ro,this.messageBuffer=""}get onMessage(){return this._onMessage.asEvent()}get onError(){return this._onError.asEvent()}get onClose(){return this._onClose.asEvent()}async connect(s){return new Promise((e,t)=>{this.socket=new WebSocket(s),"binary"===this.options.mode&&(this.socket.binaryType="blob");let i=e=>{this.socket.removeEventListener("error",i),t(new Jg.ConnectError(`Connection to "${s}" failed`))};this.socket.addEventListener("open",()=>{this.socket.removeEventListener("error",i),this.handleOpen(),e()}),this.socket.addEventListener("error",i),this.socket.addEventListener("error",e=>this.handleError(e)),this.socket.addEventListener("close",e=>this.handleClose(e)),this.socket.addEventListener("message",e=>{globalThis.Blob&&e.data instanceof Blob?this.parseData(e.data).then(e=>{this.handleMessage(e)}).catch(e=>{console.error("Failed to decode socket message.",e)}):this.handleMessage(e.data)})})}handleOpen(){this.logger.info("Connection open to "+this.socket.url)}handleError(e){this.logger.error("Connection error",e),this._onError.dispatch(this,e)}handleClose(e){this.logger.info(`Connection closed (${this.socket.url})`,e),this._onClose.dispatch(this,e)}handleMessage(e){if("string"!=typeof e){if(e[0]===this.options.binaryRplPrefix)return void this._onMessage.dispatch(this,e.slice(1));e=L(e)}this.logger.enabledFor(yr.DEBUG)&&this.logger.debug("Got message:","string"==typeof e?this.options.logFilter?.(e)??e:e),e=this.messageBuffer+e,this.messageBuffer="";let t=e.split(/\r?\n/);e=t.pop();e.length&&(this.messageBuffer=e),t.filter(e=>!!e).forEach(e=>this._onMessage.dispatch(this,e))}parseData(s){return new Promise((e,t)=>{let i=new FileReader;i.onload=()=>e(new Uint8Array(i.result)),i.onerror=()=>t(),i.readAsArrayBuffer(s)})}async sendCommand(e,h){if(h.replyStartCode&&!h.replyEndCode)throw new Error("Invalid argument. Expected a reply end code, but got only a start code.");let l=[];return await this.sendRawCommand(e,(e,r,a,n)=>{let o=(e,t)=>{if("number"==typeof e)return t.code===e;let[i,s]=e;return t.code===i&&s(t)};if("string"!=typeof e){if(e[0]===this.options.binaryRplPrefix)return!1;e=L(e)}return h.replyRawText?(a(e.split(/\r?\n/).map(e=>({raw:e,time:r}))),!0):e.split(/\r?\n/).filter(e=>!!e).some(e=>(e=>{if(h.replyMatch)return!!h.replyMatch.exec(e)&&(a([{raw:e,time:r}]),!0);if(!h.replyEndCode&&!h.replyCodes)return a([{raw:e,time:r}]),!0;var[,t,...i]=e.split(" "),t=parseInt(t,10);let s={raw:e,code:t,params:i,time:r};if(h.replyEndCode)return h.replyCodes&&h.replyCodes.some(e=>o(e,s))?(a([s]),!0):(h.replyHeartbeatCodes&&-1!==h.replyHeartbeatCodes.indexOf(t)&&n(h.heartbeatTimeout),(t===h.replyStartCode||h.replyBodyCodes&&-1!==h.replyBodyCodes.indexOf(t)||t===h.replyEndCode)&&l.push(s),t===h.replyEndCode&&(a(l),!0));if(void 0===h.replyCodes)throw new Error("List of replyCodes must be specified when not using start/end codes");return!!h.replyCodes.some(e=>o(e,s))&&(a([s]),!0)})(e))},h.timeout)}async sendBinCommand(e,r){const a=this.options.binaryRplPrefix;if(!a)throw new Error("Must configure binary message reply prefix to send binary commands");const t=this.options.binaryReqPrefix;if(!t)throw new Error("Must configure binary message request prefix to send binary commands");if(e[0]!==t)throw new Error(`Binary command must start with the magic prefix 0x${t.toString(16)}`);return await this.sendRawCommand(e,(e,t,i)=>{if("string"==typeof e||e[0]!==a)return!1;var s=e[1];return-1!==r.replyCodes.indexOf(s)&&(i({code:s,data:e.slice(2),time:t}),!0)},r.timeout)}sendRawCommand(d,p,g){return new Promise((t,i)=>{let s=!1,r,a=e=>{clearTimeout(r),void 0!==e&&Number.isFinite(e)&&(r=setTimeout(h,1e3*(e??g??this.timeout)))},n=e=>{clearTimeout(r),t(e)},o=e=>{this.socket.removeEventListener("message",u),this.socket.removeEventListener("close",l),clearTimeout(r),r=void 0,i(e)},h=()=>{var e="string"==typeof d?d:`0x${d[1].toString(16)}`;o(new Jg.NoReplyError(`Timeout reached for command ${e}`))},l=async()=>{for(;s;)await Kg(10);c||o(new Jg.SocketError("Connection was closed prematurely"))},c=!1,u=e=>{if(!c){let t=Date.now();globalThis.Blob&&e.data instanceof Blob?(s=!0,this.parseData(e.data).then(e=>{s=!1,c||p(e,t,n,a)&&(c=!0,this.socket.removeEventListener("message",u),this.socket.removeEventListener("close",l))}).catch(e=>{s=!1,console.error("Failed to decode socket message.",e)})):p(e.data,t,n,a)&&(c=!0,this.socket.removeEventListener("message",u),this.socket.removeEventListener("close",l))}};if(this.socket&&this.socket.readyState===WebSocket.OPEN){r=setTimeout(h,1e3*(g??this.timeout)),this.socket.addEventListener("message",u),this.socket.addEventListener("close",l);try{this.sendMessage(d)}catch(e){o(e)}}else o(new Jg.SocketError("Send command failed. Socket is not open."+(this.socket?` (readyState = ${this.socket.readyState})`:"")))})}sendMessage(e){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new Jg.SocketError(`Socket is not open${this.socket?` (readyState = ${this.socket.readyState})`:""}`);this.logger.enabledFor(yr.DEBUG)&&this.logger.debug("Sent message:","string"==typeof e?this.options.logFilter?.(e)??e:e),"string"==typeof e&&(e+="\r\n");let t;t="binary"===this.options.mode&&"string"==typeof e?D(e):e,this.socket.send(t)}async ping(e){var t=Date.now();return(await this.sendCommand(`ping :${t}`,{replyMatch:new RegExp(`^:[^ ]+ PONG [^ :]+ :${t}`,"i"),timeout:e}))[0].time-t}close(){this.socket&&this.socket.close()}isOpen(){return this.socket&&this.socket.readyState===WebSocket.OPEN}}!function(e){class t extends Error{constructor(e){super(e)}}e.NoReplyError=t;class i extends Error{constructor(e){super(e)}}e.SocketError=i;class s extends Error{constructor(e){super(e)}}e.ConnectError=s}(Jg=Jg||{});class em extends Error{constructor(e,t){super(e),this.code=t}}(r=(r=em=em||{}).Code||(r.Code={}))[r.Unknown=0]="Unknown",r[r.OutdatedClient=1]="OutdatedClient",r[r.BadLogin=2]="BadLogin",r[r.TooManyLoginAttempts=3]="TooManyLoginAttempts",r[r.AlreadyLoggedIn=4]="AlreadyLoggedIn",r[r.InstanceNonExistent=5]="InstanceNonExistent",r[r.InstanceAlreadyExists=6]="InstanceAlreadyExists",r[r.InstanceNotAllowed=7]="InstanceNotAllowed",r[r.InstanceAlreadyStarted=8]="InstanceAlreadyStarted",r[r.InstanceVersMismatch=9]="InstanceVersMismatch",r[r.CreatedTooManyInstances=10]="CreatedTooManyInstances";const tm="#all";var im;class sm{static encode(t){let i="";for(let e=0;e<this.maxLength;e++){var s=t.charCodeAt(e),r=0<e?t.charCodeAt(t.length-e):0;i+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"[63&(0<(1&s)?s<<1&r:s^r)]}return i}}sm.maxLength=8,(r=im=im||{})[r.Channel=0]="Channel",r[r.Page=1]="Page",r[r.Whisper=2]="Whisper";const rm=new Map([[103,em.Code.BadLogin],[104,em.Code.TooManyLoginAttempts],[101,em.Code.AlreadyLoggedIn],[201,em.Code.InstanceAlreadyExists],[202,em.Code.CreatedTooManyInstances],[401,em.Code.InstanceNonExistent],[402,em.Code.InstanceNotAllowed],[403,em.Code.InstanceAlreadyStarted],[406,em.Code.InstanceVersMismatch]]);class am{constructor(e,t,i,s,r,a,n,o,h,l,c,u){this.game=e,this.gservCon=t,this.gameoptParser=i,this.gameoptSerializer=s,this.actionSerializer=r,this.actionFactory=a,this.inputActions=n,this.onDesync=o,this.actionLogger=h,this.debugLogger=l,this.replayRecorder=c,this.debugGameState=u,this.debugGameStateHistory=[],this.queuedRateChanges=[],this.errorState=!1,this.passiveMode=!1,this.receivedActions=new Map,this.receivedNetworkTurn=0,this.lagState=!1,this._onLagStateChange=new ro,this._onActionsSent=new ro,this._onActionsProcessed=new ro,this._onActionsReceived=new ro,this.receiveActions=e=>{let t=new b(e);var i=t.readUint32(),e=this.gameoptParser.parseAllPlayerActions(t);this.receivedNetworkTurn=i,this.receivedActions.set(i,e),this._onActionsReceived.dispatch(void 0,i)},this.handleGameDesync=()=>{this.setErrorState(),this.onDesync()}}get onLagStateChange(){return this._onLagStateChange.asEvent()}get onActionsSent(){return this._onActionsSent.asEvent()}get onActionsProcessed(){return this._onActionsProcessed.asEvent()}get onActionsReceived(){return this._onActionsReceived.asEvent()}init(){this.gameTurnMillis=1e3/(this.game.desiredSpeed.value*Fs.BASE_TICKS_PER_SECOND),this.currentNetworkTurn=0,this.currentSubTurn=0,this.gservCon.onGameActions.subscribe(this.receiveActions),this.gservCon.onGameDesync.subscribe(this.handleGameDesync),this.debug(`Init: gameTurnMillis = ${this.gameTurnMillis}`)}canAdvanceNetworkTurn(){return this.currentNetworkTurn<2||this.receivedActions.has(this.currentNetworkTurn-2)}setErrorState(){this.errorState=!0}getErrorState(){return this.errorState}setRate(e){if(this.debug(`Recv rate: ${e.rate} (turn ${e.turnNo})`),0===this.currentSubTurn&&0===this.currentNetworkTurn&&0===e.turnNo)this.updateRate(e.rate);else{if(e.turnNo<this.currentNetworkTurn-2)throw new Error("Rate change has turn number more than two turns in the past.");this.queuedRateChanges.push(e)}}updateRate(e){var t;this.networkTurnMillis=(t=this.gameTurnMillis,Math.max(1,Math.ceil(e/t))*t),this.hashCheckTurnInterval=Math.ceil(am.PREFERRED_HASH_CHECK_MILLIS/this.networkTurnMillis),console.log(`Rate set to ${e} (${this.networkTurnMillis}ms) @ ${this.currentNetworkTurn}`)}setPassiveMode(e){this.debug(`Send passive: ${e}`),this.passiveMode=e,this.gservCon.sendPlayerActive(!e)}getTurnMillis(){return this.gameTurnMillis}doGameTurn(e){if(!this.errorState){if(!this.networkTurnMillis)throw new Error("Network turn rate should be set by now.");if(this.game.status!==$l.Ended){if(0===this.currentSubTurn){var t=this.queuedRateChanges[0];if(t&&t.turnNo+2===this.currentNetworkTurn&&(this.debug(`Process rate ${t.rate} (turn ${t.turnNo})`),this.updateRate(t.rate),this.queuedRateChanges.shift()),!this.canAdvanceNetworkTurn())return this.handleCommsLag(!0,e),this.debug(`Lag state: ${this.lagState}`),!1;this.debug("Advance turn"),this.commsLagStartTime&&0<e-this.commsLagStartTime&&console.log(`Waited ${Math.round(e-this.commsLagStartTime)}ms for other clients to catch up.`),this.handleCommsLag(!1,e),!this.passiveMode&&this.currentNetworkTurn>=this.receivedNetworkTurn&&this.sendActions(),2<=this.currentNetworkTurn&&(i=this.receivedActions.get(this.currentNetworkTurn-2),this.replayRecorder.recordActions(this.game.currentTick,i),this.processActions(i),this.receivedActions.delete(this.currentNetworkTurn-2),this._onActionsProcessed.dispatch(void 0,this.currentNetworkTurn-2)),this.game.update(),this.passiveMode||this.currentNetworkTurn%this.hashCheckTurnInterval!=0||this.gservCon.sendGameStateHash(this.currentNetworkTurn,this.game.getHash()),this.networkTurnMillis>this.gameTurnMillis?this.currentSubTurn++:this.currentNetworkTurn++}else this.debug("Update"),this.game.update(),this.currentSubTurn++,this.currentSubTurn>=this.networkTurnMillis/this.gameTurnMillis&&(this.currentSubTurn=0,this.currentNetworkTurn++);var i;this.debugGameState&&(i=this.networkTurnMillis/this.gameTurnMillis*this.hashCheckTurnInterval,this.debugGameStateHistory.length>i&&this.debugGameStateHistory.shift(),this.debugGameStateHistory.push(this.game.debugGetState()))}else this.game.update()}}handleCommsLag(e,t){e?(this.commsLagStartTime||(this.commsLagStartTime=t),1e3<t-this.commsLagStartTime&&this.updateLagState(!0)):(this.commsLagStartTime=void 0,this.updateLagState(!1))}updateLagState(e){e!==this.lagState&&(this.lagState=e,this._onLagStateChange.dispatch(void 0,e))}sendActions(){let e=this.inputActions.dequeueAll();e.length||e.push(new ed);var t=this.gameoptSerializer.serializePlayerActions(e.map(e=>this.actionSerializer.getActionPayload(e)));this.debug(`Send actions: ${t}`),this.gservCon.sendPlayerActions(this.currentNetworkTurn,t),this._onActionsSent.dispatch(void 0,this.currentNetworkTurn)}processActions(e){[...e].forEach(([i,e])=>e.forEach(e=>{let t=this.actionFactory.create(e.id);t.player=this.game.getPlayer(i),t.unserialize(e.params),t.process();e=t.print();e&&this.actionLogger?.debug(`(${t.player.name})@${this.game.currentTick}: ${e}`)}))}debug(e){this.debugLogger?.(`${this.currentNetworkTurn}-${this.currentSubTurn}-${this.game.currentTick}: ${e}`)}dispose(){this.setErrorState(),this.gservCon.onGameActions.unsubscribe(this.receiveActions),this.gservCon.onGameDesync.unsubscribe(this.handleGameDesync)}}am.PREFERRED_HASH_CHECK_MILLIS=1e3;const nm=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks");class om{constructor(e){this.gameTurnMgr=e,this.isStarted=!1}start(){this.isStarted||(this.isStarted=!0,this.startTime=void 0,this.lastGameFrame=0)}async waitForTick(){return new Promise((e,t)=>this.doWaitForTick(e,t))}doWaitForTick(e,t){try{this.isStarted||e();var i=nm.performance.now(),s=this.updateDeltaGameFrames(i);if(0<s)if(!(!1===this.gameTurnMgr.doGameTurn(i)))return void e();setImmediate(()=>this.doWaitForTick(e,t))}catch(e){t(e)}}updateDeltaGameFrames(e){var t=this.gameTurnMgr.getTurnMillis(),i=t!==this.lastGameTurnMillis;this.lastGameTurnMillis=t,i&&(this.lastGameFrame=0,this.startTime=e);let s=0;return this.startTime?(i=e-this.startTime,t=Math.round(i/t),s=t-this.lastGameFrame,this.lastGameFrame=t):this.startTime=e,s}stop(){this.isStarted&&(this.isStarted=!1)}destroy(){this.stop()}}const hm=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");var lm,cm,um,dm,pm,gm,mm,fm,ym=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},wm=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Tm{constructor(e,t,i,s,r,a,n,o,h){lm.set(this,void 0),cm.set(this,void 0),um.set(this,void 0),dm.set(this,void 0),pm.set(this,void 0),gm.set(this,void 0),mm.set(this,void 0),fm.set(this,void 0),ym(this,lm,e,"f"),ym(this,cm,t,"f"),ym(this,um,new bg(t,!1),"f"),ym(this,dm,new ig(t.events),"f"),ym(this,pm,i,"f"),ym(this,gm,a,"f"),ym(this,mm,o,"f"),ym(this,fm,h,"f"),wm(this,dm,"f").subscribe(t=>e.forEach(e=>e.onGameEvent(t,wm(this,um,"f")))),e.forEach(e=>{e.setGameApi(wm(this,um,"f")),e.setActionsApi(new Gp(t,s,r,e,n)),e.setProductionApi(new Lg(t.getPlayerByName(e.name).production)),e.setLogger(new Cg(yr.get(e.name),wm(this,um,"f"))),e.onGameStart(wm(this,um,"f"))})}isFinished(){return wm(this,cm,"f").status===$l.Ended||wm(this,gm,"f").getErrorState()}async update(){if(wm(this,mm,"f"))await wm(this,mm,"f").waitForTick();else{if(!(wm(this,gm,"f")instanceof Fg))throw new Error("Missing animation loop or turn manager");wm(this,gm,"f").doGameTurn()}wm(this,lm,"f").forEach(e=>e.onGameTick(wm(this,um,"f")))}getCurrentTick(){return wm(this,um,"f").getCurrentTick()}getTickRate(){return wm(this,um,"f").getTickRate()}getPlayerStats(){return wm(this,cm,"f").getNonNeutralPlayers().filter(e=>!e.isObserver).map(t=>({name:t.name,country:t.country,ai:t.isAi||wm(this,lm,"f").some(e=>e.name===t.name),defeated:t.defeated,credits:t.credits,startLocation:t.startLocation}))}saveReplay(e){let t=wm(this,pm,"f");t.finish(wm(this,cm,"f").currentTick);var i=`${wm(this,cm,"f").gameOpts.mapName}_${Date.now()}${Zg.extension}`,s=t.serialize(),i=a.resolve(e??process.cwd(),i);hm.writeFileSync(i,s,"utf-8"),process.stdout.write(`Replay saved to "${i}"\n`)}dispose(){wm(this,dm,"f").dispose(),wm(this,lm,"f").length=0,wm(this,fm,"f")?.call(this)}}lm=new WeakMap,cm=new WeakMap,um=new WeakMap,dm=new WeakMap,pm=new WeakMap,gm=new WeakMap,mm=new WeakMap,fm=new WeakMap;class bm{constructor(e,t,i){this.game=e,this.replayRecorder=t,this.gservCon=i,this.disposables=new Dl,this.handleGservMessage=e=>{e.to.type===im.Channel&&e.to.name===tm&&this.replayRecorder.recordChatMessage(this.game.currentTick,e.from,e.text)}}init(){this.gservCon.onChatMessage.subscribe(this.handleGservMessage),this.disposables.add(()=>this.gservCon.onChatMessage.unsubscribe(this.handleGservMessage))}sayAll(e,t){this.gservCon.isOpen()?this.gservCon.sayChannel(t):console.warn("Can't send chat message. Network connection is already closed.")}dispose(){this.disposables.dispose()}}class vm{constructor(e,t){this.game=e,this.replayRecorder=t}sayAll(e,t){this.replayRecorder.recordChatMessage(this.game.currentTick,e,t)}}var Sm=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},km=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};const Om=a.resolve((0,e.default)(),"./res");class _m{constructor(){Pm.add(this),Im.set(this,void 0),Cm.set(this,void 0),Am.set(this,void 0),Bm.set(this,void 0),xm.set(this,!1),Em.set(this,void 0)}async init(e){Sm(this,Pm,"m",Nm).call(this),globalThis.Blob||(globalThis.Blob=(await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,91))).Blob);var t=await(0,n.getOriginPrivateDirectory)(o.default,a.resolve(e)),i=await(0,n.getOriginPrivateDirectory)(o.default,Om),e=await(0,n.getOriginPrivateDirectory)(o.default,process.cwd());Pt.initGameResSource(vt.Local);let s=await Pt.initRfs(t);s.addDirectoryHandle(i),s.addDirectoryHandle(e);let r=await Pt.initVfs(s,yr.get("vfs"));await r.loadStandaloneFiles(),await r.loadExtraMixFiles(Pt.getActiveEngine()),await r.addMixFile("ra2cd.mix"),await r.loadImplicitMixFiles(Pt.getActiveEngine()),Pt.loadRules(),km(this,Em,await Pt.loadMapList(),"f"),km(this,Im,Pt.getMpModes(),"f"),km(this,xm,!0,"f")}getAvailableMaps(){if(!Sm(this,xm,"f"))throw new Error("API is not initialized. Call init() first.");return Sm(this,Em,"f").getAll().map(e=>e.fileName.toLowerCase())}getAvailableGameModes(e){if(!Sm(this,xm,"f"))throw new Error("API is not initialized. Call init() first.");let t=Sm(this,Em,"f").getByName(e);if(!t)throw new Error(`Map "${e}" is not available`);return t.gameModes.map(e=>e.id)}async createGame(e){return e.online?await Sm(this,Pm,"m",Dm).call(this,e):await Sm(this,Pm,"m",Mm).call(this,e)}}var Im=new WeakMap,Cm=new WeakMap,Am=new WeakMap,Bm=new WeakMap,xm=new WeakMap,Em=new WeakMap,Pm=new WeakSet,Nm=function(){yr.useDefaults(),yr.setLevel(yr.ERROR);const e=process.env.DEBUG_LOGGING;var t;if(e)if(isNaN(e))for(t of e.split(","))yr.get(t).setLevel(yr.DEBUG);else yr.setLevel(Boolean(Number(e))?yr.DEBUG:yr.ERROR);km(this,Cm,yr.get("ini"),"f"),km(this,Am,yr.get("action"),"f"),km(this,Bm,yr.get("net"),"f")},Mm=async function(e){if(!Sm(this,xm,"f"))throw new Error("API is not initialized. Call init() first.");var t=await Sm(this,Pm,"m",Lm).call(this,e),i=e.agents.filter(e=>e instanceof jp),s=new Si(await Pt.vfs.openFileWithRfs(t.mapName)),r=await Sm(this,Pm,"m",Rm).call(this,0,0,t,s,void 0),a=new zp,e=new Qu;(new Cp).register(e,r,void 0);let n=new Zg;n.init(r.id,r.startTimestamp,t,Pt.getVersion(),Pt.getModHash());s=new Yg,t=new Qg(n,0,r.gameOpts.humanPlayers,s);let o=new Fg(r,a,t,s,e,Sm(this,Am,"f"));o.init();t=new vm(r,t);return new Tm(i,r,n,e,a,o,t)},Dm=async function(e){if(!Sm(this,xm,"f"))throw new Error("API is not initialized. Call init() first.");if(!e.serverUrl)throw new Error("Must specify a serverUrl");if(!e.clientUrl)throw new Error("Must specify a clientUrl");let t=[];for(var i of e.agents){if(!i.name.match(/^[a-z0-9-_]+$/i))throw new Error(`Agent name "${i.name}" must contain only alphanumeric characters, dash (-) or underscore (_)`);i instanceof jp&&t.push(i)}if(!(e.agents[0]instanceof jp))throw new Error("The first object in the agents array must be a Bot instance in online mode");if(e.agents.slice(1).some(e=>e instanceof jp))throw new Error("Only the first player in the agents array can be a bot in online mode");var s=await Sm(this,Pm,"m",Lm).call(this,e);let r=class{constructor(e){this._onLoadInfo=new ro,this._onGameStart=new ro,this._onGameActions=new ro,this._onGameDesync=new ro,this._onRateChange=new ro,this._onChatMessage=new ro,this._onTaunt=new ro,this._onPlayerDisconnect=new ro,this.handleMessage=t=>{if("string"==typeof t){let e=t.split(" ");var i,s;"ping"===e[0]?this.isOpen()&&this.con.sendMessage("pong"+(e[1]?" "+e[1]:"")):"privmsg"===e[1].toLowerCase()?this.handlePrivMsg(t):"600"===e[1]?this.handleLoadInfo(e[3]):"700"===e[1]?this.handleGameStart():"801"===e[1]?this._onGameDesync.dispatch(this):"802"===e[1]?([i,s]=e[3].slice(1).split(","),this._onRateChange.dispatch(this,{rate:Number(i),turnNo:Number(s)})):"803"===e[1]?this._onTaunt.dispatch(this,{from:e[0].replace(/^:/,""),tauntNo:Number(e[3].replace(/^:/,""))}):"804"===e[1]&&this._onPlayerDisconnect.dispatch(this,e[3].replace(/^:/,""))}else 1===t[0]&&this.handlePlayerActions(t.slice(1))},this.con=e}get onError(){return this.con.onError}get onClose(){return this.con.onClose}get onLoadInfo(){return this._onLoadInfo.asEvent()}get onGameStart(){return this._onGameStart.asEvent()}get onGameActions(){return this._onGameActions.asEvent()}get onGameDesync(){return this._onGameDesync.asEvent()}get onRateChange(){return this._onRateChange.asEvent()}get onChatMessage(){return this._onChatMessage.asEvent()}get onTaunt(){return this._onTaunt.asEvent()}get onPlayerDisconnect(){return this._onPlayerDisconnect.asEvent()}static factory(e){return new this(new Jg({mode:"text",binaryRplPrefix:2,binaryReqPrefix:2,logFilter:e=>e.replace(/^(user [^ ]+) ([^ ]+)/i,"$1 <redacted>").replace(/^((:.+!.+@.+)?privmsg ([^ ]+ )+):(.+)\r?\n?$/i,"$1:<redacted>")},e))}getCurrentUser(){return this.currentUser}getServerName(){return this.serverName}async connect(e){return this.con.onMessage.subscribe(this.handleMessage),await this.con.connect(e)}close(){this.con.onMessage.unsubscribe(this.handleMessage),this.con.close(),this.currentUser=void 0}isOpen(){return this.con.isOpen()}async cvers(e){let t=await this.con.sendCommand(`cvers ${e} 2`,{replyCodes:[10,11]});if(11===t[0].code){e=t[0].params?t[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new em(`Cvers error: ${e}`,em.Code.OutdatedClient)}}async login(e,t){let i=await this.con.sendCommand(`user ${e} ${sm.encode(t)}`,{replyCodes:[100,103,104,101]});if(100!==i[0].code){var s=rm.get(i[0].code)??em.Code.Unknown,t=i[0].params?i[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new em(`Login error: ${t}`,s)}this.currentUser=e,this.serverName=i[0].raw.match(/^:([^\s]+)/)?.[1]||""}async createGame(e,t,i,s,r){if(i.includes(" "))throw new Error("Game opts string cannot include spaces");let a=await this.con.sendCommand(`create ${e} ${t} ${i} ${s} ${r}`,{replyCodes:[200,201,202,402]});if(200!==a[0].code){s=rm.get(a[0].code)??em.Code.Unknown,r=a[0].params?a[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new em(`Create error: ${r}`,s)}}async joinGame(e,t,i){let s=await this.con.sendCommand(`join ${e} ${t} ${i}`,{replyCodes:[400,401,402,403,406]});if(400!==s[0].code){t=rm.get(s[0].code)??em.Code.Unknown,i=s[0].params?s[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new em(`Join error: ${i}`,t)}}async gameOpts(){let e=await this.con.sendCommand("gameopts",{replyCodes:[500]});if(!e[0].params)throw new Error("Unexpected server reply for getopts command. Missing params.");return e[0].params.splice(1).join(" ").replace(/^:/,"")}sendLoadedPercent(e){this.con.sendMessage(`loaded ${e}`)}requestLoadInfo(){this.con.sendMessage("loadinfo")}sendGameStateHash(e,t){let i=new b(10);i.dynamicSize=!1,i.writeUint8(2),i.writeUint8(2),i.writeUint32(e),i.writeUint32(t),this.con.sendMessage(i.toUint8Array())}sendPlayerActive(e){this.con.sendMessage(`active ${e?1:0}`)}sendTaunt(e){this.con.sendMessage(`taunt ${e}`)}async ping(e){return await this.con.ping(e)}sendPlayerActions(e,t){let i=new b(6);i.writeUint8(2),i.writeUint8(1),i.writeUint32(e),i.writeUint8Array(t),this.con.sendMessage(i.toUint8Array())}sendMap(e){let t=new b(2);t.writeUint8(2),t.writeUint8(3),t.writeUint8Array((new Wg).serializeMapData(e)),this.con.sendMessage(t.toUint8Array())}async getMap(){let e=new b(2);e.dynamicSize=!1,e.writeUint8(2),e.writeUint8(4);var t=await this.con.sendBinCommand(e.toUint8Array(),{replyCodes:[2],timeout:15});return(new zg).parseMapData(t.data)}handleLoadInfo(e){this._onLoadInfo.dispatch(this,e.replace(/^:/,""))}handleGameStart(){this._onGameStart.dispatch(this,void 0)}handlePlayerActions(e){this._onGameActions.dispatch(this,e)}sayChannel(e){this.privmsg([tm],e)}privmsg(e,t){if(!this.currentUser)throw new Error("Must login before sending messages");t.length&&(e=e.join(","),this.con.sendMessage(`privmsg ${e} :${t}`))}handlePrivMsg(e){var t=e.match(/^:([A-Za-z0-9-_]+) PRIVMSG ([A-Za-z0-9-_#']+) :(.*)/i);if(!t)throw new Error(`Unexpected PRIVMSG message format "${e}"`);var[,i,s,e]=t;let r;t=new Date;s===tm?r={from:i,to:{type:im.Channel,name:s},text:e,time:t}:s===this.currentUser&&(r={from:i,to:i===this.getServerName()?{type:im.Page,name:s}:{type:im.Channel,name:"#team"},text:e,time:t}),r&&this._onChatMessage.dispatch(this,r)}}.factory(Sm(this,Bm,"f"));await r.connect(e.serverUrl),await r.cvers(Pt.getVersion()),await r.login(e.agents[0].name,e.botPassword);let a=new Wg;var n,o=a.serializeOptions(s),h=Date.now(),l=Math.floor(Date.now()/1e3);process.stdout.write("\nYou may use the following link(s) to join, after the game is created:\n\n");for(n of e.agents.slice(1))process.stdout.write(e.clientUrl.replace(/\/$/,"")+`/#/game/${h}/${l}/${encodeURIComponent(n.name)}\n`);process.stdout.write("\n\nPress ENTER to create the game now...\n"),await new Promise(e=>process.stdin.once("data",e)),process.stdin.pause(),process.stdout.write("Creating game...\n"),await r.createGame(h,l,o,Pt.getVersion(),Pt.getModHash());let c=new zg;var u=c.parseOptions(await r.gameOpts());let d=await Pt.vfs.openFileWithRfs(s.mapName);var p=new Si(d);s.mapOfficial||r.sendMap(d.readAsString());var g=e.agents[0].name;let m=await Sm(this,Pm,"m",Rm).call(this,h,l,u,p,g);o=new Yg,s=new zp,p=new Qu;(new Cp).register(p,m,g);let f=new Zg;f.init(m.id,m.startTimestamp,u,Pt.getVersion(),Pt.getModHash());u=new Qg(f,0,m.gameOpts.humanPlayers,o);let y=new am(m,r,c,a,o,p,s,()=>{console.error("Desync detected."),process.exit(1)},Sm(this,Am,"f"),void 0,u,!1);y.init();let w=new om(y);r.onRateChange.subscribe(e=>y.setRate(e)),m.onEnd.subscribe(()=>{process.stdout.write("Game ended.\n"),w.destroy()}),process.stdout.write("\nGame created."),process.stdout.write("\nWaiting for players to join...\n"),await new Promise((e,t)=>{r.onGameStart.subscribeOnce(()=>{r.onClose.unsubscribe(t),w.start(),e()}),r.onClose.subscribeOnce(t),r.sendLoadedPercent(100)}),process.stdout.write("Game started.\n");let T=new bm(m,u,r);T.init();return r.onClose.subscribeOnce(()=>y.dispose()),new Tm(t,m,f,p,s,y,T,w,()=>{w.destroy(),T.dispose(),Sm(this,Bm,"f").setLevel(yr.OFF),r.close()})},Rm=async function(e,t,i,s,r){if(!Sm(this,xm,"f"))throw new Error("API is not initialized. Call init() first.");var a=Pt.getIni(Sm(this,Im,"f").getById(i.gameMode).rulesOverride);await Pt.loadTheater(s.theaterType);var n=Pt.getActiveEngine(),o=Pt.getTheaterSettings(n,s.theaterType),n=Pt.getTheaterIni(n,s.theaterType);let h=new Q(n);h.loadTileData(Pt.getTileData(),o.Extension);let l=class{static create(e,t,i,s,r,a,n,o,h,l,c,u,d,p,g,m){var f=i.clone().mergeWith(a).mergeWith(e);let y=new Vn(f,d);var w=new qn(y,s,e,d),a=new Mp(r);y.applySpecialFlags(e.specialFlags),class{static sanitize(e,t){t=t.mpDialogSettings;e.credits=Math.floor(W(e.credits,t.minMoney,t.maxMoney)),e.gameSpeed=Math.floor(W(e.gameSpeed,0,6)),e.unitCount=Math.floor(W(e.unitCount,t.minUnitCount,t.maxUnitCount))}}.sanitize(h,y);let T=new Vn(i),b=T.getMultiplayerCountries(),v=[...T.getMultiplayerColors().values()],S=new sc(Number(n+""+o)),k=new ul(e,t,y,S.generateRandomInt.bind(S));f=new Gh,s=l.getById(h.gameMode).type,d=new gl,r=new pl(d),i=new fl,e=new yl(1),t=new Hh(k.tiles,k.tileOccupation,k.bridges,e),l=new Qu,u=new Wp(u),m=class{constructor(e,t,i,s,r){this.actionFactory=e,this.actionQueue=t,this.botFactory=i,this.botDebugIndex=s,this.actionLogger=r,this.bots=new Map,this.disposables=new Dl}static factory(e,t,i,s){return new this(e,new zp,t,i,s)}init(t){this.gameApi=new bg(t,!0);let e=new ig(t.events);var i,s;for(i of t.getCombatants().filter(e=>e.isAi))this.bots.set(i,this.botFactory.create(i));this.updateDebugBotIndex(this.botDebugIndex.value,t);let r=e=>this.updateDebugBotIndex(e,t);this.botDebugIndex.onChange.subscribe(r),this.disposables.add(()=>this.botDebugIndex.onChange.unsubscribe(r)),e.subscribe(t=>this.bots.forEach(e=>e.onGameEvent(t,this.gameApi))),this.disposables.add(e);for(s of this.bots.values())s.setGameApi(this.gameApi),s.setActionsApi(new Gp(t,this.actionFactory,this.actionQueue,s)),s.setProductionApi(new Lg(t.getPlayerByName(s.name).production)),s.setLogger(new Cg(yr.get(s.name),this.gameApi)),s.onGameStart(this.gameApi)}update(e){var t,i;for(t of this.actionQueue.dequeueAll()){t.process();var s=t.print();s&&this.actionLogger.debug(`(${t.player.name})@${e.currentTick}: ${s}`)}for(i of e.getCombatants().filter(e=>e.isAi))this.bots.get(i).onGameTick(this.gameApi)}updateDebugBotIndex(e,t){var i,s=0<e?t.getAiPlayerName(e):void 0;for(i of this.bots.values())i.setDebugMode(i.name===s)}dispose(){this.gameApi=void 0,this.bots.clear(),this.disposables.dispose()}}.factory(l,u,g,m);let O=new Xu(f,k,y,w,a,n,o,h,s,d,i,r,e,t,m);(new Cp).register(l,O,void 0),O.traits.add(new _l),O.sellTrait=new Cl(O,y.general),O.traits.add(O.sellTrait),O.traits.add(new xl);let _=new Pl(y,p);O.traits.add(_),O.mapShroudTrait=new Nl(k,r),O.traits.add(O.mapShroudTrait),O.mapRadiationTrait=new Zu(k),O.traits.add(O.mapRadiationTrait),O.mapLightingTrait=new Np(y.audioVisual,k.getLighting()),O.traits.add(O.mapLightingTrait),O.traits.add(new hn),O.traits.add(new Ap),O.traits.add(new Bp),O.crateGeneratorTrait=new Un(h.cratesAppear),O.traits.add(O.crateGeneratorTrait),c||(O.stalemateDetectTrait=new Ep,O.traits.add(O.stalemateDetectTrait));let I=new Ol(y,h,_.getAvailableObjects()),C=Pp.factory(n,o),A=C.generateColors(h),B=C.generateCountries(h,T),x=C.generateStartLocations(h,k.startingLocations),E=[...h.humanPlayers,...h.aiPlayers].filter(Fa);return E.forEach(e=>{let t,i,s;if(As(e)?(t=e.name,i=!1):(t=O.getAiPlayerName(e),i=!0,s=e.difficulty),-3!==e.countryId){var r=B.get(e)??e.countryId,a=A.get(e)??e.colorId,e=x.get(e)??e.startPos;if(-2===r)throw new Error("Random country should have been resolved by now");if(-2===a)throw new Error("Random color should have been resolved by now");if(-2===e)throw new Error("Random start location should have been resolved by now");r=b[r].name,r=Xn.factory(r,y),a=v[a];O.addPlayer(I.createCombatant(t,r,e,a,i,s))}else O.addPlayer(I.createObserver(t,y))}),O.addPlayer(I.createNeutral(y,"@@NEUTRAL@@")),O}}.create(s,h,Pt.getRules(),Pt.getArt(),Pt.getAi(),a,e,t,i,Sm(this,Im,"f"),!1,{version:"0.0.0"},Sm(this,Cm,"f"),new yl(!1),new yl(0),Sm(this,Am,"f"));return l.init(r?l.getPlayerByName(r):void 0),l.start(),l},Lm=async function(t){let e=Sm(this,Em,"f").getAll().find(e=>e.fileName.toLowerCase()===t.mapName.toLowerCase());if(!e)throw new Error(`Map ${t.mapName} not found.`);if(!e.gameModes.find(e=>e.id===t.gameMode))throw new Error(`Map "${e.fileName}" doesn't support game mode ${t.gameMode}`);let i=await Pt.vfs.openFileWithRfs(t.mapName),s=new Vn(Pt.getRules()).getMultiplayerCountries();return{gameMode:t.gameMode,shortGame:t.shortGame,mcvRepacks:t.mcvRepacks,cratesAppear:t.cratesAppear,superWeapons:t.superWeapons,gameSpeed:t.gameSpeed,credits:t.credits,unitCount:t.unitCount,buildOffAlly:t.buildOffAlly,humanPlayers:t.agents.map((t,e)=>({name:t.name,countryId:s.findIndex(e=>e.name===t.country),colorId:e,startPos:-2,teamId:-2})),aiPlayers:new Array(8).fill(void 0),mapName:e.fileName,mapDigest:class{static compute(e){return oe.calculateCrc(e.getBytes()).toString(16)}}.compute(i),mapSizeBytes:i.getSize(),mapTitle:e.fileName,maxSlots:e.maxSlots,mapOfficial:e.official}},r=__webpack_require__(949);class Fm extends r.Euler{constructor(){super(...arguments),this.isEuler=!0}setFromRotationMatrix(e,t,i){var s=e.elements,r=s[0],a=s[4],n=s[8],o=s[1],h=s[5],l=s[9],c=s[2],e=s[6],s=s[10];return"XYZ"===(t=t||this._order)?(this._y=Qi.asin(W(n,-1,1)),Math.abs(n)<.99999?(this._x=Qi.atan2(-l,s),this._z=Qi.atan2(-a,r)):(this._x=Qi.atan2(e,h),this._z=0)):"YXZ"===t?(this._x=Qi.asin(-W(l,-1,1)),Math.abs(l)<.99999?(this._y=Qi.atan2(n,s),this._z=Qi.atan2(o,h)):(this._y=Qi.atan2(-c,r),this._z=0)):"ZXY"===t?(this._x=Qi.asin(W(e,-1,1)),Math.abs(e)<.99999?(this._y=Qi.atan2(-c,s),this._z=Qi.atan2(-a,h)):(this._y=0,this._z=Qi.atan2(o,r))):"ZYX"===t?(this._y=Qi.asin(-W(c,-1,1)),Math.abs(c)<.99999?(this._x=Qi.atan2(e,s),this._z=Qi.atan2(o,r)):(this._x=0,this._z=Qi.atan2(-a,h))):"YZX"===t?(this._z=Qi.asin(W(o,-1,1)),Math.abs(o)<.99999?(this._x=Qi.atan2(-l,h),this._y=Qi.atan2(-c,r)):(this._x=0,this._y=Qi.atan2(n,s))):"XZY"===t?(this._z=Qi.asin(-W(a,-1,1)),Math.abs(a)<.99999?(this._x=Qi.atan2(e,h),this._y=Qi.atan2(n,r)):(this._x=Qi.atan2(-l,s),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+t),this._order=t,!1!==i&&this.onChangeCallback(),this}reorder(e){return jm.setFromEuler(this),this.setFromQuaternion(jm,e)}toVector3(e){return e?e.set(this._x,this._y,this._z):new ss(this._x,this._y,this._z)}}const jm=new Yi;r=__webpack_require__(949);class Um extends r.Spherical{setFromVector3(e){return this.radius=e.length(),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Qi.atan2(e.x,e.z),this.phi=Qi.acos(W(e.y/this.radius,-1,1))),this}}r=__webpack_require__(949);class Wm extends r.Cylindrical{setFromVector3(e){return this.radius=Qi.sqrt(e.x*e.x+e.z*e.z),this.theta=Qi.atan2(e.x,e.z),this.y=e.y,this}}const zm=new _m})();var __webpack_exports__ApiEventType=__webpack_exports__.ApiEventType,__webpack_exports__ArmorType=__webpack_exports__.ArmorType,__webpack_exports__AttackState=__webpack_exports__.AttackState,__webpack_exports__Bot=__webpack_exports__.Bot,__webpack_exports__Box2=__webpack_exports__.Box2,__webpack_exports__BuildCat=__webpack_exports__.BuildCat,__webpack_exports__BuildStatus=__webpack_exports__.BuildStatus,__webpack_exports__Cylindrical=__webpack_exports__.Cylindrical,__webpack_exports__Euler=__webpack_exports__.Euler,__webpack_exports__FactoryStatus=__webpack_exports__.FactoryStatus,__webpack_exports__FactoryType=__webpack_exports__.FactoryType,__webpack_exports__GameInstanceApi=__webpack_exports__.GameInstanceApi,__webpack_exports__GameMath=__webpack_exports__.GameMath,__webpack_exports__InfDeathType=__webpack_exports__.InfDeathType,__webpack_exports__LandTargeting=__webpack_exports__.LandTargeting,__webpack_exports__LandType=__webpack_exports__.LandType,__webpack_exports__LocomotorType=__webpack_exports__.LocomotorType,__webpack_exports__Matrix4=__webpack_exports__.Matrix4,__webpack_exports__MovementZone=__webpack_exports__.MovementZone,__webpack_exports__NavalTargeting=__webpack_exports__.NavalTargeting,__webpack_exports__ObjectType=__webpack_exports__.ObjectType,__webpack_exports__OrderType=__webpack_exports__.OrderType,__webpack_exports__PipColor=__webpack_exports__.PipColor,__webpack_exports__PrereqCategory=__webpack_exports__.PrereqCategory,__webpack_exports__PublicApi=__webpack_exports__.PublicApi,__webpack_exports__Quaternion=__webpack_exports__.Quaternion,__webpack_exports__QueueStatus=__webpack_exports__.QueueStatus,__webpack_exports__QueueType=__webpack_exports__.QueueType,__webpack_exports__RadarEventType=__webpack_exports__.RadarEventType,__webpack_exports__SideType=__webpack_exports__.SideType,__webpack_exports__SpeedType=__webpack_exports__.SpeedType,__webpack_exports__Spherical=__webpack_exports__.Spherical,__webpack_exports__StanceType=__webpack_exports__.StanceType,__webpack_exports__SuperWeaponStatus=__webpack_exports__.SuperWeaponStatus,__webpack_exports__SuperWeaponType=__webpack_exports__.SuperWeaponType,__webpack_exports__TagRepeatType=__webpack_exports__.TagRepeatType,__webpack_exports__TerrainType=__webpack_exports__.TerrainType,__webpack_exports__TheaterType=__webpack_exports__.TheaterType,__webpack_exports__Vector2=__webpack_exports__.Vector2,__webpack_exports__Vector3=__webpack_exports__.Vector3,__webpack_exports__VeteranAbility=__webpack_exports__.VeteranAbility,__webpack_exports__VeteranLevel=__webpack_exports__.VeteranLevel,__webpack_exports__VhpScan=__webpack_exports__.VhpScan,__webpack_exports__WeaponType=__webpack_exports__.WeaponType,__webpack_exports__ZoneType=__webpack_exports__.ZoneType,__webpack_exports__cdapi=__webpack_exports__.cdapi;export{__webpack_exports__ApiEventType as ApiEventType,__webpack_exports__ArmorType as ArmorType,__webpack_exports__AttackState as AttackState,__webpack_exports__Bot as Bot,__webpack_exports__Box2 as Box2,__webpack_exports__BuildCat as BuildCat,__webpack_exports__BuildStatus as BuildStatus,__webpack_exports__Cylindrical as Cylindrical,__webpack_exports__Euler as Euler,__webpack_exports__FactoryStatus as FactoryStatus,__webpack_exports__FactoryType as FactoryType,__webpack_exports__GameInstanceApi as GameInstanceApi,__webpack_exports__GameMath as GameMath,__webpack_exports__InfDeathType as InfDeathType,__webpack_exports__LandTargeting as LandTargeting,__webpack_exports__LandType as LandType,__webpack_exports__LocomotorType as LocomotorType,__webpack_exports__Matrix4 as Matrix4,__webpack_exports__MovementZone as MovementZone,__webpack_exports__NavalTargeting as NavalTargeting,__webpack_exports__ObjectType as ObjectType,__webpack_exports__OrderType as OrderType,__webpack_exports__PipColor as PipColor,__webpack_exports__PrereqCategory as PrereqCategory,__webpack_exports__PublicApi as PublicApi,__webpack_exports__Quaternion as Quaternion,__webpack_exports__QueueStatus as QueueStatus,__webpack_exports__QueueType as QueueType,__webpack_exports__RadarEventType as RadarEventType,__webpack_exports__SideType as SideType,__webpack_exports__SpeedType as SpeedType,__webpack_exports__Spherical as Spherical,__webpack_exports__StanceType as StanceType,__webpack_exports__SuperWeaponStatus as SuperWeaponStatus,__webpack_exports__SuperWeaponType as SuperWeaponType,__webpack_exports__TagRepeatType as TagRepeatType,__webpack_exports__TerrainType as TerrainType,__webpack_exports__TheaterType as TheaterType,__webpack_exports__Vector2 as Vector2,__webpack_exports__Vector3 as Vector3,__webpack_exports__VeteranAbility as VeteranAbility,__webpack_exports__VeteranLevel as VeteranLevel,__webpack_exports__VhpScan as VhpScan,__webpack_exports__WeaponType as WeaponType,__webpack_exports__ZoneType as ZoneType,__webpack_exports__cdapi as cdapi};
1
+ import*as __WEBPACK_EXTERNAL_MODULE_fetch_blob_71f8024a__ from"fetch-blob";import*as __WEBPACK_EXTERNAL_MODULE_three__ from"three";import*as __WEBPACK_EXTERNAL_MODULE_websocket_polyfill_8396782d__ from"websocket-polyfill";import{createRequire as __WEBPACK_EXTERNAL_createRequire}from"module";import*as __WEBPACK_EXTERNAL_MODULE_es_dirname_044d89a0__ from"es-dirname";import*as __WEBPACK_EXTERNAL_MODULE_file_system_access_58c08c7f__ from"file-system-access";import*as __WEBPACK_EXTERNAL_MODULE_file_system_access_lib_adapters_node_js_b1c03fd5__ from"file-system-access/lib/adapters/node.js";var __webpack_modules__={251:(e,t,i)=>{i.r(t),i.d(t,{default:()=>s});const s=function(){"use strict";var i=new function(){this.blockSize=131072,this.minNewSize=this.blockSize,this.maxSize=0,this.OK=0,this.INPUT_OVERRUN=-4,this.OUTPUT_OVERRUN=-5,this.LOOKBEHIND_OVERRUN=-6,this.EOF_FOUND=-999,this.ret=0,this.buf=null,this.buf32=null,this.out=new Uint8Array(262144),this.cbl=0,this.ip_end=0,this.op_end=0,this.t=0,this.ip=0,this.op=0,this.m_pos=0,this.m_len=0,this.m_off=0,this.dv_hi=0,this.dv_lo=0,this.dindex=0,this.ii=0,this.jj=0,this.tt=0,this.v=0,this.dict=new Uint32Array(16384),this.emptyDict=new Uint32Array(16384),this.skipToFirstLiteralFun=!1,this.returnNewBuffers=!0,this.setBlockSize=function(e){return"number"==typeof e&&!isNaN(e)&&0<parseInt(e)&&(this.blockSize=parseInt(e),!0)},this.setOutputSize=function(e){return"number"==typeof e&&!isNaN(e)&&0<parseInt(e)&&(this.out=new Uint8Array(parseInt(e)),!0)},this.setReturnNewBuffers=function(e){this.returnNewBuffers=!!e},this.applyConfig=function(e){void 0!==e&&(void 0!==e.outputSize&&i.setOutputSize(e.outputSize),void 0!==e.blockSize&&i.setBlockSize(e.blockSize))},this.ctzl=function(e){var t;return 1&e?t=0:(t=1,0==(65535&e)&&(e>>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),t-=1&e),t},this.extendBuffer=function(){var e=new Uint8Array(this.minNewSize+(this.blockSize-this.minNewSize%this.blockSize));e.set(this.out),this.out=e,this.cbl=this.out.length},this.match_next=function(){this.minNewSize=this.op+3,this.minNewSize>this.cbl&&this.extendBuffer(),this.out[this.op++]=this.buf[this.ip++],1<this.t&&(this.out[this.op++]=this.buf[this.ip++],2<this.t&&(this.out[this.op++]=this.buf[this.ip++])),this.t=this.buf[this.ip++]},this.match_done=function(){return this.t=3&this.buf[this.ip-2],this.t},this.copy_match=function(){for(this.t+=2,this.minNewSize=this.op+this.t,this.minNewSize>this.cbl&&this.extendBuffer();this.out[this.op++]=this.out[this.m_pos++],0<--this.t;);},this.copy_from_buf=function(){for(this.minNewSize=this.op+this.t,this.minNewSize>this.cbl&&this.extendBuffer();this.out[this.op++]=this.buf[this.ip++],0<--this.t;);},this.match=function(){for(;;){if(64<=this.t)this.m_pos=this.op-1-(this.t>>2&7)-(this.buf[this.ip++]<<3),this.t=(this.t>>5)-1,this.copy_match();else if(32<=this.t){if(this.t&=31,0===this.t){for(;0===this.buf[this.ip];)this.t+=255,this.ip++;this.t+=31+this.buf[this.ip++]}this.m_pos=this.op-1-(this.buf[this.ip]>>2)-(this.buf[this.ip+1]<<6),this.ip+=2,this.copy_match()}else if(16<=this.t){if(this.m_pos=this.op-((8&this.t)<<11),this.t&=7,0===this.t){for(;0===this.buf[this.ip];)this.t+=255,this.ip++;this.t+=7+this.buf[this.ip++]}if(this.m_pos-=(this.buf[this.ip]>>2)+(this.buf[this.ip+1]<<6),this.ip+=2,this.m_pos===this.op)return this.state.outputBuffer=!0===this.returnNewBuffers?new Uint8Array(this.out.subarray(0,this.op)):this.out.subarray(0,this.op),this.EOF_FOUND;this.m_pos-=16384,this.copy_match()}else this.m_pos=this.op-1-(this.t>>2)-(this.buf[this.ip++]<<2),this.minNewSize=this.op+2,this.minNewSize>this.cbl&&this.extendBuffer(),this.out[this.op++]=this.out[this.m_pos++],this.out[this.op++]=this.out[this.m_pos];if(0===this.match_done())return this.OK;this.match_next()}},this.decompress=function(e){if(this.state=e,this.buf=this.state.inputBuffer,this.cbl=this.out.length,this.ip_end=this.buf.length,this.t=0,this.ip=0,this.op=0,this.m_pos=0,this.skipToFirstLiteralFun=!1,17<this.buf[this.ip])if(this.t=this.buf[this.ip++]-17,this.t<4){if(this.match_next(),this.ret=this.match(),this.ret!==this.OK)return this.ret===this.EOF_FOUND?this.OK:this.ret}else this.copy_from_buf(),this.skipToFirstLiteralFun=!0;for(;;){if(this.skipToFirstLiteralFun)this.skipToFirstLiteralFun=!1;else{if(this.t=this.buf[this.ip++],16<=this.t){if(this.ret=this.match(),this.ret!==this.OK)return this.ret===this.EOF_FOUND?this.OK:this.ret;continue}if(0===this.t){for(;0===this.buf[this.ip];)this.t+=255,this.ip++;this.t+=15+this.buf[this.ip++]}this.t+=3,this.copy_from_buf()}if(this.t=this.buf[this.ip++],this.t<16){if(this.m_pos=this.op-2049,this.m_pos-=this.t>>2,this.m_pos-=this.buf[this.ip++]<<2,this.minNewSize=this.op+3,this.minNewSize>this.cbl&&this.extendBuffer(),this.out[this.op++]=this.out[this.m_pos++],this.out[this.op++]=this.out[this.m_pos++],this.out[this.op++]=this.out[this.m_pos],0===this.match_done())continue;this.match_next()}if(this.ret=this.match(),this.ret!==this.OK)return this.ret===this.EOF_FOUND?this.OK:this.ret}return this.OK},this._compressCore=function(){for(this.ip_start=this.ip,this.ip_end=this.ip+this.ll-20,this.jj=this.ip,this.ti=this.t,this.ip+=this.ti<4?4-this.ti:0,this.ip+=1+(this.ip-this.jj>>5);!(this.ip>=this.ip_end);)if(this.dv_lo=this.buf[this.ip]|this.buf[this.ip+1]<<8,this.dv_hi=this.buf[this.ip+2]|this.buf[this.ip+3]<<8,this.dindex=((17053*this.dv_lo>>>16)+17053*this.dv_hi+6180*this.dv_lo&65535)>>>2,this.m_pos=this.ip_start+this.dict[this.dindex],this.dict[this.dindex]=this.ip-this.ip_start,(this.dv_hi<<16)+this.dv_lo==(this.buf[this.m_pos]|this.buf[this.m_pos+1]<<8|this.buf[this.m_pos+2]<<16|this.buf[this.m_pos+3]<<24)){if(this.jj-=this.ti,this.ti=0,this.v=this.ip-this.jj,0!==this.v)if(this.v<=3)for(this.out[this.op-2]|=this.v;this.out[this.op++]=this.buf[this.jj++],0<--this.v;);else{if(this.v<=18)this.out[this.op++]=this.v-3;else{for(this.tt=this.v-18,this.out[this.op++]=0;255<this.tt;)this.tt-=255,this.out[this.op++]=0;this.out[this.op++]=this.tt}for(;this.out[this.op++]=this.buf[this.jj++],0<--this.v;);}if(this.m_len=4,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len])for(;this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&(this.m_len+=1,this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]&&!(this.ip+this.m_len>=this.ip_end)&&this.buf[this.ip+this.m_len]===this.buf[this.m_pos+this.m_len]))))))););if(this.m_off=this.ip-this.m_pos,this.ip+=this.m_len,this.jj=this.ip,this.m_len<=8&&this.m_off<=2048)--this.m_off,this.out[this.op++]=this.m_len-1<<5|(7&this.m_off)<<2,this.out[this.op++]=this.m_off>>3;else if(this.m_off<=16384){if(--this.m_off,this.m_len<=33)this.out[this.op++]=32|this.m_len-2;else{for(this.m_len-=33,this.out[this.op++]=32;255<this.m_len;)this.m_len-=255,this.out[this.op++]=0;this.out[this.op++]=this.m_len}this.out[this.op++]=this.m_off<<2,this.out[this.op++]=this.m_off>>6}else{if(this.m_off-=16384,this.m_len<=9)this.out[this.op++]=16|this.m_off>>11&8|this.m_len-2;else{for(this.m_len-=9,this.out[this.op++]=16|this.m_off>>11&8;255<this.m_len;)this.m_len-=255,this.out[this.op++]=0;this.out[this.op++]=this.m_len}this.out[this.op++]=this.m_off<<2,this.out[this.op++]=this.m_off>>6}}else this.ip+=1+(this.ip-this.jj>>5);this.t=this.ll-(this.jj-this.ip_start-this.ti)},this.compress=function(e){for(this.state=e,this.ip=0,this.buf=this.state.inputBuffer,this.maxSize=this.buf.length+Math.ceil(this.buf.length/16)+64+3,this.maxSize>this.out.length&&(this.out=new Uint8Array(this.maxSize)),this.op=0,this.l=this.buf.length,this.t=0;20<this.l&&(this.ll=this.l<=49152?this.l:49152,!(this.t+this.ll>>5<=0));)this.dict.set(this.emptyDict),this.prev_ip=this.ip,this._compressCore(),this.ip=this.prev_ip+this.ll,this.l-=this.ll;if(this.t+=this.l,0<this.t){if(this.ii=this.buf.length-this.t,0===this.op&&this.t<=238)this.out[this.op++]=17+this.t;else if(this.t<=3)this.out[this.op-2]|=this.t;else if(this.t<=18)this.out[this.op++]=this.t-3;else{for(this.tt=this.t-18,this.out[this.op++]=0;255<this.tt;)this.tt-=255,this.out[this.op++]=0;this.out[this.op++]=this.tt}for(;this.out[this.op++]=this.buf[this.ii++],0<--this.t;);}return this.out[this.op++]=17,this.out[this.op++]=0,this.out[this.op++]=0,this.state.outputBuffer=!0===this.returnNewBuffers?new Uint8Array(this.out.subarray(0,this.op)):this.out.subarray(0,this.op),this.OK}};return{setBlockSize:function(e){return i.setBlockSize(e)},setOutputEstimate:function(e){return i.setOutputSize(e)},setReturnNewBuffers:function(e){i.setReturnNewBuffers(e)},compress:function(e,t){return void 0!==t&&i.applyConfig(t),i.compress(e)},decompress:function(e,t){return void 0!==t&&i.applyConfig(t),i.decompress(e)}}}()},163:function(h,l,c){var u;!function(){"use strict";function e(e,t){return function(){return t.apply(e,arguments)}}function i(){for(var e,t=arguments,i=t[0],s=1;s<t.length;s++)for(e in t[s])e in i||!t[s].hasOwnProperty(e)||(i[e]=t[s][e]);return i}var s,o={VERSION:"1.4.1"},r={},t=function(e,t){return{value:e,name:t}};o.DEBUG=t(1,"DEBUG"),o.INFO=t(2,"INFO"),o.TIME=t(3,"TIME"),o.WARN=t(4,"WARN"),o.ERROR=t(8,"ERROR"),o.OFF=t(99,"OFF");function a(e){this.context=e,this.setLevel(e.filterLevel),this.log=this.info}a.prototype={setLevel:function(e){e&&"value"in e&&(this.context.filterLevel=e)},getLevel:function(){return this.context.filterLevel},enabledFor:function(e){var t=this.context.filterLevel;return e.value>=t.value},debug:function(){this.invoke(o.DEBUG,arguments)},info:function(){this.invoke(o.INFO,arguments)},warn:function(){this.invoke(o.WARN,arguments)},error:function(){this.invoke(o.ERROR,arguments)},time:function(e){"string"==typeof e&&0<e.length&&this.invoke(o.TIME,[e,"start"])},timeEnd:function(e){"string"==typeof e&&0<e.length&&this.invoke(o.TIME,[e,"end"])},invoke:function(e,t){s&&this.enabledFor(e)&&s(t,i({level:e},this.context))}};var n=new a({filterLevel:o.OFF});(t=o).enabledFor=e(n,n.enabledFor),t.debug=e(n,n.debug),t.time=e(n,n.time),t.timeEnd=e(n,n.timeEnd),t.info=e(n,n.info),t.warn=e(n,n.warn),t.error=e(n,n.error),t.log=t.info,o.setHandler=function(e){s=e},o.setLevel=function(e){for(var t in n.setLevel(e),r)r.hasOwnProperty(t)&&r[t].setLevel(e)},o.getLevel=function(){return n.getLevel()},o.get=function(e){return r[e]||(r[e]=new a(i({name:e},n.context)))},o.createDefaultHandler=function(r){(r=r||{}).formatter=r.formatter||function(e,t){t.name&&e.unshift("["+t.name+"]")};function a(e,t){Function.prototype.apply.call(e,console,t)}var n={};return"undefined"==typeof console?function(){}:function(e,t){e=Array.prototype.slice.call(e);var i,s=console.log;t.level===o.TIME?(i=(t.name?"["+t.name+"] ":"")+e[0],"start"===e[1]?console.time?console.time(i):n[i]=(new Date).getTime():console.timeEnd?console.timeEnd(i):a(s,[i+": "+((new Date).getTime()-n[i])+"ms"])):(t.level===o.WARN&&console.warn?s=console.warn:t.level===o.ERROR&&console.error?s=console.error:t.level===o.INFO&&console.info?s=console.info:t.level===o.DEBUG&&console.debug&&(s=console.debug),r.formatter(e,t),a(s,e))}},o.useDefaults=function(e){o.setLevel(e&&e.defaultLevel||o.DEBUG),o.setHandler(o.createDefaultHandler(e))},void 0===(u="function"==typeof(u=o)?u.call(l,c,l,h):u)||(h.exports=u)}()},948:e=>{function t(e){null==e&&(e=(new Date).getTime()),this.N=624,this.M=397,this.MATRIX_A=2567483615,this.UPPER_MASK=2147483648,this.LOWER_MASK=2147483647,this.mt=new Array(this.N),this.mti=this.N+1,e.constructor==Array?this.init_by_array(e,e.length):this.init_seed(e)}t.prototype.init_seed=function(e){for(this.mt[0]=e>>>0,this.mti=1;this.mti<this.N;this.mti++){e=this.mt[this.mti-1]^this.mt[this.mti-1]>>>30;this.mt[this.mti]=(1812433253*((4294901760&e)>>>16)<<16)+1812433253*(65535&e)+this.mti,this.mt[this.mti]>>>=0}},t.prototype.init_by_array=function(e,t){var i,s,r;for(this.init_seed(19650218),i=1,s=0,r=this.N>t?this.N:t;r;r--){var a=this.mt[i-1]^this.mt[i-1]>>>30;this.mt[i]=(this.mt[i]^(1664525*((4294901760&a)>>>16)<<16)+1664525*(65535&a))+e[s]+s,this.mt[i]>>>=0,s++,++i>=this.N&&(this.mt[0]=this.mt[this.N-1],i=1),t<=s&&(s=0)}for(r=this.N-1;r;r--){a=this.mt[i-1]^this.mt[i-1]>>>30;this.mt[i]=(this.mt[i]^(1566083941*((4294901760&a)>>>16)<<16)+1566083941*(65535&a))-i,this.mt[i]>>>=0,++i>=this.N&&(this.mt[0]=this.mt[this.N-1],i=1)}this.mt[0]=2147483648},t.prototype.random_int=function(){var e,t,i=new Array(0,this.MATRIX_A);if(this.mti>=this.N){for(this.mti==this.N+1&&this.init_seed(5489),t=0;t<this.N-this.M;t++)e=this.mt[t]&this.UPPER_MASK|this.mt[t+1]&this.LOWER_MASK,this.mt[t]=this.mt[t+this.M]^e>>>1^i[1&e];for(;t<this.N-1;t++)e=this.mt[t]&this.UPPER_MASK|this.mt[t+1]&this.LOWER_MASK,this.mt[t]=this.mt[t+(this.M-this.N)]^e>>>1^i[1&e];e=this.mt[this.N-1]&this.UPPER_MASK|this.mt[0]&this.LOWER_MASK,this.mt[this.N-1]=this.mt[this.M-1]^e>>>1^i[1&e],this.mti=0}return e=this.mt[this.mti++],e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,(e^=e>>>18)>>>0},t.prototype.random_int31=function(){return this.random_int()>>>1},t.prototype.random_incl=function(){return this.random_int()*(1/4294967295)},t.prototype.random=function(){return this.random_int()*(1/4294967296)},t.prototype.random_excl=function(){return(this.random_int()+.5)*(1/4294967296)},t.prototype.random_long=function(){return 1/9007199254740992*(67108864*(this.random_int()>>>5)+(this.random_int()>>>6))},e.exports=t},367:e=>{e.exports=function(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");for(var t=["on","fire","off"],i=0;i<t.length;++i)if(e.hasOwnProperty(t[i]))throw new Error("Subject cannot be eventified, since it already has property '"+t[i]+"'")}(e);var a,n,t=(a=e,n=Object.create(null),{on:function(e,t,i){if("function"!=typeof t)throw new Error("callback is expected to be a function");return(n[e]||(n[e]=[])).push({callback:t,ctx:i}),a},off:function(e,t){if(void 0===e)return n=Object.create(null),a;if(n[e])if("function"!=typeof t)delete n[e];else for(var i=n[e],s=0;s<i.length;++s)i[s].callback===t&&i.splice(s,1);return a},fire:function(e){var t,i=n[e];if(!i)return a;1<arguments.length&&(t=Array.prototype.splice.call(arguments,1));for(var s=0;s<i.length;++s){var r=i[s];r.callback.apply(r.ctx,t)}return a}});return e.on=t.on,e.off=t.off,e.fire=t.fire,e}},495:(e,t,i)=>{e.exports=function(e){"uniqueLinkId"in(e=e||{})&&(console.warn("ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\nUse `multigraph` option instead\n","\n","Note: there is also change in default behavior: From now on each graph\nis considered to be not a multigraph by default (each edge is unique)."),e.multigraph=e.uniqueLinkId);void 0===e.multigraph&&(e.multigraph=!1);if("function"!=typeof Map)throw new Error("ngraph.graph requires `Map` to be defined. Please polyfill it before using ngraph");var n=new Map,a=[],o={},t=0,h=e.multigraph?function(e,t,i){var s=x(e,t),r=o.hasOwnProperty(s);(r||b(e,t))&&(r||(o[s]=0),r="@"+ ++o[s],s=x(e+r,t+r));return new B(e,t,i,s)}:function(e,t,i){var s=x(e,t);return new B(e,t,i,s)},i=[],l=v,r=v,c=v,u=v,s={addNode:g,addLink:function(e,t,i){c();var s=m(e)||g(e),r=m(t)||g(t),i=h(e,t,i);a.push(i),A(s,i),e!==t&&A(r,i);return l(i,"add"),u(),i},removeLink:T,removeNode:f,getNode:m,getNodeCount:y,getLinkCount:w,getLinksCount:w,getNodesCount:y,getLinks:function(e){e=m(e);return e?e.links:null},forEachNode:O,forEachLinkedNode:function(e,t,i){var s=m(e);if(s&&s.links&&"function"==typeof t)return(i?function(e,t,i){for(var s=0;s<e.length;++s){var r=e[s];if(r.fromId===t&&i(n.get(r.toId),r))return!0}}:function(e,t,i){for(var s=0;s<e.length;++s){var r=e[s],a=r.fromId===t?r.toId:r.fromId;if(i(n.get(a),r))return!0}})(s.links,e,t)},forEachLink:function(e){var t,i;if("function"==typeof e)for(t=0,i=a.length;t<i;++t)e(a[t])},beginUpdate:c,endUpdate:u,clear:function(){c(),O(function(e){f(e.id)}),u()},hasLink:b,hasNode:m,getLink:b};return _(s),function(){var e=s.on;s.on=function(){return s.beginUpdate=c=S,s.endUpdate=u=k,l=d,r=p,(s.on=e).apply(s,arguments)}}(),s;function d(e,t){i.push({link:e,changeType:t})}function p(e,t){i.push({node:e,changeType:t})}function g(e,t){if(void 0===e)throw new Error("Invalid node identifier");c();var i=m(e);return i?(i.data=t,r(i,"update")):(i=new C(e,t),r(i,"add")),n.set(e,i),u(),i}function m(e){return n.get(e)}function f(e){var t=m(e);if(!t)return!1;c();var i=t.links;if(i){t.links=null;for(var s=0;s<i.length;++s)T(i[s])}return n.delete(e),r(t,"remove"),u(),!0}function y(){return n.size}function w(){return a.length}function T(e){if(!e)return!1;var t=I(e,a);if(t<0)return!1;c(),a.splice(t,1);var i=m(e.fromId),s=m(e.toId);return i&&0<=(t=I(e,i.links))&&i.links.splice(t,1),s&&0<=(t=I(e,s.links))&&s.links.splice(t,1),l(e,"remove"),u(),!0}function b(e,t){var i,s=m(e);if(!s||!s.links)return null;for(i=0;i<s.links.length;++i){var r=s.links[i];if(r.fromId===e&&r.toId===t)return r}return null}function v(){}function S(){t+=1}function k(){0===--t&&0<i.length&&(s.fire("changed",i),i.length=0)}function O(e){if("function"!=typeof e)throw new Error("Function is expected to iterate over graph nodes. You passed "+e);for(var t=n.values(),i=t.next();!i.done;){if(e(i.value))return!0;i=t.next()}}};var _=i(367);function I(e,t){if(!t)return-1;if(t.indexOf)return t.indexOf(e);for(var i=t.length,s=0;s<i;s+=1)if(t[s]===e)return s;return-1}function C(e,t){this.id=e,this.links=null,this.data=t}function A(e,t){e.links?e.links.push(t):e.links=[t]}function B(e,t,i,s){this.fromId=e,this.toId=t,this.data=i,this.id=s}function x(e,t){return e.toString()+"👉 "+t.toString()}},603:e=>{function s(e,t){if(!(this instanceof s))return new s(e,t);if(Array.isArray(e)||(t=e,e=[]),t=t||{},this.data=e||[],this.length=this.data.length,this.compare=t.compare||a,this.setNodeId=t.setNodeId||r,0<this.length)for(var i=this.length>>1;0<=i;i--)this._down(i);if(t.setNodeId)for(i=0;i<this.length;++i)this.setNodeId(this.data[i],i)}function r(){}function a(e,t){return e-t}(e.exports=s).prototype={push:function(e){this.data.push(e),this.setNodeId(e,this.length),this.length++,this._up(this.length-1)},pop:function(){if(0!==this.length){var e=this.data[0];return this.length--,0<this.length&&(this.data[0]=this.data[this.length],this.setNodeId(this.data[0],0),this._down(0)),this.data.pop(),e}},peek:function(){return this.data[0]},updateItem:function(e){this._down(e),this._up(e)},_up:function(e){for(var t=this.data,i=this.compare,s=this.setNodeId,r=t[e];0<e;){var a=e-1>>1,n=t[a];if(0<=i(r,n))break;s(t[e]=n,e),e=a}s(t[e]=r,e)},_down:function(e){for(var t=this.data,i=this.compare,s=this.length>>1,r=t[e],a=this.setNodeId;e<s;){var n=1+(e<<1),o=n+1,h=t[n];if(o<this.length&&i(t[o],h)<0&&(h=t[n=o]),0<=i(h,r))break;a(t[e]=h,e),e=n}a(t[e]=r,e)}}},142:(e,t,i)=>{e.exports=function(y,e){var w=(e=e||{}).oriented,T=e.bestEffort,b=e.heuristic;b=b||O.heuristic;var v=e.distance;v=v||O.distance;var S=s();return{find:function(e,t){var a=y.getNode(e);if(!a)throw new Error("fromId is not defined in this graph: "+e);var n=y.getNode(t);if(!n)throw new Error("toId is not defined in this graph: "+t);if(a===n)return[a];S.reset();var i=w?function(e,t){if(d===_){if(t.fromId===g.node.id)return f(e,t,g)}else if(d===I&&t.toId===g.node.id)return f(e,t,g)}:function(e,t){return f(e,t,g)},o=new Map,s=new k({compare:O.compareFScore,setNodeId:O.setHeapIndex}),r=new k({compare:O.compareFScore,setNodeId:O.setHeapIndex}),t=S.createNewState(a);o.set(e,t),t.fScore=b(a,n),t.distanceToSource=0,s.push(t),t.open=_;e=S.createNewState(n);e.fScore=b(n,a),e.distanceToSource=0,r.push(e),e.open=I;var h,l,c=Number.POSITIVE_INFINITY,u=s,d=_,p=t;for(;0<s.length&&(0<r.length||T);){var g=(u=s.length<r.length||!r.length&&T?(d=_,s):(d=I,r)).pop();if(g.closed=!0,!(g.distanceToSource>c)&&(y.forEachLinkedNode(g.node.id,i),h&&l))return m(h,l)}return T?m(p):C;function m(e,t){for(var i=[],s=e;s;)i.push(s.node),s=s.parent;for(var r=t;r;)i.unshift(r.node),r=r.parent;return i}function f(e,t,i){var s,r=o.get(e.id);r||(r=S.createNewState(e),o.set(e.id,r)),r.closed||((e=(e=r).open)&&e!==d?(s=r.distanceToSource+i.distanceToSource)<c&&(h=r,l=i,c=s):(e=i.distanceToSource+v(r.node,i.node,t))>=r.distanceToSource||(s=d===_?n:a,t=e+b(r.node,s,r),c<=t||(r.fScore=t,0===r.open&&(u.push(r),u.updateItem(r.heapIndex),r.open=d),r.parent=i,r.distanceToSource=e,s===n&&t-e<p.fScore-p.distanceToSource&&(p=r))))}}}};var k=i(603),s=i(573),r=i(884),O=i(8),_=1,I=2,C=O.NO_PATH;e.exports.l2=r.l2,e.exports.l1=r.l1},118:(e,t,i)=>{e.exports=function(c,e){var u=(e=e||{}).oriented,d=e.bestEffort,p=e.maxExpandedNodes||Number.POSITIVE_INFINITY,g=e.heuristic;g=g||w.heuristic;var m=e.distance;m=m||w.distance;var f=s();return{find:function(e,t){var i=c.getNode(e);if(!i)throw new Error("fromId is not defined in this graph: "+e);var s=c.getNode(t);if(!s)throw new Error("toId is not defined in this graph: "+t);f.reset();var r,a=new Map,n=new y({compare:w.compareFScore,setNodeId:w.setHeapIndex}),t=f.createNewState(i);a.set(e,t),t.fScore=g(i,s),t.distanceToSource=0,n.push(t),t.open=1;var o=t,h=0;for(;0<n.length;){if(function(e,t){return e.node===t}(r=n.pop(),s))return b(r);if(p<++h)break;r.closed=!0,c.forEachLinkedNode(r.node.id,l,u)}return d?b(o):T;function l(e,t){var i=a.get(e.id);i||(i=f.createNewState(e),a.set(e.id,i)),i.closed||(0===i.open&&(n.push(i),i.open=1),(t=r.distanceToSource+m(r.node,e,t))>=i.distanceToSource||(i.parent=r,i.distanceToSource=t,i.fScore=t+g(i.node,s,i),i.fScore-i.distanceToSource<o.fScore-o.distanceToSource&&(o=i),n.updateItem(i.heapIndex)))}}}};var y=i(603),s=i(573),r=i(884),w=i(8),T=w.NO_PATH;function b(e){for(var t=[e.node],i=e.parent;i;)t.push(i.node),i=i.parent;return t}e.exports.l2=r.l2,e.exports.l1=r.l1},8:e=>{var t=[];"function"==typeof Object.freeze&&Object.freeze(t),e.exports={heuristic:function(){return 0},distance:function(){return 1},compareFScore:function(e,t){return e.fScore-t.fScore},NO_PATH:t,setHeapIndex:function(e,t){e.heapIndex=t},setH1:function(e,t){e.h1=t},setH2:function(e,t){e.h2=t},compareF1Score:function(e,t){return e.f1-t.f1},compareF2Score:function(e,t){return e.f2-t.f2}}},884:e=>{e.exports={l2:function(e,t){var i=e.x-t.x,t=e.y-t.y;return Math.sqrt(i*i+t*t)},l1:function(e,t){var i=e.x-t.x,t=e.y-t.y;return Math.abs(i)+Math.abs(t)}}},573:e=>{function r(e){this.node=e,this.parent=null,this.closed=!1,this.open=0,this.distanceToSource=Number.POSITIVE_INFINITY,this.fScore=Number.POSITIVE_INFINITY,this.heapIndex=-1}e.exports=function(){var i=0,s=[];return{createNewState:function(e){var t=s[i];t?(t.node=e,t.parent=null,t.closed=!1,t.open=0,t.distanceToSource=Number.POSITIVE_INFINITY,t.fScore=Number.POSITIVE_INFINITY,t.heapIndex=-1):(t=new r(e),s[i]=t);return i++,t},reset:function(){i=0}}}},377:(e,t,i)=>{e.exports=function(y,e){var w=(e=e||{}).oriented,T=e.quitFast,b=e.heuristic;b=b||O.heuristic;var v=e.distance;v=v||O.distance;var S=r();return{find:function(e,t){var s=y.getNode(e);if(!s)throw new Error("fromId is not defined in this graph: "+e);var r=y.getNode(t);if(!r)throw new Error("toId is not defined in this graph: "+t);S.reset();var a,i=w?function(e,t){if(t.fromId===p.node.id)return m(e,t)}:m,n=w?function(e,t){if(t.toId===p.node.id)return f(e,t)}:f,o=new Map,h=new k({compare:O.compareF1Score,setNodeId:O.setH1}),l=new k({compare:O.compareF2Score,setNodeId:O.setH2}),c=Number.POSITIVE_INFINITY,u=S.createNewState(s);o.set(e,u),u.g1=0;var d=b(s,r);u.f1=d,h.push(u);u=S.createNewState(r);o.set(t,u),u.g2=0;var p,g=d;u.f2=g,l.push(u);for(;l.length&&h.length&&(h.length<l.length?(p=h.pop()).closed||(p.closed=!0,p.f1<c&&p.g1+g-b(s,p.node)<c&&y.forEachLinkedNode(p.node.id,i),0<h.length&&(d=h.peek().f1)):(p=l.pop()).closed||(p.closed=!0,p.f2<c&&p.g2+d-b(p.node,r)<c&&y.forEachLinkedNode(p.node.id,n),0<l.length&&(g=l.peek().f2)),!T||!a););return function(e){if(!e)return _;var t=[e.node],i=e.p1;for(;i;)t.push(i.node),i=i.p1;var s=e.p2;for(;s;)t.unshift(s.node),s=s.p2;return t}(a);function m(e,t){var i=o.get(e.id);i||(i=S.createNewState(e),o.set(e.id,i)),i.closed||((t=p.g1+v(p.node,e,t))<i.g1&&(i.g1=t,i.f1=t+b(i.node,r),i.p1=p,i.h1<0?h.push(i):h.updateItem(i.h1)),(t=i.g1+i.g2)<c&&(c=t,a=i))}function f(e,t){var i=o.get(e.id);i||(i=S.createNewState(e),o.set(e.id,i)),i.closed||((t=p.g2+v(p.node,e,t))<i.g2&&(i.g2=t,i.f2=t+b(s,i.node),i.p2=p,i.h2<0?l.push(i):l.updateItem(i.h2)),(t=i.g1+i.g2)<c&&(c=t,a=i))}}}};var k=i(603),s=i(884),O=i(8),r=i(808),_=O.NO_PATH;e.exports.l2=s.l2,e.exports.l1=s.l1},808:e=>{function r(e){this.node=e,this.p1=null,this.p2=null,this.closed=!1,this.g1=Number.POSITIVE_INFINITY,this.g2=Number.POSITIVE_INFINITY,this.f1=Number.POSITIVE_INFINITY,this.f2=Number.POSITIVE_INFINITY,this.h1=-1,this.h2=-1}e.exports=function(){var i=0,s=[];return{createNewState:function(e){var t=s[i];t?(t.node=e,t.p1=null,t.p2=null,t.closed=!1,t.g1=Number.POSITIVE_INFINITY,t.g2=Number.POSITIVE_INFINITY,t.f1=Number.POSITIVE_INFINITY,t.f2=Number.POSITIVE_INFINITY,t.h1=-1,t.h2=-1):(t=new r(e),s[i]=t);return i++,t},reset:function(){i=0}}}},45:(e,t,i)=>{e.exports={aStar:i(118),aGreedy:i(142),nba:i(377)}},91:e=>{e.exports=__WEBPACK_EXTERNAL_MODULE_fetch_blob_71f8024a__},949:e=>{e.exports=__WEBPACK_EXTERNAL_MODULE_three__}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;t=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e].call(t.exports,t,t.exports,__webpack_require__),t.exports}__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},__webpack_require__.d=(e,t)=>{for(var i in t)__webpack_require__.o(t,i)&&!__webpack_require__.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};(()=>{__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{ApiEventType:()=>qp,ArmorType:()=>ai,AttackState:()=>wn,Bot:()=>Up,Box2:()=>jn,BuildCat:()=>Ji,BuildStatus:()=>Cn,Cylindrical:()=>Gm,Euler:()=>zm,FactoryStatus:()=>kn,FactoryType:()=>es,GameInstanceApi:()=>Sm,GameMath:()=>Yi,InfDeathType:()=>ti,LandTargeting:()=>ni,LandType:()=>Jt,LocomotorType:()=>si,Matrix4:()=>Zs,MovementZone:()=>ri,NavalTargeting:()=>oi,ObjectType:()=>xt,OrderType:()=>Bn,PipColor:()=>ii,PrereqCategory:()=>Yt,PublicApi:()=>Bm,Quaternion:()=>Ki,QueueStatus:()=>yn,QueueType:()=>fn,RadarEventType:()=>Qt,SideType:()=>Zt,SpeedType:()=>ei,Spherical:()=>Hm,StanceType:()=>Ls,SuperWeaponStatus:()=>Ns,SuperWeaponType:()=>is,TagRepeatType:()=>$t,TerrainType:()=>Kt,TheaterType:()=>C,Vector2:()=>ks,Vector3:()=>rs,VeteranAbility:()=>li,VeteranLevel:()=>ea,VhpScan:()=>ci,WeaponType:()=>hi,ZoneType:()=>vs,cdapi:()=>$m});__WEBPACK_EXTERNAL_MODULE_websocket_polyfill_8396782d__;const b=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"),a=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");const e=__WEBPACK_EXTERNAL_MODULE_es_dirname_044d89a0__;const n=__WEBPACK_EXTERNAL_MODULE_file_system_access_58c08c7f__;const o=__WEBPACK_EXTERNAL_MODULE_file_system_access_lib_adapters_node_js_b1c03fd5__;class h{constructor(e){this.entries=new Map,this.name=e}clone(){let i=new h(this.name);return this.entries.forEach((e,t)=>{i.set(t,e)}),i}set(e,t){this.entries.set(e,t)}get(e){return this.entries.get(e)}has(e){return this.entries.has(e)}getString(e,t=""){e=this.get(e);return e||t}getNumber(e,t=0){var i=this.get(e);if(!i)return t;var s=this.parseNumber(i);return void 0===s?(console.warn(`Invalid value for key ${e}. "${i}" is not a valid number or percentage string.`),t):s}parseNumber(e){let t;if(t=e.match(/%$/)?Number(e.replace("%",""))/100:Number(e),!isNaN(t))return t}getFixed(e,t=0){return this.toFixedPointPrecision(this.getNumber(e,t))}toFixedPointPrecision(e){return(65536*e|0)/65536}getBool(e,t=!1){let i=this.getString(e).trim();return i=i&&i.toLowerCase(),!(!i||-1===["yes","1","true","on"].indexOf(i))||(!i||-1===["no","0","false","off"].indexOf(i))&&t}getArray(e,t=/\,\s*/,i=[]){let s=this.getString(e).trim();return s=s.replace(/\,$/,"").replace(/\,+/g,","),s?s.split(t):i}getNumberArray(e,t=/\,\s*/,i=[]){let s=this.getString(e).trim();if(!s)return i;let r=[];for(var a of s.split(t)){if(!a)return i;var n=this.parseNumber(a);if(void 0===n)return console.warn(`Invalid value for key ${e}. "${a}" is not a valid number or percentage string.`),i;r.push(n)}return r}getFixedArray(e,t=/\,\s*/,i=[]){return this.getNumberArray(e,t,i).map(e=>this.toFixedPointPrecision(e))}getEnum(e,t,i,s=!1){let r=this.getString(e).trim();if(!r)return i;let a;if(s){let e=Object.getOwnPropertyNames(t);s=e.find(e=>e.toLowerCase()===r.toLowerCase());s&&(a=t[s])}else t.hasOwnProperty(r)&&(a=t[r]);return void 0===a?(console.warn(`Invalid value for key "${e}". "${r}" is not an accepted enum value.`),i):a}getEnumNumeric(e,t,i){var s=this.getString(e).trim();if(!s)return i;let r;return Number.isInteger(parseInt(s,10))&&t.hasOwnProperty(s)&&(r=parseInt(s,10)),void 0===r?(console.warn(`Invalid value for key "${e}". "${s}" is not an accepted enum value.`),i):r}getEnumArray(e,s,t=/\,\s*/,r=[],a=!1){let n=this.getString(e).trim();if(!n)return r;let o=[];for(let i of n.split(t)){if(!i)return r;let t=!1;if(a){let e=Object.getOwnPropertyNames(s);var h=e.find(e=>e.toLowerCase()===i.toLowerCase());h&&(o.push(s[h]),t=!0)}else s.hasOwnProperty(i)&&(o.push(s[i]),t=!0);if(!t)return console.warn(`Invalid value "${i}" for key "${e}".`),r}return o}getHighestNumericIndex(){let i=0,s;return this.entries.forEach((e,t)=>{s=parseInt(t,10),s>i&&(i=s)}),i}getConcatenatedValues(){let e="";for(var t of this.entries.values())e+=t;return e}toString(){let e=[];e.push(`[${this.name}]`);for(var[t,i]of this.entries)e.push(`${t}=${i}`);return e.push(""),e.join("\r\n")}}class t{parse(e){let o={},s=o,r,a=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,t=e.split(/[\r\n]+/g);return t.forEach((t,e,i)=>{if(t&&!t.match(/^\s*[;#]/)){t=(t=t.replace(/]\s*(\/\/|;|#).*$/,"]")).match(a);if(t){if(void 0!==t[1])return r=this.unsafe(t[1]),void(s=o[r]=o[r]||{});let e=this.unsafe(t[2]);t=t[3]?this.unsafe(t[4]||""):"";2<e.length&&"[]"===e.slice(-2)&&(e=e.substring(0,e.length-2),s[e]?Array.isArray(s[e])||(s[e]=[s[e]]):s[e]=[]),Array.isArray(s[e])?s[e].push(t):s[e]=t}}}),Object.keys(o).filter((e,t,i)=>{if(!o[e]||"object"!=typeof o[e]||Array.isArray(o[e]))return!1;let s=this.dotSplit(e),r=o,a=s.pop();var n=a.replace(/\\\./g,".");return s.forEach(function(e,t,i){r[e]&&"object"==typeof r[e]||(r[e]={}),r=r[e]}),(r!==o||n!==a)&&(r[n]=o[e],!0)}).forEach(function(e,t,i){delete o[e]}),o}dotSplit(e){return e.replace(/\1/g,"LITERAL\\1LITERAL").replace(/\\\./g,"").split(/\./).map(e=>e.replace(/\1/g,"\\.").replace(/\2LITERAL\\1LITERAL\2/g,""))}isQuoted(e){return'"'===e.charAt(0)&&'"'===e.slice(-1)||"'"===e.charAt(0)&&"'"===e.slice(-1)}unsafe(r){if(r=(r||"").trim(),this.isQuoted(r))return r=r.substr(1,r.length-2);{let i=!1,s="";for(let e=0,t=r.length;e<t;e++){var a=r.charAt(e);if(i)-1!=="\\;#".indexOf(a)?s+=a:s+="\\"+a,i=!1;else{if(-1!==";#".indexOf(a))break;"\\"===a?i=!0:s+=a}}return i&&(s+="\\"),s=s.trim(),s}}}class v{constructor(e,t,i=v.LITTLE_ENDIAN){this.endianness=i,this.position=0,this._dynamicSize=!0,this._byteLength=0,this._byteOffset=t||0,e instanceof ArrayBuffer?this.buffer=e:"object"==typeof e?(this.dataView=e,t&&(this._byteOffset+=t)):this.buffer=new ArrayBuffer(e||0)}get dynamicSize(){return this._dynamicSize}set dynamicSize(e){e||this._trimAlloc(),this._dynamicSize=e}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){return this._trimAlloc(),this._buffer}set buffer(e){this._buffer=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get byteOffset(){return this._byteOffset}set byteOffset(e){this._byteOffset=e,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get dataView(){return this._dataView}set dataView(e){this._byteOffset=e.byteOffset,this._buffer=e.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+e.byteLength}bigEndian(){return this.endianness=v.BIG_ENDIAN,this}_realloc(t){if(this._dynamicSize){var i=this._byteOffset+this.position+t;let e=this._buffer.byteLength;if(i<=e)i>this._byteLength&&(this._byteLength=i);else{for(e<1&&(e=1);i>e;)e*=2;var s=new ArrayBuffer(e),t=new Uint8Array(this._buffer);const r=new Uint8Array(s,0,t.length);r.set(t),this.buffer=s,this._byteLength=i}}}_trimAlloc(){if(this._byteLength!==this._buffer.byteLength){var e=new ArrayBuffer(this._byteLength);const i=new Uint8Array(e);var t=new Uint8Array(this._buffer,0,i.length);i.set(t),this.buffer=e}}seek(e){e=Math.max(0,Math.min(this.byteLength,e));this.position=isNaN(e)||!isFinite(e)?0:e}isEof(){return this.position>=this.byteLength}mapInt32Array(e,t){this._realloc(4*e);var i=new Int32Array(this._buffer,this.byteOffset+this.position,e);return v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=4*e,i}mapInt16Array(e,t){this._realloc(2*e);var i=new Int16Array(this._buffer,this.byteOffset+this.position,e);return v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=2*e,i}mapInt8Array(e){this._realloc(e);var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e,t}mapUint32Array(e,t){this._realloc(4*e);var i=new Uint32Array(this._buffer,this.byteOffset+this.position,e);return v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=4*e,i}mapUint16Array(e,t){this._realloc(2*e);var i=new Uint16Array(this._buffer,this.byteOffset+this.position,e);return v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=2*e,i}mapUint8Array(e){this._realloc(e);var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e,t}mapFloat64Array(e,t){this._realloc(8*e);var i=new Float64Array(this._buffer,this.byteOffset+this.position,e);return v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=8*e,i}mapFloat32Array(e,t){this._realloc(4*e);var i=new Float32Array(this._buffer,this.byteOffset+this.position,e);return v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=4*e,i}readInt32Array(e,t){e=void 0===e?this.byteLength-this.position/4:e;var i=new Int32Array(e);return v.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}readInt16Array(e,t){e=void 0===e?this.byteLength-this.position/2:e;var i=new Int16Array(e);return v.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}readInt8Array(e){e=void 0===e?this.byteLength-this.position:e;var t=new Int8Array(e);return v.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t}readUint32Array(e,t){e=void 0===e?this.byteLength-this.position/4:e;var i=new Uint32Array(e);return v.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}readUint16Array(e,t){e=void 0===e?this.byteLength-this.position/2:e;var i=new Uint16Array(e);return v.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}readUint8Array(e){e=void 0===e?this.byteLength-this.position:e;var t=new Uint8Array(e);return v.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,e*t.BYTES_PER_ELEMENT),this.position+=t.byteLength,t}readFloat64Array(e,t){e=void 0===e?this.byteLength-this.position/8:e;var i=new Float64Array(e);return v.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}readFloat32Array(e,t){e=void 0===e?this.byteLength-this.position/4:e;var i=new Float32Array(e);return v.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),v.arrayToNative(i,void 0===t?this.endianness:t),this.position+=i.byteLength,i}writeInt32Array(t,i){if(this._realloc(4*t.length),t instanceof Int32Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)v.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapInt32Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeInt32(t[e],i);return this}writeInt16Array(t,i){if(this._realloc(2*t.length),t instanceof Int16Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)v.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapInt16Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeInt16(t[e],i);return this}writeInt8Array(t){if(this._realloc(t.length),t instanceof Int8Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)v.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapInt8Array(t.length);else for(let e=0;e<t.length;e++)this.writeInt8(t[e]);return this}writeUint32Array(t,i){if(this._realloc(4*t.length),t instanceof Uint32Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)v.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapUint32Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeUint32(t[e],i);return this}writeUint16Array(t,i){if(this._realloc(2*t.length),t instanceof Uint16Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)v.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapUint16Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeUint16(t[e],i);return this}writeUint8Array(t){if(this._realloc(t.length),t instanceof Uint8Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)v.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapUint8Array(t.length);else for(let e=0;e<t.length;e++)this.writeUint8(t[e]);return this}writeFloat64Array(t,i){if(this._realloc(8*t.length),t instanceof Float64Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)v.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapFloat64Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeFloat64(t[e],i);return this}writeFloat32Array(t,i){if(this._realloc(4*t.length),t instanceof Float32Array&&(this.byteOffset+this.position)%t.BYTES_PER_ELEMENT==0)v.memcpy(this._buffer,this.byteOffset+this.position,t.buffer,t.byteOffset,t.byteLength),this.mapFloat32Array(t.length,i);else for(let e=0;e<t.length;e++)this.writeFloat32(t[e],i);return this}readInt32(e){e=this._dataView.getInt32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readInt16(e){e=this._dataView.getInt16(this.position,void 0===e?this.endianness:e);return this.position+=2,e}readInt8(){var e=this._dataView.getInt8(this.position);return this.position+=1,e}readUint32(e){e=this._dataView.getUint32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readUint16(e){e=this._dataView.getUint16(this.position,void 0===e?this.endianness:e);return this.position+=2,e}readUint8(){var e=this._dataView.getUint8(this.position);return this.position+=1,e}readFloat32(e){e=this._dataView.getFloat32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readFloat64(e){e=this._dataView.getFloat64(this.position,void 0===e?this.endianness:e);return this.position+=8,e}writeInt32(e,t){return this._realloc(4),this._dataView.setInt32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeInt16(e,t){return this._realloc(2),this._dataView.setInt16(this.position,e,void 0===t?this.endianness:t),this.position+=2,this}writeInt8(e){return this._realloc(1),this._dataView.setInt8(this.position,e),this.position+=1,this}writeUint32(e,t){return this._realloc(4),this._dataView.setUint32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeUint16(e,t){return this._realloc(2),this._dataView.setUint16(this.position,e,void 0===t?this.endianness:t),this.position+=2,this}writeUint8(e){return this._realloc(1),this._dataView.setUint8(this.position,e),this.position+=1,this}writeFloat32(e,t){return this._realloc(4),this._dataView.setFloat32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeFloat64(e,t){return this._realloc(8),this._dataView.setFloat64(this.position,e,void 0===t?this.endianness:t),this.position+=8,this}static memcpy(e,t,i,s,r){const a=new Uint8Array(e,t,r);r=new Uint8Array(i,s,r);a.set(r)}static arrayToNative(e,t){return t===this.endianness?e:this.flipArrayEndianness(e)}static nativeToEndian(e,t){return this.endianness===t?e:this.flipArrayEndianness(e)}static flipArrayEndianness(s){const r=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);for(let i=0;i<s.byteLength;i+=s.BYTES_PER_ELEMENT)for(let e=i+s.BYTES_PER_ELEMENT-1,t=i;e>t;e--,t++){var a=r[t];r[t]=r[e],r[e]=a}return s}static createStringFromArray(t){const i=[];for(let e=0;e<t.length;e+=32768)i.push(String.fromCharCode.apply(void 0,t.subarray(e,e+32768)));return i.join("")}readUCS2String(e,t){return v.createStringFromArray(this.readUint16Array(e,t))}writeUCS2String(e,t,i){void 0===i&&(i=e.length);let s=0;for(;s<e.length&&s<i;s++)this.writeUint16(e.charCodeAt(s),t);for(;s<i;s++)this.writeUint16(0);return this}readString(e,t){return void 0===t||"ASCII"===t?v.createStringFromArray(this.mapUint8Array(void 0===e?this.byteLength-this.position:e)):new TextDecoder(t).decode(this.mapUint8Array(e))}writeString(t,e,i){if(void 0===e||"ASCII"===e)if(void 0!==i){let e;var s=Math.min(t.length,i);for(e=0;e<s;e++)this.writeUint8(t.charCodeAt(e));for(;e<i;e++)this.writeUint8(0)}else for(let e=0;e<t.length;e++)this.writeUint8(t.charCodeAt(e));else this.writeUint8Array((new TextEncoder).encode(t.substring(0,i)));return this}writeUtf8WithLen(e){e=(new TextEncoder).encode(e);return this.writeUint16(e.length).writeUint8Array(e)}readUtf8WithLen(){var e=this.readUint16();return(new TextDecoder).decode(this.mapUint8Array(e))}readCString(e){var t=this.byteLength-this.position,i=new Uint8Array(this._buffer,this._byteOffset+this.position);let s=t;void 0!==e&&(s=Math.min(e,t));let r=0;for(;r<s&&0!==i[r];r++);var a=v.createStringFromArray(this.mapUint8Array(r));return void 0!==e?this.position+=s-r:r!==t&&(this.position+=1),a}writeCString(t,i){if(void 0!==i){let e;var s=Math.min(t.length,i);for(e=0;e<s;e++)this.writeUint8(t.charCodeAt(e));for(;e<i;e++)this.writeUint8(0)}else{for(let e=0;e<t.length;e++)this.writeUint8(t.charCodeAt(e));this.writeUint8(0)}return this}toUint8Array(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}}v.BIG_ENDIAN=!1,v.LITTLE_ENDIAN=!0,v.endianness=0<new Int8Array(new Int16Array([1]).buffer)[0];class l extends Error{constructor(){super(...arguments),this.name="IOError"}}class i{constructor(e,t){this.stream=e,this.filename=t}static async fromRealFile(t){try{const e=new v(await t.arrayBuffer());return e._trimAlloc=()=>{},new this(e,t.name)}catch(e){if(e instanceof DOMException)throw new l(`File "${t.name}" could not be read (${e.name})`,{cause:e});throw e}}static fromBytes(e,t){let i=new v(e);return i._trimAlloc=()=>{},new this(i,t)}static factory(e,t,i=0,s=e.byteLength){s=new DataView(e.buffer,e.byteOffset+i,s);const r=new v(s);return r._trimAlloc=()=>{},new this(r,t)}readAsString(e){return this.stream.seek(0),this.stream.readString(this.stream.byteLength,e)}getBytes(){return new Uint8Array(this.stream.buffer,this.stream.byteOffset,this.stream.byteLength)}getSize(){return this.stream.byteLength}asFile(e){return new File([this.getBytes()],this.filename,{type:e})}}class c{constructor(e){this.sections=new Map,e instanceof i?this.fromVirtualFile(e):"object"==typeof e?this.fromJson(e):"string"==typeof e&&this.fromString(e)}fromVirtualFile(e){return this.fromString(e.readAsString())}fromString(e){return this.fromJson((new t).parse(e)),this}fromJson(e){let t,i,s,r;var a;for(t in e)if(e.hasOwnProperty(t)){for(r in i=e[t],s=new h(t),i)i.hasOwnProperty(r)&&(a=i[r],s.set(r,a));this.sections.set(t,s)}}toString(){let e=[];for(var t of this.sections.values())e.push(t.toString());return e.join("\r\n")}clone(){let i=new c;return this.sections.forEach((e,t)=>{i.sections.set(t,e.clone())}),i}getOrCreateSection(e){let t=this.sections.get(e);return t||(t=new h(e),this.sections.set(e,t)),t}getSection(e){return this.sections.get(e)}getOrderedSections(){return[...this.sections.values()]}isValueArray(e){return-1!==["BuildingTypes","AircraftTypes","InfantryTypes","OverlayTypes","TerrainTypes","SmudgeTypes","VehicleTypes","Animations","VoxelAnims","SuperWeaponTypes","Countries","Warheads","Tiberiums"].indexOf(e)}mergeWith(e){return e.sections.forEach((e,t)=>{let s=this.getOrCreateSection(t);if(this.isValueArray(t)){let i=s.getHighestNumericIndex()+1;e.entries.forEach((e,t)=>{s.set((i++).toString(),e)})}else e.entries.forEach((e,t)=>{s.set(t,e)})}),this}}class d{constructor(e){this.height=1,this.width=1,this.x=0,this.y=0,this.imageData=e??new Uint8Array(0)}clip(i,e){let t=new d;t.width=Math.min(this.width,i),t.height=Math.min(this.height,e);let s=new Uint8Array(i*e),r=0;for(let t=0;t<this.height&&!(t>=e);t++)for(let e=0;e<this.width;e++)e>=i||(s[r++]=this.imageData[t*this.width+e]);return t.imageData=s,t.x=this.x,t.y=this.y,t}}class s{constructor(e){this.height=0,this.width=0,this.numImages=0,this.images=[],e instanceof i&&this.fromVirtualFile(e)}fromVirtualFile(e){this.filename=e.filename;let r=e.stream;if(0===r.readInt16()){this.width=r.readInt16(),this.height=r.readInt16(),this.numImages=r.readInt16();let s=[];for(let e=0;e<this.numImages;++e)s.push(this.readFrameHeader(r));this.images=[];for(let i=0;i<this.numImages;++i){var{compressionType:a,imageDataStartOffset:n,x:o,y:h,width:l,height:c}=s[i];let e=i<this.numImages-1?s[i+1].imageDataStartOffset:r.byteLength;e<n&&(e=r.byteLength);var u=e-n;r.seek(n);u=this.readImageData(r,l,c,a,u);let t=new d(u);t.x=o,t.y=h,t.width=l,t.height=c,this.images.push(t)}}}readFrameHeader(e){var t=e.readInt16(),i=e.readInt16(),s=e.readInt16(),r=e.readInt16(),a=e.readUint8();return e.readUint8(),e.readUint8(),e.readUint8(),e.readInt32(),e.readInt32(),{x:t,y:i,width:s,height:r,compressionType:a,imageDataStartOffset:e.readInt32()}}readImageData(s,e,r,t,i){var a=e*r;if(t<=1){var n=new Uint8Array(s.buffer,s.byteOffset+s.position,a);return s.position+=a,n}if(2===t){let t=0,i=new Uint8Array(a);for(let e=0;e<r;++e){var o=s.readUint16()-2;i.set(new Uint8Array(s.buffer,s.byteOffset+s.position,o),t),s.position+=o,t+=o}return i}if(3!==t)return new Uint8Array;t=new Uint8Array(s.buffer,s.byteOffset+s.position,i);return s.position+=i,class{static decode(s,r,t){let a=new Uint8Array(r*t),n=0,o=0;for(let e=0;e<t;e++){let t=(s[n+1]<<8|s[n])-2;n+=2;let i=0;for(;0<t--;){let e=s[n++];if(0!==e)i++,a[o++]=e;else for(t--,e=s[n++],i+e>r&&(e=r-i&255),i+=e;0!=e--;)a[o++]=0}}return a}}.decode(t,e,r)}getImage(e){if(e<0||this.images.length<=e)throw new RangeError(`Image index out of bounds (file=${this.filename}, index=${e}, length=${this.images.length})`);return this.images[e]}addImage(e){this.images.push(e),this.numImages++}clip(e,t){let i=new s;return i.filename=this.filename,i.width=Math.min(this.width,e),i.height=Math.min(this.height,t),i.images=this.images.map(e=>e.clip(i.width,i.height)),i.numImages=this.numImages,i}}var r=__webpack_require__(949).Vector3;const u=[new r(.54946297,-183e-6,-.835518),new r(.00014400001,.54940403,-.83555698),new r(-.54940403,-68000001e-12,-.83555698),new r(106e-6,-.54946297,-.835518),new r(.94900799,.00031599999,-.31525001),new r(-186e-6,.94899702,-.31528401),new r(-.94899702,.00031800001,-.31528401),new r(-447e-6,-.94900799,-.31525001),new r(.95084399,-279e-6,.30967101),new r(202e-6,.95084798,.30965701),new r(-.95084798,-70000002e-12,.30965701),new r(147e-6,-.95084399,.30967101),new r(.55237001,-11e-6,.83359897),new r(19999999e-12,.55238003,.833592),new r(-.55238003,57000001e-12,.83359301),new r(-66000001e-12,-.55237001,.83359897)],p=[new r(.67121398,.19849201,-.714194),new r(.26964301,.58439398,-.76536),new r(-.040546,.096988,-.99445897),new r(-.57242799,-.091913998,-.81478697),new r(-.17140099,-.57270998,-.80163902),new r(.36255699,-.30299899,-.88133103),new r(.81034702,-.34897199,-.470698),new r(.103962,.93867201,-.328767),new r(-.324047,.58766901,-.74137598),new r(-.80086499,.34046099,-.49264699),new r(-.66549802,-.59014702,-.45698899),new r(.314767,-.803002,-.506073),new r(.97262901,.151076,-.17655),new r(.680291,.68423599,-.26272699),new r(-.52007902,.82777703,-.210483),new r(-.96164399,-.179001,-.207847),new r(-.262714,-.937451,-.22840101),new r(.219707,-.97130102,.091124997),new r(.92380798,-.229975,.30608699),new r(-.082488999,.97065997,.225866),new r(-.59179801,.69678998,.40528899),new r(-.92529601,.36660099,.097111002),new r(-.705051,-.68777502,.172828),new r(.7324,-.68036699,-.026304999),new r(.85516202,.37458199,.358311),new r(.47300601,.83648002,.276705),new r(-.097617,.65411198,.750072),new r(-.90412402,-.153725,.39865801),new r(-.211916,-.85808998,.46773201),new r(.50022697,-.67440802,.543091),new r(.584539,-.110249,.80384099),new r(.43737301,.45464399,.77588898),new r(-.042440999,.083318003,.995619),new r(-.59625101,.22013199,.77202803),new r(-.506455,-.39697701,.76544899),new r(.070569001,-.47847399,.87526202)],g=[new r(.45651099,-.073968001,-.88663799),new r(.50769401,.38511699,-.77067),new r(.095431998,.22666401,-.96928602),new r(-.35876599,.54318798,-.75910097),new r(-.361276,.13299499,-.92292601),new r(-.48311701,-.32406601,-.813375),new r(-.018073,-.197559,-.980124),new r(.3211,-.501477,-.80337799),new r(.79949099,.069615997,-.59662998),new r(.390971,.77130598,-.50222403),new r(.080782004,.61448997,-.784778),new r(-.73275,.41143101,-.54203498),new r(-.73525399,.0091019999,-.67773098),new r(-.80249399,-.39490801,-.44727099),new r(-.13413,-.58915502,-.79680902),new r(.71955299,-.37622699,-.58369303),new r(.96687502,.173593,-.187132),new r(.760831,.51910597,-.38944301),new r(-.114642,.87551898,-.46938601),new r(-.53236699,.76885903,-.354177),new r(-.96226698,.024977,-.27095801),new r(-.46738699,-.721986,-.51018202),new r(.058449998,-.85235399,-.51968902),new r(.49823299,-.74374002,-.44566301),new r(.93915099,-.27024499,-.212044),new r(.58393198,.80944198,-.061857),new r(.183797,.97322798,-.138007),new r(-.88435501,.45221901,-.115822),new r(-.943178,-.33206701,.012138),new r(-.69844002,-.70656699,-.113772),new r(-.228411,-.95470601,-.190694),new r(.73156399,-.675861,-.089588001),new r(.96925098,.046804,.24158201),new r(.85564703,.50347698,.119916),new r(-.25115299,.96794701,-80999998e-12),new r(-.64779502,.75674897,.087711997),new r(-.96916401,.14519399,.1991),new r(-.41479301,-.88896698,.194126),new r(.25077501,-.961178,-.115109),new r(.47862899,-.84259301,.246883),new r(.89004397,-.39614201,.225595),new r(.52405101,.76235998,.37970701),new r(.11962,.94548202,.30291),new r(-.76085001,.49007499,.42536199),new r(-.86978501,-.20215,.450122),new r(-.70946699,-.60242403,.36570701),new r(.019308999,-.95887101,.28318599),new r(.626113,-.564677,.53770101),new r(.769943,-.126663,.62541503),new r(.76419097,.35070199,.54131401),new r(-.001878,.74136698,.67109799),new r(-.37088001,.81836802,.43900099),new r(-.71390897,.12865201,.68831801),new r(-.295165,-.73866397,.60601401),new r(.186195,-.73836899,.648184),new r(.387523,-.35878301,.84917599),new r(.481022,.124846,.86777401),new r(.391808,.54505599,.741216),new r(-.0035359999,.36559799,.93076599),new r(-.42049801,.484961,.76680797),new r(-.35490301,.019470001,.93470001),new r(-.54783702,-.35920799,.75554299),new r(-.106662,-.445115,.88909799),new r(.086796001,-.059307002,.99445897)],m=[new r(.52657801,-.35962099,-.77031702),new r(.150482,.43598399,.88728398),new r(.414195,.73825502,-.53237402),new r(.075152002,.91624898,-.393498),new r(-.316149,.93073601,-.18379299),new r(-.77381903,.62333399,-.11251),new r(-.90084201,.42853701,-.069568001),new r(-.99894202,-.010971,.044665001),new r(-.979761,-.15767001,-.123324),new r(-.91127402,-.362371,-.19562),new r(-.62406898,-.72094101,-.301301),new r(-.310173,-.80934501,-.498752),new r(.146613,-.81581903,-.55941403),new r(-.71651602,-.69435602,-.066887997),new r(.50397199,-.114202,-.85613698),new r(.45549101,.87262702,-.176211),new r(-.00501,-.114373,-.99342501),new r(-.104675,-.327701,-.93896502),new r(.56041199,.75258899,-.34575599),new r(-.060575999,.82162797,-.566796),new r(-.30234101,.79700702,-.522847),new r(-.671543,.67074001,-.314863),new r(-.77840102,-.12835699,.61450499),new r(-.92404997,.278382,-.261985),new r(-.69977301,-.55049098,-.45527801),new r(-.56824797,-.51718903,-.64000797),new r(.054097999,-.93286401,-.356143),new r(.75838202,.57289302,-.31088799),new r(.0036200001,.30502599,-.95233703),new r(-.060849998,-.98688602,-.14951099),new r(.63523,.045478001,-.77098298),new r(.52170497,.241309,-.81828701),new r(.26940399,.63542497,-.72364098),new r(.045676,.67275399,-.738455),new r(-.180511,.67465699,-.71571898),new r(-.397131,.63664001,-.66104198),new r(-.55200398,.47251499,-.687038),new r(-.77217001,.08309,-.62996),new r(-.669819,-.119533,-.73284),new r(-.54045498,-.31844401,-.77878201),new r(-.38613501,-.522789,-.75999397),new r(-.261466,-.68856698,-.676395),new r(-.019412,-.69610298,-.71767998),new r(.30356899,-.48184401,-.82199299),new r(.68193901,-.19512901,-.70490003),new r(-.24488901,-.116562,-.96251899),new r(.80075902,-.022979001,-.59854603),new r(-.37027499,.095583998,-.92399102),new r(-.33067101,-.32657799,-.88543999),new r(-.16322,-.52757901,-.83367902),new r(.12639,-.313146,-.941257),new r(.34954801,-.27222601,-.89649802),new r(.23991799,-.085825004,-.96699202),new r(.390845,.081537001,-.91683799),new r(.25526699,.26869699,-.92878503),new r(.146245,.48043799,-.86474901),new r(-.32601601,.47845599,-.81534898),new r(-.46968201,-.112519,-.87563598),new r(.81844002,-.25852001,-.51315099),new r(-.474318,.292238,-.83043301),new r(.778943,.39584199,-.48637101),new r(.62409401,.39377299,-.67487001),new r(.74088597,.203834,-.63995302),new r(.48021701,.565768,-.67029703),new r(.38093001,.42453501,-.82137799),new r(-.093422003,.50112402,-.86031801),new r(-.236485,.29619801,-.92538702),new r(-.131531,.093959004,-.98684901),new r(-.82356203,.29577699,-.48400599),new r(.61106598,-.624304,-.486664),new r(.069495998,-.52033001,-.85113299),new r(.226522,-.66487902,-.711775),new r(.47130799,-.56890398,-.67395699),new r(.38842499,-.74262398,-.54556),new r(.78367501,-.48072901,-.39338499),new r(.962394,.135676,-.235349),new r(.876607,.172034,-.449406),new r(.63340503,.58979303,-.50094098),new r(.182276,.80065799,-.57072097),new r(.177003,.76413399,.62029701),new r(-.544016,.675515,-.49772099),new r(-.67929697,.28646699,-.67564201),new r(-.59039098,.091369003,-.801929),new r(-.82436001,-.13312399,-.55018902),new r(-.71579403,-.33454201,-.61296099),new r(.17428599,-.89248401,.416049),new r(-.082528003,-.83712298,-.54075301),new r(.28333101,-.88087398,-.37918901),new r(.675134,-.42662701,-.60181701),new r(.84372002,-.512335,-.160156),new r(.97730398,-.098555997,-.18752),new r(.846295,.522672,-.102947),new r(.67714101,.72132498,-.145501),new r(.32096499,.87089199,-.37219399),new r(-.178978,.911533,-.37023601),new r(-.44716901,.82670099,-.341474),new r(-.70320302,.496328,-.50908101),new r(-.97718102,.063562997,-.202674),new r(-.87817001,-.412938,.241455),new r(-.83583099,-.35855001,-.415728),new r(-.499174,-.69343299,-.51959199),new r(-.188789,-.92375302,-.33322501),new r(.19225401,-.96936101,-.152896),new r(.51594001,-.783907,-.34539199),new r(.90592498,-.30095199,-.29787099),new r(.99111199,-.127746,.037106998),new r(.99513501,.098424003,-.0043830001),new r(.76012301,.64627701,.067367002),new r(.205221,.95958,-.192591),new r(-.042750001,.97951299,-.19679099),new r(-.43801701,.89892697,.0084920004),new r(-.82199401,.48078501,-.30523899),new r(-.89991701,.081710003,-.42833701),new r(-.92661202,-.144618,-.347096),new r(-.79365999,-.55779201,-.24283899),new r(-.43134999,-.84777898,-.30855799),new r(-.0054919999,-.96499997,.26219299),new r(.58790499,-.80402601,-.088940002),new r(.69949299,-.66768599,-.254765),new r(.88930303,.359795,-.282291),new r(.780972,.197037,.59267199),new r(.52012098,.50669599,.68755698),new r(.40389499,.69396102,.59605998),new r(-.154983,.89923602,.40909001),new r(-.65733802,.53716803,.528543),new r(-.74619502,.33409101,.575827),new r(-.62495202,-.049144,.77911502),new r(.31814101,-.254715,.913185),new r(-.555897,.405294,.725752),new r(-.79443401,.099405997,.59916002),new r(-.64036101,-.68946302,.33849499),new r(-.12671299,-.73409498,.66711998),new r(.105457,-.78081697,.61579502),new r(.40799299,-.48091599,.77605498),new r(.69513601,-.54512,.468647),new r(.97319102,-.0064889998,.229908),new r(.94689399,.317509,-.050799001),new r(.56358302,.82561201,.027183),new r(.325773,.94542301,.0069490001),new r(-.171821,.98509699,-.0078149997),new r(-.67044097,.73993897,.054768998),new r(-.822981,.55496198,.121322),new r(-.96619302,.117857,.229307),new r(-.95376903,-.29470399,.058945),new r(-.86438698,-.50272799,-.010015),new r(-.53060901,-.84200603,-.097365998),new r(-.162618,-.98407501,.071772002),new r(.081446998,-.99601102,.036439002),new r(.74598402,-.66596299,.00076199998),new r(.94205701,-.32926899,-.064106002),new r(.93970197,-.28108999,.194803),new r(.77121401,.55067003,.319363),new r(.641348,.73069,.23402099),new r(.080682002,.99669099,.0098789996),new r(-.046725001,.97664303,.20972501),new r(-.53107601,.82100099,.209562),new r(-.69581503,.65599,.29243499),new r(-.97612202,.216709,-.014913),new r(-.96166098,-.14412899,.23331399),new r(-.772084,-.61364698,.165299),new r(-.44960001,-.83605999,.314426),new r(-.39269999,-.91461599,.096247002),new r(.390589,-.91947001,.044890001),new r(.58252901,-.79919797,.148127),new r(.866431,-.48981199,.096864),new r(.90458697,.111498,.41145),new r(.95353699,.23232999,.191806),new r(.497311,.77080297,.398177),new r(.194066,.95631999,.218611),new r(.422876,.882276,.206797),new r(-.373797,.84956598,.37217399),new r(-.53449702,.71402299,.4522),new r(-.881827,.23716,.40759799),new r(-.904948,-.014069,.42528901),new r(-.751827,-.51281703,.41445801),new r(-.50101501,-.69791698,.51175803),new r(-.23519,-.92592299,.295555),new r(.228983,-.95393997,.193819),new r(.734025,-.63489801,.241062),new r(.91375297,-.063253,-.40131599),new r(.90573502,-.161487,.391875),new r(.85892999,.342446,.38074899),new r(.62448603,.60758102,.49077699),new r(.28926399,.85747898,.42550799),new r(.069968,.90216899,.42567101),new r(-.28617999,.94069999,.182165),new r(-.57401299,.80511898,-.14930899),new r(.111258,.099717997,-.98877603),new r(-.30539301,-.94422799,-.12316),new r(-.60116601,-.78957599,.123163),new r(-.290645,-.81213999,.50591898),new r(-.064920001,-.87716299,.47578499),new r(.408301,-.862216,.29978901),new r(.56609702,-.72556603,.39126399),new r(.83936399,-.427387,.33586901),new r(.81889999,-.041305002,.57244802),new r(.71978402,.41499701,.55649698),new r(.88174403,.45027,.140659),new r(.40182301,-.89822,-.17815199),new r(-.054019999,.79134399,.60898),new r(-.29377401,.76399398,.57446498),new r(-.450798,.61034697,.65135098),new r(-.63822103,.186694,.74687302),new r(-.87287003,-.25712699,.41470799),new r(-.58725703,-.52170998,.618828),new r(-.35365799,-.64197397,.680291),new r(.041648999,-.61127299,.79032302),new r(.348342,-.77918297,.52108699),new r(.499167,-.62244099,.602826),new r(.79001898,-.30383101,.53250003),new r(.66011798,.060733002,.74870199),new r(.60492098,.29416099,.73996001),new r(.38569701,.37934601,.84103203),new r(.239693,.207876,.94833201),new r(.012623,.25853199,.96591997),new r(-.100557,.457147,.88368797),new r(.046967,.62858802,.77631903),new r(-.43039101,-.44540501,.785097),new r(-.43429101,-.196228,.87913901),new r(-.25663701,-.336867,.90590203),new r(-.131372,-.15891001,.97851402),new r(.102379,-.208767,.972592),new r(.195687,-.450129,.87125802),new r(.62731898,-.42314801,.65377098),new r(.68743902,-.171583,.70568198),new r(.27592,-.021255,.96094602),new r(.45936701,.15746599,.87417799),new r(.285395,.583184,.76055598),new r(-.81217402,.46030301,.35846099),new r(-.189068,.64122301,.743698),new r(-.338875,.47648001,.811252),new r(-.92099398,.347186,.176727),new r(.040638998,.024465,.99887401),new r(-.73913199,-.35374701,.57318997),new r(-.60351199,-.28661501,.74405998),new r(-.188676,-.547059,.81555402),new r(-.026045,-.39782,.91709399),new r(.26789701,-.649041,.71202302),new r(.518246,-.28489101,.80638599),new r(.493451,-.066532999,.86722499),new r(-.328188,.140251,.93414301),new r(.328188,.140251,.93414301),new r(-.328188,.140251,.93414301),new r(-.328188,.140251,.93414301),new r(-.328188,.140251,.93414301)];class f{constructor(e,t,i){this.sizeX=e,this.sizeY=t,this.sizeZ=i,this.arr=new Array(e*t*i)}add(e){this.arr[e.x+e.y*this.sizeX+e.z*this.sizeX*this.sizeY]=e}get(e,t,i){if(!(e>=this.sizeX||t>=this.sizeY||i>=this.sizeZ))return this.arr[e+t*this.sizeX+i*this.sizeX*this.sizeY]}}var y=__webpack_require__(949);class w{get spanX(){return this.maxBounds.x-this.minBounds.x}get spanY(){return this.maxBounds.y-this.minBounds.y}get spanZ(){return this.maxBounds.z-this.minBounds.z}get scaleX(){return this.spanX/this.sizeX}get scaleY(){return this.spanY/this.sizeY}get scaleZ(){return this.spanZ/this.sizeZ}get scale(){return new y.Vector3(this.scaleX,this.scaleY,this.scaleZ)}getAllVoxels(){let i=[],s=new f(this.sizeX+1,this.sizeY+1,this.sizeZ+1);for(let e=0,t=this.spans.length;e<t;e++){var r=this.spans[e].voxels;for(let e=0,t=r.length;e<t;e++){var a=r[e];i.push(a),s.add(a)}}return{voxels:i,voxelField:s}}getNormals(){switch(this.normalsMode){case 1:return u;case 2:return p;case 3:return g;case 4:return m;default:throw new Error(`Invalid normalsmode ${this.normalsMode}`)}}scaleHvaMatrix(e){return(e=e.clone()).elements[12]*=this.hvaMultiplier,e.elements[13]*=this.hvaMultiplier,e.elements[14]*=this.hvaMultiplier,e}toPlain(){return{name:this.name,normalsMode:this.normalsMode,minBounds:this.minBounds.toArray(),maxBounds:this.maxBounds.toArray(),sizeX:this.sizeX,sizeY:this.sizeY,sizeZ:this.sizeZ,hvaMultiplier:this.hvaMultiplier,transfMatrix:this.transfMatrix.toArray(),spans:this.spans}}fromPlain(e){return this.name=e.name,this.normalsMode=e.normalsMode,this.minBounds=(new y.Vector3).fromArray(e.minBounds),this.maxBounds=(new y.Vector3).fromArray(e.maxBounds),this.sizeX=e.sizeX,this.sizeY=e.sizeY,this.sizeZ=e.sizeZ,this.hvaMultiplier=e.hvaMultiplier,this.transfMatrix=(new y.Matrix4).fromArray(e.transfMatrix),this.spans=e.spans,this}}class T{read(e){this.fileName=e.readCString(16),this.paletteCount=e.readUint32(),this.headerCount=e.readUint32(),this.tailerCount=e.readUint32(),this.bodySize=e.readUint32(),this.paletteRemapStart=e.readUint8(),this.paletteRemapEnd=e.readUint8(),e.seek(e.position+768)}}T.size=32;var S=__webpack_require__(949);class k{constructor(e){this.voxelCount=0,e instanceof i&&this.fromVirtualFile(e)}fromVirtualFile(e){this.filename=e.filename;let r=e.stream;if(this.sections=[],!(r.byteLength<T.size)){let s=new T;if(s.read(r),s.headerCount&&s.tailerCount&&s.tailerCount===s.headerCount){for(let e=0;e<s.headerCount;++e){const n=new w;this.readSectionHeader(n,r),this.sections.find(e=>e.name===n.name)&&console.warn(`Duplicate section name "${n.name}" found in VXL "${this.filename}".`),this.sections.push(n)}var a=r.position;r.seek(r.position+s.bodySize);let t=[];for(let e=0;e<s.tailerCount;++e)t[e]=this.readSectionTailer(this.sections[e],r);let i=0;for(let e=0;e<s.headerCount;++e)r.seek(a),i+=this.readSectionBodySpans(this.sections[e],t[e],r);this.voxelCount=i}}}readSectionHeader(e,t){e.name=t.readCString(16),t.readUint32(),t.readUint32(),t.readUint32()}readSectionTailer(e,t){var i=t.readUint32(),s=t.readUint32(),r=t.readUint32();return e.hvaMultiplier=t.readFloat32(),e.transfMatrix=this.readTransfMatrix(t),e.minBounds=new S.Vector3(t.readFloat32(),t.readFloat32(),t.readFloat32()),e.maxBounds=new S.Vector3(t.readFloat32(),t.readFloat32(),t.readFloat32()),e.sizeX=t.readUint8(),e.sizeY=t.readUint8(),e.sizeZ=t.readUint8(),e.normalsMode=t.readUint8(),{startingSpanOffset:i,endingSpanOffset:s,dataSpanOffset:r}}readTransfMatrix(t){let i=[];for(let e=0;e<3;++e)i.push(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32());return i.push(0,0,0,1),(new S.Matrix4).fromArray(i).transpose()}readSectionBodySpans(e,t,i){i.seek(i.position+t.startingSpanOffset);var{sizeX:s,sizeY:r,sizeZ:a}=e;let n=new Array(r);for(let t=0;t<r;++t){n[t]=new Array(s);for(let e=0;e<s;++e)n[t][e]=i.readInt32()}let o=new Array(r);for(let t=0;t<r;++t){o[t]=new Array(s);for(let e=0;e<s;++e)o[t][e]=i.readInt32()}let h=e.spans=[],l=0;for(let t=0;t<r;++t)for(let e=0;e<s;++e){var c={x:e,y:t,voxels:this.readSpanVoxels(n[t][e],o[t][e],e,t,a,i)};h.push(c),l+=c.voxels.length}return l}readSpanVoxels(e,t,i,s,r,a){if(-1===e||-1===t)return[];let n=[];for(let t=0;t<r;){t+=a.readUint8();var o=a.readUint8();for(let e=0;e<o;++e){var h={x:i,y:s,z:t++,colorIndex:a.readUint8(),normalIndex:a.readUint8()};n.push(h)}a.readUint8()}return n}fromPlain(e){return this.sections=e.sections.map(e=>(new w).fromPlain(e)),this.voxelCount=e.voxelCount,this}toPlain(){return{sections:this.sections.map(e=>e.toPlain()),voxelCount:this.voxelCount}}getSection(e){return this.sections[e]}}var O,_,I,C,A,B=__webpack_require__(949);(r=O=O||{})[r.ExtraData=1]="ExtraData",r[r.ZData=2]="ZData",r[r.DamagedData=4]="DamagedData";const x=e=>e<0?e+256:e;class E{constructor(e,t,i){this.fromStream(e,t,i)}fromStream(e,t,i){this.x=e.readInt32(),this.y=e.readInt32(),e.readInt32(),e.readInt32();var s=e.readInt32();this.extraX=e.readInt32(),this.extraY=e.readInt32(),this.extraWidth=e.readInt32(),this.extraHeight=e.readInt32();var r=e.readUint32();this.height=e.readUint8(),this.terrainType=e.readUint8(),this.rampType=e.readUint8(),this.radarLeft=this.readRadarRgb(e.readInt8(),e.readInt8(),e.readInt8()),this.radarRight=this.readRadarRgb(e.readInt8(),e.readInt8(),e.readInt8()),e.seek(e.position+3),this.tileData=new Uint8Array(e.buffer,e.byteOffset+e.position,t*i/2),e.position+=t*i/2,this.hasZData=(r&O.ZData)===O.ZData,this.hasZData&&(e.position+=t*i/2),this.hasExtraData=(r&O.ExtraData)===O.ExtraData,this.hasExtraData&&(r=Math.abs(this.extraWidth*this.extraHeight),this.extraData=new Uint8Array(e.buffer,e.byteOffset+e.position,r),e.position+=r),this.hasZData&&this.hasExtraData&&0<s&&s<e.byteLength&&(e.position+=Math.abs(this.extraWidth*this.extraHeight))}readRadarRgb(e,t,i){return new B.Color(x(e)/255,x(t)/255,x(i)/255)}}class P{constructor(e){this.images=[],e instanceof i&&this.fromVirtualFile(e)}fromVirtualFile(e){let t=e.stream;this.width=t.readInt32(),this.height=t.readInt32(),this.blockWidth=t.readInt32(),this.blockHeight=t.readInt32();var i=this.width*this.height,s=new Uint8Array(t.buffer,t.byteOffset+t.position,4*i);this.images=[];for(let e=0;e<i;e++){var r=s[4*e+3]<<24|s[4*e+2]<<16|s[4*e+1]<<8|s[4*e];t.seek(r);r=new E(t,this.blockWidth,this.blockHeight);this.images.push(r)}}}class N{static encode(e){return void 0!==globalThis.btoa?globalThis.btoa(e):Buffer.from(e,"binary").toString("base64")}static decode(e){return void 0!==globalThis.atob?globalThis.atob(e):Buffer.from(e,"base64").toString("binary")}static isBase64(e){return!!e.match(/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/)}}function M(e,t="0000"){e=""+e;return t.substring(0,t.length-e.length)+e}function D(e,t){return e.toLowerCase()===t.toLowerCase()}function R(t){var i=t.length;let s=new Uint8Array(i);for(let e=0;e<i;e++)s[e]=t.charCodeAt(e);return s}function L(e){return R(N.decode(e))}function F(e){return e.reduce((e,t)=>e+String.fromCharCode(t),"")}function j(t){var i=t.length;let s="";for(let e=0;e<i;e++){var r=t.charCodeAt(e);s+=String.fromCharCode(r>>8),s+=String.fromCharCode(255&r)}return s}function U(t){var i=t.length;let s="";for(let e=0;e<i;e+=2){var r=(t.charCodeAt(e)<<8)+t.charCodeAt(e+1);s+=String.fromCharCode(r)}return s}class W{constructor(e,t,i){this.r=e,this.g=t,this.b=i}static fromRgb(e,t,i){return new W(e,t,i)}static fromHsv(e,t,i){let s=0,r=0,a=0;if(e=e/255*360%360,i/=255,0===(t/=255))s=i,r=i,a=i;else{var n=e/60,e=Math.floor(n),n=n-e,o=i*(1-t),h=i*(1-t*n),l=i*(1-t*(1-n));switch(e){case 0:s=i,r=l,a=o;break;case 1:s=h,r=i,a=o;break;case 2:s=o,r=i,a=l;break;case 3:s=o,r=h,a=i;break;case 4:s=l,r=o,a=i;break;case 5:s=i,r=o,a=h}}return W.fromRgb(Math.floor(255*s),Math.floor(255*r),Math.floor(255*a))}asHex(){return(this.r<<16)+(this.g<<8)+this.b}asHexString(){return"#"+M(this.asHex().toString(16),"000000")}clone(){return new W(this.r,this.g,this.b)}}function z(e,t,i){return Math.min(i,Math.max(e,t))}function V(e,t,i){return t<=e&&e<=i}function H(e,t,i){return(1-i)*e+i*t}function G(i){let s=2166136261;for(let e=0,t=i.length;e<t;++e)s^=i[e],s+=(s<<1)+(s<<4)+(s<<7)+(s<<8)+(s<<24);return s>>>0}class ${constructor(e){e instanceof i?this.fromVirtualFile(e):"object"==typeof e&&this.fromJson(e)}fromVirtualFile(e){e=e.stream.readUint8Array(768);this.fromJson(e)}fromJson(t){this.colors=[];for(let e=0;e<t.length/3;++e)this.colors.push(W.fromRgb(4*t[3*e],4*t[3*e+1],4*t[3*e+2]));this._hash=this.computeHash(this.colors)}getColor(e){return this.colors[e]}getColorAsHex(e){return this.getColor(e).asHex()}setColors(e){this.colors=e,this._hash=this.computeHash(this.colors)}get size(){return this.colors.length}get hash(){return this._hash}computeHash(e){let t=new Uint8Array(3*this.size),i=0;for(var s of e)t[i]=s.r,t[i+1]=s.g,t[i+2]=s.b,i+=3;return G(t)}clone(){let e=new $;return e.colors=this.colors.map(e=>e.clone()),e._hash=this._hash,e}remap(t){var i=[63,59,55,52,48,44,41,37,33,30,26,22,19,15,11,8];for(let e=$.REMAP_START_IDX;e<$.REMAP_START_IDX+i.length;e++)this.colors[e].r=Math.floor(t.r/255*i[e-$.REMAP_START_IDX]*4),this.colors[e].g=Math.floor(t.g/255*i[e-$.REMAP_START_IDX]*4),this.colors[e].b=Math.floor(t.b/255*i[e-$.REMAP_START_IDX]*4);return this._hash=this.computeHash(this.colors),this}}$.REMAP_START_IDX=16;class q{constructor(e,t){this.owner=e,this.index=t,this.files=[]}addFile(e){this.files.push(e)}setAnimation(e){this.animation=e}getAnimation(){return this.animation}getTmpFile(e,t,i=!1){if(this.files.length){t=this.files[t(0,this.files.length-1)];return t.images[Math.min(e,t.images.length-1)].hasDamagedData?this.files[Math.min(i?1:0,this.files.length-1)]:t}}}class X{constructor(e,t,i){this.fileName=e,this.setName=t,this.tilesInSet=i,this.entries=[]}}class Z{constructor(e,t,i,s){this.name=e,this.subTile=t,this.offsetX=i,this.offsetY=s}}(r=_=_||{})[r.TopLeft=0]="TopLeft",r[r.BottomRight=1]="BottomRight",r[r.TopRight=2]="TopRight",r[r.BottomLeft=3]="BottomLeft",r[r.MiddleTlBr=4]="MiddleTlBr",r[r.MiddleTrBl=5]="MiddleTrBl";const Q=new Map([[_.TopLeft,["BridgeTopLeft1","BridgeTopLeft2"]],[_.BottomRight,["BridgeBottomRight1","BridgeBottomRight2"]],[_.TopRight,["BridgeTopRight1","BridgeTopRight2"]],[_.BottomLeft,["BridgeBottomLeft1","BridgeBottomLeft2"]],[_.MiddleTlBr,["BridgeMiddle1"]],[_.MiddleTrBl,["BridgeMiddle2"]]]);class Y{constructor(e){this.theaterIni=e,this.tileSets=[],this.orderedEntries=[],this.highBridgeSetNums=[this.getGeneralValue("BridgeSet"),this.getGeneralValue("WoodBridgeSet")],this.cliffSetNums=[this.getGeneralValue("CliffSet"),this.getGeneralValue("WaterCliffs"),this.getGeneralValue("DestroyableCliffs")]}getTile(e){return this.orderedEntries[e]}getTileImage(e,t,i){let s=this.getTile(e);if(!s)throw new Error(`TileNum ${e} not found`);i=s.getTmpFile(t,i);if(!i||t>=i.images.length)throw new Error(`SubTile ${t} not found`);return i.images[t]}getSetNum(e){var t=this.orderedEntries[e];if(!t)throw new Error("Invalid tileNum "+e);return this.tileSets.indexOf(t.owner)}getTileNumFromSet(i,s=0){let r=0;return this.tileSets.some((e,t)=>t===i?(r+=s,!0):(r+=e.entries.length,!1)),r}getGeneralValue(e){let t=this.theaterIni.getSection("General");if(!t)throw new Error("Missing [General] section in theather ini");return t.getNumber(e)}loadTileData(e,t){this.tileSets.length=0,this.orderedEntries.length=0,this.initTileSets(e,t),this.initAnimations()}readMaxTileNum(){let t=0,i=0;for(;;){var s="TileSet"+M(t,"0000");let e=this.theaterIni.getSection(s);if(!e)break;t++,i+=e.getNumber("TilesInSet")}return i}initTileSets(a,n){let e=0,t;for(var i;;){if(i="TileSet"+M(e,"0000"),t=this.theaterIni.getSection(i),!t)break;e++;let r=new X(t.getString("FileName"),t.getString("SetName"),t.getNumber("TilesInSet"));this.tileSets.push(r);for(let s=1;s<=r.tilesInSet;s++){let i=new q(r,s-1);var o="a".charCodeAt(0);for(let t=o-1;t<="z".charCodeAt(0);t++)if(!(t>=o&&"Bridges"===r.setName)){let e=r.fileName+M(s,"00");t>=o&&(e+=String.fromCharCode(t)),e+=n;var h=a.get(e);if(!h)break;i.addFile(h)}r.entries.push(i),this.orderedEntries.push(i)}}}initAnimations(){var s=this.theaterIni.getOrderedSections();for(let e=this.tileSets.length;e<s.length;++e){let t=s[e],i=this.tileSets.find(e=>e.setName===t.name);if(i)for(let e=1;e<=i.tilesInSet;++e){var r=`Tile${M(e,"00")}`,a=`${r}Anim`,n=t.getString(a);n?(r=new Z(n,t.getNumber(`${r}AttachesTo`),t.getNumber(`${r}XOffset`),t.getNumber(`${r}YOffset`)),i.entries[e-1].setAnimation(r)):console.warn(`Missing anim "${a}" for tileset ${i.setName}`)}}}isLAT(e){return e===this.getGeneralValue("RoughTile")||e===this.getGeneralValue("SandTile")||e===this.getGeneralValue("GreenTile")||e===this.getGeneralValue("PaveTile")}isCLAT(e){return e===this.getGeneralValue("ClearToRoughLat")||e===this.getGeneralValue("ClearToSandLat")||e===this.getGeneralValue("ClearToGreenLat")||e===this.getGeneralValue("ClearToPaveLat")}getLAT(e){return e===this.getGeneralValue("ClearToRoughLat")?this.getGeneralValue("RoughTile"):e===this.getGeneralValue("ClearToSandLat")?this.getGeneralValue("SandTile"):e===this.getGeneralValue("ClearToGreenLat")?this.getGeneralValue("GreenTile"):e===this.getGeneralValue("ClearToPaveLat")?this.getGeneralValue("PaveTile"):-1}getCLATSet(e){return e===this.getGeneralValue("RoughTile")?this.getGeneralValue("ClearToRoughLat"):e===this.getGeneralValue("SandTile")?this.getGeneralValue("ClearToSandLat"):e===this.getGeneralValue("GreenTile")?this.getGeneralValue("ClearToGreenLat"):e===this.getGeneralValue("PaveTile")?this.getGeneralValue("ClearToPaveLat"):-1}canConnectTiles(e,t){if(e===t)return!1;var i=this.getGeneralValue("GreenTile"),s=this.getGeneralValue("PaveTile"),r=this.getGeneralValue("MiscPaveTile"),a=this.getGeneralValue("ShorePieces"),n=this.getGeneralValue("WaterBridge"),o=this.getGeneralValue("PavedRoads"),h=this.getGeneralValue("Medians");return!(e===i&&t===a||t===i&&e===a)&&(!(e===i&&t===n||t===i&&e===n)&&(!(e===s&&t===o||t===s&&e===o)&&(!(e===s&&t===r||t===s&&e===r)&&!(e===s&&t===h||t===s&&e===h))))}getHighBridgeHeadType(e){for(var[t,i]of Q)for(var s of i)if(this.getGeneralValue(s)===e+1)return t}getOppositeHighBridgeHeadType(e){switch(e){case _.TopLeft:return _.BottomRight;case _.TopRight:return _.BottomLeft;case _.BottomLeft:return _.TopRight;case _.BottomRight:return _.TopLeft;case _.MiddleTlBr:case _.MiddleTrBl:throw new Error("Middle bridge heads can't have opposites");default:throw new Error(`Unhandled headType ${e}`)}}isCliffTile(e){return this.cliffSetNums.includes(this.getSetNum(e))}isHighBridgeBoundaryTile(e){if(this.highBridgeSetNums.includes(this.getSetNum(e))){e=this.getTile(e),e=this.getHighBridgeHeadType(e.index);return void 0!==e&&![_.MiddleTlBr,_.MiddleTrBl].includes(e)}return!1}isHighBridgeMiddleTile(e){if(this.highBridgeSetNums.includes(this.getSetNum(e))){e=this.getTile(e),e=this.getHighBridgeHeadType(e.index);return void 0!==e&&[_.MiddleTlBr,_.MiddleTrBl].includes(e)}return!1}}(r=I=I||{})[r.None=0]="None",r[r.Iso=1]="Iso",r[r.Unit=2]="Unit",r[r.Overlay=3]="Overlay",r[r.Anim=4]="Anim",r[r.Custom=5]="Custom",r[r.Default=6]="Default";class K{constructor(e,t,i,s,r,a,n,o,h){this.type=e,this.settings=t,this.palettes=i,this.isoPalette=s,this.ovlPalette=r,this.unitPalette=a,this.animPalette=n,this.libPalette=o,this.tileSets=h}static factory(e,t,i,s,r){var a=r.get(i.IsoPaletteName);if(!a)throw new Error(`Missing palette "${i.IsoPaletteName}"`);var n=r.get(i.OverlayPaletteName);if(!n)throw new Error(`Missing palette "${i.OverlayPaletteName}"`);var o=r.get(i.UnitPaletteName);if(!o)throw new Error(`Missing palette "${i.UnitPaletteName}"`);var h=r.get("anim.pal");if(!h)throw new Error("Missing anim palette");var l=r.get(i.LibPaletteName);if(!l)throw new Error(`Missing lib palette ${i.LibPaletteName}`);let c=new Y(t);return c.loadTileData(s,i.Extension),new this(e,i,r,a,n,o,h,l,c)}getPalette(e,t){switch(e){case I.Anim:return this.animPalette;case I.Overlay:return this.ovlPalette;case I.Unit:return this.unitPalette;case I.Custom:if("lib"===t)return this.libPalette;var i=this.palettes.get(t+".pal");if(!i)throw new Error(`Custom palette "${t}" not found`);return i;default:I.Iso;return this.isoPalette}}}(r=C=C||{})[r.None=0]="None",r[r.Temperate=1]="Temperate",r[r.Urban=2]="Urban",r[r.Snow=4]="Snow",r[r.Lunar=8]="Lunar",r[r.Desert=16]="Desert",r[r.NewUrban=32]="NewUrban",r[r.All=63]="All";class J{constructor(){this.fileData=new Map}fromVirtualFile(e,t){var i,s;for([i,s]of t.entries){var r=this.buildWavData(e.stream,s);this.fileData.set(i,r)}return this}getFileList(){return[...this.fileData.keys()]}containsFile(e){return this.fileData.has(e)}openFile(e){if(!this.containsFile(e))throw new Error(`File "${e}" not found`);return new i(this.fileData.get(e),e)}buildWavData(e,t){let i=new v;var s,r,a,n,o=0<(1&t.flags)?2:1;let h=0;0<(2&t.flags)?(i.writeString("RIFF"),i.writeUint32(t.length+36),i.writeString("WAVE"),i.writeString("fmt "),i.writeInt32(16),i.writeInt16(1),i.writeInt16(o),i.writeUint32(t.sampleRate),i.writeUint32(2*o*t.sampleRate),i.writeInt16(2*o),i.writeInt16(16),i.writeString("data"),i.writeUint32(t.length)):0<(8&t.flags)&&(s=11100*o*(t.sampleRate/22050|0),r=t.chunkSize,a=1017*(n=Math.max(2,Math.ceil(t.length/r))),n=n*r,h=n-t.length,i.writeString("RIFF"),i.writeUint32(52+n),i.writeString("WAVE"),i.writeString("fmt "),i.writeUint32(20),i.writeInt16(17),i.writeInt16(o),i.writeUint32(t.sampleRate),i.writeInt32(s),i.writeInt16(r),i.writeInt16(4),i.writeInt16(2),i.writeInt16(1017),i.writeString("fact"),i.writeUint32(4),i.writeInt32(a),i.writeString("data"),i.writeUint32(n)),e.seek(t.offset),i.writeUint8Array(e.readUint8Array(t.length));for(let e=0;e<h;e++)i.writeUint8(0);return i.seek(0),i._trimAlloc=()=>{},i}}class ee{}class te{constructor(e){this.entries=new Map,this.parse(e)}parse(t){var e=t.readCString(4);if("GABA"!==e)throw new Error(`Unable to load Idx file, did not find magic id, found ${e} instead`);e=t.readInt32();if(2!==e)throw new Error(`Unable to load Idx file, did not find magic number 2, found ${e} instead`);var i=t.readInt32();for(let e=0;e<i;e++){const r=new ee;let e=t.readString(16);var s=e.indexOf("\0");0!==s&&(e=e.substr(0,s)),r.filename=e+".wav",r.offset=t.readUint32(),r.length=t.readUint32(),r.sampleRate=t.readUint32(),r.flags=t.readUint32(),r.chunkSize=t.readUint32(),this.entries.set(r.filename,r)}}}function ie(e){return e=((e=(e<<16>>>0|e>>>16)>>>0)<<8>>>0&4278255360|e>>>8&16711935)>>>0}class se{constructor(i){this.m_p=new Uint32Array([608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731]),this.m_s=[new Uint32Array([3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946]),new Uint32Array([1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055]),new Uint32Array([3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504]),new Uint32Array([976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462])];for(let e=0,t=0;e<18;++e){var s=i[t++%i.length],r=i[t++%i.length],a=i[t++%i.length],n=i[t++%i.length];this.m_p[e]^=s<<24|r<<16|a<<8|n}let o=0,h=0;for(let e=0;e<18;)[o,h]=this._encrypt(o,h),this.m_p[e++]=o,this.m_p[e++]=h;for(let t=0;t<4;++t)for(let e=0;e<256;)[o,h]=this._encrypt(o,h),this.m_s[t][e++]=o,this.m_s[t][e++]=h}encrypt(e){return this.runCipher(e,this._encrypt.bind(this))}decrypt(e){return this.runCipher(e,this._decrypt.bind(this))}runCipher(e,t){let i=new Uint32Array(e.length),s=e.length/2|0,r=0;for(;0<s--;){var a=ie(e[r]),n=ie(e[r+1]);[a,n]=t(a,n),i[r++]=ie(a),i[r++]=ie(n)}return i}_encrypt(e,t){let i=e,s=t;i^=this.m_p[0];let r=!1;for(let e=1;e<=16;e++,r=!r)r?i=this.round(i,s,e):s=this.round(s,i,e);return s^=this.m_p[17],[s,i]}_decrypt(e,t){let i=e,s=t;i^=this.m_p[17];let r=!1;for(let e=16;1<=e;e--,r=!r)r?i=this.round(i,s,e):s=this.round(s,i,e);return s^=this.m_p[0],[s,i]}s(e,t){return this.m_s[t][e>>(3-t<<3)&255]}bf_f(e){return(this.s(e,0)+this.s(e,1)>>>0^this.s(e,2))+this.s(e,3)>>>0}round(e,t,i){return e^(this.bf_f(t)^this.m_p[i])}}const re="AihRvNoIbTn85FZRYNZRcT+i6KpU+maCsEqr3Q5q+LDB5tH7Tz2qQ38V",ae=new Int8Array([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1]);class ne{constructor(){this.key1=new Uint32Array(64),this.key2=new Uint32Array(64)}}class oe{constructor(){this.pubkey=new ne,this.glob1=new Uint32Array(64),this.glob2=new Uint32Array(130),this.glob1_hi=new Uint32Array(4),this.glob1_hi_inv=new Uint32Array(4)}init_bignum(t,e,i){for(let e=0;e<i;e++)t[e]=0;t[0]=e}move_key_to_big(e,t,i,s){let r;r=0!=(128&t[0])?255:0;const a=new Uint8Array(e.buffer,e.byteOffset);let n=4*s;for(;n>i;n--)a[n-1]=r;for(;0<n;n--)a[n-1]=t[i-n]}key_to_bignum(e,t,i){let s,r,a=0;if(2===t[a]){if(a++,0!=(128&t[a])){for(s=0,r=0;r<(127&t[a]);r++)s=(s<<8>>>0|t[a+r+1])>>>0;a+=1+(127&t[a])}else s=t[a],a++;s<=4*i&&this.move_key_to_big(e,t.subarray(a),s,i)}}len_bignum(e,t){let i=t-1;for(;0<=i&&0===e[i];)i--;return i+1}bitlen_bignum(e,t){var i;let s,r;if(0===(i=this.len_bignum(e,t)))return 0;for(s=32*i,r=2147483648;0==(r&e[i-1]);)r>>>=1,s--;return s}init_pubkey(){let e=0,t;var i;const s=new Uint8Array(256);for(this.init_bignum(this.pubkey.key2,65537,64),t=0;e<re.length;)i=(((ae[re.charCodeAt(e++)]>>>0<<6>>>0|255&ae[re.charCodeAt(e++)])>>>0<<6>>>0|255&ae[re.charCodeAt(e++)])>>>0<<6>>>0|255&ae[re.charCodeAt(e++)])>>>0,s[t++]=i>>16&255,s[t++]=i>>8&255,s[t++]=255&i;this.key_to_bignum(this.pubkey.key1,s,64),this.pubkey.len=this.bitlen_bignum(this.pubkey.key1,64)-1}len_predata(){var e=(this.pubkey.len-1)/8|0;return(1+(55/e|0))*(1+e)>>>0}cmp_bignum(e,t,i){for(;0<i;){if(e[--i]<t[i])return-1;if(e[i]>t[i])return 1}return 0}mov_bignum(t,i,s){for(let e=0;e<s;e++)t[e]=i[e]}shr_bignum(e,t,i){let s;var r=t/32|0;if(0<r){for(s=0;s<i-r;s++)e[s]=e[s+r];for(;s<i;s++)e[s]=0;t%=32}if(0!==t){for(s=0;s<i-1;s++)e[s]=(e[s]>>>t|e[s+1]<<32-t>>>0)>>>0;e[s]=e[s]>>>t}}shl_bignum(e,t,i){let s;var r=t/32|0;if(0<r){for(s=i-1;s>r;s--)e[s]=e[s-r];for(;0<s;s--)e[s]=0;t%=32}if(0!==t){for(s=i-1;0<s;s--)e[s]=(e[s]<<t>>>0|e[s-1]>>>32-t)>>>0;e[0]=e[0]<<t>>>0}}sub_bignum(e,t,i,s,r){var a,n;r+=r;var o=new Uint16Array(t.buffer,t.byteOffset),h=new Uint16Array(i.buffer,i.byteOffset);const l=new Uint16Array(e.buffer,e.byteOffset);let c=0;for(;-1!=--r;)a=o[c],n=h[c],l[c]=a-n-s&65535,s=0!=(a-n-s&65536)?1:0,c++;return s}sub_bignum_word(e,t,i,s,r){var a,n;let o=0;for(;-1!=--r;)a=t[o],n=i[o],e[o]=a-n-s&65535,s=0!=(a-n-s&65536)?1:0,o++;return s}inv_bignum(e,t,i){const s=new Uint32Array(64);var r;let a,n,o=0;for(this.init_bignum(s,0,i),this.init_bignum(e,0,i),n=this.bitlen_bignum(t,i),a=1<<n%32>>>0,o=((n+32)/32|0)-1,r=4*((n-1)/32|0)>>>0,s[r/4|0]=s[r/4|0]|1<<(n-1&31)>>>0;0<n;)n--,this.shl_bignum(s,1,i),-1!==this.cmp_bignum(s,t,i)&&(this.sub_bignum(s,s,t,0,i),e[o]=e[o]|a>>>0),a>>>=1,0===a&&(o--,a=2147483648);this.init_bignum(s,0,i)}inc_bignum(e,t){let i=0;for(;0==++e[i]&&0<--t;)i++}init_two_dw(e,t){this.mov_bignum(this.glob1,e,t),this.glob1_bitlen=this.bitlen_bignum(this.glob1,t),this.glob1_len_x2=(this.glob1_bitlen+15)/16|0,this.mov_bignum(this.glob1_hi,this.glob1.subarray(this.len_bignum(this.glob1,t)-2),2),this.glob1_hi_bitlen=this.bitlen_bignum(this.glob1_hi,2)-32>>>0,this.shr_bignum(this.glob1_hi,this.glob1_hi_bitlen,2),this.inv_bignum(this.glob1_hi_inv,this.glob1_hi,2),this.shr_bignum(this.glob1_hi_inv,1,2),this.glob1_hi_bitlen=(this.glob1_hi_bitlen+15)%16+1>>>0,this.inc_bignum(this.glob1_hi_inv,2),32<this.bitlen_bignum(this.glob1_hi_inv,2)&&(this.shr_bignum(this.glob1_hi_inv,1,2),this.glob1_hi_bitlen--),this.glob1_hi_inv_lo=65535&this.glob1_hi_inv[0],this.glob1_hi_inv_hi=this.glob1_hi_inv[0]>>>16&65535}mul_bignum_word(e,t,i,s){let r,a;var n=new Uint16Array(t.buffer,t.byteOffset);let o=a=0;for(r=0;r<s;r++)a=i*n[o]+e[o]+a,e[o]=65535&a,o++,a>>>=16;e[o]+=65535&a}mul_bignum(e,t,i,s){let r;var a=new Uint16Array(i.buffer,i.byteOffset);let n=new Uint16Array(e.buffer,e.byteOffset);this.init_bignum(e,0,2*s);let o=0;for(r=0;r<2*s;r++)this.mul_bignum_word(n.subarray(o),t,a[o],2*s),o++}not_bignum(e,t){let i;for(i=0;i<t;i++)e[i]=~e[i]>>>0}neg_bignum(e,t){this.not_bignum(e,t),this.inc_bignum(e,t)}get_mulword(e,t){let i=((((65535&(65535^e[t-1]))*this.glob1_hi_inv_lo+65536>>>1)+((65535^e[t-2])*this.glob1_hi_inv_hi+this.glob1_hi_inv_hi>>>1)+1>>>16)+((65535&(65535^e[t-1]))*this.glob1_hi_inv_hi>>>1)+((65535^e[t])*this.glob1_hi_inv_lo>>>1)+1>>>14)+this.glob1_hi_inv_hi*(65535^e[t])*2>>>this.glob1_hi_bitlen>>>0;return 65535<i&&(i=65535),65535&i}dec_bignum(e,t){let i=0;for(;--e[i]>>>0==4294967295&&0<--t;)i++}calc_a_bignum(e,t,s,r){let a;var n=this.glob1,o=this.glob2;if(this.mul_bignum(this.glob2,t,s,r),this.glob2[2*r]=0,(s=2*this.len_bignum(this.glob2,2*r+1))>=this.glob1_len_x2){this.inc_bignum(this.glob2,2*r+1),this.neg_bignum(this.glob2,2*r+1),a=1+s-this.glob1_len_x2;let e=new Uint16Array(o.buffer),t=a,i=1+s;for(;0!==a;a--){i--;var h=this.get_mulword(e,i);t--;var l=e.subarray(t);0<h&&(this.mul_bignum_word(l,this.glob1,h,2*r),0==(32768&e[i])&&0!==this.sub_bignum_word(l,l,new Uint16Array(n.buffer),0,2*r)&&e[i]--)}this.neg_bignum(this.glob2,r),this.dec_bignum(this.glob2,r)}this.mov_bignum(e,this.glob2,r)}clear_tmp_vars(e){this.init_bignum(this.glob1,0,e),this.init_bignum(this.glob2,0,e),this.init_bignum(this.glob1_hi_inv,0,4),this.init_bignum(this.glob1_hi,0,4),this.glob1_bitlen=0,this.glob1_hi_bitlen=0,this.glob1_len_x2=0,this.glob1_hi_inv_lo=0,this.glob1_hi_inv_hi=0}calc_a_key(e,t,i,s,r){var a,n=new Uint32Array(64);let o,h,l=0;for(this.init_bignum(e,1,r),a=this.len_bignum(s,r),this.init_two_dw(s,a),o=this.bitlen_bignum(i,a)<<24>>24,s=((o+31)/32|0)>>>0,h=1<<(o-1)%32>>>1,l+=s-1,o--,this.mov_bignum(e,t,a);-1!=--o;)0===h&&(h=2147483648,l--),this.calc_a_bignum(n,e,e,a),0!=(i[l]&h)?this.calc_a_bignum(e,n,t,a):this.mov_bignum(e,n,a),h>>>=1;this.init_bignum(n,0,a),this.clear_tmp_vars(r)}memcpy(e,t,i){let s=0;for(;0!=i--;)e[s]=t[s],s++}process_predata(e,t,i){var s=new Uint32Array(64),r=new Uint32Array(64);let a=0,n=0;for(var o=(this.pubkey.len-1)/8|0;1+o<=t;)this.init_bignum(s,0,64),this.memcpy(new Uint8Array(s.buffer),e.subarray(a),1+o),this.calc_a_key(r,s,this.pubkey.key2,this.pubkey.key1,64),this.memcpy(i.subarray(n),new Uint8Array(r.buffer),o),t-=1+o,a+=1+o,n+=o}decryptKey(e){this.init_pubkey();let t=new Uint8Array(256);return this.process_predata(e,this.len_predata(),t),t.subarray(0,56)}}class he{constructor(e=4294967295){this.polynomal=e,this.crc=e}static calculateCrc(i,e=4294967295){let s=e;for(let e=0,t=i.length;e<t;e++)s=(s>>>8^this.lookUp[255&s^i[e]])>>>0;return s=(s^e)>>>0,s}append(i){for(let e=0,t=i.length;e<t;e++)this.crc=(this.crc>>>8^he.lookUp[255&this.crc^i[e]])>>>0}get(){return(this.crc^this.polynomal)>>>0}}he.lookUp=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);class le{constructor(e,t,i){this.hash=e,this.offset=t,this.length=i}static hashFilename(t){var i=(t=t.toUpperCase()).length,s=i>>2;if(0!=(3&i)){t+=String.fromCharCode(i-(s<<2));let e=3-(3&i);for(;0!=e--;)t+=t[s<<2]}return he.calculateCrc(R(t))}}le.size=12,(r=A=A||{})[r.Checksum=65536]="Checksum",r[r.Encrypted=131072]="Encrypted";class ce{constructor(e){this.stream=e,this.headerStart=84,this.index=new Map,this.parseHeader()}parseHeader(){var e=this.stream.readUint32(),t=0==(e&~(A.Checksum|A.Encrypted));if(t){if(0!=(e&A.Encrypted))return void(this.dataStart=this.parseRaHeader())}else this.stream.seek(0);this.dataStart=this.parseTdHeader(this.stream)}parseRaHeader(){const e=this.stream;var t=e.readUint8Array(80),i=(new oe).decryptKey(t),s=e.readUint32Array(2);const r=new se(i);let a=new v(r.decrypt(s));t=a.readUint16();a.readUint32(),e.position=this.headerStart;i=6+t*le.size,t=(3+i)/4|0,s=e.readUint32Array(t+t%2);a=new v(r.decrypt(s));i=this.headerStart+i+(1+(~i>>>0)&7);return this.parseTdHeader(a),i}parseTdHeader(t){var i=t.readUint16();t.readUint32();for(let e=0;e<i;e++){var s=new le(t.readUint32(),t.readUint32(),t.readUint32());this.index.set(s.hash,s)}return t.position}containsFile(e){return this.index.has(le.hashFilename(e))}openFile(e){var t=this.index.get(le.hashFilename(e));if(!t)throw new Error(`File "${e}" not found`);return i.factory(this.stream,e,this.dataStart+t.offset,t.length)}}class ue extends Error{constructor(){super(...arguments),this.name="FileNotFoundError"}}class de{constructor(){this.entries=new Map}addFile(e){this.entries.set(e.filename,e)}containsFile(e){return this.entries.has(e)}openFile(e){if(!this.containsFile(e))throw new Error(`File "${e}" not found`);return this.entries.get(e)}}class pe{constructor(e,t){this.rfs=e,this.logger=t,this.allArchives=new Map,this.archivesByPriority=[]}fileExists(e){for(const t of this.archivesByPriority)if(t.containsFile(e))return!0;return!1}openFile(e){for(const t of this.archivesByPriority)if(t.containsFile(e))return t.openFile(e);throw new ue(`File "${e}" not found in VFS`)}addArchive(e,t){this.allArchives.has(t)||(this.allArchives.set(t,e),this.archivesByPriority.push(e)),this.logger.info(`Added archive "${t}" to VFS`)}hasArchive(e){return this.allArchives.has(e)}removeArchive(e){var t=this.allArchives.get(e);t&&(this.allArchives.delete(e),this.archivesByPriority.splice(this.archivesByPriority.indexOf(t),1),this.logger.info(`Removed archive "${e}" from VFS`))}listArchives(){return[...this.allArchives.keys()]}async addMixFile(e){await this.addArchiveByFilename(e,e=>new ce(e.stream))}async addBagFile(e){const i=await this.openFileWithRfs(e.replace(".bag",".idx"));await this.addArchiveByFilename(e,e=>{var t=new te(i.stream);return(new J).fromVirtualFile(e,t)})}async addArchiveByFilename(e,t){var i;this.allArchives.has(e)||(i=await this.openFileWithRfs(e))&&this.addArchive(t(i),e)}async openFileWithRfs(e){let t;try{t=await this.rfs.openFile(e)}catch(e){if(!(e instanceof ue))throw e}if(!t){if(!this.fileExists(e))throw new ue(`File "${e}" not found`);t=this.openFile(e)}return t}async loadImplicitMixFiles(e){this.logger.info("Initializing implicit mix files..."),e===Bt.YurisRevenge&&await this.addMixFile("langmd.mix"),await this.addMixFile("language.mix"),e===Bt.YurisRevenge&&await this.addMixFile("ra2md.mix"),await this.addMixFile("ra2.mix"),e===Bt.YurisRevenge&&await this.addMixFile("cachemd.mix"),await this.addMixFile("cache.mix"),e===Bt.YurisRevenge&&await this.addMixFile("loadmd.mix"),await this.addMixFile("load.mix"),e===Bt.YurisRevenge&&await this.addMixFile("localmd.mix"),await this.addMixFile("local.mix"),e===Bt.YurisRevenge&&await this.addMixFile("ntrlmd.mix"),await this.addMixFile("neutral.mix"),e===Bt.YurisRevenge&&await this.addMixFile("audiomd.mix"),await this.addMixFile("audio.mix"),await this.addBagFile("audio.bag"),await this.addMixFile("conquer.mix"),e===Bt.YurisRevenge&&(await this.addMixFile("conqmd.mix"),await this.addMixFile("genermd.mix")),await this.addMixFile("generic.mix"),e===Bt.YurisRevenge&&await this.addMixFile("isogenmd.mix"),await this.addMixFile("isogen.mix"),e===Bt.YurisRevenge&&await this.addMixFile("cameomd.mix"),await this.addMixFile("cameo.mix"),e===Bt.YurisRevenge&&await this.addMixFile("multimd.mix"),await this.addMixFile("multi.mix")}async loadExtraMixFiles(i){let s=new Set;for await(var e of this.rfs.getEntries())s.add(e.toLowerCase());for(var r of["ecache","expand","elocal"])for(let t=99;0<=t;t--){let e=[`${r}${M(t,"00")}.mix`];i===Bt.YurisRevenge&&e.push(`${r}md${M(t,"00")}.mix`);for(var a of e)s.has(a)&&await this.addMixFile(a)}let t=[".mmx"];i===Bt.YurisRevenge&&t.push(".yro");for(const n of t)for(const o of s)o.endsWith(n)&&this.addArchive(new ce((await this.rfs.openFile(o)).stream),o)}async loadStandaloneFiles(e){let i=["ini","csf"],s=new Set(e?.exclude),r=[];for await(var a of this.rfs.getEntries()){let t=a.toLowerCase();i.some(e=>t.endsWith("."+e))&&!s.has(t)&&r.push(await this.rfs.openFile(a,!0))}if(r.length){let e=new de;for(var t of r)e.addFile(t);this.addArchive(e,"mem.archive")}}}class ge extends Error{constructor(e){super("Storage quota exceeded",e),this.name="StorageQuotaError"}}class me extends l{constructor(){super(...arguments),this.name="NameNotAllowedError"}}class fe{constructor(e,t=!1){this.handle=e,this.caseSensitive=t}get name(){return this.handle.name}async*getEntries(){try{for await(var e of this.handle.keys())yield e}catch(e){if("NotFoundError"===e.name)throw new ue(`Directory "${this.handle.name}" not found`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${this.handle.name}" could not be read (${e.name})`,{cause:e});throw e}}async listEntries(){let e=[];for await(var t of this.getEntries())e.push(t);return e}async*getFileHandles(){try{for await(const e of this.handle.values())"file"===e.kind&&(yield e)}catch(e){if("NotFoundError"===e.name)throw new ue(`Directory "${this.handle.name}" not found`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${this.handle.name}" could not be read (${e.name})`,{cause:e});throw e}}async*getRawFiles(){for await(const e of this.getFileHandles())yield await e.getFile()}async containsEntry(e){return void 0!==await this.resolveEntryName(e)}async resolveEntryName(e){if(this.caseSensitive)return(await this.handle.getFileHandle(e).catch(()=>this.handle.getDirectoryHandle(e)).catch(()=>{}))?.name;for await(const t of this.getEntries())if(D(t,e))return t}async fixEntryCase(e){if(!this.caseSensitive)for await(var t of this.getEntries())if(D(t,e)){e=t;break}return e}async getRawFile(t,e=!1,i){let s;try{var r=e?t:await this.fixEntryCase(t);s=await this.handle.getFileHandle(r)}catch(e){if("NotFoundError"===e.name)throw new ue(`File "${t}" not found in directory "${this.handle.name}"`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new me(`File name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`File "${t}" could not be read (${e.name})`,{cause:e});throw e}t=await s.getFile();return i?new File([t],t.name,{type:i}):t}async openFile(e,t=!1){t=await this.getRawFile(e,t);return i.fromRealFile(t)}async writeFile(i,s){s=s??(i instanceof File?i.name:i.filename);try{var r=await this.fixEntryCase(s);await this.deleteFile(r,!0);let e=await this.handle.getFileHandle(r,{create:!0}),t=await e.createWritable();try{await t.write(i instanceof File?i:new Uint8Array(i.stream.buffer,i.stream.byteOffset,i.stream.byteLength)),await t.close()}catch(e){throw await t.abort(),e}}catch(e){if("QuotaExceededError"===e.name)throw new ge({cause:e});if("NotFoundError"===e.name)throw new ue(`Directory "${this.handle.name}" not found`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new me(`File name "${s}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`File "${s}" could not be written (${e.name})`,{cause:e});throw e}}async deleteFile(t,i=!1){t=i?t:await this.resolveEntryName(t);if(t)try{await this.handle.removeEntry(t)}catch(e){if(i&&"NotFoundError"===e.name)return;if("QuotaExceededError"===e.name)throw new ge({cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new me(`File name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`File "${t}" could not be deleted (${e.name})`,{cause:e});throw e}}async getDirectory(t,e=this.caseSensitive){var i=e?t:await this.fixEntryCase(t);let s;try{s=await this.handle.getDirectoryHandle(i)}catch(e){if("NotFoundError"===e.name)throw new ue(`Directory "${t}" not found or parent directory "${this.handle.name}" is gone`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new me(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be read (${e.name})`,{cause:e});throw e}return new fe(s,e)}async getOrCreateDirectory(t,e=this.caseSensitive){var i=e?t:await this.fixEntryCase(t);try{return new fe(await this.handle.getDirectoryHandle(i,{create:!0}),e)}catch(e){if("QuotaExceededError"===e.name)throw new ge({cause:e});if("NotFoundError"===e.name)throw new ue(`Directory "${this.handle.name}" not found"`,{cause:e});if(e instanceof TypeError&&e.message.includes("not allowed"))throw new me(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be created (${e.name})`,{cause:e});throw e}}async deleteDirectory(t,e=!1){t=await this.resolveEntryName(t);if(t)try{await this.handle.removeEntry(t,{recursive:e})}catch(e){if("QuotaExceededError"===e.name)throw new ge({cause:e});if("InvalidModificationError"===e.name)throw new l("Can't delete non-empty directory when recursive = false");if(e instanceof TypeError&&e.message.includes("not allowed"))throw new me(`Directory name "${t}" is not allowed`,{cause:e});if(e instanceof DOMException)throw new l(`Directory "${t}" could not be deleted (${e.name})`,{cause:e});throw e}}}class ye{constructor(){this.directories=[]}addRootDirectoryHandle(e){this.rootDirectory=this.addDirectoryHandle(e),this.rootDirectoryHandle=e}getRootDirectoryHandle(){return this.rootDirectoryHandle}addDirectoryHandle(e){e=new fe(e);return this.directories.push(e),e}addDirectory(e){this.directories.push(e)}async getDirectory(e){var t=await this.findDirectory(e);if(!t)throw new Error(`Directory "${e}" not found in real file system`);return t}async findDirectory(e){for(const t of this.directories)if(await t.containsEntry(e))return await t.getDirectory(e)}getRootDirectory(){return this.rootDirectory}async containsEntry(e){for(const t of this.directories)if(await t.containsEntry(e))return!0;return!1}async openFile(e,t=!1){for(const i of this.directories)try{return await i.openFile(e,t)}catch(e){if(!(e instanceof ue))throw e}throw new ue(`File "${e}" not found in real file system`)}async getRawFile(e){for(const t of this.directories)if(await t.containsEntry(e))return await t.getRawFile(e);throw new Error(`File "${e}" not found in real file system`)}async*getEntries(){for(var e of this.directories)for await(var t of e.getEntries())yield t}}class we{constructor(e){this.resourceFactory=e,this.resources=new Map}setVfs(e){this.vfs=e}set(e,t){this.resources.set(e,t)}has(e){return!!this.resources.has(e)||(this.vfs?.fileExists(e)??!1)}get(e){let t;return t=this.resources.get(e),!t&&this.vfs?.fileExists(e)&&(t=this.resourceFactory(this.vfs.openFile(e)),this.resources.set(e,t)),t}clear(e){e?this.resources.delete(e):this.resources.clear()}}const Te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function be(s,e,r,t){if(-1<["32f","64"].indexOf(e)&&-1<["32f","64"].indexOf(t))r.set(s);else{Oe(e),Oe(t);let i=function(e,t){let i=function(e){return e};e!=t&&(i=["32f","64"].includes(e)?Se:["32f","64"].includes(t)?ke:ve);return i}(e,t);var a={oldMin:Math.pow(2,parseInt(e,10))/2,newMin:Math.pow(2,parseInt(t,10))/2,oldMax:Math.pow(2,parseInt(e,10))/2-1,newMax:Math.pow(2,parseInt(t,10))/2-1};_e(e,s,!0);for(let e=0,t=s.length;e<t;e++)r[e]=i(s[e],a);_e(t,r,!1)}}function ve(e,t){return e=0<e?parseInt(e/t.oldMax*t.newMax,10):parseInt(e/t.oldMin*t.newMin,10)}function Se(e,t){return parseInt(0<e?e*t.newMax:e*t.newMin,10)}function ke(e,t){return 0<e?e/t.oldMax:e/t.oldMin}function Oe(e){if("32f"!=e&&"64"!=e&&(parseInt(e,10)<"8"||"53"<parseInt(e,10)))throw new Error("Invalid bit depth.")}function _e(e,i,t){if("8"==e){var s=t?-128:128;for(let e=0,t=i.length;e<t;e++)i[e]=i[e]+=s}}const Ie=[-1,-1,-1,-1,2,4,6,8,-1,-1,-1,-1,2,4,6,8],Ce=[7,8,9,10,11,12,13,14,16,17,19,21,23,25,28,31,34,37,41,45,50,55,60,66,73,80,88,97,107,118,130,143,157,173,190,209,230,253,279,307,337,371,408,449,494,544,598,658,724,796,876,963,1060,1166,1282,1411,1552,1707,1878,2066,2272,2499,2749,3024,3327,3660,4026,4428,4871,5358,5894,6484,7132,7845,8630,9493,10442,11487,12635,13899,15289,16818,18500,20350,22385,24623,27086,29794,32767];function Ae(i){var s={index:0,predicted:0,step:7};let r=new Uint8Array(i.length),a=[],n=0,o=0;for(let e=0,t=i.length;e<t;e++)e%505==0&&0!=e&&(r.set(function(i,s){let r=function(e,t){xe(e,t);let i=[];return i.push(255&e),i.push(e>>8&255),i.push(t.index),i.push(0),i}(i[0],s);for(let e=3,t=i.length;e<t;e+=2){var a=xe(i[e],s),n=xe(i[e+1],s);r.push(n<<4|a)}return r}(a,s),n),n+=256,a=[],o++),a.push(i[e]);let e=i.length/2;return e%2&&e++,r.slice(0,e+512+4*o)}function Be(t,e=256){var i={index:0,predicted:0,step:7};let s=new Int16Array(2*t.length),r=[],a=0,n=t.length,o=0;for(;0<n;){var h=Math.min(n,e);for(let e=0;e<h;e++)r.push(t[o]),o++;var l=function(i,s){s.predicted=function(e){return 32767<e?e-65536:e}(i[1]<<8|i[0]),s.index=i[2],s.step=Ce[s.index];let r=[s.predicted];for(let e=4,t=i.length;e<t;e++){var a=i[e],n=a>>4,a=n<<4^a;r.push(Ee(a,s)),r.push(Ee(n,s))}return r}(r,i);s.set(l,a),a+=l.length,r=[],n-=e}return s.slice(0,a)}function xe(e,t){let i=e-t.predicted,s=0;0<=i?s=0:(s=8,i=-i);let r=Ce[t.index],a=r>>3;return i>r&&(s|=4,i-=r,a+=r),r>>=1,i>r&&(s|=2,i-=r,a+=r),r>>=1,i>r&&(s|=1,a+=r),function(e,t,i){8&e?i.predicted-=t:i.predicted+=t;i.predicted<-32768?i.predicted=-32768:32767<i.predicted&&(i.predicted=32767);i.index+=Ie[7&e],i.index<0?i.index=0:88<i.index&&(i.index=88)}(s,a,t),s}function Ee(e,t){let i=0;return 4&e&&(i+=t.step),2&e&&(i+=t.step>>1),1&e&&(i+=t.step>>2),i+=t.step>>3,8&e&&(i=-i),t.predicted+=i,32767<t.predicted?t.predicted=32767:t.predicted<-32768&&(t.predicted=-32768),function(e,t){t.index+=Ie[e],t.index<0?t.index=0:88<t.index&&(t.index=88);t.step=Ce[t.index]}(e,t),t.predicted}const Pe=[1,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7];function Ne(i){let s=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=function(e){let t;var i,s=~(e=-32768==e?-32767:e)>>8&128;return s||(e*=-1),32635<e&&(e=32635),t=256<=e?(i=Pe[e>>8&127])<<4|e>>i+3&15:e>>4,85^t^s}(i[e]);return s}function Me(i){let s=new Int16Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=function(e){let t=0;0!=(128&(e^=85))&&(e&=-129,t=-1);var i=4+((240&e)>>4);let s=0;return s=4!=i?1<<i|(15&e)<<i-4|1<<i-5:e<<1|1,s=0===t?s:-s,8*s*-1}(i[e]);return s}const De=132,Re=32635,Le=[0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7],Fe=[0,132,396,924,1980,4092,8316,16764];function je(i){let s=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=(r=i[e],a=void 0,0!=(a=r>>8&128)&&(r=-r),(r+=De)>Re&&(r=Re),~(a|(a=Le[r>>7&255])<<4|r>>a+3&15));var r,a;return s}function Ue(i){let s=new Int16Array(i.length);for(let e=0,t=i.length;e<t;e++)s[e]=function(e){var t,i;let s;return t=128&(e=~e),i=e>>4&7,e=15&e,s=Fe[i]+(e<<3+i),0!=t&&(s=-s),s}(i[e]);return s}function We(t,i,s=0,r=t.length){for(let e=s;e<r;e+=i)!function(t,i,s){i--;for(let e=0;e<i;e++){var r=t[s+e];t[s+e]=t[s+i],t[s+i]=r,i--}}(t,i,e)}function ze(e,i,s=0){let r=0;for(var t=e.length;r<t;){var a=e.codePointAt(r);if(a<128)i[s]=a,s++;else{let e=0,t=0;for(a<=2047?(e=1,t=192):a<=65535?(e=2,t=224):a<=1114111&&(e=3,t=240,r++),i[s]=(a>>6*e)+t,s++;0<e;)i[s]=128|a>>6*(e-1)&63,s++,e--}r++}return s}const Ve=new Array(8).fill(0).map((e,t)=>Math.pow(2,8*t));class He{constructor(e,t=!1){this.bits=e,this.offset=Math.ceil(e/8),this.max=Math.pow(2,e)-1,this.min=0,this.unpack=this.unpack_,t&&(this.max=Math.pow(2,e)/2-1,this.min=-this.max-1,this.unpack=this.unpackSigned_)}pack(i,s,r=0){s=this.clamp_(Math.round(s));for(let e=0,t=this.offset;e<t;e++)i[r]=255&Math.floor(s/Ve[e]),r++;return r}unpack_(t,i=0){let s=0;for(let e=0;e<this.offset;e++)s+=t[i+e]*Ve[e];return s}unpackSigned_(e,t=0){return this.sign_(this.unpack_(e,t))}clamp_(e){return e>this.max?this.max:e<this.min?this.min:e}sign_(e){return e>this.max&&(e-=2*this.max+2),e}}class Ge{constructor(e,t){this.offset=Math.ceil((e+t)/8),this.ebits=e,this.fbits=t,this.bias=(1<<e-1)-1,this.biasP2=Math.pow(2,this.bias+1),this.ebitsFbits=e+t,this.fbias=Math.pow(2,-(8*this.offset-1-e))}pack(e,t,i){var s=((t=+(t=Math.abs(t)>this.biasP2-2*this.ebitsFbits?t<0?-1/0:1/0:t))||1/t)<0||t<0?1:0;t=Math.abs(t);let r=Math.min(Math.floor(Math.log(t)/Math.LN2),1023),a=$e(t/Math.pow(2,r)*Math.pow(2,this.fbits));return t!=t?(a=Math.pow(2,this.fbits-1),r=(1<<this.ebits)-1):0!==t&&(t>=Math.pow(2,1-this.bias)?(2<=a/Math.pow(2,this.fbits)&&(r+=1,a=1),a=r>this.bias?(r=(1<<this.ebits)-1,0):(r+=this.bias,$e(a)-Math.pow(2,this.fbits))):(a=$e(t/Math.pow(2,1-this.bias-this.fbits)),r=0)),this.packFloatBits_(e,i,s,r,a)}unpack(t,i){var e=(1<<this.ebits)-1;let s,r="";for(let e=this.offset-1;0<=e;e--){var a=t[e+i].toString(2);r+="00000000".substring(a.length)+a}var n="1"==r.charAt(0)?-1:1;r=r.substring(1);let o=parseInt(r.substring(0,this.ebits),2);return r=r.substring(this.ebits),o==e?0!==parseInt(r,2)?NaN:1/0*n:(s=0===o?(o+=1,parseInt(r,2)):parseInt("1"+r,2),n*s*this.fbias*Math.pow(2,o-this.bias))}packFloatBits_(e,t,i,s,r){let a=[];a.push(i);for(let e=this.ebits;0<e;--e)a[e]=s%2?1:0,s=Math.floor(s/2);var n=a.length;for(let e=this.fbits;0<e;--e)a[n+e]=r%2?1:0,r=Math.floor(r/2);let o=a.join(""),h=this.offset+t-1,l=t;for(;h>=t;)e[h]=parseInt(o.substring(0,8),2),o=o.substring(8),h--,l++;return l}}function $e(e){var t=Math.floor(e),e=e-t;return!(e<.5)&&(.5<e||t%2)?t+1:t}function qe(e,t=0,i=e.length){return function(o,e=0,t=o.length){let h="";for(let n=e;n<t;){let i=128,s=191,r=!1,a=o[n++];if(0<=a&&a<=127)h+=String.fromCharCode(a);else{let t=0;194<=a&&a<=223?t=1:224<=a&&a<=239?(t=2,224===o[n]&&(i=160),237===o[n]&&(s=159)):240<=a&&a<=244?(t=3,240===o[n]&&(i=144),244===o[n]&&(s=143)):r=!0,a&=(1<<8-t-1)-1;for(let e=0;e<t;e++)(o[n]<i||o[n]>s)&&(r=!0),a=a<<6|63&o[n],n++;r?h+=String.fromCharCode(65533):a<=65535?h+=String.fromCharCode(a):(a-=65536,h+=String.fromCharCode(55296+(a>>10&1023),56320+(1023&a)))}}return h}(e,t,i)}function Xe(e){var t=[];return ze(e,t),t}function Ze(e,t,i=0){return ze(e,t,i)}function Qe(e,t,i,s=0){let r=it((t=t||{}).bits,t.fp,t.signed);var a=Math.ceil(t.bits/8);let n=0;for(var o=s,h=e.length;n<h;n++)s=r.pack(i,e[n],s);return t.be&&We(i,a,o,s),s}function Ye(e,t,i,s=0,r=e.length){var a,n=it((t=t||{}).bits,t.fp,t.signed);r=function(e,t,i){i=(t-e)%i;return t-i}(s,r,n.offset),t.be?(a=new Uint8Array(e),t.be&&We(a,n.offset,s,r),tt(a,i,s,r,n)):tt(e,i,s,r,n)}function Ke(e,t,i,s=0){return Qe([e],t,i,s)}function Je(e,t){var i=[];return Ke(e,t,i,0),i}function et(e,t,i=0){var s=[];return Ye(e,t,s,i,i+Math.ceil(t.bits/8)),s[0]}function tt(i,s,r,a,n){var o=n.offset;for(let e=0,t=r;t<a;t+=o,e++)s[e]=n.unpack(i,t)}function it(e,t,i){return t&&32==e?new Ge(8,23):t&&64==e?new Ge(11,52):new He(e,i)}function st(e,t){let i=Xe(e);for(let e=i.length;e<t;e++)i.push(0);return i}(class qm extends class{constructor(){this.container="",this.chunkSize=0,this.format="",this.signature=null,this.head=0,this.uInt32={bits:32,be:!1},this.supported_containers=["RIFF","RIFX"]}setSignature(e){if(this.head=0,this.container=this.readString(e,4),-1===this.supported_containers.indexOf(this.container))throw Error("Not a supported format.");this.uInt32.be="RIFX"===this.container,this.chunkSize=this.readUInt32(e),this.format=this.readString(e,4),this.signature={chunkId:this.container,chunkSize:this.chunkSize,format:this.format,subChunks:this.getSubChunksIndex_(e)}}findChunk(t,i=!1){var s=this.signature.subChunks;let r=[];for(let e=0;e<s.length;e++)if(s[e].chunkId==t){if(!i)return s[e];r.push(s[e])}return"LIST"==t&&r.length?r:null}readString(e,t){e=qe(e,this.head,this.head+t);return this.head+=t,e}readUInt32(e){return e=et(e,this.uInt32,this.head),this.head+=4,e}getSubChunksIndex_(e){let t=[],i=this.head;for(;i<=e.length-8;)t.push(this.getSubChunkIndex_(e,i)),i+=8+t[t.length-1].chunkSize,i=i%2?i+1:i;return t}getSubChunkIndex_(e,t){let i={chunkId:this.getChunkId_(e,t),chunkSize:this.getChunkSize_(e,t)};return"LIST"==i.chunkId?(i.format=qe(e,t+8,t+12),this.head+=4,i.subChunks=this.getSubChunksIndex_(e)):(e=i.chunkSize%2?i.chunkSize+1:i.chunkSize,this.head=t+8+e,i.chunkData={start:t+8,end:this.head}),i}getChunkId_(e,t){return this.head+=4,qe(e,t,t+4)}getChunkSize_(e,t){return this.head+=4,et(e,this.uInt32,t+4)}}{constructor(){super(),this.supported_containers.push("RF64"),this.fmt={chunkId:"",chunkSize:0,audioFormat:0,numChannels:0,sampleRate:0,byteRate:0,blockAlign:0,bitsPerSample:0,cbSize:0,validBitsPerSample:0,dwChannelMask:0,subformat:[]},this.fact={chunkId:"",chunkSize:0,dwSampleLength:0},this.cue={chunkId:"",chunkSize:0,dwCuePoints:0,points:[]},this.smpl={chunkId:"",chunkSize:0,dwManufacturer:0,dwProduct:0,dwSamplePeriod:0,dwMIDIUnityNote:0,dwMIDIPitchFraction:0,dwSMPTEFormat:0,dwSMPTEOffset:0,dwNumSampleLoops:0,dwSamplerData:0,loops:[]},this.bext={chunkId:"",chunkSize:0,description:"",originator:"",originatorReference:"",originationDate:"",originationTime:"",timeReference:[0,0],version:0,UMID:"",loudnessValue:0,loudnessRange:0,maxTruePeakLevel:0,maxMomentaryLoudness:0,maxShortTermLoudness:0,reserved:"",codingHistory:""},this.iXML={chunkId:"",chunkSize:0,value:""},this.ds64={chunkId:"",chunkSize:0,riffSizeHigh:0,riffSizeLow:0,dataSizeHigh:0,dataSizeLow:0,originationTime:0,sampleCountHigh:0,sampleCountLow:0},this.data={chunkId:"",chunkSize:0,samples:new Uint8Array(0)},this.LIST=[],this.junk={chunkId:"",chunkSize:0,chunkData:[]},this._PMX={chunkId:"",chunkSize:0,value:""},this.uInt16={bits:16,be:!1,signed:!1,fp:!1}}fromBuffer(e,t=!0){if(this.clearHeaders(),this.setSignature(e),this.uInt16.be=this.uInt32.be,"WAVE"!=this.format)throw Error('Could not find the "WAVE" format identifier');this.readDs64Chunk_(e),this.readFmtChunk_(e),this.readFactChunk_(e),this.readBextChunk_(e),this.readiXMLChunk_(e),this.readCueChunk_(e),this.readSmplChunk_(e),this.readDataChunk_(e,t),this.readJunkChunk_(e),this.readLISTChunk_(e),this.read_PMXChunk_(e)}clearHeaders(){var e=new qm;Object.assign(this.fmt,e.fmt),Object.assign(this.fact,e.fact),Object.assign(this.cue,e.cue),Object.assign(this.smpl,e.smpl),Object.assign(this.bext,e.bext),Object.assign(this.iXML,e.iXML),Object.assign(this.ds64,e.ds64),Object.assign(this.data,e.data),this.LIST=[],Object.assign(this.junk,e.junk),Object.assign(this._PMX,e._PMX)}readFmtChunk_(e){var t=this.findChunk("fmt ");if(!t)throw Error('Could not find the "fmt " chunk');this.head=t.chunkData.start,this.fmt.chunkId=t.chunkId,this.fmt.chunkSize=t.chunkSize,this.fmt.audioFormat=this.readUInt16_(e),this.fmt.numChannels=this.readUInt16_(e),this.fmt.sampleRate=this.readUInt32(e),this.fmt.byteRate=this.readUInt32(e),this.fmt.blockAlign=this.readUInt16_(e),this.fmt.bitsPerSample=this.readUInt16_(e),this.readFmtExtension_(e)}readFmtExtension_(e){16<this.fmt.chunkSize&&(this.fmt.cbSize=this.readUInt16_(e),18<this.fmt.chunkSize&&(this.fmt.validBitsPerSample=this.readUInt16_(e),20<this.fmt.chunkSize&&(this.fmt.dwChannelMask=this.readUInt32(e),this.fmt.subformat=[this.readUInt32(e),this.readUInt32(e),this.readUInt32(e),this.readUInt32(e)])))}readFactChunk_(e){var t=this.findChunk("fact");t&&(this.head=t.chunkData.start,this.fact.chunkId=t.chunkId,this.fact.chunkSize=t.chunkSize,this.fact.dwSampleLength=this.readUInt32(e))}readCueChunk_(t){var e=this.findChunk("cue ");if(e){this.head=e.chunkData.start,this.cue.chunkId=e.chunkId,this.cue.chunkSize=e.chunkSize,this.cue.dwCuePoints=this.readUInt32(t);for(let e=0;e<this.cue.dwCuePoints;e++)this.cue.points.push({dwName:this.readUInt32(t),dwPosition:this.readUInt32(t),fccChunk:this.readString(t,4),dwChunkStart:this.readUInt32(t),dwBlockStart:this.readUInt32(t),dwSampleOffset:this.readUInt32(t)})}}readSmplChunk_(t){var e=this.findChunk("smpl");if(e){this.head=e.chunkData.start,this.smpl.chunkId=e.chunkId,this.smpl.chunkSize=e.chunkSize,this.smpl.dwManufacturer=this.readUInt32(t),this.smpl.dwProduct=this.readUInt32(t),this.smpl.dwSamplePeriod=this.readUInt32(t),this.smpl.dwMIDIUnityNote=this.readUInt32(t),this.smpl.dwMIDIPitchFraction=this.readUInt32(t),this.smpl.dwSMPTEFormat=this.readUInt32(t),this.smpl.dwSMPTEOffset=this.readUInt32(t),this.smpl.dwNumSampleLoops=this.readUInt32(t),this.smpl.dwSamplerData=this.readUInt32(t);for(let e=0;e<this.smpl.dwNumSampleLoops;e++)this.smpl.loops.push({dwName:this.readUInt32(t),dwType:this.readUInt32(t),dwStart:this.readUInt32(t),dwEnd:this.readUInt32(t),dwFraction:this.readUInt32(t),dwPlayCount:this.readUInt32(t)})}}readDataChunk_(e,t){var i=this.findChunk("data");if(!i)throw Error('Could not find the "data" chunk');this.data.chunkId="data",this.data.chunkSize=i.chunkSize,t&&(this.data.samples=e.slice(i.chunkData.start,i.chunkData.end))}readBextChunk_(e){var t=this.findChunk("bext");t&&(this.head=t.chunkData.start,this.bext.chunkId=t.chunkId,this.bext.chunkSize=t.chunkSize,this.bext.description=this.readString(e,256),this.bext.originator=this.readString(e,32),this.bext.originatorReference=this.readString(e,32),this.bext.originationDate=this.readString(e,10),this.bext.originationTime=this.readString(e,8),this.bext.timeReference=[this.readUInt32(e),this.readUInt32(e)],this.bext.version=this.readUInt16_(e),this.bext.UMID=this.readString(e,64),this.bext.loudnessValue=this.readUInt16_(e),this.bext.loudnessRange=this.readUInt16_(e),this.bext.maxTruePeakLevel=this.readUInt16_(e),this.bext.maxMomentaryLoudness=this.readUInt16_(e),this.bext.maxShortTermLoudness=this.readUInt16_(e),this.bext.reserved=this.readString(e,180),this.bext.codingHistory=this.readString(e,this.bext.chunkSize-602))}readiXMLChunk_(e){var t=this.findChunk("iXML");t&&(this.head=t.chunkData.start,this.iXML.chunkId=t.chunkId,this.iXML.chunkSize=t.chunkSize,this.iXML.value=qe(e,this.head,this.head+this.iXML.chunkSize))}readDs64Chunk_(e){var t=this.findChunk("ds64");if(t)this.head=t.chunkData.start,this.ds64.chunkId=t.chunkId,this.ds64.chunkSize=t.chunkSize,this.ds64.riffSizeHigh=this.readUInt32(e),this.ds64.riffSizeLow=this.readUInt32(e),this.ds64.dataSizeHigh=this.readUInt32(e),this.ds64.dataSizeLow=this.readUInt32(e),this.ds64.originationTime=this.readUInt32(e),this.ds64.sampleCountHigh=this.readUInt32(e),this.ds64.sampleCountLow=this.readUInt32(e);else if("RF64"==this.container)throw Error('Could not find the "ds64" chunk')}readLISTChunk_(t){var i=this.findChunk("LIST",!0);if(null!==i)for(let e=0;e<i.length;e++){var s=i[e];this.LIST.push({chunkId:s.chunkId,chunkSize:s.chunkSize,format:s.format,subChunks:[]});for(let e=0;e<s.subChunks.length;e++)this.readLISTSubChunks_(s.subChunks[e],s.format,t)}}readLISTSubChunks_(e,t,i){"adtl"==t?-1<["labl","note","ltxt"].indexOf(e.chunkId)&&this.readLISTadtlSubChunks_(i,e):"INFO"==t&&this.readLISTINFOSubChunks_(i,e)}readLISTadtlSubChunks_(e,t){this.head=t.chunkData.start;let i={chunkId:t.chunkId,chunkSize:t.chunkSize,dwName:this.readUInt32(e)};"ltxt"==t.chunkId?(i.dwSampleLength=this.readUInt32(e),i.dwPurposeID=this.readUInt32(e),i.dwCountry=this.readUInt16_(e),i.dwLanguage=this.readUInt16_(e),i.dwDialect=this.readUInt16_(e),i.dwCodePage=this.readUInt16_(e),i.value=""):i.value=this.readZSTR_(e,this.head),this.LIST[this.LIST.length-1].subChunks.push(i)}readLISTINFOSubChunks_(e,t){this.head=t.chunkData.start,this.LIST[this.LIST.length-1].subChunks.push({chunkId:t.chunkId,chunkSize:t.chunkSize,value:this.readZSTR_(e,this.head)})}readJunkChunk_(e){var t=this.findChunk("junk");t&&(this.junk={chunkId:t.chunkId,chunkSize:t.chunkSize,chunkData:[].slice.call(e.slice(t.chunkData.start,t.chunkData.end))})}read_PMXChunk_(e){var t=this.findChunk("_PMX");t&&(this.head=t.chunkData.start,this._PMX.chunkId=t.chunkId,this._PMX.chunkSize=t.chunkSize,this._PMX.value=qe(e,this.head,this.head+this._PMX.chunkSize))}readZSTR_(t,i=0){for(let e=i;e<t.length&&(this.head++,0!==t[e]);e++);return qe(t,i,this.head-1)}readUInt16_(e){return e=et(e,this.uInt16,this.head),this.head+=2,e}});function rt(e,t,i){return!(i<1||4294967295<e*(t/8)*i)}class at extends class extends class qm extends class{constructor(){this.container="",this.chunkSize=0,this.format="",this.signature=null,this.head=0,this.uInt32={bits:32,be:!1},this.supported_containers=["RIFF","RIFX"]}setSignature(e){if(this.head=0,this.container=this.readString(e,4),-1===this.supported_containers.indexOf(this.container))throw Error("Not a supported format.");this.uInt32.be="RIFX"===this.container,this.chunkSize=this.readUInt32(e),this.format=this.readString(e,4),this.signature={chunkId:this.container,chunkSize:this.chunkSize,format:this.format,subChunks:this.getSubChunksIndex_(e)}}findChunk(t,i=!1){var s=this.signature.subChunks;let r=[];for(let e=0;e<s.length;e++)if(s[e].chunkId==t){if(!i)return s[e];r.push(s[e])}return"LIST"==t&&r.length?r:null}readString(e,t){e=qe(e,this.head,this.head+t);return this.head+=t,e}readUInt32(e){return e=et(e,this.uInt32,this.head),this.head+=4,e}getSubChunksIndex_(e){let t=[],i=this.head;for(;i<=e.length-8;)t.push(this.getSubChunkIndex_(e,i)),i+=8+t[t.length-1].chunkSize,i=i%2?i+1:i;return t}getSubChunkIndex_(e,t){let i={chunkId:this.getChunkId_(e,t),chunkSize:this.getChunkSize_(e,t)};return"LIST"==i.chunkId?(i.format=qe(e,t+8,t+12),this.head+=4,i.subChunks=this.getSubChunksIndex_(e)):(e=i.chunkSize%2?i.chunkSize+1:i.chunkSize,this.head=t+8+e,i.chunkData={start:t+8,end:this.head}),i}getChunkId_(e,t){return this.head+=4,qe(e,t,t+4)}getChunkSize_(e,t){return this.head+=4,et(e,this.uInt32,t+4)}}{constructor(){super(),this.supported_containers.push("RF64"),this.fmt={chunkId:"",chunkSize:0,audioFormat:0,numChannels:0,sampleRate:0,byteRate:0,blockAlign:0,bitsPerSample:0,cbSize:0,validBitsPerSample:0,dwChannelMask:0,subformat:[]},this.fact={chunkId:"",chunkSize:0,dwSampleLength:0},this.cue={chunkId:"",chunkSize:0,dwCuePoints:0,points:[]},this.smpl={chunkId:"",chunkSize:0,dwManufacturer:0,dwProduct:0,dwSamplePeriod:0,dwMIDIUnityNote:0,dwMIDIPitchFraction:0,dwSMPTEFormat:0,dwSMPTEOffset:0,dwNumSampleLoops:0,dwSamplerData:0,loops:[]},this.bext={chunkId:"",chunkSize:0,description:"",originator:"",originatorReference:"",originationDate:"",originationTime:"",timeReference:[0,0],version:0,UMID:"",loudnessValue:0,loudnessRange:0,maxTruePeakLevel:0,maxMomentaryLoudness:0,maxShortTermLoudness:0,reserved:"",codingHistory:""},this.iXML={chunkId:"",chunkSize:0,value:""},this.ds64={chunkId:"",chunkSize:0,riffSizeHigh:0,riffSizeLow:0,dataSizeHigh:0,dataSizeLow:0,originationTime:0,sampleCountHigh:0,sampleCountLow:0},this.data={chunkId:"",chunkSize:0,samples:new Uint8Array(0)},this.LIST=[],this.junk={chunkId:"",chunkSize:0,chunkData:[]},this._PMX={chunkId:"",chunkSize:0,value:""},this.uInt16={bits:16,be:!1,signed:!1,fp:!1}}fromBuffer(e,t=!0){if(this.clearHeaders(),this.setSignature(e),this.uInt16.be=this.uInt32.be,"WAVE"!=this.format)throw Error('Could not find the "WAVE" format identifier');this.readDs64Chunk_(e),this.readFmtChunk_(e),this.readFactChunk_(e),this.readBextChunk_(e),this.readiXMLChunk_(e),this.readCueChunk_(e),this.readSmplChunk_(e),this.readDataChunk_(e,t),this.readJunkChunk_(e),this.readLISTChunk_(e),this.read_PMXChunk_(e)}clearHeaders(){var e=new qm;Object.assign(this.fmt,e.fmt),Object.assign(this.fact,e.fact),Object.assign(this.cue,e.cue),Object.assign(this.smpl,e.smpl),Object.assign(this.bext,e.bext),Object.assign(this.iXML,e.iXML),Object.assign(this.ds64,e.ds64),Object.assign(this.data,e.data),this.LIST=[],Object.assign(this.junk,e.junk),Object.assign(this._PMX,e._PMX)}readFmtChunk_(e){var t=this.findChunk("fmt ");if(!t)throw Error('Could not find the "fmt " chunk');this.head=t.chunkData.start,this.fmt.chunkId=t.chunkId,this.fmt.chunkSize=t.chunkSize,this.fmt.audioFormat=this.readUInt16_(e),this.fmt.numChannels=this.readUInt16_(e),this.fmt.sampleRate=this.readUInt32(e),this.fmt.byteRate=this.readUInt32(e),this.fmt.blockAlign=this.readUInt16_(e),this.fmt.bitsPerSample=this.readUInt16_(e),this.readFmtExtension_(e)}readFmtExtension_(e){16<this.fmt.chunkSize&&(this.fmt.cbSize=this.readUInt16_(e),18<this.fmt.chunkSize&&(this.fmt.validBitsPerSample=this.readUInt16_(e),20<this.fmt.chunkSize&&(this.fmt.dwChannelMask=this.readUInt32(e),this.fmt.subformat=[this.readUInt32(e),this.readUInt32(e),this.readUInt32(e),this.readUInt32(e)])))}readFactChunk_(e){var t=this.findChunk("fact");t&&(this.head=t.chunkData.start,this.fact.chunkId=t.chunkId,this.fact.chunkSize=t.chunkSize,this.fact.dwSampleLength=this.readUInt32(e))}readCueChunk_(t){var e=this.findChunk("cue ");if(e){this.head=e.chunkData.start,this.cue.chunkId=e.chunkId,this.cue.chunkSize=e.chunkSize,this.cue.dwCuePoints=this.readUInt32(t);for(let e=0;e<this.cue.dwCuePoints;e++)this.cue.points.push({dwName:this.readUInt32(t),dwPosition:this.readUInt32(t),fccChunk:this.readString(t,4),dwChunkStart:this.readUInt32(t),dwBlockStart:this.readUInt32(t),dwSampleOffset:this.readUInt32(t)})}}readSmplChunk_(t){var e=this.findChunk("smpl");if(e){this.head=e.chunkData.start,this.smpl.chunkId=e.chunkId,this.smpl.chunkSize=e.chunkSize,this.smpl.dwManufacturer=this.readUInt32(t),this.smpl.dwProduct=this.readUInt32(t),this.smpl.dwSamplePeriod=this.readUInt32(t),this.smpl.dwMIDIUnityNote=this.readUInt32(t),this.smpl.dwMIDIPitchFraction=this.readUInt32(t),this.smpl.dwSMPTEFormat=this.readUInt32(t),this.smpl.dwSMPTEOffset=this.readUInt32(t),this.smpl.dwNumSampleLoops=this.readUInt32(t),this.smpl.dwSamplerData=this.readUInt32(t);for(let e=0;e<this.smpl.dwNumSampleLoops;e++)this.smpl.loops.push({dwName:this.readUInt32(t),dwType:this.readUInt32(t),dwStart:this.readUInt32(t),dwEnd:this.readUInt32(t),dwFraction:this.readUInt32(t),dwPlayCount:this.readUInt32(t)})}}readDataChunk_(e,t){var i=this.findChunk("data");if(!i)throw Error('Could not find the "data" chunk');this.data.chunkId="data",this.data.chunkSize=i.chunkSize,t&&(this.data.samples=e.slice(i.chunkData.start,i.chunkData.end))}readBextChunk_(e){var t=this.findChunk("bext");t&&(this.head=t.chunkData.start,this.bext.chunkId=t.chunkId,this.bext.chunkSize=t.chunkSize,this.bext.description=this.readString(e,256),this.bext.originator=this.readString(e,32),this.bext.originatorReference=this.readString(e,32),this.bext.originationDate=this.readString(e,10),this.bext.originationTime=this.readString(e,8),this.bext.timeReference=[this.readUInt32(e),this.readUInt32(e)],this.bext.version=this.readUInt16_(e),this.bext.UMID=this.readString(e,64),this.bext.loudnessValue=this.readUInt16_(e),this.bext.loudnessRange=this.readUInt16_(e),this.bext.maxTruePeakLevel=this.readUInt16_(e),this.bext.maxMomentaryLoudness=this.readUInt16_(e),this.bext.maxShortTermLoudness=this.readUInt16_(e),this.bext.reserved=this.readString(e,180),this.bext.codingHistory=this.readString(e,this.bext.chunkSize-602))}readiXMLChunk_(e){var t=this.findChunk("iXML");t&&(this.head=t.chunkData.start,this.iXML.chunkId=t.chunkId,this.iXML.chunkSize=t.chunkSize,this.iXML.value=qe(e,this.head,this.head+this.iXML.chunkSize))}readDs64Chunk_(e){var t=this.findChunk("ds64");if(t)this.head=t.chunkData.start,this.ds64.chunkId=t.chunkId,this.ds64.chunkSize=t.chunkSize,this.ds64.riffSizeHigh=this.readUInt32(e),this.ds64.riffSizeLow=this.readUInt32(e),this.ds64.dataSizeHigh=this.readUInt32(e),this.ds64.dataSizeLow=this.readUInt32(e),this.ds64.originationTime=this.readUInt32(e),this.ds64.sampleCountHigh=this.readUInt32(e),this.ds64.sampleCountLow=this.readUInt32(e);else if("RF64"==this.container)throw Error('Could not find the "ds64" chunk')}readLISTChunk_(t){var i=this.findChunk("LIST",!0);if(null!==i)for(let e=0;e<i.length;e++){var s=i[e];this.LIST.push({chunkId:s.chunkId,chunkSize:s.chunkSize,format:s.format,subChunks:[]});for(let e=0;e<s.subChunks.length;e++)this.readLISTSubChunks_(s.subChunks[e],s.format,t)}}readLISTSubChunks_(e,t,i){"adtl"==t?-1<["labl","note","ltxt"].indexOf(e.chunkId)&&this.readLISTadtlSubChunks_(i,e):"INFO"==t&&this.readLISTINFOSubChunks_(i,e)}readLISTadtlSubChunks_(e,t){this.head=t.chunkData.start;let i={chunkId:t.chunkId,chunkSize:t.chunkSize,dwName:this.readUInt32(e)};"ltxt"==t.chunkId?(i.dwSampleLength=this.readUInt32(e),i.dwPurposeID=this.readUInt32(e),i.dwCountry=this.readUInt16_(e),i.dwLanguage=this.readUInt16_(e),i.dwDialect=this.readUInt16_(e),i.dwCodePage=this.readUInt16_(e),i.value=""):i.value=this.readZSTR_(e,this.head),this.LIST[this.LIST.length-1].subChunks.push(i)}readLISTINFOSubChunks_(e,t){this.head=t.chunkData.start,this.LIST[this.LIST.length-1].subChunks.push({chunkId:t.chunkId,chunkSize:t.chunkSize,value:this.readZSTR_(e,this.head)})}readJunkChunk_(e){var t=this.findChunk("junk");t&&(this.junk={chunkId:t.chunkId,chunkSize:t.chunkSize,chunkData:[].slice.call(e.slice(t.chunkData.start,t.chunkData.end))})}read_PMXChunk_(e){var t=this.findChunk("_PMX");t&&(this.head=t.chunkData.start,this._PMX.chunkId=t.chunkId,this._PMX.chunkSize=t.chunkSize,this._PMX.value=qe(e,this.head,this.head+this._PMX.chunkSize))}readZSTR_(t,i=0){for(let e=i;e<t.length&&(this.head++,0!==t[e]);e++);return qe(t,i,this.head-1)}readUInt16_(e){return e=et(e,this.uInt16,this.head),this.head+=2,e}}{toBuffer(){this.uInt16.be="RIFX"===this.container,this.uInt32.be=this.uInt16.be;var t=[this.getJunkBytes_(),this.getDs64Bytes_(),this.getBextBytes_(),this.getiXMLBytes_(),this.getFmtBytes_(),this.getFactBytes_(),Xe(this.data.chunkId),Je(this.data.samples.length,this.uInt32),this.data.samples,this.getCueBytes_(),this.getSmplBytes_(),this.getLISTBytes_(),this.get_PMXBytes_()];let i=0;for(let e=0;e<t.length;e++)i+=t[e].length;let s=new Uint8Array(i+12),r=0;r=Ze(this.container,s,r),r=Ke(i+4,this.uInt32,s,r),r=Ze(this.format,s,r);for(let e=0;e<t.length;e++)s.set(t[e],r),r+=t[e].length;return s}getBextBytes_(){let e=[];return this.enforceBext_(),this.bext.chunkId&&(this.bext.chunkSize=602+this.bext.codingHistory.length,e=e.concat(Xe(this.bext.chunkId),Je(602+this.bext.codingHistory.length,this.uInt32),st(this.bext.description,256),st(this.bext.originator,32),st(this.bext.originatorReference,32),st(this.bext.originationDate,10),st(this.bext.originationTime,8),Je(this.bext.timeReference[0],this.uInt32),Je(this.bext.timeReference[1],this.uInt32),Je(this.bext.version,this.uInt16),st(this.bext.UMID,64),Je(this.bext.loudnessValue,this.uInt16),Je(this.bext.loudnessRange,this.uInt16),Je(this.bext.maxTruePeakLevel,this.uInt16),Je(this.bext.maxMomentaryLoudness,this.uInt16),Je(this.bext.maxShortTermLoudness,this.uInt16),st(this.bext.reserved,180),st(this.bext.codingHistory,this.bext.codingHistory.length))),this.enforceByteLen_(e),e}enforceBext_(){for(var e in this.bext)if(this.bext.hasOwnProperty(e)&&this.bext[e]&&"timeReference"!=e){this.bext.chunkId="bext";break}(this.bext.timeReference[0]||this.bext.timeReference[1])&&(this.bext.chunkId="bext")}getiXMLBytes_(){let e=[];var t;return this.iXML.chunkId&&(t=Xe(this.iXML.value),this.iXML.chunkSize=t.length,e=e.concat(Xe(this.iXML.chunkId),Je(this.iXML.chunkSize,this.uInt32),t)),this.enforceByteLen_(e),e}getDs64Bytes_(){let e=[];return this.ds64.chunkId&&(e=e.concat(Xe(this.ds64.chunkId),Je(this.ds64.chunkSize,this.uInt32),Je(this.ds64.riffSizeHigh,this.uInt32),Je(this.ds64.riffSizeLow,this.uInt32),Je(this.ds64.dataSizeHigh,this.uInt32),Je(this.ds64.dataSizeLow,this.uInt32),Je(this.ds64.originationTime,this.uInt32),Je(this.ds64.sampleCountHigh,this.uInt32),Je(this.ds64.sampleCountLow,this.uInt32))),this.enforceByteLen_(e),e}getCueBytes_(){let e=[];var t;return this.cue.chunkId&&(t=this.getCuePointsBytes_(),e=e.concat(Xe(this.cue.chunkId),Je(t.length+4,this.uInt32),Je(this.cue.dwCuePoints,this.uInt32),t)),this.enforceByteLen_(e),e}getCuePointsBytes_(){let t=[];for(let e=0;e<this.cue.dwCuePoints;e++)t=t.concat(Je(this.cue.points[e].dwName,this.uInt32),Je(this.cue.points[e].dwPosition,this.uInt32),Xe(this.cue.points[e].fccChunk),Je(this.cue.points[e].dwChunkStart,this.uInt32),Je(this.cue.points[e].dwBlockStart,this.uInt32),Je(this.cue.points[e].dwSampleOffset,this.uInt32));return t}getSmplBytes_(){let e=[];var t;return this.smpl.chunkId&&(t=this.getSmplLoopsBytes_(),e=e.concat(Xe(this.smpl.chunkId),Je(t.length+36,this.uInt32),Je(this.smpl.dwManufacturer,this.uInt32),Je(this.smpl.dwProduct,this.uInt32),Je(this.smpl.dwSamplePeriod,this.uInt32),Je(this.smpl.dwMIDIUnityNote,this.uInt32),Je(this.smpl.dwMIDIPitchFraction,this.uInt32),Je(this.smpl.dwSMPTEFormat,this.uInt32),Je(this.smpl.dwSMPTEOffset,this.uInt32),Je(this.smpl.dwNumSampleLoops,this.uInt32),Je(this.smpl.dwSamplerData,this.uInt32),t)),this.enforceByteLen_(e),e}getSmplLoopsBytes_(){let t=[];for(let e=0;e<this.smpl.dwNumSampleLoops;e++)t=t.concat(Je(this.smpl.loops[e].dwName,this.uInt32),Je(this.smpl.loops[e].dwType,this.uInt32),Je(this.smpl.loops[e].dwStart,this.uInt32),Je(this.smpl.loops[e].dwEnd,this.uInt32),Je(this.smpl.loops[e].dwFraction,this.uInt32),Je(this.smpl.loops[e].dwPlayCount,this.uInt32));return t}getFactBytes_(){let e=[];return this.fact.chunkId&&(e=e.concat(Xe(this.fact.chunkId),Je(this.fact.chunkSize,this.uInt32),Je(this.fact.dwSampleLength,this.uInt32))),this.enforceByteLen_(e),e}getFmtBytes_(){if(this.fmt.chunkId){var e=[].concat(Xe(this.fmt.chunkId),Je(this.fmt.chunkSize,this.uInt32),Je(this.fmt.audioFormat,this.uInt16),Je(this.fmt.numChannels,this.uInt16),Je(this.fmt.sampleRate,this.uInt32),Je(this.fmt.byteRate,this.uInt32),Je(this.fmt.blockAlign,this.uInt16),Je(this.fmt.bitsPerSample,this.uInt16),this.getFmtExtensionBytes_());return this.enforceByteLen_(e),e}throw Error('Could not find the "fmt " chunk')}getFmtExtensionBytes_(){let e=[];return 16<this.fmt.chunkSize&&(e=e.concat(Je(this.fmt.cbSize,this.uInt16))),18<this.fmt.chunkSize&&(e=e.concat(Je(this.fmt.validBitsPerSample,this.uInt16))),20<this.fmt.chunkSize&&(e=e.concat(Je(this.fmt.dwChannelMask,this.uInt32))),24<this.fmt.chunkSize&&(e=e.concat(Je(this.fmt.subformat[0],this.uInt32),Je(this.fmt.subformat[1],this.uInt32),Je(this.fmt.subformat[2],this.uInt32),Je(this.fmt.subformat[3],this.uInt32))),e}getLISTBytes_(){let t=[];for(let e=0;e<this.LIST.length;e++){var i=this.getLISTSubChunksBytes_(this.LIST[e].subChunks,this.LIST[e].format);t=t.concat(Xe(this.LIST[e].chunkId),Je(i.length+4,this.uInt32),Xe(this.LIST[e].format),i)}return this.enforceByteLen_(t),t}getLISTSubChunksBytes_(i,s){let r=[];for(let e=0,t=i.length;e<t;e++)"INFO"==s?r=r.concat(this.getLISTINFOSubChunksBytes_(i[e])):"adtl"==s&&(r=r.concat(this.getLISTadtlSubChunksBytes_(i[e]))),this.enforceByteLen_(r);return r}getLISTINFOSubChunksBytes_(e){let t=[];var i=st(e.value,e.value.length);return t=t.concat(Xe(e.chunkId),Je(i.length+1,this.uInt32),i),t.push(0),t}getLISTadtlSubChunksBytes_(e){let t=[];var i;return-1<["labl","note"].indexOf(e.chunkId)?(i=st(e.value,e.value.length),t=t.concat(Xe(e.chunkId),Je(i.length+4+1,this.uInt32),Je(e.dwName,this.uInt32),i),t.push(0)):"ltxt"==e.chunkId&&(t=t.concat(this.getLtxtChunkBytes_(e))),t}getLtxtChunkBytes_(e){return[].concat(Xe(e.chunkId),Je(e.value.length+20,this.uInt32),Je(e.dwName,this.uInt32),Je(e.dwSampleLength,this.uInt32),Je(e.dwPurposeID,this.uInt32),Je(e.dwCountry,this.uInt16),Je(e.dwLanguage,this.uInt16),Je(e.dwDialect,this.uInt16),Je(e.dwCodePage,this.uInt16),st(e.value,e.value.length))}get_PMXBytes_(){let e=[];var t;return this._PMX.chunkId&&(t=Xe(this._PMX.value),this._PMX.chunkSize=t.length,e=e.concat(Xe(this._PMX.chunkId),Je(this._PMX.chunkSize,this.uInt32),t)),this.enforceByteLen_(e),e}getJunkBytes_(){let e=[];return this.junk.chunkId?e.concat(Xe(this.junk.chunkId),Je(this.junk.chunkData.length,this.uInt32),this.junk.chunkData):(this.enforceByteLen_(e),e)}enforceByteLen_(e){e.length%2&&e.push(0)}}{constructor(){super(),this.bitDepth="0",this.dataType={bits:0,be:!1},this.WAV_AUDIO_FORMATS={4:17,8:1,"8a":6,"8m":7,16:1,24:1,32:1,"32f":3,64:3}}fromScratch(e,t,i,s,r){r=r||{},this.clearHeaders(),this.newWavFile_(e,t,i,s,r)}fromBuffer(e,t=!0){super.fromBuffer(e,t),this.bitDepthFromFmt_(),this.updateDataType_()}toBuffer(){return this.validateWavHeader_(),super.toBuffer()}getSamples(e=!1,t=Float64Array){var i=new t(this.data.samples.length/(this.dataType.bits/8));return Ye(this.data.samples,this.dataType,i,0,this.data.samples.length),!e&&1<this.fmt.numChannels?function(s,r,t=Float64Array){let a=[];for(let e=0;e<r;e++)a[e]=new t(s.length/r);for(let i=0;i<r;i++)for(let e=i,t=0;e<s.length;e+=r,t++)a[i][t]=s[e];return a}(i,this.fmt.numChannels,t):i}getSample(e){if((e*=this.dataType.bits/8)+this.dataType.bits/8>this.data.samples.length)throw new Error("Range error");return et(this.data.samples.slice(e,e+this.dataType.bits/8),this.dataType)}setSample(e,t){if((e*=this.dataType.bits/8)+this.dataType.bits/8>this.data.samples.length)throw new Error("Range error");Ke(t,this.dataType,this.data.samples,e)}getiXML(){return this.iXML.value}setiXML(e){if("string"!=typeof e)throw new TypeError("iXML value must be a string.");this.iXML.value=e,this.iXML.chunkId="iXML"}get_PMX(){return this._PMX.value}set_PMX(e){if("string"!=typeof e)throw new TypeError("_PMX value must be a string.");this._PMX.value=e,this._PMX.chunkId="_PMX"}newWavFile_(e,t,i,s,r){r.container||(r.container="RIFF"),this.container=r.container,this.bitDepth=i,s=function(r){let a=[];if(0<r.length)if(r[0].constructor!==Number){a=new Float64Array(r[0].length*r.length);for(let i=0,e=r[0].length,s=0;i<e;i++)for(let e=0,t=r.length;e<t;e++,s++)a[s]=r[e][i]}else a=r;return a}(s),this.updateDataType_();var a=this.dataType.bits/8;this.data.samples=new Uint8Array(s.length*a),Qe(s,this.dataType,this.data.samples,0),this.makeWavHeader_(i,e,t,a,this.data.samples.length,r),this.data.chunkId="data",this.data.chunkSize=this.data.samples.length,this.validateWavHeader_()}makeWavHeader_(e,t,i,s,r,a){"4"==e?this.createADPCMHeader_(e,t,i,s,r,a):"8a"==e||"8m"==e?this.createALawMulawHeader_(e,t,i,s,r,a):-1==Object.keys(this.WAV_AUDIO_FORMATS).indexOf(e)||2<t?this.createExtensibleHeader_(e,t,i,s,r,a):this.createPCMHeader_(e,t,i,s,r,a)}createPCMHeader_(e,t,i,s,r,a){this.container=a.container,this.chunkSize=36+r,this.format="WAVE",this.bitDepth=e,this.fmt={chunkId:"fmt ",chunkSize:16,audioFormat:this.WAV_AUDIO_FORMATS[e]||65534,numChannels:t,sampleRate:i,byteRate:t*s*i,blockAlign:t*s,bitsPerSample:parseInt(e,10),cbSize:0,validBitsPerSample:0,dwChannelMask:0,subformat:[]}}createADPCMHeader_(e,t,i,s,r,a){this.createPCMHeader_(e,t,i,s,r,a),this.chunkSize=40+r,this.fmt.chunkSize=20,this.fmt.byteRate=4055,this.fmt.blockAlign=256,this.fmt.bitsPerSample=4,this.fmt.cbSize=2,this.fmt.validBitsPerSample=505,this.fact={chunkId:"fact",chunkSize:4,dwSampleLength:2*r}}createExtensibleHeader_(e,t,i,s,r,a){this.createPCMHeader_(e,t,i,s,r,a),this.chunkSize=60+r,this.fmt.chunkSize=40,this.fmt.bitsPerSample=1+(parseInt(e,10)-1|7),this.fmt.cbSize=22,this.fmt.validBitsPerSample=parseInt(e,10),this.fmt.dwChannelMask=function(e){let t=0;1===e?t=4:2===e?t=3:4===e?t=51:6===e?t=63:8===e&&(t=1599);return t}(t),this.fmt.subformat=[1,1048576,2852126848,1905997824]}createALawMulawHeader_(e,t,i,s,r,a){this.createPCMHeader_(e,t,i,s,r,a),this.chunkSize=40+r,this.fmt.chunkSize=20,this.fmt.cbSize=2,this.fmt.validBitsPerSample=8,this.fact={chunkId:"fact",chunkSize:4,dwSampleLength:r}}bitDepthFromFmt_(){3===this.fmt.audioFormat&&32===this.fmt.bitsPerSample?this.bitDepth="32f":6===this.fmt.audioFormat?this.bitDepth="8a":7===this.fmt.audioFormat?this.bitDepth="8m":this.bitDepth=this.fmt.bitsPerSample.toString()}validateBitDepth_(){if(this.WAV_AUDIO_FORMATS[this.bitDepth])return!0;if(8<parseInt(this.bitDepth,10)&&parseInt(this.bitDepth,10)<54)return!0;throw new Error("Invalid bit depth.")}updateDataType_(){this.dataType={bits:1+(parseInt(this.bitDepth,10)-1|7),fp:"32f"==this.bitDepth||"64"==this.bitDepth,signed:"8"!=this.bitDepth,be:"RIFX"==this.container},-1<["4","8a","8m"].indexOf(this.bitDepth)&&(this.dataType.bits=8,this.dataType.signed=!1)}validateWavHeader_(){if(this.validateBitDepth_(),e=this.fmt.numChannels,t=this.fmt.bitsPerSample,e<1||65535<e*t/8)throw new Error("Invalid number of channels.");var e,t;if(!rt(this.fmt.numChannels,this.fmt.bitsPerSample,this.fmt.sampleRate))throw new Error("Invalid sample rate.")}}class nt extends at{getTag(e){e=this.getTagIndex_(e);return null!==e.TAG?this.LIST[e.LIST].subChunks[e.TAG].value:null}setTag(e,t){e=function(i){{if(i.constructor!==String)throw new Error("Invalid tag name.");if(i.length<4)for(let e=0,t=4-i.length;e<t;e++)i+=" "}return i}(e);var i=this.getTagIndex_(e);null!==i.TAG?(this.LIST[i.LIST].subChunks[i.TAG].chunkSize=t.length+1,this.LIST[i.LIST].subChunks[i.TAG].value=t):null!==i.LIST?this.LIST[i.LIST].subChunks.push({chunkId:e,chunkSize:t.length+1,value:t}):(this.LIST.push({chunkId:"LIST",chunkSize:8+t.length+1,format:"INFO",subChunks:[]}),this.LIST[this.LIST.length-1].subChunks.push({chunkId:e,chunkSize:t.length+1,value:t}))}deleteTag(e){e=this.getTagIndex_(e);return null!==e.TAG&&(this.LIST[e.LIST].subChunks.splice(e.TAG,1),!0)}listTags(){var i=this.getLISTIndex("INFO");let s={};if(null!==i)for(let e=0,t=this.LIST[i].subChunks.length;e<t;e++)s[this.LIST[i].subChunks[e].chunkId]=this.LIST[i].subChunks[e].value;return s}getLISTIndex(i){for(let e=0,t=this.LIST.length;e<t;e++)if(this.LIST[e].format==i)return e;return null}getTagIndex_(s){let r={LIST:null,TAG:null};for(let i=0,e=this.LIST.length;i<e;i++)if("INFO"==this.LIST[i].format){r.LIST=i;for(let e=0,t=this.LIST[i].subChunks.length;e<t;e++)if(this.LIST[i].subChunks[e].chunkId==s){r.TAG=e;break}break}return r}}class ot extends nt{listCuePoints(){let i=this.getCuePoints_();for(let e=0,t=i.length;e<t;e++)i[e].position=i[e].dwSampleOffset/this.fmt.sampleRate*1e3,i[e].dwSampleLength?(i[e].end=i[e].dwSampleLength/this.fmt.sampleRate*1e3,i[e].end+=i[e].position):i[e].end=null,delete i[e].value;return i}setCuePoint(e){this.cue.chunkId="cue ",e.label||(e.label="");var t=this.getCuePoints_();this.clearLISTadtl_(),this.cue.points=[],e.dwSampleOffset=e.position*this.fmt.sampleRate/1e3,e.dwSampleLength=0,e.end&&(e.dwSampleLength=e.end*this.fmt.sampleRate/1e3-e.dwSampleOffset),0===t.length?this.setCuePoint_(e,1):this.setCuePointInOrder_(t,e),this.cue.dwCuePoints=this.cue.points.length}deleteCuePoint(t){this.cue.chunkId="cue ";var i=this.getCuePoints_();this.clearLISTadtl_();var s=this.cue.points.length;this.cue.points=[];for(let e=0;e<s;e++)e+1!==t&&this.setCuePoint_(i[e],e+1);this.cue.dwCuePoints=this.cue.points.length,this.cue.dwCuePoints?this.cue.chunkId="cue ":(this.cue.chunkId="",this.clearLISTadtl_())}updateLabel(i,s){var r=this.getLISTIndex("adtl");if(null!==r)for(let e=0,t=this.LIST[r].subChunks.length;e<t;e++)this.LIST[r].subChunks[e].dwName==i&&(this.LIST[r].subChunks[e].value=s)}getCuePoints_(){let i=[];for(let t=0;t<this.cue.points.length;t++){var s=this.cue.points[t];let e=this.getDataForCuePoint_(s.dwName);e.label=e.value||"",e.dwPosition=s.dwPosition,e.fccChunk=s.fccChunk,e.dwChunkStart=s.dwChunkStart,e.dwBlockStart=s.dwBlockStart,e.dwSampleOffset=s.dwSampleOffset,i.push(e)}return i}getDataForCuePoint_(e){var t=this.getLISTIndex("adtl"),i={};return null!==t&&this.getCueDataFromLIST_(i,t,e),i}getCueDataFromLIST_(i,s,r){for(let e=0,t=this.LIST[s].subChunks.length;e<t;e++){var a;this.LIST[s].subChunks[e].dwName==r&&(a=this.LIST[s].subChunks[e],i.value=a.value||i.value,i.dwName=a.dwName||0,i.dwSampleLength=a.dwSampleLength||0,i.dwPurposeID=a.dwPurposeID||0,i.dwCountry=a.dwCountry||0,i.dwLanguage=a.dwLanguage||0,i.dwDialect=a.dwDialect||0,i.dwCodePage=a.dwCodePage||0)}}setCuePoint_(e,t){this.cue.points.push({dwName:t,dwPosition:e.dwPosition||0,fccChunk:e.fccChunk||"data",dwChunkStart:e.dwChunkStart||0,dwBlockStart:e.dwBlockStart||0,dwSampleOffset:e.dwSampleOffset}),this.setLabl_(e,t)}setCuePointInOrder_(t,i){let s=!1;for(let e=0;e<t.length;e++)t[e].dwSampleOffset>i.dwSampleOffset&&!s?(this.setCuePoint_(i,e+1),this.setCuePoint_(t[e],e+2),s=!0):this.setCuePoint_(t[e],s?e+2:e+1);s||this.setCuePoint_(i,this.cue.points.length+1)}clearLISTadtl_(){for(let e=0,t=this.LIST.length;e<t;e++)"adtl"==this.LIST[e].format&&this.LIST.splice(e)}setLabl_(e,t){let i=this.getLISTIndex("adtl");null===i&&(this.LIST.push({chunkId:"LIST",chunkSize:4,format:"adtl",subChunks:[]}),i=this.LIST.length-1),this.setLabelText_(i,e,t),e.dwSampleLength&&this.setLtxtChunk_(i,e,t)}setLabelText_(e,t,i){this.LIST[e].subChunks.push({chunkId:"labl",chunkSize:4,dwName:i,value:t.label}),this.LIST[e].chunkSize+=12}setLtxtChunk_(e,t,i){this.LIST[e].subChunks.push({chunkId:"ltxt",chunkSize:20,dwName:i,dwSampleLength:t.dwSampleLength,dwPurposeID:t.dwPurposeID||0,dwCountry:t.dwCountry||0,dwLanguage:t.dwLanguage||0,dwDialect:t.dwDialect||0,dwCodePage:t.dwCodePage||0,value:t.label}),this.LIST[e].chunkSize+=28}}class ht{constructor(e,t,i){var s;this.length_=e,this.scaleFactor_=(e-1)/t,this.interpolate=this.sinc,"point"===i.method?this.interpolate=this.point:"linear"===i.method?this.interpolate=this.linear:"cubic"===i.method&&(this.interpolate=this.cubic),this.tangentFactor_=1-Math.max(0,Math.min(1,i.tension||0)),this.sincFilterSize_=i.sincFilterSize||1,this.kernel_=(s=i.sincWindow||lt,function(e){return(0!==(t=e)?Math.sin(Math.PI*t)/(Math.PI*t):1)*s(e);var t})}point(e,t){return this.getClippedInput_(Math.round(this.scaleFactor_*e),t)}linear(e,t){e=this.scaleFactor_*e;var i=Math.floor(e);return(1-(e-=i))*this.getClippedInput_(i,t)+e*this.getClippedInput_(i+1,t)}cubic(e,t){e=this.scaleFactor_*e;var i=Math.floor(e),s=[this.getTangent_(i,t),this.getTangent_(i+1,t)],r=[this.getClippedInput_(i,t),this.getClippedInput_(i+1,t)],t=(e-=i)*e,i=e*t;return(2*i-3*t+1)*r[0]+(i-2*t+e)*s[0]+(-2*i+3*t)*r[1]+(i-t)*s[1]}sinc(t,i){t=this.scaleFactor_*t;var e=Math.floor(t),s=e-this.sincFilterSize_+1,r=e+this.sincFilterSize_;let a=0;for(let e=s;e<=r;e++)a+=this.kernel_(t-e)*this.getClippedInput_(e,i);return a}getTangent_(e,t){return this.tangentFactor_*(this.getClippedInput_(e+1,t)-this.getClippedInput_(e-1,t))/2}getClippedInput_(e,t){return 0<=e&&e<this.length_?t[e]:0}}function lt(e){return Math.exp(-e/2*e/2)}const ct={point:!1,linear:!1,cubic:!0,sinc:!0},ut={IIR:16,FIR:71},dt={IIR:class{constructor(t,i,s){let r=[];for(let e=0;e<t;e++)r.push(this.getCoeffs_({Fs:i,Fc:s,Q:.5/Math.sin(Math.PI/(2*t)*(e+.5))}));this.stages=[];for(let e=0;e<r.length;e++)this.stages[e]={b0:r[e].b[0],b1:r[e].b[1],b2:r[e].b[2],a1:r[e].a[0],a2:r[e].a[1],k:r[e].k,z:[0,0]}}filter(e){let i=e;for(let e=0,t=this.stages.length;e<t;e++)i=this.runStage_(e,i);return i}getCoeffs_(e){let t={a:[],b:[]};e=this.preCalc_(e,t);return t.k=1,t.b.push((1-e.cw)/(2*e.a0)),t.b.push(2*t.b[0]),t.b.push(t.b[0]),t}preCalc_(e,t){let i={};var s=2*Math.PI*e.Fc/e.Fs;return i.alpha=Math.sin(s)/(2*e.Q),i.cw=Math.cos(s),i.a0=1+i.alpha,t.a0=i.a0,t.a.push(-2*i.cw/i.a0),t.k=1,t.a.push((1-i.alpha)/i.a0),i}runStage_(e,t){var i=t*this.stages[e].k-this.stages[e].a1*this.stages[e].z[0]-this.stages[e].a2*this.stages[e].z[1],t=this.stages[e].b0*i+this.stages[e].b1*this.stages[e].z[0]+this.stages[e].b2*this.stages[e].z[1];return this.stages[e].z[1]=this.stages[e].z[0],this.stages[e].z[0]=i,t}reset(){for(let e=0;e<this.stages.length;e++)this.stages[e].z=[0,0]}},FIR:class{constructor(t,e,i){var s=2*Math.PI*i/e;let r=0;this.filters=[];for(let e=0;e<=t;e++)e-t/2==0?this.filters[e]=s:(this.filters[e]=Math.sin(s*(e-t/2))/(e-t/2),this.filters[e]*=.54-.46*Math.cos(2*Math.PI*e/t)),r+=this.filters[e];for(let e=0;e<=t;e++)this.filters[e]/=r;this.z=this.initZ_()}filter(e){this.z.buf[this.z.pointer]=e;let i=0;for(let e=0,t=this.z.buf.length;e<t;e++)i+=this.filters[e]*this.z.buf[(this.z.pointer+e)%this.z.buf.length];return this.z.pointer=(this.z.pointer+1)%this.z.buf.length,i}reset(){this.z=this.initZ_()}initZ_(){let t=[];for(let e=0;e<this.filters.length-1;e++)t.push(0);return{buf:t,pointer:0}}}};function pt(e,t,i,s=null){s=s||{};var r=new Float64Array(e.length*((i-t)/t+1));s.method=s.method||"cubic";var a=new ht(e.length,r.length,{method:s.method,tension:s.tension||0,sincFilterSize:s.sincFilterSize||6,sincWindow:s.sincWindow||void 0,clip:s.clip||"mirror"});if(void 0===s.LPF&&(s.LPF=ct[s.method]),s.LPF){s.LPFType=s.LPFType||"IIR";const n=dt[s.LPFType];t<i?function(i,s,r,a){for(let e=0,t=s.length;e<t;e++)s[e]=a.filter(r.interpolate(e,i));a.reset();for(let e=s.length-1;0<=e;e--)s[e]=a.filter(s[e])}(e,r,a,new n(s.LPForder||ut[s.LPFType],i,t/2)):function(i,e,t,s){for(let e=0,t=i.length;e<t;e++)i[e]=s.filter(i[e]);s.reset();for(let e=i.length-1;0<=e;e--)i[e]=s.filter(i[e]);gt(i,e,t)}(e,r,a,new n(s.LPForder||ut[s.LPFType],t,i/2))}else gt(e,r,a);return r}function gt(i,s,r){for(let e=0,t=s.length;e<t;e++)s[e]=r.interpolate(e,i)}class mt extends ot{toRIFF(){var e=new Float64Array(ft(this.data.samples.length,this.dataType.bits/8));Ye(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,this.bitDepth,e,{container:"RIFF"})}toRIFX(){var e=new Float64Array(ft(this.data.samples.length,this.dataType.bits/8));Ye(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,this.bitDepth,e,{container:"RIFX"})}toIMAADPCM(){if(8e3!==this.fmt.sampleRate)throw new Error("Only 8000 Hz files can be compressed as IMA-ADPCM.");if(1!==this.fmt.numChannels)throw new Error("Only mono files can be compressed as IMA-ADPCM.");this.assure16Bit_();var e=new Int16Array(ft(this.data.samples.length,2));Ye(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"4",Ae(e),{container:this.correctContainer_()})}fromIMAADPCM(e="16"){let r;if(1<this.fmt.numChannels){if(2<this.fmt.numChannels)throw new Error("Only 1 or 2 channels are supported");var a=this.data.samples.length/2;let t=new Uint8Array(a),i=new Uint8Array(a),s=0;for(let e=0;e<a;e++)e&&e%4==0&&(s+=4),t[e]=this.data.samples[s+e],i[e]=this.data.samples[s+e+4];r=[Be(t,this.fmt.blockAlign/2),Be(i,this.fmt.blockAlign/2)]}else r=Be(this.data.samples,this.fmt.blockAlign);this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",r,{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toALaw(){this.assure16Bit_();var e=new Int16Array(ft(this.data.samples.length,2));Ye(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"8a",Ne(e),{container:this.correctContainer_()})}fromALaw(e="16"){this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",Me(this.data.samples),{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toMuLaw(){this.assure16Bit_();var e=new Int16Array(ft(this.data.samples.length,2));Ye(this.data.samples,this.dataType,e,0,this.data.samples.length),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"8m",je(e),{container:this.correctContainer_()})}fromMuLaw(e="16"){this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",Ue(this.data.samples),{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toBitDepth(e,t=!0){let i=e,s=this.bitDepth;t||("32f"!=e&&(i=this.dataType.bits.toString()),s=""+this.dataType.bits),this.assureUncompressed_();var r=this.getSamples(!0),t=new Float64Array(r.length);be(r,s,t,i),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,e,t,{container:this.correctContainer_()})}toSampleRate(t,i){this.validateResample_(t);var s=this.getSamples();let r=[];if(s.constructor===Float64Array)r=pt(s,this.fmt.sampleRate,t,i);else for(let e=0;e<s.length;e++)r.push(pt(s[e],this.fmt.sampleRate,t,i));this.fromExisting_(this.fmt.numChannels,t,this.bitDepth,r,{container:this.correctContainer_()})}validateResample_(e){if(!rt(this.fmt.numChannels,this.fmt.bitsPerSample,e))throw new Error("Invalid sample rate.");if(-1<["4","8a","8m"].indexOf(this.bitDepth))throw new Error("wavefile can't change the sample rate of compressed files.")}assure16Bit_(){this.assureUncompressed_(),"16"!=this.bitDepth&&this.toBitDepth("16")}assureUncompressed_(){"8a"==this.bitDepth?this.fromALaw():"8m"==this.bitDepth?this.fromMuLaw():"4"==this.bitDepth&&this.fromIMAADPCM()}correctContainer_(){return"RF64"==this.container?"RIFF":this.container}fromExisting_(e,t,i,s,r){var a=new ot;Object.assign(this.fmt,a.fmt),Object.assign(this.fact,a.fact),Object.assign(this.ds64,a.ds64),Object.assign(this.data,a.data),this.newWavFile_(e,t,i,s,r)}}function ft(e,t){let i=e/t;return i%2&&i++,i}class yt extends mt{constructor(e){super(),e&&this.fromBuffer(e)}fromBase64(e){this.fromBuffer(function(i){let s=new Uint8Array(256);for(let e=0;e<Te.length;e++)s[Te.charCodeAt(e)]=e;let e=.75*i.length;"="===i[i.length-1]&&(e--,"="===i[i.length-2]&&e--);let r=new Uint8Array(e);for(let e=0,t=0;e<i.length;e+=4){var a=s[i.charCodeAt(e)],n=s[i.charCodeAt(e+1)],o=s[i.charCodeAt(e+2)],h=s[i.charCodeAt(e+3)];r[t++]=a<<2|n>>4,r[t++]=(15&n)<<4|o>>2,r[t++]=(3&o)<<6|63&h}return r}(e))}toBase64(){return function(t){let i="";for(let e=0;e<t.length;e+=3)i+=Te[t[e]>>2],i+=Te[(3&t[e])<<4|t[e+1]>>4],i+=Te[(15&t[e+1])<<2|t[e+2]>>6],i+=Te[63&t[e+2]];return t.length%3==2?i=i.substring(0,i.length-1)+"=":t.length%3==1&&(i=i.substring(0,i.length-2)+"=="),i}(this.toBuffer())}toDataURI(){return"data:audio/wav;base64,"+this.toBase64()}fromDataURI(e){this.fromBase64(e.replace("data:audio/wav;base64,",""))}}class wt{constructor(e){e instanceof Uint8Array?this.fromRawData(e):e instanceof i&&this.fromVirtualFile(e)}fromRawData(e){return this.rawData=e,this}fromVirtualFile(e){e=e.stream;return this.rawData=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),this}getRawData(){return this.rawData}getData(){if(!this.decodedData){if(!this.rawData)throw new Error("No data loaded");this.decodedData=this.decodeData(this.rawData),this.rawData=void 0}return this.decodedData}setData(e){this.rawData=void 0,this.decodedData=e}decodeData(e){let t=new yt(e);return"4"===t.bitDepth&&t.fromIMAADPCM(),t.toBuffer()}isRawImaAdpcm(){return this.rawData&&"4"===new yt(this.rawData).bitDepth}}class Tt{constructor(e,t=!0){this.resourceFactory=e,this.cache=t,this.resources=new Map}setDir(e){this.rfsDir=e}set(e,t){this.resources.set(e,t)}async has(e){return!!this.resources.has(e)||(await this.rfsDir?.containsEntry(e)??!1)}async get(e){let t;return t=this.resources.get(e),!t&&await this.rfsDir?.containsEntry(e)&&(t=await this.resourceFactory(await this.rfsDir.getRawFile(e)),this.cache&&this.resources.set(e,t)),t}clear(){this.resources.clear()}}class bt{constructor(e){this.file=e}asFile(){return new File([this.file],this.file.name,{type:"audio/mp3"})}}const vt=(new Map).set("cameo.mix",["adogicon.shp","adoguico.shp","aengicon.shp","aenguico.shp","agapgen.shp","agisicon.shp","ahrvicon.shp","ahrvuico.shp","aparicon.shp","apchicon.shp","apcicon.shp","artyicon.shp","asaticon.shp","ayaricon.shp","batricon.shp","beagicon.shp","bggyicon.shp","bolticon.shp","brrkicon.shp","carricon.shp","ccomicon.shp","ccomuico.shp","chemicon.shp","chroicon.shp","clckicon.shp","clegicon.shp","cleguico.shp","clonicon.shp","cnsticon.shp","crryicon.shp","csphicon.shp","darken.shp","desoicon.shp","desouico.shp","desticon.shp","detnicon.shp","dlphicon.shp","dlphuico.shp","dogicon.shp","doguico.shp","dredicon.shp","dronicon.shp","e1icon.shp","e1uico.shp","e2icon.shp","e2uico.shp","e4icon.shp","empicon.shp","engnicon.shp","facticon.shp","falcicon.shp","fixicon.shp","flakicon.shp","flkticon.shp","flktuico.shp","forticon.shp","fsdicon.shp","fspicon.shp","fstdicon.shp","fvicon.shp","fvuico.shp","gapicon.shp","gat2icon.shp","gateicon.shp","gbayicon.shp","gcanicon.shp","giicon.shp","giuico.shp","gorep.shp","gtnkicon.shp","gtnkuico.shp","gwepicon.shp","handicon.shp","harvicon.shp","harvuico.shp","heliicon.shp","hindicon.shp","hmecicon.shp","hovricon.shp","htkicon.shp","htkuico.shp","htnkicon.shp","htnkuico.shp","ioncicon.shp","ircricon.shp","ironicon.shp","ivanicon.shp","ivanuico.shp","ivncicon.shp","ivncuico.shp","jjeticon.shp","jjetuico.shp","landicon.shp","lasricon.shp","liteicon.shp","lpsticon.shp","mcvicon.shp","mcvuico.shp","metricon.shp","mltiicon.shp","mmchicon.shp","msslicon.shp","mtnkicon.shp","mtnkuico.shp","mutcicon.shp","nga2icon.shp","ngaticon.shp","nhpdicon.shp","npsiicon.shp","npwricon.shp","nradicon.shp","nrcticon.shp","nreficon.shp","ntchicon.shp","nukeicon.shp","nwalicon.shp","nwepicon.shp","obliicon.shp","obmbicon.shp","orcaicon.shp","otrnicon.shp","paraicon.shp","pillicon.shp","plticon.shp","plugicon.shp","podsicon.shp","powricon.shp","prisicon.shp","proicon.shp","psicicon.shp","psicuico.shp","psisicon.shp","psiticon.shp","psituico.shp","rad1icon.shp","rad2icon.shp","rad3icon.shp","radricon.shp","rboticon.shp","reficon.shp","rfixicon.shp","rtnkicon.shp","rtnkuico.shp","samicon.shp","sapcicon.shp","sapicon.shp","sbagicon.shp","sealicon.shp","sealuico.shp","seekicon.shp","shadicon.shp","shaduico.shp","shkicon.shp","shkuico.shp","smchicon.shp","smcvicon.shp","smcvuico.shp","snipicon.shp","snipuico.shp","soniicon.shp","spoticon.shp","spyicon.shp","spyuico.shp","sqdicon.shp","sreficon.shp","srefuico.shp","stnkicon.shp","subicon.shp","subticon.shp","tanyicon.shp","tanyuico.shp","techicon.shp","tempicon.shp","teslaicon.shp","tickicon.shp","tnkdicon.shp","tnkduico.shp","towricon.shp","trkaicon.shp","trsticon.shp","trstuico.shp","tslaicon.shp","ttnkicon.shp","ttnkuico.shp","turbicon.shp","twr1icon.shp","twr2icon.shp","twr3icon.shp","v3icon.shp","v3uico.shp","wallicon.shp","weapicon.shp","weaticon.shp","weedicon.shp","wethicon.shp","xxicon.shp","yardicon.shp","yuriicon.shp","yuriuico.shp","yurpicon.shp","yurpuico.shp","zepicon.shp","zepuico.shp"]).set("theme.mix",["200meter.wav","blowitup.wav","burn.wav","destroy.wav","eaglehun.wav","fortific.wav","grinder.wav","hm2.wav","indeep.wav","industro.wav","jank.wav","motorize.wav","power.wav","ra2-opt.wav","ra2-sco.wav","tension.wav"]);r=["addon.shp","bkgdlg.shp","bkgdmd.shp","bkgdsm.shp","bttnbkgd.shp","button00.shp","button01.shp","button02.shp","button03.shp","button04.shp","button05.shp","button06.shp","button07.shp","button08.shp","button09.shp","button10.shp","button11.shp","credits.shp","diplobtn.shp","gclock2.shp","key.ini","lendcap.shp","lspacer.shp","optbtn.shp","pbeacon.shp","power.shp","powerp.shp","pwrlvl.shp","radar.shp","radar01.shp","radar02.shp","r-dn.shp","rdrbeacn.shp","rendcap.shp","repair.shp","r-up.shp","sell.shp","side1.shp","side2.shp","side2b.shp","side3.shp","sidebar.pal","sidebttn.shp","tab00.shp","tab01.shp","tab02.shp","tab03.shp","tabs.shp","top.shp","uibkgd.pal","wayp.shp"];vt.set("sidec01.mix",r).set("sidec02.mix",r);var St,kt,r=["reportbug.shp"];vt.set("sidec01cd.mix",r).set("sidec02cd.mix",r),(r=St=St||{})[r.Archive=0]="Archive",r[r.Cdn=1]="Cdn",r[r.Local=2]="Local";class Ot{readIni(e){return this.minMoney=e.getNumber("MinMoney"),this.money=e.getNumber("Money"),this.maxMoney=e.getNumber("MaxMoney"),this.moneyIncrement=e.getNumber("MoneyIncrement"),this.minUnitCount=e.getNumber("MinUnitCount"),this.unitCount=e.getNumber("UnitCount"),this.maxUnitCount=e.getNumber("MaxUnitCount"),this.crates=e.getBool("Crates"),this.gameSpeed=e.getNumber("GameSpeed"),this.mcvRedeploys=e.getBool("MCVRedeploys"),this.shortGame=e.getBool("ShortGame"),this.superWeapons=e.getBool("SuperWeapons"),this.techLevel=e.getNumber("TechLevel"),this.alliesAllowed=e.getBool("AlliesAllowed",!0),this.allyChangeAllowed=e.getBool("AllyChangeAllowed",!0),this.mustAlly=e.getBool("MustAlly"),this}}(r=kt=kt||{})[r.Battle=0]="Battle",r[r.ManBattle=1]="ManBattle",r[r.FreeForAll=2]="FreeForAll",r[r.Unholy=3]="Unholy",r[r.Cooperative=4]="Cooperative";class _t{constructor(e,t){this.modeIniLoader=t,this.entries=new Map,this.loadIni(e)}loadIni(e){e.getOrderedSections().forEach(s=>{let r=kt[s.name]??kt.Battle;[...s.entries.keys()].forEach(e=>{let t=s.getArray(e);if(t.length<5)throw new Error(`Invalid format for mp mode entry "${e}".`);var i=Number(e),e=t[2].toLowerCase(),e={id:i,type:r,label:t[0],description:t[1],rulesOverride:e,mapFilter:t[3],randomMapsAllowed:t[4],aiAllowed:i<3,mpDialogSettings:(new Ot).readIni(this.modeIniLoader(e).getOrCreateSection("MultiplayerDialogSettings"))};this.entries.set(i,e)})})}getById(e){if(!this.entries.has(e))throw new Error(`No game mode found with id ${e}`);return this.entries.get(e)}hasId(e){return this.entries.has(e)}getAll(){return[...this.entries.values()]}}class It{fromIni(t,e){return this.fileName=t.getString("File")||t.name.toLowerCase()+".map",this.uiName=t.getString("Description"),this.maxSlots=t.getNumber("MaxPlayers"),this.official=!0,this.gameModes=e.filter(e=>t.getArray("GameMode").includes(e.mapFilter)),this}getFullMapTitle(e){return this.addTitleSlotsSuffix(e.get(this.uiName),this.maxSlots)}addTitleSlotsSuffix(e,t){return e.match(/(\(|()\s*\d(-\d)?\s*(\)|))\s*$/)||(e+=` (2${2<t?"-"+t:""})`),e}fromMapFile(e,t){var i=e.readAsString();let s=e.filename;const r=new c(this.extractIniSection("Basic",i)).getSection("Basic");if(!r)throw new Error(`Map "${s}" is missing the [Basic] section`);this.fileName=s,this.uiName="NOSTR:"+(r.getString("Name")||s.replace(/\.[^.]+$/,""));let a=r.getNumber("MaxPlayer");if(!a){i=this.extractIniSection("Header",i);const o=i?new c(i).getSection("Header"):void 0;a=o?.getNumber("NumberStartingPoints")||2}this.maxSlots=a,this.official=r.getBool("Official");let n=r.getArray("GameMode",void 0,["standard"]);return this.gameModes=t.filter(e=>n.includes(e.mapFilter)),this}extractIniSection(t,i){t=i.indexOf(`[${t}]`);if(-1!==t){let e=t+1;for(;e<i.length&&("["!==i[e]||"\n"!==i[e-1]);e++);return i.slice(t,e)}}}class Ct{constructor(e){this.gameModes=e,this.manifests=[]}addFromIni(i){let e=i.getSection("MultiMaps");if(!e)throw new Error("Invalid map list. Missing [MultiMaps] section.");return this.manifests=this.manifests.concat([...e.entries.values()].map(e=>{var t=i.getSection(e);if(!t)throw new Error(`Invalid map list. Missing [${e}] section.`);return(new It).fromIni(t,this.gameModes.getAll())})),this.dedupeEntries(),this}add(e){this.manifests.push(e)}addFromMapFile(e){this.add((new It).fromMapFile(e,this.gameModes.getAll()))}getAll(){return this.manifests}getByName(t){return this.manifests.find(e=>e.fileName.toLowerCase()===t.toLowerCase())}sortByName(){this.manifests.sort((e,t)=>e.fileName.localeCompare(t.fileName))}clone(){let e=new Ct(this.gameModes);return e.manifests=[...this.manifests],e}mergeWith(e){return this.manifests.push(...e.manifests),this.dedupeEntries(),this}dedupeEntries(){this.manifests=[...new Map(this.manifests.map(e=>[e.fileName.toLowerCase(),e])).values()]}}class At{getMatrix(e){return this.matrices[e]}}var Bt,xt,Et=__webpack_require__(949);class Pt{constructor(e){e instanceof i&&this.fromVirtualFile(e)}fromVirtualFile(e){this.filename=e.filename;let i=e.stream;this.sections=[],i.readCString(16);var s=i.readInt32(),r=i.readInt32();for(let e=0;e<r;++e){let e=new At;e.name=i.readCString(16),e.matrices=new Array(s),this.sections.push(e)}for(let t=0;t<s;++t)for(let e=0;e<r;++e)this.sections[e].matrices[t]=this.readMatrix(i)}readMatrix(t){let i=[];for(let e=0;e<3;++e)i.push(t.readFloat32(),t.readFloat32(),t.readFloat32(),t.readFloat32());return i.push(0,0,0,1),(new Et.Matrix4).fromArray(i).transpose()}}(r=Bt=Bt||{})[r.AutoDetect=0]="AutoDetect",r[r.TiberianSun=1]="TiberianSun",r[r.Firestorm=2]="Firestorm",r[r.RedAlert2=3]="RedAlert2",r[r.YurisRevenge=4]="YurisRevenge";class Nt{static getVersion(){return"0.64.0".split(".").slice(0,2).join(".")}static getModHash(){if(!this.modHash)throw new Error("Rules must be loaded first");return this.modHash}static getActiveMod(){return this.activeMod}static setActiveMod(e){this.activeMod=e}static initGameResSource(e){this.gameResSource=e}static async initRfs(e){let t=this.rfs=new ye;return t.addRootDirectoryHandle(e),t}static async initVfs(e,t){return this.vfs=new pe(e,t),Nt.iniFiles.setVfs(this.vfs),Nt.palettes.setVfs(this.vfs),Nt.images.setVfs(this.vfs),Nt.voxels.setVfs(this.vfs),Nt.voxelAnims.setVfs(this.vfs),Nt.tileData.setVfs(this.vfs),Nt.sounds.setVfs(this.vfs),Nt.themes.setDir(await this.rfs?.findDirectory(Nt.rfsSettings.musicDir)),Nt.taunts.setDir(await this.rfs?.findDirectory(Nt.rfsSettings.tauntsDir)),this.vfs}static supportsTheater(t){var e=this.getActiveEngine();return this.theaterSettings.get(e)?.some(e=>e.Type===t)||!1}static getTheaterSettings(e,t){if(!this.theaterSettings.has(e))throw new Error(`Unknown engineType "${e}`);e=this.theaterSettings.get(e).find(e=>e.Type===t);if(!e)throw new Error(`Unsupported theater "${C[t]}"`);return e}static async loadTheater(e){if(!Nt.rules||!Nt.art)throw new Error("Rules and art should be loaded first");if(void 0===Nt.gameResSource)throw new Error("No gameResSource is set");var t=Nt.getActiveEngine();let i;var s,r=Nt.getTheaterSettings(t,e);if(Nt.gameResSource!==St.Cdn)for(var a of r.Mixes)await Nt.vfs.addMixFile(a);return Nt.theaters.has(e)?i=Nt.theaters.get(e):(s=Nt.getTheaterIni(t,e),t=Nt.getTileData(),i=K.factory(e,s,r,t,Nt.palettes),Nt.theaters.set(e,i)),Nt.activeTheater=i,i}static unloadTheater(e){if(Nt.vfs){var t,i=Nt.getActiveEngine();for(t of Nt.getTheaterSettings(i,e).Mixes)Nt.vfs.removeArchive(t)}}static unloadSideMixData(){for(var e of["sidec01.mix","sidec01cd.mix"]){var t,i=vt.get(e);if(!i)return void console.warn(`Mix "${e}" not found in mix database`);for(t of i)("pal"===t.split(".").pop()?Nt.palettes:Nt.images).clear(t)}}static getTheaterIni(e,t){t=Nt.getTheaterSettings(e,t).TheaterIni;return Nt.getIni(t)}static loadRules(){var e=this.getFileNameVariant("rules.ini"),t=this.getFileNameVariant("art.ini"),i=this.getFileNameVariant("ai.ini");let s=this.iniFiles.get(e),r=this.iniFiles.get(t);var a=this.iniFiles.get(i);if(!s)throw new Error(`Rules "${e}" not found`);if(!r)throw new Error(`Art "${t}" not found`);if(!a)throw new Error(`AI "${i}" not found`);t=this.iniFiles.get(Nt.customRulesFileName),i=this.iniFiles.get(Nt.customArtFileName);if(!t)throw new Error(`Rules "${Nt.customRulesFileName}" not found`);if(!i)throw new Error(`Art "${Nt.customArtFileName}" not found`);Nt.art=r.clone().mergeWith(i),Nt.rules=s.clone().mergeWith(t),Nt.ai=a,Nt.modHash=Nt.computeModHash()}static computeModHash(){if(!this.vfs)throw new Error("VFS not initialized");let e=[this.customRulesFileName,this.customArtFileName,this.customMpModesFileName,this.getFileNameVariant("rules.ini"),this.getFileNameVariant("art.ini"),this.getFileNameVariant("ai.ini")];var t,i,s,r=this.theaterSettings.get(this.getActiveEngine());if(!r)throw new Error(`Unsupported engineType "${this.getActiveEngine()}`);for(t of r)e.push(this.getFileNameVariant(t.TheaterIni));let a=this.getMpModes();for(i of a.getAll())e.push(i.rulesOverride);let n=new he;for(s of e){if(!this.vfs.fileExists(s))throw new Error(`File ${s} not found`);var o=this.vfs.openFile(s).stream;n.append(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}return n.append(R(this.getVersion())),n.get()}static getRules(){if(!Nt.rules)throw new Error("Rules must be loaded first");return Nt.rules}static getArt(){if(!Nt.art)throw new Error("Art must be loaded first");return Nt.art}static getAi(){if(!Nt.ai)throw new Error("AI must be loaded first");return Nt.ai}static getFileNameVariant(e){var t=this.getActiveEngine();let i;if(t===Bt.YurisRevenge)i="md";else{if(t!==Bt.RedAlert2)throw new Error(`Unsupported engine type ${Bt[t]}`);i=""}return i?e.replace(/\.([^.]+)$/,i+".$1"):e}static getMpModes(){return new _t(this.getIni(this.customMpModesFileName),e=>this.getIni(e))}static getUiIni(){var e=this.getFileNameVariant("ui.ini");return this.getIni(e)}static getIni(e){if(!this.iniFiles.has(e))throw new Error(`INI file ${e} not found.`);return this.iniFiles.get(e)}static async loadMapList(){if(!this.vfs)throw new Error("File system not initialized");var e,i,s,t=this.getMpModes();let r=new Ct(t);r.addFromIni(this.getIni(this.getFileNameVariant("missions.pkt")));for(e of this.vfs.listArchives()){var a=e.toLowerCase().replace(/\.[^.]+$/,"")+".pkt";this.vfs.fileExists(a)&&r.addFromIni(new c(this.vfs.openFile(a)))}let n=new Ct(t);if(this.rfs)for await(var o of this.rfs.getEntries()){let t=o.toLowerCase();try{t.endsWith(".pkt")?(i=new c(await this.rfs.openFile(o,!0)),r.addFromIni(i)):this.supportedMapTypes.some(e=>t.endsWith("."+e))&&(s=await this.rfs.openFile(o,!0),n.addFromMapFile(s))}catch(e){console.warn(`Couldn't read file "${o}"`,e)}}return n.sortByName(),r.mergeWith(n),this.mapList=r,r}static getTileData(){return Nt.tileData}static getImages(){return Nt.images}static getVoxels(){return Nt.voxels}static getVoxelAnims(){return Nt.voxelAnims}static getPalettes(){return Nt.palettes}static getSounds(){return Nt.sounds}static getThemes(){return Nt.themes}static getTaunts(){return Nt.taunts}static getActiveEngine(){return Bt.RedAlert2}static getLastTheaterType(){return Nt.activeTheater?.type}static getCacheDir(){try{return this.getOrCreateDir(this.rfsSettings.cacheDir,!0)}catch(e){return void console.error("Couldn't get cache directory",[e])}}static async getReplayDir(){var i=this.getActiveMod();if(i){let e=await this.getModDir(),t=await e?.getDirectory(i);return t?.getOrCreateDirectory(Nt.rfsSettings.replayDir)}return this.getOrCreateDir(this.rfsSettings.replayDir)}static getModDir(){return this.getOrCreateDir(Nt.rfsSettings.modDir)}static getMapDir(){return this.getOrCreateDir(Nt.rfsSettings.mapDir)}static async getOrCreateDir(e,t=!1){let i=this.rfs?.getRootDirectory();if(i)return await i.getOrCreateDirectory(e,t)}static getMapList(){return this.mapList}static destroy(){this.activeTheater=void 0,this.activeMod=void 0,this.modHash=void 0,this.mapList=void 0,this.rfs=void 0,this.vfs=void 0,this.art=void 0,this.iniFiles.clear(),this.images.clear(),this.palettes.clear(),this.rules=void 0,this.ai=void 0,this.theaters.clear(),this.tileData.clear(),this.voxels.clear(),this.voxelAnims.clear()}}Nt,Nt.UI_ANIM_SPEED=2,Nt.rfsSettings={menuVideoFileName:"ra2ts_l.webm",splashImgFileName:"glsl.png",mapDir:"maps",modDir:"mods",musicDir:"music",tauntsDir:"Taunts",cacheDir:"cache",replayDir:"replays"},Nt.supportedMapTypes=["mpr","map"],Nt.images=new we(e=>new s(e)),Nt.voxels=new we(e=>new k(e)),Nt.voxelAnims=new we(e=>new Pt(e)),Nt.sounds=new we(e=>new wt(e)),Nt.themes=new Tt(e=>new bt(e),!1),Nt.taunts=new Tt(async e=>new wt(new Uint8Array(await e.arrayBuffer()))),Nt.iniFiles=new we(e=>new c(e)),Nt.tileData=new we(e=>new P(e)),Nt.palettes=new we(e=>new $(e)),Nt.theaters=new Map,Nt.theaterSettings=(new Map).set(Bt.RedAlert2,[{Type:C.Temperate,TheaterIni:"temperat.ini",Mixes:["isotemp.mix","temperat.mix","tem.mix"],Extension:".tem",NewTheaterChar:"T",IsoPaletteName:"isotem.pal",UnitPaletteName:"unittem.pal",OverlayPaletteName:"temperat.pal",LibPaletteName:"libtem.pal"},{Type:C.Snow,TheaterIni:"snow.ini",Mixes:["isosnow.mix","snow.mix","sno.mix"],Extension:".sno",NewTheaterChar:"A",IsoPaletteName:"isosno.pal",UnitPaletteName:"unitsno.pal",OverlayPaletteName:"snow.pal",LibPaletteName:"libsno.pal"},{Type:C.Urban,TheaterIni:"urban.ini",Mixes:["isourb.mix","urb.mix","urban.mix"],Extension:".urb",NewTheaterChar:"U",IsoPaletteName:"isourb.pal",UnitPaletteName:"uniturb.pal",OverlayPaletteName:"urban.pal",LibPaletteName:"liburb.pal"}]).set(Bt.YurisRevenge,[{Type:C.Temperate,TheaterIni:"temperatmd.ini",Mixes:["isotemp.mix","isotemmd.mix","temperat.mix","tem.mix"],Extension:".tem",NewTheaterChar:"T",IsoPaletteName:"isotem.pal",UnitPaletteName:"unittem.pal",OverlayPaletteName:"temperat.pal",LibPaletteName:"libtem.pal"},{Type:C.Snow,TheaterIni:"snowmd.ini",Mixes:["isosnomd.mix","snowmd.mix","isosnow.mix","snow.mix","sno.mix"],Extension:".sno",NewTheaterChar:"A",IsoPaletteName:"isosno.pal",UnitPaletteName:"unitsno.pal",OverlayPaletteName:"snow.pal",LibPaletteName:"libsno.pal"},{Type:C.Urban,TheaterIni:"urbanmd.ini",Mixes:["isourbmd.mix","isourb.mix","urb.mix","urban.mix"],Extension:".urb",NewTheaterChar:"U",IsoPaletteName:"isourb.pal",UnitPaletteName:"uniturb.pal",OverlayPaletteName:"urban.pal",LibPaletteName:"liburb.pal"},{Type:C.NewUrban,TheaterIni:"urbannmd.ini",Mixes:["isoubnmd.mix","isoubn.mix","ubn.mix","urbann.mix"],Extension:".ubn",NewTheaterChar:"N",IsoPaletteName:"isoubn.pal",UnitPaletteName:"unitubn.pal",OverlayPaletteName:"urbann.pal",LibPaletteName:"libubn.pal"},{Type:C.Desert,TheaterIni:"desertmd.ini",Mixes:["isodesmd.mix","desert.mix","des.mix","isodes.mix"],Extension:".des",NewTheaterChar:"D",IsoPaletteName:"isodes.pal",UnitPaletteName:"unitdes.pal",OverlayPaletteName:"desert.pal",LibPaletteName:"libdes.pal"},{Type:C.Lunar,TheaterIni:"lunarmd.ini",Mixes:["isolunmd.mix","isolun.mix","lun.mix","lunar.mix"],Extension:".lun",NewTheaterChar:"L",IsoPaletteName:"isolun.pal",UnitPaletteName:"unitlun.pal",OverlayPaletteName:"lunar.pal",LibPaletteName:"liblun.pal"}]),Nt.customRulesFileName="rulescd.ini",Nt.customArtFileName="artcd.ini",Nt.customMpModesFileName="mpmodescd.ini",(r=xt=xt||{})[r.None=0]="None",r[r.Aircraft=1]="Aircraft",r[r.Building=2]="Building",r[r.Infantry=3]="Infantry",r[r.Overlay=4]="Overlay",r[r.Smudge=5]="Smudge",r[r.Terrain=6]="Terrain",r[r.Vehicle=7]="Vehicle",r[r.Animation=8]="Animation",r[r.Projectile=9]="Projectile",r[r.VoxelAnim=10]="VoxelAnim",r[r.Debris=11]="Debris";class Mt{constructor(e){this.type=e}isStructure(){return this.type===xt.Building}isVehicle(){return this.type===xt.Vehicle}isInfantry(){return this.type===xt.Infantry}isAircraft(){return this.type===xt.Aircraft}isTerrain(){return this.type===xt.Terrain}isSmudge(){return this.type===xt.Smudge}isOverlay(){return this.type===xt.Overlay}isNamed(){return"name"in this}isTechno(){return"health"in this}}class Dt extends Mt{}class Rt extends Dt{}class Lt extends Rt{constructor(){super(xt.Building)}}class Ft extends Rt{constructor(){super(xt.Vehicle)}}class jt extends Rt{constructor(){super(xt.Infantry)}}class Ut extends Rt{constructor(){super(xt.Aircraft)}}class Wt extends Dt{constructor(){super(xt.Terrain)}}class zt extends Dt{constructor(){super(xt.Smudge)}}class Vt extends Mt{constructor(){super(xt.Overlay)}}class Ht{static decode(e,t){t=new Uint8Array(t);return this.decodeInto(e,t),t}static decodeInto(e,t){let i=new v(new DataView(e.buffer,e.byteOffset,e.byteLength)),s=0;for(;;){var r=i.readUint8();if(0==(128&r)){var a=i.readUint8(),n=3+((112&r)>>4);this.replicatePrevious(t,s,s-(((15&r)<<8)+a),n),s+=n}else if(0==(64&r)){n=63&r;if(0==n)return s;t.set(i.readUint8Array(n),s),s+=n}else{r=63&r;if(62==r)for(var o=i.readInt16(),h=i.readUint8(),l=s+o;s<l;s++)t[s]=h;else if(63==r){o=i.readInt16();let e=i.readInt16();if(e>=s)throw new Error(`srcIndex >= destIndex ${e} ${s}`);for(var c=s+o;s<c;s++)t[s]=t[e++]}else{r=3+r;let e=i.readInt16();if(e>=s)throw new Error(`srcIndex >= destIndex ${e} ${s}`);for(var u=s+r;s<u;s++)t[s]=t[e++]}}}}static replicatePrevious(t,i,s,r){if(i<s)throw new Error(`srcIndex > destIndex ${s} ${i}`);if(i-s==1)for(let e=0;e<r;e++)t[i+e]=t[i-1];else for(let e=0;e<r;e++)t[i+e]=t[s+e]}}var Gt,$t,qt,Xt,Zt,Qt,Yt,Kt,Jt,ei,ti,ii,si,ri,ai,ni,oi,hi,li,ci,ui=__webpack_require__(251).default;class di{static decompress(e,t){e={inputBuffer:e,outputBuffer:null},t=ui.decompress(e,{outputSize:t});if(0!==t)throw new Error(`MiniLzo decode failed with code ${t}`);return e.outputBuffer}}class pi{static decode(e,t,i=5){t=new Uint8Array(t);return this.decodeInto(e,t,i),t}static decodeInto(e,i,s=5){var t=i.length;let r=0,a=0;for(;a<t;){var n=e[r+1]<<8|e[r];r+=2;var o=e[r+1]<<8|e[r];if(r+=2,!n||!o)break;let t;t=80===s?Ht.decode(e.subarray(r,r+n),o):di.decompress(e.subarray(r,r+n),o);for(let e=0;e<o;++e)i[a+e]=t[e];r+=n,a+=o}}}function gi(e){switch(e){case Gt.Indexed:return 1;case Gt.Rgb:return 3;case Gt.Rgba:return 4;default:throw new Error(`Unsupported pixel format ${e}`)}}(r=Gt=Gt||{})[r.Rgb=1]="Rgb",r[r.Rgba=2]="Rgba",r[r.Indexed=3]="Indexed";class mi{constructor(e,t,i,s=Gt.Rgba){var r=gi(s);this.data=i||new Uint8Array(r*e*t),this.pixelFormat=s,this.width=e,this.height=t}drawIndexedImage(t,e,i){var s=gi(this.pixelFormat);const r=this.data;var a=this.width,n=s*a,o=s*a*this.height;let h=0+n*i+s*e,l=0;for(let e=0;e<t.height;e++){for(let e=0;e<t.width;e++){var c=t.data[l];0!==c&&0<=h&&h<o&&(r[h]=c,3<=s&&(r[h+1]=0,r[h+2]=0),4===s&&(r[h+3]=255)),h+=s,l++}h+=n-t.width*s}}}class fi extends mi{constructor(e,t,i){super(e,t,i,Gt.Rgb)}}(r=$t=$t||{})[r.OnceAny=0]="OnceAny",r[r.OnceAll=1]="OnceAll",r[r.Repeat=2]="Repeat";class yi{read(e){let t=[];for(var[i,s]of e.entries){var r=s.split(",");r.length<3?console.warn(`Invalid tag ${i}=${s}. Skipping.`):(s=Number(r[0]),void 0!==$t[s]?(r={id:i,repeatType:s,name:r[1],triggerId:r[2]},t.push(r)):console.warn(`Invalid repeat value ${s} for tag id ${i}. Skipping.`))}return t}}(r=qt=qt||{})[r.NoEvent=0]="NoEvent",r[r.EnteredBy=1]="EnteredBy",r[r.SpiedBy=2]="SpiedBy",r[r.AttackedByAny=6]="AttackedByAny",r[r.DestroyedByAny=7]="DestroyedByAny",r[r.AnyEvent=8]="AnyEvent",r[r.DestroyedAllUnits=9]="DestroyedAllUnits",r[r.DestroyedAllBuildings=10]="DestroyedAllBuildings",r[r.DestroyedAll=11]="DestroyedAll",r[r.CreditsExceed=12]="CreditsExceed",r[r.ElapsedTime=13]="ElapsedTime",r[r.MissionTimerExpired=14]="MissionTimerExpired",r[r.DestroyedBuildings=15]="DestroyedBuildings",r[r.DestroyedUnits=16]="DestroyedUnits",r[r.NoFactoriesLeft=17]="NoFactoriesLeft",r[r.BuildBuilding=19]="BuildBuilding",r[r.BuildUnit=20]="BuildUnit",r[r.BuildInfantry=21]="BuildInfantry",r[r.BuildAircraft=22]="BuildAircraft",r[r.CrossesHorizontalLine=25]="CrossesHorizontalLine",r[r.CrossesVerticalLine=26]="CrossesVerticalLine",r[r.GlobalIsSet=27]="GlobalIsSet",r[r.GlobalIsCleared=28]="GlobalIsCleared",r[r.DestroyedOrCaptured=29]="DestroyedOrCaptured",r[r.LowPower=30]="LowPower",r[r.DestroyedBridge=31]="DestroyedBridge",r[r.BuildingExists=32]="BuildingExists",r[r.ComesNearWaypoint=34]="ComesNearWaypoint",r[r.LocalIsSet=36]="LocalIsSet",r[r.LocalIsCleared=37]="LocalIsCleared",r[r.FirstDamagedCombat=38]="FirstDamagedCombat",r[r.HalfHealthCombat=39]="HalfHealthCombat",r[r.QuarterHealthCombat=40]="QuarterHealthCombat",r[r.FirstDamagedAny=41]="FirstDamagedAny",r[r.HalfHealthAny=42]="HalfHealthAny",r[r.QuarterHealthAny=43]="QuarterHealthAny",r[r.AttackedByHouse=44]="AttackedByHouse",r[r.AmbientLightBelow=45]="AmbientLightBelow",r[r.AmbientLightAbove=46]="AmbientLightAbove",r[r.ElapsedScenarioTime=47]="ElapsedScenarioTime",r[r.DestroyedOrCapturedOrInfiltrated=48]="DestroyedOrCapturedOrInfiltrated",r[r.PickupCrate=49]="PickupCrate",r[r.PickupCrateAny=50]="PickupCrateAny",r[r.RandomDelay=51]="RandomDelay",r[r.CreditsBelow=52]="CreditsBelow",r[r.SpyEnteringAsHouse=53]="SpyEnteringAsHouse",r[r.SpyEnteringAsInfantry=54]="SpyEnteringAsInfantry",r[r.DestroyedAllUnitsNaval=55]="DestroyedAllUnitsNaval",r[r.DestroyedAllUnitsLand=56]="DestroyedAllUnitsLand",r[r.BuildingNotExists=57]="BuildingNotExists",(r=Xt=Xt||{})[r.NoAction=0]="NoAction",r[r.FireSale=9]="FireSale",r[r.TextTrigger=11]="TextTrigger",r[r.DestroyTrigger=12]="DestroyTrigger",r[r.ChangeHouse=14]="ChangeHouse",r[r.RevealMap=16]="RevealMap",r[r.RevealAroundWaypoint=17]="RevealAroundWaypoint",r[r.PlaySoundFx=19]="PlaySoundFx",r[r.PlaySpeech=21]="PlaySpeech",r[r.ForceTrigger=22]="ForceTrigger",r[r.TimerStart=23]="TimerStart",r[r.TimerStop=24]="TimerStop",r[r.TimerExtend=25]="TimerExtend",r[r.TimerShorten=26]="TimerShorten",r[r.TimerSet=27]="TimerSet",r[r.GlobalSet=28]="GlobalSet",r[r.GlobalClear=29]="GlobalClear",r[r.DestroyObject=32]="DestroyObject",r[r.AddOneTimeSuperWeapon=33]="AddOneTimeSuperWeapon",r[r.AddRepeatingSuperWeapon=34]="AddRepeatingSuperWeapon",r[r.AllChangeHouse=36]="AllChangeHouse",r[r.ResizePlayerView=40]="ResizePlayerView",r[r.PlayAnimAt=41]="PlayAnimAt",r[r.DetonateWarhead=42]="DetonateWarhead",r[r.ReshroudMap=51]="ReshroudMap",r[r.EnableTrigger=53]="EnableTrigger",r[r.DisableTrigger=54]="DisableTrigger",r[r.CreateRadarEvent=55]="CreateRadarEvent",r[r.LocalSet=56]="LocalSet",r[r.LocalClear=57]="LocalClear",r[r.SellBuilding=60]="SellBuilding",r[r.TurnOffBuilding=61]="TurnOffBuilding",r[r.TurnOnBuilding=62]="TurnOnBuilding",r[r.ApplyOneHundredDamage=63]="ApplyOneHundredDamage",r[r.ForceEnd=69]="ForceEnd",r[r.DestroyTag=70]="DestroyTag",r[r.SetAmbientStep=71]="SetAmbientStep",r[r.SetAmbientRate=72]="SetAmbientRate",r[r.SetAmbientLight=73]="SetAmbientLight",r[r.NukeStrike=95]="NukeStrike",r[r.PlaySoundFxAt=99]="PlaySoundFxAt",r[r.UnrevealAroundWaypoint=101]="UnrevealAroundWaypoint",r[r.LightningStrike=102]="LightningStrike",r[r.TimerText=103]="TimerText",r[r.CreateCrate=108]="CreateCrate",r[r.IronCurtainAt=109]="IronCurtainAt",r[r.EvictOccupiers=111]="EvictOccupiers",r[r.Cheer=113]="Cheer",r[r.StopSoundsAt=116]="StopSoundsAt";class wi{read(e,t,i,s){let r=this.readTriggers(e),{events:a,unknownEventTypes:n}=this.readEvents(t),{actions:o,unknownActionTypes:h}=this.readActions(i),l=[...s.values()],c=new Set(r);for(let t of r.values()){var u=a.get(t.id);u&&t.events.push(...u);u=o.get(t.id);u&&t.actions.push(...u),!t.attachedTriggerId||(u=r.find(e=>e.id===t.attachedTriggerId))&&(t.attachedTrigger=u,c.delete(u))}for(let t of c){var d=l.find(e=>e.triggerId===t.id);if(d){let e=t;for(;e;)e.tag=d,e=e.attachedTrigger}else{let e=t;for(;e;){console.warn(`Trigger ${e.id} has no associated tag or valid root trigger. Skipping.`);var p=r.indexOf(e);-1!==p&&r.splice(p,1),e=e.attachedTrigger}}}return{triggers:r,unknownEventTypes:n,unknownActionTypes:h}}readTriggers(e){let t=[];for(var[i,s]of e.entries){var r=s.split(",");r.length<8?console.warn(`Invalid trigger ${i}=${s}. Skipping.`):(r={id:i,houseName:r[0],attachedTriggerId:"<none>"!==r[1]?r[1]:void 0,attachedTrigger:void 0,name:r[2],disabled:Boolean(Number(r[3])),difficulties:{easy:Boolean(Number(r[4])),medium:Boolean(Number(r[5])),hard:Boolean(Number(r[6]))},events:[],actions:[],tag:void 0},t.push(r))}return t}readEvents(e){let t=new Map,r=new Set;for(var[a,i]of e.entries){let s=i.split(",");if(s.length<4)console.warn(`Invalid event ${a}=${i}. Skipping.`);else{var n=Number(s.shift());let i=[];for(let t=0;t<n;t++){var o=Number(s.shift()),h=Number(s.shift());let e=s.splice(0,2===h?2:1);void 0!==qt[o]?(h={triggerId:a,eventIndex:t,type:o,params:[h,...e.map(e=>e||"0")]},i.push(h)):(r.add(o),console.warn(`Unknown event type ${o} for trigger id ${a}. Skipping.`))}t.set(a,i)}}return{events:t,unknownEventTypes:r}}readActions(e){let s=new Map,r=new Set;for(var[a,t]of e.entries){let i=t.split(",");if(i.length<9)console.warn(`Invalid action ${a}=${t}. Skipping.`);else{var n=Number(i.shift());if(i.length<8*n)console.warn(`Invalid action ${a}=${t}. Skipping.`);else{let t=[];for(let e=0;e<n;e++){var o=Number(i.shift()),h=i.splice(0,7);void 0!==Xt[o]?(h={triggerId:a,index:e,type:o,params:[Number(h[0]||"0"),h[1]||"0",h[2]||"0",h[3]||"0",h[4]||"0",h[5]||"0",h[6]?this.readAZActionParam(h[6]):0]},t.push(h)):(r.add(o),console.warn(`Unknown action type ${o} for trigger id "${a}". Skipping.`))}s.set(a,t)}}}return{actions:s,unknownActionTypes:r}}readAZActionParam(e){var t="Z".charCodeAt(0),i="A".charCodeAt(0),t=t-i+1;return 1<e.length?e.charCodeAt(1)-i+(e.charCodeAt(0)-i+1)*t:e.charCodeAt(0)-i}}class Ti{constructor(){this.level=0,this.ambient=1,this.red=1,this.green=1,this.blue=1,this.ground=0,this.forceTint=!1}read(e,t=""){return this.level=e.getNumber(t+"Level",.032),this.ambient=e.getNumber(t+"Ambient",1),this.red=e.getNumber(t+"Red",1),this.green=e.getNumber(t+"Green",1),this.blue=e.getNumber(t+"Blue",1),this.ground=e.getNumber(t+"Ground",0),this}copy(e){return this.level=e.level,this.ambient=e.ambient,this.red=e.red,this.green=e.green,this.blue=e.blue,this.ground=e.ground,this.forceTint=e.forceTint,this}}class bi{read(e,t){let i=[];for(var[s,r]of e.entries){s={tagId:r,coords:this.readCoords(Number(s),t)};i.push(s)}return i}readCoords(e,t){t=t<4?128:1e3;return{x:e%t,y:Math.floor(e/t)}}}class vi{constructor(e,t){this.name=e,this.value=t}clone(){return new vi(this.name,this.value)}}class Si{read(e){return this.initialVeteran=e.getBool("InitialVeteran"),this}}class ki extends c{fromString(e){super.fromString(e);let t=this.getSection("Map");if(!t)throw new Error("[Map] section not found");e=t.getNumberArray("Size");if(this.fullSize={x:e[0],y:e[1],width:e[2],height:e[3]},e=t.getNumberArray("LocalSize"),this.localSize={x:e[0],y:e[1],width:e[2],height:e[3]},this.theaterType=t.getEnum("Theater",C,C.None,!0),this.theaterType===C.None)throw new Error(`Unsupported theater type "${t.getString("Theater")}"`);let i=this.getSection("Basic");e=this.iniFormat=i?.getNumber("NewINIFormat")??0;return this.readTiles(),i?.getBool("MultiplayerOnly")&&this.readWaypoints(this.getOrCreateSection("Waypoints")),this.readStructures(this.getOrCreateSection("Structures")),this.readVehicles(),this.readInfantries(),this.readAircrafts(),this.readTerrains(this.getOrCreateSection("Terrain")),this.readOverlays(),this.readSmudges(),this.readLighting(),this.readTagsAndTriggers(),this.readCellTags(e),this.readVariableNames(),this.startingLocations=this.readStartingLocations(this.waypoints),this.specialFlags=(new Si).read(this.getOrCreateSection("SpecialFlags")),this}readStartingLocations(e){let t=[];var i;for(i of e.filter(e=>e.number<8).sort((e,t)=>e.number<t.number?-1:1))t.push({x:i.rx,y:i.ry});return t}readLighting(){var e=this.getOrCreateSection("Lighting");this.lighting=(new Ti).read(e),this.ionLighting=(new Ti).read(e,"Ion"),this.ionLighting.forceTint=!0}readTagsAndTriggers(){this.tags=(new yi).read(this.getOrCreateSection("Tags"));var e=this.getOrCreateSection("Triggers"),t=this.getOrCreateSection("Events"),i=this.getOrCreateSection("Actions"),{triggers:e,unknownEventTypes:t,unknownActionTypes:i}=(new wi).read(e,t,i,this.tags);this.triggers=e,this.unknownEventTypes=t,this.unknownActionTypes=i}readCellTags(e){this.cellTags=(new bi).read(this.getOrCreateSection("CellTags"),e)}readVariableNames(){var e,t,i=this.getOrCreateSection("VariableNames");let s=new Map;for([e,t]of i.entries){var r,a,n=Number(e);Number.isNaN(n)?console.warn(`Map [VariableNames] contains non-numeric index "${e}". Skipping.`):([r,a]=t.split(","),a=new vi(r,Boolean(Number(a))),s.set(n,a))}this.variables=s}readTiles(){let e=this.getSection("IsoMapPack5");if(!e)throw new Error("[IsoMapPack5] section not found");var t=L(e.getConcatenatedValues()),i=(2*this.fullSize.width-1)*this.fullSize.height,s=new Uint8Array(11*i+4);pi.decodeInto(t,s);let r=new v(s.buffer),a=2*this.fullSize.width-1;var n,o,h,l,s=this.fullSize.height,c=(e,t)=>t*a+e;this.tiles=new Array(a*s);for(let e=this.maxTileNum=0;e<i;e++){var u=r.readUint16(),d=r.readUint16(),p=Math.max(0,r.readInt16());this.maxTileNum=Math.max(this.maxTileNum,p),r.readInt16();var g=r.readUint8(),m=r.readUint8();r.readUint8();var f=u-d+this.fullSize.width-1,y=u+d-this.fullSize.width-1;0<=f&&f<2*this.fullSize.width&&0<=y&&y<2*this.fullSize.height&&(g={dx:f,dy:y,rx:u,ry:d,z:m,tileNum:p,subTile:g},this.tiles[c(f,Math.floor(y/2))]=g)}for(let t=0;t<this.fullSize.height;t++)for(let e=0;e<=2*this.fullSize.width-2;e++)null==this.tiles[c(e,t)]&&(n=e,l=(o=2*t+e%2)-(h=(n+o)/2+1)+this.fullSize.width+1,this.tiles[c(e,t)]={dx:n,dy:o,rx:h,ry:l,z:0,tileNum:0,subTile:0})}readWaypoints(e){this.waypoints=[];for(var[t,i]of e.entries){var s;let e;isNaN(s=parseInt(t,10))||isNaN(e=parseInt(i,10))||(t=Math.floor(e/1e3),i=e-1e3*t,this.waypoints.push({number:s,rx:i,ry:t}))}}readStructures(e){this.structures=[];for(var[,t]of e.entries){t=t.split(",");if(!(t.length<=15)){let e=new Lt;e.owner=t[0],e.name=t[1],e.health=Number(t[2]),e.rx=Number(t[3]),e.ry=Number(t[4]),e.tag=this.readTagId(t[6]),e.poweredOn=Boolean(Number(t[9])),this.structures.push(e)}}}readTagId(e){return"none"!==e.toLowerCase()?e:void 0}readVehicles(){this.vehicles=[];let e=this.getSection("Units");if(e)for(var t of e.entries.values()){var i=t.split(",");if(i.length<=11)console.warn(`Invalid Vehicle entry: "${t}"`);else{let e=new Ft;e.owner=i[0],e.name=i[1],e.health=Number(i[2]),e.rx=Number(i[3]),e.ry=Number(i[4]),e.direction=Number(i[5]),e.tag=this.readTagId(i[7]),e.veterancy=Number(i[8]),e.onBridge="1"===i[10],this.vehicles.push(e)}}}readInfantries(){this.infantries=[];let e=this.getSection("Infantry");if(e)for(var t of e.entries.values()){var i=t.split(",");let e=new jt;i.length<=8?console.warn(`Invalid Infantry entry: "${t}"`):(e.owner=i[0],e.name=i[1],e.health=Number(i[2]),e.rx=Number(i[3]),e.ry=Number(i[4]),e.subCell=Number(i[5]),e.direction=Number(i[7]),e.tag=this.readTagId(i[8]),e.veterancy=Number(i[9]),e.onBridge="1"===i[11],this.infantries.push(e))}}readAircrafts(){this.aircrafts=[];let e=this.getSection("Aircraft");if(e)for(var t of e.entries.values()){t=t.split(",");let e=new Ut;e.owner=t[0],e.name=t[1],e.health=Number(t[2]),e.rx=Number(t[3]),e.ry=Number(t[4]),e.direction=Number(t[5]),e.tag=this.readTagId(t[7]),e.veterancy=Number(t[8]),e.onBridge="1"===t[t.length-4],this.aircrafts.push(e)}}readTerrains(e){this.terrains=[];for(var[t,i]of e.entries){t=Number(t);if(!isNaN(t)){let e=new Wt;e.name=i,e.rx=t%1e3,e.ry=Math.floor(t/1e3),this.terrains.push(e)}}}readOverlays(){this.overlays=[],this.maxOverlayId=0;let t=this.getSection("OverlayPack");if(t){var i=L(t.getConcatenatedValues()),s=new Uint8Array(1<<18);pi.decodeInto(i,s,80);let e=this.getSection("OverlayDataPack");if(e){var i=L(e.getConcatenatedValues()),r=new Uint8Array(1<<18);pi.decodeInto(i,r,80);for(let t=0;t<this.fullSize.height;t++)for(let e=2*this.fullSize.width-2;0<=e;e--){var a=e,n=2*t+e%2,o=(a+n)/2+1,h=n-o+this.fullSize.width+1,a=o+512*h,n=s[a];if(255!==n){a=r[a];let e=new Vt;e.id=n,e.value=a,e.rx=o,e.ry=h,this.overlays.push(e),this.maxOverlayId=Math.max(this.maxOverlayId,n)}}}else console.warn("[OverlayDataPack] section not found. Skipping.")}else console.warn("[Overlay] section not found. Skipping.")}readSmudges(){this.smudges=[];let e=this.getSection("Smudge");if(e)for(var t of e.entries.values()){t=t.split(",");if(t.length<=2)console.warn(`Invalid Smudge entry: "${t}"`);else{let e=new zt;e.name=t[0],e.rx=Number(t[1]),e.ry=Number(t[2]),this.smudges.push(e)}}}decodePreviewImage(){let e=this.getSection("Preview"),t=this.getSection("PreviewPack");if(e&&t){var[,,i,s]=e.getArray("Size").map(e=>Number(e)),r=L(t.getConcatenatedValues()),s=new fi(i,s);return pi.decodeInto(r,s.data),s}}}(r=Zt=Zt||{})[r.GDI=0]="GDI",r[r.Nod=1]="Nod",r[r.Civilian=2]="Civilian",r[r.Mutant=3]="Mutant";const Oi=(new Map).set("GDI",Zt.GDI).set("Nod",Zt.Nod).set("Civilian",Zt.Civilian).set("Mutant",Zt.Mutant),_i=new Map([["Americans","STT:PlayerSideAmerica"],["Alliance","STT:PlayerSideKorea"],["French","STT:PlayerSideFrance"],["Germans","STT:PlayerSideGermany"],["British","STT:PlayerSideBritain"],["Africans","STT:PlayerSideLibya"],["Arabs","STT:PlayerSideIraq"],["Confederation","STT:PlayerSideCuba"],["Russians","STT:PlayerSideRussia"]]);class Ii{constructor(e){this.id=e}readIni(e){this.name=e.name,this.uiName=e.getString("UIName"),this.uiTooltip=e.get("UITooltip")||_i.get(this.name);var t=e.getString("Side");if(!t)throw new Error(`Missing Side for country "${this.name}"`);var i=Oi.get(t);if(void 0===i)throw new Error(`Unknown side "${t}" for country "${this.name}"`);this.side=i,this.multiplay=e.getBool("Multiplay"),this.multiplayPassive=e.getBool("MultiplayPassive"),this.veteranAircraft=e.getArray("VeteranAircraft"),this.veteranInfantry=e.getArray("VeteranInfantry"),this.veteranUnits=e.getArray("VeteranUnits")}}class Ci{constructor(e,t,i=-1){this.type=e,this.ini=t,this.index=i,this.parse()}static iniSpeedToLeptonsPerTick(e,t){return Math.min(256,256*e/t)}static iniRotToDegsPerTick(e){return e/256*360}parse(){this.alphaImage=this.ini.getString("AlphaImage")||void 0,this.alternateArcticArt=this.ini.getBool("AlternateArcticArt"),this.crushable=this.ini.getBool("Crushable",this.type===xt.Infantry),this.crushSound=this.ini.getString("CrushSound")||void 0,this.dontScore=this.ini.getBool("DontScore"),this.insignificant=this.ini.getBool("Insignificant"),this.legalTarget=this.ini.getBool("LegalTarget",!0),this.noShadow=this.ini.getBool("NoShadow"),this.uiName=this.ini.getString("UIName")}get name(){return this.ini.name}get imageName(){let e=this.ini.getString("Image");return e&&"null"!==e||(e=this.name),e}}Ci.IMAGE_NONE="none";class Ai{constructor(e){this.rules=e,this.parse()}parse(){this.ambientDamage=this.rules.getNumber("AmbientDamage"),this.anim=this.rules.getArray("Anim"),this.areaFire=this.rules.getBool("AreaFire"),this.burst=this.rules.getNumber("Burst",1),this.cellRangefinding=this.rules.getBool("CellRangefinding"),this.damage=this.rules.getNumber("Damage"),this.decloakToFire=this.rules.getBool("DecloakToFire",!0),this.fireOnce=this.rules.getBool("FireOnce"),this.isAlternateColor=this.rules.getBool("IsAlternateColor"),this.isElectricBolt=this.rules.getBool("IsElectricBolt"),this.isHouseColor=this.rules.getBool("IsHouseColor"),this.isLaser=this.rules.getBool("IsLaser"),this.isRadBeam=this.rules.getBool("IsRadBeam"),this.isSonic=this.rules.getBool("IsSonic"),this.laserDuration=this.rules.getNumber("LaserDuration"),this.limboLaunch=this.rules.getBool("LimboLaunch"),this.minimumRange=this.rules.getNumber("MinimumRange"),this.name=this.rules.name,this.neverUse=this.rules.getBool("NeverUse"),this.omniFire=this.rules.getBool("OmniFire"),this.projectile=this.rules.getString("Projectile"),this.radLevel=this.rules.getNumber("RadLevel"),this.range=this.rules.getNumber("Range"),-2===this.range&&(this.range=Number.POSITIVE_INFINITY),this.report=this.rules.getArray("Report"),this.revealOnFire=this.rules.getBool("RevealOnFire",!0),this.rof=this.rules.getNumber("ROF"),this.sabotageCursor=this.rules.getBool("SabotageCursor"),this.spawner=this.rules.getBool("Spawner");var e=this.rules.getNumber("Speed");this.iniSpeed=e,this.speed=Ci.iniSpeedToLeptonsPerTick(e,100),this.suicide=this.rules.getBool("Suicide"),this.useSparkParticles=this.rules.getBool("UseSparkParticles"),this.warhead=this.rules.getString("Warhead")}}class Bi{readIni(e){this.ini=e,this.ambientChangeRate=e.getNumber("AmbientChangeRate"),this.ambientChangeStep=e.getNumber("AmbientChangeStep"),this.behind=e.getString("Behind"),this.bridgeExplosions=e.getArray("BridgeExplosions"),this.chronoBeamColor=e.getNumberArray("ChronoBeamColor"),this.chronoBlast=e.getString("ChronoBlast"),this.chronoBlastDest=e.getString("ChronoBlastDest"),this.chronoPlacement=e.getString("ChronoPlacement"),this.chronoSparkle1=e.getString("ChronoSparkle1"),this.conditionRed=e.getNumber("ConditionRed"),this.conditionYellow=e.getNumber("ConditionYellow"),this.creditTicks=e.getArray("CreditTicks"),this.extraAircraftLight=e.getNumber("ExtraAircraftLight"),this.extraInfantryLight=e.getNumber("ExtraInfantryLight"),this.extraUnitLight=e.getNumber("ExtraUnitLight");let t=e.getString("DamageFireTypes");t=t||"FIRE01,FIRE02,FIRE03",this.fireNames=t.split(/\.|,/).filter(e=>""!==e),this.flyerHelper=e.getString("FlyerHelper"),this.gravity=e.getNumber("Gravity"),this.idleActionFrequency=60*e.getNumber("IdleActionFrequency"),this.impactLandSound=e.getString("ImpactLandSound")||void 0,this.impactWaterSound=e.getString("ImpactWaterSound")||void 0,this.infantryExplode=e.getString("InfantryExplode"),this.flamingInfantry=e.getString("FlamingInfantry"),this.infantryHeadPop=e.getString("InfantryHeadPop"),this.infantryNuked=e.getString("InfantryNuked"),this.ironCurtainInvokeAnim=e.getString("IronCurtainInvokeAnim"),this.messageDuration=e.getNumber("MessageDuration",10),this.metallicDebris=e.getArray("MetallicDebris"),this.nukeTakeOff=e.getString("NukeTakeOff"),this.deadBodies=e.getArray("DeadBodies"),this.wake=e.getString("Wake"),this.parachute=e.getString("Parachute"),this.moveFlash=e.getString("MoveFlash"),this.warpOut=e.getString("WarpOut"),this.warpAway=e.getString("WarpAway"),this.weaponNullifyAnim=e.getString("WeaponNullifyAnim"),this.weatherConClouds=e.getArray("WeatherConClouds"),this.weatherConBoltExplosion=e.getString("WeatherConBoltExplosion"),this.weatherConBolts=e.getArray("WeatherConBolts")}}(r=Qt=Qt||{})[r.GenericCombat=0]="GenericCombat",r[r.GenericNonCombat=1]="GenericNonCombat",r[r.DropZone=2]="DropZone",r[r.BaseUnderAttack=3]="BaseUnderAttack",r[r.HarvesterUnderAttack=4]="HarvesterUnderAttack",r[r.EnemyObjectSensed=5]="EnemyObjectSensed";class xi{readIni(e){return this.eventSuppressionDistances=e.getNumberArray("RadarEventSuppressionDistances"),this.eventVisibilityDurations=e.getNumberArray("RadarEventVisibilityDurations"),this.eventDurations=e.getNumberArray("RadarEventDurations"),this.flashFrameTime=e.getNumber("FlashFrameTime"),this.combatFlashTime=e.getNumber("RadarCombatFlashTime"),this.eventMinRadius=e.getNumber("RadarEventMinRadius"),this.eventSpeed=e.getNumber("RadarEventSpeed"),this.eventRotationSpeed=e.getNumber("RadarEventRotationSpeed"),this.eventColorSpeed=e.getNumber("RadarEventColorSpeed"),this}getEventSuppresionDistance(e){if(e>this.eventSuppressionDistances.length-1)throw new RangeError(`No event suppression distance is defined for type ${Qt[e]}`);return this.eventSuppressionDistances[e]}getEventVisibilityDuration(e){if(e>this.eventVisibilityDurations.length-1)throw new RangeError(`No event visibility duration is defined for type ${Qt[e]}`);return this.eventVisibilityDurations[e]}getEventDuration(e){if(e>this.eventDurations.length-1)throw new RangeError(`No event duration is defined for type ${Qt[e]}`);return this.eventDurations[e]}}class Ei{readIni(e){return this.reloadRate=e.getNumber("ReloadRate"),this.repairPercent=e.getNumber("RepairPercent"),this.repairRate=e.getNumber("RepairRate"),this.repairStep=e.getNumber("RepairStep"),this.uRepairRate=e.getNumber("URepairRate"),this.iRepairRate=e.getNumber("IRepairRate"),this.iRepairStep=e.getNumber("IRepairStep"),this}}class Pi{readIni(e){return this.veteranRatio=e.getNumber("VeteranRatio",3),this.veteranCombat=e.getNumber("VeteranCombat",1),this.veteranSpeed=e.getNumber("VeteranSpeed",1),this.veteranSight=Math.max(1,e.getNumber("VeteranSight",1)),this.veteranArmor=e.getNumber("VeteranArmor",1),this.veteranROF=e.getNumber("VeteranROF",1),this.veteranCap=e.getNumber("VeteranCap",2),this.initialVeteran=e.getBool("InitialVeteran"),this}}class Ni{readIni(e){return this.alliedCrew=e.getString("AlliedCrew"),this.alliedSurvivorDivisor=e.getNumber("AlliedSurvivorDivisor"),this.crewEscape=e.getNumber("CrewEscape"),this.sovietCrew=e.getString("SovietCrew"),this.sovietSurvivorDivisor=e.getNumber("SovietSurvivorDivisor"),this.survivorRate=e.getNumber("SurvivorRate"),this}}class Mi{readIni(e){return this.type=e.getString("PrismType"),this.supportHeight=e.getNumber("PrismSupportHeight"),this.supportMax=e.getNumber("PrismSupportMax"),this.supportModifier=e.getNumber("PrismSupportModifier",1),this}}class Di{readIni(e){return this.myEffectivenessCoefficientDefault=e.getNumber("MyEffectivenessCoefficientDefault"),this.targetEffectivenessCoefficientDefault=e.getNumber("TargetEffectivenessCoefficientDefault"),this.targetSpecialThreatCoefficientDefault=e.getNumber("TargetSpecialThreatCoefficientDefault"),this.targetStrengthCoefficientDefault=e.getNumber("TargetStrengthCoefficientDefault"),this.targetDistanceCoefficientDefault=e.getNumber("TargetDistanceCoefficientDefault"),this}}class Ri{readIni(e){if(this.allyParaDrop=this.readParadropSquad(e.getArray("AllyParaDropInf"),e.getNumberArray("AllyParaDropNum"),"Ally"),this.amerParaDrop=this.readParadropSquad(e.getArray("AmerParaDropInf"),e.getNumberArray("AmerParaDropNum"),"Amer"),this.sovParaDrop=this.readParadropSquad(e.getArray("SovParaDropInf"),e.getNumberArray("SovParaDropNum"),"Sov"),this.paradropPlane=e.getString("ParadropPlane"),!this.paradropPlane)throw new Error("Missing rules [General]->ParadropPlane");return this.paradropRadius=e.getNumber("ParadropRadius"),this}readParadropSquad(t,i,e){if(t.length!==i.length)throw new RangeError(`${e}ParaDropInf/Num size mismatch (${t.length}, ${i.length})`);let s=[];for(let e=0;e<t.length;++e)0<i[e]&&s.push({inf:t[e],num:i[e]});return s}getParadropSquads(e){switch(e){case Zt.GDI:return this.allyParaDrop;case Zt.Nod:return this.sovParaDrop;default:throw new Error(`Unhandled side type "${e}"`)}}}class Li{readIni(e){return this.deferment=e.getNumber("LightningDeferment"),this.damage=e.getNumber("LightningDamage"),this.duration=e.getNumber("LightningStormDuration"),this.warhead=e.getString("LightningWarhead"),this.hitDelay=e.getNumber("LightningHitDelay"),this.scatterDelay=e.getNumber("LightningScatterDelay"),this.cellSpread=e.getNumber("LightningCellSpread"),this.separation=e.getNumber("LightningSeparation"),this}}class Fi{}class ji extends Fi{readIni(e){return this.pauseFrames=e.getNumber("V3RocketPauseFrames"),this.tiltFrames=e.getNumber("V3RocketTiltFrames"),this.pitchInitial=e.getNumber("V3RocketPitchInitial"),this.pitchFinal=e.getNumber("V3RocketPitchFinal"),this.turnRate=e.getNumber("V3RocketTurnRate"),this.acceleration=e.getNumber("V3RocketAcceleration"),this.altitude=e.getNumber("V3RocketAltitude"),this.damage=e.getNumber("V3RocketDamage"),this.eliteDamage=e.getNumber("V3RocketEliteDamage"),this.bodyLength=e.getNumber("V3RocketBodyLength"),this.lazyCurve=e.getBool("V3RocketLazyCurve"),this.type=e.getString("V3RocketType"),this}}class Ui extends Fi{readIni(e){return this.pauseFrames=e.getNumber("DMislPauseFrames"),this.tiltFrames=e.getNumber("DMislTiltFrames"),this.pitchInitial=e.getNumber("DMislPitchInitial"),this.pitchFinal=e.getNumber("DMislPitchFinal"),this.turnRate=e.getNumber("DMislTurnRate"),this.acceleration=e.getNumber("DMislAcceleration"),this.altitude=e.getNumber("DMislAltitude"),this.damage=e.getNumber("DMislDamage"),this.eliteDamage=e.getNumber("DMislEliteDamage"),this.bodyLength=e.getNumber("DMislBodyLength"),this.lazyCurve=e.getBool("DMislLazyCurve"),this.type=e.getString("DMislType"),this}}class Wi{readIni(e){return this.height=e.getNumber("HoverHeight"),this.dampen=e.getNumber("HoverDampen"),this.bob=e.getNumber("HoverBob"),this.boost=e.getNumber("HoverBoost"),this.acceleration=e.getNumber("HoverAcceleration"),this.brake=e.getNumber("HoverBrake"),this}}(r=Yt=Yt||{})[r.Power=0]="Power",r[r.Factory=1]="Factory",r[r.Barracks=2]="Barracks",r[r.Radar=3]="Radar",r[r.Tech=4]="Tech",r[r.Proc=5]="Proc";const zi=(new Map).set(Yt.Power,"PrerequisitePower").set(Yt.Factory,"PrerequisiteFactory").set(Yt.Barracks,"PrerequisiteBarracks").set(Yt.Radar,"PrerequisiteRadar").set(Yt.Tech,"PrerequisiteTech").set(Yt.Proc,"PrerequisiteProc");class Vi{constructor(){this.prereqCategories=new Map}readIni(e){this.aircraftFogReveal=e.getNumber("AircraftFogReveal"),this.alliedDisguise=e.getString("AlliedDisguise"),this.baseUnit=e.getArray("BaseUnit"),this.bridgeVoxelMax=e.getNumber("BridgeVoxelMax"),this.buildSpeed=e.getFixed("BuildSpeed"),this.buildupTime=e.getNumber("BuildupTime"),this.chronoDelay=e.getNumber("ChronoDelay"),this.chronoDistanceFactor=e.getNumber("ChronoDistanceFactor",32),this.chronoHarvTooFarDistance=e.getNumber("ChronoHarvTooFarDistance"),this.chronoMinimumDelay=e.getNumber("ChronoMinimumDelay"),this.chronoRangeMinimum=e.getNumber("ChronoRangeMinimum"),this.chronoTrigger=e.getBool("ChronoTrigger",!0),this.cliffBackImpassability=e.getNumber("CliffBackImpassability",2),this.cloakDelay=e.getNumber("CloakDelay"),this.closeEnough=e.getNumber("CloseEnough"),this.crew=(new Ni).readIni(e),this.defaultMirageDisguises=e.getArray("DefaultMirageDisguises"),this.dMisl=(new Ui).readIni(e),this.dropPodWeapon=e.getString("DropPodWeapon"),this.engineer=e.getString("Engineer"),this.flightLevel=e.getNumber("FlightLevel"),this.guardAreaTargetingDelay=e.getNumber("GuardAreaTargetingDelay"),this.harvesterTooFarDistance=e.getNumber("HarvesterTooFarDistance"),this.harvesterUnit=e.getArray("HarvesterUnit"),this.hover=(new Wi).readIni(e),this.infantryBlinkDisguiseTime=e.getNumber("InfantryBlinkDisguiseTime"),this.lightningStorm=(new Li).readIni(e),this.lowPowerPenaltyModifier=e.getNumber("LowPowerPenaltyModifier",1),this.minLowPowerProductionSpeed=e.getFixed("MinLowPowerProductionSpeed",.5),this.maxLowPowerProductionSpeed=e.getFixed("MaxLowPowerProductionSpeed",1),this.maximumCheerRate=e.getNumber("MaximumCheerRate"),this.maximumQueuedObjects=e.getNumber("MaximumQueuedObjects"),this.maxWaypointPathLength=e.getNumber("MaxWaypointPathLength"),this.multipleFactory=e.getFixed("MultipleFactory",1),this.normalTargetingDelay=e.getNumber("NormalTargetingDelay"),this.padAircraft=e.getArray("PadAircraft"),this.parachuteMaxFallRate=e.getNumber("ParachuteMaxFallRate"),this.paradrop=(new Ri).readIni(e),this.prism=(new Mi).readIni(e),this.purifierBonus=e.getNumber("PurifierBonus"),this.radar=(new xi).readIni(e),this.refundPercent=z(e.getNumber("RefundPercent"),0,1),this.repair=(new Ei).readIni(e),this.revealTriggerRadius=Math.min(10,e.getNumber("RevealTriggerRadius")),this.shipSinkingWeight=e.getNumber("ShipSinkingWeight"),this.sovietDisguise=e.getString("SovietDisguise"),this.spyMoneyStealPercent=e.getNumber("SpyMoneyStealPercent"),this.spyPowerBlackout=e.getNumber("SpyPowerBlackout"),this.technician=e.getString("Technician"),this.threat=(new Di).readIni(e),this.treeStrength=e.getNumber("TreeStrength"),this.v3Rocket=(new ji).readIni(e),this.veteran=(new Pi).readIni(e),this.wallBuildSpeedCoefficient=e.getFixed("WallBuildSpeedCoefficient"),this.readPrereqCategories(e)}readPrereqCategories(e){for(var[t,i]of zi){if(!e.has(i))throw new Error(`Missing prerequisite category ${i} in [General] section`);this.prereqCategories.set(t,e.getArray(i))}}getMissileRules(e){switch(e){case this.v3Rocket.type:return this.v3Rocket;case this.dMisl.type:return this.dMisl;default:throw new Error(`Unsupported missile type "${e}"`)}}}(r=Kt=Kt||{})[r.Default=0]="Default",r[r.Tunnel=5]="Tunnel",r[r.Railroad=6]="Railroad",r[r.Rock1=7]="Rock1",r[r.Rock2=8]="Rock2",r[r.Water=9]="Water",r[r.Shore=10]="Shore",r[r.Pavement=11]="Pavement",r[r.Dirt=12]="Dirt",r[r.Clear=13]="Clear",r[r.Rough=14]="Rough",r[r.Cliff=15]="Cliff",(r=Jt=Jt||{})[r.Clear=0]="Clear",r[r.Road=1]="Road",r[r.Rock=2]="Rock",r[r.Beach=3]="Beach",r[r.Rough=4]="Rough",r[r.Railroad=5]="Railroad",r[r.Weeds=6]="Weeds",r[r.Water=7]="Water",r[r.Wall=8]="Wall",r[r.Tiberium=9]="Tiberium",r[r.Cliff=10]="Cliff";const Hi=new Map([[Kt.Default,Jt.Clear],[Kt.Clear,Jt.Clear],[Kt.Tunnel,Jt.Cliff],[Kt.Railroad,Jt.Railroad],[Kt.Rock1,Jt.Rock],[Kt.Rock2,Jt.Rock],[Kt.Water,Jt.Water],[Kt.Shore,Jt.Beach],[Kt.Pavement,Jt.Road],[Kt.Dirt,Jt.Road],[Kt.Rough,Jt.Rough],[Kt.Cliff,Jt.Cliff]]);function Gi(e){if(!Hi.has(e))throw new Error(`Unknown terrain type ${e}`);return Hi.get(e)}(r=ei=ei||{})[r.Foot=0]="Foot",r[r.Track=1]="Track",r[r.Wheel=2]="Wheel",r[r.Hover=3]="Hover",r[r.Float=4]="Float",r[r.FloatBeach=5]="FloatBeach",r[r.Amphibious=6]="Amphibious",r[r.Winged=7]="Winged";class $i{constructor(){this.speedModifiers=new Map}readIni(t){return this.buildable=t.getBool("Buildable",!1),[...t.entries.keys()].forEach(e=>{void 0!==ei[e]&&this.speedModifiers.set(ei[e],t.getNumber(e))}),this}getSpeedModifier(e){if(e===ei.Foot&&0===this.speedModifiers.get(ei.Track))return 0;let t=this.speedModifiers.get(e);return void 0===t&&(t=1),e!==ei.Track&&e!==ei.Wheel&&0<t&&(t=1),t}}(r=ti=ti||{})[r.None=0]="None",r[r.Gunfire=1]="Gunfire",r[r.Explode=2]="Explode",r[r.ExplodeAlt=3]="ExplodeAlt",r[r.Fire=4]="Fire",r[r.Electro=5]="Electro",r[r.HeadExplode=6]="HeadExplode",r[r.Nuke=7]="Nuke";class qi{constructor(e){this.rules=e,this.verses=new Map,this.parse()}get name(){return this.rules.name}parse(){this.animList=this.rules.getArray("AnimList"),this.bombDisarm=this.rules.getBool("BombDisarm"),this.bullets=this.rules.getBool("Bullets"),this.causesDelayKill=this.rules.getBool("CausesDelayKill"),this.cellSpread=this.rules.getNumber("CellSpread"),this.conventional=this.rules.getBool("Conventional"),this.culling=this.rules.getBool("Culling"),this.delayKillAtMax=this.rules.getNumber("DelayKillAtMax"),this.delayKillFrames=this.rules.getNumber("DelayKillFrames"),this.electricAssault=this.rules.getBool("ElectricAssault"),this.emEffect=this.rules.getBool("EMEffect"),this.infDeath=this.rules.getEnumNumeric("InfDeath",ti,ti.None),this.ivanBomb=this.rules.getBool("IvanBomb"),this.makesDisguise=this.rules.getBool("MakesDisguise"),this.mindControl=this.rules.getBool("MindControl"),this.nukeMaker=this.rules.getBool("NukeMaker"),this.paralyzes=this.rules.getNumber("Paralyzes"),this.parasite=this.rules.getBool("Parasite"),this.percentAtMax=this.rules.getNumber("PercentAtMax",1),this.proneDamage=this.rules.getNumber("ProneDamage",1),this.psychicDamage=this.rules.getBool("PsychicDamage"),this.radiation=this.rules.getBool("Radiation"),this.rocker=this.rules.getBool("Rocker"),this.sonic=this.rules.getBool("Sonic"),this.temporal=this.rules.getBool("Temporal");let e=this.rules.getFixedArray("Verses");e.forEach((e,t)=>this.verses.set(t,e)),this.wallAbsoluteDestroyer=this.rules.getBool("WallAbsoluteDestroyer"),this.wall=this.rules.getBool("Wall"),this.wood=this.rules.getBool("Wood")}}class Xi extends Ci{parse(){super.parse();var e=this.ini.getNumber("ROT",0);let t=this.ini.getNumber("Acceleration");1!==e||t||(t=Number.POSITIVE_INFINITY),t=t||3,this.acceleration=t,this.arcing=this.ini.getBool("Arcing"),this.courseLockDuration=this.ini.getNumber("CourseLockDuration"),this.detonationAltitude=this.ini.getNumber("DetonationAltitude"),this.firersPalette=this.ini.getBool("FirersPalette"),this.flakScatter=this.ini.getBool("FlakScatter"),this.inaccurate=this.ini.getBool("Inaccurate"),this.inviso=this.ini.getBool("Inviso"),this.isAntiAir=this.ini.getBool("AA"),this.isAntiGround=this.ini.getBool("AG",!0),this.level=this.ini.getBool("Level"),this.rot=Ci.iniRotToDegsPerTick(e),this.iniRot=e,this.shadow=this.ini.getBool("Shadow",!0),this.shrapnelWeapon=this.ini.getString("ShrapnelWeapon")||void 0,this.shrapnelCount=this.ini.getNumber("ShrapnelCount"),this.subjectToCliffs=this.ini.getBool("SubjectToCliffs"),this.subjectToElevation=this.ini.getBool("SubjectToElevation"),this.subjectToWalls=this.ini.getBool("SubjectToWalls"),this.vertical=this.ini.getBool("Vertical")}}(r=ii=ii||{})[r.Green=0]="Green",r[r.Yellow=1]="Yellow",r[r.White=2]="White",r[r.Red=3]="Red",r[r.Blue=4]="Blue",(r=si=si||{})[r.Statue=0]="Statue",r[r.Aircraft=1]="Aircraft",r[r.Chrono=2]="Chrono",r[r.Hover=3]="Hover",r[r.Infantry=4]="Infantry",r[r.Jumpjet=5]="Jumpjet",r[r.Missile=6]="Missile",r[r.Ship=7]="Ship",r[r.Vehicle=8]="Vehicle";const Zi=new Map([["{4A582746-9839-11d1-B709-00A024DDAFD1}",si.Aircraft],["{4A582747-9839-11d1-B709-00A024DDAFD1}",si.Chrono],["{4A582742-9839-11d1-B709-00A024DDAFD1}",si.Hover],["{4A582744-9839-11d1-B709-00A024DDAFD1}",si.Infantry],["{92612C46-F71F-11d1-AC9F-006008055BB5}",si.Jumpjet],["{B7B49766-E576-11d3-9BD9-00104B972FE8}",si.Missile],["{2BEA74E1-7CCA-11d3-BE14-00104B62A16C}",si.Ship],["{4A582741-9839-11d1-B709-00A024DDAFD1}",si.Vehicle]]),Qi=new Map([[si.Infantry,ei.Foot],[si.Ship,ei.Float],[si.Hover,ei.Hover],[si.Jumpjet,ei.Winged],[si.Aircraft,ei.Winged],[si.Missile,ei.Winged]]);(r=ri=ri||{})[r.Amphibious=0]="Amphibious",r[r.AmphibiousCrusher=1]="AmphibiousCrusher",r[r.AmphibiousDestroyer=2]="AmphibiousDestroyer",r[r.Crusher=3]="Crusher",r[r.CrusherAll=4]="CrusherAll",r[r.Destroyer=5]="Destroyer",r[r.Fly=6]="Fly",r[r.Infantry=7]="Infantry",r[r.InfantryDestroyer=8]="InfantryDestroyer",r[r.Normal=9]="Normal",r[r.Subterranean=10]="Subterranean",r[r.Water=11]="Water",(r=ai=ai||{})[r.None=0]="None",r[r.Flak=1]="Flak",r[r.Plate=2]="Plate",r[r.Light=3]="Light",r[r.Medium=4]="Medium",r[r.Heavy=5]="Heavy",r[r.Wood=6]="Wood",r[r.Steel=7]="Steel",r[r.Concrete=8]="Concrete",r[r.Special_1=9]="Special_1",r[r.Special_2=10]="Special_2",(r=ni=ni||{})[r.LandOk=0]="LandOk",r[r.LandNotOk=1]="LandNotOk",r[r.LandSecondary=2]="LandSecondary",(r=oi=oi||{})[r.UnderwaterNever=0]="UnderwaterNever",r[r.UnderwaterSecondary=1]="UnderwaterSecondary",r[r.UnderwaterOnly=2]="UnderwaterOnly",r[r.OrganicSecondary=3]="OrganicSecondary",r[r.SealSpecial=4]="SealSpecial",r[r.NavalAll=5]="NavalAll",r[r.NavalNone=6]="NavalNone",(r=hi=hi||{})[r.Primary=0]="Primary",r[r.Secondary=1]="Secondary",r[r.DeathWeapon=2]="DeathWeapon",(r=li=li||{})[r.FASTER=0]="FASTER",r[r.STRONGER=1]="STRONGER",r[r.FIREPOWER=2]="FIREPOWER",r[r.SCATTER=3]="SCATTER",r[r.ROF=4]="ROF",r[r.SIGHT=5]="SIGHT",r[r.SELF_HEAL=6]="SELF_HEAL",r[r.CLOAK=7]="CLOAK",r[r.EXPLODES=8]="EXPLODES",r[r.RADAR_INVISIBLE=9]="RADAR_INVISIBLE",r[r.SENSORS=10]="SENSORS",r[r.FEARLESS=11]="FEARLESS",r[r.C4=12]="C4",r[r.GUARD_AREA=13]="GUARD_AREA",r[r.CRUSHER=14]="CRUSHER",(r=ci=ci||{})[r.None=0]="None",r[r.Normal=1]="Normal",r[r.Strong=2]="Strong";class Yi{static reverseSinTableLookup(e,t,i,s){for(;t<=i;){var r=Math.floor((t+i)/2),a=this.SIN_TABLE[r];if(a===e)return r;(s?e<a:a<e)?t=r+1:i=r-1}return Math.abs(e-this.SIN_TABLE[t])<Math.abs(e-this.SIN_TABLE[i])?t:i}static pow(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||Number.isSafeInteger(e)&&Number.isSafeInteger(t))return e**t;if(!Number.isSafeInteger(t))throw new Error("Exponent must be a safe integer");return Math.floor(e*this.EXP_10_PRECISION)**t/this.EXP_10_PRECISION**t}static sqrt(e){if(0===e)return 0;var t;let i=e/3;for(;t=i,i=(e/i+i)/2,5e-15<Math.abs(t-i););return i}static sin(e){if(!Number.isFinite(e))return NaN;if(!e)return e;e=e/(2*Math.PI)-Math.floor(e/(2*Math.PI)),e=Math.floor(e*this.SIN_TABLE.length);return this.SIN_TABLE[e]}static cos(e){return this.sin(e+Math.PI/2)}static asin(e){if(!V(e,-1,1))return NaN;if(!e)return 0;let t;var i=this.SIN_TABLE.length;return t=0<e?2*Math.PI*this.reverseSinTableLookup(e,0,i/4,!1)/i:Math.PI-2*Math.PI*this.reverseSinTableLookup(e,i/2,.75*i,!0)/i,t}static acos(e){return Math.PI/2-this.asin(e)}static atan2(e,t){if(Number.isNaN(t)||Number.isNaN(e))return NaN;let i;return i=Number.isFinite(e)||Number.isFinite(t)?Number.isFinite(t)&&0!==e?Number.isFinite(e)&&0!==t?this.atan2FiniteNonZero(e,t):this.signIncZero(e)*Math.PI*.5:this.signIncZero(e)*(this.signIncZero(t)<0?Math.PI:0):Math.sign(e)*Math.PI*(0<Math.sign(t)?.25:.75),i}static atan2FiniteNonZero(e,t){var i=Math.abs(t),s=Math.abs(e),r=Math.min(i,s)/Math.max(i,s),a=r*r;let n=((-.0464964749*a+.15931422)*a-.327622764)*a*r+r;return i<s&&(n=Math.PI/2-n),t<0&&(n=Math.PI-n),e<0&&(n=-n),n}static signIncZero(e){return e===-1/0||1/e<0?-1:1}}Yi.PRECISION=6,Yi.EXP_10_PRECISION=10**Yi.PRECISION,Yi.SIN_TABLE=[0,.004848117819001859,.009696121685978396,.014543897651582654,.01939133177182437,.024238310110748135,.0290847187431114,.03393044375706223,.03877537125681671,.043619387365336,.04846237822700296,.05330423001029823,.05814482891047582,.06298406115223795,.06782181299240934,.0726579707226106,.07749242067193093,.08232504920959989,.08715574274765817,.09198438774362744,.09681087070317909,.10163507818280187,.10645689679246824,.11127621319829964,.11609291412523022,.12090688635966935,.12571801675216268,.13052619222005157,.13533129975013108,.14013322640130627,.14493185930724672,.1497270856790396,.15451879280784048,.15930686806752256,.16409119891732396,.1688716729044928,.17364817766693033,.17842060093583212,.18318883053832663,.18795275440011186,.19271226054808968,.19746723711299752,.20221757233203794,.20696315455150538,.2117038722294107,.21643961393810288,.22117026836688775,.2258957243246448,.23061587074244014,.2353305966761376,.24003979130900588,.2447433439543238,.24944114405798126,.25413308120107847,.25881904510252074,.26349892562161076,.2681726127606373,.272839996667461,.27750096763809573,.28215541611928774,.2868032327110902,.29144430816943495,.2960785334086999,.3007057995042731,.3053259976951131,.30993901938630514,.31454475615161365,.31914309973603083,.323733942058321,.328317175213561,.33289269147567657,.3374603832999741,.3420201433256687,.34657186437840753,.3511154394727888,.3556507618148765,.3601777248047104,.36469622203881186,.3692061473126844,.3737073946233105,.3781998581716425,.3826834323650898,.3871580118200006,.3916234913641391,.3960797660391568,.4005267311030606,.4049642820326736,.4093923145260926,.4138107245051391,.4182194081178064,.42261826174069944,.4270071819814715,.4313860656812534,.4357548099170794,.4401133120043048,.44446146949902104,.4487991802004621,.4531263421534082,.4574428536505808,.4617486132350339,.46604351970253877,.4703274721039625,.4746003697476404,.4788621122017435,.4831125992966384,.48735173112724234,.49157940805537054,.49579553071207916,.49999999999999994,.5041927170956704,.5083735834518556,.5125425007998652,.5166993711518628,.5208440968031697,.5249765803345602,.5290967246145525,.5332044328016912,.5372996083468239,.5413821549953696,.5454519767895825,.549508978070806,.5535530634817223,.5575841379685927,.5616021067834929,.5656068754865385,.5695983499481065,.573576436351046,.5775410411928851,.5814920712880266,.5854294337699405,.5893530360933448,.593262786036382,.5971585917027862,.6010403615240428,.6049080042615417,.6087614290087207,.6126005451932028,.6164252625789254,.62023549126826,.6240311417041269,.6278121246720986,.6315783513024975,.6353297330724851,.6390661818081416,.6427876096865393,.6464939292378065,.6501850533471834,.6538608952570697,.6575213685690636,.6611663872459932,.6647958656139378,.6684097183642425,.6720078605555224,.6755902076156601,.6791566753437932,.6827071799122926,.6862416378687335,.6897599661378576,.6932620820235242,.696747903210655,.7002173477671685,.7036703341459059,.7071067811865475,.710526608117521,.713929734557899,.7173160805192894,.7206855664077146,.7240381130254825,.7273736415730487,.7306920736508674,.7339933312612352,.7372773368101241,.7405440131090046,.7437932833766612,.747025071240996,.7502393007408245,.7534358963276606,.7566147828674927,.7597758856425494,.7629191303530553,.766044443118978,.7691517504817651,.7722409794060692,.7753120572814658,.7783649119241599,.7813994715786823,.7844156649195757,.7874134210530723,.7903926695187593,.7933533402912352,.7962953637817558,.7992186708398696,.8021231927550437,.8050088612582783,.8078756085237111,.8107233671702122,.8135520702629676,.8163616513150519,.8191520442889918,.821923183598318,.8246750041091067,.8274074411415104,.8301204304712788,.8328139083312671,.8354878114129364,.8381420768678404,.8407766423091032,.8433914458128856,.845986425919841,.848561521636559,.8511166724369997,.8536518182639162,.8561668995302665,.8586618571206132,.8611366323925137,.8635911671778986,.8660254037844386,.8684392849969005,.870832754078492,.8732057547721958,.8755582313020908,.8778901283746645,.8802013911801111,.8824919653936212,.8847617971766577,.8870108331782216,.8892390205361062,.8914463068781385,.8936326403234122,.8957979694835052,.8979422434636881,.9000654118641211,.9021674247810376,.9042482328079179,.9063077870366499,.9083460390586793,.9103629409661466,.9123584453530141,.9143325053161794,.9162850744565779,.918216106880274,.9201255571995389,.9220133805339185,.9238795325112867,.9257239692688903,.9275466474543786,.9293475242268224,.9311265572577219,.9328837047320004,.9346189253489884,.9363321783233931,.9380234233862578,.9396926207859083,.9413397312888874,.942964716180876,.9445675372676047,.9461481568757504,.947706537853822,.9492426435730339,.9507564379281666,.9522478853384153,.9537169507482269,.955163599628123,.9565877979755122,.9579895123154889,.9593687097016201,.9607253577167205,.9620594244736131,.9633708786158803,.9646596893185995,.9659258262890683,.9671692597675166,.9683899605278059,.969587899878116,.97076304966162,.9719153822571454,.9730448705798238,.9741514880817275,.9752352087524931,.9762960071199334,.9773338582506355,.9783487377505475,.9793406217655515,.980309486982024,.9812553106273847,.9821780704706308,.98307774482286,.9839543125377807,.984807753012208,.9856380461865492,.9864451725452739,.987229113117374,.987989849476809,.9887273637429388,.9894416385809445,.9901326572022359,.9908004033648453,.9914448613738104,.9920660160815423,.9926638528881819,.993238357741943,.9937895171394426,.9943173181260184,.9948217482960331,.9953027957931658,.9957604493106914,.9961946980917455,.9966055319295779,.996992941167792,.9973569167005722,.9976974499728977,.9980145329807433,.9983081582712682,.9985783189429907,.9988250086459504,.9990482215818578,.99924795250423,.9994241967185149,.9995769500822006,.9997062090049132,.9998119704485015,.9998942319271075,.9999529915072262,.9999882478077495,1,.9999882478077495,.9999529915072262,.9998942319271075,.9998119704485015,.9997062090049132,.9995769500822006,.9994241967185149,.99924795250423,.9990482215818578,.9988250086459504,.9985783189429907,.9983081582712682,.9980145329807433,.9976974499728977,.9973569167005722,.996992941167792,.9966055319295779,.9961946980917455,.9957604493106914,.9953027957931658,.9948217482960331,.9943173181260184,.9937895171394426,.993238357741943,.9926638528881819,.9920660160815423,.9914448613738105,.9908004033648453,.9901326572022359,.9894416385809446,.9887273637429388,.987989849476809,.987229113117374,.9864451725452739,.9856380461865492,.984807753012208,.9839543125377807,.98307774482286,.9821780704706307,.9812553106273847,.9803094869820241,.9793406217655516,.9783487377505476,.9773338582506356,.9762960071199334,.9752352087524931,.9741514880817276,.9730448705798238,.9719153822571455,.9707630496616201,.969587899878116,.9683899605278059,.9671692597675166,.9659258262890683,.9646596893185995,.9633708786158803,.9620594244736133,.9607253577167205,.9593687097016202,.9579895123154889,.9565877979755123,.9551635996281231,.9537169507482269,.9522478853384153,.9507564379281666,.949242643573034,.9477065378538221,.9461481568757505,.9445675372676048,.942964716180876,.9413397312888873,.9396926207859084,.9380234233862579,.9363321783233931,.9346189253489885,.9328837047320006,.9311265572577219,.9293475242268225,.9275466474543786,.9257239692688904,.9238795325112867,.9220133805339185,.920125557199539,.918216106880274,.916285074456578,.9143325053161794,.9123584453530141,.9103629409661467,.9083460390586793,.90630778703665,.904248232807918,.9021674247810377,.9000654118641213,.8979422434636883,.8957979694835051,.8936326403234123,.8914463068781386,.8892390205361062,.8870108331782218,.8847617971766579,.8824919653936212,.8802013911801111,.8778901283746644,.8755582313020909,.8732057547721958,.8708327540784921,.8684392849969006,.8660254037844387,.8635911671778987,.8611366323925138,.858661857120613,.8561668995302665,.8536518182639163,.8511166724369997,.8485615216365591,.8459864259198412,.8433914458128856,.8407766423091031,.8381420768678404,.8354878114129364,.8328139083312672,.8301204304712789,.8274074411415107,.8246750041091069,.8219231835983182,.819152044288992,.8163616513150518,.8135520702629675,.8107233671702123,.8078756085237112,.8050088612582784,.802123192755044,.7992186708398695,.7962953637817556,.7933533402912352,.7903926695187593,.7874134210530723,.7844156649195758,.7813994715786824,.7783649119241601,.775312057281466,.7722409794060693,.769151750481765,.766044443118978,.7629191303530551,.7597758856425494,.756614782867493,.7534358963276608,.7502393007408243,.7470250712409959,.7437932833766611,.7405440131090045,.7372773368101241,.7339933312612353,.7306920736508675,.7273736415730488,.7240381130254827,.7206855664077148,.7173160805192896,.713929734557899,.710526608117521,.7071067811865476,.703670334145906,.7002173477671687,.6967479032106549,.6932620820235241,.6897599661378576,.6862416378687336,.6827071799122926,.6791566753437933,.6755902076156604,.6720078605555225,.6684097183642426,.6647958656139381,.6611663872459935,.6575213685690636,.6538608952570697,.6501850533471835,.6464939292378067,.6427876096865395,.6390661818081418,.635329733072485,.6315783513024975,.6278121246720986,.6240311417041269,.6202354912682602,.6164252625789255,.612600545193203,.6087614290087209,.6049080042615419,.6010403615240432,.5971585917027862,.593262786036382,.5893530360933449,.5854294337699406,.5814920712880268,.5775410411928852,.5735764363510459,.5695983499481064,.5656068754865385,.5616021067834929,.5575841379685929,.5535530634817224,.5495089780708062,.5454519767895827,.5413821549953699,.5372996083468241,.5332044328016912,.5290967246145525,.5249765803345602,.5208440968031698,.516699371151863,.5125425007998654,.5083735834518555,.5041927170956703,.49999999999999994,.49579553071207916,.49157940805537065,.48735173112724245,.48311259929663863,.4788621122017437,.47460036974764064,.47032747210396275,.46604351970253877,.4617486132350339,.45744285365058085,.4531263421534083,.44879918020046233,.4444614694990212,.4401133120043047,.43575480991707927,.43138606568125343,.4270071819814714,.4226182617406995,.4182194081178065,.4138107245051393,.40939231452609276,.4049642820326738,.40052673110306086,.3960797660391572,.39162349136413904,.38715801182000065,.3826834323650899,.37819985817164264,.3737073946233107,.3692061473126843,.36469622203881175,.3601777248047104,.3556507618148765,.35111543947278884,.34657186437840765,.3420201433256689,.3374603832999743,.33289269147567685,.32831717521356135,.3237339420583214,.31914309973603083,.3145447561516137,.30993901938630525,.30532599769511326,.30070579950427334,.29607853340870016,.2914443081694349,.2868032327110902,.28215541611928774,.2775009676380958,.2728399966674611,.26817261276063753,.263498925621611,.258819045102521,.2541330812010788,.24944114405798165,.24474334395432376,.24003979130900596,.2353305966761377,.23061587074244033,.225895724324645,.22117026836688802,.21643961393810274,.21170387222941067,.20696315455150538,.20221757233203796,.19746723711299763,.19271226054808982,.18795275440011205,.18318883053832688,.17842060093583242,.17364817766693072,.16887167290449276,.16409119891732402,.15930686806752267,.15451879280784062,.1497270856790398,.14493185930724697,.14013322640130613,.135331299750131,.13052619222005157,.12571801675216274,.12090688635966945,.11609291412523036,.11127621319829985,.1064568967924685,.10163507818280217,.09681087070317945,.09198438774362741,.0871557427476582,.08232504920959997,.07749242067193107,.07265797072261079,.0678218129924096,.06298406115223781,.05814482891047573,.0533042300102982,.04846237822700297,.04361938736533607,.038775371256816835,.03393044375706242,.029084718743111644,.02423831011074843,.01939133177182472,.014543897651583058,.009696121685978408,.004848117819001927,12246467991473532e-32,-.004848117819001238,-.009696121685978163,-.01454389765158237,-.019391331771824474,-.02423831011074774,-.029084718743111398,-.03393044375706173,-.03877537125681659,-.04361938736533583,-.048462378227003174,-.05330423001029795,-.05814482891047593,-.06298406115223758,-.06782181299240934,-.07265797072261056,-.07749242067193128,-.08232504920959974,-.08715574274765794,-.09198438774362716,-.09681087070317876,-.10163507818280193,-.10645689679246781,-.1112762131982996,-.11609291412523012,-.12090688635966965,-.1257180167521625,-.13052619222005177,-.13533129975013078,-.14013322640130632,-.14493185930724675,-.14972708567904,-.1545187928078404,-.15930686806752198,-.16409119891732377,-.16887167290449254,-.17364817766693047,-.17842060093583176,-.18318883053832663,-.1879527544001114,-.1927122605480896,-.19746723711299738,-.20221757233203816,-.20696315455150513,-.21170387222941087,-.21643961393810252,-.2211702683668878,-.22589572432464475,-.23061587074244053,-.23533059667613745,-.2400397913090053,-.2447433439543235,-.24944114405798098,-.2541330812010786,-.25881904510252035,-.2634989256216107,-.26817261276063686,-.2728399966674609,-.27750096763809556,-.2821554161192879,-.28680323271108993,-.29144430816943506,-.29607853340869994,-.30070579950427306,-.30532599769511304,-.3099390193863046,-.3145447561516135,-.3191430997360306,-.3237339420583211,-.3283171752135607,-.33289269147567657,-.3374603832999737,-.34202014332566866,-.3465718643784074,-.35111543947278906,-.35565076181487626,-.36017772480471055,-.3646962220388115,-.3692061473126845,-.3737073946233105,-.3781998581716428,-.38268343236508967,-.38715801182000004,-.3916234913641388,-.39607976603915657,-.40052673110306064,-.4049642820326732,-.40939231452609254,-.41381072450513867,-.4182194081178062,-.4226182617406993,-.4270071819814716,-.4313860656812532,-.43575480991707943,-.4401133120043045,-.444461469499021,-.4487991802004621,-.4531263421534085,-.4574428536505806,-.46174861323503374,-.46604351970253854,-.47032747210396214,-.4746003697476404,-.47886211220174313,-.4831125992966384,-.4873517311272422,-.4915794080553708,-.49579553071207894,-.5000000000000001,-.50419271709567,-.5083735834518556,-.5125425007998652,-.5166993711518633,-.5208440968031696,-.5249765803345596,-.5290967246145523,-.533204432801691,-.5372996083468239,-.5413821549953693,-.5454519767895825,-.5495089780708056,-.5535530634817222,-.5575841379685926,-.5616021067834931,-.5656068754865384,-.5695983499481065,-.5735764363510458,-.577541041192885,-.5814920712880266,-.5854294337699408,-.5893530360933448,-.5932627860363815,-.597158591702786,-.6010403615240426,-.6049080042615417,-.6087614290087203,-.6126005451932028,-.6164252625789249,-.6202354912682599,-.6240311417041268,-.6278121246720987,-.6315783513024973,-.6353297330724852,-.6390661818081416,-.6427876096865393,-.6464939292378065,-.6501850533471829,-.6538608952570695,-.6575213685690635,-.6611663872459933,-.6647958656139376,-.6684097183642425,-.6720078605555221,-.6755902076156601,-.6791566753437931,-.6827071799122927,-.6862416378687334,-.6897599661378577,-.693262082023524,-.696747903210655,-.7002173477671685,-.7036703341459061,-.7071067811865475,-.7105266081175206,-.7139297345578989,-.7173160805192892,-.7206855664077146,-.7240381130254823,-.7273736415730487,-.7306920736508671,-.7339933312612352,-.737277336810124,-.7405440131090048,-.743793283376661,-.747025071240996,-.7502393007408242,-.7534358963276607,-.7566147828674927,-.7597758856425493,-.7629191303530554,-.7660444431189779,-.7691517504817651,-.7722409794060688,-.7753120572814659,-.7783649119241597,-.7813994715786822,-.7844156649195754,-.7874134210530722,-.7903926695187589,-.7933533402912349,-.7962953637817558,-.79921867083987,-.8021231927550437,-.8050088612582785,-.8078756085237111,-.8107233671702119,-.8135520702629674,-.8163616513150515,-.8191520442889916,-.8219231835983181,-.8246750041091064,-.8274074411415104,-.830120430471279,-.8328139083312671,-.8354878114129365,-.8381420768678401,-.8407766423091032,-.8433914458128855,-.8459864259198411,-.8485615216365587,-.8511166724369996,-.8536518182639165,-.8561668995302664,-.8586618571206132,-.8611366323925135,-.8635911671778986,-.8660254037844385,-.8684392849969005,-.8708327540784918,-.8732057547721956,-.8755582313020905,-.8778901283746643,-.8802013911801112,-.8824919653936215,-.8847617971766578,-.8870108331782218,-.889239020536106,-.8914463068781383,-.8936326403234122,-.8957979694835049,-.897942243463688,-.9000654118641208,-.9021674247810375,-.9042482328079179,-.90630778703665,-.9083460390586792,-.9103629409661468,-.912358445353014,-.9143325053161795,-.9162850744565778,-.918216106880274,-.9201255571995388,-.9220133805339183,-.9238795325112865,-.9257239692688903,-.9275466474543786,-.9293475242268223,-.9311265572577219,-.9328837047320003,-.9346189253489884,-.9363321783233929,-.9380234233862578,-.9396926207859082,-.9413397312888873,-.9429647161808761,-.9445675372676049,-.9461481568757504,-.9477065378538222,-.9492426435730339,-.9507564379281666,-.9522478853384153,-.9537169507482267,-.9551635996281229,-.956587797975512,-.9579895123154888,-.9593687097016201,-.9607253577167205,-.9620594244736131,-.9633708786158804,-.9646596893185994,-.9659258262890683,-.9671692597675166,-.9683899605278059,-.9695878998781159,-.97076304966162,-.9719153822571452,-.9730448705798238,-.9741514880817276,-.975235208752493,-.9762960071199334,-.9773338582506355,-.9783487377505475,-.9793406217655514,-.980309486982024,-.9812553106273846,-.9821780704706307,-.98307774482286,-.9839543125377805,-.984807753012208,-.9856380461865493,-.9864451725452739,-.9872291131173742,-.9879898494768089,-.9887273637429387,-.9894416385809445,-.9901326572022358,-.9908004033648452,-.9914448613738104,-.9920660160815423,-.9926638528881818,-.993238357741943,-.9937895171394426,-.9943173181260184,-.994821748296033,-.9953027957931658,-.9957604493106913,-.9961946980917455,-.9966055319295779,-.996992941167792,-.9973569167005722,-.9976974499728977,-.9980145329807433,-.9983081582712682,-.9985783189429907,-.9988250086459504,-.9990482215818578,-.99924795250423,-.9994241967185149,-.9995769500822006,-.9997062090049132,-.9998119704485015,-.9998942319271076,-.9999529915072262,-.9999882478077495,-1,-.9999882478077495,-.9999529915072262,-.9998942319271076,-.9998119704485015,-.9997062090049132,-.9995769500822006,-.9994241967185149,-.99924795250423,-.9990482215818578,-.9988250086459504,-.9985783189429907,-.9983081582712682,-.9980145329807433,-.9976974499728977,-.9973569167005724,-.996992941167792,-.9966055319295779,-.9961946980917455,-.9957604493106914,-.9953027957931658,-.9948217482960331,-.9943173181260185,-.9937895171394426,-.993238357741943,-.9926638528881819,-.9920660160815424,-.9914448613738105,-.9908004033648453,-.9901326572022358,-.9894416385809446,-.9887273637429387,-.987989849476809,-.9872291131173742,-.986445172545274,-.9856380461865493,-.9848077530122081,-.9839543125377807,-.9830777448228601,-.9821780704706308,-.9812553106273846,-.9803094869820241,-.9793406217655515,-.9783487377505476,-.9773338582506355,-.9762960071199335,-.9752352087524931,-.9741514880817276,-.9730448705798239,-.9719153822571454,-.9707630496616201,-.969587899878116,-.968389960527806,-.9671692597675167,-.9659258262890684,-.9646596893185995,-.9633708786158806,-.9620594244736133,-.9607253577167206,-.9593687097016202,-.9579895123154889,-.9565877979755121,-.955163599628123,-.9537169507482268,-.9522478853384154,-.9507564379281668,-.949242643573034,-.9477065378538223,-.9461481568757506,-.944567537267605,-.9429647161808762,-.9413397312888874,-.9396926207859083,-.9380234233862579,-.936332178323393,-.9346189253489885,-.9328837047320004,-.9311265572577221,-.9293475242268224,-.9275466474543788,-.9257239692688904,-.9238795325112866,-.9220133805339186,-.9201255571995389,-.9182161068802742,-.9162850744565779,-.9143325053161796,-.9123584453530141,-.9103629409661469,-.9083460390586794,-.9063077870366503,-.9042482328079181,-.9021674247810376,-.9000654118641209,-.8979422434636882,-.895797969483505,-.8936326403234123,-.8914463068781384,-.8892390205361063,-.887010833178222,-.8847617971766579,-.8824919653936216,-.8802013911801113,-.8778901283746645,-.8755582313020907,-.8732057547721959,-.870832754078492,-.8684392849969007,-.8660254037844386,-.8635911671778989,-.8611366323925137,-.8586618571206134,-.8561668995302666,-.8536518182639167,-.8511166724369998,-.848561521636559,-.8459864259198413,-.8433914458128857,-.8407766423091034,-.8381420768678404,-.8354878114129367,-.8328139083312672,-.8301204304712791,-.8274074411415107,-.8246750041091067,-.8219231835983183,-.8191520442889918,-.8163616513150517,-.8135520702629676,-.8107233671702121,-.8078756085237113,-.8050088612582788,-.802123192755044,-.7992186708398701,-.796295363781756,-.7933533402912352,-.7903926695187591,-.7874134210530724,-.7844156649195756,-.7813994715786825,-.7783649119241599,-.7753120572814661,-.7722409794060691,-.7691517504817653,-.7660444431189781,-.7629191303530556,-.7597758856425495,-.7566147828674927,-.753435896327661,-.7502393007408246,-.7470250712409963,-.7437932833766612,-.740544013109005,-.7372773368101242,-.7339933312612357,-.7306920736508676,-.7273736415730492,-.7240381130254828,-.7206855664077145,-.7173160805192891,-.7139297345578991,-.7105266081175208,-.7071067811865477,-.7036703341459063,-.7002173477671687,-.6967479032106556,-.6932620820235246,-.6897599661378577,-.6862416378687334,-.6827071799122926,-.679156675343793,-.6755902076156605,-.6720078605555223,-.6684097183642427,-.6647958656139378,-.6611663872459935,-.6575213685690637,-.6538608952570701,-.6501850533471836,-.6464939292378064,-.6427876096865396,-.6390661818081416,-.6353297330724854,-.6315783513024976,-.627812124672099,-.624031141704127,-.6202354912682606,-.6164252625789255,-.6126005451932034,-.6087614290087209,-.6049080042615417,-.6010403615240425,-.5971585917027863,-.5932627860363818,-.589353036093345,-.585429433769941,-.5814920712880269,-.5775410411928856,-.5735764363510465,-.5695983499481065,-.5656068754865391,-.561602106783493,-.5575841379685926,-.5535530634817225,-.5495089780708059,-.5454519767895828,-.5413821549953696,-.5372996083468242,-.5332044328016913,-.5290967246145529,-.5249765803345603,-.5208440968031696,-.5166993711518632,-.5125425007998651,-.5083735834518559,-.5041927170956704,-.5000000000000004,-.49579553071207927,-.49157940805537115,-.48735173112724256,-.48311259929663913,-.4788621122017438,-.47460036974764036,-.4703274721039621,-.4660435197025389,-.46174861323503363,-.45744285365058096,-.4531263421534088,-.44879918020046244,-.4444614694990217,-.4401133120043052,-.43575480991708015,-.4313860656812539,-.42700718198147153,-.4226182617406992,-.4182194081178066,-.413810724505139,-.40939231452609287,-.40496428203267354,-.400526731103061,-.3960797660391569,-.39162349136413954,-.38715801182000076,-.3826834323650904,-.37819985817164276,-.3737073946233104,-.3692061473126848,-.36469622203881186,-.3601777248047109,-.3556507618148766,-.3511154394727894,-.34657186437840776,-.34202014332566943,-.3374603832999744,-.3328926914756765,-.32831717521356063,-.32373394205832107,-.31914309973603056,-.3145447561516138,-.3099390193863049,-.30532599769511337,-.30070579950427384,-.2960785334087003,-.29144430816943584,-.2868032327110907,-.28215541611928785,-.2775009676380955,-.2728399966674612,-.2681726127606372,-.2634989256216111,-.2588190451025207,-.2541330812010789,-.24944114405798135,-.24474334395432432,-.24003979130900607,-.23533059667613823,-.23061587074244044,-.2258957243246447,-.22117026836688813,-.21643961393810288,-.21170387222941123,-.2069631545515055,-.20221757233203852,-.19746723711299774,-.19271226054809037,-.1879527544001122,-.18318883053832655,-.17842060093583256,-.1736481776669304,-.16887167290449245,-.16409119891732413,-.15930686806752234,-.15451879280784075,-.14972708567904036,-.1449318593072471,-.14013322640130713,-.13533129975013158,-.13052619222005168,-.1257180167521624,-.12090688635966958,-.11609291412523004,-.11127621319829996,-.10645689679246818,-.10163507818280229,-.09681087070317913,-.09198438774362797,-.08715574274765832,-.08232504920960054,-.0774924206719312,-.07265797072261047,-.06782181299240972,-.06298406115223794,-.0581448289104763,-.05330423001029832,-.04846237822700354,-.043619387365336194,-.038775371256817404,-.03393044375706254,-.02908471874311221,-.02423831011074855,-.019391331771824397,-.014543897651582293,-.009696121685978531,-.004848117819001606];r=__webpack_require__(949);class Ki extends r.Quaternion{setFromEuler(e,t){if(!e||!e.isEuler)throw new Error("THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.");var i=e.x,s=e.y,r=e.z,a=e.order,n=Yi.cos(i/2),o=Yi.cos(s/2),e=Yi.cos(r/2),i=Yi.sin(i/2),s=Yi.sin(s/2),r=Yi.sin(r/2);return"XYZ"===a?(this._x=i*o*e+n*s*r,this._y=n*s*e-i*o*r,this._z=n*o*r+i*s*e,this._w=n*o*e-i*s*r):"YXZ"===a?(this._x=i*o*e+n*s*r,this._y=n*s*e-i*o*r,this._z=n*o*r-i*s*e,this._w=n*o*e+i*s*r):"ZXY"===a?(this._x=i*o*e-n*s*r,this._y=n*s*e+i*o*r,this._z=n*o*r+i*s*e,this._w=n*o*e-i*s*r):"ZYX"===a?(this._x=i*o*e-n*s*r,this._y=n*s*e+i*o*r,this._z=n*o*r-i*s*e,this._w=n*o*e+i*s*r):"YZX"===a?(this._x=i*o*e+n*s*r,this._y=n*s*e+i*o*r,this._z=n*o*r-i*s*e,this._w=n*o*e-i*s*r):"XZY"===a&&(this._x=i*o*e-n*s*r,this._y=n*s*e-i*o*r,this._z=n*o*r+i*s*e,this._w=n*o*e+i*s*r),!1!==t&&this.onChangeCallback(),this}setFromAxisAngle(e,t){var i=t/2,t=Yi.sin(i);return this._x=e.x*t,this._y=e.y*t,this._z=e.z*t,this._w=Yi.cos(i),this.onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,i=t[0],s=t[4],r=t[8],a=t[1],n=t[5],o=t[9],h=t[2],l=t[6],c=t[10],u=i+n+c,d;return 0<u?(d=.5/Yi.sqrt(u+1),this._w=.25/d,this._x=(l-o)*d,this._y=(r-h)*d,this._z=(a-s)*d):n<i&&c<i?(d=2*Yi.sqrt(1+i-n-c),this._w=(l-o)/d,this._x=.25*d,this._y=(s+a)/d,this._z=(r+h)/d):c<n?(d=2*Yi.sqrt(1+n-i-c),this._w=(r-h)/d,this._x=(s+a)/d,this._y=.25*d,this._z=(o+l)/d):(d=2*Yi.sqrt(1+c-i-n),this._w=(a-s)/d,this._x=(r+h)/d,this._y=(o+l)/d,this._z=.25*d),this.onChangeCallback(),this}length(){return Yi.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);var i=this._x,s=this._y,r=this._z,a=this._w;let n=a*e._w+i*e._x+s*e._y+r*e._z;if(n<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,n=-n):this.copy(e),1<=n)return this._w=a,this._x=i,this._y=s,this._z=r,this;var o=1-n*n;if(o<=Number.EPSILON){var h=1-t;return this._w=h*a+t*this._w,this._x=h*i+t*this._x,this._y=h*s+t*this._y,this._z=h*r+t*this._z,this.normalize()}e=Yi.sqrt(o),h=Yi.atan2(e,n),o=Yi.sin((1-t)*h)/e,e=Yi.sin(t*h)/e;return this._w=a*o+this._w*e,this._x=i*o+this._x*e,this._y=s*o+this._y*e,this._z=r*o+this._z*e,this.onChangeCallback(),this}}var Ji,es,ts,is,ss,r=__webpack_require__(949);class rs extends r.Vector3{applyEuler(e){return e&&e.isEuler||console.error("THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order."),this.applyQuaternion(as.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(as.setFromAxisAngle(e,t))}length(){return Yi.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}projectOnPlane(e){return ns.copy(this).projectOnVector(e),this.sub(ns)}reflect(e){return this.sub(ns.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){e=this.dot(e)/Yi.sqrt(this.lengthSq()*e.lengthSq());return Yi.acos(z(e,-1,1))}distanceTo(e){return Yi.sqrt(this.distanceToSquared(e))}setFromSpherical(e){var t=Yi.sin(e.phi)*e.radius;return this.x=t*Yi.sin(e.theta),this.y=Yi.cos(e.phi)*e.radius,this.z=t*Yi.cos(e.theta),this}setFromCylindrical(e){return this.x=e.radius*Yi.sin(e.theta),this.y=e.y,this.z=e.radius*Yi.cos(e.theta),this}}const as=new Ki,ns=new rs;(r=Ji=Ji||{})[r.Combat=0]="Combat",r[r.Tech=1]="Tech",r[r.Resource=2]="Resource",r[r.Power=3]="Power",(r=es=es||{})[r.None=0]="None",r[r.BuildingType=1]="BuildingType",r[r.InfantryType=2]="InfantryType",r[r.UnitType=3]="UnitType",r[r.NavalUnitType=4]="NavalUnitType",r[r.AircraftType=5]="AircraftType";class os extends Ci{parse(){super.parse(),this.owner=this.ini.getArray("Owner");var e=this.ini.getNumber("AIBasePlanningSide");this.aiBasePlanningSide=-1!==e&&void 0!==Zt[e]?e:void 0,this.requiredHouses=this.ini.getArray("RequiredHouses"),this.forbiddenHouses=this.ini.getArray("ForbiddenHouses"),this.requiresStolenAlliedTech=this.ini.getBool("RequiresStolenAlliedTech"),this.requiresStolenSovietTech=this.ini.getBool("RequiresStolenSovietTech"),this.techLevel=this.ini.getNumber("TechLevel",-1),this.cost=this.ini.getNumber("Cost"),this.points=this.ini.getNumber("Points"),this.power=this.ini.getNumber("Power"),this.powered=this.ini.getBool("Powered"),this.prerequisite=this.ini.getArray("Prerequisite"),this.soylent=this.ini.getNumber("Soylent"),this.crateGoodie=this.ini.getBool("CrateGoodie"),this.buildCat=this.ini.getEnum("BuildCat",Ji,Ji.Combat),this.adjacent=this.ini.getNumber("Adjacent",1),this.baseNormal=this.ini.getBool("BaseNormal",!0),this.buildLimit=this.ini.getNumber("BuildLimit",Number.POSITIVE_INFINITY),this.airRangeBonus=this.ini.getNumber("AirRangeBonus"),this.guardRange=this.ini.getNumber("GuardRange"),this.defaultToGuardArea=this.ini.getBool("DefaultToGuardArea"),this.eligibileForAllyBuilding=this.ini.getBool("EligibileForAllyBuilding"),this.numberImpassableRows=this.ini.getNumber("NumberImpassableRows"),this.bridgeRepairHut=this.ini.getBool("BridgeRepairHut"),this.constructionYard=this.ini.getBool("ConstructionYard"),this.refinery=this.ini.getBool("Refinery"),this.unitRepair=this.ini.getBool("UnitRepair"),this.unitReload=this.ini.getBool("UnitReload"),this.isBaseDefense=this.ini.getBool("IsBaseDefense"),this.superWeapon=this.parseWeaponName(this.ini.getString("SuperWeapon")),this.chargedAnimTime=this.ini.getNumber("ChargedAnimTime");var t=this.ini.getBool("Naval");this.naval=t,this.underwater=this.ini.getBool("Underwater"),this.waterBound=this.ini.getBool("WaterBound"),this.orePurifier=this.ini.getBool("OrePurifier"),this.cloning=this.ini.getBool("Cloning"),this.nukeSilo=this.ini.getBool("NukeSilo"),this.repairable=this.ini.getBool("Repairable",this.type===xt.Building),this.clickRepairable=this.ini.getBool("ClickRepairable",this.type===xt.Building),this.unsellable=this.ini.getBool("Unsellable"),this.gdiBarracks=this.ini.getBool("GDIBarracks"),this.nodBarracks=this.ini.getBool("NODBarracks"),this.numberOfDocks=this.ini.getNumber("NumberOfDocks"),this.unitRepair&&!this.numberOfDocks&&(this.numberOfDocks=1),this.factory=this.ini.getEnum("Factory",es,es.None),this.factory===es.UnitType&&t&&(this.factory=es.NavalUnitType),this.weaponsFactory=this.ini.getBool("WeaponsFactory"),this.helipad=this.ini.getBool("Helipad"),this.hospital=this.ini.getBool("Hospital"),this.landTargeting=this.ini.getEnumNumeric("LandTargeting",ni,ni.LandOk),this.navalTargeting=this.ini.getEnumNumeric("NavalTargeting",oi,oi.UnderwaterNever),this.tooBigToFitUnderBridge=this.ini.getBool("TooBigToFitUnderBridge",this.type===xt.Building),this.canBeOccupied=this.ini.getBool("CanBeOccupied"),this.maxNumberOccupants=this.ini.getNumber("MaxNumberOccupants"),this.leaveRubble=this.ini.getBool("LeaveRubble"),this.undeploysInto=this.ini.getString("UndeploysInto"),this.deploysInto=this.ini.getString("DeploysInto"),this.capturable=this.ini.getBool("Capturable"),this.spyable=this.ini.getBool("Spyable"),this.needsEngineer=this.ini.getBool("NeedsEngineer"),this.c4=this.ini.getBool("C4"),this.canC4=this.ini.getBool("CanC4",!0),this.eligibleForDelayKill=this.ini.getBool("EligibleForDelayKill"),this.produceCashStartup=this.ini.getNumber("ProduceCashStartup"),this.produceCashAmount=this.ini.getNumber("ProduceCashAmount"),this.produceCashDelay=this.ini.getNumber("ProduceCashDelay"),this.explosion=this.ini.getArray("Explosion"),this.explodes=this.ini.getBool("Explodes"),this.ifvMode=this.ini.getNumber("IFVMode"),this.turretIndexesByIfvMode=this.parseTurretIndexes(),this.turret=this.ini.getBool("Turret"),this.turretCount=this.ini.getNumber("TurretCount",this.turret?1:0),this.turretAnim=this.ini.getString("TurretAnim"),this.turretAnimIsVoxel=this.ini.getBool("TurretAnimIsVoxel"),this.turretAnimX=this.ini.getNumber("TurretAnimX"),this.turretAnimY=this.ini.getNumber("TurretAnimY"),this.turretAnimZAdjust=this.ini.getNumber("TurretAnimZAdjust"),this.isChargeTurret=this.ini.getBool("IsChargeTurret"),this.overpowerable=this.ini.getBool("Overpowerable"),this.freeUnit=this.ini.getString("FreeUnit"),this.primary=this.parseWeaponName(this.ini.getString("Primary")),this.secondary=this.parseWeaponName(this.ini.getString("Secondary")),this.elitePrimary=this.parseWeaponName(this.ini.getString("ElitePrimary")),this.eliteSecondary=this.parseWeaponName(this.ini.getString("EliteSecondary")),this.weaponCount=this.ini.getNumber("WeaponCount"),this.deathWeapon=this.parseWeaponName(this.ini.getString("DeathWeapon")),this.deathWeaponDamageModifier=this.ini.getNumber("DeathWeaponDamageModifier",1),this.occupyWeapon=this.parseWeaponName(this.ini.getString("OccupyWeapon")),this.eliteOccupyWeapon=this.parseWeaponName(this.ini.getString("EliteOccupyWeapon")),this.veteranAbilities=new Set(this.ini.getEnumArray("VeteranAbilities",li)),this.eliteAbilities=new Set([...this.veteranAbilities,...this.ini.getEnumArray("EliteAbilities",li)]),this.selfHealing=this.ini.getBool("SelfHealing"),this.wall=this.ini.getBool("Wall"),this.gate=this.ini.getBool("Gate"),this.armor=this.ini.getEnum("Armor",ai,ai.None,!0),this.strength=Math.floor(this.ini.getNumber("Strength")),this.immune=this.ini.getBool("Immune"),this.immuneToRadiation=this.ini.getBool("ImmuneToRadiation"),this.immuneToPsionics=this.ini.getBool("ImmuneToPsionics"),this.typeImmune=this.ini.getBool("TypeImmune"),this.warpable=this.ini.getBool("Warpable",!0),this.isTilter=this.ini.getBool("IsTilter",!0),this.walkRate=this.ini.getNumber("WalkRate",1),this.idleRate=this.ini.getNumber("IdleRate",0),this.noSpawnAlt=this.ini.getBool("NoSpawnAlt"),this.crusher=this.ini.getBool("Crusher"),this.consideredAircraft=this.ini.getBool("ConsideredAircraft"),this.crashable=this.ini.getBool("Crashable");var i=this.ini.getBool("Landable");this.landable=i,this.airportBound=this.ini.getBool("AirportBound"),this.balloonHover=this.ini.getBool("BalloonHover"),this.hoverAttack=this.ini.getBool("HoverAttack"),this.omniFire=this.ini.getBool("OmniFire"),this.fighter=this.ini.getBool("Fighter"),this.flightLevel=this.ini.getNumber("FlightLevel")||void 0;var s=this.ini.getString("Locomotor"),e=this.type===xt.Building?si.Statue:si.Chrono;if(s?(t=Zi.get(s))?this.locomotor=t:(console.warn(`Object rules "${this.name}" has invalid Locomotor "${s}"`),this.locomotor=e):this.locomotor=e,this.locomotor!==si.Statue){let e=Qi.get(this.locomotor);void 0===e&&(this.type===xt.Aircraft||this.consideredAircraft?e=ei.Winged:this.type===xt.Vehicle?e=this.crusher?ei.Track:ei.Wheel:this.type===xt.Infantry&&(e=ei.Foot)),this.speedType=this.ini.getEnum("SpeedType",ei,e,!0)}e=[si.Ship,si.Vehicle,si.Chrono].includes(this.locomotor)?65:100;this.speed=Ci.iniSpeedToLeptonsPerTick(this.ini.getNumber("Speed"),e),this.movementZone=this.ini.getEnum("MovementZone",ri,ri.Normal),this.fearless=this.ini.getBool("Fearless"),this.deployer=this.ini.getBool("Deployer"),this.deployFire=this.ini.getBool("DeployFire"),this.deployFireWeapon=this.ini.getNumber("DeployFireWeapon",hi.Secondary),this.undeployDelay=this.ini.getNumber("UndeployDelay"),this.fraidycat=this.ini.getBool("Fraidycat",!1),this.isHuman=!this.ini.getBool("NotHuman"),this.organic=this.type===xt.Infantry||this.ini.getBool("Organic"),this.occupier=this.ini.getBool("Occupier"),this.engineer=this.ini.getBool("Engineer"),this.ivan=this.ini.getBool("Ivan"),this.civilian=this.ini.getBool("Civilian"),this.agent=this.ini.getBool("Agent"),this.infiltrate=this.ini.getBool("Infiltrate"),this.threatPosed=this.ini.getNumber("ThreatPosed"),this.specialThreatValue=this.ini.getNumber("SpecialThreatValue"),this.canPassiveAquire=this.ini.getBool("CanPassiveAquire",!0),this.canRetaliate=this.ini.getBool("CanRetaliate",!0),this.preventAttackMove=this.ini.getBool("PreventAttackMove"),this.opportunityFire=this.ini.getBool("OpportunityFire"),this.distributedFire=this.ini.getBool("DistributedFire"),this.radialFireSegments=this.ini.getNumber("RadialFireSegments"),this.attackCursorOnFriendlies=this.ini.getBool("AttackCursorOnFriendlies"),this.bombable=this.ini.getBool("Bombable",!0),this.trainable=this.ini.getBool("Trainable",this.type!==xt.Building),this.crewed=this.ini.getBool("Crewed"),this.parasiteable=this.ini.getBool("Parasiteable",this.type!==xt.Building),this.suppressionThreshold=this.ini.getNumber("SuppressionThreshold"),this.reselectIfLimboed=this.ini.getBool("ReselectIfLimboed"),this.rejoinTeamIfLimboed=this.ini.getBool("RejoinTeamIfLimboed"),this.weight=this.ini.getNumber("Weight"),this.accelerates=this.ini.getBool("Accelerates",!0),this.accelerationFactor=this.ini.getNumber("AccelerationFactor",.03),this.teleporter=this.ini.getBool("Teleporter"),this.canDisguise=this.ini.getBool("CanDisguise"),this.disguiseWhenStill=this.ini.getBool("DisguiseWhenStill"),this.permaDisguise=this.ini.getBool("PermaDisguise"),this.detectDisguise=this.ini.getBool("DetectDisguise"),this.detectDisguiseRange=this.ini.getNumber("DetectDisguiseRange"),this.cloakable=this.ini.getBool("Cloakable"),this.sensors=this.ini.getBool("Sensors"),this.sensorArray=this.ini.getBool("SensorArray"),this.sensorsSight=this.ini.getNumber("SensorsSight"),this.burstDelay=this.parseBurstDelay(),this.vhpScan=this.ini.getEnum("VHPScan",ci,ci.None,!0),this.pip=this.ini.getEnum("Pip",ii,ii.Green,!0),this.passengers=this.ini.getNumber("Passengers"),this.gunner=this.ini.getBool("Gunner"),this.ammo=this.ini.getNumber("Ammo",-1),this.initialAmmo=this.ini.getNumber("InitialAmmo",-1),this.manualReload=this.ini.getBool("ManualReload",this.type===xt.Aircraft),this.storage=this.ini.getNumber("Storage"),this.spawned=this.ini.getBool("Spawned"),this.spawns=this.ini.getString("Spawns"),this.spawnsNumber=this.ini.getNumber("SpawnsNumber"),this.spawnRegenRate=this.ini.getNumber("SpawnRegenRate"),this.spawnReloadRate=this.ini.getNumber("SpawnReloadRate"),this.missileSpawn=this.ini.getBool("MissileSpawn"),this.size=this.ini.getNumber("Size",1),this.sizeLimit=this.ini.getNumber("SizeLimit"),this.sight=Math.min(os.MAX_SIGHT,this.ini.getNumber("Sight",1)),this.spySat=this.ini.getBool("SpySat"),this.gapGenerator=this.ini.getBool("GapGenerator"),this.gapRadiusInCells=this.ini.getNumber("GapRadiusInCells"),this.psychicDetectionRadius=this.ini.getNumber("PsychicDetectionRadius"),this.hasRadialIndicator=this.ini.getBool("HasRadialIndicator"),this.harvester=this.ini.getBool("Harvester"),this.unloadingClass=this.ini.getString("UnloadingClass"),this.dock=this.ini.getArray("Dock"),this.radar=this.ini.getBool("Radar"),this.radarInvisible=this.ini.getBool("RadarInvisible"),this.revealToAll=this.ini.getBool("RevealToAll"),this.selectable=!(this.type===xt.Aircraft&&!i)&&this.ini.getBool("Selectable",!0),this.isSelectableCombatant=this.ini.getBool("IsSelectableCombatant"),this.invisibleInGame=this.ini.getBool("InvisibleInGame"),this.moveToShroud=this.ini.getBool("MoveToShroud",this.type!==xt.Aircraft),this.leadershipRating=this.ini.getNumber("LeadershipRating",5),this.allowedToStartInMultiplayer=this.ini.getBool("AllowedToStartInMultiplayer",!0),this.rot=Ci.iniRotToDegsPerTick(this.ini.getNumber("ROT",0)),this.jumpjetAccel=this.ini.getNumber("JumpJetAccel",2),this.jumpjetClimb=this.ini.getNumber("JumpjetClimb",5),this.jumpjetCrash=this.ini.getNumber("JumpjetCrash",5),this.jumpjetDeviation=this.ini.getNumber("JumpjetDeviation",40),this.jumpjetHeight=this.ini.getNumber("JumpjetHeight",500),this.jumpjetNoWobbles=this.ini.getBool("JumpjetNoWobbles"),this.jumpjetSpeed=this.ini.getNumber("JumpjetSpeed",14),this.jumpjetTurnRate=Ci.iniRotToDegsPerTick(this.ini.getNumber("JumpJetTurnRate",4)),this.jumpjetWobbles=this.ini.getNumber("JumpjetWobbles",.15),this.pitchSpeed=this.ini.getNumber("PitchSpeed",.25),this.pitchAngle=1<=this.pitchSpeed?0:20,this.damageParticleSystems=this.ini.getArray("DamageParticleSystems");i=this.ini.getNumberArray("DamageSmokeOffset",void 0,[0,0,0]);this.damageSmokeOffset=new rs(i[0],i[2]/Math.SQRT2,i[1]),this.minDebris=this.ini.getNumber("MinDebris"),this.maxDebris=this.ini.getNumber("MaxDebris"),this.debrisTypes=this.ini.getArray("DebrisTypes"),this.debrisAnims=this.ini.getArray("DebrisAnims"),this.isLightpost="GALITE"===this.imageName,this.lightVisibility=this.ini.getNumber("LightVisibility",5e3),this.lightIntensity=this.ini.getNumber("LightIntensity"),this.lightRedTint=this.ini.getNumber("LightRedTint",1),this.lightGreenTint=this.ini.getNumber("LightGreenTint",1),this.lightBlueTint=this.ini.getNumber("LightBlueTint",1),this.ambientSound=this.ini.getString("AmbientSound")||void 0,this.createSound=this.ini.getString("CreateSound")||void 0,this.deploySound=this.ini.getString("DeploySound")||void 0,this.undeploySound=this.ini.getString("UndeploySound")||void 0,this.voiceSelect=this.ini.getString("VoiceSelect")||void 0,this.voiceMove=this.ini.getString("VoiceMove")||void 0,this.voiceAttack=this.ini.getString("VoiceAttack")||void 0,this.voiceFeedback=this.ini.getString("VoiceFeedback")||void 0,this.voiceSpecialAttack=this.ini.getString("VoiceSpecialAttack")||void 0,this.voiceEnter=this.ini.getString("VoiceEnter")||void 0,this.voiceCapture=this.ini.getString("VoiceCapture")||void 0,this.voiceCrashing=this.ini.getString("VoiceCrashing")||void 0,this.crashingSound=this.ini.getString("CrashingSound")||void 0,this.impactLandSound=this.ini.getString("ImpactLandSound")||void 0,this.auxSound1=this.ini.getString("AuxSound1")||void 0,this.auxSound2=this.ini.getString("AuxSound2")||void 0,this.dieSound=this.ini.getString("DieSound")||void 0,this.moveSound=this.ini.getString("MoveSound")||void 0,this.enterWaterSound=this.ini.getString("EnterWaterSound")||void 0,this.leaveWaterSound=this.ini.getString("LeaveWaterSound")||void 0,this.turretRotateSound=this.ini.getString("TurretRotateSound")||void 0,this.workingSound=this.ini.getString("WorkingSound")||void 0,this.notWorkingSound=this.ini.getString("NotWorkingSound")||void 0,this.chronoInSound=this.ini.getString("ChronoInSound")||void 0,this.chronoOutSound=this.ini.getString("ChronoOutSound")||void 0,this.enterTransportSound=this.ini.getString("EnterTransportSound")||void 0,this.leaveTransportSound=this.ini.getString("LeaveTransportSound")||void 0}parseWeaponName(e){return e&&"none"!==e.toLowerCase()?e:void 0}parseTurretIndexes(){let i=new Map;return this.ini.getBool("Gunner")&&this.ini.entries.forEach((e,t)=>{t=t.match(/^(.*)TurretWeapon$/i);t&&(t=t[1]+"TurretIndex",this.ini.has(t)&&i.set(Number(e),this.ini.getNumber(t)))}),i}parseBurstDelay(){let t=[];for(let e=0;e<4;++e)t.push(this.ini.has(`BurstDelay${e}`)?this.ini.getNumber(`BurstDelay${e}`):void 0);return t}hasOwner(e){return!!this.owner.length&&-1!==this.owner.indexOf(e.name)}isAvailableTo(e){return(!this.requiredHouses.length||-1!==this.requiredHouses.indexOf(e.name))&&-1===this.forbiddenHouses.indexOf(e.name)}get proneWhenAttacked(){return!this.fearless&&this.isHuman}getWeaponAtIndex(e){return this.parseWeaponName(this.ini.getString(`Weapon${e+1}`))}getEliteWeaponAtIndex(e){return this.parseWeaponName(this.ini.getString(`EliteWeapon${e+1}`))}}os.MAX_SIGHT=11;class hs extends Ci{parse(){super.parse(),this.armor=this.ini.getEnum("Armor",ai,ai.None,!0),this.crate=this.ini.getBool("Crate");var e=this.ini.getBool("IsARock");this.isARock=e,this.isRubble=this.ini.getBool("IsRubble"),this.isVeinholeMonster=this.ini.getBool("IsVeinholeMonster"),this.isVeins=this.ini.getBool("IsVeins"),this.land=this.ini.getEnum("Land",Jt,Jt.Clear),this.noUseTileLandType=!!this.ini.getString("NoUseTileLandType"),this.strength=this.ini.getNumber("Strength"),this.tiberium=this.ini.getBool("Tiberium");var t=this.ini.getBool("Wall");this.wall=t,this.radarInvisible=this.ini.getBool("RadarInvisible",!t&&!e)}}(r=ts=ts||{})[r.All=7]="All",r[r.Right=1]="Right",r[r.Left=2]="Left",r[r.Bottom=4]="Bottom";class ls extends Ci{parse(){super.parse(),this.animationRate=this.ini.getNumber("AnimationRate"),this.animationProbability=this.ini.getNumber("AnimationProbability"),this.gate=this.ini.getBool("Gate"),this.immune=this.ini.getBool("Immune"),this.isAnimated=this.ini.getBool("IsAnimated"),this.snowOccupationBits=this.normalizeOccupationBits(this.ini.getNumber("SnowOccupationBits",ts.All)),this.spawnsTiberium=this.ini.getBool("SpawnsTiberium"),this.strength=this.ini.getNumber("Strength"),this.radarInvisible=this.ini.getBool("RadarInvisible"),this.temperateOccupationBits=this.normalizeOccupationBits(this.ini.getNumber("TemperateOccupationBits",ts.All))}normalizeOccupationBits(e){return(e+8*Math.abs(Math.floor(e/8)))%8}getOccupationBits(e){return e!==C.Snow?this.temperateOccupationBits:this.snowOccupationBits}getOccupiedSubCells(e){var t,i=this.getOccupationBits(e),e=[0,1,2,3,4];if(i===ts.All)return e;let s=[];for(t of e)!function(e,t){switch(e){case 0:case 1:return 1;case 2:return 0!=(t&ts.Right);case 3:return 0!=(t&ts.Left);case 4:return 0!=(t&ts.Bottom);default:throw new Error(`Invalid subCell "${e}`)}}(t,i)||s.push(t);return s}}class cs extends Ci{parse(){super.parse(),this.burn=this.ini.getBool("Burn"),this.crater=this.ini.getBool("Crater"),this.width=this.ini.getNumber("Width",1),this.height=this.ini.getNumber("Height",1)}}class us extends Ci{parse(){super.parse(),this.damage=this.ini.getNumber("Damage"),this.damageRadius=this.ini.getNumber("DamageRadius"),this.duration=this.ini.getNumber("Duration"),this.elasticity=z(this.ini.getNumber("Elasticity",.75),0,1),this.expireAnim=this.ini.getString("ExpireAnim")||void 0,this.minAngularVelocity=this.ini.getNumber("MinAngularVelocity"),this.maxAngularVelocity=this.ini.getNumber("MaxAngularVelocity"),this.maxXYVel=this.ini.getNumber("MaxXYVel"),this.minZVel=this.ini.getNumber("MinZVel"),this.maxZVel=this.ini.getNumber("MaxZVel"),this.shareTurretData=this.ini.getBool("ShareTurretData"),this.shareBodyData=this.ini.getBool("ShareBodyData"),this.shareBarrelData=this.ini.getBool("ShareBarrelData"),this.shareSource=this.ini.get("ShareSource")||void 0,this.trailerAnim=this.ini.getString("TrailerAnim")||void 0,this.trailerSeparation=this.ini.getNumber("TrailerSeperation"),this.warhead=this.ini.getString("Warhead")||void 0}}class ds{create(e,t,i){switch(e){case xt.Aircraft:case xt.Building:case xt.Infantry:case xt.Vehicle:return new os(e,t,i);case xt.Overlay:return new hs(e,t,i);case xt.Terrain:return new ls(e,t,i);case xt.Smudge:return new cs(e,t,i);case xt.VoxelAnim:return new us(e,t,i);default:return new Ci(e,t,i)}}}class ps{readIni(e){this.ballisticScatter=e.getNumber("BallisticScatter"),this.bridgeStrength=e.getNumber("BridgeStrength"),this.c4Delay=e.getNumber("C4Delay"),this.c4Warhead=e.getString("C4Warhead"),this.deathWeapon=e.getString("DeathWeapon"),this.dMislEliteWarhead=e.getString("DMislEliteWarhead"),this.dMislWarhead=e.getString("DMislWarhead"),this.flameDamage=e.getString("FlameDamage"),this.ironCurtainDuration=e.getNumber("IronCurtainDuration"),this.ivanDamage=e.getNumber("IvanDamage"),this.ivanIconFlickerRate=e.getNumber("IvanIconFlickerRate"),this.ivanTimedDelay=e.getNumber("IvanTimedDelay"),this.ivanWarhead=e.getString("IvanWarhead"),this.splashList=e.getArray("SplashList"),this.v3EliteWarhead=e.getString("V3EliteWarhead"),this.v3Warhead=e.getString("V3Warhead")}}class gs{readIni(e){return this.value=e.getNumber("Value"),this}}class ms{readIni(e){this.buildPower=e.getArray("BuildPower"),this.buildRefinery=e.getArray("BuildRefinery"),this.buildTech=e.getArray("BuildTech"),this.tiberiumFarScan=e.getNumber("TiberiumFarScan",50),this.tiberiumNearScan=e.getNumber("TiberiumNearScan",5)}}class fs{readIni(e){return this.increment=e.getNumber("ElevationIncrement"),this.incrementBonus=e.getNumber("ElevationIncrementBonus",1),this.bonusCap=e.getNumber("ElevationBonusCap"),this}getBonus(e,t){return e<=t?0:Math.min(this.bonusCap,Math.floor((e-t)/this.increment))*this.incrementBonus}}class ys{readIni(e){this.radDurationMultiple=e.getNumber("RadDurationMultiple"),this.radApplicationDelay=e.getNumber("RadApplicationDelay"),this.radLevelMax=e.getNumber("RadLevelMax"),this.radLevelDelay=e.getNumber("RadLevelDelay"),this.radLightDelay=e.getNumber("RadLightDelay"),this.radLevelFactor=e.getNumber("RadLevelFactor"),this.radLightFactor=e.getNumber("RadLightFactor"),this.radTintFactor=e.getNumber("RadTintFactor"),this.radColor=e.getNumberArray("RadColor"),this.radSiteWarhead=e.getString("RadSiteWarhead")}}(r=is=is||{})[r.MultiMissile=0]="MultiMissile",r[r.IronCurtain=1]="IronCurtain",r[r.LightningStorm=2]="LightningStorm",r[r.ChronoSphere=3]="ChronoSphere",r[r.ChronoWarp=4]="ChronoWarp",r[r.ParaDrop=5]="ParaDrop",r[r.AmerParaDrop=6]="AmerParaDrop";class ws{constructor(e){this.index=e}readIni(e){return this.disableableFromShell=e.getBool("DisableableFromShell"),this.isPowered=e.getBool("IsPowered",!0),this.name=e.name,this.preClick=e.getBool("PreClick"),this.preDependent=e.getEnum("PreDependent",is,void 0),this.postClick=e.getBool("PostClick"),this.rechargeTime=e.getNumber("RechargeTime",5),this.showTimer=e.getBool("ShowTimer"),this.sidebarImage=e.getString("SidebarImage").toLowerCase(),this.type=e.getEnum("Type",is,void 0),this.uiName=e.getString("UIName"),this.weaponType=e.getString("WeaponType")||void 0,this}}class Ts{readIni(e){this.crateMaximum=e.getNumber("CrateMaximum"),this.crateMinimum=e.getNumber("CrateMinimum"),this.crateRadius=e.getNumber("CrateRadius"),this.crateRegen=e.getNumber("CrateRegen");let t=e.getString("UnitCrateType");return this.unitCrateType="none"!==t.toLowerCase()?t:void 0,this.healCrateSound=e.getString("HealCrateSound"),this.crateImg=e.getString("CrateImg"),this.waterCrateImg=e.getString("WaterCrateImg"),this.freeMCV=e.getBool("FreeMCV"),this}}(r=ss=ss||{})[r.Cheer=0]="Cheer",r[r.UnitDeployUndeploy=1]="UnitDeployUndeploy",r[r.WeaponFire=2]="WeaponFire",r[r.ObjectDestroy=3]="ObjectDestroy",r[r.ObjectSpawn=4]="ObjectSpawn",r[r.ObjectUnspawn=5]="ObjectUnspawn",r[r.ObjectMorph=6]="ObjectMorph",r[r.ObjectLiftOff=7]="ObjectLiftOff",r[r.ObjectLand=8]="ObjectLand",r[r.ObjectCrashing=9]="ObjectCrashing",r[r.ObjectDisguiseChange=10]="ObjectDisguiseChange",r[r.ObjectCloakChange=11]="ObjectCloakChange",r[r.ObjectAttacked=12]="ObjectAttacked",r[r.ShipSubmergeChange=13]="ShipSubmergeChange",r[r.BridgeRepair=14]="BridgeRepair",r[r.BuildStatusChange=15]="BuildStatusChange",r[r.BuildingPlace=16]="BuildingPlace",r[r.BuildingFailedPlace=17]="BuildingFailedPlace",r[r.BuildingSell=18]="BuildingSell",r[r.BuildingRepairFull=19]="BuildingRepairFull",r[r.BuildingCapture=20]="BuildingCapture",r[r.BuildingInfiltration=21]="BuildingInfiltration",r[r.BuildingGarrison=22]="BuildingGarrison",r[r.BuildingEvacuate=23]="BuildingEvacuate",r[r.BuildingRepairStart=24]="BuildingRepairStart",r[r.UnitRepairStart=25]="UnitRepairStart",r[r.UnitRepairFinish=26]="UnitRepairFinish",r[r.UnitRecycle=27]="UnitRecycle",r[r.InflictDamage=28]="InflictDamage",r[r.HealthChange=29]="HealthChange",r[r.WarheadDetonate=30]="WarheadDetonate",r[r.PlayerDefeated=31]="PlayerDefeated",r[r.PlayerResigned=32]="PlayerResigned",r[r.PlayerDropped=33]="PlayerDropped",r[r.DeployNotAllowed=34]="DeployNotAllowed",r[r.PowerChange=35]="PowerChange",r[r.PowerLow=36]="PowerLow",r[r.PowerRestore=37]="PowerRestore",r[r.RadarOnOff=38]="RadarOnOff",r[r.ObjectOwnerChange=39]="ObjectOwnerChange",r[r.RadarEvent=40]="RadarEvent",r[r.InsufficientFunds=41]="InsufficientFunds",r[r.RallyPointChange=42]="RallyPointChange",r[r.PrimaryFactoryChange=43]="PrimaryFactoryChange",r[r.FactoryProduceUnit=44]="FactoryProduceUnit",r[r.ObjectTeleport=45]="ObjectTeleport",r[r.AllianceChange=46]="AllianceChange",r[r.UnitPromote=47]="UnitPromote",r[r.EnterTransport=48]="EnterTransport",r[r.LeaveTransport=49]="LeaveTransport",r[r.EnterObject=50]="EnterObject",r[r.EnterTile=51]="EnterTile",r[r.SuperWeaponReady=52]="SuperWeaponReady",r[r.SuperWeaponActivate=53]="SuperWeaponActivate",r[r.LightningStormManifest=54]="LightningStormManifest",r[r.LightningStormCloud=55]="LightningStormCloud",r[r.CratePickup=56]="CratePickup",r[r.PingLocation=57]="PingLocation",r[r.StalemateDetect=58]="StalemateDetect",r[r.TriggerSoundFx=59]="TriggerSoundFx",r[r.TriggerStopSoundFx=60]="TriggerStopSoundFx",r[r.TriggerEva=61]="TriggerEva",r[r.TriggerAnim=62]="TriggerAnim",r[r.TriggerText=63]="TriggerText",r[r.TimerExpire=64]="TimerExpire";class bs{constructor(e,t,i,s){this.target=e,this.player=t,this.source=i,this.tile=s,this.type=ss.CratePickup}}var vs,Ss,r=__webpack_require__(949);class ks extends r.Vector2{length(){return Yi.sqrt(this.x*this.x+this.y*this.y)}angle(){let e=Yi.atan2(this.y,this.x);return e<0&&(e+=2*Math.PI),e}distanceTo(e){return Yi.sqrt(this.distanceToSquared(e))}rotateAround(e,t){var i=Yi.cos(t),s=Yi.sin(t),r=this.x-e.x,t=this.y-e.y;return this.x=r*i-t*s+e.x,this.y=r*s+t*i+e.y,this}}class Os{static tileToWorld(e,t){return{x:e*Os.LEPTONS_PER_TILE,y:t*Os.LEPTONS_PER_TILE}}static vecWorldToGround(e){return new ks(e.x,e.z)}static vecGroundToWorld(e){return new rs(e.x,0,e.y)}static tileHeightToWorld(e){return e*(Os.LEPTONS_PER_TILE/2)*Os.zScale}static worldToTileHeight(e){return e/(Os.LEPTONS_PER_TILE/2*Os.zScale)}static tile3dToWorld(e,t,i){t=Os.tileToWorld(e,t),i=Os.tileHeightToWorld(i);return new rs(t.x,i,t.y)}static screenDistanceToWorld(e,t){return{x:Math.floor((e+2*t)/2*Os.ISO_WORLD_SCALE),y:Math.floor((2*t-e)/2*Os.ISO_WORLD_SCALE)}}static getWorldTileSize(){return Os.LEPTONS_PER_TILE}}function _s(e){return[Jt.Water,Jt.Beach].includes(e)?vs.Water:vs.Ground}Os.ISO_TILE_SIZE=30,Os.LEPTONS_PER_TILE=256,Os.ISO_WORLD_SCALE=Os.LEPTONS_PER_TILE/Os.ISO_TILE_SIZE,Os.ISO_CAMERA_ALPHA=Math.PI/6,Os.ISO_CAMERA_BETA=Math.PI/4,Os.COS_ISO_CAMERA_BETA=Yi.cos(Os.ISO_CAMERA_BETA),Os.zScale=Os.COS_ISO_CAMERA_BETA/Yi.cos(Os.ISO_CAMERA_ALPHA),(r=vs=vs||{})[r.Ground=0]="Ground",r[r.Air=1]="Air",r[r.Water=2]="Water";const Is=e=>void 0!==e.position,Cs=e=>void 0!==e.addScalar;class As{constructor(e){this.tileOccupation=e}isInWeaponRange(e,t,i,s,r){var a=r??e;if(i.rules.limboLaunch&&2<Math.abs((Is(a)?a.position.tileElevation+a.tile.z:a.z)-(Is(t)?t.position.tileElevation+t.tile.z:t.z)))return!1;var{minRange:r,range:s}=this.computeWeaponRangeVsTarget(a,t,i,s);return i.rules.cellRangefinding?this.isInTileRange(a,t,r,s):e.isUnit()&&e.rules.movementZone===ri.Fly?this.isInRange2(a,t,r,s):this.isInRange3(a,t,r,s)}computeWeaponRangeVsTarget(e,t,i,s){let r=0;var a,n;return!Is(t)||!t.isBuilding()||i.projectileRules.arcing||i.projectileRules.vertical||i.warhead.rules.ivanBomb||1<(n=t.getFoundation()).width&&1<n.height&&(r+=Math.ceil(Math.min(n.width,n.height)/2)),!i.projectileRules.subjectToElevation||i.projectileRules.arcing&&!Is(t)||(a=Is(e)?e.tile.z+e.tileElevation:e.z,(n=Is(t)?t.tile.z+t.tileElevation:t.z)<a&&(r+=s.elevationModel.getBonus(a,n))),i.projectileRules.isAntiAir&&Is(e)&&e.isTechno()&&Is(t)&&t.isUnit()&&t.zone===vs.Air&&(r+=e.rules.airRangeBonus),{minRange:i.minRange,range:i.range+r}}isInRange(e,t,i,s,r=!1){return r?this.isInTileRange(e,t,i,s):e.isUnit()&&e.rules.movementZone===ri.Fly?this.isInRange2(e,t,i,s):this.isInRange3(e,t,i,s)}isInRange3(e,t,i,s){return V(this.distance3(e,t)/Os.LEPTONS_PER_TILE,i,s)}isInRange2(e,t,i,s){return V(this.distance2(e,t)/Os.LEPTONS_PER_TILE,i,s)}distance3(e,t){let i=Is(e)?e.position.worldPosition:Cs(e)?e:Os.tile3dToWorld(e.rx+.5,e.ry+.5,e.z);t=Is(t)?t.position.worldPosition:Cs(t)?t:Os.tile3dToWorld(t.rx+.5,t.ry+.5,t.z);return i.distanceTo(t)}distance2(e,t){let i=Is(e)?new ks(e.position.worldPosition.x,e.position.worldPosition.z):Cs(e)?new ks(e.x,e.z):new ks(e.rx+.5,e.ry+.5).multiplyScalar(Os.LEPTONS_PER_TILE);t=Is(t)?new ks(t.position.worldPosition.x,t.position.worldPosition.z):Cs(t)?new ks(t.x,t.z):new ks(t.rx+.5,t.ry+.5).multiplyScalar(Os.LEPTONS_PER_TILE);return i.distanceTo(t)}isInTileRange(e,t,i,s){return V(this.tileDistance(e,t),i,s)}tileDistance(e,t){var i,e=Is(e)?this.tileOccupation.calculateTilesForGameObject(e.tile,e):Array.isArray(e)?e:[e],s=Is(t)?this.tileOccupation.calculateTilesForGameObject(t.tile,t):Array.isArray(t)?t:[t];let r=new ks,a=new ks,n=Number.POSITIVE_INFINITY;for(i of e)for(var o of s){r.set(i.rx,i.ry),a.set(o.rx,o.ry);o=r.distanceTo(a);o<=n&&(n=o)}return n}}const Bs=e=>"name"in e;(r=Ss=Ss||{})[r.Brutal=0]="Brutal",r[r.Medium=1]="Medium",r[r.Easy=2]="Easy";var xs,Es,Ps,Ns,Ms,Ds,Rs,Ls,Fs;(new Map).set(Ss.Easy,"GUI:AIDummy").set(Ss.Medium,"GUI:AIEasyBeta"),new Map;class js{static computeGameSpeed(e){let t;return t=6===e?60:5===e?45:60/(6-e),t/js.BASE_TICKS_PER_SECOND}}js.BASE_TICKS_PER_SECOND=15;class Us{constructor(e,t,i,s,r,a,n,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.foundation=s,this.maxDistance=a,this.predicate=n,this.checkBounds=o,this.distance=r,this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){var s=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t))return t};do{var r=this.startTile.rx-this.distance,a=this.startTile.ry-this.distance,n=this.startTile.rx+this.foundation.width-1+this.distance,o=this.startTile.ry+this.foundation.height-1+this.distance;let e,t,i;if(0<this.distance){for(e=n;e>=r;e--)i=s(e,o),i&&(yield i);for(t=o-1;t>=a;t--)i=s(n,t),i&&(yield i);for(e=r;e<n;e++)i=s(e,a),i&&(yield i);for(t=1+a;t<o;t++)i=s(r,t),i&&(yield i)}else this.predicate(this.startTile)&&(yield this.startTile)}while(this.distance++,this.distance<=this.maxDistance)}}(r=xs=xs||{})[r.Armor=0]="Armor",r[r.Firepower=1]="Firepower",r[r.HealBase=2]="HealBase",r[r.Money=3]="Money",r[r.Reveal=4]="Reveal",r[r.Speed=5]="Speed",r[r.Veteran=6]="Veteran",r[r.Unit=7]="Unit",r[r.Invulnerability=8]="Invulnerability",r[r.IonStorm=9]="IonStorm",r[r.Gas=10]="Gas",r[r.Tiberium=11]="Tiberium",r[r.Pod=12]="Pod",r[r.Cloak=13]="Cloak",r[r.Darkness=14]="Darkness",r[r.Explosion=15]="Explosion",r[r.ICBM=16]="ICBM",r[r.Napalm=17]="Napalm",r[r.Squad=18]="Squad",(Es=Es||{}).onTick=Symbol(),(Ps=Ps||{}).onChange=Symbol();class Ws{constructor(e){this.target=e,this.type=ss.SuperWeaponReady}}(r=Ns=Ns||{})[r.Charging=0]="Charging",r[r.Paused=1]="Paused",r[r.Ready=2]="Ready";class zs{constructor(e,t,i,s=!1){this.name=e,this.rules=t,this.owner=i,this.oneTimeOnly=s,this.status=Ns.Charging,this.isGift=!1,this.rechargeTicks=60*t.rechargeTime*js.BASE_TICKS_PER_SECOND,this.chargeTicks=this.rechargeTicks,s&&(this.status=Ns.Ready,this.chargeTicks=0)}update(e){0<this.chargeTicks&&this.status!==Ns.Paused&&(this.chargeTicks--,0===this.chargeTicks&&(this.status=Ns.Ready,e.events.dispatch(new Ws(this))))}pauseTimer(){this.status=Ns.Paused}resumeTimer(){this.status=0<this.chargeTicks?Ns.Charging:Ns.Ready}resetTimer(){this.chargeTicks=this.rechargeTicks,this.status===Ns.Ready&&(this.status=Ns.Charging)}getTimerSeconds(){return this.chargeTicks/js.BASE_TICKS_PER_SECOND}getChargeProgress(){return(this.rechargeTicks-this.chargeTicks)/this.rechargeTicks}}(r=Ms=Ms||{})[r.NotStarted=0]="NotStarted",r[r.Running=1]="Running",r[r.Finished=2]="Finished";class Vs{constructor(e,t,i){this.type=e,this.owner=t,this.tile=i,this.status=Ms.NotStarted}onStart(e){}onTick(e){return!0}}(r=Ds=Ds||{}).onPowerLow=Symbol(),r.onPowerRestore=Symbol(),r.onPowerChange=Symbol(),(Rs=Rs||{}).onActivate=Symbol();class Hs{constructor(e,t,i,s,r){this.target=e,this.owner=t,this.atTile=i,this.atTile2=s,this.noSfxWarning=r,this.type=ss.SuperWeaponActivate}}(r=Ls=Ls||{})[r.None=0]="None",r[r.Guard=1]="Guard",r[r.Prone=2]="Prone",r[r.Deployed=3]="Deployed",r[r.Paradrop=4]="Paradrop",r[r.Cheer=5]="Cheer",(r=Fs=Fs||{})[r.NotStarted=0]="NotStarted",r[r.Running=1]="Running",r[r.Finished=2]="Finished",r[r.Cancelling=3]="Cancelling",r[r.Cancelled=4]="Cancelled";class Gs{constructor(){this.status=Fs.NotStarted,this.children=[],this.cancellable=!0,this.useChildTargetLines=!1,this.blocking=!0,this.waitingForChildrenToFinish=!1,this.preventOpportunityFire=!0,this.preventLanding=!0,this.isAttackMove=!1}isRunning(){return this.status===Fs.Running}isCancelling(){return this.status===Fs.Cancelling}setCancellable(e){return this.cancellable=e,this}onStart(e){}onEnd(e){}cancel(){if(this.cancellable)if(this.status===Fs.Running)this.status=Fs.Cancelling,this.children.length&&this.children.forEach(e=>e.cancel());else if(this.status===Fs.NotStarted&&(this.status=Fs.Cancelled,this.children.length))throw new Error("Should't have any children before starting a task")}getTargetLinesConfig(e){}}function $s(t,i){for(let e=t.length-1;0<=e;e--)if(i(t[e],e,t))return e;return-1}class qs extends Gs{constructor(e){super(),this.ticks=e}onTick(){return!!this.isCancelling()||!(0<this.ticks--)}}class Xs{constructor(e){this.map=e}findPositions(e,s,r,a){let n=new Map,t=this.clusterObjects(e);if(!t.length)throw new Error("We should have found at least one cluster");let i=t.reduce((e,t)=>t.objects.size>e.objects.size?t:e,t[0]);t.splice(t.indexOf(i),1);let o=[],h=this.findCenterTile([...i.objects]);i.objects.forEach(t=>{var i=this.map.tiles.getByMapCoords(s.rx+t.tile.rx-h.rx,s.ry+t.tile.ry-h.ry),e=i?.onBridgeLandType?this.map.tileOccupation.getBridgeOnTile(i):void 0;if(!i||!this.map.mapBounds.isWithinBounds(i)||n.has(i)&&!this.tileHasRoom(t,n.get(i))||t.rules.movementZone===ri.Fly&&!(t.rules.airportBound||a&&t.rules.balloonHover&&!t.rules.hoverAttack)&&!this.map.terrain.getPassableSpeed(i,ei.Amphibious,!!e)||t.rules.movementZone!==ri.Fly&&!this.isEligibleTile(i,e,r,s))o.push(t);else{let e=n.get(i);void 0===e&&(e=[],n.set(i,e)),e.push(t)}}),t.forEach(e=>o.push(...e.objects));let l=new Us(this.map.tiles,this.map.mapBounds,s,{width:1,height:1},1,5,()=>!0),c;for(;o.length&&(c=l.getNextTile());){var u=o[0],d=this.map.tileOccupation.getBridgeOnTile(c);if((!n.has(c)||this.tileHasRoom(u,n.get(c)))&&((u.rules.movementZone!==ri.Fly||u.rules.airportBound||this.map.terrain.getPassableSpeed(c,ei.Amphibious,!!d))&&(u.rules.movementZone===ri.Fly||this.isEligibleTile(c,d,r,s)))){let e=n.get(c);void 0===e&&(e=[],n.set(c,e)),e.push(o.shift())}}let p=new Map;if(n.forEach((e,t)=>{e.forEach(e=>p.set(e,t))}),o.forEach(e=>p.set(e,s)),p.size!==e.length)throw new Error("We should have computed a number of positions equal to the number of input objects");return p}tileHasRoom(e,t){if(e.isInfantry()){if(t.find(e=>!e.isInfantry()))return!1;e=e.rules.movementZone===ri.Fly?1:3;return t.filter(e=>e.isInfantry()).length>=e?!1:!0}return!t.length}isEligibleTile(e,t,i,s){return i?.isHighBridge()||t?.isHighBridge()?e.z+(t?.tileElevation??0)===s.z+(i?.tileElevation??0):!(!i&&!t)||Math.abs(e.z-s.z)<2}clusterObjects(e){let r=new Map;e.forEach(e=>{var t=e.tile.rx+"_"+e.tile.ry;r.set(t,[...r.get(t)||[],e])});let t=[],a=new Set(e);for(;a.size;){let e=new Set,s=[];var i=[...a][0].tile;for(r.get(i.rx+"_"+i.ry).forEach(e=>{s.push(e)});s.length;){var n=s.shift();e.add(n),a.delete(n);for(let i=-1;i<=1;i++)for(let t=-1;t<=1;t++)if(i||t){let e=r.get(n.tile.rx+i+"_"+(n.tile.ry+t));e&&e.length&&e.forEach(e=>{a.has(e)&&(a.delete(e),s.push(e))})}}t.push({objects:e})}return t}findCenterTile(e){let t=0,i=0;e.forEach(e=>{t+=e.tile.rx,i+=e.tile.ry}),t=Math.round(t/e.length),i=Math.round(i/e.length);let s=this.map.tiles.getByMapCoords(t,i);if(!s&&(s=e.find(e=>Math.abs(e.tile.rx-t)<=1&&Math.abs(e.tile.ry-i)<=1)?.tile,!s))throw new Error("At least one adjacent object should have been found");return s}}r=__webpack_require__(949);class Zs extends r.Matrix4{extractRotation(e){let t=this.elements;var i=e.elements,s=1/Qs.setFromMatrixColumn(e,0).length(),r=1/Qs.setFromMatrixColumn(e,1).length(),e=1/Qs.setFromMatrixColumn(e,2).length();return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=0,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=0,t[8]=i[8]*e,t[9]=i[9]*e,t[10]=i[10]*e,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){e&&e.isEuler||console.error("THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.");let t=this.elements;var i,s,r,a,n,o,h,l,c,u,d,p=e.x,g=e.y,m=e.z,f=Yi.cos(p),y=Yi.sin(p),w=Yi.cos(g),T=Yi.sin(g),p=Yi.cos(m),g=Yi.sin(m);return"XYZ"===e.order?(i=f*p,r=f*g,s=y*p,m=y*g,t[0]=w*p,t[4]=-w*g,t[8]=T,t[1]=r+s*T,t[5]=i-m*T,t[9]=-y*w,t[2]=m-i*T,t[6]=s+r*T,t[10]=f*w):"YXZ"===e.order?(a=w*p,i=w*g,s=T*p,r=T*g,t[0]=a+r*y,t[4]=s*y-i,t[8]=f*T,t[1]=f*g,t[5]=f*p,t[9]=-y,t[2]=i*y-s,t[6]=r+a*y,t[10]=f*w):"ZXY"===e.order?(h=w*p,a=w*g,n=T*p,o=T*g,t[0]=h-o*y,t[4]=-f*g,t[8]=n+a*y,t[1]=a+n*y,t[5]=f*p,t[9]=o-h*y,t[2]=-f*T,t[6]=y,t[10]=f*w):"ZYX"===e.order?(n=f*p,o=f*g,l=y*p,h=y*g,t[0]=w*p,t[4]=l*T-o,t[8]=n*T+h,t[1]=w*g,t[5]=h*T+n,t[9]=o*T-l,t[2]=-T,t[6]=y*w,t[10]=f*w):"YZX"===e.order?(u=f*w,l=f*T,c=y*w,d=y*T,t[0]=w*p,t[4]=d-u*g,t[8]=c*g+l,t[1]=g,t[5]=f*p,t[9]=-y*p,t[2]=-T*p,t[6]=l*g+c,t[10]=u-d*g):"XZY"===e.order&&(c=f*w,u=f*T,d=y*w,e=y*T,t[0]=w*p,t[4]=-g,t[8]=T*p,t[1]=c*g+e,t[5]=f*p,t[9]=u*g-d,t[2]=d*g-u,t[6]=y*p,t[10]=e*g+c),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}lookAt(e,t,i){Ys.set(0,0,0),Ks.set(0,0,0),Js.set(0,0,0);const s=this.elements;return Js.subVectors(e,t),0===Js.lengthSq()&&(Js.z=1),Js.normalize(),Ys.crossVectors(i,Js),0===Ys.lengthSq()&&(1===Math.abs(i.z)?Js.x+=1e-4:Js.z+=1e-4,Js.normalize(),Ys.crossVectors(i,Js)),Ys.normalize(),Ks.crossVectors(Js,Ys),s[0]=Ys.x,s[4]=Ks.x,s[8]=Js.x,s[1]=Ys.y,s[5]=Ks.y,s[9]=Js.y,s[2]=Ys.z,s[6]=Ks.z,s[10]=Js.z,this}getMaxScaleOnAxis(){var e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],e=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Yi.sqrt(Math.max(t,i,e))}makeRotationX(e){var t=Yi.cos(e),e=Yi.sin(e);return this.set(1,0,0,0,0,t,-e,0,0,e,t,0,0,0,0,1),this}makeRotationY(e){var t=Yi.cos(e),e=Yi.sin(e);return this.set(t,0,e,0,0,1,0,0,-e,0,t,0,0,0,0,1),this}makeRotationZ(e){var t=Yi.cos(e),e=Yi.sin(e);return this.set(t,-e,0,0,e,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){var i=Yi.cos(t),s=Yi.sin(t),r=1-i,a=e.x,n=e.y,o=e.z,t=r*a,e=r*n;return this.set(t*a+i,t*n-s*o,t*o+s*n,0,t*n+s*o,e*n+i,e*o-s*a,0,t*o-s*n,e*o+s*a,r*o*o+i,0,0,0,0,1),this}decompose(e,t,i){var s=this.elements;let r=Qs.set(s[0],s[1],s[2]).length();var a=Qs.set(s[4],s[5],s[6]).length(),n=Qs.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),e.x=s[12],e.y=s[13],e.z=s[14],er.copy(this);var o=1/r,e=1/a,s=1/n;return er.elements[0]*=o,er.elements[1]*=o,er.elements[2]*=o,er.elements[4]*=e,er.elements[5]*=e,er.elements[6]*=e,er.elements[8]*=s,er.elements[9]*=s,er.elements[10]*=s,t.setFromRotationMatrix(er),i.x=r,i.y=a,i.z=n,this}}const Qs=new rs,Ys=new rs,Ks=new rs,Js=new rs,er=new Zs;var tr=__webpack_require__(949);function ir(e){return e*tr.Math.RAD2DEG}function sr(e){return e*tr.Math.DEG2RAD}const rr=new ks;function ar(e,t){t=sr(Math.floor(t));return e.rotateAround(rr,t)}function nr(e){return Math.round(ir(e.angle()))}function or(e,t){t=ir(2*Yi.acos(Math.abs(z(e.dot(t),-1,1))));return Math.round(t)}function hr(e,t){e=nr(e),t=nr(t);return Math.min((e-t+360)%360,(t-e+360)%360)}function lr(e,t){return or(cr(e,mr),cr(t,fr))}function cr(e,t=new Ki){return t.setFromRotationMatrix(ur.lookAt(e,dr,pr))}const ur=new Zs,dr=new rs(0,0,0),pr=new rs(0,1,0);function gr(e,t,i){var s=e.length(),r=cr(t,mr),t=cr(e,fr);!function(e,t,i){var s=or(e,t);if(0!==s){s=Math.min(1,i/s);e.slerp(t,s)}}(t,r,i),e.set(0,0,1).applyQuaternion(t).setLength(s)}const mr=new Ki,fr=new Ki;class yr extends Gs{constructor(e,t){super(),this.game=e,this.fromDirection=t,this.resolved=!1,this.chainPushIssued=!1}onEnd(e){e.moveTrait.collisionState=Zr.Resolved}onTick(i){if(this.timeoutTicks=void 0===this.timeoutTicks?0:this.timeoutTicks+1,40<this.timeoutTicks||this.resolved||this.isCancelling())return!0;let s=this.game.map,t=new Xs(s),r=i.onBridge?s.tileOccupation.getBridgeOnTile(i.tile):void 0,a,n;for(let e=0;e<360;e+=45)if((0!==e||this.chainPushIssued)&&180!==e){var o=ar(this.fromDirection.clone(),e).round(),o=s.tiles.getByMapCoords(i.tile.rx+Math.sign(o.x),i.tile.ry+Math.sign(o.y));if(o&&s.mapBounds.isWithinBounds(o)&&(n=!r||r.isHighBridge()?s.tileOccupation.getBridgeOnTile(o):void 0,i.rules.movementZone===ri.Fly||!s.terrain.findObstacles({tile:o,onBridge:n},i).length&&t.isEligibleTile(o,n,r,i.tile))){a=o;break}}if(a)return this.resolved=!0,i.isInfantry()&&i.deployerTrait&&i.deployerTrait.isDeployed()&&i.deployerTrait.setDeployed(!1),!!i.moveTrait.isDisabled()||(this.children.push(new ka(this.game,a,!!n,{closeEnoughTiles:0,strictCloseEnough:!0})),!1);{if(this.chainPushIssued)return this.children.push(new qs(5)),!1;let t=s.tiles.getByMapCoords(i.tile.rx+Math.sign(this.fromDirection.x),i.tile.ry+Math.sign(this.fromDirection.y));if(!t||!s.mapBounds.isWithinBounds(t))return!0;n=!r||r.isHighBridge()?s.tileOccupation.getBridgeOnTile(t):void 0;let e=s.tileOccupation.getGroundObjectsOnTile(t).filter(e=>e.isUnit()&&e.owner===i.owner&&e.tile===t&&e.onBridge===!!n&&!(e.isInfantry()&&e.stance===Ls.Paradrop)&&!(e.isAircraft()&&e.missileSpawnTrait));return e.find(e=>e.moveTrait.collisionState===Zr.Waiting||e.unitOrderTrait.hasTasks())?(this.children.push(new qs(5)),i.moveTrait.collisionState=Zr.Waiting,i.moveTrait.moveState=qr.PlanMove,!1):(e.forEach(e=>{e.unitOrderTrait.addTask(new yr(this.game,this.fromDirection))}),this.children.push(new qs(1)),i.moveTrait.collisionState=Zr.Waiting,i.moveTrait.moveState=qr.PlanMove,!(this.chainPushIssued=!0))}}}const wr=__webpack_require__(163);class Tr{constructor(e){this.game=e,this.ignoresTerrain=!0,this.distanceToWaypoint=new ks}onNewWaypoint(e,t){}tick(e,t,i,s){if(s)return{distance:new rs,done:!0};this.distanceToWaypoint.copy(t).sub(e.position.getMapPosition());s=this.game.rules.general;return s.chronoTrigger&&(s=(t=this.distanceToWaypoint.length())<s.chronoRangeMinimum?s.chronoMinimumDelay:t/s.chronoDistanceFactor,e.warpedOutTrait.setTimed(s,!1,this.game)),{distance:new rs(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!0,isTeleport:!0}}}class br{static tick(e,t,i){if(e===t)return{facing:e,delta:0};var s=(e-t+360)%360,r=(t-e+360)%360;if(Math.min(s,r)<i)return{facing:t,delta:0};i*=r<=s?1:-1;return{facing:(e+i+360)%360,delta:i}}static fromMapCoords(e){return(-nr(e)-90+720)%360}static toMapCoords(e){return ar(new ks(1e3,0),br.toWorldDeg(e)).round().normalize()}static toWorldDeg(e){return-(e+90)}}class vr extends Gs{constructor(e){super(),this.direction=e,this.cancellable=!1}onTick(e){if(e.direction===this.direction)return!(e.spinVelocity=0);var t=e.rules.rot,{facing:i,delta:t}=br.tick(e.direction,this.direction,t);return e.direction=i,e.spinVelocity=t,!1}}r=__webpack_require__(949);class Sr extends r.LineCurve{constructor(e,t){super(e||new ks,t||new ks)}getPoint(e,t){return super.getPoint(e,t||new ks)}}r=__webpack_require__(949);class kr extends r.CurvePath{closePath(){let e=this.curves[0].getPoint(0);var t=this.curves[this.curves.length-1].getPoint(1);e.equals(t)||this.curves.push(new Sr(t,e))}}var Or,_r,r=__webpack_require__(949);class Ir extends r.QuadraticBezierCurve{constructor(e,t,i){super(e||new ks,t||new ks,i||new ks)}getPoint(e,t){return super.getPoint(e,t||new ks)}}(r=Or=Or||{})[r.None=0]="None",r[r.Start=1]="Start",r[r.Normal=2]="Normal",r[r.End=3]="End",r[r.Single=4]="Single";class Cr{constructor(e){this.game=e,this.hasMomentum=!1,this.moveOnCurve=!1,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=Or.None}selectNextWaypoint(i,s){if(this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==Or.End?Or.Normal:Or.Start,this.initialPosition=i.position.getMapPosition(),this.currentWaypointType!==Or.Start?i.moveTrait.speedPenalty=0:this.currentSpeed=0,1<s.length){var r=s[s.length-1],a=s[s.length-2],e=new ks(r.tile.rx-i.tile.rx,r.tile.ry-i.tile.ry),n=Math.abs(nr(e)-nr(new ks(a.tile.rx-r.tile.rx,a.tile.ry-r.tile.ry)));if(!Math.abs(br.fromMapCoords(e)-i.direction)&&0<n&&n<90&&this.hasMomentum){this.moveOnCurve=!0,this.currentWaypointType=2===s.length?this.currentWaypointType===Or.Start?Or.Single:Or.End:Or.Normal;let e=this.initialPosition;i=new ks(r.tile.rx+.5,r.tile.ry+.5).multiplyScalar(Os.LEPTONS_PER_TILE);let t=new ks(a.tile.rx+.5,a.tile.ry+.5).multiplyScalar(Os.LEPTONS_PER_TILE);n=e.clone().lerp(i,.5),r=t.clone().lerp(i,.5);return this.steerCurve=new kr,this.steerCurve.add(new Sr(e,n)),this.steerCurve.add(new Ir(n,i,r)),this.steerCurve.add(new Sr(r,t)),this.lastPosition=e,a}}else this.currentWaypointType=this.currentWaypointType===Or.Start?Or.Single:Or.End;return this.hasMomentum=!0,this.moveOnCurve=!1,s[s.length-1]}onNewWaypoint(e,t,i){let s=(new ks).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=this.moveOnCurve?this.steerCurve.getLength():s.length();t=br.fromMapCoords(s);if(t!==e.direction&&(this.pointTurretToTarget(e,i),!this.moveOnCurve))return e.moveTrait.velocity.set(0,0,0),[new vr(t)]}tick(i,s,r){this.pointTurretToTarget(i,r);let a=this.currentSpeed;a=i.rules.accelerates?(h=this.distanceTravelled/this.totalDistanceToTravel,this.currentSpeed=this.applyAcceleration(i,a,i.moveTrait.baseSpeed,h)):this.currentSpeed=i.moveTrait.baseSpeed,1<a&&(a=Math.floor(a));let e=this.game.map.terrain.getPassableSpeed(i.tile,i.rules.speedType,i.onBridge,void 0,!0);e?i.moveTrait.lastTileSpeed=e:e=i.moveTrait.lastTileSpeed,a*=e,1<a&&(a=Math.floor(a)),this.carryOverDistance&&(a=this.carryOverDistance);var n=i.position.getMapPosition();let o;if(this.moveOnCurve){var r=this.steerCurve.getLength(),h=Math.min(this.distanceTravelled+a,r);this.carryOverDistance=Math.max(0,this.distanceTravelled+a-r),this.distanceTravelled=h;let e=this.steerCurve.getPointAt(this.distanceTravelled/r),t=this.steerCurve.getTangentAt(this.distanceTravelled/r);h=t.clone().setLength(a);i.moveTrait.velocity.set(h.x,0,h.y);var r=i.rules.rot,{facing:h,delta:r}=br.tick(i.direction,br.fromMapCoords(t),r);i.direction=h,i.spinVelocity=r;r=this.lastPosition;this.lastPosition=e.clone(),o=e.sub(r)}else{let e=(new ks).copy(s).sub(n);n=Math.min(e.length(),a);o=e.clone().setLength(n);let t=o.clone();this.carryOverDistance&&t.add(Os.vecWorldToGround(i.moveTrait.velocity)),i.moveTrait.velocity.set(t.x,0,t.y),this.distanceTravelled+=n,this.carryOverDistance=Math.max(0,a-e.length())}return{distance:new rs(o.x,0,o.y),done:!o.length()||!!this.carryOverDistance}}pointTurretToTarget(t,i){if(t.turretTrait){t.attackTrait?.currentTarget?.obj&&(i=t.attackTrait.currentTarget.obj.position.getMapPosition());var s=t.position.getMapPosition();let e=(new ks).copy(i).sub(s);e.length()&&(s=br.fromMapCoords(e),t.turretTrait.desiredFacing=s)}}applyAcceleration(e,t,i,s){if(this.currentWaypointType===Or.Single)return i/2;if(this.currentWaypointType!==Or.End)return Math.min(t+e.rules.accelerationFactor*i,i);return H(1,i,1-(s=this.moveOnCurve&&this.currentWaypointType===Or.End?s<=.5?0:2*(s-.5):s))}}class Ar{constructor(e){this.game=e,this.currentMoveDirection=new ks,this.distanceToWaypoint=new ks,this.endPauseFrames=0}onNewWaypoint(e,t){this.currentMoveDirection.copy(t).sub(e.position.getMapPosition());t=br.fromMapCoords(this.currentMoveDirection);t!==e.direction&&(e.direction=t),this.endPauseFrames=1}onWaypointUpdate(e,t){this.onNewWaypoint(e,t)}tick(e,t,i){let s=e.moveTrait.baseSpeed;s=Math.floor(s),e.stance===Ls.Prone&&(s/=2),e.isPanicked&&(s*=2);let r=this.game.map.terrain.getPassableSpeed(e.tile,e.rules.speedType,e.onBridge,void 0,!0);r?this.lastTileSpeed=r:r=this.lastTileSpeed||1,s*=r,s=Math.floor(s),this.distanceToWaypoint.copy(t).sub(e.position.getMapPosition());let a=this.distanceToWaypoint.clone().setLength(s);(a.length()||t.equals(i))&&e.moveTrait.velocity.set(a.x,0,a.y);i=Math.min(this.distanceToWaypoint.length(),s),e=!i&&0<this.endPauseFrames--;return this.distanceToWaypoint.setLength(i),{distance:new rs(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!this.distanceToWaypoint.length()&&!e}}}(r=_r=_r||{})[r.None=0]="None",r[r.Start=1]="Start",r[r.Normal=2]="Normal",r[r.End=3]="End",r[r.Single=4]="Single";class Br{constructor(e){this.hoverRules=e,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=_r.None,this.nextWaypointDir=new ks}selectNextWaypoint(e,t){var i;return this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==_r.End?_r.Normal:_r.Start,this.initialPosition=e.position.getMapPosition(),this.currentWaypointType===_r.Start&&(this.currentSpeed=0),t.length<=1?(this.currentWaypointType=this.currentWaypointType===_r.Start?_r.Single:_r.End,(i=t[t.length-1])&&this.nextWaypointDir.set(i.tile.rx-e.tile.rx,i.tile.ry-e.tile.ry)):(i=t[t.length-1],e=t[t.length-2],this.nextWaypointDir.set(e.tile.rx-i.tile.rx,e.tile.ry-i.tile.ry)),t[t.length-1]}onNewWaypoint(e,t,i){let s=(new ks).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=s.length();t=this.maxSpeed=e.moveTrait.baseSpeed,e=60*this.hoverRules.acceleration*js.BASE_TICKS_PER_SECOND;this.acceleration=t/e;e=60*this.hoverRules.brake*js.BASE_TICKS_PER_SECOND;this.deceleration=t/e}tick(e,t){var i=e.position.getMapPosition();let s=t.clone().sub(i);t=s.length(),i=this.maxSpeed;this.currentWaypointType===_r.Single?this.currentSpeed=i/2:this.currentWaypointType===_r.End?(r=this.computeBrakeDistance(this.currentSpeed,this.deceleration),this.totalDistanceToTravel-this.distanceTravelled<=r&&(this.currentSpeed=Math.max(0,this.currentSpeed-this.deceleration))):this.currentSpeed=Math.min(this.currentSpeed+this.acceleration,i);var r=br.fromMapCoords(s),i=br.fromMapCoords(this.nextWaypointDir);let a=r,n=e.rules.rot;this.currentWaypointType===_r.Normal&&r!==i&&(r=(o=hr(this.nextWaypointDir,br.toMapCoords(e.direction)))/n,r=Math.max(this.currentSpeed*r,this.totalDistanceToTravel),this.totalDistanceToTravel-this.distanceTravelled<=r&&(a=i,n=o/((this.totalDistanceToTravel-this.distanceTravelled)/this.currentSpeed)));var o=br.tick(e.direction,a,n)["facing"];e.direction=o;let h=this.currentSpeed;this.carryOverDistance&&(h=this.carryOverDistance);o=Math.min(h,t);let l=s.clone().setLength(o),c=l.clone();return this.carryOverDistance&&c.add(Os.vecWorldToGround(e.moveTrait.velocity)),e.moveTrait.velocity.set(c.x,0,c.y),this.distanceTravelled+=o,this.carryOverDistance=Math.max(0,h-t),{distance:new rs(l.x,0,l.y),done:!l.length()||!!this.carryOverDistance}}computeBrakeDistance(e,t){var i=e/t;return Math.max(0,e*i-t*i*i/2)}}class xr{static computeInterceptPoint(e,t,i,s){let r=e.clone().sub(i);var a=s.length(),e=t*t-a*a,t=2*r.dot(s),a=-r.dot(r);if(t*t-4*e*a<0)return new rs;e=(-t+Yi.sqrt(t*t-4*e*a))/(2*e);return s.clone().multiplyScalar(e).add(i)}static computeTurnCircle(e,t,i,s){s/=sr(Math.abs(i));let r=ar(t.clone(),90*-Math.sign(i));return{center:isFinite(s)?r.setLength(s).add(e):e.clone(),radius:s}}}var Er=__webpack_require__(949);function Pr(e,t){var i=e.center;return(i.x-t.x)*(i.x-t.x)+(i.y-t.y)*(i.y-t.y)<=e.radius*e.radius}function Nr(e,t){let i=new Er.Box2(new Er.Vector2(e.x,e.y),new Er.Vector2(e.x+e.width,e.y+e.height));return i.containsPoint(new Er.Vector2(t.x,t.y))}class Mr{constructor(e){this.gameObject=e,this.type=ss.ObjectLiftOff}}class Dr{constructor(e){this.gameObject=e,this.type=ss.ObjectLand}}class Rr{constructor(e){this.game=e,this.allowOutOfBounds=!0,this.currentMoveDir=new ks,this.currentHorizSpeed=0}static tickStationary(t,i){if(t.zone===vs.Air){var s=t.tile.onBridgeLandType?i.map.tileOccupation.getBridgeOnTile(t.tile):void 0,r=!t.rules.balloonHover&&(!t.unitOrderTrait.getCurrentTask()?.preventLanding||!t.rules.hoverAttack)&&(i.map.getGroundObjectsOnTile(t.tile).find(e=>e.isBuilding()&&e.dockTrait?.isDocked(t))||i.map.getTileZone(t.tile)!==vs.Water&&0<i.map.terrain.getPassableSpeed(t.tile,ei.Foot,!!t.tile.onBridgeLandType)&&0===i.map.terrain.findObstacles({tile:t.tile,onBridge:s},t).length);let e;e=r?(a=t.tile.z+(s?.tileElevation??0),Os.tileHeightToWorld(a)):(n=t.tile.z+i.map.getGroundObjectsOnTile(t.tile).filter(e=>!(e.isInfantry()&&e.stance===Ls.Paradrop)).reduce((e,t)=>Math.max(e,t.tileElevation+t.art.height),0),Os.tileHeightToWorld(n)+t.rules.jumpjetHeight);var a,n,o=t.position.worldPosition.y;e!==o?(a=t.rules.jumpjetClimb,n=Math.abs(e-o),a=Math.sign(e-o)*Math.min(a,n),n=t.tileElevation,t.position.moveByLeptons3(new rs(0,a,0)),t.moveTrait.handleElevationChange(n,i)):r&&(t.zone=vs.Ground,t.onBridge=!!s,i.events.dispatch(new Dr(t)),(s=i.map.tileOccupation.getGroundObjectsOnTile(t.tile).find(e=>e.isOverlay()&&e.rules.crate))&&i.crateGeneratorTrait.pickupCrate(t,s,i))}}static tickCrash(e,t,i){var s=2*e.rules.jumpjetCrash;return e.direction=(e.direction-6+360)%360,new rs(0,-s,0)}onNewWaypoint(e,t,i){this.currentMoveDir=br.toMapCoords(e.direction),this.cancelDestLeptons=void 0}tick(t,e,i,s){if(t.zone!==vs.Air&&(t.onBridge=!1,t.zone=vs.Air,this.game.events.dispatch(new Mr(t))),s){if(!this.cancelDestLeptons){let e=t.tile;this.game.map.isWithinBounds(e)||(e=this.game.map.clampWithinBounds(e)),this.cancelDestLeptons=this.computeCancelDest(e,i)}i=this.cancelDestLeptons}var r=t.position.getMapPosition();let a=i.clone().sub(r),n=this.findTilesToCheckForBlockers(t.tile,r,this.currentMoveDir,a.length());var o=n.map(e=>e.z+this.game.map.getGroundObjectsOnTile(e).filter(e=>!(e.isDestroyed||e.isInfantry()&&e.stance===Ls.Paradrop)).reduce((e,t)=>Math.max(e,t.tileElevation+t.art.height),0)).reduce((e,t)=>Math.max(e,t),0);let h=0;(void 0===this.lastClearZ||2<o-this.lastClearZ)&&(h=4);var l=Os.tileHeightToWorld(o),c=Os.tileHeightToWorld(o+h),u=t.position.worldPosition.y,d=br.fromMapCoords(a),p=a.length()<t.rules.jumpjetSpeed;let g=0;l<=u&&!p&&({facing:T,delta:s}=br.tick(t.direction,d,t.rules.jumpjetTurnRate),g=s,t.direction=T,this.currentMoveDir.copy(br.toMapCoords(t.direction))),t.isVehicle()&&(t.spinVelocity=g);let m,f=!1,y=0,w=0;var T=t.rules.jumpjetClimb;u<c?(y=Math.min(T,c-u),m=!1,this.currentHorizSpeed=0):(this.lastClearZ=o,o=l+t.rules.jumpjetHeight,m=!0,o!==u&&(l=Math.abs(o-u),y=Math.sign(o-u)*Math.min(T,l),m=l<=T),T=this.currentHorizSpeed,this.currentHorizSpeed=Math.min(this.currentHorizSpeed+2,t.rules.jumpjetSpeed),f=d===t.direction?(w=Math.min(T,a.length()),T>=a.length()):((r=T||g?xr.computeTurnCircle(r,this.currentMoveDir,Math.sign(g)*t.rules.jumpjetTurnRate,T):void 0)&&Pr(r,i)?(w=0,this.currentHorizSpeed=0):w=T,!1));let b;b=p?(f=!0,a):this.currentMoveDir.clone().setLength(w);let v=new rs(b.x,y,b.y);p=v.clone();return t.moveTrait.velocity.copy(p),{distance:v,done:f&&m}}findTilesToCheckForBlockers(e,t,i,s){s=i.clone().setLength(Math.min(s,Os.LEPTONS_PER_TILE)).add(t).multiplyScalar(1/Os.LEPTONS_PER_TILE).floor(),t=this.game.map.tiles.getByMapCoords(s.x,s.y);if(!t||t===e)return[e];s=Math.sign(t.rx-e.rx),t=Math.sign(t.ry-e.ry);let r=[e],a;return s&&(a=this.game.map.tiles.getByMapCoords(e.rx+s,e.ry),a&&r.push(a)),t&&(a=this.game.map.tiles.getByMapCoords(e.rx,e.ry+t),a&&r.push(a)),s&&t&&(a=this.game.map.tiles.getByMapCoords(e.rx+s,e.ry+t),a&&r.push(a)),r}computeCancelDest(e,t){var i=t.clone().multiplyScalar(1/Os.LEPTONS_PER_TILE).floor().multiplyScalar(Os.LEPTONS_PER_TILE),i=t.clone().sub(i);return new ks(e.rx,e.ry).multiplyScalar(Os.LEPTONS_PER_TILE).add(i)}}var Lr,Fr,jr,Ur,Wr,zr,Vr,Hr,Gr,$r,qr,Xr,Zr,Qr,Yr,Kr,Jr,ea,ta,ia,sa,ra,aa,na,oa,ha,la,ca,ua,r=__webpack_require__(949);class da extends r.CubicBezierCurve3{constructor(e,t,i,s){super(e||new rs,t||new rs,i||new rs,s||new rs)}getPoint(e,t){return super.getPoint(e,t||new rs)}}(r=Lr=Lr||{})[r.Boost=0]="Boost",r[r.Midcourse=1]="Midcourse",r[r.Terminal=2]="Terminal";class pa{constructor(e,t){this.game=e,this.missileRules=t,this.flightPhase=Lr.Boost}selectNextWaypoint(e,t){var i=t[t.length-1],t=this.game.map.tileOccupation.getBridgeOnTile(i.tile),t=i.tile.z+(t?.tileElevation??0);return this.targetPosition=Os.tile3dToWorld(i.tile.rx+.5,i.tile.ry+.5,t),this.cruiseAltitude=Os.tileHeightToWorld(t)+this.missileRules.altitude,i}onNewWaypoint(e,t,i){}tick(i,e,t){let s=i.position.worldPosition.clone(),r=this.targetPosition.clone().sub(s);i.zone!==vs.Air&&(i.onBridge=!1,i.zone=vs.Air,this.game.events.dispatch(new Mr(i)));let a;var n;a=this.currentVelocity?(n=i.rules.speed,Math.min(this.currentVelocity.length()+this.missileRules.acceleration,n)):(p=this.missileRules.acceleration,this.missileRules.lazyCurve?this.currentVelocity=new rs(r.x,0,r.z):this.currentVelocity=Os.vecGroundToWorld(br.toMapCoords(i.direction)),gr(this.currentVelocity,new rs(this.currentVelocity.x,1e8,this.currentVelocity.z),i.pitch),p),this.currentVelocity.setLength(a);let o=!1;switch(this.flightPhase){case Lr.Boost:if(!(i.position.worldPosition.y>=this.cruiseAltitude)){o=!1;break}this.flightPhase=Lr.Midcourse;case Lr.Midcourse:var h,l=new ks(r.x,r.z).length();if(!this.missileRules.lazyCurve){gr(this.currentVelocity,new rs(this.currentVelocity.x,0,this.currentVelocity.z),i.rules.rot),this.currentVelocity.y<1&&(h=this.currentVelocity.length(),this.currentVelocity.y=0,this.currentVelocity.setLength(h)),gr(this.currentVelocity,new rs(r.x,this.currentVelocity.y,r.z),i.rules.rot),i.direction=br.fromMapCoords(Os.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*lr(this.currentVelocity,new rs(this.currentVelocity.x,0,this.currentVelocity.z)),l/(s.y-this.targetPosition.y)<1&&(this.flightPhase=Lr.Terminal);break}this.flightPhase=Lr.Terminal;var c=s.clone().add(this.currentVelocity.clone().setLength(l/3/Yi.cos(sr(i.pitch)))),u=this.targetPosition.clone().lerp(s,.15).setY(c.y);this.descentCurve=new da(s,c,u,this.targetPosition);case Lr.Terminal:c=this.missileRules.bodyLength;if(this.missileRules.lazyCurve){var d=this.descentCurve.getLength();this.descentTravelled??(this.descentTravelled=0),this.descentTravelled+=Math.min(a,d-c-this.descentTravelled);u=this.descentTravelled/d;let e=this.descentCurve.getPointAt(u),t=this.descentCurve.getTangentAt(u);this.currentVelocity.copy(e.sub(s));u=t.clone().setY(0);i.pitch=Math.sign(t.y-u.y)*lr(u,t),o=1<=(this.descentTravelled+c)/d}else{gr(this.currentVelocity,r,i.rules.rot),i.direction=br.fromMapCoords(Os.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*lr(this.currentVelocity,new rs(this.currentVelocity.x,0,this.currentVelocity.z));d=r.length()-c;(d<a||d<1)&&(this.currentVelocity.copy(r.clone().addScalar(-c)),o=!0)}break;default:throw new Error(`Unhandled flight phase "${this.flightPhase}"`)}var p=s.clone().add(this.currentVelocity);return this.game.map.isWithinHardBounds(p)?(i.moveTrait.velocity.copy(this.currentVelocity),{distance:this.currentVelocity,done:o}):(this.game.destroyObject(i),{done:!0,distance:new rs})}}class ga extends qs{constructor(e){super(Math.floor(js.BASE_TICKS_PER_SECOND*e*60))}}class ma extends Gs{constructor(e){super(),this.cb=e}onTick(e){return this.cb(e),!0}}(Fr=Fr||{}).onTick=Symbol(),(r=jr=jr||{})[r.Idle=0]="Idle",r[r.MoveToQueueingTile=1]="MoveToQueueingTile",r[r.WaitForTurn=2]="WaitForTurn",r[r.MoveToDock=3]="MoveToDock",r[r.Docking=4]="Docking",r[r.Docked=5]="Docked";class fa extends Gs{constructor(e,t){super(),this.game=e,this.target=t,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.dockingStatus=jr.Idle}onStart(e){if(!this.target.dockTrait)throw new Error(`Target object "${this.target.name}" is not a valid dock`);var t;this.target.dockTrait.hasReservedDockForUnit(e)?this.dockingStatus=jr.MoveToDock:void 0!==(t=this.target.dockTrait.getFirstAvailableDockNumber())?(this.target.dockTrait.reserveDockAt(e,t),this.dockingStatus=jr.MoveToDock):this.target.helipadTrait?this.cancel():this.dockingStatus=jr.MoveToQueueingTile}onEnd(e){this.dockingStatus!==jr.Docked&&this.target.isSpawned&&(this.target.dockTrait.undockUnit(e),this.target.dockTrait.unreserveDockForUnit(e)),this.dockingStatus=jr.Idle}onTick(e){if(this.isCancelling())return!0;if(!this.isValidTarget(this.target,e))return!0;if(this.dockingStatus===jr.MoveToQueueingTile){var t=this.findReachableQueueingTile(e);if(!t)return!0;if(e.tile!==t)return this.children.push(new ka(this.game,t,!1,{closeEnoughTiles:5}),new ma(()=>{e.moveTrait.lastMoveResult===Xr.Fail?this.cancel():e.moveTrait.lastMoveResult===Xr.CloseEnough&&(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)||(this.dockingStatus=jr.WaitForTurn))})),!1;this.dockingStatus=jr.WaitForTurn}if(this.dockingStatus===jr.WaitForTurn){var i=this.target.dockTrait.getFirstAvailableDockNumber();if(void 0===i)return this.children.push(new ga(1/60)),!1;this.target.dockTrait.reserveDockAt(e,i),this.dockingStatus=jr.MoveToDock}if(this.dockingStatus===jr.MoveToDock){var s=this.target.dockTrait.getReservedDockForUnit(e),i=this.target.dockTrait.getDockTile(s),s=Os.vecWorldToGround(this.target.dockTrait.getDockOffset(s)).add(this.target.position.getMapPosition()).sub(new ks(i.rx,i.ry).multiplyScalar(Os.LEPTONS_PER_TILE));if(e.tile!==i)return this.children.push(new ka(this.game,i,!1,{targetOffset:e.isAircraft()?s:void 0,closeEnoughTiles:0,strictCloseEnough:!0}),new ma(()=>{e.moveTrait.lastMoveResult===Xr.Fail&&this.cancel()})),this.game.afterTick(()=>e.unitOrderTrait[Fr.onTick](e,this.game)),!1;this.dockingStatus=jr.Docking}if(this.dockingStatus!==jr.Docking)return!1;s=this.target.dockTrait.getReservedDockForUnit(e);return this.target.dockTrait.unreserveDockForUnit(e),this.target.dockTrait.dockUnitAt(e,s),e.isAircraft()&&e.airportBoundTrait&&this.target.helipadTrait&&(e.airportBoundTrait.preferredAirport=this.target),this.dockingStatus=jr.Docked,!0}isValidTarget(e,t){return e.isSpawned&&this.game.areFriendly(e,t)}findReachableQueueingTile(t){var e=this.target.getFoundation(),e=new ks(this.target.tile.rx+e.width,this.target.tile.ry+e.height),e=this.game.map.tiles.getByMapCoords(e.x,e.y);return e&&this.isValidQueueingTile(e,t)?e:new Us(this.game.map.tiles,this.game.map.mapBounds,this.target.tile,this.target.getFoundation(),1,1,e=>this.isValidQueueingTile(e,t)).getNextTile()}isValidQueueingTile(e,t){return(t.rules.movementZone===ri.Fly||0<this.game.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&Math.abs(e.z-this.target.tile.z)<2&&!e.onBridgeLandType&&!this.game.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length)&&!this.game.map.tileOccupation.isTileOccupiedBy(e,this.target)}}(r=Ur=Ur||{})[r.None=0]="None",r[r.CircleStrafe=1]="CircleStrafe",r[r.HoverStrafe=2]="HoverStrafe";class ya{constructor(e){this.game=e,this.allowOutOfBounds=!0,this.lastDestLeptons=new ks,this.currentMoveDir=new ks,this.currentHorizSpeed=0,this.maneuverType=Ur.None,this.deceleratingToTurn=!1}static tickStationary(r,a){if(r.zone===vs.Air){var n=r.tile.onBridgeLandType?a.map.tileOccupation.getBridgeOnTile(r.tile):void 0;let e=r.rules.landable&&!r.unitOrderTrait.getCurrentTask()?.preventLanding,i=r.spawnLinkTrait?.getParent();e&&i?e=!((!i.isUnit()||!i.onBridge)&&n||i.tile!==r.tile):e&&!r.airportBoundTrait&&(e=a.map.getTileZone(r.tile)!==vs.Water&&0<a.map.terrain.getPassableSpeed(r.tile,ei.Foot,!!r.tile.onBridgeLandType)&&0===a.map.terrain.findObstacles({tile:r.tile,onBridge:n},r).length);let s;if(e){let e=r.airportBoundTrait?.preferredAirport?.dockTrait;var o=e?.isDocked(r)||e?.hasReservedDockForUnit(r);if(!r.airportBoundTrait||o){var h=o?0:270;if(r.direction!==h)return void(r.direction=br.tick(r.direction,h,r.rules.rot).facing)}if(r.airportBoundTrait){let e=r.airportBoundTrait.preferredAirport;if(!e?.dockTrait?.isDocked(r))return e?.dockTrait?.getAvailableDockCount()||(e=r.airportBoundTrait.findAvailableAirport(r),r.airportBoundTrait.preferredAirport=e,e&&(h=e.dockTrait.getFirstAvailableDockNumber(),e.dockTrait.reserveDockAt(r,h))),void(e?(r.unitOrderTrait.addTask(new fa(a,e)),r.unitOrderTrait[Fr.onTick](r,a)):r.crashableTrait.crash(void 0))}let t;t=i?i.tile.z+i.tileElevation:r.tile.z+(n?.tileElevation??0),s=Os.tileHeightToWorld(t)}else{var t=r.tile.z+(n?.tileElevation??0),l=r.rules.flightLevel??a.rules.general.flightLevel;s=Os.tileHeightToWorld(t)+l}t=r.position.worldPosition.y;s!==t?(l=Math.abs(s-t),t=Math.sign(s-t)*Math.min(30,l),l=r.tileElevation,r.position.moveByLeptons3(new rs(0,t,0)),r.moveTrait.handleElevationChange(l,a)):e&&(r.zone=vs.Ground,i?i.airSpawnTrait.storeAircraft(r,a):r.onBridge=!!n,a.events.dispatch(new Dr(r)),(n=a.map.tileOccupation.getGroundObjectsOnTile(r.tile).find(e=>e.isOverlay()&&e.rules.crate))&&a.crateGeneratorTrait.pickupCrate(r,n,a))}}static tickCrash(e,t,i){i.rollDelta??(i.rollDelta=t.generateRandomInt(-15,15)),i.pitchDelta??(i.pitchDelta=t.generateRandomInt(0,15)),e.roll+=i.rollDelta,e.pitch+=i.pitchDelta;e=Os.vecWorldToGround(e.moveTrait.velocity);return new rs(e.x,-30,e.y)}onNewWaypoint(e,t,i){this.currentHorizSpeed=Os.vecWorldToGround(e.moveTrait.velocity).length(),this.cancelDestLeptons=void 0}tick(t,e,i,s){if(s){if(!this.cancelDestLeptons){let e=t.tile;this.game.map.isWithinBounds(e)||(e=this.game.map.clampWithinBounds(e)),this.cancelDestLeptons=this.computeCancelDest(e,i)}i=this.cancelDestLeptons}var r=t.position.getMapPosition();let a=i.clone().sub(r);var n=a.length();this.lastDestLeptons.equals(i)||(this.lastDestLeptons.copy(i),s?this.maneuverType=Ur.HoverStrafe:t.zone===vs.Air&&this.currentHorizSpeed<5?this.maneuverType=n>Os.LEPTONS_PER_TILE?Ur.CircleStrafe:Ur.HoverStrafe:this.maneuverType=Ur.None,this.deceleratingToTurn=!1),t.zone!==vs.Air&&(t.onBridge=!1,t.zone=vs.Air,this.game.events.dispatch(new Mr(t)));var o=t.tile.onBridgeLandType?this.game.map.tileOccupation.getBridgeOnTile(t.tile):void 0,h=t.tile.z+(o?.tileElevation??0),l=t.rules.flightLevel??this.game.rules.general.flightLevel,s=Os.tileHeightToWorld(h)+l,o=t.position.worldPosition.y,c=br.fromMapCoords(a);t.direction===c&&this.maneuverType===Ur.None&&n<=Os.LEPTONS_PER_TILE?this.maneuverType=Ur.HoverStrafe:t.direction===c&&this.maneuverType===Ur.CircleStrafe&&(this.maneuverType=Ur.None);let u;switch(this.maneuverType){case Ur.HoverStrafe:if(t.attackTrait?.currentTarget){let e=Os.vecWorldToGround(t.attackTrait.currentTarget.getWorldCoords());u=br.fromMapCoords(e.sub(r))}else u=t.airportBoundTrait?.preferredAirport?.dockTrait?.hasReservedDockForUnit(t)?0:270;break;case Ur.CircleStrafe:case Ur.None:u=c;break;default:throw new Error(`Unknown maneuver type "${this.maneuverType}`)}var{facing:d,delta:p}=br.tick(t.direction,u,t.rules.rot);t.direction=d,t.roll=Math.sign(p)*t.rules.pitchAngle;let g;switch(this.maneuverType){case Ur.HoverStrafe:g=c;break;case Ur.CircleStrafe:g=(d-90*Math.sign(p)+360)%360;break;case Ur.None:g=d;break;default:throw new Error(`Unknown maneuver type "${this.maneuverType}`)}void 0===this.thrustFacing&&(this.thrustFacing=g);var h=5<this.currentHorizSpeed?t.rules.rot:Number.POSITIVE_INFINITY,{facing:l,delta:h}=br.tick(this.thrustFacing,g,h);this.thrustFacing=l,this.currentMoveDir.copy(br.toMapCoords(this.thrustFacing));let m=!1,f=0,y=0;let w=!0;s!==o&&(b=Math.abs(s-o),f=Math.sign(s-o)*Math.min(30,b),w=b<=30);let T=t.rules.speed;n<=Os.LEPTONS_PER_TILE&&this.maneuverType!==Ur.CircleStrafe&&(T=H(1,T/2,Yi.sqrt(n/Os.LEPTONS_PER_TILE))),this.deceleratingToTurn?this.currentHorizSpeed=Math.max(0,this.currentHorizSpeed-2):this.currentHorizSpeed=Math.min(this.currentHorizSpeed+2,T);var b=this.currentHorizSpeed;this.deceleratingToTurn=!1,m=h?(h=b||h?xr.computeTurnCircle(r,this.currentMoveDir,Math.sign(h)*t.rules.rot,b):void 0,0!==b&&!Pr(h,i)||(this.maneuverType===Ur.HoverStrafe||n>Os.LEPTONS_PER_TILE?this.deceleratingToTurn=!0:this.maneuverType===Ur.None&&(this.maneuverType=Ur.HoverStrafe)),y=b,!1):(y=Math.min(b,n),n<=b);let v;v=n<1?(m=!0,a):m?a:this.currentMoveDir.clone().setLength(y);let S=new rs(v.x,f,v.y);n=S.clone();return t.moveTrait.velocity.copy(n),{distance:S,done:m&&w}}computeCancelDest(e,t){var i=t.clone().multiplyScalar(1/Os.LEPTONS_PER_TILE).floor().multiplyScalar(Os.LEPTONS_PER_TILE),i=t.clone().sub(i);return new ks(e.rx,e.ry).multiplyScalar(Os.LEPTONS_PER_TILE).add(i)}}class wa{constructor(e){this.game=e}create(e){var t=e.rules.locomotor;switch(t){case si.Infantry:return new Ar(this.game);case si.Jumpjet:return new Rr(this.game);case si.Vehicle:case si.Ship:return new Cr(this.game);case si.Chrono:return e.isVehicle()&&e.harvesterTrait&&e.rules.teleporter?new Cr(this.game):new Tr(this.game);case si.Aircraft:return new ya(this.game);case si.Missile:return new pa(this.game,this.game.rules.general.getMissileRules(e.name));case si.Hover:return new Br(this.game.rules.general.hover);default:throw new Error(`Unhandled locomotor type ${t}`)}}}class Ta{constructor(e,t,i,s,r,a,n=!1,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=s,this.rng=r,this.predicate=a,this.includeStartTile=n,this.checkBounds=o,this.pool=[],this.pool=new Array(Yi.pow(2*this.maxDistance+1,2)).fill(0).map((e,t)=>t),this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){for(var e=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(this.includeStartTile||t!==this.startTile)return t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t)?t:void 0},t=2*this.maxDistance+1;this.pool.length;){var i=1<this.pool.length?this.rng.generateRandomInt(0,this.pool.length):0,s=this.pool.splice(i,1)[0],i=s%t,s=Math.floor(s/t),s=e(this.startTile.rx-this.maxDistance+i,this.startTile.ry-this.maxDistance+s);s&&(yield s)}}}class ba{constructor(e,t,i){this.target=e,this.isChronoshift=t,this.prevTile=i,this.type=ss.ObjectTeleport}}(Wr=Wr||{}).onBeforeTeleport=Symbol();class va{constructor(e){this.game=e,this.movePositionHelper=new Xs(e.map)}findPositions(e,t){let i=new Set,s=new Map;for(var r of e){var a=this.findFreeMovePosition(r,i,t);a&&(s.set(r,a),i.add(a.tile))}return s}findFreeMovePosition(i,e,{ignoredBlockers:t,excludedTiles:s,noSlopes:r}={}){let a=this.game.map,n=i.onBridge?a.tileOccupation.getBridgeOnTile(i.tile):void 0,o=new Ta(a.tiles,a.mapBounds,i.tile,1,this.game,e=>{if(s?.includes(e))return!1;var t=a.tileOccupation.getBridgeOnTile(e);return(t&&this.movePositionHelper.isEligibleTile(e,t,n,i.tile)||this.movePositionHelper.isEligibleTile(e,void 0,n,i.tile))&&(!r||0===e.rampType)}),h,l;for(;;){var c=o.getNextTile();if(!c)break;if(h=c,l=a.tileOccupation.getBridgeOnTile(c),l&&!this.movePositionHelper.isEligibleTile(c,l,n,i.tile)&&(l=void 0),!e.has(c)){let e=a.terrain.findObstacles({tile:c,onBridge:l},i);if(t&&t.length&&(e=e.filter(e=>!t.includes(e.obj))),!e.length)break}}if(h)return{tile:h,onBridge:l}}}class Sa extends Gs{constructor(e,t,i){super(),this.game=e,this.target=t,this.options=i}onStart(i){if(!i.moveTrait.isDisabled()&&i.rules.movementZone!==ri.Fly){let e,t;if(this.target)({tile:e,toBridge:t}=this.target);else{i=new va(this.game).findPositions([i],this.options).get(i);if(!i)return;e=i.tile,t=!!i.onBridge}this.children.push(new ka(this.game,e,t,{closeEnoughTiles:0,ignoredBlockers:this.options?.ignoredBlockers}))}}onTick(e){return!0}}class ka extends Gs{constructor(e,t,i,s){super(),this.game=e,this.targetTile=t,this.toBridge=i,this.options=s,this.preventOpportunityFire=!1,this.logger=wr.get("move"),this.destinationLeptons=new ks,this.currentWaypointLeptons=new ks,this.needsPathUpdate=!1,this.targetChangeRequested=!1,this.allObstaclesAreBlockers=!1,this.blockedPathNodes=[],this.unreachableTargets=[],this.pushTried=!1,this.cancelProcessed=!1,this.cancelRepositionPending=!1,this.targetLinesConfig={pathNodes:[]}}duplicate(){return new ka(this.game,this.targetTile,this.toBridge,this.options)}setForceMove(e){e?(this.options??(this.options={}),this.options.forceMove=!0):this.options?.forceMove&&(this.options.forceMove=void 0)}onStart(e){if(e.moveTrait.currentWaypoint)throw new Error("Nested move tasks are not supported");void 0===e.moveTrait.locomotor&&(e.moveTrait.locomotor=new wa(this.game).create(e)),e.moveTrait.lastTargetOffset?this.targetOffset=e.moveTrait.lastTargetOffset:this.targetOffset=this.computeTargetOffset(e),e.moveTrait.lastVelocity&&(e.moveTrait.velocity=e.moveTrait.lastVelocity),this.path||(this.computePath(e,e.moveTrait.locomotor),this.targetLinesConfig.isRecalc=!1),this.updateDestination(this.path,this.targetOffset),e.moveTrait.moveState=qr.ReachedNextWaypoint,e.moveTrait.lastMoveResult=void 0,e.moveTrait.lastTargetOffset=void 0,e.moveTrait.lastVelocity=void 0}computeTargetOffset(e){return this.options?.targetOffset??(e.isInfantry()?e.position.getTileOffset():e.position.computeSubCellOffset(0))}computePath(e,t){let i;i=this.options?.allowOutOfBoundsTarget||this.game.map.mapBounds.isWithinBounds(this.targetTile)?e.rules.movementZone===ri.Fly?this.computeAirPath(e):t.ignoresTerrain?this.computeDirectJumpPath(e):(this.blockedPathNodes=this.blockedPathNodes.filter(e=>e.obj.isSpawned&&e.node.tile===e.obj.tile),this.computeGroundPath(e)):[],e.rules.movementZone===ri.Fly?(this.targetLinesConfig.pathNodes=i.map(({tile:e,onBridge:t})=>({tile:e,onBridge:t})),i.length&&(this.targetLinesConfig.pathNodes[0].onBridge=this.toBridge?this.game.map.tileOccupation.getBridgeOnTile(this.targetTile):void 0)):this.targetLinesConfig.pathNodes=i,this.path=i}computeAirPath(e){return[{tile:this.targetTile,onBridge:void 0},{tile:e.tile,onBridge:void 0}]}computeDirectJumpPath(t){let i=this.game.map;var e=t.onBridge?i.tileOccupation.getBridgeOnTile(t.tile):void 0;let s=this.targetTile,r=this.toBridge?i.tileOccupation.getBridgeOnTile(this.targetTile):void 0,a=this.options?.ignoredBlockers;var n=new Us(i.tiles,i.mapBounds,s,{width:1,height:1},0,5,e=>0<i.terrain.getPassableSpeed(e,t.rules.speedType,!!e.onBridgeLandType,a)&&!i.terrain.findObstacles({tile:e,onBridge:!!e.onBridgeLandType},t).find(e=>!a?.includes(e.obj))).getNextTile();return n?(n!==s&&(s=n,r=i.tileOccupation.getBridgeOnTile(s)),[{tile:s,onBridge:r},{tile:t.tile,onBridge:e}]):[]}computeGroundPath(t){let e=t.tile,i=t.onBridge?this.game.map.tileOccupation.getBridgeOnTile(e):void 0;t.moveTrait.moveState===qr.Moving&&t.moveTrait.currentWaypoint&&(e=t.moveTrait.currentWaypoint.tile,i=t.moveTrait.currentWaypoint.onBridge);let s;var r=this.toBridge?this.game.map.tileOccupation.getBridgeOnTile(this.targetTile):void 0,a=this.nodeIsBlockedForPathfinding({tile:this.targetTile,onBridge:r},t);if(Math.abs(e.rx-this.targetTile.rx)<=1&&Math.abs(e.ry-this.targetTile.ry)<=1&&new Xs(this.game.map).isEligibleTile(e,i,r,this.targetTile)&&a)s=[];else{const o=this.game.map.getObjectsOnTile(e).find(e=>e.isBuilding());if(o&&!this.game.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)){this.options??(this.options={});var n=this.options?.ignoredBlockers?.includes(o);if(this.options.ignoredBlockers=[...new Set([...this.options?.ignoredBlockers??[],o])],!n&&o.dockTrait){let t=new Set(o.dockTrait?.getAllDockTiles()),e=this.game.map.tileOccupation.calculateTilesForGameObject(o.tile,o);e.filter(e=>!t.has(e)).forEach(e=>this.blockedPathNodes.push({node:{tile:e,onBridge:void 0},obj:o}))}}n=this.game.map.getGroundObjectsOnTile(this.targetTile).find(e=>(e.isInfantry()||e.isVehicle())&&e.disguiseTrait?.hasTerrainDisguise()&&!(this.game.alliances.haveSharedIntel(t.owner,e.owner)||e.owner.sharedDetectDisguiseTrait?.has(t)));n&&this.blockedPathNodes.push({node:{tile:this.targetTile,onBridge:r},obj:n}),s=this.game.map.terrain.computePath(t.rules.speedType,e,!!i,this.targetTile,this.toBridge,{maxExpandedNodes:this.allObstaclesAreBlockers?Math.min(300,this.options?.maxExpandedPathNodes??Number.POSITIVE_INFINITY):this.options?.maxExpandedPathNodes,bestEffort:!this.options?.strictCloseEnough,ignoredBlockers:[...new Set([...this.options?.ignoredBlockers??[],...this.options?.pathFinderIgnoredBlockers??[]])],excludeTiles:this.allObstaclesAreBlockers||this.blockedPathNodes.length?e=>this.nodeIsBlockedForPathfinding(e,t):void 0})}return s}nodeIsBlockedForPathfinding(t,e){return this.allObstaclesAreBlockers?!!this.game.map.terrain.findObstacles(t,e).find(e=>!this.options?.ignoredBlockers?.includes(e.obj)):!!this.blockedPathNodes.find(({node:e})=>e.tile===t.tile&&e.onBridge===t.onBridge)}updateDestination(e,t){e=e.length?e[0].tile:this.targetTile;this.destinationLeptons.set(e.rx*Os.LEPTONS_PER_TILE,e.ry*Os.LEPTONS_PER_TILE).add(t)}canStopAtTile(t,i,s){if(t.zone===vs.Air){if((!t.isAircraft()||!t.airportBoundTrait)&&!t.rules.spawned&&(!this.options?.forceMove||!t.rules.balloonHover||t.rules.hoverAttack)&&(!this.game.map.terrain.getPassableSpeed(i,ei.Amphibious,s)||this.game.map.getObjectsOnTile(i).filter(e=>e.isBuilding()&&!e.isDestroyed&&!e.dockTrait?.hasReservedDockForUnit(t)&&!t.rules.dock.includes(e.name)||e.isUnit()&&e.tile===i&&e.moveTrait.moveState!==qr.Moving&&e!==t).length))return!1}else if(t.isInfantry()){let e=this.game.map.getGroundObjectsOnTile(i).filter(e=>e.isInfantry()&&e.tile===i&&e.onBridge===s&&e.moveTrait.moveState!==qr.Moving&&e!==t);if(2<e.length||e.find(e=>e.position.subCell===t.position.subCell))return!1}return!(t.zone!==vs.Air&&t.rules.tooBigToFitUnderBridge&&!s&&i.onBridgeLandType&&this.game.map.tileOccupation.getBridgeOnTile(i)?.isHighBridge())&&!(!this.isCancelling()&&this.options?.strictCloseEnough&&void 0!==this.options?.closeEnoughTiles&&!this.isCloseEnoughToDest(t,i,this.options.closeEnoughTiles))}isCloseEnoughToDest(e,t,i){if(void 0===i)return!0;let s=new As(this.game.map.tileOccupation);return!(s.tileDistance(this.targetTile,t)>i)}hasReachedDestination(e){return!this.path.length}updateTarget(e,t){this.targetTile=e,this.toBridge=t,this.needsPathUpdate=!0,this.targetChangeRequested=!0}onEnd(e){e.moveTrait.collisionState=Zr.Resolved,e.moveTrait.currentWaypoint=void 0,this.targetOffset.equals(this.computeTargetOffset(e))||(e.moveTrait.lastTargetOffset=this.targetOffset)}forceCancel(e){return!(!this.cancellable||this.children.some(e=>!e.cancellable))&&(!(!this.options?.allowOutOfBoundsTarget&&!this.game.map.isWithinBounds(e.tile))&&(this.status!==Fs.Running&&this.status!==Fs.Cancelling||(e.moveTrait.unreservePathNodes(),e.moveTrait.lastMoveResult=Xr.Cancel,this.onEnd(e),e.moveTrait.lastTargetOffset=this.targetOffset,e.moveTrait.lastVelocity=e.moveTrait.velocity.clone()),this.status=Fs.Cancelled,!0))}onTick(r){if(r.moveTrait.isDisabled()&&r.moveTrait.moveState===qr.ReachedNextWaypoint)return!!this.isCancelling()&&(r.moveTrait.lastMoveResult=Xr.Cancel,!0);this.needsPathUpdate&&(r.moveTrait.moveState===qr.PlanMove&&(this.inPlanningForTicks=void 0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.collisionState=Zr.Resolved,r.moveTrait.moveState=qr.ReachedNextWaypoint,r.moveTrait.velocity.set(0,0,0)),this.computePath(r,r.moveTrait.locomotor),this.path.length||this.unreachableTargets.push({tile:this.targetTile,toBridge:this.toBridge}),this.updateDestination(this.path,this.targetOffset),this.targetLinesConfig.isRecalc=!this.targetChangeRequested,this.targetChangeRequested=!1,this.needsPathUpdate=!1,this.allObstaclesAreBlockers=!1);let i=this.game.map;if(r.moveTrait.moveState===qr.ReachedNextWaypoint){r.moveTrait.unreservePathNodes();var s=this.path.findIndex(e=>e===r.moveTrait.currentWaypoint);if(-1!==s?this.path.splice(s):this.path.pop(),r.moveTrait.currentWaypoint=void 0,this.isCancelling()?!this.cancelProcessed:this.hasReachedDestination(r)){var a=!this.isCancelling()&&!this.isCloseEnoughToDest(r,r.tile,this.options?.closeEnoughTiles);if(!a&&this.canStopAtTile(r,r.tile,r.onBridge))return r.moveTrait.lastMoveResult=this.isCancelling()?Xr.Cancel:Xr.Success,!0;{if(5<this.unreachableTargets.length)return r.moveTrait.lastMoveResult=Xr.Fail,this.log(r,"bail_max_unreachable_dest"),!0;let e=r.tile,t=r.onBridge?i.tileOccupation.getBridgeOnTile(e):void 0;a&&(e=this.targetTile,t=this.toBridge?i.tileOccupation.getBridgeOnTile(e):void 0);s=this.findRelocationTile(e,t,r);if(!s)return r.moveTrait.lastMoveResult=a?Xr.Fail:Xr.CloseEnough,this.log(r,"bail_no_free_dest"),!0;a=!t||t.isHighBridge()?i.tileOccupation.getBridgeOnTile(s):void 0;return this.updateTarget(s,!!a),this.isCancelling()&&(this.cancelProcessed=!0,this.cancelRepositionPending=!0),!1}}if(this.cancelProcessed&&!this.path.length)return r.moveTrait.lastMoveResult=Xr.Cancel,!0;this.cancelProcessed=!1,r.moveTrait.moveState=qr.PlanMove;let e=r.moveTrait.locomotor;r.moveTrait.currentWaypoint=e.selectNextWaypoint?e.selectNextWaypoint(r,this.path):this.path[this.path.length-1],this.currentWaypointLeptons.set(r.moveTrait.currentWaypoint.tile.rx,r.moveTrait.currentWaypoint.tile.ry).multiplyScalar(Os.LEPTONS_PER_TILE).add(this.targetOffset);a=e.onNewWaypoint(r,this.currentWaypointLeptons,this.destinationLeptons);if(a)return this.children.push(...a),!1}if(r.moveTrait.moveState===qr.PlanMove){if(this.isCancelling()&&!this.cancelRepositionPending)return r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=qr.ReachedNextWaypoint,this.onTick(r);if(this.inPlanningForTicks=void 0===this.inPlanningForTicks?0:this.inPlanningForTicks+1,200<this.inPlanningForTicks)return this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,r.moveTrait.velocity.set(0,0,0),this.log(r,"repath_plan_timeout"),!1;if(r.rules.movementZone!==ri.Fly&&!r.moveTrait.locomotor.ignoresTerrain){let t=this.path.slice(this.path.indexOf(r.moveTrait.currentWaypoint)).reverse();var n,e,o=r.moveTrait.velocity.length();for(n of t){if(!i.terrain.getPassableSpeed(n.tile,r.rules.speedType,!!n.onBridge,this.options?.ignoredBlockers))return this.options?.stopOnBlocker&&i.terrain.findObstacles(n,r).some(e=>e.obj===this.options.stopOnBlocker)?(r.moveTrait.lastMoveResult=Xr.CloseEnough,!0):(this.needsPathUpdate=!0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=qr.ReachedNextWaypoint,this.onTick(r));if(!n.onBridge){var h=i.getGroundObjectsOnTile(n.tile).find(e=>e.isOverlay()&&e.rules.crate);if(h)if(this.game.crateGeneratorTrait.peekInsideCrate(h)===xs.Unit){this.game.crateGeneratorTrait.pickupCrate(r,h,this.game);h=this.game.map.getGroundObjectsOnTile(n.tile).find(e=>e.isUnit()&&!e.onBridge);if(h)return this.needsPathUpdate=!0,this.blockedPathNodes.push({node:n,obj:h}),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=qr.ReachedNextWaypoint,this.onTick(r)}}for(e of i.terrain.findObstacles(n,r).filter(e=>!this.options?.ignoredBlockers?.includes(e.obj))){if(e.static)return this.needsPathUpdate=!0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=qr.ReachedNextWaypoint,this.onTick(r);if(e.obj.rules.crushable){if([ei.Track,ei.Hover].includes(r.rules.speedType)&&r.crusher&&(!e.obj.isTechno()||!this.game.areFriendly(e.obj,r)))continue;if(!e.obj.isTechno())return this.needsPathUpdate=!0,r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=qr.ReachedNextWaypoint,this.onTick(r)}if(e.obj.isTerrain()){if(!r.isInfantry())throw new Error(`Obstacle ${e.obj.name} should be a blocker for non infantry`);var l=this.findFreeSubCell(r,n);return void 0!==l?this.relocateToSubCell(r,l):(this.needsPathUpdate=!0,this.blockedPathNodes.push({node:n,obj:e.obj}),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=qr.ReachedNextWaypoint),this.onTick(r)}if(!e.obj.isTechno())throw new Error(`Unexpected obstacle of type ${e.obj.type}`);const f=e.obj;var c=f.isUnit()?f.moveTrait.velocity.length():0;if(!f.isAircraft()||f.zone!==vs.Ground||!this.options?.ignoredBlockers?.some(e=>e.isBuilding()&&e.dockTrait?.isDocked(f))){if(1===t.length&&f.isUnit()&&c&&o&&o<=c&&r.direction===f.direction&&f.tile===n.tile&&f.moveTrait.currentWaypoint?.tile!==n.tile)break;if(f.isBuilding()||f.moveTrait.moveState===qr.Idle||f.moveTrait.collisionState!==Zr.Resolved){if(!o&&r.moveTrait.collisionState!==Zr.Resolved&&f.isUnit()&&f.moveTrait.collisionState!==Zr.Resolved)return 200<this.inPlanningForTicks+1&&(this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,this.log(r,"repath_waited_too_long_blocker "+f.id),r.moveTrait.velocity.set(0,0,0)),!1;{if(f.isInfantry()&&r.isInfantry()&&f.moveTrait.collisionState===Zr.Resolved){var u=this.findFreeSubCell(r,n);if(void 0!==u)return this.relocateToSubCell(r,u),this.onTick(r)}l=$s(this.path.slice(0,this.path.indexOf(n)),e=>!i.terrain.findObstacles(e,r).length);if(-1===l){if(this.canStopAtTile(r,r.tile,r.onBridge)&&this.isCloseEnoughToDest(r,r.tile,this.options?.closeEnoughTiles))return r.moveTrait.lastMoveResult=Xr.CloseEnough,this.log(r,"bail_waypoints_blocked_close_enough"),!0;if(!(0===this.options?.closeEnoughTiles||Math.abs(r.tile.rx-this.targetTile.rx)<=1&&Math.abs(r.tile.ry-this.targetTile.ry)<=1))return this.needsPathUpdate=!0,this.blockedPathNodes.push(...this.path.slice(0,this.path.indexOf(n)+1).map(e=>({node:e,obj:i.terrain.findObstacles(e,r)[0].obj}))),r.moveTrait.velocity.set(0,0,0),this.log(r,"repath_waypoints_blocked_too_far"),!1}let e;if(e=-1!==l?(u=this.path[l],i.terrain.computePath(r.rules.speedType,r.tile,r.onBridge,u.tile,!!u.onBridge,{maxExpandedNodes:15,bestEffort:!1,excludeTiles:e=>!!i.terrain.findObstacles(e,r).length})):[],e.length||f.owner!==r.owner||1!==t.length)return e.length?(this.path.splice(l,this.path.length,...e),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=qr.ReachedNextWaypoint,this.onTick(r)):((d=this.selectWeaponVsObstacle(r,f))?(this.children.push(r.attackTrait.createAttackTask(this.game,f,f.tile,d,{passive:!0,holdGround:!0})),r.moveTrait.velocity.set(0,0,0)):this.options?.forceWaitOnPathBlocked?(this.children.push(new qs(40)),this.inPlanningForTicks=0,r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=Zr.Waiting):(this.needsPathUpdate=!0,this.blockedPathNodes.push({node:n,obj:f}),f.isBuilding()&&(this.allObstaclesAreBlockers=!0),this.log(r,"repath_unavoidable_blocker "+f.id),r.moveTrait.velocity.set(0,0,0)),!1);d=f.unitOrderTrait.hasTasks();if(this.pushTried||f.isBuilding()||f.moveTrait.collisionState===Zr.Waiting||d||f.isAircraft()&&f.missileSpawnTrait)return!this.options?.forceWaitOnPathBlocked&&(f.isBuilding()||d&&f.moveTrait.moveState===qr.Idle||200<this.inPlanningForTicks+40)?(this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,this.log(r,"repath_blocker_busy_wait_timeout "+f.id),r.moveTrait.velocity.set(0,0,0)):(this.children.push(new qs(40)),this.options?.forceWaitOnPathBlocked?this.inPlanningForTicks=0:this.inPlanningForTicks+=40,r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=Zr.Waiting),!1;d=new ks(f.tile.rx-r.tile.rx,f.tile.ry-r.tile.ry);return this.pushTried=!0,f.unitOrderTrait.addTask(new yr(this.game,d)),this.children.push(new qs(1)),r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=Zr.Waiting,this.log(r,"push "+f.id),!1}}if(f.isInfantry()&&r.isInfantry()){var d=this.findFreeSubCell(r,n);if(void 0!==d)return this.relocateToSubCell(r,d),this.onTick(r)}if(!o)return 40<this.inPlanningForTicks&&(r.moveTrait.collisionState=Zr.Waiting),!1;if(180===Math.abs(r.direction-f.direction))return r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=Zr.Waiting,!1;if(Math.abs(r.direction-f.direction)<=45&&1.5*c<o){c=this.path.indexOf(n);if(5<=c){let e=$s(this.path.slice(0,c-5),e=>!i.terrain.findObstacles(e,r).length);if(-1!==e){c=this.path[e],c=i.terrain.computePath(r.rules.speedType,r.tile,r.onBridge,c.tile,!!c.onBridge,{maxExpandedNodes:15,bestEffort:!1,excludeTiles:t=>!!i.terrain.findObstacles(t,r).length||this.path.findIndex(e=>e.tile===t.tile&&e.onBridge===t.onBridge)>e});if(c.length)return this.path.splice(e,this.path.length,...c),r.moveTrait.currentWaypoint=void 0,r.moveTrait.moveState=qr.ReachedNextWaypoint,this.onTick(r)}}return r.moveTrait.collisionState=Zr.Waiting,r.moveTrait.velocity.set(0,0,0),!1}return r.moveTrait.velocity.set(0,0,0),r.moveTrait.collisionState=Zr.Waiting,!1}}}if(r.rules.speedType===ei.Track&&o){var p,g=this.path.indexOf(r.moveTrait.currentWaypoint);if(0<g){let t=this.path[g-1];for(p of i.getGroundObjectsOnTile(t.tile).filter(e=>e.isUnit()&&e.onBridge===!!t.onBridge&&e.rules.crushable&&e.veteranTrait?.hasVeteranAbility(li.SCATTER)&&!this.game.areFriendly(e,r)))p.unitOrderTrait.hasTasks()||p.unitOrderTrait.addTask(new Sa(this.game))}}r.moveTrait.reservedPathNodes.length||(r.moveTrait.reservedPathNodes.push(...t),t.forEach(e=>{i.tileOccupation.occupySingleTile(e.tile,r)}))}r.moveTrait.moveState=qr.Moving,this.inPlanningForTicks=void 0,this.unreachableTargets.length=0,this.pushTried=!1,r.moveTrait.collisionState===Zr.Waiting&&(r.moveTrait.collisionState=Zr.Resolved)}if(r.moveTrait.moveState===qr.Moving){let e=r.moveTrait.locomotor,{distance:t,done:i,isTeleport:s}=e.tick(r,this.currentWaypointLeptons,this.destinationLeptons,(this.isCancelling()||!this.path.length)&&!this.cancelRepositionPending);if(s&&r.traits.filter(Wr).forEach(e=>{e[Wr.onBeforeTeleport](r,this.game,!0,!0)}),t.length()){a=r.tile,g=e.allowOutOfBounds;if(t.y?(m=r.tileElevation,r.position.moveByLeptons3(t,g),r.moveTrait.handleElevationChange(m,this.game)):r.position.moveByLeptons(t.x,t.z,g),r.tile!==a){var m=r.onBridge?this.game.map.tileOccupation.getBridgeOnTile(a):void 0,g=function(t,i){for(let e=t.length-1;0<=e;e--)if(i(t[e],e,t))return t[e]}(this.path,e=>e.tile===r.tile),m=g?g.onBridge:m||r.moveTrait.currentWaypoint.onBridge?this.game.map.tileOccupation.getBridgeOnTile(r.tile):void 0;if(r.moveTrait.handleTileChange(a,m,!1,this.game,s),s&&(r.moveTrait.lastTeleportTick=this.game.currentTick,this.game.events.dispatch(new ba(r,!0,a))),r.isDestroyed)return!0}}if(i)return r.moveTrait.moveState=qr.ReachedNextWaypoint,this.onTick(r)}return!1}selectWeaponVsObstacle(e,t){let i;if(!this.game.areFriendly(t,e)&&e.attackTrait&&!e.attackTrait.isDisabled()&&e.attackTrait.isIdle()&&(i=e.attackTrait.selectWeaponVersus(e,t,this.game,!1,!0))&&i.name!==e.armedTrait?.deathWeapon?.name&&(!i.rules.limboLaunch||!i.warhead.rules.parasite)&&!i.warhead.rules.mindControl)return i}findRelocationTile(s,r,a){let n=this.game.map,i;if(a.rules.movementZone===ri.Fly){var t=e=>!n.tileOccupation.getGroundObjectsOnTile(e).some(e=>e.isBuilding()&&!e.isDestroyed||e.isTerrain()||e.isOverlay()&&e.rules.isARock);let e=new Ta(n.tiles,n.mapBounds,s,1,this.game,t);if(i=e.getNextTile(),!i){let e=new Us(n.tiles,n.mapBounds,s,a.getFoundation(),2,15,t);i=e.getNextTile()}}else{let e=new Xs(n),t=new Us(n.tiles,n.mapBounds,s,{width:1,height:1},0,5,t=>{let i=!r||r.isHighBridge()?n.tileOccupation.getBridgeOnTile(t):void 0;return!this.unreachableTargets.find(e=>e.tile===t&&e.toBridge===!!i)&&(a.zone===vs.Air||!n.terrain.findObstacles({tile:t,onBridge:i},a).length&&e.isEligibleTile(t,i,r,s))&&this.canStopAtTile(a,t,!!i)});i=t.getNextTile()}return i}findFreeSubCell(t,i){let e=this.game.map.getGroundObjectsOnTile(i.tile);var s=e.filter(e=>e.isInfantry()&&e.onBridge===!!i.onBridge&&e!==t).map(e=>e.position.desiredSubCell),r=e.filter(e=>e.isTerrain()).map(e=>e.rules.getOccupiedSubCells(this.game.map.getTheaterType())).flat();let a=[...s,...r];return Ra.SUB_CELLS.find(e=>-1===a.indexOf(e))}relocateToSubCell(e,t){e.position.desiredSubCell=t;t=e.position.computeSubCellOffset(t);this.targetOffset=t,this.currentWaypointLeptons.set(e.moveTrait.currentWaypoint.tile.rx,e.moveTrait.currentWaypoint.tile.ry).multiplyScalar(Os.LEPTONS_PER_TILE).add(this.targetOffset),this.updateDestination(this.path,this.targetOffset),e.moveTrait.locomotor.onWaypointUpdate?.(e,this.currentWaypointLeptons,this.destinationLeptons)}getTargetLinesConfig(e){var t;return this.path||((t=e.moveTrait).locomotor??(t.locomotor=new wa(this.game).create(e)),this.computePath(e,e.moveTrait.locomotor),this.targetLinesConfig.isRecalc=!1),this.targetLinesConfig}log(e,t){this.logger.debug(`<${e.id}>: ${t}`)}}(zr=zr||{}).onDestroy=Symbol(),(r=Vr=Vr||{})[r.None=0]="None",r[r.Normal=1]="Normal",r[r.Demolish=2]="Demolish",r[r.Crush=3]="Crush",r[r.Temporal=4]="Temporal",r[r.Sink=5]="Sink",(Hr=Hr||{}).onTileChange=Symbol(),(Gr=Gr||{}).onTileChange=Symbol();class Oa{constructor(e,t){this.target=e,this.source=t,this.type=ss.EnterTile}}($r=$r||{}).onElevationChange=Symbol(),(r=qr=qr||{})[r.Idle=0]="Idle",r[r.ReachedNextWaypoint=1]="ReachedNextWaypoint",r[r.PlanMove=2]="PlanMove",r[r.Moving=3]="Moving",(r=Xr=Xr||{})[r.Success=0]="Success",r[r.Cancel=1]="Cancel",r[r.CloseEnough=2]="CloseEnough",r[r.Fail=3]="Fail",(r=Zr=Zr||{})[r.Waiting=0]="Waiting",r[r.Resolved=1]="Resolved";const _a=e=>e instanceof ka||e.children[0]&&_a(e.children[0]);class Ia{constructor(e,t){this.gameObject=e,this.tileOccupation=t,this.disabled=!1,this.speedPenalty=0,this.velocity=new rs,this.reservedPathNodes=[],this.moveState=qr.Idle,this.collisionState=Zr.Resolved}get baseSpeed(){return this.gameObject.rules.speed*(this.gameObject.veteranTrait?.getVeteranSpeedMultiplier()??1)*this.gameObject.crateBonuses.speed*(this.gameObject.isVehicle()&&this.gameObject.healthTrait.health<=50&&this.gameObject.rules.locomotor!==si.Hover?.75:1)*(1-this.speedPenalty)}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}isMoving(){return this.moveState===qr.Moving}isIdle(){return this.moveState===qr.Idle}isWaiting(){return this.collisionState===Zr.Waiting}[Fr.onTick](e,t){var i;this.moveState!==qr.Idle&&this.collisionState===Zr.Resolved&&((i=e.unitOrderTrait.getCurrentTask())&&_a(i)||(this.velocity.set(0,0,0),this.moveState=qr.Idle,this.locomotor=void 0,!i&&!e.attackTrait?.currentTarget&&e.isVehicle()&&e.turretTrait&&(e.turretTrait.desiredFacing=e.direction))),this.moveState===qr.Idle&&(e.rules.locomotor===si.Jumpjet?Rr.tickStationary(e,t):e.isAircraft()&&e.rules.locomotor===si.Aircraft&&ya.tickStationary(e,t))}[zr.onDestroy](e,t){this.unreservePathNodes()}teleportUnitToTile(e,t,i,s,r){let a=this.gameObject;var n=a.tile;a.traits.filter(Wr).forEach(e=>{e[Wr.onBeforeTeleport](a,r,i,s)}),a.position.tileElevation=a.tileElevation,a.position.tile=e,a.position.subCell=a.position.desiredSubCell,this.handleTileChange(n,t,!0,r,!0),s||(this.unreservePathNodes(),this.speedPenalty=0,this.velocity.set(0,0,0),this.moveState=qr.Idle,this.collisionState=Zr.Resolved,this.locomotor=void 0,this.currentWaypoint=void 0,this.lastTargetOffset=void 0,this.lastVelocity=void 0,this.lastMoveResult=Xr.Cancel,a.isVehicle()&&(a.spinVelocity=0,a.turretTrait&&(a.turretTrait.desiredFacing=a.direction))),this.lastTeleportTick=r.currentTick,r.events.dispatch(new ba(a,i,n))}handleTileChange(t,e,i,s,r=!1){const a=this.gameObject;if(s.map.tileOccupation.unoccupyTileRange(t,a),s.map.tileOccupation.occupyTileRange(a.tile,a),s.map.technosByTile.updateObject(a),a.zone!==vs.Air){var n=a.onBridge?s.map.tileOccupation.getBridgeOnTile(t):void 0,o=a.onBridge?t.onBridgeLandType:t.landType,h=e?a.tile.onBridgeLandType:a.tile.landType;o!==h&&(0<s.rules.getLandRules(h).getSpeedModifier(a.rules.speedType)||a.rules.speedType===ei.Amphibious||r)&&(a.zone=_s(h)),e!==n&&(a.position.tileElevation+=-(n?.tileElevation??0)+(e?.tileElevation??0),a.onBridge=!!e);var l,e=a.moveTrait.reservedPathNodes.findIndex(e=>e.tile===a.tile&&!!e.onBridge===a.onBridge);if(-1!==e&&a.moveTrait.reservedPathNodes.splice(e,1),a.crusher)for(l of s.map.getGroundObjectsOnTile(a.tile).filter(e=>(!e.isUnit()||e.onBridge===a.onBridge)&&e.rules.crushable&&!(e.isInfantry()&&e.stance===Ls.Paradrop)&&(!(e.isTechno()&&!i)||!s.areFriendly(e,a))))l.isDestroyed||(l.isInfantry()&&(l.infDeathType=ti.None),a.isVehicle()&&l.isOverlay()&&l.rules.wall&&a.applyRocking(0,.5),l.deathType=Vr.Crush,s.destroyObject(l,{player:a.owner,obj:a}));a.onBridge||(e=s.map.tileOccupation.getGroundObjectsOnTile(a.tile).find(e=>e.isOverlay()&&e.rules.crate))&&s.crateGeneratorTrait.pickupCrate(a,e,s)}s.traits.filter(Hr).forEach(e=>{e[Hr.onTileChange](a,s,t,r)}),a.traits.filter(Gr).forEach(e=>{e[Gr.onTileChange](a,s,t,r)}),s.events.dispatch(new Oa(a.tile,a))}handleElevationChange(t,i){i.traits.filter($r).forEach(e=>{e[$r.onElevationChange](this.gameObject,i,t)})}unreservePathNodes(){this.reservedPathNodes.forEach(e=>{e.tile!==this.gameObject.tile&&this.tileOccupation.unoccupySingleTile(e.tile,this.gameObject)}),this.reservedPathNodes.length=0}dispose(){this.gameObject=void 0}}class Ca{constructor(){this.suppressionTicks=0,this.enabled=!0}disable(){this.enabled=!1}isSuppressed(){return this.enabled&&0<this.suppressionTicks}supress(){this.enabled&&(this.suppressionTicks=30)}[Fr.onTick](){0<this.suppressionTicks&&this.suppressionTicks--}}class Aa{constructor(){this.allTraits=[],this.traitsByTypeCache=new Map}add(e){this.allTraits.push(e),this.traitsByTypeCache.clear()}addToFront(e){this.allTraits.unshift(e),this.traitsByTypeCache.clear()}remove(e){e=this.allTraits.indexOf(e);-1!==e&&(this.allTraits.splice(e,1),this.traitsByTypeCache.clear())}filter(t){let e=this.traitsByTypeCache.get(t);return e||(e="function"==typeof t?this.allTraits.filter(e=>e instanceof t):this.allTraits.filter(e=>this.traitImplements(e,t)),this.traitsByTypeCache.set(t,e)),e}get(e){e=this.find(e);if(!e)throw new Error("No matching trait found");return e}find(e){return this.filter(e)[0]}getAll(){return this.allTraits}traitImplements(e,t){for(var i of Object.getOwnPropertyNames(t))if(void 0===e[t[i]])return!1;return!0}clear(){this.allTraits.length=0,this.traitsByTypeCache.clear()}dispose(){this.getAll().forEach(e=>e.dispose?.()),this.clear()}}(Qr=Qr||{}).onChange=Symbol(),(Yr=Yr||{}).onSpawn=Symbol(),(Kr=Kr||{}).onUnspawn=Symbol(),(Jr=Jr||{}).onAttack=Symbol();class Ba{constructor(e,t,i,s){this.traits=new Aa,this.cachedTraits={tick:[]},this.isCrashing=!1,this.isDestroyed=!1,this.deathType=Vr.Normal,this.isDisposed=!1,this.isSpawned=!1,this.type=e,this.name=t,this.rules=i,this.art=s}get tile(){return this.position.tile}get tileElevation(){return this.position.tileElevation}getFoundation(){return{width:1,height:1}}isSmudge(){return this.type===xt.Smudge}isOverlay(){return this.type===xt.Overlay}isTerrain(){return this.type===xt.Terrain}isProjectile(){return this.type===xt.Projectile}isDebris(){return this.type===xt.Debris}isBuilding(){return!1}isInfantry(){return!1}isVehicle(){return!1}isAircraft(){return!1}isUnit(){return!1}isTechno(){return!1}update(e){for(var t of this.cachedTraits.tick)t[Fr.onTick](this,e)}onSpawn(t){this.isSpawned=!0,this.traits.filter(Yr).forEach(e=>{e[Yr.onSpawn](this,t)})}onUnspawn(t){this.isSpawned=!1,this.traits.filter(Kr).forEach(e=>{e[Kr.onUnspawn](this,t)})}onDestroy(t,i,s){this.traits.filter(zr).forEach(e=>{e[zr.onDestroy](this,t,i,s)})}onOwnerChange(t,i){this.traits.filter(Qr).forEach(e=>{e[Qr.onChange](this,t,i)})}onAttack(t,i){this.traits.filter(Jr).forEach(e=>{e[Jr.onAttack](this,i,t)})}addTrait(e){this.traits.add(e),e[Fr.onTick]&&this.cachedTraits.tick.push(e)}getUiName(){return this.rules.uiName}getHash(){var e=this.position.worldPosition;return G([this.id,...new Uint8Array(new Float64Array([e.x,e.y,e.z]).buffer),...this.traits.getAll().map(e=>e.getHash?.()??0)])}debugGetState(){return{id:this.id,position:this.position.worldPosition.toArray(),traits:this.traits.getAll().reduce((e,t)=>{var i=t.debugGetState?.();return void 0!==i&&(e[t.constructor.name]=i),e},{})}}dispose(){this.isDisposed=!0,this.traits.dispose(),this.cachedTraits.tick.length=0}}(r=ea=ea||{})[r.None=0]="None",r[r.Veteran=1]="Veteran",r[r.Elite=2]="Elite";class xa extends Ba{constructor(e,t,i,s){super(e,t,i,s),this.explodes=this.rules.explodes,this.radarInvisible=this.rules.radarInvisible,this.c4=this.rules.c4,this.crusher=this.rules.crusher,this.defaultToGuardArea=this.rules.defaultToGuardArea,this.guardMode=this.rules.defaultToGuardArea,this.purchaseValue=this.rules.cost}get primaryWeapon(){return this.armedTrait?.primaryWeapon}get secondaryWeapon(){return this.armedTrait?.secondaryWeapon}get ammo(){return this.ammoTrait?.ammo}get sight(){return Math.min(os.MAX_SIGHT,this.rules.sight*(this.veteranTrait?.getVeteranSightMultiplier()??1))}get veteranLevel(){return this.veteranTrait?.veteranLevel??ea.None}resetGuardModeToIdle(){this.guardMode=this.defaultToGuardArea,this.guardArea=void 0}update(e){if(this.warpedOutTrait.isActive())for(var t of this.cachedTraits.tick)t.ticksWhenWarpedOut&&t[Fr.onTick](this,e);else super.update(e)}isTechno(){return!0}}class Ea{constructor(){this.cooldownTicks=Number.POSITIVE_INFINITY,this._actionDueThisTick=!1}[Fr.onTick](e,t){this._actionDueThisTick=!1;var i=!e.unitOrderTrait.hasTasks();i&&!this.idle?this.resetCooldown(t):i?0===this.cooldownTicks?(this.doIdleAction(e,t),this.resetCooldown(t)):this.cooldownTicks--:this.cooldownTicks=Number.POSITIVE_INFINITY,this.idle=i}doIdleAction(e,t){if(e.isInfantry()){if(e.rules.fraidycat)if(.5<t.generateRandom())return void e.unitOrderTrait.addTask(new Sa(t,void 0,{noSlopes:!0}));this._actionDueThisTick=!0}}actionDueThisTick(){return this._actionDueThisTick}resetCooldown(e){var t=e.rules.audioVisual.idleActionFrequency,e=e.generateRandom()*t*.5,e=Math.max(0,t-e);this.cooldownTicks=Math.floor(e*js.BASE_TICKS_PER_SECOND)}}class Pa{constructor(e){this.gameObject=e,this.type=ss.ObjectCrashing}}(ta=ta||{}).onCrash=Symbol();class Na{constructor(e){this.gameObject=e,this.crashingEvtSent=!1,this.crashState={}}[Fr.onTick](i,s){if(i.isCrashing){if(this.crashingEvtSent||(this.crashingEvtSent=!0,i.traits.filter(ta).forEach(e=>e[ta.onCrash](i,s)),s.events.dispatch(new Pa(i))),i.rules.locomotor!==si.Jumpjet&&i.rules.locomotor!==si.Aircraft)throw new Error(`Crashing logic not implemented for locomotor ${si[i.rules.locomotor]}`);{let e;if(i.rules.locomotor===si.Jumpjet)e=Rr.tickCrash(i,s,this.crashState);else{if(i.rules.locomotor!==si.Aircraft)throw new Error(`Unhandled locomotor type "${i.rules.locomotor}"`);if(!i.isAircraft())throw new Error(`Obj "${i.name}#${i.id} is not an aircraft`);e=ya.tickCrash(i,s,this.crashState)}let t=!1;var r,a,n=e.clone().add(i.position.worldPosition);s.map.isWithinHardBounds(n)?(a=i.tile,r=i.tileElevation,i.position.moveByLeptons3(e),i.tile!==a&&i.moveTrait.handleTileChange(a,void 0,!1,s),a=(n=i.tile.onBridgeLandType?s.map.tileOccupation.getBridgeOnTile(i.tile):void 0)?.tileElevation??0,i.position.tileElevation=Math.max(i.position.tileElevation,a),i.position.tileElevation===a&&(i.zone=s.map.getTileZone(i.tile),i.onBridge=!!n,t=!0),i.tileElevation!==r&&i.moveTrait.handleElevationChange(r,s)):t=!0,t&&s.destroyObject(i,this.attackerInfo)}}}crash(e){this.attackerInfo=e,this.gameObject.isCrashing=!0,this.gameObject.cachedTraits.tick.length=0,this.gameObject.cachedTraits.tick=[this]}dispose(){this.gameObject=void 0}}class Ma{infiltrate(e,t,i){var s;t.rules.radar&&![...t.owner.buildings].some(e=>e.rules.spySat)&&i.mapShroudTrait.resetShroud(t.owner,i),0<t.rules.power&&(s=i.rules.general.spyPowerBlackout,t.owner.powerTrait?.setBlackoutFor(s,i)),t.superWeaponTrait&&t.superWeaponTrait.getSuperWeapon(t)?.resetTimer(),0<t.rules.storage&&(s=z(i.rules.general.spyMoneyStealPercent,0,1),s=Math.floor(t.owner.credits*s),t.owner.credits-=s,e.owner.credits+=s),!i.rules.ai.buildTech.includes(t.name)||void 0!==(i=t.rules.aiBasePlanningSide)&&e.owner.production.addStolenTech(i),[es.InfantryType,es.UnitType].includes(t.factoryTrait?.type)&&e.owner.production?.addVeteranType(t.factoryTrait.type)}}class Da{constructor(){this.firepower=1,this.armor=1,this.speed=1}}class Ra extends xa{constructor(e,t,i){super(xt.Infantry,e,t,i),this.direction=0,this.onBridge=!1,this.zone=vs.Ground,this._stance=Ls.None,this.isFiring=!1,this.isPanicked=!1,this.infDeathType=ti.Gunfire,this.crateBonuses=new Da}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,s){let r=new this(e,t,i);return r.moveTrait=new Ia(r,s),r.traits.add(r.moveTrait),r.rules.crashable&&(r.crashableTrait=new Na(r),r.traits.add(r.crashableTrait)),r.rules.proneWhenAttacked&&(r.suppressionTrait=new Ca,r.traits.add(r.suppressionTrait)),r.rules.agent&&(r.agentTrait=new Ma,r.traits.add(r.agentTrait)),r.idleActionTrait=new Ea,r.traits.add(r.idleActionTrait),r}get stance(){return this._stance===Ls.None&&this.suppressionTrait?.isSuppressed()?Ls.Prone:this._stance}set stance(e){this._stance=e,this.moveTrait.setDisabled([Ls.Deployed,Ls.Cheer].includes(e)),this.attackTrait?.setDisabled([Ls.Paradrop,Ls.Cheer].includes(e))}isUnit(){return!0}isInfantry(){return!0}}Ra.SUB_CELLS=[2,4,3];class La extends Gs{constructor(e){super(),this.game=e}onTick(e){var t=Math.abs(this.game.rules.general.parachuteMaxFallRate),i=e.tile.onBridgeLandType?this.game.map.tileOccupation.getBridgeOnTile(e.tile).tileElevation:0,s=Os.tileHeightToWorld(i),r=e.tileElevation,a=Os.tileHeightToWorld(r);return s<Math.max(s,a-t)?(e.position.moveByLeptons3(new rs(0,-t,0)),e.moveTrait.handleElevationChange(r,this.game),!1):(e.position.tileElevation=i,e.stance=Ls.None,this.game.map.terrain.getPassableSpeed(e.tile,e.rules.speedType,e.onBridge)||(e.infDeathType=ti.None,this.game.destroyObject(e,void 0,!0)),!0)}}function Fa(i,s,r,a,n){let o=[];n=n||((e,t)=>{o.push({x:e,y:t})});var e=r-i,t=a-s,h=Math.abs(e),l=Math.abs(t);let c=0;var u=0<e?1:-1,d=0<t?1:-1;if(l<h)for(let e=i,t=s;u<0?e>=r:e<=r;e+=u)n(e,t),c+=l,c<<1>=h&&(t+=d,c-=h);else for(let e=i,t=s;d<0?t>=a:t<=a;t+=d)n(e,t),c+=h,c<<1>=l&&(e+=u,c-=l);return o}function ja(e){return null!=e}class Ua extends Gs{constructor(...e){super(),this.children.push(...e)}onTick(e){return!0}}class Wa{constructor(){this.enabled=!0}setEnabled(e){this.enabled=e}[Fr.onTick](e,t){var i;this.enabled&&(e.owner.isNeutral||e.name===t.rules.general.paradrop.paradropPlane)&&e.unitOrderTrait.isIdle()&&(i=this.chooseExitTile(e.tile,t),e.unitOrderTrait.addTask(new Ua(new ka(t,i,!1,{allowOutOfBoundsTarget:!0}),new ma(e=>t.unspawnObject(e))).setCancellable(!1)))}chooseExitTile(e,t){var i=t.map.tiles.getMapSize(),i=.5<t.generateRandom()?new ks(Math.floor(i.width/2),0):new ks(0,Math.floor(i.height/2)),e=new ks(e.rx,e.ry),i=Fa(e.x,e.y,i.x,i.y).map(e=>t.map.tiles.getByMapCoords(e.x,e.y)).filter(ja);if(!i.length)throw new Error("No valid exit tile found");return i[i.length-1]}}(r=ia=ia||{})[r.Spawning=0]="Spawning",r[r.EnRoute=1]="EnRoute",r[r.Dropping=2]="Dropping",r[r.TurningAround=3]="TurningAround";const za=5*js.BASE_TICKS_PER_SECOND;class Va extends Vs{constructor(e,t,i,s,r){super(e,t,i),this.paradropSquad=s,this.state=ia.Spawning,this.failedAttempts=0,this.spawnDelay=r*za}onStart(e){this.passengerRules=e.rules.getObject(this.paradropSquad.inf,xt.Infantry),this.passengerCount=this.paradropSquad.num}computeFlightPath(e,t,i){if(t.equals(e))throw new Error("Source and destination must be different");let s=e.clone().sub(t);e=i.rules.general.paradrop.paradropRadius/Os.LEPTONS_PER_TILE,e=t.clone().add(s.clone().setLength(s.length()+2*e)).floor();let r=Fa(t.x,t.y,e.x,e.y).map(e=>i.map.tiles.getByMapCoords(e.x,e.y)??i.map.tiles.getPlaceholderTile(e.x,e.y));for(;r.length;){var a=r[0],a=Os.tileToWorld(a.rx+.5,a.ry+.5);if(i.map.isWithinHardBounds(new ks(a.x,a.y)))break;r.shift()}if(!r.length)throw new Error("No valid paradrop path found");return{fromTile:r[0],toTile:r[r.length-1]}}onTick(r){if(this.state===ia.Spawning){if(0<this.spawnDelay)return this.spawnDelay--,!1;var a=r.map.tiles.getMapSize(),n=[new ks(0,0),new ks(Math.floor(a.width/2),0),new ks(0,Math.floor(a.height/2))][r.generateRandomInt(0,2)];let t=this.passengerRules.speedType,e=new Us(r.map.tiles,r.map.mapBounds,this.tile,{width:1,height:1},0,50,e=>0<r.map.terrain.getPassableSpeed(e,t,!!e.onBridgeLandType));var o=this.targetTile=e.getNextTile();if(!o)return!0;let i=new ks(o.rx,o.ry);var{fromTile:h,toTile:a}=this.computeFlightPath(i,n,r),o=r.rules.general.paradrop.paradropPlane,n=r.rules.getObject(o,xt.Aircraft);let s=this.pdPlane=r.createUnitForPlayer(n,this.owner);r.spawnObject(s,h),s.direction=br.fromMapCoords(i.clone().sub(new ks(h.rx,h.ry))),s.position.tileElevation=Os.worldToTileHeight(s.rules.flightLevel??r.rules.general.flightLevel),s.zone=vs.Air,s.onBridge=!1,s.unitOrderTrait.addTask(new ka(r,a,!1,{allowOutOfBoundsTarget:!0})),s.traits.get(Wa).setEnabled(!1),this.state=ia.EnRoute}if(!this.pdPlane||this.pdPlane.isDestroyed||this.pdPlane.isCrashing)return!0;o=this.targetTile;if(!this.pdPlane.unitOrderTrait.hasTasks())return this.state=ia.TurningAround,this.pdPlane.unitOrderTrait.addTask(new ka(r,o,!1,{allowOutOfBoundsTarget:!0})),!1;n=r.rules.general.paradrop.paradropRadius/Os.LEPTONS_PER_TILE;let e=new As(r.map.tileOccupation);h=e.isInTileRange(this.pdPlane.tile,o,0,n);if(this.state===ia.EnRoute&&h&&(this.state=ia.Dropping),this.state===ia.Dropping)if(h&&0<this.passengerCount){a=this.pdPlane.tile;let t=!!a.onBridgeLandType;if(!r.map.terrain.getPassableSpeed(a,this.passengerRules.speedType,t))return!1;let e=r.map.getGroundObjectsOnTile(a);if(e.some(e=>e.isVehicle()&&e.onBridge===t||e.isBuilding()&&!e.isDestroyed||e.isInfantry()&&e.stance===Ls.Paradrop))return!1;n=this.findFreeSubCell(r,a);if(!n)return!1;this.passengerCount--;let i=r.createUnitForPlayer(this.passengerRules,this.owner);i.stance=Ls.Paradrop,i.position.tileElevation=this.pdPlane.tileElevation,i.position.subCell=n,i.onBridge=t,i.rules.trainable&&this.owner.canProduceVeteran(i.rules)&&i.veteranTrait?.setVeteranLevel(ea.Veteran),r.spawnObject(i,a),i.unitOrderTrait.addTask(new La(r).setCancellable(!1))}else{if(!(0<this.passengerCount))return this.pdPlane.unitOrderTrait.getCurrentTask().forceCancel(this.pdPlane),this.pdPlane.traits.get(Wa).setEnabled(!0),!0;if(this.failedAttempts++,5<this.failedAttempts)return this.passengerCount=0,!1;this.state=ia.TurningAround,this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!!o.onBridgeLandType)}return this.state===ia.TurningAround&&h&&(o=this.computeFlightPath(new ks(o.rx,o.ry),new ks(this.pdPlane.tile.rx,this.pdPlane.tile.ry),r)["toTile"],this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!1),this.state=ia.EnRoute),!1}findFreeSubCell(t,e){let i=t.map.getGroundObjectsOnTile(e).filter(e=>e.isTerrain()).map(e=>e.rules.getOccupiedSubCells(t.map.getTheaterType())).flat();e=Ra.SUB_CELLS.filter(e=>-1===i.indexOf(e));if(e.length)return 1<e.length?e[t.generateRandomInt(0,e.length-1)]:e[0]}}(r=sa=sa||{})[r.NotBridge=0]="NotBridge",r[r.Concrete=1]="Concrete",r[r.Wood=2]="Wood";class Ha{static getOverlayBridgeType(e){return V(e,this.minHighBridgeConcreteId,this.maxHighBridgeConcreteId)||V(e,this.minLowBridgeConcreteId,this.maxLowBridgeConcreteId)?sa.Concrete:V(e,this.minHighBridgeWoodId,this.maxHighBridgeWoodId)||V(e,this.minLowBridgeWoodId,this.maxLowBridgeWoodId)?sa.Wood:sa.NotBridge}static isBridge(e){return this.isHighBridge(e)||this.isLowBridge(e)}static isBridgePlaceholder(e){return this.bridgePlaceholderIds.includes(e)}static isHighBridge(e){return V(e,this.minHighBridgeWoodId,this.maxHighBridgeWoodId)||V(e,this.minHighBridgeConcreteId,this.maxHighBridgeConcreteId)}static isLowBridge(e){return V(e,this.minLowBridgeWoodId,this.maxLowBridgeWoodId)||V(e,this.minLowBridgeConcreteId,this.maxLowBridgeConcreteId)}static isXBridge(e){return e===this.minHighBridgeWoodId||e===this.minHighBridgeConcreteId||V(e,this.minLowBridgeWoodId,this.minLowBridgeWoodId+8)||V(e,this.minLowBridgeWoodId+18,this.minLowBridgeWoodId+21)||V(e,this.minLowBridgeConcreteId,this.minLowBridgeConcreteId+8)||V(e,this.minLowBridgeConcreteId+18,this.minLowBridgeConcreteId+21)}static isLowBridgeHead(e){return V(e,this.minLowBridgeWoodId+18,this.minLowBridgeWoodId+25)||V(e,this.minLowBridgeConcreteId+18,this.minLowBridgeConcreteId+25)}static isLowBridgeHeadStart(e){return V(e,this.minLowBridgeWoodId+20,this.minLowBridgeWoodId+23)||V(e,this.minLowBridgeConcreteId+20,this.minLowBridgeConcreteId+23)}static calculateLowBridgeOverlayId(e,t){let i;if(e===sa.Concrete)i=this.minLowBridgeConcreteId;else{if(e!==sa.Wood)throw new Error("Not implemented");i=this.minLowBridgeWoodId}return i+(t?0:9)}static calculateHighBridgeOverlayId(e,t){let i;if(e===sa.Concrete)i=this.minHighBridgeConcreteId;else{if(e!==sa.Wood)throw new Error("Not implemented");i=this.minHighBridgeWoodId}return i+(t?0:1)}}Ha.minLowBridgeWoodId=74,Ha.maxLowBridgeWoodId=99,Ha.minLowBridgeConcreteId=205,Ha.maxLowBridgeConcreteId=230,Ha.minHighBridgeConcreteId=24,Ha.maxHighBridgeConcreteId=25,Ha.minHighBridgeWoodId=237,Ha.maxHighBridgeWoodId=238,Ha.bridgePlaceholderIds=[100,101,231,232],(ra=ra||{}).onAttack=Symbol(),(r=aa=aa||{})[r.None=0]="None",r[r.Ground=1]="Ground",r[r.Wall=2]="Wall",r[r.Cliff=3]="Cliff",r[r.OnBridge=4]="OnBridge",r[r.UnderBridge=5]="UnderBridge",r[r.Shore=6]="Shore";class Ga{constructor(e,t,i,s){this.target=e,this.position=t,this.explodeAnim=i,this.isLightningStrike=s,this.type=ss.WarheadDetonate}}(r=na=na||{})[r.Top=0]="Top",r[r.TopLeft=1]="TopLeft",r[r.TopRight=2]="TopRight",r[r.Left=3]="Left",r[r.Right=4]="Right",r[r.BottomLeft=5]="BottomLeft",r[r.Bottom=6]="Bottom",r[r.BottomRight=7]="BottomRight";class $a{constructor(i,s,e,r){this.tileSets=s,this.generalRules=e;let a=this.rSize={width:0,height:0},n=this.dSize={width:0,height:0};for(let e=0,t=i.length;e<t;++e)a.width=Math.max(a.width,i[e].rx),a.height=Math.max(a.height,i[e].ry),n.width=Math.max(n.width,i[e].dx),n.height=Math.max(n.height,i[e].dy);a.width++,a.height++,n.width++,n.height++;let o=this.tilesByRxy=new Array(a.width*a.height);o.fill(void 0);let h=this.tilesByDxy=new Array(n.width*n.height);h.fill(void 0);let l=this.tiles=new Array(i.length),c=[],u=this.bridgeSetTiles=[],d=new Set(Object.values(Kt));this.minTileHeight=Number.POSITIVE_INFINITY;for(let e=this.maxTileHeight=0,t=i.length;e<t;++e){var p=i[e],g=s.getTileImage(p.tileNum,p.subTile,r),m=g.terrainType;if(!d.has(m))throw new Error(`Tile (${p.rx}, ${p.ry}) has unknown terrain type "${m}"`);var f={...p,terrainType:m,landType:Gi(m),onBridgeLandType:void 0,rampType:g.rampType,id:p.rx+"_"+p.ry,occluded:!1},y=f.rx,w=f.ry,T=f.dx,m=f.dy;l[e]=f,o[y+w*a.width]=f,h[T+m*n.width]=f,this.minTileHeight=Math.min(this.minTileHeight,f.z),this.maxTileHeight=Math.max(this.maxTileHeight,f.z),4!==g.height||f.terrainType!==Kt.Cliff&&!s.isCliffTile(f.tileNum)||c.push(f),s.isHighBridgeBoundaryTile(p.tileNum)&&u.push(f)}this.computeLandBehindCliffTiles(c),this.cutoffTileHeight=this.computeCutoffTileHeight()}computeLandBehindCliffTiles(t){if(!(this.generalRules.cliffBackImpassability<2)){let e=[[-2,-2],[-1,-1],[-1,1],[1,-1],[0,1],[1,0]];t.forEach(t=>{for(var[i,s]of e){let e=this.getByMapCoords(t.rx+i,t.ry+s);e&&e.z<t.z&&e.terrainType!==Kt.Cliff&&e.terrainType!==Kt.Rough&&0===e.rampType&&(e.landType=Jt.Rock)}})}}getTileRadarColor(e){let t=this.tileSets.getTileImage(e.tileNum,e.subTile,()=>0);return t.radarLeft.clone().multiplyScalar(.5)}getAll(){return[...this.tiles]}forEach(i){for(let e=0,t=this.tiles.length;e<t;++e)i(this.tiles[e],e)}reduce(t,e){let i=e;return this.forEach(e=>{i=t(i,e)}),i}getMinTileHeight(){return this.minTileHeight}getMaxTileHeight(){return this.maxTileHeight}getCutoffTileHeight(){return this.cutoffTileHeight}computeCutoffTileHeight(){var t=this.dSize.width-1;let i=this.dSize.height-1,s=0,r=!0;for(;r&&0<i;){for(let e=1;e<t-3;e++){var a=this.getByDisplayCoords(e,i);a&&(r=!1,a.z>s&&(s=a.z))}r&&i--}return s}getAllBridgeSetTiles(){return this.bridgeSetTiles}getAllNeighbourTiles(e){var t=e.rx,e=e.ry;return[this.getByMapCoords(t+1,e+1),this.getByMapCoords(t-1,e-1),this.getByMapCoords(t-1,e+1),this.getByMapCoords(t+1,e-1),this.getByMapCoords(t,e+1),this.getByMapCoords(t+1,e),this.getByMapCoords(t-1,e),this.getByMapCoords(t,e-1)].filter(ja)}getNeighbourTile(e,t){var i=e.rx,s=e.ry;switch(t){case na.Bottom:return this.getByMapCoords(i+1,s+1);case na.Top:return this.getByMapCoords(i-1,s-1);case na.Left:return this.getByMapCoords(i-1,s+1);case na.Right:return this.getByMapCoords(i+1,s-1);case na.BottomLeft:return this.getByMapCoords(i,s+1);case na.BottomRight:return this.getByMapCoords(i+1,s);case na.TopLeft:return this.getByMapCoords(i-1,s);case na.TopRight:return this.getByMapCoords(i,s-1);default:throw new Error("Invalid direction")}}getByDisplayCoords(e,t){if(!(e>=this.dSize.width||t>=this.dSize.height))return this.tilesByDxy[e+t*this.dSize.width]}getByMapCoords(e,t){if(!(e>=this.rSize.width||t>=this.rSize.height))return this.tilesByRxy[e+t*this.rSize.width]}getMapSize(){return this.rSize}getDisplaySize(){return this.dSize}getInRectangle(e,t){let i,s,r,a;a=t?(i=e.rx,s=e.ry,r=t.width,t.height):(i=e.x,s=e.y,r=e.width,e.height);let n=[];for(let t=0;t<r;t++)for(let e=0;e<a;e++){var o=i+t,h=s+e,h=this.getByMapCoords(o,h);h&&n.push(h)}return n}getPlaceholderTile(e,t){var i=this.tiles[0],i=i.dx-i.rx+i.ry+1;return{rx:e,ry:t,dx:e-t+i-1,dy:e+t-i-1,z:0,id:`${e}_${t}`,landType:Jt.Rock,terrainType:Kt.Rock1,rampType:0,subTile:0,tileNum:0,occluded:!1,onBridgeLandType:void 0}}}(r=oa=oa||{})[r.NotSpecial=0]="NotSpecial",r[r.Riparius=1]="Riparius",r[r.Cruentus=2]="Cruentus",r[r.Vinifera=4]="Vinifera",r[r.Aboreus=8]="Aboreus",r[r.Ore=1]="Ore",r[r.Gems=2]="Gems",r[r.All=15]="All";class qa{static getOverlayTibType(e){return this.isRiparius(e)?oa.Riparius:this.isCruentus(e)?oa.Cruentus:this.isVinifera(e)?oa.Vinifera:this.isAboreus(e)?oa.Aboreus:oa.NotSpecial}static isRiparius(e){return e>=this.minIdRiparius&&e<=this.maxIdRiparius}static isCruentus(e){return e>=this.minIdCruentus&&e<=this.maxIdCruentus}static isVinifera(e){return e>=this.minIdVinifera&&e<=this.maxIdVinifera}static isAboreus(e){return e>=this.minIdAboreus&&e<=this.maxIdAboreus}}qa.minIdRiparius=102,qa.maxIdRiparius=127,qa.minIdCruentus=27,qa.maxIdCruentus=38,qa.minIdVinifera=127,qa.maxIdVinifera=146,qa.minIdAboreus=147,qa.maxIdAboreus=166,(r=ha=ha||{})[r.Riparius=0]="Riparius",r[r.Cruentus=1]="Cruentus",r[r.Vinifera=2]="Vinifera",r[r.Aboreus=3]="Aboreus",r[r.Ore=0]="Ore",r[r.Gems=1]="Gems";class Xa{constructor(e){this.gameObject=e}static canBePlacedOn(e,t){return[Jt.Clear,Jt.Road,Jt.Rough].includes(e.landType)&&!t.getGroundObjectsOnTile(e).find(e=>!e.isSmudge()&&!e.isUnit())}getTiberiumType(){var e=qa.getOverlayTibType(this.gameObject.overlayId);switch(e){case oa.Ore:return ha.Ore;case oa.Gems:return ha.Gems;case oa.Vinifera:return ha.Ore;default:throw new Error(`Unsupported tiberium type ${e}`)}}collectBail(){var e=this.getBailCount();if(e<=0)throw new Error("Attempted to collect an ore bail, but there are none left");return this.gameObject.value--,1<e?this.getTiberiumType():void 0}spawnBails(e){this.gameObject.value=Math.min(Xa.maxBails,this.gameObject.value+e)}removeBails(e){this.gameObject.value=Math.max(-1,this.gameObject.value-e)}getBailCount(){return this.gameObject.value+1}dispose(){this.gameObject=void 0}}Xa.maxBails=11;class Za{destroyOre(i,s,r){if(s.landType===Jt.Tiberium&&(r.art.hasObject(i,xt.Animation)?r.art.getAnimation(i):void 0)?.crater){let t=r.map.getObjectsOnTile(s).find(e=>e.isOverlay()&&e.isTiberium());if(t){s=Math.ceil(Xa.maxBails/2),s=i.startsWith("S_CLSN")?s:r.generateRandomInt(1,s);let e=t.traits.get(Xa);e.removeBails(s),e.getBailCount()||r.unspawnObject(t)}}}spawnSmudges(e,r,a){if(r.landType===Jt.Clear&&0===r.rampType&&a.map.mapBounds.isWithinBounds(r)&&!a.map.getObjectsOnTile(r).find(e=>!e.isUnit())){e=a.art.hasObject(e,xt.Animation)?a.art.getAnimation(e):void 0;if(e?.crater){let t=e?.forceBigCraters?2:1,i=e?.scorch,s=[na.Bottom,na.BottomLeft,na.BottomRight].every(e=>a.map.tiles.getNeighbourTile(r,e));e=[...a.rules.smudgeRules.values()].filter(e=>(e.crater&&e.width===t&&e.height===t||i&&e.burn)&&!((1<e.width||1<e.height)&&!s));e.length&&(e=e[a.generateRandomInt(0,e.length-1)].name,e=a.createObject(xt.Smudge,e),a.spawnObject(e,r))}}}}class Qa{constructor(e,t,i){this.target=e,this.attacker=t,this.incidental=i,this.type=ss.ObjectAttacked}}class Ya{constructor(e){this.rules=e}canDamage(e,t,i){return!(!e.isSpawned||e.isDisposed||e.isDestroyed||e.isCrashing)&&(!(e.isTechno()&&e.warpedOutTrait.isInvulnerable()&&!this.rules.temporal)&&((!e.isUnit()||!e.moveTrait.reservedPathNodes.find(e=>e.tile===t))&&(!!e.healthTrait&&((!e.isUnit()||e.zone!==vs.Air||i===vs.Air)&&(!(!e.isUnit()&&i===vs.Air)&&((!e.isBuilding()||!e.rules.invisibleInGame)&&(!((e.isTechno()||e.isTerrain())&&e.rules.immune&&!this.rules.temporal)&&(!(e.isTechno()&&!e.rules.warpable&&this.rules.temporal)&&(!(this.rules.radiation&&(!e.isUnit()||e.rules.immuneToRadiation))&&(!(this.rules.psychicDamage&&(!e.isUnit()||e.rules.immuneToPsionics))&&(!e.isOverlay()||!Ha.isLowBridgeHead(e.overlayId))))))))))))}computeDamage(t,i,s=!1){let r=t;if(0<t&&i.isTechno()&&i.invulnerableTrait.isActive())return 0;if(i.isAircraft()&&i.missileSpawnTrait&&i.zone!==vs.Air)return 0;if(this.rules.radiation||this.rules.temporal||!i.isInfantry()||i.stance!==Ls.Prone||(r*=this.rules.proneDamage),i.isTechno()||i.isOverlay()||i.isTerrain()){let e=i.isTerrain()?ai.Wood:i.rules.armor;i.isOverlay()&&i.isBridge()&&((t=Ha.getOverlayBridgeType(i.overlayId))===sa.Wood?e=ai.Wood:t===sa.Concrete&&(e=ai.Concrete)),s&&i.isOverlay()&&(i.isBridge()||i.rules.wall)||(r*=this.rules.verses.get(e)),0<r&&i.isTechno()&&i.veteranTrait&&(r/=i.veteranTrait.getVeteranArmorMultiplier()),0<r&&i.isUnit()&&(r/=i.crateBonuses.armor)}return(i.isOverlay()||i.isBuilding())&&i.rules.wall&&(this.rules.wallAbsoluteDestroyer?r=Number.POSITIVE_INFINITY:this.rules.wall||this.rules.wood&&i.rules.armor===ai.Wood||(r=0)),i.isOverlay()&&i.isBridge()&&(this.rules.wall||(r=0)),r=0<r?Math.floor(r):Math.ceil(r),r}inflictDamage(e,t,i,s,r=!1){let a=t.healthTrait;return e===Number.POSITIVE_INFINITY&&(e=a.getHitPoints()),a.inflictDamage(e,i,s),s.traits.filter(ra).forEach(e=>{e[ra.onAttack](t,i?.obj,s)}),t.onAttack(s,i),s.events.dispatch(new Qa(t,i,r)),t.isTechno()&&!this.rules.temporal&&this.supressOrScatterTarget(t,s),!a.health&&(t.isInfantry()&&(t.infDeathType=this.rules.infDeath),this.rules.temporal&&(t.deathType=Vr.Temporal),t.isUnit()&&t.crashableTrait&&t.zone===vs.Air&&!this.rules.temporal?t.crashableTrait.crash(i):s.destroyObject(t,i,void 0,r),!0)}supressOrScatterTarget(e,t){e.rules.fraidycat||e.isVehicle()&&!e.owner.isCombatant()&&e.rules.insignificant?e.unitOrderTrait.hasTasks()||(e.isInfantry()&&(e.isPanicked=!0),e.unitOrderTrait.addTask(new Sa(t)),e.isInfantry()&&e.unitOrderTrait.addTask(new ma(()=>e.isPanicked=!1).setCancellable(!1))):e.isInfantry()&&e.suppressionTrait?.supress()}createDummyWeaponInfo(){return{minRange:0,range:0,speed:Number.POSITIVE_INFINITY,type:hi.Primary,rules:new Ai(new h("Dummy")),projectileRules:new Xi(xt.Projectile,new h("Dummy")),warhead:this}}detonate(i,e,t,s,r,a,n,o,h,l,c,u,d,p=!1){var g,m,f,y=h?.weapon??this.createDummyWeaponInfo(),w=h?.obj,T=h?.player,b=d?d/Os.LEPTONS_PER_TILE:this.rules.cellSpread,v=this.rules.percentAtMax;let S=new Set,k=new Map,O=new As(i.map.tileOccupation),_=new Us(i.map.tiles,i.map.mapBounds,t,{width:1,height:1},0,Math.ceil(b),()=>!0);for(;g=_.getNextTile();)for(m of i.map.getObjectsOnTile(g))if((!S.has(m)||m.isBuilding())&&(n!==aa.UnderBridge||!m.isUnit()||!m.onBridge)&&!(w&&m.isTechno()&&m.rules.typeImmune&&m.owner===T&&m.name===w.name)&&this.canDamage(m,g,a)&&(!m.isOverlay()||!(!n&&.1<Math.abs(m.tileElevation-s)||n===aa.OnBridge&&!m.isBridge()))){let e=m.isBuilding()?g===t?0:O.distance3(g,r)/Os.LEPTONS_PER_TILE:m.isTerrain()||m.isOverlay()?O.distance3(g,t)/Os.LEPTONS_PER_TILE:O.distance3(m,r)/Os.LEPTONS_PER_TILE;if(e<.001&&(e=0),!(l&&m.isInfantry()&&T)||m.owner!==T&&!i.alliances.areAllied(m.owner,T)){if(!b)if(m.isTerrain()){if(g!==t||!this.rules.wall)continue}else if(!l&&(g!==t||!m.isBuilding()&&m!==(o.obj||o.getBridge())))continue;b&&e>b||(S.add(m),k.set(m,m.isBuilding()?(k.get(m)||[]).concat(e):[e]))}}let I=!1,C;for(f of S)if(!f.isDestroyed&&!f.isCrashing){var A,B,x=this.computeDamage(e,f,c);if(x)for(var E of k.get(f)){let t=x;if(0<b&&Number.isFinite(t)&&(t=H(t,v*t,E/b)),Math.abs(t)<1&&(!b||.25<=t/x)&&(t=+Math.sign(t)),t=0<t?Math.floor(t):Math.ceil(t),t){let e=f.healthTrait;if(t<0){if(!w)throw new Error("Expected healer object to be set");if(e.healBy(-t,w,i),100===e.health)break}else{if(f===o.obj&&E<1&&(C=f),this.rules.causesDelayKill&&f.isBuilding()&&f.delayedKillTrait&&(A=f.healthTrait.getHitPoints(),t>=A&&(t=A-1,f.delayedKillTrait.isActive()||(A=this.rules.delayKillAtMax,B=H(B=this.rules.delayKillFrames,A*B,E/b),f.delayedKillTrait.activate(B,h)))),this.inflictDamage(t,f,h,i,!C))break;f.isVehicle()&&this.rules.rocker&&(0<(E=z(x/300,0,1))&&(B=br.fromMapCoords(f.position.getMapPosition().clone().sub(Os.vecWorldToGround(r)))-f.direction,f.applyRocking(B,E)))}}}else f.isTechno()&&f.invulnerableTrait.isActive()&&(I=!0)}y=y.rules.radLevel;y&&b&&i.mapRadiationTrait.createRadSite(t,y,b+1);p=p?void 0:I?i.rules.audioVisual.weaponNullifyAnim:this.pickExplodeAnim(e,C,a,i,c);if(!I&&a===vs.Ground){let e=new Za;p&&e.destroyOre(p,t,i),u&&e.spawnSmudges(u,t,i),p&&e.spawnSmudges(p,t,i)}i.events.dispatch(new Ga(this,r,p,c))}pickExplodeAnim(t,i,s,r,a){if(t){if(a)return r.rules.audioVisual.weatherConBoltExplosion;if(this.rules.conventional&&s===vs.Water&&(!i||i.isBuilding()||i.isVehicle()&&i.submergibleTrait)){var n=r.rules.combatDamage.splashList;return n[z(Math.floor(t/50),0,n.length-1)]}n=this.rules.animList.length;let e;return n?(e=r.rules.combatDamage.c4Warhead===this.rules.name?n-1:this.rules.emEffect?r.generateRandomInt(0,n-1):z(Math.floor(t/25),0,n-1),this.rules.animList[e]):void 0}}}Ya.SPECIAL_WARHEAD_NAME="Special",Ya.HE_WARHEAD_NAME="HE";class Ka{constructor(e){this.forward=0,this.lateral=0,this.vertical=0,e&&3===e.length&&this.fromArray(e)}fromArray(e){return this.forward=e[0],this.lateral=e[1],this.vertical=e[2],this}clone(){return new Ka([this.forward,this.lateral,this.vertical])}}class Ja{constructor(e,t){this.weapon=e,this.gameObject=t,this.type=ss.WeaponFire}}class en{constructor(e,t,i,s,r,a){this.weaponType=e,this.projectileRules=t,this.weaponRules=i,this.warheadRules=s,this.gameObject=r,this.generalRules=a,this.targetChecks=[],this.initConditions()}initConditions(){this.projectileRules.isAntiGround||this.targetChecks.push(e=>!!e);const a=this.generalRules.prism.type;this.gameObject.name===a&&this.weaponType===hi.Secondary?this.targetChecks.push((e,t,i,s,r)=>!(!r||!e?.isBuilding()||e.name!==a||e.owner!==this.gameObject.owner)):this.warheadRules.electricAssault?this.targetChecks.push((e,t,i,s,r)=>!(!s&&!r||!e?.isBuilding()||!e.overpoweredTrait||e.owner!==this.gameObject.owner)):this.weaponRules.damage<0?this.targetChecks.push((e,t,i)=>!!(e!==this.gameObject&&e?.isUnit()&&i.areFriendly(e,this.gameObject)&&e.healthTrait.health<100&&this.gameObject.isAircraft()===e.isAircraft())):(this.gameObject.rules.attackCursorOnFriendlies||this.warheadRules.bombDisarm?this.targetChecks.push((e,t,i,s,r)=>!r&&!!(!this.warheadRules.bombDisarm||e?.isTechno()&&e.tntChargeTrait?.hasCharge())):this.targetChecks.push((e,t,i,s)=>!((!s||this.warheadRules.mindControl)&&e?.isTechno()&&i.areFriendly(e,this.gameObject))),this.targetChecks.push((e,t,i)=>!(e?.isTechno()&&e.cloakableTrait?.isCloaked()&&!i.alliances.haveSharedIntel(this.gameObject.owner,e.owner))),this.weaponRules.limboLaunch&&this.targetChecks.push((e,t,i,s,r)=>!(r&&e&&(e.isVehicle()||e.isAircraft())&&e.parasiteableTrait?.isInfested())),this.gameObject.rules.ivan&&this.targetChecks.push(e=>!(!e?.isTechno()||!e.tntChargeTrait||e.tntChargeTrait.hasCharge())),this.warheadRules.parasite&&this.targetChecks.push((e,t,i,s)=>!!(!e&&s||e?.isInfantry()||(e?.isVehicle()||e?.isAircraft())&&e.parasiteableTrait)),this.warheadRules.mindControl&&this.targetChecks.push(e=>!(!e?.isTechno()||!e.mindControllableTrait)),this.warheadRules.temporal||this.targetChecks.push((e,t,i,s,r)=>!(r&&e?.isTechno()&&e.warpedOutTrait.isInvulnerable()))),this.targetChecks.push((e,t)=>this.canTargetZone(e,t))}canTarget(t,i,s,r,a){return this.targetChecks.every(e=>e(t,i,s,r,a))}canTargetZone(e,t){let i;if(e?.isUnit()){if(e?.isInfantry()&&e.stance===Ls.Paradrop)return this.projectileRules.isAntiAir&&(this.projectileRules.isAntiGround||this.weaponType===hi.Secondary);if(e.zone===vs.Air)return this.projectileRules.isAntiAir;if(this.weaponType===hi.Secondary&&this.projectileRules.isAntiAir&&!this.projectileRules.isAntiGround)return!1;i=e.zone}else i=t.landType===Jt.Water?vs.Water:vs.Ground;return i===vs.Water?this.canTargetNaval(this.gameObject.rules.navalTargeting,this.gameObject,e,this.weaponType):this.canTargetLand(this.gameObject.rules.landTargeting,this.weaponType)}canTargetLand(e,t){switch(e){case ni.LandOk:return!0;case ni.LandNotOk:return!1;case ni.LandSecondary:return t===hi.Secondary;default:throw new Error(`Unhandled LandTargeting value "${e}"`)}}canTargetNaval(e,t,i,s){switch(e){case oi.UnderwaterNever:return!i||!(i.isVehicle()&&i.submergibleTrait?.isSubmerged());case oi.UnderwaterSecondary:return i&&i.isVehicle()&&i.submergibleTrait&&!t.rules.spawned?s===hi.Secondary:s===hi.Primary;case oi.UnderwaterOnly:return!!(i&&i.isVehicle()&&i.submergibleTrait);case oi.OrganicSecondary:return i?.isTechno()&&i.rules.organic?s===hi.Secondary:s===hi.Primary;case oi.SealSpecial:return i?.isTechno()&&i.rules.naval&&!i.rules.organic&&(i.isBuilding()||i.rules.speedType===ei.Float)?s===hi.Secondary:s===hi.Primary;case oi.NavalAll:return!0;case oi.NavalNone:return!1;default:throw new Error(`Unhandled NavalTargeting value "${e}"`)}}}class tn{constructor(e,t,i,s,r,a,n){this.type=e,this.gameObject=t,this.rules=i,this.warhead=s,this.projectileRules=r,this.flh=a,this.targeting=n,this.cooldownTicks=0,this.burstsLeft=0,this.burstIndex=0,this.useBurstDelay=!1,this.lateralMuzzleMult=1,this.distributedFireAngle=t.rules.distributedFire&&t.rules.radialFireSegments?-90:0}static factory(e,t,i,s,r){var a=s.getWeapon(e);let n=a.warhead;n===Ya.SPECIAL_WARHEAD_NAME&&(n=tn.findSpecialWarheadName(a,i,s));var o=new Ya(s.getWarhead(n)),e=s.getProjectile(a.projectile),s=new en(t,e,a,o.rules,i,s.general);return new this(t,i,a,o,e,r||new Ka,s)}static findSpecialWarheadName(e,t,i){let s;if(!e.spawner)throw new Error(`Weapon "${e.name} can't use "Special" warhead without Spawner=yes`);if(t.rules.spawns===i.general.v3Rocket.type)s=i.combatDamage.v3Warhead;else if(t.rules.spawns===i.general.dMisl.type)s=i.combatDamage.dMislWarhead;else{if(!t.rules.spawns)throw new Error(`Can't use "Special" warhead on unit type "${t.name}" without "Spawns"`);t=i.getObject(t.rules.spawns,xt.Aircraft);if(!t.primary)throw new Error(`Spawned unit "${t.name}" doesn't have a primary weapon`);s=i.getWeapon(t.primary).warhead}return s}static computeSpeed(e,t){return t.arcing?.75*Ci.iniSpeedToLeptonsPerTick(50,100):!t.rot||t.inviso||e.isLaser||e.isElectricBolt?Number.POSITIVE_INFINITY:e.speed}get name(){return this.rules.name}get minRange(){return this.rules.minimumRange}get range(){return this.gameObject.isBuilding()&&!this.gameObject.overpoweredTrait&&this.type===hi.Secondary&&this.gameObject.primaryWeapon?Math.min(this.gameObject.primaryWeapon.rules.range,this.rules.range):this.rules.range}get speed(){return tn.computeSpeed(this.rules,this.projectileRules)}get rof(){let e=this.rules.rof;return this.gameObject.isBuilding()&&this.gameObject.garrisonTrait?.isOccupied()&&(e/=this.gameObject.garrisonTrait.units.length),this.gameObject.veteranTrait&&(e*=this.gameObject.veteranTrait.getVeteranRofMultiplier()),Math.floor(e)}getCooldownTicks(){return this.cooldownTicks}expireCooldown(){this.cooldownTicks=0}resetCooldown(){this.cooldownTicks=this.rof}hasBurstsLeft(){return 0<this.burstsLeft}resetBursts(){this.burstsLeft=0,this.burstIndex=0,this.resetCooldown(),this.gameObject.ammoTrait&&0<this.gameObject.ammoTrait.ammo&&this.gameObject.ammoTrait.ammo--}tick(){0<this.cooldownTicks&&this.cooldownTicks--}getBurstsFired(){return this.burstIndex}fire(r,a,n=1){let o=this.gameObject,e,t=0;if(!o.airSpawnTrait||!this.rules.spawner||(e=o.airSpawnTrait.prepareLaunch(o,r,a),t=o.airSpawnTrait.availableSpawns,e)){this.burstsLeft?(this.burstsLeft--,this.burstIndex++,this.lateralMuzzleMult*=-1):(this.useBurstDelay=!1,this.burstIndex=0,e?this.burstsLeft=t:this.gameObject.isAircraft()?this.burstsLeft=this.projectileRules.iniRot<=1?4:this.gameObject.rules.fighter?0:1:(this.burstsLeft=this.rules.burst-1,this.useBurstDelay=!0),this.lateralMuzzleMult=1),0<this.burstsLeft&&(e&&0<t?this.cooldownTicks=this.rules.iniSpeed:this.gameObject.isAircraft()?this.cooldownTicks=this.rules.rof:this.cooldownTicks=this.useBurstDelay&&void 0!==this.gameObject.rules.burstDelay[this.burstIndex]?this.gameObject.rules.burstDelay[this.burstIndex]:a.generateRandomInt(3,5)),this.burstsLeft||this.resetBursts(),this.rules.limboLaunch&&(a.limboObject(this.gameObject,{selected:a.getUnitSelection().isSelected(this.gameObject),controlGroup:a.getUnitSelection().getOrCreateSelectionModel(this.gameObject).getControlGroupNumber()}),this.warhead.rules.parasite&&(r.obj?.isVehicle()||r.obj?.isAircraft())&&r.obj.parasiteableTrait&&(r.obj.parasiteableTrait.beingBoarded=!0));let i=e??a.createProjectile(this.projectileRules.name,this.gameObject,this,r,!1);i.isAircraft()||(i.baseDamageMultiplier=n*(this.gameObject.isUnit()?this.gameObject.crateBonuses.firepower:1));let s=this.flh.clone();s.lateral*=this.lateralMuzzleMult;var h=o.position.getMapPosition();if(a.map.isWithinHardBounds(h)){i.position.moveToLeptons(h),i.position.tileElevation=o.position.tileElevation;let e=new ks(s.lateral,s.forward);n=this.getMuzzleFacing()+this.distributedFireAngle;e=ar(e,n);var h=ar(h=new ks(0,o.art.turretOffset),o.direction);e.add(h),o.rules.radialFireSegments&&o.rules.distributedFire&&(h=Math.floor(180/o.rules.radialFireSegments),this.distributedFireAngle=(this.distributedFireAngle+h+90)%180-90),i.direction=n,o.isBuilding()&&o.rules.turretAnim&&(l=Os.screenDistanceToWorld(o.rules.turretAnimX,o.rules.turretAnimY),n=o.getFoundationCenterOffset(),i.position.moveByLeptons(-n.x+l.x,-n.y+l.y));let t=new rs(e.x,s.vertical,-e.y);var l=t.clone().add(i.position.worldPosition);if(a.map.isWithinHardBounds(l)&&i.position.moveByLeptons3(t),i.tileElevation<0&&(i.position.tileElevation=0),i.isAircraft()?a.unlimboObject(i,i.position.tile):a.spawnObject(i,i.position.tile),this.rules.revealOnFire&&r.obj?.isTechno()){let e=a.mapShroudTrait.getPlayerShroud(r.obj.owner);e?.isShrouded(o.tile,o.tileElevation)&&e.revealTemporarily(o)}this.rules.decloakToFire&&this.gameObject.cloakableTrait?.uncloak(a),a.events.dispatch(new Ja(this,this.gameObject))}else e&&(e.owner.removeOwnedObject(e),e.dispose())}}getMuzzleFacing(){let e=this.gameObject,t;return t=!e.isInfantry()&&!e.isAircraft()&&(e.isBuilding()||e.isVehicle())&&e.turretTrait?e.turretTrait.facing:e.direction,t}}tn.NUKE_PAYLOAD_NAME="NukePayload";class sn extends Vs{constructor(e,t,i,s){super(e,t,i),this.weaponType=s}onStart(t){var i=t.rules.getWeapon(this.weaponType),s=t.createTarget(void 0,this.tile),r=this.owner.getOwnedObjectsByType(xt.Building).find(e=>e.rules.nukeSilo);if(r){let e=tn.factory(i.name,hi.Primary,r,t.rules);e.fire(s,t)}else this.fireLooseNuke(i,s,t)}fireLooseNuke(t,i,s){var r=new ks(this.tile.rx+.5,this.tile.ry+.5).multiplyScalar(Os.LEPTONS_PER_TILE);if(s.map.isWithinHardBounds(r)){let e=s.createLooseProjectile(t.name,this.owner,i);e.position.moveToLeptons(r),e.position.tileElevation=Os.worldToTileHeight(e.rules.detonationAltitude),s.spawnObject(e,e.position.tile)}}onTick(e){return!0}}class rn{constructor(e){this.position=e,this.type=ss.LightningStormCloud}}class an{constructor(e){this.target=e,this.type=ss.LightningStormManifest}}(r=la=la||{})[r.Approaching=0]="Approaching",r[r.Manifesting=1]="Manifesting";class nn extends Vs{constructor(){super(...arguments),this.state=la.Approaching,this.clouds=[]}onStart(e){e=e.rules.general.lightningStorm;this.manifestStartTimer=e.deferment,this.manifestEndTimer=e.duration,this.nextDirectHitTimer=0,this.nextRandomHitTimer=0}onTick(t){if(this.state===la.Approaching&&(0<this.manifestStartTimer?this.manifestStartTimer--:(this.state=la.Manifesting,t.events.dispatch(new an(this.tile)))),this.state===la.Manifesting){var i,r=t.rules.general.lightningStorm;if(0<this.manifestEndTimer&&(this.manifestEndTimer--,0<this.nextDirectHitTimer&&this.nextDirectHitTimer--,this.nextDirectHitTimer<=0&&(this.nextDirectHitTimer=r.hitDelay,this.spawnCloudAt(this.tile,t)),0<this.nextRandomHitTimer&&this.nextRandomHitTimer--,this.nextRandomHitTimer<=0)){this.nextRandomHitTimer=r.scatterDelay;var a=Math.floor(r.cellSpread/2);let i=r.separation,s=new As(t.map.tileOccupation),e=new Ta(t.map.tiles,t.map.mapBounds,this.tile,a,t,t=>!this.clouds.some(e=>s.tileDistance(t,e.tile)<i),!1);a=e.getNextTile();a&&this.spawnCloudAt(a,t)}for(i of this.clouds.slice())if(0<i.ticksLeft){if(i.ticksLeft--,i.ticksLeft===Math.floor(i.durationTicks/2)){var s=r.warhead;let e=new Ya(t.rules.getWarhead(s));var n=i.tile,o=t.map.tileOccupation.getBridgeOnTile(n),h=o?.tileElevation??0,s=t.map.getTileZone(n);e.detonate(t,r.damage,n,h,Os.tile3dToWorld(n.rx+.5,n.ry+.5,n.z+h),s,o?aa.OnBridge:aa.None,t.createTarget(o,n),{player:this.owner,weapon:void 0},!1,!0,void 0)}}else this.clouds.splice(this.clouds.indexOf(i),1);if(!this.clouds.length&&this.manifestEndTimer<=0)return!0}return!1}spawnCloudAt(e,t){var i=t.rules.audioVisual.weatherConClouds,i=t.generateRandomInt(0,i.length-1);let s=t.art.getAnimation(t.rules.audioVisual.weatherConClouds[i]);i=s.art.getNumber("Rate",60*js.BASE_TICKS_PER_SECOND)/60,i=Math.floor(js.BASE_TICKS_PER_SECOND/i*60);this.clouds.push({tile:e,durationTicks:i,ticksLeft:i});i=(t.map.tileOccupation.getBridgeOnTile(e)?.tileElevation??0)+Os.worldToTileHeight(t.rules.general.flightLevel),i=Os.tile3dToWorld(e.rx+.5,e.ry+.5,e.z+i);t.events.dispatch(new rn(i))}}class on extends Vs{onStart(e){var t,i,s=e.rules.combatDamage.ironCurtainDuration,r={player:this.owner};let a=new Us(e.map.tiles,e.map.mapBounds,this.tile,{width:1,height:1},0,1,()=>!0);for(;t=a.getNextTile();)for(i of e.map.getGroundObjectsOnTile(t))!i.isTechno()||i.isUnit()&&i.tile!==t||i.rules.missileSpawn||(i.rules.organic?i.isDestroyed||e.destroyObject(i,r):(i.invulnerableTrait.setActiveFor(s,e.currentTick),(i.isVehicle()||i.isAircraft())&&i.parasiteableTrait?.isInfested()&&i.parasiteableTrait.destroyParasite(r,e)))}onTick(e){return!0}}class hn extends Vs{constructor(e,t,i,s){super(e,t,i),this.tile2=s,this.objectsToTeleport=[]}onStart(i){this.delayTicks=i.rules.general.chronoDelay;let s=i.map.tiles;for(let t=-1;t<=1;t++)for(let e=-1;e<=1;e++){var r=s.getByMapCoords(this.tile.rx+t,this.tile.ry+e);if(r){var a,n=!!r.onBridgeLandType,o=s.getByMapCoords(this.tile2.rx+t,this.tile2.ry+e);for(a of i.map.getGroundObjectsOnTile(r))!a.isUnit()||a.tile!==r||a.onBridge!==n||a.isInfantry()&&a.stance===Ls.Paradrop||a.isDisposed||a.invulnerableTrait.isActive()||(a.rules.organic&&!a.rules.teleporter||!o?i.destroyObject(a,{player:this.owner}):a.warpedOutTrait.isActive()||(a.warpedOutTrait.setActive(!0,!0,i),this.objectsToTeleport.push({obj:a,destTile:o})))}}}onTick(l){if(0<this.delayTicks&&this.delayTicks--,this.delayTicks)return!1;for(let{obj:o,destTile:h}of this.objectsToTeleport)if(o.isSpawned){let i=!1,s=h?l.map.tileOccupation.getBridgeOnTile(h):void 0,r=l.map.getGroundObjectsOnTile(h),a=r.find(e=>e.isBuilding());var c=r.some(e=>l.rules.general.padAircraft.includes(e.name)),t=l.rules.general.padAircraft.includes(o.name)&&!!a?.helipadTrait&&!!a.dockTrait?.getAllDockTiles().includes(h)&&!a.dockTrait.hasReservedDockAt(a.dockTrait.getDockNumberByTile(h))&&a.owner===o.owner;let e=!1,n=o.rules.speedType;o.rules.movementZone===ri.Fly&&(n=ei.Wheel);var u=l.map.mapBounds.isWithinBounds(h);if(!(t||l.map.terrain.getPassableSpeed(h,n,!!s)&&u)){let t=!1;if(!c&&(0<l.map.terrain.getPassableSpeed(h,n,!!s,void 0,!0)||!u)){a&&(i=!0);let e=new Us(l.map.tiles,l.map.mapBounds,h,{width:1,height:1},1,15,e=>0<l.map.terrain.getPassableSpeed(e,n,!!e.onBridgeLandType)&&!l.map.terrain.findObstacles({tile:e,onBridge:!!e.onBridgeLandType},o).length);u=e.getNextTile();u&&(h=u,s=l.map.tileOccupation.getBridgeOnTile(h),r=l.map.getGroundObjectsOnTile(h),t=!0)}t||(o.moveTrait.teleportUnitToTile(h,s,!0,!1,l),o.warpedOutTrait.setActive(!1,!0,l),l.map.getTileZone(h)===vs.Water&&(o.deathType=Vr.Sink),l.destroyObject(o,{player:this.owner}),e=!0)}if(!e||c)for(let t of r)t.isDisposed||t.isUnit()&&(this.objectsToTeleport.some(({obj:e})=>e===t)||t.onBridge!==!!s&&t.tile===h||2<Math.abs(t.tileElevation-o.tileElevation)||(t.isInfantry()&&t.stance!==Ls.Paradrop&&(t.deathType=Vr.Crush),l.destroyObject(t,{player:this.owner,obj:o})));if(!e){if(o.moveTrait.teleportUnitToTile(h,s,!0,!1,l),t&&a?.dockTrait){t=a.dockTrait.getAllDockTiles().indexOf(h);if(a.dockTrait.undockUnitAt(t),a.dockTrait.hasReservedDockAt(t))throw new Error("Target building dock is already reserved by another unit");a.dockTrait.dockUnitAt(o,t)}i?o.warpedOutTrait.setTimed(l.rules.general.chronoDelay,!1,l):o.warpedOutTrait.setActive(!1,!0,l)}}return!0}}(ca=ca||{}).onDeactivate=Symbol();class ln{constructor(){this.effects=[]}[Es.onTick](i){for(var e of i.getCombatants()){var t;for(t of e.superWeaponsTrait.getAll())t.update(i)}for(let t of this.effects)t.status===Ms.NotStarted&&(t.onStart(i),t.status=Ms.Running),t.onTick(i)&&(t.status=Ms.Finished,i.traits.filter(ca).forEach(e=>{e[ca.onDeactivate](t.type,t.owner,i)}));this.effects=this.effects.filter(e=>e.status!==Ms.Finished)}[Ds.onPowerLow](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!1)})}[Ds.onPowerRestore](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!0)})}[Ds.onPowerChange](e,t){}[Ps.onChange](e,t){var i;e.owner.powerTrait&&e.isBuilding()&&e.superWeaponTrait&&((i=e.superWeaponTrait.getSuperWeapon(e))&&this.updateTimer(i,!e.owner.powerTrait.isLowPower()))}updateTimer(e,t){var i=this.superWeaponHasValidBuilding(e);t&&i?e.resumeTimer():e.pauseTimer()}superWeaponHasValidBuilding(t){return[...t.owner.buildings].find(e=>!(e.superWeaponTrait?.getSuperWeapon(e)!==t||e.warpedOutTrait.isActive()&&t.rules.isPowered))}addEffect(e){this.effects.push(e)}activateSuperWeapon(t,e,i,s,r){let a=e.superWeaponsTrait?.getAll().find(e=>e.rules.type===t);if(a&&a.status===Ns.Ready){if(a.oneTimeOnly){e.superWeaponsTrait.remove(a.name);for(var n of e.buildings)n.rules.superWeapon===a.name&&n.superWeaponTrait&&n.superWeaponTrait.addSuperWeaponToPlayerIfNeeded(e,i)}else a.resetTimer();this.activateEffect(a.rules,e,i,s,r)}}activateEffect(e,i,s,r,a,n=!1){const o=e.type;if(void 0!==o){let t=[];switch(o){case is.AmerParaDrop:for(var[h,l]of s.rules.general.paradrop.amerParaDrop.entries())s.rules.hasObject(l.inf,xt.Infantry)?t.push(new Va(o,i,r,l,h)):console.warn(`Can't paradrop unknown infantry type "${l.inf}"`);break;case is.ParaDrop:{let e=s.rules.general.paradrop.getParadropSquads(i.country.side);for(var[c,u]of e.entries())s.rules.hasObject(u.inf,xt.Infantry)?t.push(new Va(o,i,r,u,c)):console.warn(`Can't paradrop unknown infantry type "${u.inf}"`);break}case is.MultiMissile:if(!e.weaponType)throw new Error("Missing WeaponType in super weapon rules");t.push(new sn(o,i,r,e.weaponType));break;case is.LightningStorm:t.push(new nn(o,i,r));break;case is.IronCurtain:t.push(new on(o,i,r));break;case is.ChronoSphere:if(!a)throw new Error("Missing tile2 action param");t.push(new hn(o,i,r,a))}for(var d of t)this.addEffect(d);s.traits.filter(Rs).forEach(e=>{e[Rs.onActivate](o,i,s,r,a)}),s.events.dispatch(new Hs(o,i,r,a,n))}}}class cn{constructor(e){this.target=e,this.type=ss.ObjectCloakChange}}(ua=ua||{}).onDamage=Symbol();class un{constructor(e,t){this.gameObject=e,this.cloakDelayMinutes=t,this.isActive=!1,this.resetCloakCooldown()}isCloaked(){return this.isActive}uncloak(e){var t=this.isActive;this.resetCloakCooldown(),t&&(this.isActive=!1,e.events.dispatch(new cn(this.gameObject)))}resetCloakCooldown(){this.cooldownTicks=Math.floor(60*this.cloakDelayMinutes*js.BASE_TICKS_PER_SECOND)}[Yr.onSpawn](e,t){this.resetCloakCooldown()}[Fr.onTick](e,t){0<this.cooldownTicks&&this.cooldownTicks--,!(this.cooldownTicks<=0)||this.isActive||e.isVehicle()&&e.submergibleTrait&&!e.submergibleTrait.isSubmerged()||e.temporalTrait.getTarget()||(this.isActive=!0,t.events.dispatch(new cn(this.gameObject)))}[ua.onDamage](e,t){this.uncloak(t)}dispose(){this.gameObject=void 0}}class dn{static calculateOverlayId(e,t){if(e!==oa.NotSpecial){var i=t.dx,t=t.dy,i=Math.floor((t-9)/2%12*((t-8)/2%12)%12-(i-13)/2%12*((i-12)/2%12)%12+12e4);return i%=12,e===oa.Ore?qa.minIdRiparius+i:e===oa.Gems?qa.minIdCruentus+i:e===oa.Vinifera?qa.minIdVinifera+i:e===oa.Aboreus?qa.minIdAboreus+i:void 0}}}var pn,gn,mn,fn,yn,wn,Tn,bn,vn,Sn,kn,On,_n,In,Cn,An,Bn,xn,En,Pn,Nn,Mn,Dn,Rn,Ln,Fn,r=__webpack_require__(949);class jn extends r.Box2{}const Un=[xs.IonStorm,xs.Gas,xs.Pod,xs.Squad];class Wn{constructor(e){this.randomCrateSpawn=e,this.crates=[],this.availEdgeTiles=[],this.allTiles=[]}init(n){var o=n.map.tiles.getMapSize();let h=n.map.tiles,e=[],l=0;for(let a=0;a<o.width;++a){let t,i,s=!1,r=!1;for(let e=0;e<o.height;++e){var c=h.getByMapCoords(a,e);if(c&&this.canPlaceCrateOnTile(n,c)){var u=n.map.getTileZone(c)===vs.Water;t?(u||(i=c),r=u):u?s=r=!0:t=i=c}else if(t&&!c)break}t&&(e.push(t),i&&i!==t&&e.push(i),s||r||l++)}this.availEdgeTiles=e,this.allTiles=h.getAll(),this.mapEdgeIsWater=0===l,this.minCrates=n.rules.crateRules.crateMinimum*n.gameOpts.humanPlayers.filter(e=>-3!==e.countryId).length}[Es.onTick](t){for(var e of this.crates)e.ticksLeft--,e.ticksLeft<=0&&(t.unspawnObject(e.obj),e.obj.dispose());if(this.crates=this.crates.filter(e=>0<e.ticksLeft),this.randomCrateSpawn)for(let e=0;e<this.minCrates-this.crates.length&&this.spawnCrateAtRandom(this.allTiles,t);e++);}spawnCrateAtRandom(e,t){e=this.chooseSpawnTile(e,t);if(e)return this.spawnRandomCrateAt(e,t)}spawnRandomCrateAt(e,t){if(this.canPlaceCrateOnTile(t,e)){var i=t.map.getTileZone(e,!0)===vs.Water,i=this.choosePowerup(i,t.rules.powerups.powerups,t);if(i)return this.spawnCrateAt(e,i,t)}}spawnCrateAt(t,i,s){if(this.canPlaceCrateOnTile(s,t)){var r=s.map.getTileZone(t,!0)===vs.Water,a=s.rules.crateRules,r=r?a.waterCrateImg:a.crateImg;let e=s.createObject(xt.Overlay,r);e.overlayId=s.rules.getOverlayId(r),e.value=0,s.spawnObject(e,t);s=60*a.crateRegen*js.BASE_TICKS_PER_SECOND*(.5+1.5*s.generateRandom());return this.crates.push({obj:e,powerup:i,ticksLeft:s}),e}}chooseSpawnTile(e,t){return t.generateRandom()<(this.mapEdgeIsWater?1/3:2/3)&&this.availEdgeTiles.length&&(e=this.availEdgeTiles),this.chooseRandomTile(e,t)}chooseRandomTile(e,t){let i;let s=0;for(;i=e[t.generateRandomInt(0,e.length-1)],s++,s<100&&!this.canPlaceCrateOnTile(t,i););if(100<=s){var r=t.map.tileOccupation.getEmptyTiles();if(!r.length)return;i=r[t.generateRandomInt(0,r.length-1)]}return i}canPlaceCrateOnTile(e,t){return e.map.mapBounds.isWithinBounds(t)&&!e.map.getGroundObjectsOnTile(t).length&&0<e.map.terrain.getPassableSpeed(t,ei.Amphibious,!1)&&t.terrainType!==Kt.Shore&&0===t.rampType}choosePowerup(t,i,s){if((i=t?i.filter(e=>e.waterAllowed):i).length){var r,t=i.reduce((e,t)=>e+t.probShares,0),a=s.generateRandomInt(0,t);let e=0;for(r of i)if(e+=r.probShares,a<e)return r}}peekInsideCrate(t){return this.crates.find(e=>e.obj===t)?.powerup.type}pickupCrate(e,t,i){let s=this.crates.find(e=>e.obj===t);if(s){this.crates.splice(this.crates.indexOf(s),1),i.unspawnObject(s.obj),s.obj.dispose();let t=this.grantPowerup(e,s.powerup,s.obj.tile,i);var r;return void 0!==t&&(e.owner.cratesPickedUp++,r=i.rules.powerups.powerups.find(e=>e.type===t),i.events.dispatch(new bs(r,e.owner,e,s.obj.tile))),this.randomCrateSpawn&&this.spawnCrateAtRandom(this.allTiles,i),t}}grantPowerup(t,i,s,r){let a=t.owner,n=!1;if(a.isCombatant()){if(i.type===xs.Unit){let e;if(![...a.buildings].some(e=>e.rules.constructionYard)&&r.rules.crateRules.freeMCV){let t=r.rules.general.baseUnit;if(!a.getOwnedObjects(!0).some(e=>t.includes(e.name))&&a.credits>=[...r.rules.ai.buildPower,...r.rules.ai.buildRefinery].map(e=>r.rules.getBuilding(e)).filter(e=>e.aiBasePlanningSide===a.country.side).reduce((e,t)=>e+t.cost,0)){var o=t.find(e=>{let t=r.rules.getObject(e,xt.Vehicle);return t.isAvailableTo(a.country)&&t.hasOwner(a.country)});if(!o)throw new Error(`No suitable MCV found for player country ${a.country}`);e=r.rules.getObject(o,xt.Vehicle)}}if(e||(h=(h=r.rules.crateRules.unitCrateType)?r.rules.hasObject(h,xt.Vehicle)?[r.rules.getObject(h,xt.Vehicle)]:[]:[...r.rules.vehicleRules.values()].filter(e=>e.crateGoodie&&0<r.map.terrain.getPassableSpeed(s,e.speedType,!1))).length&&(e=h[r.generateRandomInt(0,h.length-1)]),e){let t=r.createUnitForPlayer(e,a);var h=new Us(r.map.tiles,r.map.mapBounds,s,{width:1,height:1},0,3,e=>0<r.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&!r.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length).getNextTile();h?(r.spawnObject(t,h),n=!0):(a.removeOwnedObject(t),t.dispose())}}else if(i.type===xs.Money){if(!i.data)throw new Error("Money powerup missing data field");a.credits=Math.max(0,a.credits+Math.floor(Number(i.data)*(.55+2*r.generateRandom()*.45))),n=!0}else if(i.type===xs.HealBase){var e;for(e of a.getOwnedObjects(!0))e.isDestroyed||e.healthTrait.healToFull(void 0,r);n=!0}else if(i.type===xs.Reveal)r.mapShroudTrait.revealMap(a,r),n=!0;else if(i.type===xs.Darkness)r.mapShroudTrait.resetShroud(a,r),n=!0;else if(i.type===xs.Veteran){if(t.veteranTrait&&!t.veteranTrait.isMaxLevel()){n=!0;var l,c=Number(i.data);for(l of this.getUnitsInCrateRadius(r,s,a))l.veteranTrait?.promote(c,r)}}else if(i.type===xs.Armor){if(1===t.crateBonuses.armor){n=!0;var u,d=Number(i.data);for(u of this.getUnitsInCrateRadius(r,s,a))1===u.crateBonuses.armor&&(u.crateBonuses.armor=d)}}else if(i.type===xs.Firepower){if(1===t.crateBonuses.firepower){n=!0;var p,g=Number(i.data);for(p of this.getUnitsInCrateRadius(r,s,a))1===p.crateBonuses.firepower&&(p.crateBonuses.firepower=g)}}else if(i.type===xs.Speed){if(1===t.crateBonuses.speed){n=!0;var m,f=Number(i.data);for(m of this.getUnitsInCrateRadius(r,s,a))1===m.crateBonuses.speed&&(m.crateBonuses.speed=f)}}else if(i.type===xs.Cloak){if(!t.cloakableTrait){n=!0;for(var y of this.getUnitsInCrateRadius(r,s,a))y.cloakableTrait||(y.cloakableTrait=new un(y,r.rules.general.cloakDelay),r.addObjectTrait(y,y.cloakableTrait))}}else if(i.type===xs.ICBM){var w=[...r.rules.superWeaponRules.values()].find(e=>e.type===is.MultiMissile);if(w&&a.superWeaponsTrait&&!a.superWeaponsTrait.has(w.name)){let e=r.createSuperWeapon(w.name,a,!0);e.isGift=!0,a.superWeaponsTrait.add(e),n=!0}}else if(i.type===xs.Invulnerability){var T=[...r.rules.superWeaponRules.values()].find(e=>e.type===is.IronCurtain);T&&(r.traits.get(ln).activateEffect(T,a,r,s,void 0,!0),n=!0)}else if(i.type===xs.Explosion||i.type===xs.Napalm){n=!0;w=Number(i.data),T=i.type===xs.Napalm?r.rules.combatDamage.flameDamage:r.rules.combatDamage.c4Warhead;let e=new Ya(r.rules.getWarhead(T));e.detonate(r,w,t.tile,t.tileElevation,t.position.worldPosition,t.zone,aa.None,r.createTarget(t,t.tile),{player:t.owner,weapon:void 0},!1,!1,void 0,0)}else{if(i.type!==xs.Tiberium)return void console.warn(`Unhandled powerup type "${xs[i.type]}"`);{let e=new Ta(r.map.tiles,r.map.mapBounds,s,2,r,e=>Xa.canBePlacedOn(e,r.map)),t,i=0;for(;i++<6&&(t=e.getNextTile());){var b=dn.calculateOverlayId(oa.Ore,t);if(void 0===b)throw new Error("Expected an overlayId");let e=r.createObject(xt.Overlay,r.rules.getOverlayName(b));e.overlayId=b,e.value=3,r.spawnObject(e,t),n=!0}}}if(n)return i.type;i=r.rules.powerups.powerups.find(e=>e.type===xs.Money&&0<e.probShares);return i?this.grantPowerup(t,i,s,r):void 0}}getUnitsInCrateRadius(e,t,i){let s=e.rules.crateRules.crateRadius,r=new As(e.map.tileOccupation);return e.map.technosByTile.queryRange((new jn).setFromCenterAndSize(new ks(t.rx,t.ry),new ks(s,s))).filter(e=>e.owner===i&&e.isUnit()&&r.tileDistance(e,t)<=s)}}class zn{constructor(){this.powerups=[]}readIni(e){for(var[r,a]of e.entries){let[e,t,i,s]=a.split(",");var n=Number(e),a=xs[r];void 0!==a?Un.includes(a)||this.powerups.push({type:a,probShares:n,animName:"<none>"!==t.toLowerCase()?t:void 0,waterAllowed:"yes"===i,data:s}):console.warn(`Unknown powerup "${r}". Skipping.`)}return this}}const Vn=["Gold","DarkRed","DarkBlue","DarkGreen","Orange","DarkSky","Purple","Magenta"];class Hn{constructor(e,t){this.ini=e,this.logger=t,this.buildingTypes=new Map,this.vehicleTypes=new Map,this.infantryTypes=new Map,this.aircraftTypes=new Map,this.terrainTypes=new Map,this.overlayTypes=new Map,this.overlayIdsByType=new Map,this.animationTypes=new Map,this.animationNames=new Set,this.voxelAnimTypes=new Map,this.smudgeTypes=new Map,this.warheadTypes=new Map,this.tiberiumTypes=new Map,this.superWeaponTypes=new Map,this.countryTypes=new Map,this.weaponTypes=new Map,this.allObjectRules=new Map,this.buildingRules=new Map,this.infantryRules=new Map,this.vehicleRules=new Map,this.aircraftRules=new Map,this.terrainRules=new Map,this.overlayRules=new Map,this.smudgeRules=new Map,this.voxelAnimRules=new Map,this.countryRules=new Map,this.warheadRules=new Map,this.powerups=new zn,this.colors=new Map,this.general=new Vi,this.ai=new ms,this.crateRules=new Ts,this.elevationModel=new fs,this.mpDialogSettings=new Ot,this.audioVisual=new Bi,this.combatDamage=new ps,this.radiation=new ys,this.landRules=new Map,this.tiberiumRules=new Map,this.superWeaponRules=new Map,this.cachedWeaponRules=new Map,this.cachedProjectileRules=new Map,this.init()}hasObject(e,t){return this.allObjectRules.get(t)?.has(e)}getObject(e,t){t=this.allObjectRules.get(t)?.get(e);if(!t)throw new Error(`Missing rules for object "${e}"`);return t}getTechnoByInternalId(e,t){let i;if(t===xt.Building)i=this.buildingTypes.get(e);else if(t===xt.Infantry)i=this.infantryTypes.get(e);else if(t===xt.Vehicle)i=this.vehicleTypes.get(e);else{if(t!==xt.Aircraft)throw new Error(`Type ${xt[t]} is not a techno type`);i=this.aircraftTypes.get(e)}if(void 0===i)throw new Error(`Object type "${xt[t]}" with ID "${e}" not found`);return this.getObject(i,t)}getBuilding(e){var t=this.buildingRules.get(e);if(!t)throw new Error(`Missing rules for building "${e}"`);return t}getWeapon(e){let t=this.cachedWeaponRules.get(e);if(!t){var i=this.ini.getSection(e);if(!i)throw new Error(`Weapon ${e} is missing ini section`);t=new Ai(i),this.cachedWeaponRules.set(e,t)}return t}getWeaponByInternalId(e){var t=this.weaponTypes.get(e);if(!t)throw new RangeError(`Weapon with internal ID "${e}" not found`);return this.getWeapon(t)}getWarhead(e){let t=this.warheadRules.get(e.toLowerCase());var i;if(t||(i=this.ini.getSection(e))&&(t=new qi(i),this.warheadRules.set(e.toLowerCase(),t)),!t)throw new Error(`Unknown warhead ${e}`);return t}getProjectile(e){let t=this.cachedProjectileRules.get(e);if(!t){var i=this.ini.getSection(e);if(!i)throw new Error(`Projectile ${e} is missing ini section`);t=new Xi(xt.Projectile,i),this.cachedProjectileRules.set(e,t)}return t}getOverlayName(e){var t=this.overlayTypes.get(e);if(!t)throw new Error(`Invalid overlay id ${e}`);return t}hasOverlayId(e){return this.overlayTypes.has(e)}getOverlayId(e){var t=this.overlayIdsByType.get(e);if(void 0===t)throw new Error(`Invalid overlay name ${e}`);return t}getOverlay(e){var t=this.overlayRules.get(e);if(!t)throw new Error(`Missing rules for overlay "${e}"`);return t}getAnimationName(e){return this.animationTypes.get(e)}getCountry(e){if(!this.countryRules.has(e))throw new Error(`Unknown country ${e}`);return this.countryRules.get(e)}getMultiplayerCountries(){return[...this.countryRules.values()].filter(e=>e.multiplay)}getMultiplayerColors(){let t=new Map;return Vn.forEach(e=>{if(!this.colors.has(e))throw new Error(`Multiplayer color "${e}" does not exist in the rules [Colors] section.`);t.set(e,this.colors.get(e))}),t}getLandRules(e){let t=this.landRules.get(e);var i;return t||(i=e===Jt.Cliff?"Rock":Jt[e],t=(new $i).readIni(this.ini.getOrCreateSection(i)),this.landRules.set(e,t)),t}getTiberium(e){var t=this.tiberiumTypes.get(e);if(!t)throw new Error(`Unknown tiberium type ${e}`);return this.tiberiumRules.get(t)}getSuperWeapon(e){if(!this.superWeaponRules.has(e))throw new Error(`Unknown superweapon type "${e}"`);return this.superWeaponRules.get(e)}getIni(){return this.ini}applySpecialFlags(e){e.initialVeteran&&(this.general.veteran.initialVeteran=!0)}init(){this.readAudioVisual(),this.readCombatDamage(),this.readRadiation(),this.readGeneral(),this.readAi(),this.readCrateRules(),this.readElevationModel(),this.readMpDialogSettings(),this.readObjectTypes("BuildingTypes",this.buildingTypes),this.readObjectTypes("InfantryTypes",this.infantryTypes),this.readObjectTypes("VehicleTypes",this.vehicleTypes),this.readObjectTypes("AircraftTypes",this.aircraftTypes),this.readObjectTypes("TerrainTypes",this.terrainTypes),this.readObjectTypes("SmudgeTypes",this.smudgeTypes),this.readObjectTypes("Animations",this.animationTypes),this.animationNames=new Set(this.animationTypes.values()),this.readObjectTypes("VoxelAnims",this.voxelAnimTypes),this.readObjectTypes("OverlayTypes",this.overlayTypes),this.overlayTypes.forEach((e,t)=>this.overlayIdsByType.set(e,t)),this.readColors(),this.readObjectTypes("Countries",this.countryTypes),this.readObjectTypes("Warheads",this.warheadTypes),this.readObjectTypes("Tiberiums",this.tiberiumTypes),this.readObjectTypes("SuperWeaponTypes",this.superWeaponTypes),this.allObjectRules.set(xt.Building,this.buildingRules).set(xt.Infantry,this.infantryRules).set(xt.Vehicle,this.vehicleRules).set(xt.Aircraft,this.aircraftRules).set(xt.Terrain,this.terrainRules).set(xt.Overlay,this.overlayRules).set(xt.Smudge,this.smudgeRules).set(xt.VoxelAnim,this.voxelAnimRules),this.readObjects(xt.Building,this.buildingTypes,this.buildingRules),this.readObjects(xt.Infantry,this.infantryTypes,this.infantryRules),this.readObjects(xt.Vehicle,this.vehicleTypes,this.vehicleRules),this.readObjects(xt.Aircraft,this.aircraftTypes,this.aircraftRules),this.readObjects(xt.Terrain,this.terrainTypes,this.terrainRules),this.readObjects(xt.Overlay,this.overlayTypes,this.overlayRules),this.readObjects(xt.Smudge,this.smudgeTypes,this.smudgeRules),this.readObjects(xt.VoxelAnim,this.voxelAnimTypes,this.voxelAnimRules),this.readCountries(),this.readWarheads(),this.readPowerups(),this.readTiberiums(),this.readSuperWeapons(),this.buildWeaponsList()}readAudioVisual(){var e=this.ini.getSection("AudioVisual");if(!e)throw new Error("Missing [AudioVisual] section");this.audioVisual.readIni(e)}readCombatDamage(){var e=this.ini.getSection("CombatDamage");if(!e)throw new Error("Missing [CombatDamage] section");this.combatDamage.readIni(e)}readRadiation(){var e=this.ini.getSection("Radiation");if(!e)throw new Error("Missing [Radiation] section");this.radiation.readIni(e)}readGeneral(){var e=this.ini.getSection("General");if(!e)throw new Error("Missing [General] section");this.general.readIni(e)}readAi(){var e=this.ini.getSection("AI");if(!e)throw new Error("Missing [AI] section");this.ai.readIni(e)}readCrateRules(){var e=this.ini.getSection("CrateRules");if(!e)throw new Error("Missing [CrateRules] section");this.crateRules.readIni(e)}readElevationModel(){var e=this.ini.getSection("ElevationModel");if(!e)throw new Error("Missing [ElevationModel] section");this.elevationModel.readIni(e)}readMpDialogSettings(){var e=this.ini.getSection("MultiplayerDialogSettings");if(!e)throw new Error("Missing [MultiplayerDialogSettings] section");this.mpDialogSettings.readIni(e)}readObjectTypes(i,s){let e=this.ini.getSection(i);if(!e)throw new Error(`Missing [${i}] section`);let r=0,a=new Set;e.entries.forEach((e,t)=>{Number.isNaN(Number(t))?this.logger?.debug(`Non-numeric id "${t}" found in rules section [${i}]. Skipping.`):a.has(e)?this.logger?.debug(`Duplicate type "${e}" in rules section [${i}]. Skipping.`):(s.set(r++,e),a.add(e))})}readColors(){let e=this.ini.getSection("Colors");if(!e)throw new Error("Missing [Colors] section");e.entries.forEach((e,t)=>{var[i,s,e]=e.split(","),e=W.fromHsv(parseInt(i,10),parseInt(s,10),parseInt(e,10));this.colors.set(t,e)})}readObjects(s,e,r){e.forEach((e,t)=>{var i=this.ini.getSection(e);i?(t=(new ds).create(s,i,t),r.set(e,t)):this.logger?.debug(`${xt[s]} type "${e}" has no rules section`)})}readCountries(){this.countryTypes.forEach((e,t)=>{var i=this.ini.getSection(e);if(!i)throw new Error(`Missing ini section for country ${e}`);let s=new Ii(t);s.readIni(i),this.countryRules.set(e,s)})}readWarheads(){this.warheadTypes.forEach(e=>{var t=this.ini.getSection(e);t?(t=new qi(t),this.warheadRules.set(e.toLowerCase(),t)):this.logger?.debug(`Warhead "${e}" has no rules section`)})}readPowerups(){var e=this.ini.getSection("Powerups");if(!e)throw new Error("Missing [Powerups] section");this.powerups.readIni(e)}readTiberiums(){this.tiberiumTypes.forEach(e=>{var t=this.ini.getSection(e);if(!t)throw new Error(`Missing rules section for tiberium type ${e}`);this.tiberiumRules.set(e,(new gs).readIni(t))})}readSuperWeapons(){this.superWeaponTypes.forEach((e,t)=>{var i=this.ini.getSection(e);if(!i)throw new Error(`Missing rules section for superweapon type ${e}`);this.superWeaponRules.set(e,new ws(t).readIni(i))})}buildWeaponsList(){let e=new Set;e.add(this.general.dropPodWeapon);for(var t of this.superWeaponRules.values())t.weaponType&&e.add(t.weaponType);var s,i;e.add(tn.NUKE_PAYLOAD_NAME);for(let i of[...this.buildingRules.values(),...this.aircraftRules.values(),...this.vehicleRules.values(),...this.infantryRules.values()])for(s of[i.deathWeapon,i.primary,i.secondary,i.elitePrimary,i.eliteSecondary,i.occupyWeapon,i.eliteOccupyWeapon,...i.weaponCount?new Array(i.weaponCount).fill(0).map((e,t)=>[i.getWeaponAtIndex(t),i.getEliteWeaponAtIndex(t)]).flat():[]].filter(ja).filter(e=>""!==e))e.add(s);let r=0;for(i of e)this.weaponTypes.set(r++,i)}}(r=pn=pn||{})[r.Ready=0]="Ready",r[r.Guard=1]="Guard",r[r.Prone=2]="Prone",r[r.Walk=3]="Walk",r[r.FireUp=4]="FireUp",r[r.Down=5]="Down",r[r.Crawl=6]="Crawl",r[r.Up=7]="Up",r[r.FireProne=8]="FireProne",r[r.Idle1=9]="Idle1",r[r.Idle2=10]="Idle2",r[r.Die1=11]="Die1",r[r.Die2=12]="Die2",r[r.Hover=13]="Hover",r[r.Fly=14]="Fly",r[r.FireFly=15]="FireFly",r[r.Tumble=16]="Tumble",r[r.AirDeathStart=17]="AirDeathStart",r[r.AirDeathFalling=18]="AirDeathFalling",r[r.AirDeathFinish=19]="AirDeathFinish",r[r.Tread=20]="Tread",r[r.Swim=21]="Swim",r[r.WetAttack=22]="WetAttack",r[r.WetIdle1=23]="WetIdle1",r[r.WetIdle2=24]="WetIdle2",r[r.WetDie1=25]="WetDie1",r[r.WetDie2=26]="WetDie2",r[r.Deploy=27]="Deploy",r[r.Deployed=28]="Deployed",r[r.DeployedFire=29]="DeployedFire",r[r.DeployedIdle=30]="DeployedIdle",r[r.Undeploy=31]="Undeploy",r[r.Paradrop=32]="Paradrop",r[r.Cheer=33]="Cheer",r[r.Panic=34]="Panic";const Gn=new Map([["E",5],["S",3],["W",1],["N",7]]);class $n{readIni(e){let t=new Map;for(var[i,s]of e.entries){i=pn[i];void 0!==i&&(s=s.split(","),s={type:i,startFrame:Number(s[0]),frameCount:Number(s[1]),facingMult:Number(s[2]),onlyFacing:s[3]?Gn.get(s[3]):void 0},t.set(i,s))}return t}}(r=gn=gn||{})[r.None=0]="None",r[r.Global=1]="Global",r[r.Level=2]="Level",r[r.Ambient=3]="Ambient",r[r.Full=4]="Full",r[r.Default=5]="Default";class qn{constructor(e,t,i){this.sequences=new Map,this.dockingOffsets=[],this.type=e,this.rules=t,this.art=i,this.init()}static getDefaultPalette(e){switch(e){case xt.Building:case xt.Aircraft:case xt.Infantry:case xt.Vehicle:case xt.Projectile:case xt.VoxelAnim:return I.Unit;case xt.Overlay:return I.Overlay;case xt.Smudge:case xt.Terrain:return I.Iso;default:xt.Animation;return I.Anim}}static getDefaultLighting(e){switch(e){case xt.Animation:return gn.None;case xt.Aircraft:case xt.Building:case xt.Infantry:case xt.Vehicle:return gn.Ambient;case xt.Projectile:case xt.VoxelAnim:return gn.Global;case xt.Overlay:case xt.Smudge:case xt.Terrain:default:return gn.Full}}static getDefaultRemapability(e){switch(e){case xt.Aircraft:case xt.Building:case xt.Infantry:case xt.Vehicle:return!0;case xt.Overlay:case xt.Smudge:case xt.Terrain:case xt.Animation:case xt.Projectile:case xt.VoxelAnim:return!1;default:throw new Error(`Unknown object type ${e}`)}}static getDefaultDrawOffset(e){switch(e){case xt.Animation:case xt.Building:case xt.Vehicle:case xt.Infantry:case xt.Overlay:case xt.Smudge:case xt.Projectile:case xt.VoxelAnim:return new ks(0,0);case xt.Terrain:case xt.Aircraft:return new ks(0,(Os.ISO_TILE_SIZE+1)/2);default:throw new Error(`Unknown object type ${e}`)}}static getDefaultShadow(e){switch(e){case xt.Overlay:case xt.Building:case xt.Infantry:case xt.Terrain:case xt.Vehicle:case xt.Aircraft:return!0;default:case xt.Smudge:case xt.Animation:case xt.Projectile:case xt.VoxelAnim:return!1}}static getDefaultHeight(e){switch(e){case xt.Building:return 2;case xt.Infantry:case xt.Vehicle:case xt.Aircraft:return 1;default:return 0}}static factory(e,t,i,s){let r=new this(e,t,s);return e===xt.Infantry&&(!(s=s.getString("Sequence"))||(s=i.getSection(s))&&(r.sequences=(new $n).readIni(s))),r}init(){this.image=[xt.Infantry,xt.Vehicle,xt.Aircraft].includes(this.type)?"":this.art.getString("Image"),this.report=this.art.getString("Report")||void 0,this.readRotors(),this.noHva=this.art.getBool("NoHVA"),this.startSound=this.art.getString("StartSound")||void 0,this.readMuzzleFlash(),this.readPaletteAndLightingTypes(),this.readRemapability(),this.readFlatness(),this.readDockingOffsets();var e=this.art.getNumberArray("QueueingCell");this.queueingCell=e.length?new ks(e[0],e[1]):void 0,this.demandLoad=this.art.getBool("DemandLoad");var t=this.art.getBool("UseLineTrail"),i=this.art.getNumberArray("LineTrailColor"),e=this.art.getNumber("LineTrailColorDecrement",qn.DEFAULT_LINE_TRAIL_DEC);t&&i.length?(this.useLineTrail=!0,this.lineTrailColor=i,this.lineTrailColorDecrement=e):this.useLineTrail=!1,this.crater=this.art.getBool("Crater"),this.forceBigCraters=this.art.getBool("ForceBigCraters"),this.scorch=this.art.getBool("Scorch"),this.height=this.art.getNumber("Height",qn.getDefaultHeight(this.type)),this.isVoxel=this.art.getBool("Voxel"),this.occupyHeight=this.art.getNumber("OccupyHeight",this.height),this.type===xt.Building?this.canHideThings=this.art.getBool("CanHideThings",!0):this.canHideThings=!1,this.canBeHidden=this.art.getBool("CanBeHidden",!0),this.addOccupy=this.readAddRemoveOccupy("AddOccupy"),this.removeOccupy=this.readAddRemoveOccupy("RemoveOccupy"),this.rotates=this.art.getBool("Rotates")}get imageName(){return(this.image||this.rules.imageName)+(this.rules.alternateArcticArt?"A":"")}get cameo(){let e=this.art.getString("Cameo")||qn.MISSING_CAMEO;return e.toLowerCase()}get altCameo(){let e=this.art.getString("AltCameo")||qn.MISSING_CAMEO;return e.toLowerCase()}get useTheaterExtension(){return this.art.getBool("Theater")}readPaletteAndLightingTypes(){this.paletteType=I.Default,this.lightingType=gn.Default,(this.rules instanceof hs?this.rules.noUseTileLandType:void 0)&&(this.paletteType=I.Iso,this.lightingType=gn.Full),this.art.getBool("TerrainPalette")||this.art.getBool("ShouldUseCellDrawer")?this.paletteType=I.Iso:this.art.getBool("AnimPalette")?(this.paletteType=I.Anim,this.lightingType=gn.None):this.art.getString("Palette")&&(this.paletteType=I.Custom,this.customPaletteName=this.art.getString("Palette")),this.art.getBool("AltPalette")&&(this.paletteType=I.Unit),(this.rules instanceof hs||this.rules instanceof os)&&this.rules.wall&&(this.paletteType=I.Unit,this.lightingType=gn.Ambient),(this.rules instanceof ls||this.rules instanceof os)&&this.rules.gate&&(this.paletteType=I.Unit),this.rules instanceof ls&&this.rules.spawnsTiberium&&(this.paletteType=I.Unit,this.lightingType=gn.None),this.rules instanceof hs&&(this.rules.isVeins&&(this.paletteType=I.Unit,this.lightingType=gn.None),this.rules.isVeinholeMonster&&(this.paletteType=I.Unit,this.lightingType=gn.None),this.rules.tiberium&&(this.lightingType=gn.None),this.rules.land===Jt.Railroad&&(this.paletteType=I.Iso,this.lightingType=gn.Full),this.rules.crate&&(this.paletteType=I.Iso,this.lightingType=gn.Full)),this.paletteType===I.Default&&(this.paletteType=qn.getDefaultPalette(this.type)),this.lightingType===gn.Default&&(this.lightingType=qn.getDefaultLighting(this.type))}readRemapability(){this.remapable=qn.getDefaultRemapability(this.type),this.art.getBool("TerrainPalette")||this.art.getBool("AnimPalette")?this.remapable=!1:this.rules instanceof Xi&&this.rules.firersPalette&&(this.remapable=!0)}readFlatness(){let e=!1;this.type===xt.Building||this.type===xt.Animation?e=this.art.getBool("Flat"):this.type===xt.Smudge&&(e=!0),this.rules instanceof hs&&(this.rules.wall||this.rules.crate||this.rules.isARock||(e=!0)),this.flat=e}readRotors(){var i=this.art.getArray("Rotors");if(i.length){let t=[];for(let e=0;e<i.length;++e){var s=this.art.getNumberArray(`Rotor${e+1}Axis`,void 0,[0,1,0]),s=new rs(-s[2],-s[0],s[1]).normalize();t.push({name:i[e],axis:s,speed:this.art.getNumber(`Rotor${e+1}Rate`)||void 0,idleSpeed:this.art.getNumber(`Rotor${e+1}IdleRate`)||void 0})}t.length&&(this.rotors=t)}}readMuzzleFlash(){let e=0,t=`MuzzleFlash${e}`,i=[];for(;this.art.has(t);){var[s,r]=this.art.getNumberArray(t);i.push({x:s,y:r}),e++,t=`MuzzleFlash${e}`}this.muzzleFlash=i.length?i:void 0}readDockingOffsets(){if(this.type===xt.Building){var t=this.rules.numberOfDocks;for(let e=0;e<t;e++){var[i,s,r]=this.art.getNumberArray(`DockingOffset${e}`,/\,\s*/,[0,0,0]);this.dockingOffsets.push(new rs(i,r,s))}}}readAddRemoveOccupy(e){let t=0,i=[];for(;;){var s=this.art.getNumberArray(e+ ++t);if(!s.length)break;i.push(new ks(s[0],s[1]))}return i}get bibShape(){return this.art.getString("BibShape")}get foundation(){let e=this.art.getString("Foundation","1x1");var[t,i]=e.split("x");return{width:parseInt(t,10),height:parseInt(i,10)}}get foundationCenter(){return new ks(Math.floor(this.foundation.width/2-.5),Math.floor(this.foundation.height/2-.5))}getDrawOffset(){if(this.rules instanceof ls&&this.rules.spawnsTiberium)return new ks(0,0);let e=qn.getDefaultDrawOffset(this.type);return this.rules instanceof hs&&this.rules.isARock&&(e.y+=(Os.ISO_TILE_SIZE+1)/2),e}get hasShadow(){return this.art.getBool("Shadow",qn.getDefaultShadow(this.type))&&!this.rules.noShadow}get turretOffset(){return this.art.getNumber("TurretOffset")}get walkFrames(){return this.art.getNumber("WalkFrames")}get firingFrames(){return this.art.getNumber("FiringFrames")}get isFlamingGuy(){return this.art.getBool("IsFlamingGuy")}get runningFrames(){return this.art.getNumber("RunningFrames")}get primaryFireFlh(){return new Ka(this.art.getNumberArray("PrimaryFireFLH"))}get elitePrimaryFireFlh(){var e=this.art.getNumberArray("ElitePrimaryFireFLH");return e.length?new Ka(e):this.primaryFireFlh}get primaryFirePixelOffset(){return this.art.getNumberArray("PrimaryFirePixelOffset")}get secondaryFirePixelOffset(){return this.art.getNumberArray("SecondaryFirePixelOffset")}get secondaryFireFlh(){return new Ka(this.art.getNumberArray("SecondaryFireFLH"))}get eliteSecondaryFireFlh(){var e=this.art.getNumberArray("EliteSecondaryFireFLH");return e.length?new Ka(e):this.secondaryFireFlh}getSpecialWeaponFlh(e){return new Ka(this.art.getNumberArray(`Weapon${e+1}FLH`))}get fireUp(){return this.art.getNumber("FireUp")||this.art.getNumber("DelayedFireDelay")}get isAnimDelayedFire(){return this.art.getBool("IsAnimDelayedFire")}get zShapePointMove(){return this.art.getNumberArray("ZShapePointMove")}get zAdjust(){return this.art.getNumber("ZAdjust")}get trailer(){return this.art.getString("Trailer")}get spawnDelay(){return this.art.getNumber("SpawnDelay",1)}get translucent(){return this.art.getBool("Translucent")}get translucency(){var e=(e=this.art.getNumber("Translucency",0))/25*25;return e/=100}}qn.DEFAULT_LINE_TRAIL_DEC=16,qn.MISSING_CAMEO="xxicon";class Xn{constructor(e,t,i,s){this.rules=e,this.artIni=t,this.mapFile=i,this.logger=s,this.objectArt=new Map,this.parse()}hasObject(e,t){return this.objectArt.get(t)?.has(e)}getObject(e,t){if(!e)throw new Error(`Must specify an art name for type "${xt[t]}"`);var i=this.objectArt.get(t)?.get(e);return i||(this.logger?.debug(`Missing art for object "${e}"`),new qn(t,this.rules.hasObject(e,t)?this.rules.getObject(e,t):new Ci(t,new h(e)),new h(e)))}getAnimation(e){return this.getObject(e,xt.Animation)}getProjectile(e){var t=this.rules.getProjectile(e),i=t.imageName;let s=this.artIni.getSection(i);return s||(this.logger?.debug(`Image ${i} (Projectile: ${e}) has no section in art.ini`),s=new h(i)),qn.factory(t.type,t,this.artIni,s)}getIni(){return this.artIni}parse(){this.rules.allObjectRules.forEach((e,t)=>{let s=new Map;this.objectArt.set(t,s),e.forEach(e=>{var t=this.artIni.getSection(e.imageName),i=this.artIni.getSection(e.name);(t=this.applyUnitMapOverrides(e,this.mapFile,i,t))?(t=qn.factory(e.type,e,this.artIni,t),s.set(e.name,t)):this.logger?.debug(`${xt[e.type]} "${e.name}" has no art section "${e.imageName}"`)})});let e=[[xt.Animation,this.rules.animationNames]];e.forEach(([s,e])=>{let r=new Map;this.objectArt.set(s,r),e.forEach(e=>{var t,i=this.artIni.getSection(e);i?(t=new Ci(s,new h(e)),i=new qn(s,t,i),r.set(e,i)):this.logger?.debug(`${xt[s]} "${e}" has no art section`)})})}applyUnitMapOverrides(e,t,s,r){if([xt.Infantry,xt.Vehicle,xt.Aircraft].includes(e.type)&&!!t?.getSection(e.name)?.getString("Image")&&s){let i=s.clone();r?.entries.forEach((e,t)=>{i.set(t,e)}),r=i,this.logger?.debug(`${xt[e.type]} "${e.name}": `+`Using merged art sections ${e.name} and ${e.imageName}`)}return r}}class Zn{constructor(e){this.rules=e}static factory(e,t){return new this(t.getCountry(e))}get id(){return this.rules.id}get side(){return this.rules.side}get name(){return this.rules.name}isPlayable(){return this.rules.multiplay&&!this.rules.multiplayPassive}hasVeteranUnit(e,t){let i=[];switch(e){case xt.Aircraft:i=this.rules.veteranAircraft;break;case xt.Infantry:i=this.rules.veteranInfantry;break;case xt.Vehicle:i=this.rules.veteranUnits;break;default:throw new Error(`Unsupported object type "${xt[e]}"`)}return i.includes(t)}}class Qn{constructor(e,t){this.target=e,this.player=t,this.type=ss.BuildingEvacuate}}class Yn{constructor(e,t,i){this.building=e,this.evacThreshold=t,this.maxOccupants=i,this.units=[]}isOccupied(){return!!this.units.length}canBeOccupied(){return this.building.healthTrait.health>100*this.evacThreshold}[ua.onDamage](e,t){e.healthTrait.health<=100*this.evacThreshold&&this.evacuate(t)}[zr.onDestroy](e,t,i,s){if(s){for(var r of this.units)t.destroyObject(r,i,!0);this.units=[]}else this.evacuate(t)}getHash(){return G(this.units.map(e=>e.getHash()))}debugGetState(){return{units:this.units.map(e=>e.debugGetState())}}dispose(){this.building=void 0}evacuate(s,r=!1){let a=this.building,n=this.units;if(n.length){let e=new Map;for(var t of n)e.set(t.rules.speedType,(e.get(t.rules.speedType)||[]).concat(t));for(let[t,i]of e){var o,h=new Us(s.map.tiles,s.map.mapBounds,a.tile,a.art.foundation,1,1,e=>0<s.map.terrain.getPassableSpeed(e,t,!1)&&Math.abs(e.z-a.tile.z)<2&&!s.map.terrain.findObstacles({tile:e,onBridge:void 0},i[0]).length).getNextTile();for(o of i){var l=n.indexOf(o);h?(n.splice(l,1),s.unlimboObject(o,h),o.unitOrderTrait.addTask(new Sa(s))):r||(s.destroyObject(o,{player:o.owner}),n.splice(l,1))}}var i=a.owner;n.length||a.isDestroyed||s.changeObjectOwner(a,s.getCivilianPlayer()),s.events.dispatch(new Qn(a,i))}}}class Kn{constructor(){this.facing=0,this.desiredFacing=0}isRotating(){return this.facing!==this.desiredFacing}[Fr.onTick](e){this.desiredFacing!==this.facing&&(e=e.rules.rot,this.facing=br.tick(this.facing,this.desiredFacing,e||Number.POSITIVE_INFINITY).facing)}}class Jn{constructor(e,t){this.target=e,this.status=t,this.type=ss.BuildStatusChange}}class eo{constructor(e){this.target=e,this.type=ss.PowerLow}}class to{constructor(e){this.target=e,this.type=ss.PowerRestore}}class io{constructor(e,t,i){this.target=e,this.power=t,this.drain=i,this.type=ss.PowerChange}}(r=mn=mn||{})[r.Low=0]="Low",r[r.Normal=1]="Normal";class so{constructor(e){this.player=e,this.power=0,this.drain=0,this.level=mn.Normal,this.blackoutFrames=0,this.powerByObject=new Map}isLowPower(){return this.level===mn.Low}setBlackoutFor(e,t){var i=0<this.blackoutFrames;this.blackoutFrames=e,i||this.updateLevel(t)}updateBlackout(e){0<this.blackoutFrames&&(this.blackoutFrames--,this.blackoutFrames<=0&&this.updateLevel(e))}getBlackoutDuration(){return this.blackoutFrames}updateFrom(t,i,s){var r=t.rules.power;if(r){if(r<0)"add"!==i&&"remove"!==i||(this.drain+="add"===i?-r:r);else{let e=0;if("add"===i){var a=Math.ceil(r*t.healthTrait.health/100);this.powerByObject.set(t,a),e=a}else if("update"===i||"remove"===i){a=this.powerByObject.get(t);if(void 0===a)throw new Error("Cannot update power before add.");e="update"===i?(r=Math.ceil(r*t.healthTrait.health/100),this.powerByObject.set(t,r),r-a):(this.powerByObject.delete(t),-a)}this.power+=e}this.updateLevel(s),s.traits.filter(Ds).forEach(e=>{e[Ds.onPowerChange](this.player,s)}),s.events.dispatch(new io(this.player,this.power,this.drain))}}updateLevel(t){var e=this.level;this.level=this.power>=this.drain&&!this.blackoutFrames?mn.Normal:mn.Low,this.level!==e&&(e===mn.Normal&&this.level===mn.Low&&(t.traits.filter(Ds).forEach(e=>{e[Ds.onPowerLow](this.player,t)}),t.events.dispatch(new eo(this.player))),e===mn.Low&&this.level===mn.Normal&&(t.traits.filter(Ds).forEach(e=>{e[Ds.onPowerRestore](this.player,t)}),t.events.dispatch(new to(this.player))))}getHash(){return G([this.power,this.drain])}debugGetState(){return{power:this.power,drain:this.drain}}dispose(){this.player=void 0,this.powerByObject.clear()}}class ro{constructor(e){this.obj=e,this.turnedOn=!0}setTurnedOn(e){this.turnedOn=e}isCharged(){return!!this.obj.isBuilding()&&!!this.obj.overpoweredTrait?.hasChargersToPowerOn()}isPoweredOn(e=!1){return!(!this.obj||!this.turnedOn)&&(!(e||!this.isCharged())||(!this.obj.rules.power&&this.obj.rules.needsEngineer?!this.obj.owner.isNeutral:!!this.obj.owner.powerTrait&&this.obj.owner.powerTrait?.level!==mn.Low))}dispose(){this.obj=void 0}}class ao{constructor(){this.listeners=new Set}subscribe(e){this.listeners.add(e)}subscribeOnce(i){let s=(e,t)=>{i(e,t),this.unsubscribe(s),s=void 0};this.subscribe(s)}unsubscribe(e){this.listeners.delete(e)}dispatch(t,i){this.listeners.forEach(e=>e(i,t))}asEvent(){return this}}(r=fn=fn||{})[r.Structures=0]="Structures",r[r.Armory=1]="Armory",r[r.Infantry=2]="Infantry",r[r.Vehicles=3]="Vehicles",r[r.Aircrafts=4]="Aircrafts",r[r.Ships=5]="Ships",(r=yn=yn||{})[r.Idle=0]="Idle",r[r.Active=1]="Active",r[r.OnHold=2]="OnHold",r[r.Ready=3]="Ready";class no{constructor(e,t,i){this.type=e,this._maxSize=t,this.maxItemQuantity=i,this.items=[],this.size=0,this._status=yn.Idle,this._onUpdate=new ao}get onUpdate(){return this._onUpdate.asEvent()}get status(){return this._status}set status(e){var t=this._status;(this._status=e)!==t&&this._onUpdate.dispatch(this)}get maxSize(){return this._maxSize}set maxSize(e){var t=this.size;this.size=Math.min(e,this.size);let i=0,s=0;for(;i<=this.size&&s<this.items.length;){let e=this.items[s];i+=e.quantity,i>this.size&&(e.quantity-=i-this.size),0<e.quantity&&s++}this._maxSize=e,this.items[s]&&this.items.splice(s),t!==this.size&&(this.size||(this._status=yn.Idle),this._onUpdate.dispatch(this))}get currentSize(){return this.size}find(t){return this.items.filter(e=>e.rules===t)}getFirst(){return this.items[0]}getAll(){return[...this.items]}push(e,t,i){t=Math.min(this.maxSize-this.size,t);var s=this.find(e).reduce((e,t)=>e+t.quantity,0);t=Math.min(this.maxItemQuantity-s,t),this.items[this.items.length-1]?.rules===e?this.items[this.items.length-1].quantity+=t:this.items.push({rules:e,quantity:t,creditsEach:i,creditsSpent:0,creditsSpentLeftover:0,progress:0}),this.size+=t,t&&(this._status===yn.Idle&&(this._status=yn.Active),this._onUpdate.dispatch(this))}pop(e,t){this.remove(e,t,!1)}shift(e,t){this.remove(e,t,!0)}remove(e,t,i){let s=this.find(e);if(!s.length)throw new Error(`Can't remove non-existent item ${e.name} from queue ${fn[this.type]}`);var r;if(s.reduce((e,t)=>e+t.quantity,0)<t)throw new Error(`Attempted to remove a quantity larger than the one in queue (${e.name})`);let a=t;for(;0<a;){let e=i?s.shift():s.pop();e.quantity<=a?(r=this.getFirst()===e,this.items.splice(this.items.indexOf(e),1),r&&(this._status=yn.Active),a-=e.quantity):(e.quantity-=a,a=0)}this.size-=t,t&&(this.size||(this._status=yn.Idle),this._onUpdate.dispatch(this))}notifyUpdated(){this._onUpdate.dispatch(this)}}const oo=e=>void 0!==e.position;class ho{constructor(e,t){this.tiles=e,this.tileOccupation=t}hasLineOfSight(t,i,s){var r=s.warhead.rules.wall||!s.projectileRules.subjectToWalls,a=s.projectileRules.subjectToCliffs,n=s.rules.spawner;let o=0,h=!1;if(!r||a||n){var l,c,s=oo(t)?t.tile:t,i=oo(i)?i.isBuilding()?i.centerTile:i.tile:i;let e=s.z;a&&oo(t)&&t.isUnit()&&t.onBridge&&(e+=this.tileOccupation.getBridgeOnTile(s)?.tileElevation??0);for({x:l,y:c}of Fa(s.rx,s.ry,i.rx,i.ry)){var u=this.tiles.getByMapCoords(l,c);if(!u)return!1;if(!r&&u.landType===Jt.Wall)return!1;if(a)if(u.landType===Jt.Cliff){if(u.z>e)return!1;h=!0}else{if(u.z>e&&h)return!1;h=!1}if(n&&o<2&&this.tileOccupation.getBridgeOnTile(u)?.isHighBridge())return!1;o++}}return!0}}class lo extends ka{constructor(e,t,i,s){super(e,t instanceof Ba?t.isBuilding()?t.centerTile:t.tile:t,i,{pathFinderIgnoredBlockers:t instanceof Ba&&0<s.range?[t]:void 0}),this.target=t,this.weapon=s,this.recalcMinRange=!0,this.cancelRequested=!1,this.bomberInitialLock=!1,this.rangeHelper=new As(e.map.tileOccupation),this.losHelper=new ho(e.map.tiles,e.map.tileOccupation)}onStart(i){let e=this.target,s=this.game.map;if(e instanceof Ba&&e.isBuilding()&&i.rules.movementZone!==ri.Fly){let t=e.tile;var r=e instanceof Ba?e.getFoundation():{width:1,height:1},r=new Us(s.tiles,s.mapBounds,t,r,1,5,e=>0<s.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&Math.abs(e.z-t.z)<2).getNextTile();r&&this.rangeHelper.tileDistance(e,r)>Math.SQRT2&&this.updateTarget(r,!1)}this.bomberInitialLock=this.isCloseEnoughToDest(i,i.tile),super.onStart(i)}cancel(){this.bomberManeuverTile?this.cancelRequested=!0:super.cancel()}shouldAirStrafe(e){return e.rules.movementZone===ri.Fly&&e.rules.locomotor===si.Aircraft&&e.rules.fighter&&1<this.weapon.projectileRules.iniRot}isBombingRun(e){return e.rules.movementZone===ri.Fly&&e.rules.locomotor===si.Aircraft&&this.weapon.projectileRules.iniRot<=1}isAirStrafeCloseEnough(e){return this.rangeHelper.tileDistance(e,this.targetTile)<Math.min(this.weapon.range,2)}bomberCanReturn(e){return!this.bomberManeuverTile||this.rangeHelper.tileDistance(e,this.bomberManeuverTile)<=1}findStrafeDestination(t,i){let e=new Ta(this.game.map.tiles,this.game.map.mapBounds,i,this.weapon.range,this.game,e=>this.rangeHelper.isInWeaponRange(t,i,this.weapon,this.game.rules,e));return e.getNextTile()}hasReachedDestination(e){return super.hasReachedDestination(e)||this.canStopAtTile(e,e.tile,e.onBridge)}canStopAtTile(t,e,i){if(t.zone!==vs.Air&&this.target instanceof Ba&&this.game.map.tileOccupation.isTileOccupiedBy(e,this.target)&&(!this.target.isUnit()||this.target.tile===e&&this.target.moveTrait.moveState!==qr.Moving))return!1;if(t.zone!==vs.Air){if(!super.canStopAtTile(t,e,i))return!1}else if(this.game.map.tileOccupation.getAirObjectsOnTile(e).filter(e=>e.isUnit()&&e.moveTrait.moveState!==qr.Moving&&e!==t).length)return!1;return!(this.isBombingRun(t)&&!this.bomberCanReturn(e))&&(!!this.isCancelling()||this.isCloseEnoughToDest(t,e))}isCloseEnoughToDest(e,t){if(e.rules.balloonHover&&!e.rules.hoverAttack)return this.rangeHelper.isInTileRange(t,this.target,0,0);if(this.weapon.rules.cellRangefinding||!e.isInfantry())return this.rangeHelper.isInWeaponRange(e,this.target,this.weapon,this.game.rules,t)&&this.losHelper.hasLineOfSight(t,this.target,this.weapon);var i=e.zone===vs.Air?e.position.computeSubCellOffset(e.position.desiredSubCell):e.position.getTileOffset(),{minRange:s,range:r}=this.rangeHelper.computeWeaponRangeVsTarget(t,this.target,this.weapon,this.game.rules),i=Os.tile3dToWorld(t.rx+i.x/Os.LEPTONS_PER_TILE,t.ry+i.y/Os.LEPTONS_PER_TILE,t.z+e.position.tileElevation);return(e.isUnit()&&e.rules.movementZone===ri.Fly?this.rangeHelper.isInRange2(i,this.target,s,r):this.rangeHelper.isInRange3(i,this.target,s,r))&&this.losHelper.hasLineOfSight(t,this.target,this.weapon)}findRelocationTile(t,i,s){if(s.rules.movementZone!==ri.Fly)return super.findRelocationTile(t,i,s);{i=this.game.map;let e=new Ta(i.tiles,i.mapBounds,t,1,this.game,e=>this.isCancelling()||this.isCloseEnoughToDest(s,e));return e.getNextTile()}}retarget(e,t){var i=e instanceof Ba?e.isBuilding()?e.centerTile:e.tile:e;this.bomberManeuverTile?this.bomberQueuedTargetTile=i:(this.updateTarget(i,t),this.recalcMinRange=!0),this.target=e,this.options?.ignoredBlockers&&(this.options.ignoredBlockers=e instanceof Ba?[e]:void 0),this.options??(this.options={}),this.options.pathFinderIgnoredBlockers=e instanceof Ba?[e]:void 0}onTick(r){if(this.recalcMinRange){this.recalcMinRange=!1;var e=this.findMinRangeRelocationTile(r,this.targetTile);if(e!==this.targetTile){if(!e)return this.cancel(),!1;this.updateTarget(e,!!e.onBridgeLandType)}}if(this.shouldAirStrafe(r)&&!this.isCancelling()&&(this.updateTarget(this.target instanceof Ba?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target,!1),!this.isAirStrafeCloseEnough(r)||(a=this.findStrafeDestination(r,this.targetTile))&&this.updateTarget(a,!1)),this.isBombingRun(r)&&!this.isCancelling()&&(!r.ammo||this.weapon.getBurstsFired()||this.bomberInitialLock)&&!this.bomberManeuverTile){this.bomberInitialLock=!1;let e=r.position.getMapPosition();var a=this.target instanceof Ba?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target;let t=new ks(a.rx+.5,a.ry+.5).clone().multiplyScalar(Os.LEPTONS_PER_TILE).sub(e),i=t.length();i||(t.copy(br.toMapCoords(r.direction)),i=Number.EPSILON);let s=e.clone().add(t.setLength(i+7*Os.LEPTONS_PER_TILE));a=s.multiplyScalar(1/Os.LEPTONS_PER_TILE).floor(),a=Fa(a.x,a.y,r.tile.rx,r.tile.ry);if(!a.length)throw new Error("Bresenham returned no tiles");a=a[0];this.bomberManeuverTile=this.game.map.tiles.getByMapCoords(a.x,a.y)??this.game.map.tiles.getPlaceholderTile(a.x,a.y),this.options.allowOutOfBoundsTarget=!0,this.updateTarget(this.bomberManeuverTile,!1)}return this.bomberManeuverTile&&this.bomberCanReturn(r.tile)&&(this.bomberManeuverTile=void 0,this.bomberQueuedTargetTile&&(this.updateTarget(this.bomberQueuedTargetTile,!1),this.recalcMinRange=!0,this.bomberQueuedTargetTile=void 0)),this.cancelRequested&&(this.bomberManeuverTile||(this.cancelRequested=!1,this.cancel())),!!(this.isBombingRun(r)&&this.isCancelling()&&this.forceCancel(r))||super.onTick(r)}forceCancel(e){return!this.bomberManeuverTile&&super.forceCancel(e)}findMinRangeRelocationTile(e,t){var{minRange:i,range:s}=this.rangeHelper.computeWeaponRangeVsTarget(e,this.target,this.weapon,this.game.rules);return e.rules.locomotor===si.Chrono?this.rangeHelper.isInRange(e,this.target,s-1,s,this.weapon.rules.cellRangefinding)?t:this.findTileInRange(e,t,s-1,2*s)??t:this.rangeHelper.isInRange(e,this.target,i,Number.POSITIVE_INFINITY,this.weapon.rules.cellRangefinding)?t:this.findTileInRange(e,t,2*i,s-i)}findTileInRange(t,e,i,s){let r=this.game.map;var a,i=new ks(t.tile.rx-e.rx,t.tile.ry-e.ry).setLength(i).floor().add(new ks(e.rx,e.ry));let n;for(a of Fa(i.x,i.y,e.rx,e.ry))if(n=r.tiles.getByMapCoords(a.x,a.y),n)break;if(n){let e=new Us(r.tiles,r.mapBounds,n,{width:1,height:1},0,s,e=>this.rangeHelper.isInWeaponRange(t,this.target,this.weapon,this.game.rules,e)&&this.losHelper.hasLineOfSight(e,this.target,this.weapon)&&0<r.terrain.getPassableSpeed(e,t.rules.speedType,!!e.onBridgeLandType)&&!r.terrain.findObstacles({tile:e,onBridge:!!e.onBridgeLandType},t).length);return e.getNextTile()}}}class co{tick(e,t){this.tickChildren(e,t)}startTask(e,t){if(e.status!==Fs.NotStarted)throw new Error(`Attempted to start a task with status ${e.status}`);e.status=Fs.Running,e.onStart(t)}tickTask(e,t){let i=this.tickChildren(e.children,t);var s=e.children.find(e=>e.blocking);if(!i&&s)return!1;if(!t.isSpawned)return!1;if(e.status===Fs.NotStarted)throw new Error("Attempted tick on a non-started task");if(e.isRunning()||e.isCancelling()){var r=e.isCancelling(),a=!!e.waitingForChildrenToFinish||e.onTick(t);e.children.length&&!s&&a&&(i=e.children.every(e=>e.status===Fs.Cancelled||e.status===Fs.Finished),e.waitingForChildrenToFinish=!i);a=a&&i;return a&&(e.onEnd(t),e.status=r?Fs.Cancelled:Fs.Finished),a}return!0}tickChildren(s,r){let a=!0;if(s.length){let t=new Set,i;for(;r.isSpawned&&(i=s.find(e=>!t.has(e)));){let e;if(i.status===Fs.NotStarted&&this.startTask(i,r),i.status===Fs.Running||i.status===Fs.Cancelling)e=!0===this.tickTask(i,r);else{if(i.status!==Fs.Cancelled)throw new Error(`Unhandled task status ${Fs[i.status]}`);e=!0}if(e){var n=s.indexOf(i);-1!==n&&s.splice(n,1)}else{if(a=!1,i.blocking)break;t.add(i)}}}return a}}class uo{constructor(e,t,i){this.tileOccupation=i,this.isOre=!1,e?e.isOverlay()&&e.isBridge()?(this.bridge=e,this.tile=t):e.isOverlay()&&e.isTiberium()?(this.isOre=!0,this.tile=e.tile):(this.obj=e,this.tile=e.isBuilding()?e.centerTile:e.tile):(t.landType===Jt.Tiberium&&(this.isOre=!0),this.tile=t)}equals(e){return this.obj===e.obj&&this.tile===e.tile&&this.bridge===e.bridge&&this.isOre===e.isOre}getWorldCoords(){return this.obj?this.obj.position.worldPosition:Os.tile3dToWorld(this.tile.rx+.5,this.tile.ry+.5,this.tile.z+(this.bridge?.tileElevation??0))}isBridge(){return!this.obj&&!!this.bridge}getBridge(){return this.bridge||(this.obj?.isUnit()&&this.obj.onBridge?this.tileOccupation.getBridgeOnTile(this.obj.tile):void 0)}}(r=wn=wn||{})[r.Idle=0]="Idle",r[r.CheckRange=1]="CheckRange",r[r.PrepareToFire=2]="PrepareToFire",r[r.FireUp=3]="FireUp",r[r.Firing=4]="Firing",r[r.JustFired=5]="JustFired";class po{constructor(e,t){this.disabled=!1,this.attackState=wn.Idle,this.passiveScanCooldownTicks=0,this.taskRunner=new co,this.distributedFireHistory=new Map,this.rangeHelper=new As(t),this.losHelper=new ho(e,t)}isIdle(){return this.attackState===wn.Idle}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}isOnCooldown(e){let t=[e.primaryWeapon,e.secondaryWeapon],i=e.armedTrait?.getDeployFireWeapon();return i?.rules.areaFire&&!i.rules.fireOnce&&(t=t.filter(e=>e!==i)),t.some(e=>0<(e?.getCooldownTicks()??0))}expirePassiveScanCooldown(){this.passiveScanCooldownTicks=0}increasePassiveScanCooldown(e){this.passiveScanCooldownTicks+=e}cancelOpportunityFire(){this.opportunityFireTask?.cancel()}selectDefaultWeapon(e){let i;if((e.isInfantry()||e.isVehicle())&&e.rules.deployFire){let t=e.armedTrait?.getDeployFireWeapon();i=e.deployerTrait?.isDeployed()?t&&!t.rules.areaFire?t:void 0:[e.primaryWeapon,e.secondaryWeapon].find(e=>e!==t)}else i=e.isBuilding()&&e.garrisonTrait?e.garrisonTrait.isOccupied()?e.owner.country.side===Zt.GDI?e.primaryWeapon:e.secondaryWeapon??e.primaryWeapon:void 0:e.isBuilding()&&e.overpoweredTrait?e.overpoweredTrait.getWeapon():e.primaryWeapon;return i}selectWeaponVersus(e,t,i,s=!1,r=!1){var a=t.tile;const n=t instanceof uo?t.obj:t;t=this.getAvailableWeapons(e,r,n?.isOverlay()||s&&!n);return this.selectWeaponFromList(e,n,a,t,i,s,r,!1)}selectWeaponFromList(e,t,i,s,r,a,n,o){if((!t?.isInfantry()&&!t?.isVehicle()||!t.disguiseTrait||this.canAttackThroughDisguise(e,t,t.disguiseTrait,r,a,n,o))&&(t?.isBuilding()&&t.overpoweredTrait&&t.owner===e.owner&&s.find(e=>e.warhead.rules.electricAssault)&&(s=s.filter(e=>e.warhead.rules.electricAssault)),!(n&&t?.isAircraft()&&t.missileSpawnTrait&&t.zone!==vs.Air))){var h=t?.isTechno()?t.rules.armor:void 0;for(const l of s)if(l.targeting.canTarget(t,i,r,a,n)&&(void 0===h||this.checkArmor(l.warhead.rules,h,n)))return l}}getAvailableWeapons(e,t,i){let s;var r;return s=(e.isInfantry()||e.isVehicle())&&e.rules.deployFire&&e.armedTrait?(r=e.armedTrait.getDeployFireWeapon(),[e.deployerTrait?.isDeployed()?r.rules.areaFire?void 0:r:r===e.secondaryWeapon?e.primaryWeapon:e.secondaryWeapon]):e.isBuilding()&&e.garrisonTrait?e.garrisonTrait.isOccupied()?[e.owner.country.side===Zt.GDI?e.primaryWeapon:e.secondaryWeapon??e.primaryWeapon]:[]:e.isBuilding()&&e.overpoweredTrait?[e.overpoweredTrait.getWeapon()]:i||t?[e.primaryWeapon,!i&&t&&e.secondaryWeapon?e.secondaryWeapon:void 0]:[e.primaryWeapon,e.secondaryWeapon],s.filter(e=>e&&!e.rules.neverUse)}canAttackThroughDisguise(e,t,i,s,r,a,n){if(!r&&i.hasTerrainDisguise()&&!s.areFriendly(e,t)&&!e.owner.sharedDetectDisguiseTrait?.has(t))return!1;if(a){if(n&&t.moveTrait.isIdle()&&!e.rules.detectDisguise&&!e.owner.sharedDetectDisguiseTrait?.has(t)&&!s.areFriendly(t,e))return!1;i=i.getDisguise();if(i?.owner&&!e.rules.detectDisguise&&!e.owner.sharedDetectDisguiseTrait?.has(t)&&(i.owner===e.owner||s.alliances.areAllied(e.owner,i.owner)))return!1}return!0}checkArmor(e,t,i){var s=e.ivanBomb||e.bombDisarm||e.nukeMaker?1:e.verses.get(t);return void 0===s?(console.warn(`Unhandled ArmorType ${ai[t]} in warhead ${e.name} verses`),!1):!(100*s<=(i?1:0))}createAttackTask(e,t,i,s,r){return new go(e,e.createTarget(t,i),s,r)}[Fr.onTick](a,n){if(!this.isDisabled()){if(this.opportunityFireTask&&(!a.unitOrderTrait.hasTasks()||a.isUnit()&&!a.unitOrderTrait.getTasks()[0].preventOpportunityFire||(a.unitOrderTrait.getTasks()[0]instanceof go?this.opportunityFireTask=void 0:this.opportunityFireTask.cancel()),this.opportunityFireTask&&(c=[this.opportunityFireTask],this.taskRunner.tick(c,a),c.length||(this.opportunityFireTask=void 0))),!this.opportunityFireTask&&this.retaliateTarget){var o=this.retaliateTarget;this.retaliateTarget=void 0;let e;!a.unitOrderTrait.hasTasks()&&n.isValidTarget(o)&&(e=this.selectWeaponVersus(a,o,n,!1))&&a.unitOrderTrait.addTask(this.createAttackTask(n,o,o.tile,e,{holdGround:a.rules.movementZone===ri.Fly}))}if(!this.opportunityFireTask&&this.shouldPassiveAcquire(a))if(0<this.passiveScanCooldownTicks)this.passiveScanCooldownTicks--;else{this.passiveScanCooldownTicks=a.guardMode?n.rules.general.guardAreaTargetingDelay:n.rules.general.normalTargetingDelay;let e=this.selectDefaultWeapon(a);var h,l,c=a.unitOrderTrait.hasTasks();let t=void 0,i,s;!c&&a.guardMode&&e&&a.owner.isCombatant()&&(t=a.armedTrait?.computeGuardScanRange(e),i=a.guardArea?.tile,s=50);let r=!1;!e||(o=this.scanForTarget(a,e,n,t,i)).target&&({target:h,weapon:l}=o,h=this.createAttackTask(n,h,h.tile,l,{holdGround:c||!a.guardMode,disallowTurning:c,leashTiles:s,passive:!0}),c?this.opportunityFireTask=h:a.unitOrderTrait.addTask(h),r=!0,c||!a.guardMode||a.guardArea||(a.guardArea={tile:a.tile,onBridge:!!a.isUnit()&&a.onBridge})),r||c||!a.secondaryWeapon?.warhead.rules.electricAssault||(e=a.secondaryWeapon,(l=this.scanForTarget(a,e,n,void 0,void 0,!0)).target&&({target:h,weapon:l}=l,l=this.createAttackTask(n,h,h.tile,l,{passive:!0}),a.unitOrderTrait.addTask(l),r=!0)),!r&&!c&&a.guardArea&&a.isUnit()&&a.moveTrait&&!a.moveTrait.isDisabled()&&a.guardArea.tile!==a.tile&&a.unitOrderTrait.addTasks(new ka(n,a.guardArea.tile,a.guardArea.onBridge),new ma(()=>{[Xr.Success,Xr.CloseEnough].includes(a.moveTrait.lastMoveResult)||a.resetGuardModeToIdle(),a.guardArea=void 0}))}}}[ua.onDamage](e,t,i,s){this.isDisabled()||!this.retaliateTarget&&!this.opportunityFireTask&&s&&s.obj&&s.weapon&&this.shouldRetaliate(e,t,i,s.obj,s.weapon.warhead)&&(this.retaliateTarget=s.obj)}[Wr.onBeforeTeleport](e,t,i,s){s||(this.attackState=wn.Idle,this.currentTarget=void 0,this.retaliateTarget=void 0,this.opportunityFireTask=void 0)}shouldPassiveAcquire(e){if(!e.owner.isCombatant()&&e.rules.needsEngineer||!e.rules.canPassiveAquire||!e.primaryWeapon)return!1;if(e.mindControllerTrait?.isAtCapacity())return!1;var t=e.rules.opportunityFire||e.rules.balloonHover&&e.unitOrderTrait.getCurrentTask()?.isAttackMove;if(e.isUnit()&&t){if(e.unitOrderTrait.hasTasks()&&e.unitOrderTrait.getTasks()[0].preventOpportunityFire)return!1}else if(e.unitOrderTrait.hasTasks())return!1;return!0}shouldRetaliate(e,t,i,s,r){if(i<1||t.areFriendly(e,s)||!e.rules.canRetaliate||!e.primaryWeapon||r.rules.temporal||s.rules.missileSpawn||e.unitOrderTrait.hasTasks()||!t.isValidTarget(s)||(s.isInfantry()||s.isVehicle())&&s.disguiseTrait&&!e.rules.detectDisguise||e.mindControllerTrait?.isAtCapacity())return!1;t=this.selectWeaponVersus(e,s,t,!1);return!(!t||(e.isBuilding()||s.isBuilding()?this.rangeHelper.tileDistance(e,s):this.rangeHelper.distance2(e,s)/Os.LEPTONS_PER_TILE)>Math.max(t.range,e.sight))}scanForTarget(e,t,i,s,r,a=!1){let n={},o=Number.NEGATIVE_INFINITY;var h=this.getAvailableWeapons(e,!0,!1),t=s??(e.rules.guardRange||t.range)+1+3+i.rules.elevationModel.bonusCap+(t.projectileRules.isAntiAir?e.rules.airRangeBonus:0);for(const u of this.scanTechnosAround(e,t,i)){var l,c=this.selectWeaponFromList(e,u,u.tile,h,i,!1,!0,!0);c&&this.canPassiveAcquire(u,i)&&i.isValidTarget(u)&&(s?this.rangeHelper.isInRange(e,u,c.minRange,s,c.rules.cellRangefinding)&&(!r||this.rangeHelper.isInRange2(r,u,0,s)):this.rangeHelper.isInWeaponRange(e,u,c,i.rules))&&(a||this.losHelper.hasLineOfSight(e,u,c))&&(l=this.rangeHelper.distance3(e,u)/Os.LEPTONS_PER_TILE,(l=this.computeThreat(u,e,c,l,i.rules.general.threat))>o&&(n={target:u,weapon:c},o=l))}return n.target&&e.rules.distributedFire&&this.updateDistributedFireHistory(n),n}scanTechnosAround(e,t,i){var s=e.getFoundation();const r=new ks(e.tile.rx,e.tile.ry),a=new ks(e.tile.rx+s.width-1,e.tile.ry+s.height-1);r.addScalar(-t),a.addScalar(t);t=new jn(r,a);return i.map.technosByTile.queryRange(t)}canPassiveAcquire(e,t){return!e.owner.isNeutral&&!e.rules.civilian&&!e.rules.insignificant&&(1<e.rules.threatPosed||0<e.rules.specialThreatValue&&!e.isBuilding()||e.rules.harvester||e.name===t.rules.general.paradrop.paradropPlane)}computeThreat(e,t,i,s,r){let a=[e.primaryWeapon,e.secondaryWeapon].filter(ja).map(e=>e.warhead.rules.verses.get(t.rules.armor)??0).reduce((e,t)=>Math.max(e,t),0)*r.targetEffectivenessCoefficientDefault;return e.attackTrait?.currentTarget?.obj===t&&(a*=-1),a+=e.rules.specialThreatValue*r.targetSpecialThreatCoefficientDefault,a+=(i.warhead.rules.verses.get(e.rules.armor)??0)*r.myEffectivenessCoefficientDefault,a+=e.healthTrait.health/100*r.targetStrengthCoefficientDefault,a+=s*r.targetDistanceCoefficientDefault,t.rules.distributedFire&&(a-=1e6*(this.distributedFireHistory.get(e)??0)),t.rules.vhpScan===ci.Strong&&e.healthTrait.getProjectedHitPoints()<=0&&(a-=1e6),a}updateDistributedFireHistory(e){if(50!==this.distributedFireHistory.get(e.target)){for(var[t,i]of this.distributedFireHistory)i--,i<=0?this.distributedFireHistory.delete(t):this.distributedFireHistory.set(t,i);this.distributedFireHistory.set(e.target,50)}}dispose(){this.distributedFireHistory.clear()}}class go extends Gs{constructor(e,t,i,s={}){super(),this.game=e,this.target=t,this.weapon=i,this.options=s,this.moveExecuted=!1,this.moveAttempts=0,this.rangeCheckCooldown=0,this.lastInRangeTargetPosition=new rs,this.lastInRangeSelfPosition=new rs,this.initialIndirectTarget=!1,this.forceDropTarget=!1,this.rangeHelper=new As(e.map.tileOccupation),this.losHelper=new ho(e.map.tiles,e.map.tileOccupation),this.targetLinesConfig={pathNodes:[]},this.updateTargetLines(this.target,!0)}duplicate(){return new go(this.game,this.target,this.weapon,this.options)}getWeapon(){return this.weapon}setWeapon(e){this.weapon=e}setForceAttack(e){this.options.force=e}requestTargetUpdate(e){this.target.equals(e)||(this.needsTargetUpdate=e)}onTargetChange(e){let t=e.attackTrait,i=this.target;t.currentTarget=i,this.lastValidTargetPosition=i.obj?{tile:i.tile,onBridge:i.getBridge()}:void 0,this.initialTargetOwner=i.obj?.isTechno()?i.obj.owner:void 0,this.initialIndirectTarget=!i.obj&&this.game.map.tileOccupation.getObjectsOnTile(i.tile).some(e=>e.isOverlay()&&!e.isBridgePlaceholder()||e.isTerrain()),this.updateTargetLines(i,!0)}updateTargetLines(e,t){this.targetLinesConfig.target=e.obj,this.targetLinesConfig.pathNodes=e.obj?[]:[{tile:e.tile,onBridge:e.getBridge()}],this.targetLinesConfig.isAttack=t}onStart(t){if(!t.attackTrait)throw new Error(`Object ${t.name} has no attack trait`);if(0!==t.ammo){let e=this.game.map.tileOccupation;var i,s;t.attackTrait.attackState=wn.CheckRange,this.onTargetChange(t),this.initialSelfPosition={tile:t.tile,onBridge:t.isUnit()&&t.onBridge?e.getBridgeOnTile(t.tile):void 0},this.weapon.rules.limboLaunch&&t.isUnit()&&!this.target.obj&&(this.forceDropTarget=!0,{reachable:i,fallback:s}=this.findReachableMeleePosition(this.target.tile,!!this.target.getBridge(),{width:1,height:1},t),!i&&s&&(this.lastValidTargetPosition=s,this.updateTargetLines(this.game.createTarget(s.onBridge,s.tile),!1))),this.weapon.rules.limboLaunch&&this.target.obj?.isTechno()&&t.isUnit()&&!this.rangeHelper.isInWeaponRange(t,this.target.obj,this.weapon,this.game.rules)&&({reachable:i,fallback:s}=this.findReachableMeleePosition(this.target.obj.tile,this.target.obj.isUnit()&&this.target.obj.onBridge,this.target.obj.getFoundation(),t),i||(1<(t.unitOrderTrait.waypointPath?.waypoints?.length??0)?this.cancel():(this.forceDropTarget=!0,s&&(this.lastValidTargetPosition=s,this.updateTargetLines(this.game.createTarget(s.onBridge,s.tile),!1))))),this.rangeHelper.isInWeaponRange(t,this.target.obj??this.target.tile,this.weapon,this.game.rules)&&t.isUnit()&&t.rules.movementZone===ri.Fly&&t.zone!==vs.Air&&(t.rules.hoverAttack||t.isAircraft())&&this.children.push(new ka(this.game,t.tile,!1).setCancellable(!1))}else this.cancel()}findReachableMeleePosition(s,e,t,r){let i=this.game.map,a=i.tileOccupation,n=e?a.getBridgeOnTile(s):void 0,o=new Xs(i),h=r.rules.movementZone===ri.Fly,l=(e,t)=>h||0<i.terrain.getPassableSpeed(e,r.rules.speedType,!!t)&&o.isEligibleTile(e,t,n,s)&&!i.terrain.findObstacles({tile:e,onBridge:t},r).length,c,u=new Us(i.tiles,i.mapBounds,s,t,1,Math.ceil(this.weapon.rules.range),e=>{let t=!1;var i;return l(e,void 0)&&(c=c??{tile:e,onBridge:void 0},t=!0),void 0!==e.onBridgeLandType&&(i=a.getBridgeOnTile(e),l(e,i)&&(c=c??{tile:e,onBridge:i},t=!0)),!!t&&this.rangeHelper.isInWeaponRange(r,s,this.weapon,this.game.rules,e)});return{reachable:u.getNextTile(),fallback:c}}onEnd(e){e.isVehicle()&&e.turretTrait&&(e.turretTrait.desiredFacing=e.direction),e.attackTrait.attackState=wn.Idle,e.attackTrait.currentTarget=void 0;var t=this.game.rules.general.prism.type;e.isBuilding()&&e.name===t&&this.weapon.type!==hi.Secondary&&this.countSupportBeamsAndFireDownTowers(e,t),this.weapon.rules.limboLaunch&&e.attackTrait.expirePassiveScanCooldown(),(e.isInfantry()||e.isVehicle())&&(e.isFiring=!1),this.weapon.hasBurstsLeft()&&this.weapon.resetBursts()}forceCancel(t){if(t.rules.movementZone!==ri.Fly)return!1;if(!this.cancellable||this.children.some(e=>!e.cancellable))return!1;if(this.status===Fs.Running||this.status===Fs.Cancelling){if(this.children.filter(e=>e instanceof ka).some(e=>!e.forceCancel(t)))return!1;this.onEnd(t),(t.isInfantry()||t.isVehicle())&&(t.isFiring=!1)}return this.status=Fs.Cancelled,!0}onTick(i){let s=i.attackTrait;(i.isInfantry()||i.isVehicle())&&s.attackState!==wn.Firing&&(i.isFiring=!1);let r=this.target.obj,a=this.children.find(e=>e instanceof lo);if(this.isCancelling()&&s.attackState!==wn.FireUp)return!i.airSpawnTrait?.isLaunchingMissiles()&&(a?.cancel(),!0);let n=!1;if(s.attackState===wn.FireUp){if(s.isDisabled())return!0;s.attackState=wn.Firing,n=!0}if(s.attackState===wn.Firing){if(this.initialIndirectTarget&&!this.game.map.getObjectsOnTile(this.target.tile).find(e=>e.isOverlay()&&!e.isBridgePlaceholder()||e.isTerrain()))return this.cancel(),this.onTick(i);if(n){var o=this.target.obj||this.target.tile;if(!this.game.isValidTarget(this.target.obj)||this.shouldDropTarget(this.target.obj)||!this.weapon.targeting.canTarget(this.target.obj,this.target.tile,this.game,!!this.options.force,!!this.options.passive)||!this.rangeHelper.isInWeaponRange(i,o,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(i,o,this.weapon))return s.attackState=wn.CheckRange,this.onTick(i)}if(this.weapon.rules.limboLaunch){if((r?.isVehicle()||r?.isAircraft())&&r.parasiteableTrait?.isInfested())return!0;if(i.rules.movementZone!==ri.Fly&&r?.isUnit()&&r.zone===vs.Air)return!0}if(this.target.tile.onBridgeLandType&&i.tile.onBridgeLandType&&i.isUnit()&&(this.game.map.tileOccupation.getBridgeOnTile(this.target.tile)?.isHighBridge()||this.game.map.tileOccupation.getBridgeOnTile(i.tile)?.isHighBridge()))if((r?r.isUnit()&&(r.zone===vs.Air||r.onBridge):this.target.isBridge())!==(i.zone===vs.Air||i.onBridge)&&this.game.map.bridges.findHighBridgeBoundary(i.tile)?.tile===this.game.map.bridges.findHighBridgeBoundary(this.target.tile)?.tile)return!0;let e=1;o=this.game.rules.general.prism.type;if(i.isBuilding()&&i.name===o&&this.weapon.type!==hi.Secondary&&(o=this.countSupportBeamsAndFireDownTowers(i,o),e=1+o*this.game.rules.general.prism.supportModifier),this.weapon.rules.spawner&&(i.isVehicle()||i.isAircraft())&&i.parasiteableTrait?.isParalyzed())return!0;if(0===i.ammo)return i.isAircraft()&&(i.rules.fighter||i.rules.spawned)&&a?.cancel(),!0;let t=!1;if(this.weapon.rules.limboLaunch&&a){if(!a.forceCancel(i))return!1;i.moveTrait.lastTargetOffset=void 0,i.moveTrait.lastVelocity=void 0,t=!0}return(this.weapon.fire(this.target,this.game,e),t)?!0:!!this.weapon.rules.fireOnce||(!(!this.options.passive||!i.rules.distributedFire)||(s.attackState=wn.JustFired,!1))}if(s.attackState===wn.JustFired)return s.attackState=wn.PrepareToFire,this.onTick(i);this.needsTargetUpdate&&(this.target=this.needsTargetUpdate,r=this.target.obj,this.needsTargetUpdate=void 0,this.onTargetChange(i),r||a?.retarget(this.target.tile,!!this.target.getBridge())),r?.isTechno()&&r.replacedBy&&(h=this.game.createTarget(r.replacedBy,r.replacedBy.tile),this.target=h,r=r.replacedBy,this.onTargetChange(i));let t=this.game.isValidTarget(r)&&!this.shouldDropTarget(r);if(t){let e=this.weapon.targeting.canTarget(r,this.target.tile,this.game,!!this.options.force,!!this.options.passive);if(!e||!i.armedTrait.isEquippedWithWeapon(this.weapon)){var h=s.selectWeaponVersus(i,this.target,this.game,this.options.force,this.options.passive);if(h){if(this.setWeapon(h),s.attackState!==wn.CheckRange)return s.attackState=wn.CheckRange,this.onTick(i);e=!0}else e=!1}t=e}if(t&&(l=this.lastTargetTpCheck,r?.isUnit()&&l&&r.moveTrait.lastTeleportTick>=l?(t=!1,this.rangeCheckCooldown=0):this.lastTargetTpCheck=this.game.currentTick),t&&r&&(this.lastValidTargetPosition={tile:r.tile,onBridge:this.target.getBridge()}),t||(this.targetLinesConfig.isAttack=!1),s.attackState===wn.CheckRange){if(0<this.rangeCheckCooldown)return this.rangeCheckCooldown--,!1;let e=this.target.obj?t?this.target.obj:this.lastValidTargetPosition.tile:this.target.tile;var l=this.target.obj?t?this.target.obj.isBuilding()?this.target.obj.centerTile:this.target.obj.tile:this.lastValidTargetPosition.tile:this.target.tile;if(!this.rangeHelper.isInWeaponRange(i,e,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(i,e,this.weapon)||i.isUnit()&&i.rules.balloonHover&&!i.rules.hoverAttack&&!a&&i.tile!==l&&!this.options.holdGround||i.isAircraft()&&this.weapon.projectileRules.iniRot<=1&&!a){if(i.isUnit()&&!this.options.holdGround&&this.game.map.isWithinBounds(l)){if(a){if(a.target!==this.target.obj||t)if(t&&this.target.obj&&this.rangeHelper.tileDistance(this.target.obj,this.lastSelfMoveTargetTile)>this.weapon.range)a.retarget(this.target.obj,!!this.target.getBridge()),this.lastSelfTileBeforeMove=i.tile,this.lastSelfMoveTargetTile=this.target.obj?.tile??this.target.tile;else{if(void 0!==this.options.leashTiles&&this.rangeHelper.tileDistance(this.initialSelfPosition.tile,i.tile)>this.options.leashTiles)return a.cancel(),!0;var c=e instanceof Ba&&e.isUnit()?e.moveTrait.baseSpeed:0,u=Math.ceil((this.rangeHelper.tileDistance(i,e)-(this.weapon.range+1))/((i.moveTrait.baseSpeed+c)/Os.LEPTONS_PER_TILE));0<u&&(this.rangeCheckCooldown=Math.min(js.BASE_TICKS_PER_SECOND,u))}else{let e;e=void 0!==this.options.leashTiles?this.game.createTarget(this.initialSelfPosition.onBridge,this.initialSelfPosition.tile):this.game.createTarget(this.lastValidTargetPosition.onBridge,this.lastValidTargetPosition.tile),s.currentTarget=e,a.retarget(e.tile,e.isBridge()),this.updateTargetLines(e,!1)}return!1}if(!i.moveTrait||i.moveTrait.isDisabled())return!0;if(this.isCancelling())return!0;if(i.tile===this.lastSelfTileBeforeMove||this.moveExecuted&&i.moveTrait.lastMoveResult===Xr.Fail?this.moveAttempts++:this.moveAttempts=0,this.weapon.rules.limboLaunch&&i.defaultToGuardArea&&r&&this.moveExecuted&&i.moveTrait.lastMoveResult===Xr.Fail&&this.rangeHelper.isInRange(i,r,0,i.armedTrait.computeGuardScanRange(this.weapon),!0))return!0;if(3<this.moveAttempts)return!0;0<this.moveAttempts&&this.children.push(new ga(1/60));c=e,u=r&&!t?this.lastValidTargetPosition.onBridge:this.target.getBridge();return a=new lo(this.game,c,!!u,this.weapon),a.blocking=!1,this.children.push(a),this.moveExecuted=!0,this.lastSelfTileBeforeMove=i.tile,this.lastSelfMoveTargetTile=c instanceof Ba?c.tile:c,this.onTick(i)}return!0}if(this.moveExecuted=!1,this.moveAttempts=0,a&&(i.rules.balloonHover&&!i.rules.hoverAttack||i.rules.fighter||i.rules.spawned||i.rules.movementZone===ri.Fly&&!this.rangeHelper.isInRange2(i,this.target.obj??this.target.tile,this.weapon.minRange,this.weapon.range-1)||a.cancel()),a&&(i.isInfantry()&&!i.rules.balloonHover||this.weapon.rules.spawner))return!1;if(a?.children.some(e=>!e.cancellable)&&this.weapon.rules.limboLaunch)return!1;if(a&&a.shouldAirStrafe(i)&&this.target.obj?.isUnit()&&this.target.obj.moveTrait.isMoving()&&1<this.weapon.range&&!this.rangeHelper.isInRange2(i,this.target.obj,this.weapon.minRange,this.weapon.range-1))return!1;s.attackState=wn.PrepareToFire}if(s.attackState!==wn.PrepareToFire)return!1;if(!t||s.isDisabled())return a?.cancel(),!0;u=this.target.getWorldCoords(),c=i.position.worldPosition;if(!(this.lastInRangeTargetPosition.length()&&this.lastInRangeTargetPosition.equals(u)&&this.lastInRangeSelfPosition.length()&&this.lastInRangeSelfPosition.equals(c)))return this.lastInRangeTargetPosition.copy(u),this.lastInRangeSelfPosition.copy(c),s.attackState=wn.CheckRange,this.onTick(i);if(!(this.weapon.rules.omniFire||i.rules.omniFire&&i.rules.fighter)){var c=(new rs).copy(u).sub(c),e=br.fromMapCoords(new ks(c.x,c.z)),c=this.weapon.projectileRules.rot?45:11.25;if((i.isVehicle()||i.isBuilding())&&i.turretTrait){if(i.turretTrait.desiredFacing=e,Math.abs(e-i.turretTrait.facing)>=c)return!1}else if(Math.abs(e-i.direction)>=c){if(i.isAircraft())return i.direction=br.tick(i.direction,e,i.rules.rot).facing,!1;if(a)return!1;if(this.options.disallowTurning)return!0;if(i.isVehicle())return this.children.push(new vr(e)),!1;i.direction=e}}if(!this.losHelper.hasLineOfSight(i,this.target.obj||this.target.tile,this.weapon))return s.attackState=wn.CheckRange,this.onTick(i);if(s.isOnCooldown(i))return!1;if(this.weapon.warhead.rules.temporal&&i.temporalTrait.getTarget()===this.target.obj)return!1;if(this.weapon.rules.suicide&&this.weapon.type!==hi.DeathWeapon)return this.game.destroyObject(i,{player:i.owner,obj:i,weapon:this.weapon}),!0;e=this.game.rules.general.prism.type;return i.isBuilding()&&i.name===e&&this.weapon.type!==hi.Secondary&&this.fireUpPrismSupportTowers(i,e),(i.isInfantry()||i.isVehicle())&&(i.isFiring=!0),i.art.fireUp?(this.children.push(new qs(i.art.fireUp).setCancellable(!1)),s.attackState=wn.FireUp,!1):(s.attackState=wn.Firing,this.onTick(i))}shouldDropTarget(e){return this.forceDropTarget||e?.isTechno()&&(this.weapon.rules.limboLaunch&&((e.isVehicle()||e.isAircraft())&&e.parasiteableTrait?.isInfested()||e.invulnerableTrait.isActive())||e.warpedOutTrait.isInvulnerable()&&!this.weapon.warhead.rules.temporal||this.initialTargetOwner!==e.owner)}fireUpPrismSupportTowers(t,i){var e;for(e of t.owner.getOwnedObjectsByType(xt.Building).filter(e=>e.name===i&&e.secondaryWeapon&&!e.unitOrderTrait.hasTasks()&&e.attackTrait&&!e.attackTrait.isDisabled()&&!e.attackTrait.isOnCooldown(e)).filter(e=>this.rangeHelper.isInWeaponRange(e,t,e.secondaryWeapon,this.game.rules)).slice(0,this.game.rules.general.prism.supportMax))e.unitOrderTrait.addTask(e.attackTrait.createAttackTask(this.game,t,t.centerTile,e.secondaryWeapon,{passive:!0}))}countSupportBeamsAndFireDownTowers(t,i){var e,s=t.owner.getOwnedObjectsByType(xt.Building).filter(e=>e.name===i&&e.attackTrait?.currentTarget?.obj===t);for(e of s)e.unitOrderTrait.getCurrentTask()?.cancel();return Math.min(this.game.rules.general.prism.supportMax,s.length)}getTargetLinesConfig(){return this.targetLinesConfig}}class mo extends go{constructor(e,t,i){if(super(e,t,i),this.isAttackMove=!0,this.attackPerformed=!1,this.passedFirstWaypoint=!1,this.internalTargetUpdateRequested=!1,this.scanCooldownTicks=0,!t.obj?.isTechno())throw new Error("Target must be a techno object");this.initialTarget=t,this.initialWeapon=i,this.requestedTarget=t}duplicate(){return new mo(this.game,this.initialTarget,this.initialWeapon)}requestTargetUpdate(e){this.internalTargetUpdateRequested?(this.requestedTarget=e,this.internalTargetUpdateRequested=!1):(this.requestedTarget===this.initialTarget?this.requestedTarget=e:this.attackPerformed=!0,this.initialTarget=e),super.requestTargetUpdate(e)}onTargetChange(e){super.onTargetChange(e);e=e.attackTrait.currentTarget;e&&e.obj!==this.initialTarget.obj&&e.obj!==this.requestedTarget.obj&&(this.requestedTarget===this.initialTarget&&(this.requestedTarget=e),this.initialTarget=e)}onTick(t){if(t.moveTrait.moveState===qr.Moving&&(this.passedFirstWaypoint=!0),this.scanCooldownTicks=Math.max(0,this.scanCooldownTicks-1),t.attackTrait&&!t.attackTrait.isDisabled()&&!this.isCancelling()&&(this.requestedTarget===this.initialTarget||this.attackPerformed)){if(!(t.moveTrait.isIdle()||t.tile===this.lastScanTile&&this.scanCooldownTicks)){this.lastScanTile=t.tile,this.scanCooldownTicks=this.game.rules.general.normalTargetingDelay;let e=t.attackTrait.selectDefaultWeapon(t);if(e&&(this.passedFirstWaypoint||!e.getCooldownTicks())){var i=t.attackTrait.scanForTarget(t,e,this.game);if(i.target){let{target:e,weapon:t}=i;if(!t.getCooldownTicks()){this.options.holdGround=!0,this.options.passive=!0,this.setWeapon(t);var s=this.game.createTarget(e,e.tile);return this.internalTargetUpdateRequested=!0,this.requestTargetUpdate(s),this.attackPerformed=!1}}}}if(this.attackPerformed){if(!t.isSpawned){if(!this.forceCancel(t))throw new Error("Force cancel failed");return!0}this.attackPerformed=!1,this.passedFirstWaypoint=!1,this.options.holdGround=!1,this.options.passive=!1,this.setWeapon(this.initialWeapon),this.internalTargetUpdateRequested=!0,this.requestTargetUpdate(this.initialTarget)}}s=super.onTick(t);return s&&this.requestedTarget!==this.initialTarget?(this.attackPerformed=!0,this.isCancelling()||t.attackTrait.isDisabled()):s}}class fo extends ka{constructor(){super(...arguments),this.isAttackMove=!0,this.attackPerformed=!1,this.passedFirstWaypoint=!1}duplicate(){return new fo(this.game,this.targetTile,this.toBridge,this.options)}onTick(i){if(i.moveTrait.moveState===qr.Moving&&(this.passedFirstWaypoint=!0),i.moveTrait.moveState===qr.ReachedNextWaypoint&&i.attackTrait&&!i.attackTrait.isDisabled()&&(i.rules.movementZone!==ri.Fly||!i.rules.balloonHover)&&!this.isCancelling()){let e=i.attackTrait.selectDefaultWeapon(i);if(e&&(this.passedFirstWaypoint||e&&!e.getCooldownTicks())){var s=i.attackTrait.scanForTarget(i,e,this.game);if(s.target){let{target:e,weapon:t}=s;if(!t.getCooldownTicks()){s=i.attackTrait.createAttackTask(this.game,e,e.tile,t,{holdGround:!0,passive:!0});return this.children.push(s),this.useChildTargetLines=!0,this.attackPerformed=!0,i.moveTrait.velocity.set(0,0,0),i.moveTrait.currentWaypoint=void 0,i.moveTrait.collisionState=Zr.Waiting,!1}}}if(this.attackPerformed){if(!i.isSpawned){if(!this.forceCancel(i))throw new Error("Force cancel failed");return!0}this.attackPerformed=!1,this.passedFirstWaypoint=!1,this.useChildTargetLines=!1,i.moveTrait.collisionState=Zr.Resolved,this.updateTarget(this.targetTile,this.toBridge)}}return super.onTick(i)}}class yo extends ka{constructor(e,t,i,s){super(e,i,!1,{ignoredBlockers:[t],closeEnoughTiles:0,strictCloseEnough:!0,forceWaitOnPathBlocked:t.factoryTrait?.type!==es.InfantryType}),this.factory=t,this.rallyPoint=s,this.preventOpportunityFire=!0,this.rampBlockersPushed=!1,this.cancellable=!1}onStart(t){super.onStart(t),this.factory.factoryTrait?.type===es.UnitType&&(this.checkRampTiles=this.game.map.tileOccupation.calculateTilesForGameObject(this.factory.tile,this.factory).filter(e=>0<this.game.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)))}canStopAtTile(e,t,i){return!this.game.map.tileOccupation.isTileOccupiedBy(t,this.factory)&&super.canStopAtTile(e,t,i)}onTick(e){if(this.checkRampTiles){for(var t of this.checkRampTiles){var i,s;for(i of this.game.map.tileOccupation.getGroundObjectsOnTile(t))if(i.isUnit()){if(this.rampBlockersPushed)return!1;let e=new Sa(this.game,void 0,{excludedTiles:this.checkRampTiles});e.setCancellable(!1);let t=i.unitOrderTrait.getCurrentTask();t?t.constructor!==ka&&t.constructor!==go&&t.constructor!==fo&&t.constructor!==mo||(s=t.duplicate(),t.cancel(),i.unitOrderTrait.addTaskNext(s),i.unitOrderTrait.addTaskNext(e)):i.unitOrderTrait.addTask(e)}}if(!this.rampBlockersPushed)return!(this.rampBlockersPushed=!0);this.checkRampTiles=void 0}return e.moveTrait.moveState===qr.ReachedNextWaypoint&&this.options?.ignoredBlockers&&!this.game.map.terrain.isBlockerObject(this.factory,e.tile,!1,e.rules.speedType)&&(this.options.ignoredBlockers=void 0,this.preventOpportunityFire=!1,this.rallyPoint&&(this.updateTarget(this.rallyPoint.tile,!!this.rallyPoint.onBridge),this.cancellable=!0,this.options.closeEnoughTiles=this.game.rules.general.closeEnough,this.options.strictCloseEnough=!1,this.options.forceWaitOnPathBlocked=!1)),super.onTick(e)}}class wo{constructor(e,t,i,s,r,a=()=>!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=r,this.predicate=a,this.dirVec=new ks(10,0),this.finished=!1,this.diagonal=!0,this.distance=s}getNextTile(){if(!this.finished){let t;do{let e={x:this.startTile.rx,y:this.startTile.ry};e.x+=this.distance*Math.sign(this.dirVec.x),e.y+=this.distance*Math.sign(this.dirVec.y),this.dirVec.rotateAround(new ks,Math.PI/4*(this.diagonal?1:2)).round();var i=this.tiles.getByMapCoords(e.x,e.y);if(i&&this.mapBounds.isWithinBounds(i)&&this.predicate(i)&&(t=i),!this.dirVec.angle()){if(this.maxDistance&&this.distance>=this.maxDistance)return this.finished=!0,t;this.distance++}}while(!t);return t}}}(Tn=Tn||{}).onSell=Symbol();class To{[Kr.onUnspawn](e){this.undock(e),this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[Qr.onChange](e){e.owner!==this.dock?.owner&&this.undock(e),e.owner!==this.reservedDock?.owner&&this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[Wr.onBeforeTeleport](e,t,i,s){s||this.undock(e)}undock(e){this.dock&&!this.dock.isDisposed&&this.dock.dockTrait.undockUnit(e)}dispose(){this.dock=void 0,this.reservedDock=void 0}}class bo{constructor(e,t,i,s){this.building=e,this.tiles=t,this.numberOfDocks=i,this.dockingOffsets=s,this.ticksWhenWarpedOut=!0,this.unitsByDockNumber=new Array(i).fill(void 0),this.reservedDocks=new Array(i).fill(void 0)}[Yr.onSpawn](){this.dockTiles=[];for(let e=0;e<this.numberOfDocks;e++){var t=this.findDockTile(e);if(!t)throw new Error(`Docking tile ${e} not found for object "${this.building.name}"`);this.dockTiles[e]=t}}[Kr.onUnspawn](){for(let e=0;e<this.numberOfDocks;e++)this.unreserveDockAt(e)}[Fr.onTick](){for(let e=0;e<this.numberOfDocks;e++){var t=this.unitsByDockNumber[e];t&&t.tile!==this.getDockTile(e)&&this.undockUnit(t)}}[zr.onDestroy](e,t,i,s){var r=(e.rules.unitRepair||e.helipadTrait)&&!e.rules.naval&&!i?.weapon?.warhead.rules.temporal;if(r)for(var a of this.unitsByDockNumber)a&&!a.isDestroyed&&(r?t.destroyObject(a,i,s):this.undockUnit(a))}[Tn.onSell](s,r){if(s.helipadTrait&&this.hasDockedUnits()){var a,e,n;let t=[],i=0;for(a of[...s.owner.buildings].filter(e=>e.helipadTrait&&(e.dockTrait?.getAvailableDockCount()??!1)&&e!==s)){let e=a.dockTrait?.getAvailableDockCount()??0;for(;0<e&&i<this.unitsByDockNumber.length;)t.push(a),e--,i++;if(i===this.unitsByDockNumber.length)break}i=0;for(e of this.unitsByDockNumber)e&&((n=t[i])?e.unitOrderTrait.addTask(new fa(r,n)):e.unitOrderTrait.addTask(new Ua(new ka(r,e.tile,!1),new ma(e=>{e.crashableTrait?e.crashableTrait.crash({player:s.owner}):r.destroyObject(e,{player:s.owner})})).setCancellable(!1))),i++}else{var t,i=s.rules.unitRepair&&!s.rules.naval;for(t of this.unitsByDockNumber)t&&(i?r.sellTrait.sell(t):this.undockUnit(t))}}[Qr.onChange](e,t,i){for(var s of this.unitsByDockNumber)s&&i.changeObjectOwner(s,e.owner)}getFirstAvailableDockNumber(){if(!this.building?.warpedOutTrait.isActive()){var e=this.unitsByDockNumber.findIndex((e,t)=>!e&&!this.reservedDocks[t]);if(-1!==e)return e}}getAvailableDockCount(){return this.building?.warpedOutTrait.isActive()?0:this.unitsByDockNumber.filter((e,t)=>!e&&!this.reservedDocks[t]).length}getFirstEmptyDockNumber(){if(!this.building?.warpedOutTrait.isActive()){var e=this.unitsByDockNumber.findIndex(e=>!e);if(-1!==e)return e}}getDockOffset(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);return this.dockingOffsets[e]}getDockTile(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);return this.dockTiles[e]}getDockNumberByTile(e){e=this.dockTiles.indexOf(e);if(-1!==e)return e}getAllDockTiles(){return[...this.dockTiles]}findDockTile(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);var t=this.building.position.getMapPosition(),e=this.getDockOffset(e);return this.tiles.getByMapCoords(Math.floor((t.x+e.x)/Os.LEPTONS_PER_TILE),Math.floor((t.y+e.z)/Os.LEPTONS_PER_TILE))}isValidUnitForDock(e){return(this.building.unitRepairTrait&&e.isVehicle()&&!this.building.helipadTrait&&(!e.rules.consideredAircraft||e.rules.landable)||e.rules.dock.includes(this.building.name)&&!(e.isAircraft()&&!this.building.helipadTrait))&&this.building.rules.naval===e.rules.naval}dockUnitAt(e,t){if(t>this.numberOfDocks-1)throw new RangeError(`Index ${t} exceeds available docks (${this.numberOfDocks})`);if(this.unitsByDockNumber[t])throw new Error(`Another unit is already docked at dock #${t}`);let i=e.traits.find(To);if(!i)throw new Error(`Unit "${e.name}" cannot be docked to ${this.building.name}`);this.unitsByDockNumber[t]=e,i.dock=this.building}undockUnitAt(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);let t=this.unitsByDockNumber[e];t&&(this.unitsByDockNumber[e]=void 0,t.traits.get(To).dock=void 0)}undockUnit(e){e=this.unitsByDockNumber.indexOf(e);-1!==e&&this.undockUnitAt(e)}isDocked(e){return this.unitsByDockNumber.includes(e)}hasDockedUnits(){return!!this.unitsByDockNumber.find(e=>e)}getDockedUnits(){return this.unitsByDockNumber.filter(ja)}reserveDockAt(e,t){if(t>this.numberOfDocks-1)throw new RangeError(`Index ${t} exceeds available docks (${this.numberOfDocks})`);if(this.reservedDocks[t])throw new Error(`Dock #${t} is already reserved by ${this.reservedDocks[t].name}`);(this.reservedDocks[t]=e).traits.get(To).reservedDock?.dockTrait.unreserveDockForUnit(e),e.traits.get(To).reservedDock=this.building}unreserveDockAt(e){if(e>this.numberOfDocks-1)throw new RangeError(`Index ${e} exceeds available docks (${this.numberOfDocks})`);let t=this.reservedDocks[e];t&&(this.reservedDocks[e]=void 0,t.traits.get(To).reservedDock=void 0)}unreserveDockForUnit(e){e=this.reservedDocks.indexOf(e);-1!==e&&this.unreserveDockAt(e)}hasReservedDockForUnit(e){return!!this.reservedDocks.includes(e)}hasReservedDockAt(e){return!!this.reservedDocks[e]}getReservedDockForUnit(e){e=this.reservedDocks.indexOf(e);if(-1!==e)return e}dispose(){this.building=void 0}}class vo{constructor(e){this.target=e,this.type=ss.FactoryProduceUnit}}(r=bn=bn||{})[r.All=0]="All",r[r.Ground=1]="Ground",r[r.Air=2]="Air";class So{constructor(e){this.tiles=e,this.tileOccupation=[],this.emptyTiles=new Set,this._onChange=new ao;let t=this.tileOccupation;for(var i of e.getAll())t[i.rx]=t[i.rx]||[],t[i.rx][i.ry]=new Set,this.emptyTiles.add(i)}get onChange(){return this._onChange.asEvent()}occupyTileRange(e,t){let i=this.calculateTilesForGameObject(e,t);i.forEach(e=>this.occupyTile(e,t)),this._onChange.dispatch(this,{tiles:i,object:t,type:"added"})}unoccupyTileRange(e,t){let i=this.calculateTilesForGameObject(e,t);i.forEach(e=>this.unoccupyTile(e,t)),this._onChange.dispatch(this,{tiles:i,object:t,type:"removed"})}occupySingleTile(e,t){this.occupyTile(e,t),this._onChange.dispatch(this,{tiles:[e],object:t,type:"added"})}unoccupySingleTile(e,t){this.unoccupyTile(e,t),this._onChange.dispatch(this,{tiles:[e],object:t,type:"removed"})}calculateTilesForGameObject(e,t){return this.tiles.getInRectangle(e,t.getFoundation())}occupyTile(e,t){let i=this.tileOccupation[e.rx]?.[e.ry];i&&(i.add(t),this.emptyTiles.delete(e),e.landType=this.computeTileLandType(e),e.onBridgeLandType=this.computeOnBridgeLandType(e))}unoccupyTile(e,t){let i=this.tileOccupation[e.rx]?.[e.ry];i&&(i.delete(t),i.size||this.emptyTiles.add(e),e.landType=this.computeTileLandType(e),e.onBridgeLandType=this.computeOnBridgeLandType(e))}isTileOccupiedBy(e,t){return!!this.tileOccupation[e.rx]?.[e.ry]?.has(t)}computeTileLandType(e){if(e.landType===Jt.Rock)return Jt.Rock;var t,i=Gi(e.terrainType);for(t of this.tileOccupation[e.rx]?.[e.ry]??[]){if((t.isOverlay()||t.isBuilding())&&t.rules.wall)return Jt.Wall;if(t.isOverlay()&&t.isTiberium())return Jt.Tiberium;if(t.isOverlay()&&t.rules.land!==Jt.Clear&&!t.isBridge()&&!t.isBridgePlaceholder())return t.rules.land}return i}computeOnBridgeLandType(e){for(var t of this.tileOccupation[e.rx]?.[e.ry]??[])if(t.isOverlay()&&t.isBridge())return t.isHighBridge()?Jt.Road:t.rules.land}getTileZone(e,t=!1){return _s(t?e.landType:e.onBridgeLandType??e.landType)}getBridgeOnTile(e){for(var t of this.tileOccupation[e.rx]?.[e.ry]??[])if(t.isOverlay()&&t.isBridge())return t}getObjectsOnTile(e){return[...this.tileOccupation[e.rx]?.[e.ry]??[]]}getGroundObjectsOnTile(e){let t=[];for(var i of this.tileOccupation[e.rx]?.[e.ry]??[])i.isTechno()&&!i.isBuilding()&&i.zone===vs.Air||t.push(i);return t}getAirObjectsOnTile(e){let t=[];for(var i of this.tileOccupation[e.rx]?.[e.ry]??[])i.isUnit()&&i.zone===vs.Air&&t.push(i);return t}getObjectsOnTileByLayer(e,t){if(t===bn.Ground)return this.getGroundObjectsOnTile(e);if(t===bn.Air)return this.getAirObjectsOnTile(e);if(t===bn.All)return this.getObjectsOnTile(e);throw new Error(`Unhandled layer type "${t}"`)}getEmptyTiles(){return[...this.emptyTiles]}}(vn=vn||{}).onChange=Symbol(),(Sn=Sn||{}).onProduce=Symbol(),(r=kn=kn||{})[r.Idle=0]="Idle",r[r.Delivering=1]="Delivering";class ko{constructor(e,t=!1){this.type=e,this.isCloningVats=t,this.status=kn.Idle}[Yr.onSpawn](e,t){this.resetRallyPoint(e,t)}resetRallyPoint(e,t){var i;[es.BuildingType,es.AircraftType].includes(this.type)||(i=this.computeDefaultRallyPoint(e,this.type,t.map),e.rallyTrait?.changeRallyPoint(i,e,t))}[vn.onChange](t,e,i){if(t.owner.production){let e=[];e=this.type===es.BuildingType?[fn.Structures,fn.Armory]:[t.owner.production.getQueueTypeForFactory(this.type)];for(var s of e)t.owner.production.getQueue(s).notifyUpdated()}}[Fr.onTick](i,s){if(this.status===kn.Delivering){if(!this.deliveringUnit||this.deliveringUnit.isDestroyed){if(this.buildingProductionTicks=this.buildingProductionTicks??1,0<this.buildingProductionTicks--)return;this.buildingProductionTicks=void 0}else if(s.map.tileOccupation.isTileOccupiedBy(this.deliveringUnit.tile,i)){if(!this.deliveringUnit.rules.consideredAircraft)return;if(this.deliveringUnit.position.tileElevation<i.art.height)return}return this.status=kn.Idle,void(this.deliveringUnit=void 0)}if(i.owner.production&&!i.warpedOutTrait.isActive()){let e=i.owner.production.getPrimaryFactory(this.type);if((e?.warpedOutTrait.isActive()||e===i||e?.factoryTrait?.deliveringUnit&&e.factoryTrait.type===es.UnitType)&&this.type!==es.BuildingType){let e=i.owner.production.getQueueForFactory(this.type);if(e&&e.status===yn.Ready){let t=e.getFirst();if(this.type===es.AircraftType){let e=this.produceAircraftAt(i,t,s);var r;if(!e)for(r of[...i.owner.buildings].filter(e=>e.factoryTrait?.type===es.AircraftType&&e.helipadTrait)){if(e)break;e=this.produceAircraftAt(r,t,s)}if(!e)return}else if(this.produceGroundUnitAt(i,t,s),!this.isCloningVats&&this.type===es.InfantryType){let e=[...i.owner.buildings].find(e=>e.factoryTrait&&e.rules.cloning);e?.factoryTrait.status===kn.Idle&&e?.factoryTrait.produceGroundUnitAt(e,t,s)}i.owner.addUnitsBuilt(t.rules.type,1),t.creditsSpent=0,t.progress=0,e.shift(t.rules,1),e.currentSize&&(e.status=yn.Active)}}}}produceGroundUnitAt(e,t,i){let s=i.createUnitForPlayer(t.rules,e.owner);t.rules.trainable&&e.owner.canProduceVeteran(s.rules)&&s.veteranTrait?.setVeteranLevel(ea.Veteran),s.isInfantry()&&(s.position.subCell=Ra.SUB_CELLS[0]);let r=this.computeInternalRallyPoint(e,this.type,e.rallyTrait.getRallyPoint(),i.map);this.type!==es.UnitType&&(r=e.rallyTrait.findRallyPointforUnit(s,r,i.map,!1,e.tile.z));let a;var n;a=this.type===es.NavalUnitType?r:(n=this.computeExitCoords(e,this.type),i.map.tiles.getByMapCoords(Math.floor(n.rx),Math.floor(n.ry))),s.rules.consideredAircraft&&(r=a);let o;if(e.rallyTrait.getRallyPoint()!==r&&(o=e.rallyTrait.findRallyNodeForUnit(s,i.map)),s.isInfantry()){let t=i.map.tileOccupation.getObjectsOnTileByLayer(o?.tile??r,s.rules.consideredAircraft?bn.Air:bn.Ground).filter(e=>e.isInfantry()&&e.moveTrait.moveState!==qr.Moving).map(e=>e.position.subCell);s.position.subCell=Ra.SUB_CELLS.find(e=>!t.includes(e))??Ra.SUB_CELLS[0]}s.direction=270,i.spawnObject(s,a),i.traits.filter(Sn).forEach(e=>{e[Sn.onProduce](s,i)}),i.events.dispatch(new vo(s)),s.rules.consideredAircraft?(n=o??{tile:r,onBridge:void 0},s.unitOrderTrait.addTask(new ka(i,n.tile,!!n.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))):s.unitOrderTrait.addTask(new yo(i,e,r,o)),this.status=kn.Delivering,this.deliveringUnit=s}produceAircraftAt(e,t,i){let s=e.traits.find(bo);if(!s)return!1;var r=s.getFirstAvailableDockNumber();if(void 0===r)return!1;let a=i.createUnitForPlayer(t.rules,e.owner);t.rules.trainable&&e.owner.canProduceVeteran(a.rules)&&a.veteranTrait?.setVeteranLevel(ea.Veteran);t=s.getDockOffset(r);return a.position.moveToLeptons(e.position.getMapPosition()),a.position.moveByLeptons3(t),i.spawnObject(a,a.position.tile),s.dockUnitAt(a,r),a.isAircraft()&&a.airportBoundTrait&&(a.airportBoundTrait.preferredAirport=e),i.traits.filter(Sn).forEach(e=>{e[Sn.onProduce](a,i)}),i.events.dispatch(new vo(a)),!0}computeExitCoords(e,t){if(t===es.InfantryType)return this.computeBarracksDefaultExitCoords(e);if(t===es.UnitType)return this.computeWarFactoryExitCoords(e);throw new Error(`Unsupported factory type ${es[t]}`)}computeInternalRallyPoint(e,t,i,s){let r,a;if(t===es.NavalUnitType)a=this.computeNavalInternalRallyPoint(e,i,s);else{if(t===es.InfantryType)r=this.computeBarracksInternalRallyCoords(e);else{if(t!==es.UnitType)throw new Error(`Unsupported factory type ${es[t]}`);r=this.computeWarFactoryInternalRallyCoords(e)}a=s.tiles.getByMapCoords(r.rx,r.ry)}return a??this.findTileAdjacentToBuilding(e,s)}computeDefaultRallyPoint(e,t,i){let s,r;if(t===es.NavalUnitType)r=this.computeNavalDefaultRallyPoint(e,i);else{if(t===es.InfantryType)s=this.computeBarracksInternalRallyCoords(e);else{if(t!==es.UnitType)throw new Error(`Unsupported factory type ${es[t]}`);s=this.computeWarFactoryDefaultRallyCoords(e)}r=i.tiles.getByMapCoords(s.rx,s.ry)}return r??this.findTileAdjacentToBuilding(e,i)}findTileAdjacentToBuilding(e,t){return new Us(t.tiles,t.mapBounds,e.tile,e.getFoundation(),1,1,()=>!0).getNextTile()}computeBarracksDefaultExitCoords(e){var t=e.getFoundation();let i,s;return t.width<=2||t.height<=2?(i=t.width-1,s=t.height-1,e.rules.gdiBarracks&&2<t.width&&(i=Math.floor(t.width/2))):(i=0,s=t.height-1),{rx:e.tile.rx+i,ry:e.tile.ry+s}}computeBarracksInternalRallyCoords(e){var t=e.getFoundation();let{rx:i,ry:s}=this.computeBarracksDefaultExitCoords(e);return!(t.width<=2||t.height<=2)||e.rules.gdiBarracks?s+=1:e.rules.nodBarracks&&(i+=t.width<=2?1:0,s+=t.height<=2?1:0),{rx:i,ry:s}}computeWarFactoryExitCoords(e){var t=e.getFoundation();return{rx:e.tile.rx+Math.floor(t.width/2),ry:e.tile.ry+Math.floor(t.height/2)}}computeWarFactoryInternalRallyCoords(e){var t=e.getFoundation();return{rx:e.tile.rx+t.width-1,ry:e.tile.ry+Math.floor(t.height/2)}}computeWarFactoryDefaultRallyCoords(e){var t=e.getFoundation();return{rx:e.tile.rx+t.width,ry:e.tile.ry+Math.floor(t.height/2)}}computeNavalDefaultRallyPoint(e,t){let i=new wo(t.tiles,t.mapBounds,e.centerTile,5,5,e=>e.terrainType===Kt.Water&&!t.getObjectsOnTile(e).find(e=>e.isBuilding()||e.isOverlay()&&e.isBridge()));return i.diagonal=!1,i.getNextTile()??t.tiles.getByMapCoords(e.tile.rx+e.getFoundation().width,e.tile.ry+e.getFoundation().height)}computeNavalInternalRallyPoint(e,t,i){t=new ks(t.rx,t.ry).sub(new ks(e.centerTile.rx,e.centerTile.ry));return i.tiles.getByMapCoords(e.centerTile.rx+Math.sign(t.x)*(Math.floor(e.getFoundation().width/2)+1),e.centerTile.ry+Math.sign(t.y)*(Math.floor(e.getFoundation().height/2)+1))}}class Oo{constructor(e,t,i,s,r,a,n,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.foundation=s,this.maxDistance=a,this.predicate=n,this.checkBounds=o,this.distance=r,this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){var s=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t))return t};do{var r=this.startTile.rx-this.distance,a=this.startTile.ry-this.distance,n=this.startTile.rx+this.foundation.width-1+this.distance,o=this.startTile.ry+this.foundation.height-1+this.distance;let e,t,i;if(0<this.distance){for(t=1+a;t<o;t++)i=s(r,t),i&&(yield i);for(e=r;e<n;e++)i=s(e,a),i&&(yield i);for(t=o-1;t>=a;t--)i=s(n,t),i&&(yield i);for(e=n;e>=r;e--)i=s(e,o),i&&(yield i)}else this.predicate(this.startTile)&&(yield this.startTile)}while(this.distance++,this.distance<=this.maxDistance)}}class _o{[Yr.onSpawn](r,a){if(!r.owner.isNeutral){let e;if(a.rules.hasObject(r.rules.freeUnit,xt.Vehicle))e=a.rules.getObject(r.rules.freeUnit,xt.Vehicle);else{if(!a.rules.hasObject(r.rules.freeUnit,xt.Infantry))return void console.warn(`Free unit "${r.rules.freeUnit}" is not a vehicle or infantry type.`);e=a.rules.getObject(r.rules.freeUnit,xt.Infantry)}let i=a.createUnitForPlayer(e,r.owner),s;var t=new Oo(a.map.tiles,a.map.mapBounds,r.tile,r.getFoundation(),1,1,e=>{var t=0<a.map.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&Math.abs(e.z-r.tile.z)<2&&!a.map.terrain.findObstacles({tile:e,onBridge:void 0},i).length;return!s&&t&&(s=e),t&&!a.map.getObjectsOnTile(e).find(e=>e.isOverlay())}).getNextTile()??s;if(!t)return r.owner.removeOwnedObject(i),i.dispose(),void(r.owner.credits+=i.purchaseValue);a.spawnObject(i,t)}}}class Io{[Tn.onSell](e,t){this.spawnSurvivors(e,t)}[zr.onDestroy](e,t,i,s){s||i?.obj===e&&i.weapon?.rules.suicide||e.isVehicle()&&e.moveTrait.isMoving()||e.crashableTrait||this.spawnSurvivors(e,t)}spawnSurvivors(s,r){var e=r.rules.general.crew,t=s.owner.country.side;let i,a;if(t===Zt.GDI)i=e.alliedSurvivorDivisor,a=e.alliedCrew;else{if(t!==Zt.Nod)return;i=e.sovietSurvivorDivisor,a=e.sovietCrew}let n=r.sellTrait.computeRefundValue(s)/i;n=0<n&&n<1?1:Math.floor(n),n=s.isVehicle()?Math.min(1,n):Math.min(5,n);let o=[];for(let e=0;e<n;e++)o.push(a);if(0<o.length){s.rules.constructionYard&&(o[o.length-1]=r.rules.general.engineer);var h,l=r.map.tiles.getInRectangle(s.tile,s.getFoundation()).filter(e=>r.map.isWithinBounds(e));let i=[...l];for(h of o){var c=r.rules.getObject(h,xt.Infantry);if(r.map.terrain.getPassableSpeed(s.tile,c.speedType,!s.isBuilding()&&s.onBridge,void 0,!0)){let e=r.createUnitForPlayer(c,s.owner),t=i.length?i.splice(r.generateRandomInt(0,i.length-1),1)[0]:void 0;t=t||l[r.generateRandomInt(0,l.length-1)],e.isInfantry()&&(e.position.subCell=Ra.SUB_CELLS[0]),e.veteranTrait&&s.owner.canProduceVeteran(e.rules)&&e.veteranTrait.setVeteranLevel(ea.Veteran),r.spawnObject(e,t),s.isBuilding()&&e.unitOrderTrait.addTask(new Sa(r,void 0,{ignoredBlockers:s.isDestroyed?void 0:[s]}))}}}}}class Co{constructor(e,t){this.gameObject=e,this.bridges=t,this.checkedClosestBridge=!1}canRepairBridge(){var e=this.findClosestBridgeBounds();return e?this.bridges.canBeRepaired(e):(console.warn(`No bridge associated with hut at ${this.gameObject.tile.rx}, ${this.gameObject.tile.ry}.`),!1)}repairBridge(t,i){var s=this.findClosestBridgeBounds();if(!s)throw new Error("No bridge bounds found");var e=this.bridges.findDestroyedPieceTiles(s),r=s.start.rx!==s.end.rx;let a;a=s.isHigh?Ha.calculateHighBridgeOverlayId(s.type,r):Ha.calculateLowBridgeOverlayId(s.type,r);var n,o,h=t.rules.getOverlayName(a);for(n of e){let e=t.createObject(xt.Overlay,h);e.overlayId=a,e.value=0,e.position.tileElevation=s.isHigh?4:0,t.spawnObject(e,n),this.updateUnitsUnderBridgePiece(n,s,t,i)}for(o of this.bridges.findBridgePieces(s))o.obj.bridgeTrait.bridgeSpec=s}updateUnitsUnderBridgePiece(e,i,s,r){var a;for(let t of this.bridges.getPieceTiles(this.bridges.getPieceAtTile(e)))if(i.isHigh){let e=s.map.getGroundObjectsOnTile(t).filter(e=>e.tile===t&&e.isUnit()&&!e.unitOrderTrait.hasTasks()&&e.rules.tooBigToFitUnderBridge);e.forEach(e=>e.unitOrderTrait.addTask(new Sa(s)))}else for(a of s.map.getGroundObjectsOnTile(t))a.isUnit()&&(s.map.terrain.getPassableSpeed(t,a.rules.speedType,!0)?(a.zone=vs.Ground,a.onBridge=!0):a.isDestroyed||s.destroyObject(a,{player:r}))}demolishBridge(e,t){var i=this.getBridgePieces();if(i)for(var s of i)s.obj.isLowBridge()&&e.map.getTileZone(s.obj.tile,!0)!==vs.Water||s.obj.isDestroyed||(s.obj.deathType=Vr.Demolish,e.destroyObject(s.obj,t,!0))}getBridgePieces(){var e=this.findClosestBridgeBounds();if(e)return this.bridges.findBridgePieces(e)}findClosestBridgeBounds(){return this.checkedClosestBridge||(this.checkedClosestBridge=!0,this.closestBridge=this.bridges.findClosestBridgeSpec(this.gameObject.tile)),this.closestBridge}dispose(){this.gameObject=void 0}}class Ao{constructor(){this.isActive=!1,this.produceCashCooldown=0}[Yr.onSpawn](e){e.owner.isNeutral||(this.isActive=!0)}[Qr.onChange](e,t){t.isNeutral&&!e.owner.isNeutral&&(e.owner.credits=Math.max(0,e.owner.credits+e.rules.produceCashStartup),this.isActive=!0,this.produceCashCooldown=e.rules.produceCashDelay)}[Fr.onTick](e){this.isActive&&(this.produceCashCooldown--,this.produceCashCooldown<=0&&(this.produceCashCooldown=e.rules.produceCashDelay,e.owner.credits=Math.max(0,e.owner.credits+e.rules.produceCashAmount)))}}class Bo{constructor(){this.linkedDamageHandled=!1}[ua.onDamage](e,t,i,s){if(!this.linkedDamageHandled){var r=Math.floor(i/2);if(r)for(var a of t.map.tiles.getAllNeighbourTiles(e.tile))if(a.landType===Jt.Wall){let e=t.map.getObjectsOnTile(a).find(e=>(e.isBuilding()||e.isOverlay())&&e.wallTrait);e.wallTrait.linkedDamageHandled=!0,e.healthTrait.inflictDamage(r,s,t),e.wallTrait.linkedDamageHandled=!1,e.healthTrait.health||t.destroyObject(e,s)}}}}class xo{constructor(e){this.obj=e,this.chargers=new Set}isOverpowered(){let e=1;return this.obj?.poweredTrait?.isPoweredOn(!0)||(e+=2),this.chargers.size>=e}hasChargersToPowerOn(){return 2<=this.chargers.size}chargeFrom(e){this.chargers.add(e),this.swapAttackTaskWeapon()}[Fr.onTick](i){if(0<this.chargers.size){let t=!1;this.chargers.forEach(e=>{(e.isDestroyed||e.isCrashing||e.owner!==i.owner||e.attackTrait?.currentTarget?.obj!==i)&&(this.chargers.delete(e),t=!0)}),t&&this.swapAttackTaskWeapon()}}swapAttackTaskWeapon(){let e=this.obj?.unitOrderTrait.getCurrentTask();var t;e instanceof go&&((t=this.getWeapon())?e.setWeapon(t):e.cancel())}getWeapon(){return this.isOverpowered()?this.obj?.secondaryWeapon:this.obj?.primaryWeapon}dispose(){this.obj=void 0,this.chargers.clear()}}class Eo{constructor(e,t){this.target=e,this.from=t,this.type=ss.UnitRepairFinish}}class Po{constructor(e){this.target=e,this.type=ss.UnitRepairStart}}(r=On=On||{})[r.Idle=0]="Idle",r[r.Repairing=1]="Repairing";class No{constructor(){this.status=On.Idle,this.cooldownTicks=0,this.lastRepairTickSuccessful=!1}[Yr.onSpawn](e,t){this.resetRallyPoint(e,t)}resetRallyPoint(e,t){var i;e.factoryTrait||(i=this.computeDefaultRallyPoint(e,t.map),e.rallyTrait.changeRallyPoint(i,e,t))}[Fr.onTick](t,i){if(t.dockTrait&&(!t.rules.needsEngineer||!t.owner.isNeutral))if(!t.dockTrait.hasDockedUnits()||t.dockTrait.getDockedUnits().some(e=>e.zone===vs.Air)||t.poweredTrait&&!t.poweredTrait.isPoweredOn())this.status=On.Idle;else if(this.cooldownTicks<=0){var s,r,a=i.rules.general.repair,a=t.rules.unitReload?a.reloadRate:a.uRepairRate;this.cooldownTicks+=js.BASE_TICKS_PER_SECOND*a*60;let e=!1;for(s of t.dockTrait.getDockedUnits())s.zone!==vs.Air&&(s.healthTrait.health<100&&i.areFriendly(s,t)?(this.tickRepair(s,i,t)&&(e=!0),!e||this.status!==On.Idle&&this.lastRepairTickSuccessful||t.helipadTrait||i.events.dispatch(new Po(s))):((r=t.rallyTrait.findRallyNodeForUnit(s,i.map))&&(t.dockTrait.undockUnit(s),s.unitOrderTrait.addTask(new ka(i,r.tile,!!r.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))),t.helipadTrait||i.events.dispatch(new Eo(s,t))));this.lastRepairTickSuccessful=e,this.status=e?On.Repairing:On.Idle}else this.cooldownTicks--}tickRepair(e,t,i){var s=t.rules.general.repair,r=Math.floor(s.repairStep),a=s.repairPercent;let n;if(a){s=a*e.purchaseValue/e.healthTrait.maxHitPoints,a=Math.min(i.owner.credits,Math.max(1,Math.floor(s*r)));if(n=s&&a?Math.floor(a/s):r,!a)return!1;i.owner.credits-=a}else n=r;return n=Math.min(n,e.healthTrait.maxHitPoints-e.healthTrait.getHitPoints()),!!n&&(e.healthTrait.healBy(n,i,t),!0)}computeDefaultRallyPoint(e,t){var i=e.getFoundation(),i=new ks(e.tile.rx,e.tile.ry+i.height);return t.tiles.getByMapCoords(i.x,i.y)??e.tile}}class Mo{getRallyPoint(){return this.rallyPoint}changeRallyPoint(e,t,i){i=this.findValidRallyPoint(t,e,i.map);i&&(this.rallyPoint=i)}findValidRallyPoint(i,e,s){let t=new Us(s.tiles,s.mapBounds,e,{width:1,height:1},0,20,e=>i.rules.naval===(e.terrainType===Kt.Water)&&!s.tileOccupation.isTileOccupiedBy(e,i)),r=t.getNextTile();if(!r&&i.factoryTrait?.type===es.NavalUnitType){var{width:a,height:n}=i.getFoundation();for(let t=0;t<a;t++)for(let e=0;e<n;e++){var o=s.tiles.getByMapCoords(i.tile.rx+t,i.tile.ry+e);if(!o)break;if(0<s.terrain.getPassableSpeed(o,ei.Float,!1)){r=o;break}}}return r}findRallyNodeForUnit(e,t){if(this.rallyPoint){var i=this.findRallyPointforUnit(e,this.rallyPoint,t,!0);return{tile:i,onBridge:e.rules.naval?void 0:t.tileOccupation.getBridgeOnTile(i)}}}findRallyPointforUnit(i,e,s,r,a){let n=i.rules.naval?void 0:s.tileOccupation.getBridgeOnTile(e),o=i.rules.movementZone===ri.Fly,t=new Us(s.tiles,s.mapBounds,e,{width:1,height:1},0,5,e=>{var t=!n||n.isHighBridge()?s.tileOccupation.getBridgeOnTile(e):void 0;return!(o?[]:s.terrain.findObstacles({tile:e,onBridge:t},i)).length&&(void 0===a||Math.abs(a-(e.z+(t?.tileElevation??0)))<4)&&(!r||!s.getObjectsOnTile(e).find(e=>e.isBuilding()&&!e.isDestroyed))&&(o||0<s.terrain.getPassableSpeed(e,i.rules.speedType,!!t))});return t.getNextTile()??e}}class Do{constructor(){this.activeTicks=0}isActive(){return 0<this.activeTicks}setActiveFor(e,t){this.activeTicks=e,this.activeFor=e,this.activeSince=t}reset(){this.activeTicks=0,this.activeSince=void 0,this.activeFor=void 0}getTicksLeft(){return this.activeTicks}getInitialTicks(){return this.activeFor??0}tick(e){return 0<this.activeTicks&&(this.activeTicks--,this.activeTicks<=0||void 0!==this.activeSince&&e-this.activeSince>this.activeFor)&&(this.reset(),!0)}}class Ro{constructor(){this.timer=new Do}hasCharge(){return this.timer.isActive()}setCharge(e,t){this.hasCharge()||(this.timer.setActiveFor(e),this.attackerInfo=t)}[Fr.onTick](e,t){this.timer.isActive()&&!0===this.timer.tick(t.currentTick)&&(e.invulnerableTrait.isActive()||(e.isBuilding()&&e.cabHutTrait?e.cabHutTrait.demolishBridge(t,this.attackerInfo):(e.deathType=Vr.Demolish,t.destroyObject(e,this.attackerInfo,!0))))}}class Lo{[Qr.onChange](e,t,i){this.checkAircraftsForPlayer(t,i)}[Kr.onUnspawn](e,t){this.checkAircraftsForPlayer(e.owner,t)}checkAircraftsForPlayer(e,t){let i=t.rules.general.padAircraft;var s;for(s of e.getOwnedObjectsByType(xt.Aircraft).filter(e=>i.includes(e.name)))s.airportBoundTrait&&(s.airportBoundTrait.preferredAirport=void 0)}}class Fo{[Fr.onTick](t,i){if(t.dockTrait&&t.dockTrait.hasDockedUnits()&&!t.dockTrait.getDockedUnits().every(e=>!this.canReloadUnit(e)))if(void 0===this.cooldownTicks&&(this.cooldownTicks=js.BASE_TICKS_PER_SECOND*i.rules.general.repair.reloadRate*60),this.cooldownTicks<=0){this.cooldownTicks=js.BASE_TICKS_PER_SECOND*i.rules.general.repair.reloadRate*60;let e=t.dockTrait.getDockedUnits();var s;for(s of 0===e[0].ammo?e.slice(0,1):e)this.canReloadUnit(s)&&s.ammoTrait.ammo++}else this.cooldownTicks--}canReloadUnit(e){return!(!e.ammoTrait||!e.rules.manualReload||e.ammoTrait.isFull()||e.zone===vs.Air)}}class jo extends Ua{constructor(e){super(new ga(e),new ma(e=>e.buildStatus=Cn.Ready)),this.cancellable=!1}}class Uo{constructor(e){this.name=e}getSuperWeapon(e){return e.owner.superWeaponsTrait?.get(this.name)}[Yr.onSpawn](e,t){this.addSuperWeaponToPlayerIfNeeded(e.owner,t)}[Kr.onUnspawn](e,t){this.removeSuperWeaponFromPlayerIfNeeded(e.owner)}[Qr.onChange](e,t,i){this.removeSuperWeaponFromPlayerIfNeeded(t),this.addSuperWeaponToPlayerIfNeeded(e.owner,i)}addSuperWeaponToPlayerIfNeeded(t,i){if(t.superWeaponsTrait&&!t.superWeaponsTrait.has(this.name)){let e=i.createSuperWeapon(this.name,t);t.superWeaponsTrait.add(e),e.rules.isPowered&&t.powerTrait?.isLowPower()&&e.pauseTimer()}}removeSuperWeaponFromPlayerIfNeeded(e){let t=e.superWeaponsTrait;t&&(e.getOwnedObjectsByType(xt.Building).some(e=>e.superWeaponTrait?.name===this.name)||(e=t.get(this.name))&&!e.isGift&&t.remove(this.name))}}(r=_n=_n||{})[r.Unexplored=0]="Unexplored",r[r.TemporaryReveal=1]="TemporaryReveal",r[r.Explored=2]="Explored",In=In||{},In[In.Darken=8]="Darken";class Wo{constructor(){this.invalidations=new Map,this.temporaryReveals=new Map,this.fullInvalidation=!1,this._onChange=new ao}get onChange(){return this._onChange.asEvent()}fromTiles(e){var t,i=e.getMapSize(),s=e.getMaxTileHeight(),s=this.padding=(s+s%2)/2;this.size={width:i.width+s,height:i.height+s},this.tiles=new Uint8Array(this.size.width*this.size.height),this.tiles.fill(_n.Unexplored),this.tileElevation=new Uint8Array(this.size.width*this.size.height);for(t of e.getAll()){var r=this.getTileIndex(t);this.tileElevation[r]=Math.max(this.tileElevation[r],t.terrainType===Kt.Cliff&&0<t.z?t.z-1:t.z)}return this}getSize(){return this.size}getTileIndex(e){var{sx:t,sy:e}=this.rxyzToSxy(e.rx,e.ry,e.z);return t+e*this.size.width}rxyzToSxy(e,t,i){i=(i|=0)+i%2;return{sx:e-i/2+this.padding,sy:t-i/2+this.padding}}sxyzToRxy(e,t,i){return{rx:e+Math.ceil(i/2)-this.padding,ry:t+Math.ceil(i/2)-this.padding}}shroudCoordsToWorld({sx:e,sy:t}){return this.sxyzToRxy(e,t,0)}findTilesAtShroudCoords({sx:t,sy:i},s){var e=s.getMaxTileHeight(),r=e+e%2;let a=[];for(let e=0;e<=r;e+=2){var n=e+e%2,{rx:o,ry:n}=this.sxyzToRxy(t,i,n),n=s.getByMapCoords(o,n);n?.z===e&&a.push(n)}return a}clone(){let e=new Wo;return e.tiles=this.tiles.slice(),e.size=this.size,e.padding=this.padding,e.tileElevation=this.tileElevation,e}copy(e){this.tiles=e.tiles.slice(),this.size=e.size,this.padding=e.padding,this.tileElevation=e.tileElevation}merge(e){if(this.size.width!==e.size.width||this.size.height!==e.size.height)throw new Error("Size mismatch");var i=e.tiles;for(let e=0,t=this.tiles.length;e<t;e++)this.tiles[e]=Math.max(7&i[e],7&this.tiles[e])|(i[e]|this.tiles[e])>>3<<3}isShrouded(e,t=0){t=this.rxyzToSxy(e.rx,e.ry,e.z+t);return this.getShroudTypeByShroudCoords(t)===_n.Unexplored}getShroudType(e){return 7&this.tiles[this.getTileIndex(e)]}isFlagged(e,t){return 0!=(this.tiles[this.getTileIndex(e)]&t)}getShroudTypeByTileCoords(e,t,i){return this.getShroudTypeByShroudCoords(this.rxyzToSxy(e,t,i))}getShroudTypeByShroudCoords({sx:e,sy:t}){return e<0||t<0||e>=this.size.width||t>=this.size.height?_n.Unexplored:7&this.tiles[e+t*this.size.width]??_n.Unexplored}invalidateFull(){this.fullInvalidation=!0}invalidate(e,t,i){var s=e.sx+e.sy*this.size.width;let r=this.invalidations.get(s);r||(r={center:e,elevation:0,radius:0},this.invalidations.set(s,r)),r.elevation=Math.max(r.elevation,t),r.radius=Math.max(r.radius,i)}revealFrom(e){var t,i;e.isBuilding()&&e.wallTrait||(t=e.sight)&&(i=e.tile.z+e.tileElevation,e=this.rxyzToSxy(e.tile.rx,e.tile.ry,i),this.invalidate(e,i,t))}revealAround(e,t){e=this.rxyzToSxy(e.rx,e.ry,e.z);this.invalidate(e,Number.POSITIVE_INFINITY,t)}unrevealAround(e,t){var i=[],e=this.rxyzToSxy(e.rx,e.ry,e.z);this.setValueAround(e,t,Number.POSITIVE_INFINITY,i,_n.Unexplored,_n.Explored),this._onChange.dispatch(this,{type:"incremental",coords:i})}revealTemporarily(e){e=this.rxyzToSxy(e.tile.rx,e.tile.ry,e.tile.z+e.tileElevation);this.temporaryReveals.set(e,5*js.BASE_TICKS_PER_SECOND)}revealObject(e){e=this.rxyzToSxy(e.tile.rx,e.tile.ry,e.tile.z+e.tileElevation);this.invalidate(e,Number.POSITIVE_INFINITY,4.25)}toggleFlagsAround(e,t,i,s){var r=[],e=this.rxyzToSxy(e.rx,e.ry,e.z);this.setValueAround(e,t,Number.POSITIVE_INFINITY,r,void 0,void 0,s?{setFlags:i}:{clearFlags:i}),this._onChange.dispatch(this,{type:"incremental",coords:r})}update(){let i=[];if(this.invalidations.size){for(var e of this.invalidations.values())this.setValueAround(e.center,e.radius,e.elevation,i,_n.Explored,[_n.Unexplored,_n.TemporaryReveal]);this.invalidations.clear()}this.temporaryReveals.size&&this.temporaryReveals.forEach((e,t)=>{e<=0?(this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,_n.Unexplored,_n.TemporaryReveal),this.temporaryReveals.delete(t)):(e===5*js.BASE_TICKS_PER_SECOND&&this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,_n.TemporaryReveal,_n.Unexplored),this.temporaryReveals.set(t,e-1))}),this.fullInvalidation?(this.fullInvalidation=!1,this._onChange.dispatch(this,{type:"full"})):i.length&&this._onChange.dispatch(this,{type:"incremental",coords:i})}setValueAround(s,r,a,n,o,h=void 0,{setFlags:l,clearFlags:c}={}){var e=Math.ceil(r),t=z(s.sx-e,0,this.size.width-1),u=z(s.sx+e,0,this.size.width-1),d=z(s.sy-e,0,this.size.height-1),p=z(s.sy+e,0,this.size.height-1),g=this.size.width;for(let i=t;i<=u;i++)for(let t=d;t<=p;t++){var m=i+t*g,f=7&this.tiles[m],y=this.tiles[m]>>3<<3;let e=y;void 0!==l&&(e|=l),void 0!==c&&(e&=~c),void 0!==h&&("number"!=typeof h?!h.includes(f):h!==f)||((i-s.sx)*(i-s.sx)+(t-s.sy)*(t-s.sy)>r*r+1||this.tileElevation[m]>=a+4||(this.tiles[m]=(o??f)|e,f===o&&y===e||n.push({sx:i,sy:t})))}}revealAll(){this.tiles.fill(_n.Explored),this._onChange.dispatch(this,{type:"clear"})}reset(){this.tiles.fill(_n.Unexplored),this._onChange.dispatch(this,{type:"cover"})}}class zo{constructor(e){this.radiusTiles=e,this.refreshTicks=0}[Fr.onTick](e,t){0<this.refreshTicks&&this.refreshTicks--,this.refreshTicks<=0&&this.update(e,t)}[Yr.onSpawn](e,t){this.markGapTilesForFriendlies(e,e.owner,t,!0)}[Kr.onUnspawn](e,t){this.markGapTilesForFriendlies(e,e.owner,t,!1),this.update(e,t)}[Qr.onChange](e,t,i){this.markGapTilesForFriendlies(e,t,i,!1),this.markGapTilesForFriendlies(e,e.owner,i,!0),this.update(e,i)}[vn.onChange](e,t,i){this.markGapTilesForFriendlies(e,e.owner,t,!i),i&&this.update(e,t)}markGapTilesForFriendlies(i,e,s,t){let r=[e,...s.alliances.getAllies(e)],a;for(var n of r){let e=s.mapShroudTrait.getPlayerShroud(n);if(e&&(e.toggleFlagsAround(i.tile,this.radiusTiles,In.Darken,t),!t)){if(!a){let t=new As(s.map.tileOccupation);a=r.map(e=>[...e.buildings]).flat().filter(e=>e.gapGeneratorTrait&&e!==i&&t.tileDistance(e,i)<=e.gapGeneratorTrait.radiusTiles+this.radiusTiles)}for(var o of a)e.toggleFlagsAround(o.tile,o.gapGeneratorTrait.radiusTiles,In.Darken,!0)}}}update(t,i){this.refreshTicks=5*js.BASE_TICKS_PER_SECOND;let s;var r,a,n,o,h=t.owner.buildings.has(t)&&t.poweredTrait?.isPoweredOn();for(r of i.getCombatants())if(r!==t.owner&&!i.alliances.areAllied(t.owner,r)){let e=i.mapShroudTrait.getPlayerShroud(r);if(e)if(h){e.unrevealAround(t.tile,this.radiusTiles),s||(n=this.radiusTiles+os.MAX_SIGHT,a=new ks(t.tile.rx,t.tile.ry).addScalar(-n),n=new ks(t.tile.rx,t.tile.ry).addScalar(n),s=i.map.technosByTile.queryRange(new jn(a,n)));for(o of s)o.owner===r||i.alliances.areAllied(o.owner,r)?e.revealFrom(o):o.rules.revealToAll&&e.revealObject(o)}else[...r.buildings].some(e=>e.rules.spySat)&&e.revealAround(t.tile,this.radiusTiles)}}}const Vo=js.BASE_TICKS_PER_SECOND;class Ho{constructor(e){this.radiusTiles=e,this.detectionLines=[],this.nextScan=Vo}[Fr.onTick](e,t){e.owner.powerTrait?.isLowPower()?this.disable():(0<this.nextScan&&this.nextScan--,this.nextScan<=0&&(this.nextScan=Vo,this.detectionLines=this.scan(e,t)))}[vn.onChange](e,t,i){i&&this.disable()}disable(){this.detectionLines.length&&(this.detectionLines=[],this.nextScan=0)}scan(t,i){var e=i.getCombatants().filter(e=>e!==t.owner&&!i.alliances.areAllied(e,t.owner));let s=[],r=new As(i.map.tileOccupation);var a,n,o,h=e=>r.distance2(e,t)/Os.LEPTONS_PER_TILE<=this.radiusTiles;for(a of e)for(var l of a.getOwnedObjects())l.attackTrait?.currentTarget?h((n=l.attackTrait.currentTarget).obj??n.tile)&&s.push({source:l,target:n}):l.isUnit()&&l.unitOrderTrait.targetLinesConfig&&((o=l.unitOrderTrait.targetLinesConfig).target?h(o.target)&&(n=i.createTarget(o.target,o.target.tile),s.push({source:l,target:n})):(o=o.pathNodes[0])&&h(o.tile)&&(o=i.createTarget(o.onBridge,o.tile),s.push({source:l,target:o})));return s}}class Go{constructor(){this.healQueue=[]}addToHealQueue(e){return this.healQueue.push(e),this.healQueue.length-1}unitIsFirstInHealQueue(e){return this.healQueue[0]===e}removeFromHealQueue(e){e=this.healQueue.indexOf(e);-1!==e&&this.healQueue.splice(e,1)}startHealing(e){if(this.unit)throw new Error(`Already busy healing unit ${xt[this.unit.type]}#${this.unit.id}}`);this.unit=e,this.healTicks=5*js.BASE_TICKS_PER_SECOND}[Fr.onTick](e,t){var i;this.healQueue=this.healQueue.filter(e=>!e.isDestroyed&&!e.isCrashing),this.unit&&void 0!==this.healTicks&&(0<this.healTicks&&this.healTicks--,this.healTicks<=0&&(this.healTicks=void 0,this.removeFromHealQueue(this.unit),this.unit.healthTrait.healToFull(e,t),e.ammoTrait&&e.ammoTrait.ammo--,this.evacuate(this.unit,e,t),i=this.unit,this.unit=void 0,t.events.dispatch(new Eo(i,e))))}[zr.onDestroy](e,t,i){this.unit&&(t.destroyObject(this.unit,i,!0),this.unit=void 0)}evacuate(t,i,s){let e;var r={x:i.tile.rx,y:i.tile.ry+i.art.foundation.height},r=s.map.tiles.getByMapCoords(r.x,r.y);r&&s.map.isWithinBounds(r)&&this.canEvacuateTo(r,t,i,s)&&(e=r),e=e||new Us(s.map.tiles,s.map.mapBounds,i.tile,i.art.foundation,1,1,e=>this.canEvacuateTo(e,t,i,s)).getNextTile(),e?(s.unlimboObject(t,e),t.unitOrderTrait.addTask(new Sa(s))):s.destroyObject(t,{player:t.owner})}canEvacuateTo(e,t,i,s){return 0<s.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&Math.abs(e.z-i.tile.z)<2&&!s.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length}}class $o{constructor(){this.timer=new Do}isActive(){return this.timer.isActive()}activate(e,t){this.isActive()||(this.timer.setActiveFor(e),this.attackerInfo=t)}[Fr.onTick](e,t){this.timer.isActive()&&!0===this.timer.tick(t.currentTick)&&(e.invulnerableTrait.isActive()||e.isBuilding()&&e.cabHutTrait||t.destroyObject(e,this.attackerInfo,!0,!0))}}(r=Cn=Cn||{})[r.BuildUp=0]="BuildUp",r[r.Ready=1]="Ready",r[r.BuildDown=2]="BuildDown";class qo extends xa{constructor(e,t,i){super(xt.Building,e,t,i),this.showWeaponRange=!1,this.wallType=[0,0,0,0],this.direction=0,this.buildStatus=Cn.BuildUp,this.lastBuildStatus=this.buildStatus}static factory(e,t,i,s,r,a){let n=new this(e,t,s);return t.canBeOccupied&&(n.garrisonTrait=new Yn(n,i.audioVisual.conditionRed,t.maxNumberOccupants),n.traits.add(n.garrisonTrait)),t.canC4&&!t.wall&&(n.c4ChargeTrait=new Ro,n.traits.add(n.c4ChargeTrait)),t.eligibleForDelayKill&&(n.delayedKillTrait=new $o,n.traits.add(n.delayedKillTrait)),t.bridgeRepairHut&&(n.cabHutTrait=new Co(n,a),n.traits.add(n.cabHutTrait)),t.crewed&&(n.crewedTrait=new Io,n.traits.add(n.crewedTrait)),t.turret&&(n.turretTrait=new Kn,n.traits.add(n.turretTrait)),t.overpowerable&&(n.overpoweredTrait=new xo(n),n.traits.add(n.overpoweredTrait)),(t.powered&&0!==t.power||t.needsEngineer)&&(n.poweredTrait=new ro(n),n.traits.add(n.poweredTrait)),(t.factory||t.cloning)&&(n.factoryTrait=new ko(t.cloning?es.InfantryType:t.factory,t.cloning),n.traits.add(n.factoryTrait)),t.superWeapon&&(n.superWeaponTrait=new Uo(t.superWeapon),n.traits.add(n.superWeaponTrait)),t.numberOfDocks&&(n.dockTrait=new bo(n,r,t.numberOfDocks,s.dockingOffsets),n.traits.add(n.dockTrait),t.helipad&&(n.helipadTrait=new Lo,n.traits.add(n.helipadTrait)),(t.unitRepair||t.unitReload)&&(n.unitRepairTrait=new No,n.traits.add(n.unitRepairTrait)),t.unitReload&&(n.unitReloadTrait=new Fo,n.traits.add(n.unitReloadTrait))),t.hospital&&(n.hospitalTrait=new Go,n.traits.add(n.hospitalTrait)),(t.factory||t.cloning||t.numberOfDocks)&&(n.rallyTrait=new Mo,n.traits.add(n.rallyTrait)),t.freeUnit&&n.traits.add(new _o),t.produceCashStartup&&n.traits.add(new Ao),t.wall&&(n.wallTrait=new Bo,n.traits.add(n.wallTrait)),t.gapGenerator&&(n.gapGeneratorTrait=new zo(t.gapRadiusInCells),n.traits.add(n.gapGeneratorTrait)),t.psychicDetectionRadius&&(n.psychicDetectorTrait=new Ho(t.psychicDetectionRadius),n.traits.add(n.psychicDetectorTrait)),n}isBuilding(){return!0}getFoundation(){return this.art.foundation}getFoundationCenterOffset(){var e=this.getFoundation();return new ks(e.width/2*Os.LEPTONS_PER_TILE,e.height/2*Os.LEPTONS_PER_TILE)}update(e){this.buildStatus!==Cn.BuildUp||this.unitOrderTrait.hasTasks()||this.unitOrderTrait.addTask(new jo(e.rules.general.buildupTime)),this.buildStatus!==this.lastBuildStatus&&(this.lastBuildStatus=this.buildStatus,e.events.dispatch(new Jn(this,this.buildStatus))),this.attackTrait?.setDisabled(this.buildStatus!==Cn.Ready||!!this.poweredTrait&&!this.poweredTrait.isPoweredOn()),super.update(e)}}class Xo extends Ba{constructor(e,t,i){super(xt.Terrain,e,t,i),this.radarInvisible=this.rules.radarInvisible}static factory(e,t,i){return new this(e,t,i)}}class Zo extends Ba{constructor(e,t,i){super(xt.Overlay,e,t,i),this.radarInvisible=this.rules.radarInvisible}static factory(e,t,i){let s=new this(e,t,i);return t.wall&&(s.wallTrait=new Bo,s.traits.add(s.wallTrait)),s}isTiberium(){return qa.getOverlayTibType(this.overlayId)!==oa.NotSpecial}isBridge(){return Ha.isBridge(this.overlayId)}isXBridge(){return Ha.isXBridge(this.overlayId)}isHighBridge(){return Ha.isHighBridge(this.overlayId)}isLowBridge(){return Ha.isLowBridge(this.overlayId)}isBridgePlaceholder(){return Ha.isBridgePlaceholder(this.overlayId)}getFoundation(){let e={width:1,height:1};return this.isBridge()&&(this.isXBridge()?e.height+=2:e.width+=2),e}}class Qo extends Ba{constructor(e,t,i){super(xt.Smudge,e,t,i)}static factory(e,t,i){return new this(e,t,i)}getFoundation(){return{width:this.rules.width,height:this.rules.height}}}class Yo extends ka{constructor(e,t,i,s){super(e,i??t,!1,{closeEnoughTiles:i?void 0:0,strictCloseEnough:!i}),this.teleportTile=t,this.teleportCondition=s}onStart(e){if(super.onStart(e),!e.harvesterTrait||e.rules.locomotor!==si.Chrono)throw new Error(`Vehicle ${e.name} is not a chrono miner`)}onTick(e){return!e.moveTrait.isDisabled()&&(!(this.isCancelling()||e.moveTrait.moveState!==qr.ReachedNextWaypoint||e.tile===this.teleportTile||!this.tryTeleportToRefinery(e))||!0===super.onTick(e)&&(this.isCancelling()||e.tile===this.teleportTile||this.tryTeleportToRefinery(e),!0))}tryTeleportToRefinery(e){return(!this.teleportCondition||!1!==this.teleportCondition(e,this.teleportTile))&&(!this.game.map.terrain.findObstacles({tile:this.teleportTile,onBridge:void 0},e).length&&(e.moveTrait.teleportUnitToTile(this.teleportTile,void 0,!0,!0,this.game),e.zone===vs.Air&&(e.zone=vs.Ground,e.position.tileElevation=0),!0))}}const Ko=[[8,5,6],[3,0,2],[7,4,1]];class Jo extends Gs{constructor(e,t,i=!1){super(),this.game=e,this.initialTarget=t,this.explicitOrder=i,this.forceMoveTried=!1,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.rangeHelper=new As(e.map.tileOccupation),this.scanNearRadius=e.rules.ai.tiberiumNearScan,this.scanFarRadius=e.rules.ai.tiberiumFarScan,this.strictTarget=i}onStart(e){if(!e.isVehicle()||!e.harvesterTrait)throw new Error(`Unit ${e.name} is not a harvester.`);e.harvesterTrait.status=xn.MovingToOreSite,e.harvesterTrait.lastGatherExplicit=this.explicitOrder}onEnd(e){e.harvesterTrait.status!==xn.LookingForOreSite&&(e.harvesterTrait.status=xn.Idle)}onTick(i){if(this.isCancelling())return!0;let s=i.harvesterTrait;if(s.status===xn.MovingToOreSite){if(this.target=this.initialTarget?.landType===Jt.Tiberium?this.initialTarget:this.findClosestReachableOreSite(i,s.lastOreSite??i.tile,!0),s.lastOreSite=this.target,!this.target){s.status=xn.LookingForOreSite;let e=this.getRefineryOnTile(i.tile);if(e&&1===i.unitOrderTrait.getTasks().length){let t=i.rules.movementZone===ri.Fly;var r=new Us(this.game.map.tiles,this.game.map.mapBounds,e.tile,e.getFoundation(),1,5,e=>t||0<this.game.map.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&Math.abs(e.z-i.tile.z)<2&&!this.game.map.terrain.findObstacles({tile:e,onBridge:void 0},i).length).getNextTile();r&&i.unitOrderTrait.addTasks(new ka(this.game,r,!1),new ma(()=>{[Xr.Success,Xr.CloseEnough,Xr.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new ga(1/60))}))}return!0}var a=this.game.rules.general.closeEnough,r=this.rangeHelper.tileDistance(i.tile,this.target)<=a;if(i.tile!==this.target&&(i.tile.landType!==Jt.Tiberium||!r||this.strictTarget)){if(i.tile!==this.target&&r&&i.tile.landType!==Jt.Tiberium){r=this.findClosestReachableOreSite(i,i.tile,!1,!0);if(r)this.target=r,s.lastOreSite=this.target;else{if(!this.forceMoveTried)return this.forceMoveTried=!0,this.children.push(new ka(this.game,this.target,!1,{closeEnoughTiles:0,strictCloseEnough:!0})),!1;if(this.forceMoveTried=!1,!s.isEmpty())return this.returnOreIfPossible(i),!0;r=this.findClosestReachableOreSite(i,i.tile,!0,!0);if(!r)return s.status=xn.LookingForOreSite,!0;this.target=r,s.lastOreSite=this.target}}return this.children.push(new ka(this.game,this.target,!1,{closeEnoughTiles:a}),new ma(()=>{[Xr.Success,Xr.CloseEnough,Xr.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new ga(5/60))})),!1}this.target=i.tile,s.lastOreSite=this.target,s.status=xn.Harvesting,this.forceMoveTried=!1,this.strictTarget=!1}if(s.status!==xn.Harvesting)return!1;{if(s.isFull())return this.returnOreIfPossible(i),!0;let e=this.game.map.getObjectsOnTile(i.tile).find(e=>e.isOverlay()&&e.isTiberium());if(!e)return this.findClosestReachableOreSite(i,s.lastOreSite??i.tile,!1)||s.isEmpty()?(s.status=xn.MovingToOreSite,this.onTick(i)):(this.returnOreIfPossible(i),!0);let t=e.traits.get(Xa);a=t.collectBail();if(t.getBailCount()||this.game.unspawnObject(e),void 0!==a)if(a===ha.Ore)s.ore++;else{if(a!==ha.Gems)throw new Error(`Unsupported tiberium type ${a}`);s.gems++}return[...i.owner.buildings].some(e=>e.rules.refinery)||this.explicitOrder?(this.children.push(new ga(1/60)),!1):!0}}findClosestReachableOreSite(t,i,e,s=!1){let r=t.rules.movementZone===ri.Fly;var a,n=e=>e.landType===Jt.Tiberium&&(!s||(r||!this.game.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length));if(n(i))return i;let o=1;if(!e){let e=new Us(this.game.map.tiles,this.game.map.mapBounds,i,{width:1,height:1},o,o,n),t=[];for(;a=e.getNextTile();)t.push(a);if(t.length){let e=t.map(e=>{var t=this.game.map.getObjectsOnTile(e).find(e=>e.isOverlay()&&e.isTiberium());if(!t)throw new Error(`Ore should exist on tile ${e.rx},${e.ry} b/c of landType`);return{tile:e,ore:t}});return e.sort((e,t)=>1e3*(t.ore.value-e.ore.value)+(Ko[1+t.tile.ry-i.ry][1+t.tile.rx-i.rx]-Ko[1+e.tile.ry-i.ry][1+e.tile.rx-i.rx])),e[0].tile}o=2}e=e?this.scanFarRadius:this.scanNearRadius;let h=new Us(this.game.map.tiles,this.game.map.mapBounds,i,{width:1,height:1},o,e,n);return h.getNextTile()}getRefineryOnTile(e){return this.game.map.getObjectsOnTile(e).find(e=>e.isBuilding()&&e.rules.refinery)}returnOreIfPossible(e){1===e.unitOrderTrait.getTasks().length&&e.unitOrderTrait.addTask(new eh(this.game))}getTargetLinesConfig(e){return{pathNodes:this.initialTarget?[{tile:this.initialTarget,onBridge:void 0}]:[]}}}class eh extends Gs{constructor(e,t,i=!1,s=!1){super(),this.game=e,this.forceTarget=t,this.resetLastOreSite=i,this.explicitOrder=s,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.rangeHelper=new As(e.map.tileOccupation)}onStart(e){if(!e.isVehicle()||!e.harvesterTrait)throw new Error(`Unit ${e.name} is not a harvester.`);e.harvesterTrait.status=xn.MovingToRefinery,this.resetLastOreSite&&(e.harvesterTrait.lastOreSite=void 0)}onEnd(e){this.target?.isSpawned&&(this.target.dockTrait.undockUnit(e),this.target.dockTrait.unreserveDockForUnit(e)),e.harvesterTrait.status!==xn.LookingForRefinery&&(e.harvesterTrait.status=xn.Idle)}onTick(s){if(this.isCancelling())return!0;let r=s.harvesterTrait;if(r.status===xn.LookingForRefinery)return!0;if(r.status===xn.MovingToRefinery){if(!this.target||!this.isValidTargetRefinery(this.target,s)||s.tile!==this.findRefineryDockingTile(this.target)){var a=this.forceTarget??this.findClosestReachableRefinery(s);if(!a)return r.status=xn.LookingForRefinery,!0;this.target&&this.target!==a&&this.target.dockTrait.hasReservedDockForUnit(s)&&this.target.dockTrait.unreserveDockForUnit(s),this.target=a}let e=this.target.dockTrait.getFirstAvailableDockNumber(),t=!1;void 0===e&&(e=this.target.dockTrait.getFirstEmptyDockNumber(),void 0!==e&&(t=!this.target.dockTrait.hasReservedDockForUnit(s)));let i=this.findRefineryDockingTile(this.target);var n=this.rangeHelper.tileDistance(s,i);if(void 0===e||t||n>this.game.rules.general.harvesterTooFarDistance&&!this.explicitOrder){var o=this.findReachableQueueingTile(s);return o?(s.tile!==o&&this.children.push(s.rules.teleporter?new Yo(this.game,i,o,()=>this.chronoMinerCanTeleport(s,i,this.target)):new ka(this.game,o,!1),new ma(()=>{s.moveTrait.lastMoveResult===Xr.Fail?r.status=xn.LookingForRefinery:s.moveTrait.lastMoveResult===Xr.CloseEnough?this.children.push(new ga(5/60)):s.moveTrait.lastMoveResult===Xr.Success&&this.children.push(new ga(2/60))})),!1):!0}if(this.target.dockTrait.hasReservedDockForUnit(s)||this.target.dockTrait.reserveDockAt(s,e),void 0===this.reservedDockNumber&&(this.reservedDockNumber=this.target.dockTrait.getReservedDockForUnit(s)),s.tile!==i)return this.children.push(s.rules.teleporter?new Yo(this.game,i,void 0,()=>this.chronoMinerCanTeleport(s,i,this.target)):new ka(this.game,i,!1,{closeEnoughTiles:0,strictCloseEnough:!0}),new ma(()=>{s.moveTrait.lastMoveResult===Xr.Fail&&(r.status=xn.LookingForRefinery)})),!1;r.status=xn.Docking}if(!this.isValidTargetRefinery(this.target,s))return r.status=xn.MovingToRefinery,this.forceTarget=void 0,this.onTick(s);if(r.status===xn.Docking){if(270!==s.direction)return this.children.push(new vr(270)),!1;this.target.dockTrait.dockUnitAt(s,this.reservedDockNumber),this.reservedDockNumber=void 0,r.status=xn.PreparingToUnload}if(r.status===xn.PreparingToUnload)return this.preventOpportunityFire=!0,this.children.push(new ga(2/60)),r.status=xn.Unloading,!1;if(r.status!==xn.Unloading)return!1;a=r.ore*this.game.rules.getTiberium(ha.Ore).value+r.gems*this.game.rules.getTiberium(ha.Gems).value;this.target.owner.credits+=a;n=[...this.target.owner.buildings].filter(e=>e.rules.orePurifier&&(!e.poweredTrait||!this.target.owner.powerTrait?.isLowPower())).length,o=this.game.rules.general.purifierBonus;return this.target.owner.credits+=n*Math.floor(a*o),r.ore=0,r.gems=0,1===s.unitOrderTrait.getTasks().length&&s.unitOrderTrait.addTask(new Jo(this.game)),!0}isValidTargetRefinery(e,t){return e.isSpawned&&this.game.areFriendly(e,t)&&!e.warpedOutTrait.isActive()}findClosestReachableRefinery(i){let s=this.rangeHelper,e=[...i.owner.buildings].filter(e=>e.rules.refinery&&e.dockTrait&&!e.warpedOutTrait.isActive()).sort((e,t)=>s.distance2(i,e)-s.distance2(i,t));var t=e[0],r=e.find(e=>0<e.dockTrait.getAvailableDockCount());return!r||t&&s.tileDistance(i,r.centerTile)-s.tileDistance(i,t.centerTile)>this.game.rules.general.harvesterTooFarDistance?t:r}findReachableQueueingTile(t){if(this.target.art.queueingCell){var e=new ks(this.target.tile.rx,this.target.tile.ry).add(this.target.art.queueingCell),e=this.game.map.tiles.getByMapCoords(e.x,e.y);if(e&&this.isValidQueueingTile(e,t))return e}return new Us(this.game.map.tiles,this.game.map.mapBounds,this.target.tile,this.target.getFoundation(),1,1,e=>this.isValidQueueingTile(e,t)).getNextTile()}isValidQueueingTile(e,t){return t.zone===vs.Air||0<this.game.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&Math.abs(e.z-this.target.tile.z)<2&&!e.onBridgeLandType}findRefineryDockingTile(e){e={x:e.tile.rx+e.getFoundation().width-1,y:e.tile.ry+Math.floor(e.getFoundation().height/2)};return this.game.map.tiles.getByMapCoords(e.x,e.y)}chronoMinerCanTeleport(e,t,i){let s=this.rangeHelper;t=s.tileDistance(e,t);return!(!this.forceTarget&&t>this.game.rules.general.chronoHarvTooFarDistance)&&(!(t<=1)&&(!!this.isValidTargetRefinery(i,e)&&!(0===i.dockTrait.getAvailableDockCount()&&!i.dockTrait.hasReservedDockForUnit(e))))}}(An=An||{}).onPush=Symbol(),(r=Bn=Bn||{})[r.Move=0]="Move",r[r.ForceMove=1]="ForceMove",r[r.Attack=2]="Attack",r[r.ForceAttack=3]="ForceAttack",r[r.AttackMove=4]="AttackMove",r[r.Guard=5]="Guard",r[r.GuardArea=6]="GuardArea",r[r.Capture=7]="Capture",r[r.Occupy=8]="Occupy",r[r.Deploy=9]="Deploy",r[r.DeploySelected=10]="DeploySelected",r[r.Stop=11]="Stop",r[r.Cheer=12]="Cheer",r[r.Dock=13]="Dock",r[r.Gather=14]="Gather",r[r.Repair=15]="Repair",r[r.Scatter=16]="Scatter",r[r.EnterTransport=17]="EnterTransport",r[r.PlaceBomb=18]="PlaceBomb",(r=xn=xn||{})[r.Idle=0]="Idle",r[r.LookingForOreSite=1]="LookingForOreSite",r[r.MovingToOreSite=2]="MovingToOreSite",r[r.Harvesting=3]="Harvesting",r[r.LookingForRefinery=4]="LookingForRefinery",r[r.MovingToRefinery=5]="MovingToRefinery",r[r.Docking=6]="Docking",r[r.PreparingToUnload=7]="PreparingToUnload",r[r.Unloading=8]="Unloading";class th{constructor(e){this.storage=e,this.ore=0,this.gems=0,this.status=xn.Idle,this.lastGatherExplicit=!1,this.autoGatherOnNextIdle=!1,this.ticksSinceLastRefineryCheck=0,this.ticksSinceLastOreCheck=0}[Yr.onSpawn](e,t){e.owner.isCombatant()&&(t.afterTick(()=>{e.unitOrderTrait.addTask(new Jo(t))}),e.attackTrait?.increasePassiveScanCooldown(1))}[Qr.onChange](e,t,i){!t.isCombatant()&&e.owner.isCombatant()&&i.afterTick(()=>{e.unitOrderTrait.addTask(new Jo(i))})}[Fr.onTick](e,t){this.status===xn.LookingForRefinery?this.ticksSinceLastRefineryCheck++>5*js.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastRefineryCheck=0,e.unitOrderTrait.hasTasks()?this.ticksSinceLastRefineryCheck=-25*js.BASE_TICKS_PER_SECOND:[...e.owner.buildings].some(e=>e.rules.refinery)||this.lastGatherExplicit?e.unitOrderTrait.addTask(new eh(t)):this.status=xn.Idle):this.status===xn.LookingForOreSite?this.ticksSinceLastOreCheck++>20*js.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastOreCheck=0,e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new Jo(t))):this.status===xn.Idle&&this.autoGatherOnNextIdle&&e.unitOrderTrait.isIdle()&&e.tile.landType===Jt.Tiberium&&(this.autoGatherOnNextIdle=!1,e.unitOrderTrait.addTask(new Jo(t,e.tile,!0)))}[Wr.onBeforeTeleport](e,t,i,s){!s&&e.owner.isCombatant()&&(this.status=xn.Idle,this.lastOreSite=void 0,i&&e.rules.teleporter&&t.afterTick(()=>{e.unitOrderTrait.addTask(new(this.isFull()?eh:Jo)(t))}))}[An.onPush](e,t){this.autoGatherOnNextIdle=[Bn.AttackMove,Bn.Move,Bn.ForceMove,Bn.Scatter].includes(t),[xn.LookingForRefinery,xn.LookingForOreSite].includes(this.status)&&(this.status=xn.Idle)}isFull(){return this.ore+this.gems>=this.storage}isEmpty(){return!this.ore&&!this.gems}getHash(){return 100*this.ore+this.gems}debugGetState(){return{ore:this.ore,gems:this.gems}}}class ih{constructor(e){this.target=e,this.type=ss.LeaveTransport}}class sh{constructor(e){this.obj=e,this.units=[],this.loadQueue=[]}unitFitsInside(e){return e.rules.size<=this.obj.rules.sizeLimit&&e.rules.size<=this.getAvailableCapacity()}getOccupiedCapacity(){return this.units.reduce((e,t)=>e+t.rules.size,0)}getMaxCapacity(){return this.obj.rules.passengers}getAvailableCapacity(){return this.getMaxCapacity()-this.getOccupiedCapacity()}addToLoadQueue(e){return this.loadQueue.push(e),this.loadQueue.length-1}unitIsFirstInLoadQueue(e){return this.loadQueue[0]===e}removeFromLoadQueue(e){e=this.loadQueue.indexOf(e);-1!==e&&this.loadQueue.splice(e,1)}[Fr.onTick](e,t){this.loadQueue=this.loadQueue.filter(e=>!e.isDestroyed&&!e.isCrashing)}[zr.onDestroy](e,t,i,s){var r=!!e.armedTrait?.deathWeapon,a=i?.weapon?.warhead.rules.parasite;if(s||r||e.zone===vs.Air||a)for(var n of this.units)r&&n.armedTrait&&(n.armedTrait.deathWeapon=void 0),n.position.tileElevation=e.position.tileElevation,n.zone=e.zone,n.onBridge=e.onBridge,n.position.tile=e.tile,t.destroyObject(n,i,!0);else this.spawnSurvivors(t);this.units=[]}spawnSurvivors(e){var t=this.obj;if(this.units.length){for(var i of this.units)0<e.map.terrain.getPassableSpeed(t.tile,i.rules.speedType,t.onBridge)?(i.owner.addOwnedObject(i),i.position.tileElevation=t.onBridge?e.map.tileOccupation.getBridgeOnTile(t.tile).tileElevation:0,i.onBridge=t.onBridge,i.zone=e.map.getTileZone(t.tile,!t.onBridge),e.unlimboObject(i,t.tile),i.unitOrderTrait.addTask(new Sa(e))):(i.position.tileElevation=t.position.tileElevation,i.zone=t.zone,i.onBridge=t.onBridge,i.position.tile=t.tile,e.destroyObject(i,{player:i.owner}));e.events.dispatch(new ih(t))}}getHash(){return G(this.units.map(e=>e.getHash()))}debugGetState(){return this.units.map(e=>e.debugGetState())}dispose(){this.obj=void 0}}class rh{[Fr.onTick](e){var t,i;!!e.transportTrait.units.length!==this.lastHadGunner&&(this.lastHadGunner=!!e.transportTrait.units.length,i=t=e.transportTrait.units[0]?.rules.ifvMode??0,(t=e.rules.turretIndexesByIfvMode.get(t)??0)<e.rules.turretCount&&(e.turretNo=t,e.armedTrait?.selectSpecialWeapon(i,e.veteranLevel===ea.Elite)))}getUiNameForIfvMode(e,t){switch(e){case 0:return"tip:rocket";case 1:return"tip:repair";case 2:case 4:case 5:return"tip:machinegun";default:return t?"name:"+t.toLowerCase():void 0}}}(En=En||{}).onHeal=Symbol();class ah{constructor(e){this.gameObject=e,this.beingBoarded=!1}infest(e,t){this.beingBoarded=!1,this.parasite=e,this.parasiteWeapon=t,e.rules.organic?this.damageTickCooldown=ch+2:this.damageTickCooldown=0,this.lastExternalDamageInflicted=void 0,this.lastExternalDamageTick=void 0,t.warhead.rules.paralyzes&&this.gameObject.moveTrait.setDisabled(!0)}isInfested(){return!(!this.parasite||this.parasite.isDestroyed)||this.beingBoarded}isParalyzed(){return!!this.parasiteWeapon?.warhead.rules.paralyzes}uninfest(){this.parasite&&(this.parasiteWeapon.warhead.rules.paralyzes&&this.gameObject.moveTrait.setDisabled(!1),this.parasite=void 0,this.parasiteWeapon=void 0)}getParasite(){return this.parasite}[Fr.onTick](s,r){if(this.parasite)if(this.parasite.isDestroyed)this.uninfest();else if(0<this.damageTickCooldown)this.damageTickCooldown--;else{let e=this.parasiteWeapon;this.damageTickCooldown=this.parasite.rules.organic?ch+2:e.getCooldownTicks();let t=e.rules.damage;this.parasite.veteranTrait&&(t*=this.parasite.veteranTrait.getVeteranDamageMultiplier());let i=e.warhead.computeDamage(t,s);this.canBeCulled(s,this.parasite,e,r)&&(i=s.healthTrait.getHitPoints()),e.warhead.inflictDamage(i,s,{player:this.parasite.owner,obj:this.parasite,weapon:e},r),s.isCrashing?(this.parasiteWeapon.expireCooldown(),this.evictOrDestroyParasite(s,r)):!s.isDestroyed&&s.isVehicle()&&s.zone!==vs.Air&&e.warhead.rules.rocker&&s.applyRocking(90*(.5<=r.generateRandom()?1:-1),1)}}canBeCulled(e,t,i,s){if(!i.warhead.rules.culling)return!1;s=s.rules.audioVisual,s=t.veteranTrait?.isElite()?s.conditionYellow:s.conditionRed;return e.healthTrait.health<=100*s}[En.onHeal](e,t,i,s){var r;!this.parasite||this.parasite.isDestroyed||s===e||e.isAircraft()&&s?.rules.unitReload||(this.parasite.rules.organic?(r=this.parasite,this.evictOrDestroyParasite(e,t),this.stunParasite(r,t)):(this.parasite.deathType=Vr.None,t.destroyObject(this.parasite,s?{player:s.owner,obj:s}:void 0),this.uninfest()))}[ua.onDamage](e,t,i,s){s?.obj!==this.parasite&&(this.lastExternalDamageInflicted=i,this.lastExternalDamageTick=t.currentTick)}[Jr.onAttack](i,s,r){if(this.parasite&&!this.parasite.isDestroyed&&s?.weapon?.warhead.rules.sonic){var a=this.parasite;this.evictOrDestroyParasite(i,r),this.stunParasite(a,r);let e=s.weapon.warhead;e.canDamage(a,a.tile,a.zone)&&(i=e.computeDamage(s.weapon.rules.damage,a),e.inflictDamage(i,a,s,r));let t=s.obj?.unitOrderTrait.getCurrentTask();t instanceof go&&t.getWeapon().warhead.rules.sonic&&t.cancel()}}[zr.onDestroy](e,t,i,s){this.parasite&&!this.parasite.isDestroyed&&(s||!this.parasite.invulnerableTrait.isActive()&&this.shouldSupressParasite(t,this.parasite,i)?(this.parasite.deathType=Vr.None,t.destroyObject(this.parasite,i,s),this.uninfest()):(this.parasiteWeapon.expireCooldown(),this.evictOrDestroyParasite(e,t)))}shouldSupressParasite(e,t,i){return i?.obj!==t||this.lastExternalDamageInflicted&&this.lastExternalDamageInflicted>t.rules.suppressionThreshold&&e.currentTick-this.lastExternalDamageTick<2*this.lastExternalDamageInflicted}[Wr.onBeforeTeleport](e,t,i,s){i&&s&&this.parasite&&!this.parasite.isDestroyed&&(this.parasiteWeapon.expireCooldown(),s=this.parasite,this.evictOrDestroyParasite(e,t,!0),s.isDestroyed||this.stunParasite(s,t))}stunParasite(e,t){e.unitOrderTrait.addTaskToFront(new ga(10/60).setCancellable(!1)),e.isVehicle()&&e.submergibleTrait&&(e.submergibleTrait.emerge(e,t),e.cloakableTrait?.uncloak(t),e.submergibleTrait.setCooldown(10*js.BASE_TICKS_PER_SECOND))}evictOrDestroyParasite(s,r,a=!1){if(this.parasite&&!this.parasite.isDestroyed){var e=s.zone===vs.Air;if(e&&this.parasite.rules.movementZone!==ri.Fly||!e&&!r.map.terrain.getPassableSpeed(s.tile,this.parasite.rules.speedType,s.onBridge)&&!r.map.getObjectsOnTile(s.tile).find(e=>e.isBuilding()))this.parasite.deathType=Vr.None,r.destroyObject(this.parasite,{player:s.owner,obj:s});else{let t=s.tile,i=s.onBridge;if(!a&&!s.isDestroyed||this.parasite.rules.organic){let e=new Us(r.map.tiles,r.map.mapBounds,t,{width:1,height:1},1,1,e=>0<r.map.terrain.getPassableSpeed(e,this.parasite.rules.speedType,i)&&!r.map.terrain.findObstacles({tile:e,onBridge:i},this.parasite).length);a=e.getNextTile();if(!a)return this.parasite.deathType=Vr.None,r.destroyObject(this.parasite,{player:s.owner,obj:s}),void this.uninfest();t=a}this.parasite.onBridge=i,this.parasite.position.subCell=this.parasite.isInfantry()?s.position.subCell:0,this.parasite.zone=r.map.getTileZone(t,!i),this.parasite.position.tileElevation=i?r.map.tileOccupation.getBridgeOnTile(t).tileElevation:0,this.parasite.resetGuardModeToIdle(),r.unlimboObject(this.parasite,t,!0)}this.uninfest()}}destroyParasite(e,t){this.parasite&&(this.parasite.deathType=Vr.None,t.destroyObject(this.parasite,e),this.uninfest())}dispose(){this.gameObject=void 0}}class nh{constructor(e){this.target=e,this.type=ss.ShipSubmergeChange}}class oh{constructor(){this.isActive=!1}isSubmerged(){return this.isActive}setCooldown(e){this.cooldownTicks=e}[Fr.onTick](e,t){this.isActive||e.parasiteableTrait?.isInfested()||(e.attackTrait&&e.attackTrait.attackState!==wn.Idle&&!e.moveTrait.isMoving()?this.cooldownTicks=Math.max(this.cooldownTicks??0,5*js.BASE_TICKS_PER_SECOND):this.cooldownTicks??(this.cooldownTicks=Math.floor(60*t.rules.general.cloakDelay*js.BASE_TICKS_PER_SECOND)),0<this.cooldownTicks&&this.cooldownTicks--,this.cooldownTicks<=0&&(this.isActive=!0,t.events.dispatch(new nh(e))))}[ua.onDamage](e,t){this.emerge(e,t)}emerge(e,t){this.isActive&&(this.isActive=!1,this.cooldownTicks=void 0,t.events.dispatch(new nh(e)))}}class hh{constructor(){this.prevHoverBobLeptons=0,this.spawnTick=0}[Yr.onSpawn](e,t){this.setBaseElevation(e,t),this.spawnTick=t.currentTick}[Gr.onTileChange](e,t,i,s){s&&(this.prevHoverBobLeptons=0,this.setBaseElevation(e,t))}setBaseElevation(e,t){e.position.tileElevation=(e.onBridge?t.map.tileOccupation.getBridgeOnTile(e.tile)?.tileElevation??0:0)+Os.worldToTileHeight(t.rules.general.hover.height)}[Fr.onTick](e,t){var i=this.computeHoverBobLeptons(t.currentTick,t.rules.general.hover),t=i-this.prevHoverBobLeptons;this.prevHoverBobLeptons=i;i=Os.tileHeightToWorld(e.position.tileElevation);e.position.tileElevation=Os.worldToTileHeight(i+t)}computeHoverBobLeptons(e,t){e=(e-this.spawnTick)/js.BASE_TICKS_PER_SECOND/(60*t.bob);return.1*t.height*Yi.sin(2*e*Math.PI)}}class lh{constructor(){this.tilt={pitch:0,yaw:0}}[Yr.onSpawn](e){this.tilt=this.computeTilt(e.tile.rampType)}[Gr.onTileChange](e){this.tilt=this.computeTilt(e.tile.rampType)}computeTilt(e){let t,i;return 0===e||17<=e?t=i=0:i=e<=4?(t=25,-90*e):(t=25,225-(e-1)%4*90),{pitch:t,yaw:i}}}const ch=34;class uh extends xa{constructor(e,t,i){super(xt.Vehicle,e,t,i),this.direction=0,this.spinVelocity=0,this.crateBonuses=new Da,this.turretNo=0,this.onBridge=!1,this.isSinker=!1,this.isFiring=!1,this.zone=t.naval?vs.Water:vs.Ground}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,s,r){let a=new this(e,t,i);return a.isSinker=!t.underwater&&(t.weight>=s.general.shipSinkingWeight||!t.naval),a.moveTrait=new Ia(a,r),a.traits.add(a.moveTrait),t.crashable&&(a.crashableTrait=new Na(a),a.traits.add(a.crashableTrait)),t.crewed&&(a.crewedTrait=new Io,a.traits.add(a.crewedTrait)),t.harvester&&(a.harvesterTrait=new th(t.storage),a.traits.add(a.harvesterTrait)),t.passengers&&(a.transportTrait=new sh(a),a.traits.add(a.transportTrait),t.gunner&&(a.gunnerTrait=new rh,a.traits.add(a.gunnerTrait))),t.turret&&(a.turretTrait=new Kn,a.traits.add(a.turretTrait)),t.consideredAircraft&&!t.landable||a.traits.add(new To),t.parasiteable&&(a.parasiteableTrait=new ah(a),a.traits.add(a.parasiteableTrait)),t.naval&&t.underwater&&(a.submergibleTrait=new oh,a.traits.add(a.submergibleTrait)),t.locomotor===si.Hover&&a.traits.add(new hh),[si.Vehicle,si.Chrono].includes(t.locomotor)&&i.isVoxel&&(a.tilterTrait=new lh,a.traits.add(a.tilterTrait)),a}isUnit(){return!0}isVehicle(){return!0}getUiName(){if(this.gunnerTrait){var e=this.armedTrait.getSpecialWeaponIndex(),t=this.gunnerTrait.getUiNameForIfvMode(e,this.transportTrait?.units[0]?.name),e=`name:${this.name}`;return t?`{${t}} {${e}}`:e}return super.getUiName()}update(e){this.rocking&&(this.rocking.ticksLeft--,this.rocking.ticksLeft||(this.rocking=void 0)),super.update(e)}applyRocking(e,t){this.rocking={ticksLeft:this.rocking?.ticksLeft??ch,facing:e,factor:t}}}class dh{constructor(e){this.airportNames=e}findAvailableAirport(e){return[...e.owner.buildings].find(e=>e.dockTrait&&this.airportNames.includes(e.name)&&0<e.dockTrait.getAvailableDockCount())}}class ph{setParent(e){this.parent=e}getParent(){return this.parent}[Fr.onTick](s,r){if(this.parent&&s.attackTrait&&s.primaryWeapon){let e=this.parent.attackTrait?.currentTarget,t=s.unitOrderTrait.getCurrentTask(),i=new As(r.map.tileOccupation);var a=this.parent.armedTrait?.getWeapons().find(e=>e.rules.spawner);s.ammo&&!(e&&s.attackTrait.currentTarget?e.equals(s.attackTrait.currentTarget):e===s.attackTrait.currentTarget||!e&&this.parent.isUnit()&&(this.parent.unitOrderTrait.getCurrentTask()instanceof ka||this.parent.unitOrderTrait.getCurrentTask()instanceof go))&&(!e||a&&i.isInWeaponRange(this.parent,e.obj??e.tile,a,r.rules))?e&&s.primaryWeapon.targeting.canTarget(e.obj,e.tile,r,!0,!1)?!t||t instanceof ka?(s.unitOrderTrait.cancelAllTasks(),s.unitOrderTrait.addTask(s.attackTrait.createAttackTask(r,e.obj,e.tile,s.primaryWeapon,{force:!0}))):s.attackTrait.attackState!==wn.Idle&&t.requestTargetUpdate(e):t?t instanceof ka||t.cancel():this.tryMoveToParent(s,this.parent,r):this.tryMoveToParent(s,this.parent,r)}}tryMoveToParent(t,i,s){if(t.tile!==i.tile){let e=t.unitOrderTrait.getCurrentTask();e?e instanceof ka&&e.updateTarget(i.tile,!!i.isUnit()&&i.onBridge):t.unitOrderTrait.addTask(new ka(s,i.tile,!!i.isUnit()&&i.onBridge,{closeEnoughTiles:0,strictCloseEnough:!0}))}}}class gh{setWarhead(e){return this.warhead=e,this}setDamage(e){return this.damage=e,this}setLauncher(e){return this.launcher=e,this}[zr.onDestroy](e,t){this.warhead&&this.damage&&this.launcher&&this.warhead.detonate(t,this.damage,e.tile,e.tileElevation,e.position.worldPosition,e.zone,aa.None,t.createTarget(void 0,e.tile),{player:e.owner,obj:this.launcher,weapon:void 0},!1,!1,void 0)}dispose(){this.launcher=void 0}}class mh extends xa{constructor(e,t,i){super(xt.Aircraft,e,t,i),this.pitch=0,this.yaw=0,this.roll=0,this.onBridge=!1,this.zone=vs.Ground,this.crateBonuses=new Da}get direction(){return this.yaw}set direction(e){this.yaw=e}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,s,r){let a=new this(e,t,i);return a.rules.airportBound&&a.rules.dock.length&&(a.airportBoundTrait=new dh(a.rules.dock),a.traits.add(a.airportBoundTrait)),a.rules.missileSpawn||(a.crashableTrait=new Na(a),a.traits.add(a.crashableTrait)),a.rules.spawned&&(a.rules.missileSpawn?(a.missileSpawnTrait=new gh,a.traits.add(a.missileSpawnTrait)):(a.spawnLinkTrait=new ph,a.traits.add(a.spawnLinkTrait))),a.moveTrait=new Ia(a,r),a.traits.add(a.moveTrait),t.dock.length&&a.traits.add(new To),t.landable&&e!==s.general.paradrop.paradropPlane||a.traits.add(new Wa),t.parasiteable&&(a.parasiteableTrait=new ah(a),a.traits.add(a.parasiteableTrait)),a}isUnit(){return!0}isAircraft(){return!0}}class fh{constructor(e){this.gameObject=e,this.orders=[],this.queuedOrders=new Set,this.tasks=[],this.taskRunner=new co}[Fr.onTick](i,e){if(i.isSpawned){var s=this.hasTasks(),t=this.tasks.find(e=>!e.isCancelling());if(s&&this.taskRunner.tick(this.tasks,i),i.isSpawned){var r,a=this.orders.length;if(a&&(!s||!t)){let e,t=!1;for(;e=this.orders[0];){if(e.isValid()&&e.isAllowed()&&((r=e.process())&&(this.queuedOrders.has(e)&&(this.tasks.push(new qs(5)),this.tasks.push(new ma(()=>{i.resetGuardModeToIdle()}))),this.tasks.push(...r),s||this.taskRunner.tick(this.tasks,i)),t=!0),this.orders.shift(),this.queuedOrders.delete(e),!i.isSpawned)return;if(this.waypointPath&&(this.currentWaypoint?(this.cleanupWaypoint(this.currentWaypoint,this.waypointPath),this.currentWaypoint=this.currentWaypoint?.next):this.currentWaypoint=this.waypointPath.waypoints[0],this.currentWaypoint||this.cleanupWaypointPath()),t)break}}!a&&!s&&this.waypointPath&&this.currentWaypoint&&(this.cleanupWaypoint(this.currentWaypoint,this.waypointPath),this.cleanupWaypointPath());let e=t;for(;e?.useChildTargetLines;){var n=e.children.find(e=>!e.isCancelling());if(!n)break;e=n}this.targetLinesTask!==e&&(this.targetLinesTask=e,this.targetLinesConfig=e?.getTargetLinesConfig(this.gameObject))}}}[Qr.onChange](){this.clearOrders(),this.cancelAllTasks()}[Wr.onBeforeTeleport](e,t,i,s){i&&!s&&(this.clearOrders(),this.tasks.length=0)}addOrder(t,e=!1){!1!==t.onAdd(this.tasks,e)?(e||(this.clearOrders(),this.tasks=this.tasks.filter(e=>e.status!==Fs.NotStarted),this.tasks.forEach(e=>e.cancel())),this.orders.push(t),e&&this.queuedOrders.add(t),this.gameObject.traits.filter(An).forEach(e=>{e[An.onPush](this.gameObject,t.orderType)})):this.targetLinesTask=void 0}clearOrders(){this.orders.length=0,this.queuedOrders.clear(),this.currentWaypoint&&this.waypointPath&&this.cleanupWaypoint(this.currentWaypoint,this.waypointPath),this.cleanupWaypointPath(),this.gameObject.resetGuardModeToIdle()}unmarkNextQueuedOrder(){this.orders.length&&this.queuedOrders.delete(this.orders[0])}hasTasks(){return!!this.tasks.length}isIdle(){return!this.orders.length&&!this.tasks.length}getCurrentTask(){return this.tasks[0]}cancelAllTasks(){this.tasks.forEach(e=>e.cancel())}addTask(e){this.tasks.push(e)}addTasks(...e){e.forEach(e=>this.addTask(e))}addTaskToFront(e){this.tasks.unshift(e)}addTaskNext(e){this.tasks.splice(1,0,e)}getTasks(){return[...this.tasks]}dispose(){this.clearOrders(),this.tasks.length=0,this.gameObject=void 0}cleanupWaypointPath(){this.waypointPath&&(this.waypointPath.units.splice(this.waypointPath.units.indexOf(this.gameObject),1),this.waypointPath.units.length||(this.waypointPath.waypoints.forEach(e=>e.next=void 0),this.waypointPath.waypoints.length=0),this.waypointPath=void 0),this.currentWaypoint=void 0}cleanupWaypoint(t,e){if(!e.units.find(e=>e!==this.gameObject&&(e.unitOrderTrait.currentWaypoint??e.unitOrderTrait.waypointPath?.waypoints[0])===t)&&!e.waypoints.find(e=>e.next===t)){var i=e.waypoints.indexOf(t);if(-1===i)throw new Error("Given waypoint not found in waypoint path");e.waypoints.splice(i,1)}}}const yh=[[0,0,0,0],[0,0,1,1],[1,0,0,1],[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,0,0],[0,1,0,0],[0,0,1,0],[1,0,1,1],[1,1,0,1],[1,1,1,0],[0,1,1,1],[1,0,1,2],[2,1,0,1],[1,2,1,0],[0,1,2,1],[1,0,1,0],[0,1,0,1],[1,0,1,0],[0,1,0,1]];class wh{constructor(e,t){this.tiles=e,this.tileOccupation=t,this._worldPosition=new rs,this._tileOffset=new ks,this._centerOffset=new ks,this.desiredSubCell=0,this._tileElevation=0,this._onPositionChange=new ao}get onPositionChange(){return this._onPositionChange.asEvent()}get worldPosition(){return this._worldPosition}get tile(){return this._tile}set tile(e){var t=!!this._tile&&e!==this._tile;(this._tile=e)&&(this.updateWorldPosition(e,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:t}))}get tileElevation(){return void 0===this._tileElevation?(void 0===this._computedTileElevation&&(this._computedTileElevation=this.computeTileElevationFromWorldPos()),this._computedTileElevation):this._tileElevation}set tileElevation(e){this._absoluteElevation=void 0,this._tileElevation=e,this._tile&&(this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:!1}))}get subCell(){if(!this._tileOffset.x&&!this._tileOffset.y)return 0;var e=Math.sign(this._tileOffset.x/Os.LEPTONS_PER_TILE-.5),t=Math.sign(this._tileOffset.y/Os.LEPTONS_PER_TILE-.5);return e&&t?t+1+(e+1)/2+1:0}set subCell(e){this._tileOffset=this.computeSubCellOffset(e),this.desiredSubCell=e,this._tile&&(this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:!1}))}getTileOffset(){return this._tileOffset.clone()}setTileOffset(e){this._tileOffset.copy(e),this._tile&&(this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:!1}))}setCenterOffset(e){this._centerOffset.copy(e),this._tile&&(this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:!1}))}getMapPosition(){if(this._tile)return new ks(this._tile.rx*Os.LEPTONS_PER_TILE+this._tileOffset.x+this._centerOffset.x,this._tile.ry*Os.LEPTONS_PER_TILE+this._tileOffset.y+this._centerOffset.y)}getBridgeBelow(){return this._tile?.onBridgeLandType?this.tileOccupation.getBridgeOnTile(this._tile):void 0}moveToTileCell(e,t=0){if(!this._tile)throw new Error("Tile is not set");var i=e!==this._tile;this._tile=e,this._tileOffset=this.computeSubCellOffset(t),this.desiredSubCell=t,this.updateWorldPosition(e,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:i})}moveToTileCoords(e,t,i=!1){var s=Math.floor(e),r=Math.floor(t),a=!this._tile||this._tile.rx!==s||this._tile.ry!==r;if(a){let e=this.tiles.getByMapCoords(s,r);if(!e){if(!i)throw new RangeError(`Attempted move to a non-existent tile: [${s},${r}]`);e=this.tiles.getPlaceholderTile(s,r)}this._tile=e}this._tileOffset.set((e-s)*Os.LEPTONS_PER_TILE,(t-r)*Os.LEPTONS_PER_TILE),this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:a})}moveToLeptons(e,t=!1){this.moveToTileCoords(e.x/Os.LEPTONS_PER_TILE,e.y/Os.LEPTONS_PER_TILE,t)}moveByLeptons(e,t,i=!1){if(!this._tile)throw new Error("Tile is not set");this.moveToTileCoords(this._tile.rx+(this._tileOffset.x+e)/Os.LEPTONS_PER_TILE,this._tile.ry+(this._tileOffset.y+t)/Os.LEPTONS_PER_TILE,i)}moveByLeptons3(e,t=!1){var i=this._worldPosition.y;this.moveByLeptons(e.x,e.z,t),this.setAbsoluteElevationWorld(i+e.y)}setAbsoluteElevationWorld(e){this._absoluteElevation=e,this._tileElevation=void 0,this._tile&&(this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:!1}))}computeSubCellOffset(e){let t={width:0,height:0};var i;e&&(i=(e-1)%2*2-1,s=2*Math.floor((e-1)/2)-1,t={width:i*Os.LEPTONS_PER_TILE/4,height:s*Os.LEPTONS_PER_TILE/4});var s=Os.LEPTONS_PER_TILE/2;return new ks(s+t.width,s+t.height)}interpolateRampHeight(e,t,i){var s=yh[i],r=s[1],i=s[0];return r*(1-e)*(1-t)+s[2]*e*(1-t)+i*(1-e)*t+s[3]*e*t}updateWorldPosition(t,i){var e=i.x+this._centerOffset.x,s=i.y+this._centerOffset.y,r=e/Os.LEPTONS_PER_TILE,i=s/Os.LEPTONS_PER_TILE;let a;if(void 0!==this._tileElevation){let e=0;0!==t.rampType&&(e=this.interpolateRampHeight(r,i,t.rampType)),a=Os.tileHeightToWorld(t.z+e+this._tileElevation)}else a=this._absoluteElevation;this._worldPosition.set(t.rx*Os.LEPTONS_PER_TILE+e,a,t.ry*Os.LEPTONS_PER_TILE+s),void 0===this._tileElevation&&(this._computedTileElevation=this.computeTileElevationFromWorldPos())}computeTileElevationFromWorldPos(){if(!this._tile)return 0;var e=(t=Os.worldToTileHeight(this._worldPosition.y),i=14,t&&(i=10**i,Math.round(t*i)/i)),t=(this._tileOffset.x+this._centerOffset.x)/Os.LEPTONS_PER_TILE,i=(this._tileOffset.y+this._centerOffset.y)/Os.LEPTONS_PER_TILE;let s=0;return 0!==this._tile.rampType&&(s=this.interpolateRampHeight(t,i,this._tile.rampType)),e-this._tile.z-s}clone(){let e=new wh(this.tiles,this.tileOccupation);return e._worldPosition=this._worldPosition.clone(),e._tile=this._tile,e._tileOffset=this._tileOffset.clone(),e._centerOffset=this._centerOffset.clone(),e._tileElevation=this._tileElevation,e._absoluteElevation=this._absoluteElevation,e._computedTileElevation=this._computedTileElevation,e}}class Th{constructor(e){this.tileOccupation=e}checkCollisions(e,t,i){var s,r=e.tile;let a,n,o;for(s of this.tileOccupation.getObjectsOnTile(r))s.isOverlay()&&s.isBridge()&&(a=s),s.isOverlay()&&s.wallTrait&&(o=s),s.isTechno()&&!s.isDestroyed&&(n=s);if(i.walls){if(e.tileElevation<=2&&r.landType===Jt.Wall)return{type:aa.Wall,target:o};if(i.units&&n?.tile===r&&(!n.isUnit()||n.zone===vs.Ground)&&e.tileElevation<=1.1&&i.units(n.owner))return{type:aa.Wall,target:n}}if(i.shore&&r.landType!==Jt.Water)return{type:aa.Shore};if(i.ground&&e.tileElevation<0)return{type:aa.Ground};var h=e.tileElevation+r.z,l=t.tileElevation+t.tile.z;if(a?.isHighBridge()){var c=a.tile.z+a.tileElevation;if(c<l&&h<=c||l<c&&c-1<=h)return l<c?{type:aa.UnderBridge,target:a}:{type:aa.OnBridge,target:a}}else if(a?.isLowBridge()&&i.shore)return{type:aa.UnderBridge,target:a};if(i.cliffs){t=r.z-t.tile.z;if(e.tileElevation<0&&4<=t)return{type:aa.Cliff}}return{type:aa.None}}computeDetonationZone(e,t,i){let s=this.tileOccupation.getBridgeOnTile(e);return i===aa.None&&t>1.5+(s?.tileElevation??0)?vs.Air:s&&1.5<t||e.terrainType!==Kt.Water||s?.isLowBridge()?vs.Ground:vs.Water}}(r=Pn=Pn||{})[r.Travel=0]="Travel",r[r.Impact=1]="Impact",r[r.Detonation=2]="Detonation";class bh extends Ba{constructor(e,t,i,s){super(xt.Projectile,e,t,i),this.tileOccupation=s,this.state=Pn.Travel,this.detonationTimer=0,this.collisionType=aa.None,this.direction=0,this.zone=vs.Air,this.isShrapnel=!1,this.isNuke=!1,this.baseDamageMultiplier=1,this.veteranDamageMult=1,this.snapToTarget=!1,this.targetLockLost=!1,this.limboTravelTicks=0,this.homingTravelDistance=0,this.homingTravelTicks=0,this.velocity=new rs,this.sonicVisitedObjects=new Map,this.collisionHelper=new Th(s)}get fromObject(){return this._fromObject}set fromObject(e){(this._fromObject=e)&&e.veteranTrait&&!e.isDestroyed&&(this.veteranDamageMult=e.veteranTrait.getVeteranDamageMultiplier())}get rot(){return this.fromWeapon.rules.isSonic?Ci.iniRotToDegsPerTick(this.iniRot):this.rules.rot}get iniRot(){return this.fromWeapon.rules.isSonic?10:this.rules.iniRot}static factory(e,t,i,s){return new this(e,t,i,s)}onSpawn(a){var e;if(super.onSpawn(a),this.initialSelfPosition=this.position.worldPosition.clone(),!this.target.obj||this.fromWeapon.type===hi.DeathWeapon||this.fromWeapon.rules.limboLaunch||!this.isHoming()&&this.fromWeapon.speed===Number.POSITIVE_INFINITY||this.rules.inaccurate||this.rules.arcing||this.rules.flakScatter||0<(e=this.computeBaseDamage(a))&&(e=this.fromWeapon.warhead.computeDamage(e,this.target.obj),this.target.obj.healthTrait?.projectDamage(e)),a.afterTick(()=>{let e=new As(this.tileOccupation);var t=e.distance2(this.target.getWorldCoords(),this)/Os.LEPTONS_PER_TILE;this.initialTileDistToTarget=t,this.maxSpeed=this.computeMaxSpeed(this.fromWeapon.speed,t,a.rules.audioVisual.gravity)}),this.isHoming()){if(1===this.iniRot&&(this.homingMoveDir=this.target.getWorldCoords().clone().sub(this.position.worldPosition)),this.fromObject?.isAircraft()&&this.rules.isAntiGround&&!this.rules.isAntiAir){let e=this.target.obj;!e?.isVehicle()||e.isDestroyed||e.veteranLevel!==ea.Elite||e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new Sa(a))}}else if(this.rules.vertical){let e=this.position.clone();e.tileElevation=this.fromWeapon.warhead.rules.nukeMaker?Os.worldToTileHeight(this.fromWeapon.projectileRules.detonationAltitude):0,this.aimPoint=e.worldPosition.clone()}else{let r=this.target.getWorldCoords().clone();a.afterTick(()=>{let e=this.target.getWorldCoords().clone().sub(r);var t=e.length()>Os.LEPTONS_PER_TILE;let i=t?r:this.target.obj?.isUnit()&&this.target.obj.moveTrait.velocity.length()&&isFinite(this.maxSpeed)?this.computeAimPointVersusMovingTarget(this.target.obj,this.maxSpeed,this.position.worldPosition,a.map):this.target.getWorldCoords().clone();this.aimPoint=i,this.snapToTarget=!t&&isFinite(this.maxSpeed)&&!this.fromWeapon.warhead.rules.sonic,(this.rules.inaccurate||this.rules.flakScatter)&&(this.adjustAimForBallisticScatter(a,i),this.snapToTarget=!1),!t&&this.rules.arcing&&(this.rules.inaccurate?(this.overshootTiles=this.calculateInaccurateBallisticOvershoot(a),this.snapToTarget=!1):this.target.obj?.isVehicle()&&this.target.obj.moveTrait.isMoving()&&(this.overshootTiles=this.calculateBallisticOvershootVsMoving(a,this.target.obj),this.overshootTiles&&(this.snapToTarget=!1)));let s=i.clone().sub(this.position.worldPosition);s.length()<this.fromWeapon.speed&&this.update(a)})}}adjustAimForBallisticScatter(e,t){let i=e.rules.combatDamage.ballisticScatter,s;s=this.rules.flakScatter?(this.rules.inviso&&(i*=2),e.generateRandom()*i):i/2+e.generateRandom()*(i/2);let r=s*Os.LEPTONS_PER_TILE;this.rules.flakScatter&&(n=t.clone().sub(this.initialSelfPosition).length(),r*=n/(this.fromWeapon.range*Os.LEPTONS_PER_TILE));var a=ar(new ks(r,0),e.generateRandomInt(0,360)),n=Os.vecWorldToGround(t).add(a).multiplyScalar(1/Os.LEPTONS_PER_TILE).floor();e.map.tiles.getByMapCoords(n.x,n.y)&&t.add(new rs(a.x,0,a.y))}calculateBallisticOvershootVsMoving(e,t){let i=this.target.getWorldCoords().clone().sub(this.initialSelfPosition);var s=hr(Os.vecWorldToGround(i),Os.vecWorldToGround(t.moveTrait.velocity)),t=(90<s?180-s:s)/90,s=i.length()/Os.LEPTONS_PER_TILE,t=t*s/5;return e.generateRandom()<=t?2*Math.min(1,s/5):0}calculateInaccurateBallisticOvershoot(e){return e.generateRandom()<=.5?2:0}update(o){if(void 0!==this.maxSpeed)if(super.update(o),this.state!==Pn.Impact){var r=this.velocity.clone(),h=this.position.clone();if(this.velocity.set(0,0,0),this.fromWeapon.rules.limboLaunch){if(!this.fromObject)throw new Error("Limbo launch projectile must be fired from a unit");if(this.fromObject.isDestroyed)return void o.destroyObject(this)}var l=this.updateSpeed(this.maxSpeed);this.speed=l;let n=this.target.getWorldCoords();if(this.lastTargetLockPosition&&(this.targetLockLost||n.clone().sub(this.lastTargetLockPosition).length()>=Os.LEPTONS_PER_TILE)?(n=this.lastTargetLockPosition,this.targetLockLost=!0):this.lastTargetLockPosition=n.clone(),this.isHoming()){if(this.target.obj?.isUnit()&&(this.target.obj.isDestroyed||this.target.obj.isCrashing||!this.target.obj.isSpawned)&&(this.fromWeapon.rules.limboLaunch||this.homingTravelDistance>=2*Os.LEPTONS_PER_TILE))return void this.detonate(o);if(this.homingMoveDir||(u=br.toMapCoords(this.direction),this.homingMoveDir=new rs(u.x,0,u.y),this.fromObject?.isAircraft()&&(this.homingMoveDir.y=-9999999,this.homingMoveDir.normalize())),this.fromWeapon.rules.limboLaunch){if(!this.targetLockLost){if(10<this.limboTravelTicks)return this.position.moveToLeptons(this.target.obj.position.getMapPosition()),this.position.tileElevation=this.target.obj.position.tileElevation,void this.detonate(o);this.limboTravelTicks++}}else if(!this.isInHomingRange(n,o))return void this.detonate(o);let e=new As(this.tileOccupation);var c=Math.floor(e.distance2(n,this)/Os.LEPTONS_PER_TILE),u=2<c&&1<this.iniRot;let t=n.clone().sub(this.position.worldPosition),i=0;this.homingTravelTicks<this.rules.courseLockDuration||(u?(gr(this.homingMoveDir,new rs(t.x,this.homingMoveDir.y,t.z),this.rot),this.rules.level||(c=z(Math.floor(this.initialTileDistToTarget)-1,0,2)+z(c-2,0,3),d=this.tileOccupation.getBridgeOnTile(this.tile)?.tileElevation??0,(d=c-(this.position.tileElevation-d))&&(p=.25+6/this.iniRot*.1,i=Os.tileHeightToWorld(Math.sign(d)*Math.min(Math.abs(d),p))))):gr(this.homingMoveDir,t,this.rot)),this.direction=br.fromMapCoords(new ks(this.homingMoveDir.x,this.homingMoveDir.z));var d=t.length(),p=Math.min(d,l);this.homingTravelDistance+=p,this.homingTravelTicks++;let s=!1,r=aa.None,a;if(1<=p){let e=this.homingMoveDir.clone().setLength(p);i&&(e.y+=i),p===l&&this.velocity.copy(e);var g=e.clone().add(this.position.worldPosition);o.map.mapBounds.isWithinHardBounds(g)?this.position.moveByLeptons3(e):s=!0;var m=this.checkObstacles(h,o);r=m.type,a=m.target,(r||p<l)&&(s=!0)}else this.position.moveByLeptons3(t),s=!0;if(s){if(a&&r===aa.Wall){let e=a.position.worldPosition;this.position.moveByLeptons3(e.clone().sub(this.position.worldPosition))}this.collisionType=r,this.detonate(o,r)}}else{let t=this.aimPoint.clone().sub(this.position.worldPosition);this.rules.vertical||(this.direction=br.fromMapCoords(new ks(t.x,t.z))),this.rules.arcing&&(t.y=0);d=Math.min(t.length(),l);if(t.setLength(d),this.rules.arcing){let e=Os.vecWorldToGround(this.position.worldPosition.clone().sub(this.initialSelfPosition).add(t));var g=this.aimPoint.clone().sub(this.initialSelfPosition),a=e.length(),m=Os.vecWorldToGround(g).length(),p=g.y,g=o.rules.audioVisual.gravity;t.y=(p/m*l+g/2*m/l)*a/l-g*(a/l)*(a/l)/2+this.initialSelfPosition.y-this.position.worldPosition.y}let e=!1;a=t.clone().add(this.position.worldPosition);o.map.isWithinHardBounds(a)?this.position.moveByLeptons3(t):e=!0;let i=aa.None,s;if(1<=d?(d!==l&&!this.overshootTiles||this.velocity.copy(t),h=this.checkObstacles(h,o),i=h.type,s=h.target,(i||d<l)&&(e=!0)):e=!0,e){if(i){if(s&&i===aa.Wall){let e=s.isBuilding()?Os.tile3dToWorld(s.tile.rx+.5,s.tile.ry+.5,s.tile.z):s.position.worldPosition;this.position.moveByLeptons3(e.clone().sub(this.position.worldPosition))}}else if(this.overshootTiles){var f=Os.vecWorldToGround(r).setLength(this.overshootTiles*Os.LEPTONS_PER_TILE);if(ar(f,o.generateRandomInt(-45,45)),a=Os.vecGroundToWorld(f).add(this.position.worldPosition),!o.map.isWithinHardBounds(a))return void o.unspawnObject(this);this.position.moveByLeptons(f.x,f.y)}else if(this.snapToTarget&&!this.targetLockLost){if(!o.map.isWithinHardBounds(n))return void o.unspawnObject(this);this.position.moveByLeptons3(n.clone().sub(this.position.worldPosition))}this.collisionType=i,this.isNuke?(this.state=Pn.Impact,this.detonationTimer=2.5*js.BASE_TICKS_PER_SECOND):this.detonate(o,i)}}let e=this.fromWeapon.warhead;if(e.rules.sonic){var t,i,f=11/30*Os.LEPTONS_PER_TILE,f=this.position.worldPosition.clone().add(this.velocity.clone().setLength(f)),f=Os.vecWorldToGround(f).multiplyScalar(1/Os.LEPTONS_PER_TILE).floor(),s=o.map.tiles.getByMapCoords(f.x,f.y);if(s&&s!==this.fromObject?.tile){var y,w=o.map.getTileZone(s);for(y of o.map.getGroundObjectsOnTile(s))if((!y.isUnit()||!y.onBridge)&&(!y.isTechno()||!y.rules.typeImmune||y.owner!==this.fromPlayer||y.name!==this.fromObject?.name)&&(!y.isAircraft()||!y.rules.spawned)&&e.canDamage(y,s,w)){let e=this.sonicVisitedObjects.get(y)??new Set;e.add(s),this.sonicVisitedObjects.set(y,e)}}for([t,i]of this.sonicVisitedObjects)for(var T of i)o.map.tileOccupation.isTileOccupiedBy(T,t)&&t.isSpawned&&(T=this.fromWeapon.rules.ambientDamage*this.veteranDamageMult*this.baseDamageMultiplier,T=e.computeDamage(T,t),e.inflictDamage(T,t,{player:this.fromPlayer,weapon:this.fromWeapon,obj:this.fromObject},o,t!==this.target.obj))}}else 0<this.detonationTimer?this.detonationTimer--:this.detonate(o,this.collisionType)}isHoming(){return!!this.rot&&!this.rules.arcing}isInHomingRange(t,i){let s=!0,r=this.target.obj;if(r?.isUnit()&&this.fromObject){let e=new As(this.tileOccupation);i=e.computeWeaponRangeVsTarget(this.fromObject,r,this.fromWeapon,i.rules).range;this.fromWeapon.rules.limboLaunch?s=e.isInRange3(this.initialSelfPosition,t,0,i+.5):(t=r.moveTrait.velocity.length())&&(this.fromObject.rules.movementZone===ri.Fly?5<this.speed/t&&(s=e.isInRange2(this.initialSelfPosition,this.position.worldPosition,0,i)):isFinite(this.fromWeapon.speed)&&3.5<this.fromWeapon.speed/r.rules.speed&&(s=e.isInRange3(this.initialSelfPosition,this.position.worldPosition,0,i)))}return s}updateSpeed(e){let t;return t=this.isHoming()||this.rules.vertical?void 0===this.speed?Math.min(e,this.rules.acceleration):Math.min(e,this.speed+this.rules.acceleration):e,t}computeMaxSpeed(e,t,i){let s=e;return this.rules.arcing&&(s*=(1+i/6)/2,t=Math.floor(t),s*=t<=8?1:1+t/8*.5),this.fromWeapon.warhead.rules.sonic&&(s=Math.ceil(t*Os.LEPTONS_PER_TILE/21)),s}checkObstacles(e,t){return this.fromWeapon.rules.limboLaunch?{type:aa.None}:this.collisionHelper.checkCollisions(this.position,e,{cliffs:this.rules.subjectToCliffs,ground:this.isHoming(),shore:this.rules.level,walls:this.rules.subjectToWalls,units:!this.rules.inaccurate&&(e=>this.fromPlayer!==e&&!t.alliances.areAllied(this.fromPlayer,e))})}computeBaseDamage(e){var t=this.fromWeapon,i=t.warhead;let s=t.rules.damage;t.type===hi.DeathWeapon&&i.rules.ivanBomb&&(s=e.rules.combatDamage.ivanDamage);let r=s*this.baseDamageMultiplier;return t.type===hi.DeathWeapon&&this.fromObject&&(r*=this.fromObject.rules.deathWeaponDamageModifier),r*=this.veteranDamageMult,r}detonate(n,e=aa.None){var i=this.fromWeapon;let s=i.warhead;var t,r=this.zone=this.collisionHelper.computeDetonationZone(this.tile,this.tileElevation,e);let o=this.tile;i.type===hi.DeathWeapon&&s.rules.ivanBomb&&(s=new Ya(n.rules.getWarhead(n.rules.combatDamage.ivanWarhead)));let a=this.computeBaseDamage(n);n.destroyObject(this),this.state=Pn.Detonation;let h=this.target.obj,l=!1;if(s.rules.parasite&&h?.isUnit()&&o===h.tile&&s.canDamage(h,o,r))if(h.isInfantry())a=Number.POSITIVE_INFINITY;else if(h.parasiteableTrait&&this.fromObject?.isUnit()){if(!(this.fromWeapon instanceof tn))throw new Error("Projectile with parasite warhead must have a weapon reference");h.parasiteableTrait.infest(this.fromObject,this.fromWeapon),l=!0}let c=!0;if(l&&(c=!1),s.rules.sonic&&(c=!1),s.rules.ivanBomb&&(c=!1,!h?.isTechno()||!h.tntChargeTrait||h.tntChargeTrait.hasCharge()||h.isDestroyed||h.warpedOutTrait.isInvulnerable()||(t=n.rules.combatDamage.ivanTimedDelay,h.tntChargeTrait.setCharge(t,n.currentTick,{player:this.fromPlayer}))),s.rules.bombDisarm&&(c=!1,h?.isTechno()&&h.tntChargeTrait?.hasCharge()&&!h.isDestroyed&&h.tntChargeTrait.removeCharge()),s.rules.mindControl&&(c=!1,this.fromObject&&!this.fromObject.isDestroyed&&h?.isTechno()&&h.mindControllableTrait&&!h.mindControllableTrait?.isActive()&&!n.areFriendly(h,this.fromObject)&&s.canDamage(h,o,r)&&!h.invulnerableTrait.isActive()&&this.fromObject.mindControllerTrait.control(h,n)),s.rules.temporal&&(c=!1,this.fromObject&&!this.fromObject.isDestroyed&&h?.isTechno()&&s.canDamage(h,o,r)&&!h.invulnerableTrait.isActive()&&(s.inflictDamage(0,h,{player:this.fromPlayer,weapon:i,obj:this.fromObject},n),this.fromObject.temporalTrait.updateTarget(h,i,n))),s.rules.makesDisguise&&(c=!1,this.fromObject&&!this.fromObject.isDestroyed&&(this.fromObject.isInfantry()||this.fromObject.isVehicle())&&h?.isUnit()&&h.type===this.fromObject.type&&this.fromObject.disguiseTrait?.disguiseAs(h,this.fromObject,n)),s.rules.electricAssault&&(this.fromObject?.isUnit()&&!this.fromObject.isDestroyed&&h?.isBuilding()&&!h.isDestroyed&&h.overpoweredTrait&&h.owner===this.fromPlayer&&h.overpoweredTrait.chargeFrom(this.fromObject),c=!1),c&&s.detonate(n,a,o,this.tileElevation,this.position.worldPosition,r,e,this.target,{player:this.fromPlayer,weapon:i,obj:this.fromObject},this.isShrapnel,!1,this.impactAnim),s.rules.nukeMaker){let e;e=this.fromObject?(u=tn.factory(tn.NUKE_PAYLOAD_NAME,hi.Primary,this.fromObject,n.rules),n.createProjectile(u.projectileRules.name,this.fromObject,u,this.target,!1)):n.createLooseProjectile(tn.NUKE_PAYLOAD_NAME,this.fromPlayer,this.target),e.isNuke=!0,e.impactAnim="NUKEBALL";var u=this.target.tile;e.position.moveToTileCoords(u.rx+.5,u.ry+.5),e.position.tileElevation=this.position.tileElevation,n.spawnObject(e,u)}if(this.rules.shrapnelCount&&this.rules.shrapnelWeapon&&((this.target.obj?!this.target.obj.isBuilding():n.map.getGroundObjectsOnTile(this.target.tile).some(e=>e.isTerrain())&&!i.projectileRules.isAntiAir)||this.isShrapnel)){let t=n.rules.getWeapon(this.rules.shrapnelWeapon);var d,p=n.rules.getProjectile(t.projectile);let i=this.rules.shrapnelCount,s=new As(n.map.tileOccupation),e=new Us(n.map.tiles,n.map.mapBounds,o,{width:1,height:1},1,t.range,e=>s.isInTileRange(o,e,t.minimumRange,t.range)),r=new Set;for(;0<Math.floor(i);){var g,m=e.getNextTile();if(!m)break;for(g of n.map.tileOccupation.getObjectsOnTileByLayer(m,p.isAntiAir?bn.Air:bn.Ground).filter(e=>n.isValidTarget(e)&&(e.isTerrain()||e.isTechno()&&e.owner!==this.fromPlayer&&!n.alliances.areAllied(e.owner,this.fromPlayer)&&!(e.isInfantry()&&e.stance===Ls.Paradrop))))if(!r.has(g)&&(r.add(g),i=Math.max(0,i-1-(g.isTechno()?.5:0)),Math.floor(i)<=0))break}for(d of r){var f=n.createTarget(d.isTerrain()?void 0:d,d.tile);this.createShrapnel(n,f,t.name)}i=Math.floor(i);let a=new Ta(n.map.tiles,n.map.mapBounds,o,t.range,n,e=>s.isInTileRange(o,e,t.minimumRange,t.range));for(let e=0;e<i;e++){var y=a.getNextTile();if(!y)break;y=n.createTarget(void 0,y);this.createShrapnel(n,y,t.name)}}if(i.rules.limboLaunch&&!l&&this.fromObject?.isUnit()){let r=this.fromObject;s.rules.parasite&&(this.target.obj.isVehicle()||this.target.obj?.isAircraft())&&this.target.obj.parasiteableTrait&&(this.target.obj.parasiteableTrait.beingBoarded=!1);let t,a;i=r.rules.movementZone===ri.Fly;if(i)t=o,a=!1;else{let i=this.target.obj.isUnit()&&this.target.obj.tile.onBridgeLandType&&!this.target.obj.onBridge?void 0:n.map.tileOccupation.getBridgeOnTile(o),s=new Xs(n.map),e=new Us(n.map.tiles,n.map.mapBounds,o,{width:1,height:1},0,1,e=>{var t=n.map.tileOccupation.getBridgeOnTile(e);return 0<n.map.terrain.getPassableSpeed(e,r.rules.speedType,!!t)&&s.isEligibleTile(e,t,i,o)&&(e===o||!n.map.terrain.findObstacles({tile:e,onBridge:i},r).length)});t=e.getNextTile(),a=!!t?.onBridgeLandType}t?(!i&&this.target.obj.isUnit()&&(r.onBridge=a,r.position.tileElevation=a?n.map.tileOccupation.getBridgeOnTile(t)?.tileElevation??0:0),n.unlimboObject(r,t),r.isInfantry()&&(r.position.subCell=this.target.obj.position.subCell),r.direction=this.direction):r.owner.removeOwnedObject(r)}}createShrapnel(e,t,i){let s=e.createLooseProjectile(i,this.fromPlayer,t);s.isShrapnel=!0,s.veteranDamageMult=this.veteranDamageMult,s.position.moveToLeptons(this.position.getMapPosition()),s.position.tileElevation=this.position.tileElevation,e.spawnObject(s,s.position.tile)}computeAimPointVersusMovingTarget(t,i,e,s){let r=t.position.worldPosition,a=r.clone();var n=i,i=t.moveTrait.velocity.length();if(n<3*i)return r.clone();let o=xr.computeInterceptPoint(e,n,r,t.moveTrait.velocity);if(o.length()){let e=o.clone().sub(r);n=e.length(),i=i,n=i?Math.ceil(n/i):0;if(o=r.clone().add(e.setLength(n*i)),s.isWithinHardBounds(o))if(t.zone!==vs.Air){o.multiplyScalar(1/Os.LEPTONS_PER_TILE);let e=t.position.clone();e.moveToTileCoords(o.x,o.z),a=e.worldPosition}else a=o;else a=r}return a.clone()}}(r=Nn=Nn||{})[r.None=0]="None",r[r.PreparingToFire=1]="PreparingToFire",r[r.FiringUp=2]="FiringUp",r[r.Firing=3]="Firing";class vh{constructor(e){this.gameObject=e,this.deployed=!1,this.deployFireDelay=0,this.deployFireState=Nn.None,this.fireUpDelay=0,this.deployFireCount=0}isDeployed(){return this.deployed}setDeployed(t){var e=this.deployed;if((this.deployed=t)!==e){let e=this.gameObject;e.isInfantry()&&(e.stance=t?Ls.Deployed:Ls.None),t?(this.deployFireState=Nn.PreparingToFire,t=this.gameObject.armedTrait?.getDeployFireWeapon(),this.deployWeapon=t?.rules.areaFire?t:void 0,this.deployFireDelay=15+((t===e.primaryWeapon?e.secondaryWeapon:e.primaryWeapon)?.getCooldownTicks()??0),this.deployFireCount=0,this.undeployDelay=this.gameObject.rules.undeployDelay||void 0):(this.deployFireState===Nn.FiringUp&&(e.isFiring=!1),this.deployFireState=Nn.None,this.deployWeapon=void 0)}}toggleDeployed(){this.setDeployed(!this.isDeployed())}[Fr.onTick](e,t){if(void 0!==this.undeployDelay&&(0<this.undeployDelay&&this.undeployDelay--,this.undeployDelay<=0&&[Nn.None,Nn.PreparingToFire].includes(this.deployFireState)))return this.undeployDelay=void 0,void this.setDeployed(!1);if(this.deployWeapon&&this.deployFireState!==Nn.None){if(this.deployFireState===Nn.PreparingToFire){if(0<this.deployFireDelay--||0===e.ammo)return;if(0<this.computeDeployFireCooldown(this.deployWeapon,t))return;this.fireUpDelay=Math.max(1,e.art.fireUp),this.deployFireState=Nn.FiringUp}if(this.deployFireState===Nn.FiringUp){if(e.isFiring=!0,0<this.fireUpDelay--)return;this.deployFireState=Nn.Firing}var i;this.deployFireState===Nn.Firing&&(e.isFiring=!1,i=e.onBridge?t.map.tileOccupation.getBridgeOnTile(e.tile):void 0,this.deployWeapon.fire(t.createTarget(i,e.tile),t),this.deployFireCount++,(this.deployWeapon===e.primaryWeapon?e.secondaryWeapon:e.primaryWeapon)?.resetCooldown(),this.deployWeapon.rules.fireOnce?(this.deployFireState=Nn.None,this.deployWeapon=void 0):this.deployFireState=Nn.PreparingToFire)}}computeDeployFireCooldown(t,i){if(t.rules.radLevel&&t.rules.areaFire){var s=this.gameObject.tile,s=i.mapRadiationTrait.getRadSiteLevel(s);if(!s)return 0;i=i.rules.radiation;let e=Math.max(0,s*i.radDurationMultiple-i.radLevelDelay);return 1===this.deployFireCount&&(i=i.radDurationMultiple*t.rules.radLevel,e=Math.max(0,e-Math.floor(.25*i))),e}return t.getCooldownTicks()}getHash(){return this.deployed?1:0}debugGetState(){return{deployed:this.deployed}}dispose(){this.gameObject=void 0}}(Mn=Mn||{}).onChange=Symbol();class Sh{constructor(e,t,i,s,r){this.target=e,this.attacker=t,this.damageHitPoints=i,this.currentHealth=s,this.prevHealth=r,this.type=ss.InflictDamage}}(Dn=Dn||{}).onChange=Symbol(),(r=Rn=Rn||{})[r.Green=0]="Green",r[r.Yellow=1]="Yellow",r[r.Red=2]="Red";class kh{constructor(e,t,i){this.target=e,this.currentHealth=t,this.prevHealth=i,this.type=ss.HealthChange}}class Oh{constructor(e,t,i,s){this.maxHitPoints=e,this.gameObject=t,this.conditionYellow=i,this.conditionRed=s,this.setHitPoints(e),this.projectedHitPoints=this.hitPoints}get health(){return this._computedHealth}set health(e){this.setHitPoints(0<e?Math.max(1,Math.floor(e*this.maxHitPoints/100)):0),this.projectedHitPoints=this.hitPoints}get level(){return this.health>100*this.conditionYellow?Rn.Green:this.health>100*this.conditionRed?Rn.Yellow:Rn.Red}setHitPoints(e){if(e!==Math.floor(e))throw new Error(`Value ${e} is not an integer`);this.hitPoints=z(e,0,this.maxHitPoints),this._computedHealth=this.hitPoints/this.maxHitPoints*100}getHitPoints(){return this.hitPoints}getProjectedHitPoints(){return this.projectedHitPoints}inflictDamage(t,i,s){var e=this.hitPoints,r=this.health;this.applyHitPoints(e-t,s),e!==this.hitPoints&&0<t&&(this.gameObject.traits.filter(ua).forEach(e=>{e[ua.onDamage](this.gameObject,s,t,i)}),s.events.dispatch(new Sh(this.gameObject,i,t,this.health,r)))}healBy(e,i,s){if(e<0)throw new Error(`Can't heal by negative value ${e}`);if(this.hitPoints<this.maxHitPoints){var r=this.hitPoints;this.applyHitPoints(this.hitPoints+e,s),this.projectedHitPoints=this.hitPoints;let t=this.hitPoints-r;this.gameObject.traits.filter(En).forEach(e=>{e[En.onHeal]?.(this.gameObject,s,t,i)})}}healToFull(i,s){if(this.hitPoints<this.maxHitPoints){var e=this.hitPoints;this.applyHitPoints(this.maxHitPoints,s),this.projectedHitPoints=this.hitPoints;let t=this.hitPoints-e;this.gameObject.traits.filter(En).forEach(e=>{e[En.onHeal]?.(this.gameObject,s,t,i)})}}applyHitPoints(e,t){let i=this.health;this.setHitPoints(e),i!==this.health&&(t.traits.filter(Mn).forEach(e=>{e[Mn.onChange](this.gameObject,t,i)}),this.gameObject.traits.filter(Dn).forEach(e=>{e[Dn.onChange](this.gameObject,t,i)}),t.events.dispatch(new kh(this.gameObject,this.health,i)))}projectDamage(e){if(e<0)throw new Error("Projected damage must be positive");this.projectedHitPoints=Math.max(-30,this.projectedHitPoints-e)}[Fr.onTick](e,t){t.currentTick%4==0&&(this.projectedHitPoints=Math.min(this.projectedHitPoints+1,this.hitPoints))}getHash(){return this.hitPoints}debugGetState(){return{hitPoints:this.hitPoints}}dispose(){this.gameObject=void 0}}class _h{constructor(e){this.bridges=e,this.needsImageUpdate=!1,this.dominoHandled=!1}[ua.onDamage](){this.needsImageUpdate=!0}[Fr.onTick](e){this.needsImageUpdate&&(this.needsImageUpdate=!1,this.bridges.handlePieceHealthChange(this.bridges.getPieceAtTile(e.tile)))}[zr.onDestroy](s,r,a){var e=this.bridges.getPieceAtTile(s.tile);this.dominoHandled||this.bridges.findDominoPieces(e).filter(e=>!e.obj.isDestroyed).forEach(e=>{e.obj.traits.get(_h).dominoHandled=!0,r.destroyObject(e.obj,a)});let t=r.map.tileOccupation.calculateTilesForGameObject(s.tile,s);t.forEach(e=>{let t=Gi(e.terrainType),i=r.rules.getLandRules(t);r.map.getGroundObjectsOnTile(e).forEach(e=>{e.isUnit()&&e.onBridge&&!e.isDestroyed&&(s.isLowBridge()&&0<i.getSpeedModifier(e.rules.speedType)||e.isInfantry()&&e.stance===Ls.Paradrop?(e.onBridge=!1,e.zone=_s(t)):(e.isInfantry()&&(e.infDeathType=ti.None),r.destroyObject(e,a,!0)))})})}}(r=Ln=Ln||{})[r.Idle=0]="Idle",r[r.Spawning=1]="Spawning";class Ih{constructor(e){this.rules=e,this.ticksSinceLastSpawn=0,this.cooldownTicks=Math.floor(1/this.rules.animationProbability),this.status=Ln.Idle}[Fr.onTick](e,t){this.status=Ln.Idle,this.ticksSinceLastSpawn++>this.cooldownTicks&&(this.ticksSinceLastSpawn=0,this.status=Ln.Spawning,this.spawnTiberium(e.tile,t))}spawnTiberium(s,r){for(let i=1;i<=2;i++){let e=new Us(r.map.tiles,r.map.mapBounds,s,{width:1,height:1},i,i,e=>Xa.canBePlacedOn(e,r.map));var a=e.getNextTile();if(a){var n=dn.calculateOverlayId(oa.Ore,a);if(void 0===n)throw new Error("Expected an overlayId");let e=r.createObject(xt.Overlay,r.rules.getOverlayName(n));return e.overlayId=n,e.value=3,void r.spawnObject(e,a)}e=new Us(r.map.tiles,r.map.mapBounds,s,{width:1,height:1},i,i,e=>e.landType===Jt.Tiberium);let t;for(;!t;){var o=e.getNextTile();if(!o)break;t=r.map.getObjectsOnTile(o).find(e=>e.isOverlay()&&e.isTiberium()&&e.traits.get(Xa).getBailCount()+1<=Xa.maxBails)}if(t)return void t.traits.get(Xa).spawnBails(1)}}}class Ch{constructor(e=!1){this.freeRepair=e,this.disabled=!0,this.cooldownTicks=0,this.healLeftover=0}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}[Fr.onTick](t,i){if(!this.isDisabled())if(100===t.healthTrait.health&&this.setDisabled(!0),this.cooldownTicks<=0){var s=i.rules.general.repair,r=t.isInfantry()?s.iRepairRate:t.isBuilding()?s.repairRate:s.uRepairRate;this.cooldownTicks+=js.BASE_TICKS_PER_SECOND*r*60;var a=t.isInfantry()?s.iRepairStep:s.repairStep,r=this.freeRepair?0:s.repairPercent;let e;r?(s=r*t.purchaseValue/t.healthTrait.maxHitPoints,(r=Math.min(t.owner.credits,Math.max(1,Math.floor(s*a))))?(e=s?r/s:a,t.owner.credits-=r):(e=0,this.setDisabled(!0))):e=a,e&&(e+=this.healLeftover,e=Math.min(t.healthTrait.maxHitPoints-t.healthTrait.getHitPoints(),e),e&&(a=Math.floor(e),this.healLeftover=e-a,a&&t.healthTrait.healBy(a,t,i)))}else this.cooldownTicks--}[Qr.onChange](){this.setDisabled(!0)}}(Fn=Fn||{}).onDestroy=Symbol();class Ah{constructor(e){this.target=e,this.type=ss.UnitPromote}}class Bh{constructor(){this.cooldownTicks=0}[Fr.onTick](e,t){100!==e.healthTrait.health&&(this.cooldownTicks<=0?(this.cooldownTicks+=js.BASE_TICKS_PER_SECOND*t.rules.general.repair.repairRate*60,e.healthTrait.healBy(1,e,t)):this.cooldownTicks--)}}class xh{constructor(e,t){this.gameObject=e,this.rules=t,this.specialWeaponIndex=0;t=e.veteranLevel===ea.Elite;e.rules.weaponCount?(this.selectSpecialWeapon(0,t),this.guardWeaponRangeOverride=this.primaryWeapon?.range):this.selectStandardWeapons(t)}selectStandardWeapons(e=!1){var t=this.gameObject,i=e&&t.rules.elitePrimary||t.rules.primary;i?(r=e?t.art.elitePrimaryFireFlh:t.art.primaryFireFlh,this.primaryWeapon=tn.factory(i,hi.Primary,t,this.rules,r)):this.primaryWeapon=void 0;var s,r=e&&t.rules.eliteSecondary||t.rules.secondary;r?(s=e?t.art.eliteSecondaryFireFlh:t.art.secondaryFireFlh,this.secondaryWeapon=tn.factory(r,hi.Secondary,t,this.rules,s)):this.secondaryWeapon=void 0,(t.explodes||t.crashableTrait)&&(s=t.rules.deathWeapon||!!t.crashableTrait&&this.secondaryWeapon?.rules.name||this.primaryWeapon?.rules.name||this.rules.combatDamage.deathWeapon,this.deathWeapon=tn.factory(s,hi.DeathWeapon,t,this.rules))}selectSpecialWeapon(e,t=!1){let i=this.gameObject;var s=i.rules.weaponCount;if(s<1)throw new Error(`Object "${i.name}" doesn't support special weapons`);if(s-1<e)throw new RangeError(`Weapon index ${e} out of bounds (max ${s}) for object ${i.name}`);s=t&&i.rules.getEliteWeaponAtIndex(e)||i.rules.getWeaponAtIndex(e);if(!s)throw new Error(`Missing weapon at index ${e} for object "${i.name}"`);t=i.art.getSpecialWeaponFlh(e);this.primaryWeapon=tn.factory(s,hi.Primary,i,this.rules,t),this.secondaryWeapon=void 0,this.specialWeaponIndex=e,this.deathWeapon=this.primaryWeapon.rules.suicide?tn.factory(i.rules.deathWeapon||this.primaryWeapon.name,hi.DeathWeapon,i,this.rules):void 0}toggleEliteWeapons(e){this.gameObject.rules.weaponCount?this.selectSpecialWeapon(this.specialWeaponIndex,e):this.selectStandardWeapons(e)}getSpecialWeaponIndex(){return this.specialWeaponIndex}computeGuardScanRange(t){var e=this.guardWeaponRangeOverride??[this.primaryWeapon,this.secondaryWeapon].filter(e=>e===t||e?.rules.neverUse).reduce((e,t)=>Math.max(e,t.range),0),e=Math.max(e,this.gameObject.rules.guardRange);return Math.min(15,2*e-1)}getDeployFireWeapon(){if(this.gameObject.rules.deployFire)return this.gameObject.rules.deployFireWeapon===hi.Primary?this.primaryWeapon:this.secondaryWeapon}isEquippedWithWeapon(e){return[this.primaryWeapon,this.secondaryWeapon].includes(e)}getWeapons(){return[this.primaryWeapon,this.secondaryWeapon].filter(ja)}[Fr.onTick](){this.primaryWeapon&&this.primaryWeapon.tick(),this.secondaryWeapon&&this.secondaryWeapon.tick()}[zr.onDestroy](t,e,i){!this.deathWeapon||i?.weapon?.warhead.rules.temporal||t.crashableTrait&&!t.isCrashing||i?.obj?.isVehicle()&&i.weapon?.rules.suicide&&i.obj.transportTrait?.units.find(e=>e===t)||this.deathWeapon.fire(e.createTarget(t,t.tile),e)}dispose(){this.gameObject=void 0,this.primaryWeapon=void 0,this.secondaryWeapon=void 0,this.deathWeapon=void 0}}class Eh{}class Ph{constructor(e,t){this.gameObject=e,this.veteranRules=t,this.veteranLevel=ea.None,this.xp=0,this.promotionThresh=e.rules.cost*t.veteranRatio+1}[Fn.onDestroy](e,t,i,s){e.isDestroyed&&!e.isCrashing||t.isTechno()&&(t.rules.dontScore||t.rules.insignificant||(i&&(i.warhead.rules.temporal||i.warhead.rules.parasite&&e.rules.organic)||!s.areFriendly(e,t))&&(this.veteranLevel>=this.veteranRules.veteranCap||this.gainXP(t.rules.cost*(t.veteranLevel+1))&&this.handlePromotion(e,s)))}setRelativeXP(e){this.gainXP(Math.floor(e*this.promotionThresh))}gainXP(e){if(this.xp+=e,this.xp>=this.promotionThresh){var t=Math.min(this.veteranLevel+Math.floor(this.xp/this.promotionThresh),this.veteranRules.veteranCap),e=t-this.veteranLevel;if(e)return this.xp-=e*this.promotionThresh,this.setVeteranLevel(t),!0}return!1}promote(e,t){e=Math.min(this.veteranLevel+e,this.veteranRules.veteranCap);e-this.veteranLevel&&(this.setVeteranLevel(e),this.handlePromotion(this.gameObject,t))}isMaxLevel(){return this.veteranLevel===this.veteranRules.veteranCap}isElite(){return this.veteranLevel===ea.Elite}setVeteranLevel(e){this.veteranLevel=e,this.veteranLevel===ea.Elite&&this.gameObject.armedTrait?.toggleEliteWeapons(!0)}handlePromotion(e,t){this.hasVeteranAbility(li.SELF_HEAL)&&(e.traits.find(Bh)||t.addObjectTrait(e,new Bh)),this.hasVeteranAbility(li.CLOAK)&&(e.cloakableTrait||(e.cloakableTrait=new un(e,t.rules.general.cloakDelay),t.addObjectTrait(e,e.cloakableTrait))),this.hasVeteranAbility(li.EXPLODES)&&(e.explodes||(e.explodes=!0,e.armedTrait||(e.armedTrait=new xh(e,t.rules),t.addObjectTrait(e,e.armedTrait)))),this.hasVeteranAbility(li.RADAR_INVISIBLE)&&(e.radarInvisible||(e.radarInvisible=!0)),this.hasVeteranAbility(li.SENSORS)&&(e.sensorsTrait||(e.sensorsTrait=new Eh,t.addObjectTrait(e,e.sensorsTrait))),e.isInfantry()&&this.hasVeteranAbility(li.FEARLESS)&&e.suppressionTrait?.disable(),this.hasVeteranAbility(li.C4)&&(e.c4||(e.c4=!0)),this.hasVeteranAbility(li.GUARD_AREA)&&(e.defaultToGuardArea||(e.defaultToGuardArea=!0,e.unitOrderTrait.isIdle()&&e.resetGuardModeToIdle())),this.hasVeteranAbility(li.CRUSHER)&&(e.crusher||(e.crusher=!0)),t.events.dispatch(new Ah(e))}getVeteranSightMultiplier(){return this.getVeteranAbilityMultiplier(li.SIGHT)}getVeteranSpeedMultiplier(){return this.getVeteranAbilityMultiplier(li.FASTER)}getVeteranArmorMultiplier(){return this.getVeteranAbilityMultiplier(li.STRONGER)}getVeteranDamageMultiplier(){return this.getVeteranAbilityMultiplier(li.FIREPOWER)}getVeteranRofMultiplier(){return this.getVeteranAbilityMultiplier(li.ROF)}hasVeteranAbility(e){return this.veteranLevel===ea.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=ea.Elite&&this.gameObject.rules.eliteAbilities.has(e)}getVeteranAbilityMultiplier(e){let t=1;return(this.veteranLevel===ea.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=ea.Elite&&this.gameObject.rules.eliteAbilities.has(e))&&(t=this.getVeteranRulesMultiplier(e)),t}getVeteranRulesMultiplier(e){switch(e){case li.FASTER:return this.veteranRules.veteranSpeed;case li.STRONGER:return this.veteranRules.veteranArmor;case li.FIREPOWER:return this.veteranRules.veteranCombat;case li.ROF:return this.veteranRules.veteranROF;case li.SIGHT:return this.veteranRules.veteranSight;default:throw new Error(`Unhandled VeteranAbility ${e}`)}}dispose(){this.gameObject=void 0}}class Nh{constructor(e,t=e){this.maxAmmo=e,this.ammo=t}get ammo(){return this._ammo}set ammo(e){this._ammo=z(e,0,this.maxAmmo)}isFull(){return this.ammo===this.maxAmmo}}class Mh{constructor(e){this.target=e,this.type=ss.ObjectDisguiseChange}}class Dh{constructor(){this.isActive=!1,this.cooldownTicks=0}isDisguised(){return this.isActive}getDisguise(){return this.isActive?this.disguisedAs:void 0}hasTerrainDisguise(){return this.getDisguise()?.rules.type===xt.Terrain}disguiseAs(e,t,i){this.disguisedAs={rules:e.rules,owner:e.owner},this.isActive=!0,i.events.dispatch(new Mh(t))}revealDisguise(e,t){this.cooldownTicks=t.rules.general.infantryBlinkDisguiseTime,this.isActive=!1,t.events.dispatch(new Mh(e))}[Yr.onSpawn](e,t){var i;!this.disguisedAs&&e.rules.permaDisguise&&e.isInfantry()&&e.owner.country&&((i=this.getDefaultInfantryDisguise(e.owner.country.side,t.rules.general))&&(i=t.rules.getObject(i,xt.Infantry),this.disguisedAs={rules:i,owner:e.owner},this.isActive=!0))}getDefaultInfantryDisguise(e,t){switch(e){case Zt.GDI:return t.alliedDisguise;case Zt.Nod:return t.sovietDisguise;default:return}}[Fr.onTick](e,t){e.rules.permaDisguise||(e.attackTrait?.attackState===wn.JustFired||e.moveTrait.moveState!==qr.Idle?this.revealDisguise(e,t):0<this.cooldownTicks?this.cooldownTicks--:!this.isActive&&e.rules.disguiseWhenStill&&(this.isActive=!0,this.disguisedAs={rules:this.selectRandomMirageDisguise(t),owner:void 0},t.events.dispatch(new Mh(e))))}[ua.onDamage](e,t){this.revealDisguise(e,t)}selectRandomMirageDisguise(e){var t=e.rules.general.defaultMirageDisguises;if(!t.length)throw new Error("No default mirage disguises are defined");t=t[e.generateRandomInt(0,t.length-1)];return e.rules.getObject(t,xt.Terrain)}}class Rh{constructor(){this.timer=new Do}isActive(){return this.timer.isActive()}setActiveFor(e,t){this.timer.setActiveFor(e,t)}[Fr.onTick](e,t){this.timer.tick(t.currentTick)}}class Lh{constructor(e){this.gameObject=e,this.ticksWhenWarpedOut=!0,this.remainingTicks=0,this.invulnerable=!1}isActive(){return 0<this.remainingTicks}setActive(e,t,i){this.remainingTicks=e?Number.POSITIVE_INFINITY:0,this.invulnerable=t,this.notifyChange(e,i)}setTimed(e,t,i){this.remainingTicks=e,this.invulnerable=t,this.notifyChange(!0,i)}debugSetActive(e){this.remainingTicks=e?Number.POSITIVE_INFINITY:0}notifyChange(t,i){i.traits.filter(Ps).forEach(e=>{e[Ps.onChange](this.gameObject,i,t)}),this.gameObject.traits.filter(vn).forEach(e=>{e[vn.onChange](this.gameObject,i,t)})}expire(e){this.remainingTicks=0,this.notifyChange(!1,e)}isInvulnerable(){return this.isActive()&&this.invulnerable}[Fr.onTick](e,t){0<this.remainingTicks&&(this.remainingTicks--,this.remainingTicks<=0&&this.notifyChange(!1,t))}dispose(){this.gameObject=void 0}}class Fh{constructor(){this.timer=new Do}hasCharge(){return this.timer.isActive()}setCharge(e,t,i){this.hasCharge()||(this.timer.setActiveFor(e,t),this.attackerInfo=i)}getChargeOwner(){return this.attackerInfo?.player}removeCharge(){this.timer.reset()}getTicksLeft(){return this.timer.getTicksLeft()}getInitialTicks(){return this.timer.getInitialTicks()}[Fr.onTick](e,t){this.timer.isActive()&&!0===this.timer.tick(t.currentTick)&&(e.isBuilding()&&e.cabHutTrait&&e.cabHutTrait.demolishBridge(t,this.attackerInfo),this.detonateIvanWarhead(t,e))}[zr.onDestroy](e,t,i){this.timer.isActive()&&!i?.weapon?.warhead.rules.ivanBomb&&e.deathType!==Vr.None&&e.deathType!==Vr.Temporal&&(this.timer.reset(),this.detonateIvanWarhead(t,e))}detonateIvanWarhead(e,t){var i=e.rules.combatDamage.ivanDamage;let s=new Ya(e.rules.getWarhead(e.rules.combatDamage.ivanWarhead));var r=t.tile,a=t.tileElevation,n=t.isUnit()?t.zone:e.map.getTileZone(r),o=!!t.isUnit()&&t.onBridge;s.detonate(e,i,r,a,t.isBuilding()?Os.tile3dToWorld(r.rx+.5,r.ry+.5,r.z+a):t.position.worldPosition,n,o?aa.OnBridge:aa.None,e.createTarget(t,r),{...this.attackerInfo,weapon:void 0},!1,!1,void 0)}}class jh{constructor(e){this.gameObject=e}getOriginalOwner(){return this.prevOwner}isActive(){return!!this.controller}getController(){return this.controller}controlBy(e,t){if(this.controller)throw new Error(`Object "${this.gameObject?.name}" is already mind controlled by "${e.name}"`);this.controller=e,this.prevOwner=this.gameObject.owner,t.changeObjectOwner(this.gameObject,e.owner)}restore(e){this.prevOwner&&(e.changeObjectOwner(this.gameObject,this.prevOwner),this.prevOwner=void 0,this.controller=void 0)}[Kr.onUnspawn](e,t){this.controller&&(this.controller.mindControllerTrait.cleanTarget(e),!e.isDestroyed&&e.limboData&&this.restore(t))}dispose(){this.gameObject=void 0}}class Uh{constructor(e,t=1){this.gameObject=e,this.maxCapacity=t,this.targets=[]}isActive(){return 0<this.targets.length}isAtCapacity(){return this.targets.length===this.maxCapacity}getTargets(){return this.targets}control(e,t){if(!this.gameObject)throw new Error("Trait already disposed");if(!e.mindControllableTrait)throw new Error(`Target "${e.name}" cannot be mind controlled`);if(e.isDisposed)throw new Error(`Target "${e.name}" is disposed`);for(e.mindControllableTrait.controlBy(this.gameObject,t),this.targets.push(e);this.targets.length>this.maxCapacity;){let e=this.targets.shift();e.mindControllableTrait.restore(t)}}cleanTarget(e){e=this.targets.indexOf(e);-1!==e&&this.targets.splice(e,1)}[Kr.onUnspawn](e,t){for(var i of this.targets)i.mindControllableTrait.restore(t);this.targets.length=0}dispose(){this.gameObject=void 0}}class Wh{constructor(e){this.gameObject=e,this.ticksWhenWarpedOut=!0,this.attackers=new Set}[Fr.onTick](e,t){if(e.attackTrait&&(e.attackTrait.currentTarget&&!e.warpedOutTrait.isActive()||this.releaseCurrentTarget(t)),void 0!==this.eraseTicks)for(var i of this.attackers){var s=i.temporalTrait.currentWeapon;if(!s)throw new Error(`Attacker "${i.name}" is no longer targeting "${e.name}"`);var r=s.rules.damage;if(this.eraseTicks-=r,this.eraseTicks<=0){e.deathType=Vr.Temporal,t.destroyObject(e,{player:i.owner,obj:i,weapon:s},!0),this.eraseTicks=void 0;break}}}getTarget(){return this.currentTarget}updateTarget(t,e,i){if(this.currentTarget!==t){this.releaseCurrentTarget(i),this.currentTarget=t,this.currentWeapon=e;e=t.temporalTrait.attackers.size;if(t.temporalTrait.attackers.add(this.gameObject),!e){t.warpedOutTrait.setActive(!0,!0,i);let e=t.unitOrderTrait.getCurrentTask();(e&&e instanceof go||e instanceof ka)&&e.cancel(),t.temporalTrait.eraseTicks=10*t.healthTrait.maxHitPoints}}}releaseCurrentTarget(t){if(this.currentTarget){if(!this.currentTarget.isDisposed){let e=this.currentTarget.temporalTrait.attackers;e.delete(this.gameObject),e.size||(this.currentTarget.warpedOutTrait.expire(t),this.currentTarget.temporalTrait.eraseTicks=void 0)}this.currentTarget=void 0,this.currentWeapon=void 0}}[zr.onDestroy](e,t){this.releaseCurrentTarget(t)}dispose(){this.gameObject=void 0,this.attackers.clear()}}class zh{constructor(){this.spawns=[],this.storage=[],this.missileLaunches=[],this.nextRegenTicks=[]}get availableSpawns(){return this.storage.length}debugSetStorage(e,t){this.storage.length=t,this.storage.fill(e,0,t)}isLaunchingMissiles(){return 0<this.missileLaunches.length}[Yr.onSpawn](t,i){var s=i.rules.getObject(t.rules.spawns,xt.Aircraft);for(let e=0;e<t.rules.spawnsNumber;e++)this.pushNewSpawn(s,i,t)}[Kr.onUnspawn](e,t){this.destroySpawns(e,t)}[zr.onDestroy](e,t,i,s){this.destroySpawns(e,t,i,s)}pushNewSpawn(e,t,i){let s=t.createUnitForPlayer(e,i.owner);s.limboData={selected:!1,controlGroup:void 0},e.missileSpawn&&(s.pitch=90*t.rules.general.getMissileRules(e.name).pitchInitial),this.spawns.push(s),this.storage.push(s)}destroySpawns(e,t,i,s){for(var r of this.spawns)r.isDestroyed||(r.isSpawned&&!r.rules.missileSpawn&&r.crashableTrait?r.crashableTrait.crash(i):(r.isSpawned||(r.armedTrait&&(r.armedTrait.deathWeapon=void 0),r.position.tileElevation=e.position.tileElevation,r.zone=e.isUnit()?e.zone:vs.Ground,r.onBridge=!!e.isUnit()&&e.onBridge,r.position.tile=e.tile),t.destroyObject(r,i,s)));this.spawns.length=0,this.storage.length=0,this.missileLaunches.length=0}[Fr.onTick](r,a){var t;if(this.spawns=this.spawns.filter(e=>!e.isDestroyed),this.missileLaunches=this.missileLaunches.filter(e=>!e.missile.isDestroyed),this.spawns.length<r.rules.spawnsNumber){var i=r.rules.spawnsNumber-this.spawns.length,s=a.rules.getObject(r.rules.spawns,xt.Aircraft);for(let e=0;e<i;e++)s.missileSpawn&&e&&void 0===this.nextRegenTicks[e]?this.nextRegenTicks[e]=this.nextRegenTicks[0]:((t=this.nextRegenTicks)[e]??(t[e]=r.rules.spawnRegenRate),0<this.nextRegenTicks[e]&&this.nextRegenTicks[e]--),this.nextRegenTicks[e]<=0&&this.pushNewSpawn(s,a,r);this.nextRegenTicks=this.nextRegenTicks.filter(e=>0<e)}if(this.storage.length){if(this.nextReloadTicks??(this.nextReloadTicks=r.rules.spawnReloadRate),0<this.nextReloadTicks&&this.nextReloadTicks--,this.nextReloadTicks<=0){for(var e of this.storage)e.ammoTrait&&e.ammoTrait.ammo<e.ammoTrait.maxAmmo&&e.ammoTrait.ammo++;this.nextReloadTicks=r.rules.spawnReloadRate}}else this.nextReloadTicks=void 0;for(let s of this.missileLaunches.slice()){var n=a.rules.general.getMissileRules(s.missile.name);if(s.pauseFrames??(s.pauseFrames=n.pauseFrames),0<s.pauseFrames&&s.pauseFrames--,s.pauseFrames<=0){var o=90*n.pitchFinal,n=90*(n.pitchFinal-n.pitchInitial)/n.tiltFrames;let i=s.missile;if(i.pitch<o)i.pitch=Math.min(o,i.pitch+n);else{i.unitOrderTrait.addTask(new Ua(new ka(a,s.targetTile,!!s.targetBridge),new ma(()=>{var e,t;i.isDestroyed||(a.unspawnObject(i),i.dispose(),t=Os.vecGroundToWorld(br.toMapCoords(i.direction).multiplyScalar(1)),e=s.targetWorldPos.clone().add(t),t=a.map.getTileZone(s.targetTile),s.warhead.detonate(a,s.damage,s.targetTile,s.targetBridge?.tileElevation??0,e,t,s.targetBridge?aa.OnBridge:aa.None,s.target,{player:i.owner,obj:r,weapon:void 0},!1,!1,void 0))})).setCancellable(!1));n=this.spawns.indexOf(i);if(-1===n)throw new Error("Missile not found in spawns list");this.spawns.splice(n,1),this.missileLaunches.splice(this.missileLaunches.indexOf(s),1)}}}}[Qr.onChange](e,t,i){for(var s of this.spawns)s.isDestroyed||i.changeObjectOwner(s,e.owner)}[vn.onChange](e,t,i){i&&this.removeMissileLaunches(t)}[Wr.onBeforeTeleport](e,t,i,s){s||this.removeMissileLaunches(t)}removeMissileLaunches(e){if(this.missileLaunches.length){for(var t of this.missileLaunches){e.unspawnObject(t.missile),t.missile.dispose();t=this.spawns.indexOf(t.missile);if(-1===t)throw new Error("Missile not found in spawns list");this.spawns.splice(t,1)}this.missileLaunches.length=0}}prepareLaunch(s,r,a){if(this.storage.length){let i=this.storage[0];if(!i.ammo)return;if(this.storage.shift(),i.missileSpawnTrait){let e,t;var n=s.veteranTrait?.isElite(),o=a.rules;if(s.rules.spawns===o.general.v3Rocket.type)e=n?o.combatDamage.v3EliteWarhead:o.combatDamage.v3Warhead,t=n?o.general.v3Rocket.eliteDamage:o.general.v3Rocket.damage;else{if(s.rules.spawns!==o.general.dMisl.type)throw new Error(`Unhandled missile type "${s.rules.spawns}"`);e=n?o.combatDamage.dMislEliteWarhead:o.combatDamage.dMislWarhead,t=n?o.general.dMisl.eliteDamage:o.general.dMisl.damage}a=new Ya(a.rules.getWarhead(e));i.missileSpawnTrait.setDamage(t).setWarhead(a).setLauncher(s),this.missileLaunches.push({missile:i,targetTile:(r.obj?.isUnit()?r.obj:r).tile,targetBridge:r.getBridge(),targetWorldPos:r.getWorldCoords().clone(),target:r,warhead:a,damage:t,pauseFrames:void 0})}else{if(!i.spawnLinkTrait)throw new Error(`Aircraft "${i.name}" must have Spawned=yes to be launchable`);i.spawnLinkTrait.setParent(s)}return i}}storeAircraft(e,t){if(!this.spawns.includes(e))throw new Error(`Object "${e.name}#${e.id}" not found in list of linked spawns`);if(e.limboData)throw new Error(`Object "${e.name}#${e.id}" is already in limbo`);t.limboObject(e,{selected:!1,controlGroup:void 0}),this.storage.push(e)}}class Vh{[ta.onCrash](e,t){this.handleDestroy(e,t)}[zr.onDestroy](e,t,i){i?.weapon?.warhead.rules.temporal||e.isCrashing||e.deathType!==Vr.Sink&&e.isSpawned&&this.handleDestroy(e,t)}handleDestroy(e,t){var i,s;(e.isVehicle()||e.isBuilding()||e.isOverlay())&&(i=e.isOverlay()?0:e.rules.minDebris,s=e.isOverlay()?t.rules.general.bridgeVoxelMax:e.rules.maxDebris,0<(s=t.generateRandomInt(i,s))&&this.spawnDebris(e,t,s))}spawnDebris(t,i,s){let r=t.position.getMapPosition();if(i.map.isWithinHardBounds(r)){let e=t.isOverlay()?[]:t.isVehicle()?t.rules.debrisTypes:t.rules.debrisAnims;e.length||(e=i.rules.audioVisual.metallicDebris),e=e.filter(e=>i.rules.hasObject(e,xt.VoxelAnim)||i.art.hasObject(e,xt.Animation)),new Array(s).fill(0).map(()=>e[i.generateRandomInt(0,e.length-1)]).map(e=>i.createObject(xt.Debris,e)).forEach(e=>{e.position.moveToLeptons(r),e.position.tileElevation=t.position.tileElevation,i.spawnObject(e,e.position.tile)})}}}class Hh extends Ba{constructor(e,t,i,s){super(xt.Debris,e,t,i),this.age=0,this.direction=0,this.rotationAxis=new rs,this.angularVelocity=0,this.zone=vs.Air,this.velocity=new rs,this.collisionHelper=new Th(s)}static factory(e,t,i,s){return new this(e,t,i,s)}onSpawn(e){super.onSpawn(e),this.direction=e.generateRandomInt(0,359),this.xySpeed=H(0,this.rules.maxXYVel,e.generateRandom()),this.zSpeed=H(this.rules.minZVel,this.rules.maxZVel||1.5*this.rules.minZVel,e.generateRandom()),this.rotationAxis.set(e.generateRandom(),e.generateRandom(),e.generateRandom()).normalize(),this.angularVelocity=H(this.rules.minAngularVelocity,this.rules.maxAngularVelocity,e.generateRandom())}update(t){if(super.update(t),this.age++,this.rules.duration&&this.age>this.rules.duration)return this.velocity.set(0,0,0),void this.detonate(t);--this.zSpeed;var i=br.toMapCoords(this.direction).setLength(this.xySpeed);let s=new rs(i.x,this.zSpeed,i.y);var r=this.position.clone(),i=s.clone().add(this.position.worldPosition);if(t.map.isWithinHardBounds(i)){this.position.moveByLeptons3(s);let e=!1;var{type:i,target:r}=this.collisionHelper.checkCollisions(this.position,r,{cliffs:!0,ground:!0,shore:!1,walls:!0,units:!1});if(i&&(!([aa.Ground,aa.OnBridge].includes(i)&&0<this.rules.elasticity&&t.map.getTileZone(this.tile)!==vs.Water)||Math.abs(this.zSpeed)<1?e=!0:(this.zSpeed=-this.zSpeed*this.rules.elasticity,this.velocity.y=-this.velocity.y*this.rules.elasticity,this.rotationAxis.negate())),e){if(this.velocity.set(0,0,0),r&&i===aa.Wall){let e=r.position.worldPosition;this.position.moveByLeptons3(e.clone().sub(this.position.worldPosition))}this.detonate(t,i)}else this.velocity.copy(s)}else t.unspawnObject(this)}detonate(t,i=aa.None){var e,s=this.rules.warhead?t.rules.getWarhead(this.rules.warhead):void 0,r=this.zone=this.collisionHelper.computeDetonationZone(this.tile,this.tileElevation,i);let a;r===vs.Water?(e=t.rules.combatDamage.splashList,a=e[0]):(e=this.rules.expireAnim)&&t.rules.animationNames.has(e)&&(a=e),this.explodeAnim=a;let n=new Za;if(a&&n.spawnSmudges(a,this.tile,t),t.destroyObject(this),s){let e=new Ya(s);e.detonate(t,this.rules.damage,this.tile,this.tileElevation,this.position.worldPosition,r,i,t.createTarget(void 0,this.tile),void 0,!1,!1,void 0,this.rules.damageRadius||void 0,!0)}}}class Gh{constructor(e,t,i,s){this.tiles=e,this.tileOccupation=t,this.bridges=i,this.nextObjectId=s}create(e,t,i,s){let r,a;e===xt.Debris?r=i.hasObject(t,xt.VoxelAnim)?(a=s.getObject(t,xt.VoxelAnim),i.getObject(t,xt.VoxelAnim)):(a=s.getAnimation(t),new us(xt.Debris,s.getIni().getOrCreateSection(t))):a=e===xt.Projectile?(r=i.getProjectile(t),r.inviso?new qn(xt.Projectile,r,new h(t)):s.getProjectile(t)):(r=i.getObject(t,e),s.getObject(t,e));let n;switch(e){case xt.Building:n=qo.factory(t,r,i,a,this.tiles,this.bridges);break;case xt.Infantry:n=Ra.factory(t,r,a,this.tileOccupation);break;case xt.Vehicle:n=uh.factory(t,r,a,i,this.tileOccupation);break;case xt.Aircraft:n=mh.factory(t,r,a,i,this.tileOccupation);break;case xt.Terrain:n=Xo.factory(t,r,a);break;case xt.Overlay:n=Zo.factory(t,r,a);break;case xt.Smudge:n=Qo.factory(t,r,a);break;case xt.Projectile:n=bh.factory(t,r,a,this.tileOccupation);break;case xt.Debris:n=Hh.factory(t,r,a,this.tileOccupation);break;default:throw new Error("Not implemented")}if(n.id=this.nextObjectId.value++,n.position=new wh(this.tiles,this.tileOccupation),n.isUnit()?n.position.subCell=0:n.isBuilding()&&n.position.setCenterOffset(n.getFoundationCenterOffset()),n.isTechno()&&((n.rules.primary||n.rules.secondary||n.rules.weaponCount||n.rules.explodes)&&(n.armedTrait=new xh(n,i),n.traits.add(n.armedTrait)),-1!==n.rules.ammo&&(o=n.rules.initialAmmo,n.ammoTrait=new Nh(n.rules.ammo,-1!==o?o:void 0),n.traits.add(n.ammoTrait)),n.unitOrderTrait=new fh(n),n.traits.addToFront(n.unitOrderTrait),(n.primaryWeapon||n.secondaryWeapon)&&(n.attackTrait=new po(this.tiles,this.tileOccupation),n.traits.add(n.attackTrait)),(n.isInfantry()||n.isVehicle())&&n.rules.deployer&&(n.deployerTrait=new vh(n),n.traits.add(n.deployerTrait)),(n.isInfantry()||n.isVehicle())&&n.rules.canDisguise&&(n.disguiseTrait=new Dh,n.traits.add(n.disguiseTrait)),n.rules.cloakable&&(n.cloakableTrait=new un(n,i.general.cloakDelay),n.traits.add(n.cloakableTrait)),n.rules.sensors&&(n.sensorsTrait=new Eh,n.traits.add(n.sensorsTrait)),n.autoRepairTrait=new Ch(!n.isBuilding()),n.traits.add(n.autoRepairTrait),n.rules.trainable&&(n.veteranTrait=new Ph(n,i.general.veteran),n.traits.add(n.veteranTrait)),n.rules.selfHealing&&n.traits.add(new Bh),n.invulnerableTrait=new Rh,n.traits.add(n.invulnerableTrait),n.warpedOutTrait=new Lh(n),n.traits.add(n.warpedOutTrait),n.temporalTrait=new Wh(n),n.traits.add(n.temporalTrait),n.rules.bombable&&(n.tntChargeTrait=new Fh,n.traits.add(n.tntChargeTrait)),n.rules.immuneToPsionics||n.isBuilding()||(n.mindControllableTrait=new jh(n),n.traits.add(n.mindControllableTrait)),[n.primaryWeapon,n.secondaryWeapon].some(e=>e?.warhead.rules.mindControl)&&(n.mindControllerTrait=new Uh(n),n.traits.add(n.mindControllerTrait)),n.rules.spawns&&(n.airSpawnTrait=new zh,n.traits.add(n.airSpawnTrait)),n.rules.maxDebris&&n.traits.add(new Vh)),n.isTechno()||n.isOverlay()||n.isTerrain()){var o=n.isOverlay()&&Ha.isBridge(i.getOverlayId(n.name));let e=n.rules.strength;!e&&n.isTerrain()&&(e=i.general.treeStrength),o&&(e=i.combatDamage.bridgeStrength),(e||n.isTechno())&&(n.healthTrait=new Oh(e,n,i.audioVisual.conditionYellow,i.audioVisual.conditionRed),n.traits.add(n.healthTrait)),n.isOverlay()&&o&&(n.bridgeTrait=new _h(this.bridges),n.traits.add(n.bridgeTrait),Ha.getOverlayBridgeType(i.getOverlayId(n.name))===sa.Concrete&&n.traits.add(new Vh))}return n.isOverlay()&&n.isOverlay()&&qa.getOverlayTibType(i.getOverlayId(n.name))!==oa.NotSpecial&&n.traits.add(new Xa(n)),n.isTerrain()&&n.rules.spawnsTiberium&&n.traits.add(new Ih(n.rules)),n.cachedTraits.tick.push(...n.traits.filter(Fr)),n}}class $h{constructor(){this.allObjects=new Map,this._onObjectSpawned=new ao,this._onObjectRemoved=new ao}get onObjectSpawned(){return this._onObjectSpawned.asEvent()}get onObjectRemoved(){return this._onObjectRemoved.asEvent()}spawnObject(e){if(this.allObjects.has(e.id))throw new Error("Trying to add an already existing object");this.allObjects.set(e.id,e),this._onObjectSpawned.dispatch(this,e)}removeObject(e){if(!this.allObjects.has(e.id))throw new Error("Trying to remove non-existent object");this.allObjects.delete(e.id),this._onObjectRemoved.dispatch(this,e)}hasObjectId(e){return this.allObjects.has(e)}getObjectById(e){if(!this.allObjects.has(e))throw new Error(`Object with id ${e} doesn't exist`);return this.allObjects.get(e)}getAllObjects(){return[...this.allObjects.values()]}}var qh,Xh,Zh,Qh,Yh,Kh,Jh,el,tl,r=__webpack_require__(495),il=__webpack_require__.n(r),sl=__webpack_require__(45);class rl{constructor(e,t,i,s,r){this.tiles=e,this.theaterType=t,this.mapBounds=i,this.tileOccupation=s,this.rules=r,this.passabilityGraphs=new Map,this.invalidatedTiles=new Map,this.handleTileOccupationUpdate=({tiles:e,object:i})=>{e=e.filter(e=>{let t=ei.Foot;return i.isTerrain()&&i.rules.getOccupationBits(this.theaterType)!==ts.All&&(t=ei.Wheel),i.isOverlay()&&(i.isBridge()||i.isTiberium())||this.isBlockerObject(i,e,!1,t)||this.isBlockerObject(i,e,!0,t)||i.isBuilding()&&i.rules.leaveRubble});e.length&&this.invalidateTiles(e)},this.handleMapBoundsResize=()=>{this.passabilityGraphs.clear()},s.onChange.subscribe(this.handleTileOccupationUpdate),i.onLocalResize.subscribe(this.handleMapBoundsResize)}invalidateTiles(i){i.length&&[...this.passabilityGraphs.keys()].forEach(e=>{let t=this.invalidatedTiles.get(e);t?i.forEach(e=>t.add(e)):this.invalidatedTiles.set(e,new Set(i))})}computePath(t,e,i,s,r,{maxExpandedNodes:a=Number.POSITIVE_INFINITY,bestEffort:n=!0,excludeTiles:o,ignoredBlockers:h=[]}={}){let l=this.computePassabilityGraph(t);var c=h.map(e=>this.tileOccupation.calculateTilesForGameObject(e.tile,e)).reduce((e,t)=>e.concat(t),[]);if(c.length&&this.updatePassability(c,t,l,h),!this.getPassableSpeed(e,t,i,h))return c.length&&this.updatePassability(c,t,l),[];var u=this.getNodeId(s,r),d=!!l.hasNode(u);d||((h=new Us(this.tiles,this.mapBounds,s,{width:1,height:1},1,5,e=>0<this.getPassableSpeed(e,t,!1)&&Math.abs(e.z-s.z)<2&&!o?.({tile:e,onBridge:void 0,speed:100})).getNextTile())?(s=h,r=!1):(l.addNode(u,{tile:s,onBridge:void 0,speed:100}),a=Math.min(a,500)));let p=(0,sl.aStar)(l,{bestEffort:n,maxExpandedNodes:a,distance(e,t){if(o?.(t.data)||!t.data.speed)return Number.POSITIVE_INFINITY;var i=Math.abs(e.data.tile.rx-t.data.tile.rx),t=Math.abs(e.data.tile.ry-t.data.tile.ry);return i+t+(Math.SQRT2-2)*Math.min(i,t)},heuristic(e,t,i){if(o?.(t.data)||!t.data.speed)return Number.POSITIVE_INFINITY;var s=Math.abs(e.data.tile.rx-t.data.tile.rx),t=Math.abs(e.data.tile.ry-t.data.tile.ry);let r=s+t+(Math.SQRT2-2)*Math.min(s,t);return i?.parent&&(t=(s=i.parent.node).data.tile.rx-e.data.tile.rx,e=s.data.tile.ry-e.data.tile.ry,i.dirX=t,i.dirY=e,t===i.parent.dirX&&e===i.parent.dirY||(r+=.2)),r}}),g=p.find(this.getNodeId(e,i),this.getNodeId(s,r)).map(e=>({tile:e.data.tile,onBridge:e.data.onBridge}));return(g.length<2||o&&g.length&&(!n&&g[0].tile!==s||g[g.length-1].tile!==e))&&(g=[]),!d&&l.hasNode(u)&&l.removeNode(u),c.length&&this.updatePassability(c,t,l),g}computeAllPassabilityGraphs(){Object.keys(ei).forEach(e=>{e=Number(e);isNaN(e)||e===ei.Winged||this.computePassabilityGraph(e)})}computePassabilityGraph(t){let i=this.passabilityGraphs.get(t);if(i){let e=this.invalidatedTiles.get(t);e?.size&&(this.updatePassability([...e],t,i),e.clear())}else i=il()({multigraph:!0}),this.passabilityGraphs.set(t,i),this.tiles.forEach(e=>{this.computePassability(e,t,i)});return i}updatePassability(e,t,i,s=[]){let r=new Set;e.forEach(e=>{[e,this.tiles.getNeighbourTile(e,na.Right),this.tiles.getNeighbourTile(e,na.BottomRight),this.tiles.getNeighbourTile(e,na.Bottom),this.tiles.getNeighbourTile(e,na.BottomLeft)].filter(ja).forEach(e=>r.add(e))}),e.forEach(e=>{i.removeNode(this.getNodeId(e,!1)),i.removeNode(this.getNodeId(e,!0))}),r.forEach(e=>{this.computePassability(e,t,i,s)})}computePassability(e,t,i,s=[]){var r=[na.Left,na.TopLeft,na.Top,na.TopRight];let a=this.getPassableSpeed(e,t,!1,s);if(a){var n,o=this.getNodeId(e,!1);i.hasNode(o)||i.addNode(o,{speed:a,tile:e,onBridge:void 0});for(n of r)this.connectTiles(e,void 0,n,t,i,s)}var h=this.tileOccupation.getBridgeOnTile(e);if(h&&(a=this.getPassableSpeed(e,t,!0,s),a)){var l,o=this.getNodeId(e,!0);i.hasNode(o)||i.addNode(o,{speed:a,tile:e,onBridge:h});for(l of r)this.connectTiles(e,h,l,t,i,s)}}connectTiles(t,i,s,r,a,n=[]){var o=this.tiles.getNeighbourTile(t,s);if(o){let e=this.tileOccupation.getBridgeOnTile(o);s=i||e?0:1;if(Math.abs(t.z+(i?.tileElevation??0)-(o.z+(e?.tileElevation??0)))>s){if(!e?.isHighBridge()&&!i?.isHighBridge()||0!==Math.abs(t.z-o.z)||!a.hasNode(this.getNodeId(t,!1)))return;i=e=void 0}r=this.getPassableSpeed(o,r,!!e,n);r&&(n=this.getNodeId(o,!!e),a.hasNode(n)||a.addNode(n,{speed:r,tile:o,onBridge:e}),i=this.getNodeId(t,!!i),a.getLink(i,n)||a.addLink(i,n))}}getNodeId(e,t){return e.id+(t?"_bridge":"")}getPassableSpeed(e,t,i,s=[],r=!1){if(!this.mapBounds.isWithinBounds(e))return 0;let a=i?e.onBridgeLandType:e.landType;if(void 0===a)return 0;a===Jt.Wall&&t===ei.Track&&(a=Gi(e.terrainType));let n=this.rules.getLandRules(a);var o,h=n.getSpeedModifier(t);if(!h)return 0;if(!r)for(o of this.tileOccupation.getObjectsOnTile(e))if(this.isBlockerObject(o,e,i,t)&&!s.includes(o))return 0;return h}isBlockerObject(t,i,e,s){if(t.isTerrain()&&s===ei.Foot&&t.rules.getOccupationBits(this.theaterType)!==ts.All)return!1;if(t.isBuilding()){if(t.rules.invisibleInGame)return!1;if(t.isDestroyed&&t.rules.leaveRubble)return!1;if(t.rules.gate)return!1;var r=t.art.foundation;let e=t.rules.numberImpassableRows;return s===ei.Foot?e=r.width:t.rules.weaponsFactory&&!e&&(e=r.width-1),Nr({x:t.tile.rx,y:t.tile.ry,width:(e||r.width)-1,height:r.height-1},{x:i.rx,y:i.ry})}return!(t.isAircraft()||t.isInfantry()||t.isVehicle()||t.isSmudge()||t.isOverlay()&&(e&&t.isBridge()||!e&&t.isHighBridge()||t.isTiberium()||t.rules.crate||t.isBridgePlaceholder())||[ei.Track,ei.Hover].includes(s)&&t.rules.crushable)}findObstacles(t,e){var i,s,r=e.rules.speedType;let a=[];for(i of this.tileOccupation.getGroundObjectsOnTile(t.tile))i!==e&&(((s=this.isBlockerObject(i,t.tile,!!t.onBridge,r))||i.isUnit()&&(i.tile===t.tile&&i.onBridge===!!t.onBridge||i.moveTrait.reservedPathNodes.find(e=>e.tile===t.tile&&!!e.onBridge==!!t.onBridge))||[ei.Track,ei.Hover].includes(r)&&i.rules.crushable||r===ei.Foot&&i.isTerrain()||i.isBuilding()&&i.rules.gate)&&(s={obj:i,static:s},i.isInfantry()&&e.isInfantry()?i.position.desiredSubCell===e.position.desiredSubCell&&a.push(s):i.isTerrain()&&e.isInfantry()&&!i.rules.getOccupiedSubCells(this.theaterType).includes(e.position.desiredSubCell)||a.push(s)));return a}dispose(){this.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate),this.mapBounds.onLocalResize.unsubscribe(this.handleMapBoundsResize)}}class al{constructor(){this.mapCutoffHeight=0,this.mapBuildableSize={x:0,y:0,width:0,height:0},this.localSize={x:0,y:0,width:0,height:0},this.fullSize={width:0,height:0},this.clampedFullSize={x:0,y:0,width:0,height:0},this.rawLocalSize={x:0,y:0,width:0,height:0},this._onLocalResize=new ao}get onLocalResize(){return this._onLocalResize.asEvent()}fromMapFile(e,t){this.fullSize={width:2*e.fullSize.width,height:2*e.fullSize.height},this.clampedFullSize={x:1,y:2,width:2*(e.fullSize.width-1)-1/Os.ISO_TILE_SIZE,height:2*(e.fullSize.height-1)+1-1/Os.ISO_TILE_SIZE},this.mapCutoffHeight=Math.max(9,t.getCutoffTileHeight());t=Math.max(2,e.localSize.x),e={x:t,y:e.localSize.y,width:Math.min(e.fullSize.width-2-t,e.localSize.width),height:e.localSize.height};return this.updateRawLocalSize(e),this}updateRawLocalSize(e){var t,i;this.rawLocalSize.width&&this.rawLocalSize.height&&!function(e,t){let i=new Er.Box2(new Er.Vector2(e.x,e.y),new Er.Vector2(e.x+e.width,e.y+e.height));return t=new Er.Box2(new Er.Vector2(t.x,t.y),new Er.Vector2(t.x+t.width,t.y+t.height)),i.containsBox(t)}(e,this.rawLocalSize)?console.warn("New map limits must be outside old limits. Skipping."):(t=e,i=this.rawLocalSize,t.x===i.x&&t.y===i.y&&t.width===i.width&&t.height===i.height||(this.localSize=this.computeLocalSize(e,this.fullSize.height/2,this.mapCutoffHeight),this.rawLocalSize={...e},this.mapBuildableSize={x:this.localSize.x,y:this.localSize.y+4,width:this.localSize.width-2,height:this.localSize.height-8},this._onLocalResize.dispatch(this)))}computeLocalSize(e,t,i){return{x:2*e.x,y:2*e.y-4,height:Math.min(2*(e.height+5)-1,2*t-2*(e.y-3)-i),width:2*e.width}}getLocalSize(){return this.localSize}getRawLocalSize(){return this.rawLocalSize}getFullSize(){return this.fullSize}getClampedFullSize(){return this.clampedFullSize}isWithinBounds(e){return Nr(this.mapBuildableSize,{x:e.dx,y:e.dy-e.z})}clampWithinBounds(e){let{x:t,y:i}=function(e,t){let i=new Er.Box2(new Er.Vector2(e.x,e.y),new Er.Vector2(e.x+e.width,e.y+e.height));return i.clampPoint(new Er.Vector2(t.x,t.y),new Er.Vector2)}(this.mapBuildableSize,{x:e.dx,y:e.dy-e.z});return i+=t%2-i%2,i>this.mapBuildableSize.y+this.mapBuildableSize.height&&(i-=2),{dx:t,dy:i}}isWithinHardBounds(e){var t=e.x/Os.LEPTONS_PER_TILE,i=(e.z??e.y)/Os.LEPTONS_PER_TILE,e=t-i+this.fullSize.width/2-1,i=t+i-this.fullSize.width/2-1;return Nr(this.clampedFullSize,{x:++e,y:++i})}}class nl{constructor(e,t,i,s,r,a,n,o=()=>!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=r,this.dirX=a,this.dirY=n,this.predicate=o,this.finished=!1,this.distance=s}getNextTile(){if(!this.finished){let t;do{let e={x:this.startTile.rx,y:this.startTile.ry};e.x+=this.distance*Math.sign(this.dirX),e.y+=this.distance*Math.sign(this.dirY);var i=this.tiles.getByMapCoords(e.x,e.y);if(i&&this.mapBounds.isWithinBounds(i)&&this.predicate(i)&&(t=i),this.maxDistance&&this.distance>=this.maxDistance)return this.finished=!0,t}while(this.distance++,!t);return t}}}(r=qh=qh||{})[r.None=0]="None",r[r.Start=1]="Start",r[r.End=2]="End";class ol{constructor(e,t,i,s,r){this.tileSets=e,this.tiles=t,this.tileOccupation=i,this.mapBounds=s,this.rules=r,this.pieces=new Set,this.piecesByTile=new Map,this.handleTileOccupationUpdate=({object:t,type:i})=>{if(t.isOverlay()&&t.isBridge()){var s=t.tile;let e=this.piecesByTile.get(s);if("added"===i){if(e)throw new Error(`A bridge piece already exists at tile (${s.rx},${s.ry})`);var r=this.findBridgeAdjacentTiles(t);e={obj:t,prev:void 0,next:void 0,headType:this.computeHead(t,r.prev,r.next)},this.piecesByTile.set(s,e),this.pieces.add(e),this.connectPiece(e,r.prev,r.next),this.updateOverlayData(e),e.prev&&this.updateOverlayData(e.prev),e.next&&this.updateOverlayData(e.next)}else{if(!e)throw new Error(`Bridge piece was alredy removed at tile (${s.rx},${s.ry})`);t=e.prev,r=e.next;this.disconnectPiece(e),this.piecesByTile.delete(s),this.pieces.delete(e),t&&this.updateOverlayData(t),r&&this.updateOverlayData(r)}}},i.onChange.subscribe(this.handleTileOccupationUpdate)}getPieceAtTile(e){return this.piecesByTile.get(e)}handlePieceHealthChange(e){this.updateOverlayData(e),e.prev&&this.updateOverlayData(e.prev),e.next&&this.updateOverlayData(e.next)}findDominoPieces(t){let i=[],s=!1,e=t.next;if(t.headType===qh.None||e)for(;e;){if(i.push(e),e.headType!==qh.None){s=!0;break}e=e.next}else s=!0;if(s){s=!1,i.length=0;let e=t.prev;if(t.headType===qh.None||e)for(;e;){if(i.push(e),e.headType!==qh.None){s=!0;break}e=e.prev}else s=!0;if(s)return[]}return i}findBridgeAdjacentTiles(e){var t=e.isXBridge(),t=new ks(Number(t),Number(!t));let i=new ks(e.tile.rx,e.tile.ry);e=i.clone().sub(t),e=this.tiles.getByMapCoords(e.x,e.y),t=i.clone().add(t);return{prev:e,next:this.tiles.getByMapCoords(t.x,t.y)}}connectPiece(e,t,i){t&&(e.prev=this.getPieceAtTile(t),e.prev&&(e.prev.next=e)),i&&(e.next=this.getPieceAtTile(i),e.next&&(e.next.prev=e))}disconnectPiece(e){e.next&&(e.next.prev=void 0,e.next=void 0),e.prev&&(e.prev.next=void 0,e.prev=void 0)}computeHead(e,t,i){var s=e.tile;if(e.isHighBridge()){s=s.z+e.tileElevation;return t?.z===s?qh.Start:i?.z===s?qh.End:qh.None}return Ha.isLowBridgeHead(e.overlayId)?Ha.isLowBridgeHeadStart(e.overlayId)?qh.Start:qh.End:qh.None}updateOverlayData(t){let i=t.obj,s=t.prev,r=t.next,a=!1;var n=i.isXBridge(),o=Ha.getOverlayBridgeType(i.overlayId);if(Ha.isLowBridgeHead(i.overlayId)){let e=0;Ha.isLowBridgeHeadStart(i.overlayId)?(e=n?20:22,r||e++):(e=n?18:24,s||e++),i.overlayId=(o===sa.Wood?Ha.minLowBridgeWoodId:Ha.minLowBridgeConcreteId)+e,i.value=e,a=!0}else{let e;var h,l=(i.healthTrait?.health??100)<=50;e=t.headType!==qh.None?t.headType===qh.Start?r?l?6:(r.obj.healthTrait?.health??100)<=50?5:0:n?8:7:s?l?6:(s.obj.healthTrait?.health??100)<=50?4:0:n?7:8:(n||(h=s,s=r,r=h),s||r?s?r?(t=(s.obj.healthTrait?.health??100)<=50,h=(r.obj.healthTrait?.health??100)<=50,l||t&&h?6:t?4:h?5:0):8:7:0),n||(e+=9),i.isHighBridge()?i.value=e:(i.overlayId=(o===sa.Wood?Ha.minLowBridgeWoodId:Ha.minLowBridgeConcreteId)+e,i.value=e,a=!0)}a&&(i.name=this.rules.getOverlayName(i.overlayId))}findClosestBridgeSpec(i){let e=new Us(this.tiles,this.mapBounds,i,{width:1,height:1},1,3,e=>{if(e.z!==i.z)return!1;let t=this.tileOccupation.getBridgeOnTile(e);return!(!t?.isLowBridge()||this.getPieceAtTile(t.tile)?.headType===qh.None)||!!this.tileSets.isHighBridgeBoundaryTile(e.tileNum)});var o=e.getNextTile();if(o){let s,t,r,a;var h=!this.tileOccupation.getBridgeOnTile(o);let e;if(h){var l=this.findHighBridgeBoundary(o);if(!l)return;s=l.tile,t=sa.Concrete,this.tileSets.getSetNum(o.tileNum)===this.tileSets.getGeneralValue("WoodBridgeSet")&&(t=sa.Wood),r=l.headType===_.TopLeft||l.headType===_.BottomRight,a=l.headType===_.TopLeft||l.headType===_.TopRight,e=l.headType}else{s=this.tileOccupation.getBridgeOnTile(o).tile;let e=this.getPieceAtTile(s);if(!e)throw new Error("Bridge head is not defined");var c=Ha.getOverlayBridgeType(e.obj.overlayId);if(c===sa.NotBridge)throw new Error("Expected a bridge type");t=c,r=e.obj.isXBridge(),a=e.headType===qh.Start}var u=Number(r)*(a?1:-1),d=Number(!r)*(a?1:-1);let n;if(h){o=new nl(this.tiles,this.mapBounds,s,1,100,u,d,e=>e.z===s.z&&this.tileSets.isHighBridgeBoundaryTile(e.tileNum)).getNextTile(),c=this.tileSets.getSetNum(s.tileNum);if(!o||this.tileSets.getSetNum(o.tileNum)!==c)return;o=this.findHighBridgeBoundary(o);if(!o)return;if(e!==this.tileSets.getOppositeHighBridgeHeadType(o.headType))return;n=o.tile}else{let t,i=1;for(var p=s.rx,g=s.ry;!t;){var m=this.tiles.getByMapCoords(p+u*i,g+d*i);if(!m)return;let e=this.getPieceAtTile(m);if(e&&e.obj.isXBridge()!==r)return;e?.headType===(a?qh.End:qh.Start)&&(t=e),i++}n=t.obj.tile}return{start:a?s:n,end:a?n:s,type:t,isHigh:h}}}findHighBridgeBoundary(r){var a,e=this.tileSets.getTile(r.tileNum),n=this.tileSets.getHighBridgeHeadType(e.index);if(void 0!==n){let i=0,s=0;switch(n){case _.TopLeft:i=1,s=0;break;case _.BottomRight:i=-1,s=0;break;case _.TopRight:i=0,s=1;break;case _.BottomLeft:i=0,s=-1;break;case _.MiddleTlBr:i=1,s=0;break;case _.MiddleTrBl:i=0,s=1;break;default:throw new Error(`Unhandled head type "${n}"`)}let e=new Us(this.tiles,this.mapBounds,r,{width:1,height:1},0,5,e=>e.terrainType===Kt.Pavement&&e.z>=r.z&&e.tileNum===r.tileNum),t=[];for(;a=e.getNextTile();)t.push(a);if(t.sort((e,t)=>100*(i?i*(t.rx-e.rx):s*(t.ry-e.ry))+(i?e.ry-t.ry:e.rx-t.rx)),t.length)return{tile:t[0],headType:n}}else console.warn(`Couldn't find a valid bridge type for index "${e.index}" @ ${r.rx},${r.ry}`)}canBeRepaired(i){let e=this.createBridgePieceTileFinder(i,e=>!(this.getPieceAtTile(e)||this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===i.start.z)),s=!1,r;for(var a=i.start.rx!==i.end.rx?na.BottomLeft:na.BottomRight;r=e.getNextTile();){s=!0;let e=this.tiles.getNeighbourTile(r,a),t=this.tiles.getNeighbourTile(e,a);if(i.isHigh){if([r,e,t].find(e=>this.tileOccupation.getGroundObjectsOnTile(e).some(e=>e.isBuilding()&&!e.rules.invisibleInGame)))return!1}else if([r,e,t].find(e=>this.tileOccupation.getGroundObjectsOnTile(e).some(e=>!(e.isUnit()||e.isSmudge()||e.isOverlay()&&e.isBridgePlaceholder()))))return!1}return s}getPieceTiles(e){var t=e.obj.tile,i=e.obj.isXBridge()?na.BottomLeft:na.BottomRight,e=this.tiles.getNeighbourTile(t,i);return[t,e,this.tiles.getNeighbourTile(e,i)]}findMapHighBridgeHeadTiles(){var e,t=this.tiles.getAllBridgeSetTiles();let i=new Set;for(e of t){var s=this.findHighBridgeBoundary(e);s&&i.add(s.tile)}return i}findBridgeSpecsForHeadTiles(e){let t=new Map;for(var i of e){i=this.findClosestBridgeSpec(i);i&&t.set(i.start.id+":"+i.end.id,i)}return[...t.values()]}findAllBridgeTiles(e){let t=[];var i,s=e.start.rx!==e.end.rx?na.BottomLeft:na.BottomRight;for(i of this.findNonBuildablePieceTiles(e)){var r=this.tiles.getNeighbourTile(i,s),a=this.tiles.getNeighbourTile(r,s);t.push(i,r,a)}return t}findBridgePieces(e){let t=this.createBridgePieceTileFinder(e,e=>!!this.getPieceAtTile(e)),i=[];for(var s;s=t.getNextTile();)i.push(this.getPieceAtTile(s));return i}findDestroyedPieceTiles(t){let e=this.createBridgePieceTileFinder(t,e=>!(this.getPieceAtTile(e)||this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===t.start.z)),i=[];for(var s;s=e.getNextTile();)i.push(s);return i}findNonBuildablePieceTiles(t){let e=this.createBridgePieceTileFinder(t,e=>!(this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===t.start.z)),i=[];for(var s;s=e.getNextTile();)i.push(s);return i}createBridgePieceTileFinder(e,t){var i=e.start.rx!==e.end.rx;return new nl(this.tiles,this.mapBounds,e.start,1,(i?e.end.rx-e.start.rx:e.end.ry-e.start.ry)-1,Number(i),Number(!i),t)}dispose(){this.pieces.forEach(e=>{e.prev=void 0,e.next=void 0}),this.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate)}}const hl=new(__webpack_require__(949).Vector2);class ll{constructor(e,t){this.box=e,this.config=t,this.parentMap=new Map,this.objects=[]}add(e,t=!0){var i=this.config.getKey(e);if(this.box.containsPoint(i)){if(!this.regions)return this.parentMap.get(e)?.remove(e),this.parentMap.set(e,this),this.objects.push({key:i,value:e}),t&&this.update(),!0;for(var s of this.regions)if(s.add(e,t))return!0}return!1}remove(t,e=!0){let i=this.parentMap.get(t);i&&(i===this?(this.parentMap.delete(t),this.objects.splice(this.objects.findIndex(e=>e.value===t),1),e&&this.parent?.update()):i.remove(t,e))}updateObject(t){let i=this.parentMap.get(t);if(i){var e=this.config.getKey(t);if(i.box.containsPoint(e))i.objects.find(e=>e.value===t).key=e;else{i.remove(t,!1);let e=i.parent;for(;e&&!e.add(t,!1);)e=e.parent}}}queryRange(e,t=[]){if(this.box.intersectsBox(e))if(this.regions)for(var i of this.regions)i.queryRange(e,t);else for(var s of this.objects)e.containsPoint(s.key)&&t.push(s.value);return t}update(){let e=0;if(this.regions){for(var t of this.regions)e+=t.update();e<=this.config.joinThreshold&&this.join()}else e=this.objects.length,e>=this.config.splitThreshold&&this.split()&&this.update();return e}split(){if(this.regions||this.config.maxDepth<=1)return!1;var t,e,i={getKey:this.config.getKey,joinThreshold:this.config.joinThreshold,splitThreshold:this.config.splitThreshold,maxDepth:this.config.maxDepth-1},s=this.generateRegions(),r=this.objects;this.objects=[],this.regions=[];for(t of s){let e=new ll(t,i);e.parentMap=this.parentMap,this.regions.push(e),e.parent=this}for(e of r)this.parentMap.delete(e.value),this.add(e.value,!1);return!0}join(){if(!this.regions)return!1;for(var e of this.regions){e.join(),e.parent=void 0;for(var t of e.objects)this.objects.push(t),this.parentMap.set(t.value,this)}return!(this.regions=void 0)}generateRegions(){let i=[this.box.clone()];var s=this.box.getCenter(hl);let r=i[0],a=r.clone();r.max.x=s.x,a.min.x=s.x,i.push(a);for(let e=0,t=i.length;e<t;e++)r=i[e],a=r.clone(),r.max.y=s.y,a.min.y=s.y,i.push(a);return i}}class cl{constructor(e){this.tiles=e,this.tileOcclusion=[];let t=this.tileOcclusion;for(var i of e.getAll())t[i.rx]=t[i.rx]||[],t[i.rx][i.ry]=new Set}addOccluder(t){let e=this.calculateTilesForGameObject(t);e.forEach(e=>this.occludeTile(e,t))}removeOccluder(t){let e=this.calculateTilesForGameObject(t);e.forEach(e=>this.unoccludeTile(e,t))}calculateTilesForGameObject(e){var t=e.art.occupyHeight,i=Math.max(0,t-2);let s=[];var r=e.getFoundation();for(let t=1;t<=i;t++)for(let e=0;e<r.width;e++)s.push(new ks(e-t,-t));for(let t=1;t<=i;t++)for(let e=1;e<r.height;e++)s.push(new ks(-t,e-t));s.push(...e.art.addOccupy);for(let{x:t,y:i}of e.art.removeOccupy){var a=s.findIndex(e=>e.x===t&&e.y===i);-1!==a&&s.splice(a,1)}var n,o,h=e.tile;let l=[];for({x:n,y:o}of s){var c=this.tiles.getByMapCoords(h.rx+n,h.ry+o);c&&l.push(c)}return l}occludeTile(e,t){this.tileOcclusion[e.rx][e.ry].add(t),e.occluded=!0}unoccludeTile(e,t){let i=this.tileOcclusion[e.rx][e.ry];i.delete(t),e.occluded=0<i.size}isTileOccluded(e){return 0<this.tileOcclusion[e.rx][e.ry].size}}class ul{static calculate(u,d){let p=new Map;u.forEach(e=>{var t=d.getSetNum(e.tileNum);p.set(e,t),d.isCLAT(t)&&(t=d.getLAT(t),p.set(e,t),e.tileNum=d.getTileNumFromSet(t))}),u.forEach(t=>{var i=p.get(t);if(d.isLAT(i)){let e=0;var s=u.getNeighbourTile(t,na.TopRight),r=u.getNeighbourTile(t,na.BottomRight),a=u.getNeighbourTile(t,na.BottomLeft),n=u.getNeighbourTile(t,na.TopLeft);s&&d.canConnectTiles(i,p.get(s))&&(e+=1),r&&d.canConnectTiles(i,p.get(r))&&(e+=2),a&&d.canConnectTiles(i,p.get(a))&&(e+=4),n&&d.canConnectTiles(i,p.get(n))&&(e+=8),0<e&&(n=d.getCLATSet(i),t.tileNum=d.getTileNumFromSet(n,e))}else if(i===d.getGeneralValue("RampBase")&&!(t.rampType<1||4<t.terrainType)){let e=-1;var o=u.getNeighbourTile(t,na.TopRight),h=u.getNeighbourTile(t,na.BottomRight),l=u.getNeighbourTile(t,na.BottomLeft),c=u.getNeighbourTile(t,na.TopLeft);switch(t.rampType){case 1:c&&0===c.rampType&&e++,h&&0===h.rampType&&(e+=2);break;case 2:o&&0===o.rampType&&e++,l&&0===l.rampType&&(e+=2);break;case 3:h&&0===h.rampType&&e++,c&&0===c.rampType&&(e+=2);break;case 4:l&&0===l.rampType&&e++,o&&0===o.rampType&&(e+=2)}-1!==e&&(t.tileNum=d.getTileNumFromSet(d.getGeneralValue("RampSmooth"),3*(t.rampType-1)+e))}})}}class dl{constructor(e,t,i,s){this.mapFile=e,this.tiles=new $a(this.mapFile.tiles,t,i.general,s),this.mapBounds=(new al).fromMapFile(this.mapFile,this.tiles),this.tileOccupation=new So(this.tiles),this.tileOcclusion=new cl(this.tiles),this.terrain=new rl(this.tiles,this.mapFile.theaterType,this.mapBounds,this.tileOccupation,i),this.bridges=new ol(t,this.tiles,this.tileOccupation,this.mapBounds,i);let r=this.mapFile.tags;for(let t of this.mapFile.cellTags){let e=this.tiles.getByMapCoords(t.coords.x,t.coords.y);e&&(e.tag=r.find(e=>e.id===t.tagId))}s=this.tiles.getMapSize(),i=Math.max(s.width,s.height)/5;this.technosByTile=new ll(new jn(new ks(0,0),new ks(s.width,s.height)),{getKey:e=>{e=e.isBuilding()?e.centerTile:e.tile;return new ks(e.rx,e.ry)},maxDepth:this.computeQuadDepth(i),splitThreshold:10,joinThreshold:5}),this.mapFile.theaterType!==C.Snow&&ul.calculate(this.tiles,t)}get startingLocations(){return this.mapFile.startingLocations}computeQuadDepth(e){if(e<=1)return 1;let t=0;for(;1<=e/2;)e/=2,t++;return t+(1<e?1:0)}getLighting(){return this.mapFile.lighting}getIonLighting(){return this.mapFile.ionLighting}getTheaterType(){return this.mapFile.theaterType}getTags(){return this.mapFile.tags}getTriggers(){return this.mapFile.triggers}getCellTags(){return this.mapFile.cellTags}getVariables(){return this.mapFile.variables}getWaypoint(t){return this.mapFile.waypoints.find(e=>e.number===t)}getTileAtWaypoint(e){e=this.getWaypoint(e);if(e){e=this.tiles.getByMapCoords(e.rx,e.ry);if(e)return e}}isWithinBounds(e){return this.mapBounds.isWithinBounds(e)}clampWithinBounds(e){var t=this.mapBounds.clampWithinBounds(e);let i=this.tiles.getByDisplayCoords(t.dx,t.dy);if(i&&this.mapBounds.isWithinBounds(i)){let e=i,t=i.z;for(;0<=t&&e&&this.mapBounds.isWithinBounds(e);)i=e,e=this.tiles.getByDisplayCoords(e.dx,e.dy+2),t-=2}else{let e=0;for(;!i||!this.mapBounds.isWithinBounds(i);){if(30<e)throw new Error("Exceeded max elevation while trying to clamp tile to map bounds");i=this.tiles.getByDisplayCoords(t.dx,t.dy+e),e+=2}}return i}isWithinHardBounds(e){return this.mapBounds.isWithinHardBounds(e)}getInitialMapObjects(){return{terrains:this.mapFile.terrains,overlays:this.mapFile.overlays,smudges:this.mapFile.smudges,technos:[...this.mapFile.structures,...this.mapFile.infantries,...this.mapFile.vehicles,...this.mapFile.aircrafts]}}getObjectsOnTile(e){return this.tileOccupation.getObjectsOnTile(e)}getGroundObjectsOnTile(e){return this.tileOccupation.getGroundObjectsOnTile(e)}getTileZone(e,t=!1){return this.tileOccupation.getTileZone(e,t)}dispose(){this.terrain.dispose(),this.bridges.dispose()}}class pl{constructor(e,t){this.first=e,this.second=t}has(e){return this.first===e||this.second===e}equals(e){return this.first===e.first&&this.second===e.second||this.first===e.second&&this.second===e.first}}(r=Xh=Xh||{})[r.Requested=0]="Requested",r[r.Formed=1]="Formed";class gl{constructor(e){this.playerList=e,this.alliances=[]}findByPlayers(e,t){let i=new pl(e,t);return this.alliances.find(e=>e.players.equals(i))}filterByPlayer(t){return this.alliances.filter(e=>e.players.first===t||e.players.second===t)}request(e,t){if(!this.canRequestAlliance(t))throw new Error(`Player ${t.name} is not a human combatant.`);if(this.canFormAlliance(e,t)){if(this.findByPlayers(e,t))throw new Error("Can't request alliance because an alliance is already pending or formed between "+`${e.name} and ${t.name}.`);return this.setAlliance(e,t,Xh.Requested)}}cancelRequest(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==Xh.Requested)throw new Error(`There is no pending alliance request for player ${t.name} from player ${e.name}`);if(i.players.first!==e)throw new Error(`Can't cancel request initiated by the other player (${t.name})`);this.alliances.splice(this.alliances.indexOf(i),1)}acceptRequest(t,i){if(this.canFormAlliance(t,i)){let e=this.findByPlayers(t,i);if(!e||e.status!==Xh.Requested)throw new Error(`There is no pending alliance request for player ${i.name} from player ${t.name}`);if(e.players.first!==t)throw new Error(`Can't accept own alliance request for player ${i.name}`);e.status=Xh.Formed}}setAlliance(e,t,i){if(!this.canFormAlliance(e,t))throw new Error(`Can't form alliance between players "${e.name}" and "${t.name}"`);var s;if(s=this.findByPlayers(e,t))throw new Error(`An alliance already exists between players ${e.name} and ${t.name}`);return s={players:new pl(e,t),status:i},this.alliances.push(s),s}breakAlliance(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==Xh.Formed)throw new Error(`There is no alliance between player ${e.name} and player ${t.name}`);this.alliances.splice(this.alliances.indexOf(i),1)}areAllied(e,t){t=this.findByPlayers(e,t);return!!t&&t.status===Xh.Formed}getAllies(t){return this.filterByPlayer(t).filter(e=>e.status===Xh.Formed).map(e=>e.players.first===t?e.players.second:e.players.first)}haveSharedIntel(e,t){return e.isObserver||t.isObserver||e===t||this.areAllied(e,t)}canRequestAlliance(e){return e.isCombatant()&&!e.isAi}canFormAlliance(t,i){let e=this.getHostilePlayers();if(0===e.filter(e=>e.has(t)&&!e.has(i)).length)return!1;if(0===e.filter(e=>e.has(i)&&!e.has(t)).length)return!1;let s=new pl(t,i);return!!e.filter(e=>!e.equals(s)).length}getHostilePlayers(){var i,s=this.playerList.getCombatants();let r=[];for(let t=0;t<s.length;t++)for(let e=t+1;e<s.length;e++)this.getAllies(s[t]).includes(s[e])||(i=new pl(s[t],s[e]),r.push(i));return r}getHash(){return G(this.alliances.map(e=>[this.playerList.getPlayerNumber(e.players.first),this.playerList.getPlayerNumber(e.players.second),e.status]).flat())}debugGetState(){return this.alliances.map(e=>({first:e.players.first,second:e.players.second,status:e.status}))}}class ml{constructor(){this.players=[]}addPlayer(e){this.players.push(e)}getPlayerAt(e){if(e>=this.players.length)throw new RangeError(`Player #${e} out of bounds`);return this.players[e]}getPlayerByName(t){var e=this.players.find(e=>e.name===t);if(!e)throw new Error(`Player with name "${t}" not found`);return e}getPlayerNumber(e){var t=this.players.indexOf(e);if(-1===t)throw new Error(`Player ${e.name} not found`);return t}getCombatants(){return this.players.filter(e=>e.isCombatant())}getNonNeutral(){return this.players.filter(e=>!e.isNeutral)}getCivilian(){return this.players.find(e=>e.country?.side===Zt.Civilian)}getAll(){return this.players}}(r=Zh=Zh||{})[r.None=0]="None",r[r.Hover=1]="Hover",r[r.Selected=2]="Selected",r[r.SelectedHover=3]="SelectedHover";class fl{constructor(e){this.selectionLevel=Zh.None,e.isBuilding()&&e.rules.wall?this.maxSelectionLevel=Zh.None:this.maxSelectionLevel=e.rules.selectable?Zh.Selected|Zh.Hover:Zh.Hover}getSelectionLevel(){return this.selectionLevel}setSelectionLevel(e){this.selectionLevel=Math.min(this.maxSelectionLevel,e)}setHover(e){this.setSelectionLevel(e?this.selectionLevel|Zh.Hover:this.selectionLevel&~Zh.Hover)}setSelected(e){this.setSelectionLevel(e?this.selectionLevel|Zh.Selected:this.selectionLevel&~Zh.Selected)}isHovered(){return this.selectionLevel>>Zh.Hover&1}isSelected(){return this.selectionLevel>=Zh.Selected}getControlGroupNumber(){return this.controlGroupNumber}setControlGroupNumber(e){this.controlGroupNumber=e}}class yl{constructor(){this.selectedUnits=new Set,this.selectionModelsByUnit=new Map,this.groups=new Map,this.hashNeedsUpdate=!0}getOrCreateSelectionModel(e){let t=this.selectionModelsByUnit.get(e);return t||(t=new fl(e),this.selectionModelsByUnit.set(e,t)),t}deselectAll(){this.selectedUnits.forEach(e=>this.selectionModelsByUnit.get(e)?.setSelected(!1)),this.selectedUnits.clear(),this.hashNeedsUpdate=!0}addToSelection(e){this.selectedUnits.add(e),this.getOrCreateSelectionModel(e).setSelected(!0),this.hashNeedsUpdate=!0}removeFromSelection(e){e.forEach(e=>{this.selectedUnits.delete(e),this.getOrCreateSelectionModel(e).setSelected(!1)}),this.hashNeedsUpdate=!0}getSelectedUnits(){return[...this.selectedUnits].filter(e=>!e.isDestroyed&&!e.isCrashing&&!e.isDisposed&&e.isSpawned)}isSelected(e){return this.selectedUnits.has(e)}cleanupUnit(e){this.selectionModelsByUnit.delete(e),this.selectedUnits.delete(e),this.unassignUnitsFromGroup([e]),this.hashNeedsUpdate=!0}updateHash(){this.hash=G([...this.selectedUnits].map(e=>e.id))}getHash(){return this.hashNeedsUpdate&&(this.updateHash(),this.hashNeedsUpdate=!1),this.hash}createGroup(e){this.addUnitsToGroup(e,this.getSelectedUnits())}addUnitsToGroup(e,t,i=!0){this.unassignUnitsFromGroup(t);let s=this.groups.get(e);s||(s=new Set,this.groups.set(e,s)),i&&([...s.values()].forEach(e=>this.selectionModelsByUnit.get(e)?.setControlGroupNumber(void 0)),s.clear());for(var r of t)s.add(r),this.getOrCreateSelectionModel(r).setControlGroupNumber(e)}addGroupToSelection(e){if(this.groups.has(e))for(var t of[...this.groups.get(e)])this.addToSelection(t)}selectGroup(e){this.deselectAll(),this.addGroupToSelection(e)}getGroupUnits(e){return[...this.groups.get(e)??[]]}unassignUnitsFromGroup(e){for(var t of this.groups.values())for(var i of e)t.delete(i)}}class wl{constructor(e){this._onChange=new ao,this.value=e}get value(){return this._value}set value(e){var t=e!==this._value;this._value=e,t&&this._onChange.dispatch(this,e)}get onChange(){return this._onChange.asEvent()}}class Tl{constructor(e,t=void 0,i=0,s=new W(255,0,0)){this.name=e,this.country=t,this.startLocation=i,this.color=s,this.isAi=!1,this.defeated=!1,this.resigned=!1,this.dropped=!1,this.objectsByType=new Map,this.objectsById=new Map,this.traits=new Aa,this._credits=0,this.score=0,this.unitsBuiltByType=new Map,this.unitsKilledByType=new Map,this.unitsLostByType=new Map,this.buildingsCaptured=0,this.cratesPickedUp=0,this.cheerCooldownTicks=0,this.isObserver=!t,this.isNeutral=!!t&&!t.isPlayable()}get credits(){return this._credits}set credits(e){if(e<0)throw new RangeError("Can't set credits to a negative value");this._credits=e}getOrCreateObjectsForType(e){let t=this.objectsByType.get(e);return t||(t=new Set,this.objectsByType.set(e,t)),t}addOwnedObject(e){let t=this.getOrCreateObjectsForType(e.type);t.add(e),(e.owner=this).objectsById.set(e.id,e)}removeOwnedObject(e){let t=this.objectsByType.get(e.type);if(!t||!t.has(e))throw new Error(`GameObject ${e.name} does not belong to player ${this.name}`);t.delete(e),this.objectsById.delete(e.id)}getOwnedObjectById(e){return this.objectsById.get(e)}getOwnedObjectsByType(e,t=!1){let i=[];return i=[...this.objectsByType.get(e)||new Set],t||(i=i.filter(e=>!e.limboData)),i}getOwnedObjects(e=!1){let t=[];return[...this.objectsByType.values()].forEach(e=>{e.forEach(e=>t.push(e))}),e||(t=t.filter(e=>!e.limboData)),t}removeAllOwnedObjects(){this.objectsByType.forEach(e=>e.clear()),this.objectsById.clear()}get buildings(){return this.getOrCreateObjectsForType(xt.Building)}addUnitsBuilt(e,t){this.unitsBuiltByType.set(e,(this.unitsBuiltByType.get(e)??0)+t)}getUnitsBuilt(e){return void 0!==e?this.unitsBuiltByType.get(e)??0:[...this.unitsBuiltByType.values()].reduce((e,t)=>e+t,0)}addUnitsKilled(e,t){this.unitsKilledByType.set(e,(this.unitsKilledByType.get(e)??0)+t)}getUnitsKilled(e){return void 0!==e?this.unitsKilledByType.get(e)??0:[...this.unitsKilledByType.values()].reduce((e,t)=>e+t,0)}addUnitsLost(e,t){this.unitsLostByType.set(e,(this.unitsLostByType.get(e)??0)+t)}getUnitsLost(e){return void 0!==e?this.unitsLostByType.get(e)??0:[...this.unitsLostByType.values()].reduce((e,t)=>e+t,0)}isCombatant(){return!this.isNeutral&&!this.isObserver&&!this.defeated}canProduceVeteran(e){if(!this.production||!this.country)throw new Error("Non-combatants can't produce units");var t=this.production.getQueueTypeForObject(e),t=this.production.getFactoryTypeForQueueType(t);return this.production.hasVeteranType(t)||this.country.hasVeteranUnit(e.type,e.name)}getHash(){return G([this.credits,...this.traits.getAll().map(e=>e.getHash?.()??0)])}debugGetState(){return{name:this.name,credits:this.credits,traits:this.traits.getAll().reduce((e,t)=>{var i=t.debugGetState?.();return void 0!==i&&(e[t.constructor.name]=i),e},{})}}dispose(){this.traits.dispose(),this.production?.dispose()}}class bl{constructor(){this.disabled=!0,this.activeEvents=[]}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}}const vl=(new Map).set("POWER",Yt.Power).set("FACTORY",Yt.Factory).set("BARRACKS",Yt.Barracks).set("RADAR",Yt.Radar).set("TECH",Yt.Tech).set("PROC",Yt.Proc);class Sl{constructor(e,t,i,s,r){this.player=e,this.maxTechLevel=t,this.gameOpts=i,this.rules=s,this.allAvailableObjects=r,this.buildSpeedModifier=1,this.queues=new Map,this._onQueueUpdate=new ao,this.primaryFactories=new Map,this.factoryCounts=new Map,this.veteranTypes=new Set,this.stolenTech=new Set}static factory(e,t,i,s){let r=new Sl(e,t.mpDialogSettings.techLevel,i,t,s);t=t.general.maximumQueuedObjects+1;return r.addQueue(fn.Structures,new no(fn.Structures,1,1)),r.addQueue(fn.Armory,new no(fn.Armory,1,1)),r.addQueue(fn.Infantry,new no(fn.Infantry,t,t)),r.addQueue(fn.Vehicles,new no(fn.Vehicles,t,t)),r.addQueue(fn.Ships,new no(fn.Ships,t,t)),r.addQueue(fn.Aircrafts,new no(fn.Aircrafts,0,t)),r}get onQueueUpdate(){return this._onQueueUpdate.asEvent()}addQueue(e,t){this.queues.set(e,t),t.onUpdate.subscribe(()=>this._onQueueUpdate.dispatch(this,t))}getQueue(e){var t=this.queues.get(e);if(!t)throw new Error(`No queue found with type ${fn[e]}`);return t}getAllQueues(){return[...this.queues.values()]}getQueueTypeForObject(e){if(e.type===xt.Building)return e.buildCat===Ji.Combat?fn.Armory:fn.Structures;if(e.type===xt.Infantry)return fn.Infantry;if(e.type===xt.Vehicle)return e.naval?fn.Ships:fn.Vehicles;if(e.type===xt.Aircraft)return fn.Aircrafts;throw new Error(`Unsupported object type ${xt[e.type]}`)}getQueueForObject(e){return this.getQueue(this.getQueueTypeForObject(e))}getQueueTypeForFactory(e){if(e===es.InfantryType)return fn.Infantry;if(e===es.UnitType)return fn.Vehicles;if(e===es.AircraftType)return fn.Aircrafts;if(e===es.NavalUnitType)return fn.Ships;throw new Error(`Unsupported factory type ${es[e]}`)}getFactoryTypeForQueueType(e){if(e===fn.Structures||e===fn.Armory)return es.BuildingType;if(e===fn.Infantry)return es.InfantryType;if(e===fn.Vehicles)return es.UnitType;if(e===fn.Aircrafts)return es.AircraftType;if(e===fn.Ships)return es.NavalUnitType;throw new Error(`Unsupported queue type ${fn[e]}`)}getQueueForFactory(e){return this.getQueue(this.getQueueTypeForFactory(e))}isAvailableForProduction(e){return e.isAvailableTo(this.player.country)&&-1!==e.techLevel&&e.techLevel<=this.maxTechLevel&&!(0===e.buildLimit&&!this.player.isAi)&&!(e.superWeapon&&this.rules.getSuperWeapon(e.superWeapon).disableableFromShell&&!this.gameOpts.superWeapons)&&this.hasFactoryFor(e)&&this.meetsPrerequisites(e)&&this.meetsStolenTech(e)}getAvailableObjects(){return this.allAvailableObjects.filter(e=>this.isAvailableForProduction(e))}hasFactoryFor(i){if(i.owner.length){let t=this.getFactoryTypeFor(i);return!![...this.player.buildings].find(e=>e.factoryTrait?.type===t&&(t!==es.UnitType||e.rules.naval===i.naval)&&!!e.rules.owner.find(e=>i.owner.includes(e)))}return!0}meetsStolenTech(e){return e.requiresStolenAlliedTech?this.stolenTech.has(Zt.GDI):!e.requiresStolenSovietTech||this.stolenTech.has(Zt.Nod)}getFactoryTypeFor(e){return e.type===xt.Building?es.BuildingType:e.type===xt.Infantry?es.InfantryType:e.type===xt.Aircraft?es.AircraftType:e.naval?es.NavalUnitType:es.UnitType}meetsPrerequisites(e){let t=[...this.player.buildings].map(e=>e.name);var i;for(i of e.prerequisite)if(i=i.toUpperCase(),vl.has(i)){var s=vl.get(i);if(void 0===s)throw new Error(`Unknown prereqName ${i}`);var r,a=this.rules.general.prereqCategories.get(s);if(void 0===a)throw new Error(`Missing prerequisite category ${s} in rules`);let e=!1;for(r of a)if(-1!==t.indexOf(r)){e=!0;break}if(!e)return!1}else if(-1===t.indexOf(i))return!1;return!0}getPrimaryFactory(e){return this.primaryFactories.get(e)}setPrimaryFactory(e){e.rules.factory&&this.primaryFactories.set(e.rules.factory,e)}isPrimaryFactory(e){return this.getPrimaryFactory(e.rules.factory)===e}incrementFactoryCount(e){this.factoryCounts.set(e,(this.factoryCounts.get(e)??0)+1)}decrementFactoryCount(e){if(!this.factoryCounts.get(e))throw new Error(`Can't decrement factory count ${es[e]}. Already 0`);this.factoryCounts.set(e,this.factoryCounts.get(e)-1)}getFactoryCount(e){return this.factoryCounts.get(e)??0}crownPrimaryFactoryHeir(t){var e=[...this.player.buildings].find(e=>e.rules.factory===t);e?this.primaryFactories.set(t,e):this.primaryFactories.delete(t)}hasAnyFactory(){return 0<this.primaryFactories.size}addVeteranType(e){this.veteranTypes.add(e)}hasVeteranType(e){return this.veteranTypes.has(e)}addStolenTech(e){this.stolenTech.add(e)}dispose(){this.queues.clear(),this.player=void 0}}class kl{constructor(){this.superWeapons=new Map}getAll(){return[...this.superWeapons.values()]}add(e){this.superWeapons.set(e.name,e)}has(e){return this.superWeapons.has(e)}get(e){return this.superWeapons.get(e)}remove(e){this.superWeapons.delete(e)}}class Ol{constructor(){this.objects=new Set}add(e){this.objects.add(e)}delete(e){this.objects.delete(e)}has(e){return this.objects.has(e)}dispose(){this.objects.clear()}}class _l{constructor(e,t,i){this.rules=e,this.gameOpts=t,this.allAvailableObjects=i}createCombatant(e,t,i,s,r,a){let n=new Tl(e,t,i,s);return n.isAi=r,n.aiDifficulty=a,n.powerTrait=new so(n),n.traits.add(n.powerTrait),n.radarTrait=new bl,n.traits.add(n.radarTrait),n.superWeaponsTrait=new kl,n.traits.add(n.superWeaponsTrait),n.production=Sl.factory(n,this.rules,this.gameOpts,this.allAvailableObjects),n.sharedDetectDisguiseTrait=new Ol,n}createObserver(e,t){let i=new Tl(e,void 0,void 0,t.colors.get("LightGrey"));return i.radarTrait=new bl,i.traits.add(i.radarTrait),i.radarTrait.setDisabled(!1),i}createNeutral(e,t){var i=[...e.countryRules.values()].find(e=>e.side===Zt.Civilian);if(!i)throw new Error("Missing neutral country. No country found in rules with Civilian side");i=new Zn(i);let s=new Tl(t,i,void 0,e.colors.get("LightGrey"));return s.powerTrait=new so(s),s.traits.add(s.powerTrait),s}}(Qh=Qh||{}).onSpawn=Symbol(),(Yh=Yh||{}).onUnspawn=Symbol(),(Kh=Kh||{}).onChange=Symbol();class Il{[Qh.onSpawn](e,t){e.isTechno()&&e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"add",t)}[Yh.onUnspawn](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"remove",t)}[Mn.onChange](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"update",t)}[Kh.onChange](e,t,i){e.rules.power&&!e.warpedOutTrait.isActive()&&(this.isCapturablePower(e,t)||t.powerTrait?.updateFrom(e,"remove",i),this.isCapturablePower(e,e.owner)||e.owner.powerTrait?.updateFrom(e,"add",i))}[Ps.onChange](e,t,i){e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,i?"remove":"add",t)}[Es.onTick](e){for(var t of e.getCombatants())t.powerTrait.updateBlackout(e)}isCapturablePower(e,t){return 0<e.rules.power&&t.isNeutral&&e.rules.needsEngineer}}class Cl{constructor(e){this.target=e,this.type=ss.BuildingSell}}class Al{constructor(e,t){this.game=e,this.generalRules=t}sell(t){if(!t.rules.unsellable){let e=this.computeRefundValue(t);e&&(t.rules.wall&&(e=0),t.traits.filter(Tn).forEach(e=>{e[Tn.onSell](t,this.game)}),t.isBuilding()?this.game.getConstructionWorker(t.owner).unplace(t,()=>this.afterObjectUnspawned(t,e)):(this.game.unspawnObject(t),this.afterObjectUnspawned(t,e)))}}afterObjectUnspawned(e,t){e.owner.credits+=t,e.isBuilding()&&this.game.events.dispatch(new Cl(e)),e.dispose()}computeRefundValue(e){let t=0;return 0<e.rules.soylent?t=e.rules.soylent:e.rules.cost&&(t=e.purchaseValue,e.owner.isAi||(t=Math.floor(t*this.generalRules.refundPercent))),t}computePurchaseValue(e,t){return e.cost}dispose(){this.game=void 0}}class Bl{constructor(e,t){this.target=e,this.radarEnabled=t,this.type=ss.RadarOnOff}}class xl{constructor(e,t,i){this.target=e,this.radarEventType=t,this.tile=i,this.type=ss.RadarEvent}}class El{constructor(){this.activeLightningStrikes=new Map}[Qh.onSpawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Yh.onUnspawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Ds.onPowerLow](e,t){this.updateRadarForPlayer(e,t)}[Ds.onPowerRestore](e,t){this.updateRadarForPlayer(e,t)}[Ds.onPowerChange](){}[Kh.onChange](e,t,i){e.rules.radar&&(this.updateRadarForPlayer(t,i),this.updateRadarForPlayer(e.owner,i))}[Ps.onChange](e,t){e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Rs.onActivate](e,t,i){if(e===is.LightningStorm){this.activeLightningStrikes.set(t,(this.activeLightningStrikes.get(t)??0)+1);for(var s of i.getCombatants())s===t||i.alliances.areAllied(s,t)||this.updateRadarForPlayer(s,i)}}[ca.onDeactivate](e,t,i){if(e===is.LightningStorm){e=(this.activeLightningStrikes.get(t)??0)-1;if(0<e?this.activeLightningStrikes.set(t,e):this.activeLightningStrikes.delete(t),e<=0)for(var s of i.getCombatants())this.updateRadarForPlayer(s,i)}}updateRadarForPlayer(i,s){var e,t;i.radarTrait&&(e=i.radarTrait?.isDisabled(),t=![...i.buildings].find(e=>e.rules.radar&&!e.warpedOutTrait.isActive())||i.powerTrait.level===mn.Low||[...this.activeLightningStrikes.entries()].some(([e,t])=>t&&e!==i&&!s.alliances.areAllied(e,i)),i.radarTrait.setDisabled(t),e!==t&&s.events.dispatch(new Bl(i,!t)))}[ra.onAttack](e,t,i){e.isTechno()&&(!e.isBuilding()||e.rules.canBeOccupied||e.rules.needsEngineer?e.isVehicle()&&e.harvesterTrait&&this.addEventForPlayer(Qt.HarvesterUnderAttack,e.owner,e.tile,i):this.addEventForPlayer(Qt.BaseUnderAttack,e.owner,e.tile,i))}addEventForPlayer(s,e,r,a){let n=e.radarTrait;if(n){let t=a.rules.general.radar;n.activeEvents=n.activeEvents.filter(e=>a.currentTick-e.startTick<t.getEventDuration(e.type));let i=new As(a.map.tileOccupation);!!n.activeEvents.find(e=>e.type===s&&i.isInTileRange(r,e.tile,0,t.getEventSuppresionDistance(e.type)))||(n.activeEvents.push({startTick:a.currentTick,tile:r,type:s}),a.events.dispatch(new xl(e,s,r)))}}}class Pl{constructor(e){this.target=e,this.type=ss.InsufficientFunds}}class Nl{constructor(e,t){this.rules=e,this.speedCheat=t,this.availableObjectRules=new Set;t=60*e.general.buildSpeed*js.BASE_TICKS_PER_SECOND;this.baseBuildSpeed=1/(t/1e3),[...e.buildingRules.values(),...e.infantryRules.values(),...e.vehicleRules.values(),...e.aircraftRules.values()].forEach(e=>{e.owner.length&&this.availableObjectRules.add(e)})}[Es.onTick](e){for(var t of e.getCombatants())for(var i of t.production.getAllQueues())this.tickQueue(i,t,e)}[Qh.onSpawn](e,t){var i;e.isBuilding()&&e.owner.production?(i=e.rules.factory)&&(e.owner.production.getPrimaryFactory(i)||e.owner.production.setPrimaryFactory(e),e.owner.production.incrementFactoryCount(i),i===es.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t)):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[Yh.onUnspawn](e,t){var i;e.isBuilding()&&e.owner.production?(this.ensurePrerequisites(e.owner),(i=e.rules.factory)&&(e.owner.production.getPrimaryFactory(i)===e&&e.owner.production.crownPrimaryFactoryHeir(i),e.owner.production.decrementFactoryCount(i),i===es.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t))):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[Kh.onChange](e,t,i){var s;e.isBuilding()?(this.ensurePrerequisites(t),(s=e.rules.factory)&&(t.production?.getPrimaryFactory(s)===e&&t.production.crownPrimaryFactoryHeir(s),e.owner.production&&!e.owner.production.getPrimaryFactory(s)&&e.owner.production.setPrimaryFactory(e),t.production?.decrementFactoryCount(s),e.owner.production?.incrementFactoryCount(s),s===es.AircraftType&&(this.updateAircraftQueueMaxSize(e.owner,i),this.updateAircraftQueueMaxSize(t,i)))):e.isAircraft()&&this.rules.general.padAircraft.includes(e.name)&&(this.updateAircraftQueueMaxSize(e.owner,i),this.updateAircraftQueueMaxSize(t,i))}[Ds.onPowerLow](e){e.production&&(e.production.buildSpeedModifier=this.computeLowPowerBuildSpeedModifier(e.powerTrait.power,e.powerTrait.drain))}[Ds.onPowerRestore](e){e.production&&(e.production.buildSpeedModifier=1)}[Ds.onPowerChange](e){e.powerTrait?.level===mn.Low&&e.production&&(e.production.buildSpeedModifier=this.computeLowPowerBuildSpeedModifier(e.powerTrait.power,e.powerTrait.drain))}computeLowPowerBuildSpeedModifier(e,t){e=1-Math.min(1,e/t),t=this.rules.general;return z(1-.3*t.lowPowerPenaltyModifier*e/.15,t.minLowPowerProductionSpeed,t.maxLowPowerProductionSpeed)}updateAircraftQueueMaxSize(i,s){i.production&&s.afterTick(()=>{var e=[...i.buildings].filter(e=>e.helipadTrait).reduce((e,t)=>e+t.dockTrait.numberOfDocks,0),t=i.getOwnedObjectsByType(xt.Aircraft,!0).filter(e=>s.rules.general.padAircraft.includes(e.name)).length;i.production.getQueueForFactory(es.AircraftType).maxSize=Math.max(0,e-t)})}tickQueue(i,s,r){if(i.status===yn.Active){let e=!1,t=i.getFirst();var a,n=s.production.getFactoryTypeForQueueType(i.type),o=s.production.getFactoryCount(n),h=s.production.buildSpeedModifier,n=1/Yi.pow(this.rules.general.multipleFactory,o-1),o=t.rules.wall?1/this.rules.general.wallBuildSpeedCoefficient:1,n=this.baseBuildSpeed*h*n*o,o=t.creditsEach,n=o&&!this.speedCheat.value?(l=o/n,c=54,Math.floor(l/c)*c):54,n=Math.max(54,n),l=s.credits,c=t.creditsEach-t.creditsSpent,c=Math.min(s.credits,o/n+t.creditsSpentLeftover,c);0<c?(a=Math.floor(c),t.creditsSpentLeftover=c-a,a&&(t.creditsSpent+=a,t.progress=t.creditsSpent/t.creditsEach,s.credits-=a,e=!0)):t.creditsEach||(a=t.progress*n,t.progress=Math.min(1,(1+a)/n),e=!0),e&&1===t.progress&&(i.status=yn.Ready),0<l&&!s.credits&&r.events.dispatch(new Pl(s)),e&&i.notifyUpdated()}}ensurePrerequisites(e){if(e.production)for(var t of e.production.getAllQueues()){var i;for(i of t.getAll().map(e=>({rules:e.rules,quantity:e.quantity,creditsSpent:e.creditsSpent})))e.production.isAvailableForProduction(i.rules)||(t.pop(i.rules,i.quantity),e.credits+=i.creditsSpent)}}getAvailableObjects(){return[...this.availableObjectRules]}}(Jh=Jh||{}).onChange=Symbol();class Ml{constructor(e,t){this.map=e,this.alliances=t,this.shroudByPlayer=new Map,this.revealedToAll=new Set,this.gapGenerators=new Set,this.handleTileOccupationUpdate=({object:e,type:t})=>{if("removed"!==t&&e.isTechno()){var i,t=e.owner;for(i of[t,...this.alliances.getAllies(t)])this.shroudByPlayer.get(i)?.revealFrom(e)}}}getPlayerShroud(e){return this.shroudByPlayer.get(e)}init(t){t.map.tileOccupation.onChange.subscribe(this.handleTileOccupationUpdate);let i=(new Wo).fromTiles(this.map.tiles);for(var s of t.getCombatants()){let e=i.clone();this.shroudByPlayer.set(s,e),this.revealObjects(e,s,t),e.update()}}[$r.onElevationChange](e,t,i){if(Math.floor(e.tileElevation)!==Math.floor(i)){var s,i=e.owner;for(s of[i,...this.alliances.getAllies(i)])this.shroudByPlayer.get(s)?.revealFrom(e)}}[Es.onTick](e){for(var[t,i]of this.shroudByPlayer)t.defeated&&!t.isObserver?this.shroudByPlayer.delete(t):i.update()}[Kh.onChange](e,t,i){if(e.isBuilding()&&e.rules.spySat&&(this.revealMap(e.owner,i),t.getOwnedObjectsByType(xt.Building).find(e=>e.rules.spySat)||this.resetShroud(t,i)),e.isSpawned)for(var s of[e.owner,...i.alliances.getAllies(e.owner)])this.shroudByPlayer.get(s)?.revealFrom(e)}[Jh.onChange](t,e,i){if(e){let e=this.getPlayerShroud(t.players.first);var s,r,t=i.alliances.getAllies(t.players.first).map(e=>this.getPlayerShroud(e)).filter(ja);for(s of t)e.merge(s);e.invalidateFull();for(r of t)r.copy(e),r.invalidateFull()}}[Qh.onSpawn](e,t){if(e.isBuilding()){if(e.rules.spySat&&this.revealMap(e.owner,t),e.rules.revealToAll){this.revealedToAll.add(e);for(var i of t.getCombatants())i===e.owner||t.alliances.areAllied(e.owner,i)||(this.shroudByPlayer.get(i)?.revealObject(e),t.traits.get(El).addEventForPlayer(Qt.EnemyObjectSensed,i,e.centerTile,t))}e.gapGeneratorTrait&&this.gapGenerators.add(e)}}[Yh.onUnspawn](e,t){e.isBuilding()&&(e.rules.spySat&&(e.owner.getOwnedObjectsByType(xt.Building).find(e=>e.rules.spySat)||this.resetShroud(e.owner,t)),e.rules.revealToAll&&this.revealedToAll.delete(e),e.gapGeneratorTrait&&this.gapGenerators.delete(e))}[Ds.onPowerLow](e,t){this.updateGaps(t,e)}[Ds.onPowerRestore](e,t){this.updateGaps(t,e)}[Ds.onPowerChange](e,t){}revealMap(e,t){this.shroudByPlayer.get(e)?.revealAll(),this.markOwnGapTiles(t,e),this.updateGaps(t)}resetShroud(e,t){let i=this.shroudByPlayer.get(e);i&&(i.reset(),this.markOwnGapTiles(t,e),this.revealObjects(i,e,t))}revealObjects(t,e,i){var s;for(s of[...e.getOwnedObjects(),...i.alliances.getAllies(e).map(e=>e.getOwnedObjects()).flat()])t.revealFrom(s);this.revealedToAll.forEach(e=>t.revealObject(e))}updateGaps(e,t){for(var i of this.gapGenerators)t&&i.owner!==t||i.gapGeneratorTrait.update(i,e)}markOwnGapTiles(e,t){for(var i of this.gapGenerators)i.owner!==t&&!e.alliances.areAllied(i.owner,t)||this.getPlayerShroud(t)?.toggleFlagsAround(i.tile,i.gapGeneratorTrait.radiusTiles,In.Darken,!0)}dispose(){this.map.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate)}}class Dl extends Gs{onTick(e){return!(e.buildStatus!==Cn.BuildDown&&(e.buildStatus=Cn.BuildDown,!e.rules.wall))||(this.children.push(new ga(.035)),!1)}}class Rl{constructor(){this.disposables=new Set}add(...e){e.map(e=>this.disposables.add("function"==typeof e?{dispose:e}:e))}remove(...e){e.map(e=>this.disposables.delete(e))}dispose(){this.disposables.forEach(e=>{"function"==typeof e?e():e.dispose?e.dispose():e.destroy()}),this.disposables.clear()}}class Ll{constructor(e,t,i,s,r){this.player=e,this.rules=t,this.art=i,this.map=s,this.game=r,this.adjacencyMaps=new Map,this.disposables=new Rl;let a=({object:e})=>{e.isBuilding()&&this.adjacencyMaps.clear()};this.map.tileOccupation.onChange.subscribe(a),this.disposables.add(()=>this.map.tileOccupation.onChange.unsubscribe(a)),this.disposables.add(this.game.events.subscribe(ss.AllianceChange,()=>this.adjacencyMaps.clear()),this.game.events.subscribe(ss.ObjectOwnerChange,e=>{e.target.isBuilding()&&this.adjacencyMaps.clear()}),this.game.events.subscribe(ss.ObjectDestroy,e=>{e.target.isBuilding()&&e.target.rules.leaveRubble&&this.adjacencyMaps.clear()}))}getAdjacentRect(e,t,i){return{x:e.rx-i,y:e.ry-i,width:t.width+2*i,height:t.height+2*i}}getAdjacencyMap(e){var t;let i=[];for(t of[...this.player.buildings,...this.game.gameOpts.buildOffAlly?this.game.alliances.getAllies(this.player).map(e=>[...e.buildings].filter(e=>e.rules.eligibileForAllyBuilding)).flat():[]])t.rules.baseNormal&&i.push(this.getAdjacentRect(t.tile,t.art.foundation,e));return i}meetsAdjacency(e,t){let i=this.adjacencyMaps.get(t);i||(i=this.getAdjacencyMap(t),this.adjacencyMaps.set(t,i));for(var s of i)if(r=e,s=s,r.x<=s.x+s.width&&s.x<=r.x+r.width&&r.y<=s.y+s.height&&s.y<=r.y+r.height)return!0;var r;return!1}getPlacementPreview(e,t,i={}){var{normalizedTile:s=!1,ignoreObjects:r,ignoreAdjacent:i=!1}=i,a=this.rules.getBuilding(e),e=this.art.getObject(e,xt.Building);let n=[];var o=e.foundation,h=s?t:this.normalizePlacementTileCoords(e,t);let l=!0;t={x:h.rx,y:h.ry,width:o.width,height:o.height};a.constructionYard||i||this.meetsAdjacency(t,a.adjacent)||(l=!1);for(let t=0;t<o.width;t++)for(let e=0;e<o.height;e++){var c={x:h.rx+t,y:h.ry+e},u=this.map.tiles.getByMapCoords(c.x,c.y);u&&n.push({rx:c.x,ry:c.y,buildable:l&&this.isTileBuildable(u,a,r)})}if(a.wall&&n[0].buildable){let e=this.getWallConnectingTiles(h,a);e.forEach(e=>{n.push({rx:e.rx,ry:e.ry,buildable:!0})})}return n}canPlaceAt(e,t,i={}){var{normalizedTile:s=!1,ignoreObjects:r,ignoreAdjacent:i=!1}=i,a=this.rules.getBuilding(e),e=this.art.getObject(e,xt.Building),n=e.foundation,o=s?t:this.normalizePlacementTileCoords(e,t),t={x:o.rx,y:o.ry,width:n.width,height:n.height};if(!a.constructionYard&&!i&&!this.meetsAdjacency(t,a.adjacent))return!1;for(let t=0;t<n.width;t++)for(let e=0;e<n.height;e++){var h={x:o.rx+t,y:o.ry+e},h=this.map.tiles.getByMapCoords(h.x,h.y);if(!h||!this.isTileBuildable(h,a,r))return!1}return!0}placeAt(e,t,i=!1){let s=[],r=this.rules.getBuilding(e),a=i?t:this.normalizePlacementTile(e,t);if(r.wall){let t=[[a,r]],e=this.getWallConnectingTiles(a,r);e.forEach(e=>{e!==a&&t.push([e,r])});for(var n of t)s.push(this.executePlacement(n[0],n[1]));e.forEach(e=>{e=this.map.getObjectsOnTile(e).find(e=>e.isBuilding()&&e.name===r.name&&e.owner===this.player);this.connectWall(e)})}else{var o,t=this.executePlacement(a,r);s.push(t);for(o of this.map.tileOccupation.calculateTilesForGameObject(a,t)){var h=this.map.getObjectsOnTile(o).find(e=>e.isSmudge());h&&this.game.unspawnObject(h)}}return s}normalizePlacementTileCoords(e,t){e=e.foundationCenter;return{rx:t.rx-e.x,ry:t.ry-e.y}}normalizePlacementTile(e,t){e=this.art.getObject(e,xt.Building),e=this.normalizePlacementTileCoords(e,t),t=this.map.tiles.getByMapCoords(e.rx,e.ry);if(!t)throw new Error(`Can't build outside map (${e.rx}, ${e.ry})`);return t}unplace(e,t){e.unitOrderTrait.cancelAllTasks(),e.unitOrderTrait.addTasks(new Ua(new Dl,new ma(()=>{this.game.unspawnObject(e),e.rules.wall&&this.updateAdjacentWalls(e),t()})).setCancellable(!1)),e.unitOrderTrait[Fr.onTick](e,this.game)}executePlacement(e,t){let i=this.game.createObject(xt.Building,t.name);return this.game.changeObjectOwner(i,this.player),i.purchaseValue=this.game.sellTrait.computePurchaseValue(t,this.player),this.game.spawnObject(i,e),i}getWallConnectingTiles(i,s){var r,a=s.guardRange+1;let n=[];for(r of[[0,1],[0,-1],[1,0],[-1,0]]){let t=[];for(let e=0;e<a;++e){var o={x:i.rx+r[0]*e,y:i.ry+r[1]*e},o=this.map.tiles.getByMapCoords(o.x,o.y);if(!o)break;if(this.map.getObjectsOnTile(o).find(e=>e.isBuilding()&&e.name===s.name&&e.owner===this.player)){n=n.concat(t);break}if(!this.isTileBuildable(o,s))break;t.push(o)}}return n}getAdjacentBuildingData(e,t){var i;let s=[];for(i of[[0,1],[0,-1],[1,0],[-1,0]]){var r={x:e.rx+i[0],y:e.ry+i[1]},a=this.map.tiles.getByMapCoords(r.x,r.y);a&&((r=this.map.getObjectsOnTile(a).find(e=>e.isBuilding()&&e.name===t&&e.owner===this.player))&&s.push({direction:i,tile:a,building:r}))}return s}updateAdjacentWalls(t){let e=new wo(this.map.tiles,this.map.mapBounds,t.tile,1,1);for(e.diagonal=!1;i=e.getNextTile();){var i=this.map.getObjectsOnTile(i).find(e=>e.isBuilding()&&e.name===t.rules.name&&e.owner===this.player);i&&this.connectWall(i)}}connectWall(e){let t=this.getAdjacentBuildingData(e.tile,e.name);this.updateWallType(e,t.map(e=>e.direction)),t.forEach(e=>{let t=this.getAdjacentBuildingData(e.tile,e.building.name);this.updateWallType(e.building,t.map(e=>e.direction))})}updateWallType(e,t){e.wallType=[0,0,0,0];for(var i of t)0===i[0]&&-1===i[1]&&(e.wallType[0]=1),1===i[0]&&0===i[1]&&(e.wallType[1]=1),0===i[0]&&1===i[1]&&(e.wallType[2]=1),-1===i[0]&&0===i[1]&&(e.wallType[3]=1)}isTileBuildable(e,t,i){return!!this.map.isWithinBounds(e)&&(!this.game.mapShroudTrait.getPlayerShroud(this.player)?.isShrouded(e)&&(!this.map.getGroundObjectsOnTile(e).some(e=>!(i?.includes(e)||e.isBuilding()&&e.rules.invisibleInGame||e.isSmudge()))&&(t.waterBound?0<this.rules.getLandRules(e.landType).getSpeedModifier(ei.Float):0===e.rampType&&this.rules.getLandRules(e.landType).buildable)))}dispose(){this.disposables.dispose()}}class Fl{static generate(e,t,i,s){var r,a=i.reduce((e,t)=>e+t.cost,0)/i.length*e;let n=[],o=a,h=(i=i.filter(e=>e.isAvailableTo(s)&&e.hasOwner(s))).filter(e=>t.includes(e.name));for(r of h){if(o<=0)break;var l=2/3/h.length,l=Math.ceil(l*a/r.cost);o-=l*r.cost,n.push({name:r.name,type:xt.Vehicle,count:l})}var c,i=i.filter(e=>!h.includes(e)),u=o/i.length;for(c of i){if(o<=0)break;var d=Math.ceil(u/c.cost);o-=d*c.cost,n.push({name:c.name,type:xt.Infantry,count:d})}return n}}class jl{constructor(){this.dispatcher=new ao,this.dispatchersByType=new Map}dispatch(e){this.dispatcher.dispatch(void 0,e),this.dispatchersByType.get(e.type)?.dispatch(void 0,e)}subscribe(e,t){let i=void 0,s;return s="function"==typeof e?e:(i=e,t),void 0===i?(this.dispatcher.subscribe(s),()=>this.unsubscribe(s)):this.subscribeType(i,s)}unsubscribe(e,t){let i=void 0,s;s="function"==typeof e?e:(i=e,t),void 0===i?this.dispatcher.unsubscribe(s):this.unsubscribeType(i,s)}subscribeType(e,t){let i=this.dispatchersByType.get(e);return i||(i=new ao,this.dispatchersByType.set(e,i)),i.subscribe(t),()=>this.unsubscribeType(e,t)}unsubscribeType(e,t){this.dispatchersByType.get(e)?.unsubscribe(t)}}class Ul{constructor(e,t,i){this.target=e,this.attackerInfo=t,this.incidental=i,this.type=ss.ObjectDestroy}}class Wl{constructor(e){this.target=e,this.type=ss.PlayerDefeated}}(el=el||{}).onDestroy=Symbol();class zl{constructor(e,t){this.target=e,this.prevOwner=t,this.type=ss.ObjectOwnerChange}}class Vl{constructor(e){this.gameObject=e,this.type=ss.ObjectUnspawn}}class Hl{constructor(e){this.gameObject=e,this.type=ss.ObjectSpawn}}(r=tl=tl||{})[r.Requested=0]="Requested",r[r.Formed=1]="Formed",r[r.Broken=2]="Broken";class Gl{constructor(e,t,i){this.alliance=e,this.changeType=t,this.from=i,this.type=ss.AllianceChange}}var $l,ql,Xl,Zl,Ql,Yl,Kl,Jl,ec,tc,ic,r=__webpack_require__(948),sc=__webpack_require__.n(r);class rc{constructor(e){this.prng=new(sc())(e)}static factory(e,t){t=Number.isNaN(Number(e))?he.calculateCrc(R(e)):Number(e+""+t);return new rc(t)}generateRandomInt(e,t){var i=this.prng.random();return this.lastRandom=i,Math.round(i*(t-e))+e}generateRandom(){var e=this.prng.random();return this.lastRandom=e}getLastRandom(){return this.lastRandom}}class ac{constructor(e,t){this.action=e,this.trigger=t}getDebugName(){return`${this.action.triggerId}[${this.action.index}] (${this.trigger.name}).`}}class nc extends ac{constructor(e,t,i){super(e,t),this.oneTimeOnly=i,this.superWeaponIdx=Number(e.params[1])}execute(i){var s=[...i.rules.superWeaponRules.values()].find(e=>e.index===this.superWeaponIdx);if(s){let t=i.getAllPlayers().find(e=>e.country?.name===this.trigger.houseName);if(t&&t.superWeaponsTrait&&!t.superWeaponsTrait.has(s.name)){let e=i.createSuperWeapon(s.name,t,this.oneTimeOnly);e.isGift=!0,t.superWeaponsTrait.add(e)}}else console.warn(`No superweapon found with index "${this.superWeaponIdx}". `+`Skipping action ${this.getDebugName()}.`)}}class oc extends ac{constructor(e,t,i){super(e,t),this.damage=i}execute(t){var e=Number(this.action.params[1]),i=t.map.getTileAtWaypoint(e);if(i){var s=t.rules.getWarhead(Ya.HE_WARHEAD_NAME);let e=new Ya(s);var r=t.map.tileOccupation.getBridgeOnTile(i),a=r?.tileElevation??0,s=t.map.getTileZone(i);e.detonate(t,this.damage,i,a,Os.tile3dToWorld(i.rx+.5,i.ry+.5,i.z+a),s,r?aa.OnBridge:aa.None,t.createTarget(r,i),void 0,!1,!1,void 0)}else console.warn(`No valid location found for waypoint ${e}. `+`Skipping action ${this.getDebugName()}.`)}}class hc extends ac{execute(e){let i=e.getAllPlayers().find(e=>e.country?.name===this.trigger.houseName);if(i){let t=Number(this.action.params[1]);var s=e.getAllPlayers().find(e=>e.country?.id===t);if(s)for(var r of i.getOwnedObjects(!0))e.changeObjectOwner(r,s)}}}class lc extends ac{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}execute(e,t){var i=e.getAllPlayers().find(e=>e.country?.id===this.houseId);if(i)for(var s of t)s instanceof Ba&&s.isSpawned&&e.changeObjectOwner(s,i)}}class cc extends Gs{constructor(){super(),this.executed=!1,this.cancellable=!1}onTick(e){return this.executed?(e.stance=Ls.None,!0):!e.isInfantry()||!e.art.sequences.has(pn.Cheer)||(e.stance!==Ls.None&&e.stance!==Ls.Guard||(e.stance=Ls.Cheer,this.children.push(new ga(1/60).setCancellable(!1)),!(this.executed=!0)))}}class uc extends ac{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}execute(e){let t=e.getAllPlayers().filter(e=>e.country&&!e.defeated);if(-1!==this.houseId&&(t=t.filter(e=>e.country?.id===this.houseId)),t.length)for(var i of t[0].getOwnedObjectsByType(xt.Infantry))i.unitOrderTrait.isIdle()&&i.unitOrderTrait.addTask(new cc)}}const dc=new Map([[0,e=>{e=e.rules.powerups.powerups.find(e=>e.type===xs.Money);return e?{...e,data:"5000"}:void 0}],[1,xs.Unit],[2,xs.HealBase],[3,xs.Cloak],[4,xs.Explosion],[5,xs.Napalm],[6,xs.Money],[7,xs.Darkness],[8,xs.Reveal],[9,xs.Armor],[10,xs.Speed],[11,xs.Firepower],[12,xs.ICBM],[13,void 0],[14,xs.Veteran],[15,void 0],[16,xs.Gas],[17,xs.Tiberium],[18,void 0]]);class pc extends ac{execute(e){var t=Number(this.action.params[1]),i=this.action.params[6],s=e.map.getTileAtWaypoint(i);if(s)if(dc.has(t)){const r=dc.get(t);t="function"==typeof r?r(e):e.rules.powerups.powerups.find(e=>e.type===r);t&&e.crateGeneratorTrait.spawnCrateAt(s,t,e)}else e.crateGeneratorTrait.spawnRandomCrateAt(s,e);else console.warn(`No valid location found for waypoint ${i}. `+`Skipping action ${this.getDebugName()}.`)}}class gc extends ac{execute(e){var t=Number(this.action.params[1])-1;if(Object.values(Qt).includes(t)){var i=this.action.params[6],s=e.map.getTileAtWaypoint(i);if(s)for(var r of e.getCombatants())e.traits.get(El).addEventForPlayer(t,r,s,e);else console.warn(`No valid location found for waypoint ${i}. `+`Skipping action ${this.getDebugName()}.`)}else console.warn(`Unknown radar event type "${1+t}". Skipping action ${this.getDebugName()}.`)}}class mc extends ac{execute(e,t){for(var i of t)i instanceof Ba&&i.isSpawned&&e.destroyObject(i)}}class fc extends ac{execute(e){var t=this.action.params[1];e.triggers.destroyTag(t)}}class yc extends ac{execute(e){var t=this.action.params[1];e.triggers.destroyTrigger(t)}}class wc extends ac{execute(s){var r=Number(this.action.params[1]),e=this.action.params[6],a=s.map.getTileAtWaypoint(e);if(a){let t;try{t=s.rules.getWeaponByInternalId(r)}catch(e){if(e instanceof RangeError)return void console.warn(`Weapon with internal ID "${r}" not found. `+`Skipping action ${this.getDebugName()}.`);throw e}let e;try{e=s.rules.getWarhead(t.warhead)}catch(e){return void console.warn(`Warhead "${t.warhead}" not found. `+`Skipping action ${this.getDebugName()}.`)}let i=new Ya(e);var n=s.map.tileOccupation.getBridgeOnTile(a),o=n?.tileElevation??0,r=s.map.getTileZone(a);i.detonate(s,t.damage,a,o,Os.tile3dToWorld(a.rx+.5,a.ry+.5,a.z+o),r,n?aa.OnBridge:aa.None,s.createTarget(n,a),void 0,!1,!1,void 0)}else console.warn(`No valid location found for waypoint ${e}. `+`Skipping action ${this.getDebugName()}.`)}}class Tc extends ac{execute(e,t){for(var i of t)i instanceof Ba&&i.isBuilding()&&i.garrisonTrait&&!i.isDestroyed&&i.garrisonTrait.evacuate(e)}}class bc extends ac{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}execute(e){var t=e.getAllPlayers().find(e=>e.country?.id===this.houseId);if(t)for(var i of t.buildings)e.sellTrait.sell(i)}}class vc extends ac{execute(e){e.end()}}class Sc extends ac{execute(e){var t=this.action.params[1];e.triggers.forceTrigger(t,e)}}class kc extends ac{constructor(e,t,i){super(e,t),this.value=i,this.variableIdx=Number(e.params[1])}execute(e){e.triggers.toggleGlobalVariable(this.variableIdx,this.value)}}class Oc extends ac{execute(e){var t,i,s=this.action.params[6],r=e.map.getTileAtWaypoint(s);r?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===is.IronCurtain))&&e.traits.get(ln).activateEffect(i,t,e,r,void 0,!0):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class _c extends ac{execute(e){var t,i,s=this.action.params[6],r=e.map.getTileAtWaypoint(s);r?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===is.LightningStorm))&&e.traits.get(ln).activateEffect(i,t,e,r,void 0,!0):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class Ic extends ac{constructor(e,t,i){super(e,t),this.value=i,this.variableIdx=Number(e.params[1])}execute(e){e.triggers.toggleLocalVariable(this.variableIdx,this.value)}}class Cc extends ac{execute(){}}class Ac extends ac{execute(e){var t,i,s=this.action.params[6],r=e.map.getTileAtWaypoint(s);r?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===is.MultiMissile))&&e.traits.get(ln).activateEffect(i,t,e,r,void 0,!0):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class Bc{constructor(e,t){this.name=e,this.tile=t,this.type=ss.TriggerAnim}}class xc extends ac{execute(e){var t,i=this.action,s=Number(i.params[1]),r=e.rules.getAnimationName(s);void 0!==r?(t=i.params[6],(i=e.map.getTileAtWaypoint(t))?e.events.dispatch(new Bc(r,i)):console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)):console.warn(`No animation found for index "${s}". Skipping action ${this.getDebugName()}`)}}class Ec{constructor(e,t){this.soundId=e,this.tile=t,this.type=ss.TriggerSoundFx}}class Pc extends ac{execute(e){var t=this.action,i=t.params[1],s=t.params[6],t=e.map.getTileAtWaypoint(s);t?e.events.dispatch(new Ec(i,t)):console.warn(`No valid location found for waypoint ${s}. `+`Skipping action ${this.getDebugName()}.`)}}class Nc extends ac{execute(e){e.events.dispatch(new Ec(this.action.params[1]))}}class Mc{constructor(e){this.soundId=e,this.type=ss.TriggerEva}}class Dc extends ac{execute(e){e.events.dispatch(new Mc(this.action.params[1]))}}class Rc extends ac{execute(e){for(var t of e.getCombatants())e.mapShroudTrait.resetShroud(t,e)}}class Lc extends ac{execute(e){var[t,i,s,r]=this.action.params.slice(2,6).map(Number);e.map.mapBounds.updateRawLocalSize({x:t,y:i,width:s,height:r})}}class Fc extends ac{execute(e){var t=Number(this.action.params[1]),i=e.map.getTileAtWaypoint(t);if(i)for(var s of e.getCombatants())e.mapShroudTrait.getPlayerShroud(s)?.revealAround(i,e.rules.general.revealTriggerRadius);else console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class jc extends ac{execute(e){for(var t of e.getCombatants())e.mapShroudTrait.revealMap(t,e)}}class Uc extends ac{execute(e,t){for(var i of t)i instanceof Ba&&i.isBuilding()&&!i.isDestroyed&&e.sellTrait.sell(i)}}class Wc extends ac{execute(e){var t=Number(this.action.params[1])/100;e.mapLightingTrait.setTargetAmbientIntensity(t)}}function zc(e){let t=new DataView(new ArrayBuffer(4));return t.setInt32(0,e),t.getFloat32(0)}class Vc extends ac{execute(e){var t=zc(Number(this.action.params[1]));e.mapLightingTrait.setAmbientChangeRate(t)}}class Hc extends ac{execute(e){var t=zc(Number(this.action.params[1]));e.mapLightingTrait.setAmbientChangeStep(t)}}class Gc{constructor(e){this.tile=e,this.type=ss.TriggerStopSoundFx}}class $c extends ac{execute(e){var t=this.action.params[6],i=e.map.getTileAtWaypoint(t);i?e.events.dispatch(new Gc(i)):console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class qc{constructor(e){this.label=e,this.type=ss.TriggerText}}class Xc extends ac{execute(e){e.events.dispatch(new qc(this.action.params[1]))}}class Zc extends ac{execute(e){e.countdownTimer.addSeconds(Number(this.action.params[1]))}}class Qc extends ac{execute(e){e.countdownTimer.setSeconds(Number(this.action.params[1]))}}class Yc extends ac{execute(e){e.countdownTimer.addSeconds(-Number(this.action.params[1]))}}class Kc extends ac{execute(e){e.countdownTimer.start()}}class Jc extends ac{execute(e){e.countdownTimer.stop()}}class eu extends ac{execute(e){e.countdownTimer.text=this.action.params[1]}}class tu extends ac{constructor(e,t,i){super(e,t),this.triggerEnable=i}execute(e){var t=this.action.params[1];e.triggers.setTriggerEnabled(t,this.triggerEnable)}}class iu extends ac{constructor(e,t,i){super(e,t),this.turnOn=i}execute(e,t){for(var i of t)i instanceof Ba&&i.isBuilding()&&i.poweredTrait?.setTurnedOn(this.turnOn)}}class su extends ac{execute(e){var t=Number(this.action.params[1]),i=e.map.getTileAtWaypoint(t);if(i)for(var s of e.getCombatants())e.mapShroudTrait.getPlayerShroud(s)?.unrevealAround(i,e.rules.general.revealTriggerRadius);else console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class ru{create(e,t){switch(e.type){case Xt.NoAction:return new Cc(e,t);case Xt.FireSale:return new bc(e,t);case Xt.TextTrigger:return new Xc(e,t);case Xt.DestroyTrigger:return new yc(e,t);case Xt.ChangeHouse:return new lc(e,t);case Xt.RevealMap:return new jc(e,t);case Xt.RevealAroundWaypoint:return new Fc(e,t);case Xt.PlaySoundFx:return new Nc(e,t);case Xt.PlaySpeech:return new Dc(e,t);case Xt.ForceTrigger:return new Sc(e,t);case Xt.TimerStart:return new Kc(e,t);case Xt.TimerStop:return new Jc(e,t);case Xt.TimerExtend:return new Zc(e,t);case Xt.TimerShorten:return new Yc(e,t);case Xt.TimerSet:return new Qc(e,t);case Xt.GlobalSet:return new kc(e,t,!0);case Xt.GlobalClear:return new kc(e,t,!1);case Xt.DestroyObject:return new mc(e,t);case Xt.AddOneTimeSuperWeapon:return new nc(e,t,!0);case Xt.AddRepeatingSuperWeapon:return new nc(e,t,!1);case Xt.AllChangeHouse:return new hc(e,t);case Xt.ResizePlayerView:return new Lc(e,t);case Xt.PlayAnimAt:return new xc(e,t);case Xt.DetonateWarhead:return new wc(e,t);case Xt.ReshroudMap:return new Rc(e,t);case Xt.EnableTrigger:return new tu(e,t,!0);case Xt.DisableTrigger:return new tu(e,t,!1);case Xt.CreateRadarEvent:return new gc(e,t);case Xt.LocalSet:return new Ic(e,t,!0);case Xt.LocalClear:return new Ic(e,t,!1);case Xt.SellBuilding:return new Uc(e,t);case Xt.TurnOffBuilding:return new iu(e,t,!1);case Xt.TurnOnBuilding:return new iu(e,t,!0);case Xt.ApplyOneHundredDamage:return new oc(e,t,100);case Xt.ForceEnd:return new vc(e,t);case Xt.DestroyTag:return new fc(e,t);case Xt.SetAmbientStep:return new Hc(e,t);case Xt.SetAmbientRate:return new Vc(e,t);case Xt.SetAmbientLight:return new Wc(e,t);case Xt.NukeStrike:return new Ac(e,t);case Xt.PlaySoundFxAt:return new Pc(e,t);case Xt.UnrevealAroundWaypoint:return new su(e,t);case Xt.LightningStrike:return new _c(e,t);case Xt.TimerText:return new eu(e,t);case Xt.CreateCrate:return new pc(e,t);case Xt.IronCurtainAt:return new Oc(e,t);case Xt.EvictOccupiers:return new Tc(e,t);case Xt.Cheer:return new uc(e,t);case Xt.StopSoundsAt:return new $c(e,t);default:throw new Error(`Unhandled action type "${Xt[e.type]}"`)}}}class au{constructor(e,t){this.event=e,this.trigger=t,this.blocking=!1,this.targets=[]}init(e){e=e.getAllPlayers().find(e=>e.country?.name===this.trigger.houseName);e&&(this.player=e)}setTargets(e){this.targets=e}reset(){}getDebugName(){return`${this.event.triggerId}[${this.event.eventIndex}] (${this.trigger.name}).`}}class nu extends au{constructor(e,t,i){super(e,t),this.type=i,this.threshold=Number(e.params[1])/100}check(e){var t=this.previousAmbient,e=e.mapLightingTrait.getAmbient().ambient;return this.previousAmbient=e,void 0!==t&&t!==e&&("above"===this.type?e>=this.threshold&&t<this.threshold:e<=this.threshold&&t>this.threshold)}}class ou extends au{check(e){return!0}}class hu extends au{check(s,e){return e.filter(e=>{if(e.type!==ss.ObjectAttacked)return!1;let t=e.target;if(!t.isTechno()||!this.targets.includes(t))return!1;var i=e.attacker?.player;return(!i||!s.alliances.areAllied(i,t.owner)&&i!==t.owner)&&!e.incidental}).map(e=>e.target)}}class lu extends au{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==ss.ObjectAttacked)return!1;let t=e.target;if(!t.isTechno()||!this.targets.includes(t))return!1;e=e.attacker?.player;return e&&(-1===this.houseId||e?.country?.id===this.houseId)}).map(e=>e.target)}}class cu extends au{constructor(e,t,i=!1){super(e,t),this.negate=i,this.objectIndex=Number(e.params[1])}check(){if(!this.player)return!1;for(var e of this.player.buildings)if(e.rules.index===this.objectIndex)return!this.negate;return this.negate}}class uu extends au{constructor(e,t,i){super(e,t),this.objectType=i,this.objectIndex=Number(e.params[1])}check(e,t){return t.some(e=>e.type===ss.ObjectSpawn&&e.gameObject.type===this.objectType&&e.gameObject.rules.index===this.objectIndex)}}class du extends au{constructor(e,t){super(e,t)}init(e){super.init(e);var t=Number(this.event.params[1]);this.waypointTile=e.map.getTileAtWaypoint(t),this.waypointTile||console.warn(`No valid location found for waypoint ${t}. `+`Skipping event ${this.getDebugName()}.`)}check(t,e){if(!this.waypointTile||!this.player)return!1;for(var i of e)if(i.type===ss.EnterTile&&i.source.owner===this.player){let e=new As(t.map.tileOccupation);if(e.tileDistance(i.target,this.waypointTile)<2)return!0}return!1}}class pu extends au{constructor(e,t){super(e,t),this.threshold=Number(e.params[1])}check(e,t){return!!this.player&&this.player.credits<this.threshold}}class gu extends au{constructor(e,t){super(e,t),this.threshold=Number(e.params[1])}check(e,t){return!!this.player&&this.player.credits>this.threshold}}class mu extends au{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(t=>t.type===ss.EnterTile&&t.source.zone!==vs.Air&&this.targets.some(e=>e.ry===t.target.ry)&&(-1===this.houseId||t.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class fu extends au{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(t=>t.type===ss.EnterTile&&t.source.zone!==vs.Air&&this.targets.some(e=>e.rx===t.target.rx)&&(-1===this.houseId||t.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class yu extends au{constructor(e,t){super(e,t),this.allDestroyed=!1,this.houseId=Number(e.params[1])}check(e,t){return!!this.allDestroyed||!!t.some(e=>{if(e.type!==ss.ObjectDestroy)return!1;let t=e.target;return!(!t.isBuilding()||t.owner.country?.id!==this.houseId)&&!t.owner.buildings.size})&&(this.allDestroyed=!0)}}class wu extends au{constructor(e,t){super(e,t),this.allDestroyed=!1,this.houseId=Number(e.params[1])}check(e,t){return!!this.allDestroyed||!!t.some(e=>{if(e.type!==ss.ObjectDestroy)return!1;let t=e.target;return!(!t.isTechno()||t.owner.country?.id!==this.houseId)&&!t.owner.getOwnedObjects(!0).length})&&(this.allDestroyed=!0)}}class Tu extends au{constructor(e,t){super(e,t),this.allDestroyed=!1,this.houseId=Number(e.params[1])}check(e,t){return!!this.allDestroyed||!!t.some(e=>{if(e.type!==ss.ObjectDestroy)return!1;let t=e.target;return!(!t.isUnit()||t.owner.country?.id!==this.houseId)&&!this.hasUnitsLeft(t.owner)})&&(this.allDestroyed=!0)}hasUnitsLeft(e){var t;for(t of[xt.Aircraft,xt.Vehicle,xt.Infantry])if(e.getOwnedObjectsByType(t,!0).length)return!0;return!1}}class bu extends au{constructor(e,t){super(e,t),this.allDestroyed=!1,this.houseId=Number(e.params[1])}check(e,t){return!!this.allDestroyed||!!t.some(e=>{if(e.type!==ss.ObjectDestroy)return!1;let t=e.target;return!(!t.isUnit()||t.owner.country?.id!==this.houseId)&&!this.hasLandUnitsLeft(t.owner)})&&(this.allDestroyed=!0)}hasLandUnitsLeft(e){var t;for(t of[xt.Vehicle,xt.Infantry])if(e.getOwnedObjectsByType(t,!0).filter(e=>!e.rules.naval).length)return!0;return!1}}class vu extends au{constructor(e,t){super(e,t),this.allDestroyed=!1,this.houseId=Number(e.params[1])}check(e,t){return!!this.allDestroyed||!!t.some(e=>{if(e.type!==ss.ObjectDestroy)return!1;let t=e.target;return!(!t.isVehicle()||t.owner.country?.id!==this.houseId)&&!t.owner.getOwnedObjectsByType(xt.Vehicle,!0).filter(e=>e.rules.naval).length})&&(this.allDestroyed=!0)}}class Su extends au{check(s,e){return e.filter(e=>{if(e.type!==ss.ObjectDestroy)return!1;let t=e.target;if(!t.isOverlay()||!t.isBridge())return!1;e=t.bridgeTrait?.bridgeSpec;if(!e)return!1;let i=s.map.bridges.findAllBridgeTiles(e);return i.find(e=>this.targets.includes(e))}).map(e=>e.target.tile)}}class ku extends au{constructor(e,t){super(e,t),this.count=0,this.threshold=Number(e.params[1])}check(e,t){if(!this.player)return!1;if(this.count>=this.threshold)return!0;for(var i of t)if(i.type===ss.ObjectDestroy){let e=i.target;e.isBuilding()&&e.owner.country?.id===this.houseId&&this.count++}return this.count>=this.threshold}}class Ou extends au{check(s,e){return e.filter(e=>{if(e.type!==ss.ObjectDestroy)return!1;let t=e.target;if(!t.isTechno()||!this.targets.includes(t))return!1;var i=e.attackerInfo?.player;return(!i||!s.alliances.areAllied(i,t.owner)&&i!==t.owner)&&!e.incidental}).map(e=>e.target)}}class _u extends au{check(e,t){return t.filter(e=>{if(e.type!==ss.ObjectDestroy&&e.type!==ss.ObjectOwnerChange)return!1;let t=e.target;return!(!t.isTechno()||!this.targets.includes(t))}).map(e=>e.target)}}class Iu extends au{constructor(){super(...arguments),this.eventsFilter=[ss.ObjectDestroy,ss.ObjectOwnerChange,ss.BuildingInfiltration]}check(e,t){return t.filter(e=>{if(!this.eventsFilter.includes(e.type))return!1;let t=e.target;return!(!t.isTechno()||!this.targets.includes(t))}).map(e=>e.target)}}class Cu extends au{constructor(e,t){super(e,t),this.count=0,this.threshold=Number(e.params[1])}check(e,t){if(!this.player)return!1;if(this.count>=this.threshold)return!0;for(var i of t)if(i.type===ss.ObjectDestroy){let e=i.target;e.isUnit()&&e.owner.country?.id===this.houseId&&this.count++}return this.count>=this.threshold}}class Au extends au{constructor(e,t){super(e,t),this.timerTicks=Number(this.event.params[1])*js.BASE_TICKS_PER_SECOND}check(e){return e.currentTick>this.timerTicks}}class Bu extends au{constructor(e,t){super(e,t),this.elapsedTicks=0,this.timerTicks=Number(this.event.params[1])*js.BASE_TICKS_PER_SECOND}check(e){return this.elapsedTicks++>this.timerTicks}reset(){this.elapsedTicks=0}}class xu extends au{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(e=>(e.type===ss.EnterObject||e.type===ss.EnterTile)&&this.targets.includes(e.target)&&(e.type!==ss.EnterTile||e.source.zone!==vs.Air)&&(-1===this.houseId||e.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class Eu extends au{constructor(e,t,i){super(e,t),this.value=i,this.blocking=!0,this.variableIdx=Number(e.params[1])}check(e){return e.triggers.getGlobalVariable(this.variableIdx)===this.value}}class Pu extends au{constructor(e,t,i){super(e,t),this.threshold=i}check(e,t){return t.filter(e=>{if(e.type!==ss.HealthChange)return!1;let t=e.target;return!(!t.isTechno()||!this.targets.includes(t))&&(e.currentHealth<this.threshold&&e.prevHealth>this.threshold)}).map(e=>e.target)}}class Nu extends au{constructor(e,t,i){super(e,t),this.threshold=i}check(e,t){return t.filter(e=>{if(e.type!==ss.InflictDamage)return!1;let t=e.target;return!(!t.isTechno()||!this.targets.includes(t))&&(e.currentHealth<this.threshold&&e.prevHealth>this.threshold)}).map(e=>e.target)}}class Mu extends au{constructor(e,t,i){super(e,t),this.value=i,this.blocking=!0,this.variableIdx=Number(e.params[1])}check(e){return e.triggers.getLocalVariable(this.variableIdx)===this.value}}class Du extends au{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}init(e){super.init(e),this.targetPlayer=e.getAllPlayers().find(e=>e.country?.id===this.houseId)}check(){return!!this.targetPlayer?.powerTrait?.isLowPower()}}class Ru extends au{check(e){return!1}}class Lu extends au{check(){if(!this.player)return!1;for(var e of this.player.buildings)if(e.factoryTrait)return!1;return!0}}class Fu extends au{check(e,t){return t.some(e=>e.type===ss.CratePickup)}}class ju extends au{check(e,t){return t.filter(e=>e.type===ss.CratePickup&&this.targets.includes(e.source)).map(e=>e.source)}}class Uu extends au{constructor(){super(...arguments),this.elapsedTicks=0}check(e){return this.timerTicks??(this.timerTicks=Math.floor(e.generateRandomInt(50,150)/100*Number(this.event.params[1]))*js.BASE_TICKS_PER_SECOND),this.elapsedTicks++>this.timerTicks}reset(){this.timerTicks=void 0,this.elapsedTicks=0}}class Wu extends au{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(e=>e.type===ss.BuildingInfiltration&&this.targets.includes(e.target)&&(-1===this.houseId||e.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class zu extends au{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==ss.BuildingInfiltration)return!1;var t=e.target;return!!this.targets.includes(t)&&(-1===this.houseId||e.source.disguiseTrait?.getDisguise()?.owner?.country?.id===this.houseId)}).map(e=>e.target)}}class Vu extends au{constructor(e,t){super(e,t),this.infantryIdx=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==ss.BuildingInfiltration)return!1;var t=e.target;return!!this.targets.includes(t)&&e.source.disguiseTrait?.getDisguise()?.rules.index===this.infantryIdx}).map(e=>e.target)}}class Hu extends au{check(e,t){return t.some(e=>e.type===ss.TimerExpire)}}class Gu{create(e,t){switch(e.type){case qt.NoEvent:return new Ru(e,t);case qt.EnteredBy:return new xu(e,t);case qt.SpiedBy:return new Wu(e,t);case qt.AttackedByAny:return new hu(e,t);case qt.DestroyedByAny:return new Ou(e,t);case qt.AnyEvent:return new ou(e,t);case qt.DestroyedAllUnits:return new Tu(e,t);case qt.DestroyedAllBuildings:return new yu(e,t);case qt.DestroyedAll:return new wu(e,t);case qt.CreditsExceed:return new gu(e,t);case qt.ElapsedTime:return new Bu(e,t);case qt.MissionTimerExpired:return new Hu(e,t);case qt.DestroyedBuildings:return new ku(e,t);case qt.DestroyedUnits:return new Cu(e,t);case qt.NoFactoriesLeft:return new Lu(e,t);case qt.BuildBuilding:return new uu(e,t,xt.Building);case qt.BuildUnit:return new uu(e,t,xt.Vehicle);case qt.BuildInfantry:return new uu(e,t,xt.Infantry);case qt.BuildAircraft:return new uu(e,t,xt.Aircraft);case qt.CrossesHorizontalLine:return new mu(e,t);case qt.CrossesVerticalLine:return new fu(e,t);case qt.GlobalIsSet:return new Eu(e,t,!0);case qt.GlobalIsCleared:return new Eu(e,t,!1);case qt.DestroyedOrCaptured:return new _u(e,t);case qt.LowPower:return new Du(e,t);case qt.DestroyedBridge:return new Su(e,t);case qt.BuildingExists:return new cu(e,t);case qt.ComesNearWaypoint:return new du(e,t);case qt.LocalIsSet:return new Mu(e,t,!0);case qt.LocalIsCleared:return new Mu(e,t,!1);case qt.FirstDamagedCombat:return new Nu(e,t,100);case qt.HalfHealthCombat:return new Nu(e,t,50);case qt.QuarterHealthCombat:return new Nu(e,t,25);case qt.FirstDamagedAny:return new Pu(e,t,100);case qt.HalfHealthAny:return new Pu(e,t,50);case qt.QuarterHealthAny:return new Pu(e,t,25);case qt.AttackedByHouse:return new lu(e,t);case qt.AmbientLightBelow:return new nu(e,t,"below");case qt.AmbientLightAbove:return new nu(e,t,"above");case qt.ElapsedScenarioTime:return new Au(e,t);case qt.DestroyedOrCapturedOrInfiltrated:return new Iu(e,t);case qt.PickupCrate:return new ju(e,t);case qt.PickupCrateAny:return new Fu(e,t);case qt.RandomDelay:return new Uu(e,t);case qt.CreditsBelow:return new pu(e,t);case qt.SpyEnteringAsHouse:return new zu(e,t);case qt.SpyEnteringAsInfantry:return new Vu(e,t);case qt.DestroyedAllUnitsNaval:return new vu(e,t);case qt.DestroyedAllUnitsLand:return new bu(e,t);case qt.BuildingNotExists:return new cu(e,t,!0);default:throw new Error(`Unhandled trigger event type "${qt[e.type]}"`)}}}class $u{constructor(){this.disposables=new Rl,this.triggerInstances=new Map,this.targetsByTag=new Map,this.conditionFactory=new Gu,this.executorFactory=new ru,this.pendingGameEvents=[],this.globalVariables=new Map,this.localVariables=new Map}init(i){var t,e,s,r,a=i.map.getInitialMapObjects()["technos"];for(let t of a)if(t.tag){let e=this.targetsByTag.get(t.tag);e||(e=[],this.targetsByTag.set(t.tag,e));var n=i.map.tiles.getByMapCoords(t.rx,t.ry);!n||(n=i.map.getObjectsOnTile(n).find(e=>e.name===t.name&&e.type===t.type))&&e.push(n)}for(t of i.map.getCellTags()){var o=i.map.tiles.getByMapCoords(t.coords.x,t.coords.y);if(o){let e=this.targetsByTag.get(t.tagId);e||(e=[],this.targetsByTag.set(t.tagId,e)),e.push(o)}else console.warn(`CellTag out of bounds at (${t.coords.x}, ${t.coords.y}). Skipping.`)}for([e,s]of i.map.getVariables())this.localVariables.set(e,s.clone());for(r of i.map.getTriggers())this.triggerInstances.set(r.id,this.createTriggerInstance(r,i));this.disposables.add(i.events.subscribe(e=>this.pendingGameEvents.push(e)))}createTriggerInstance(i,s){let r=this.targetsByTag.get(i.tag.id)??[];return{trigger:i,conditions:i.events.map(e=>{let t=this.conditionFactory.create(e,i);return t.setTargets(r),t.init(s),t}).sort((e,t)=>Number(t.blocking)-Number(e.blocking)),targets:r,remainingTargets:new Set(i.tag.repeatType===$t.OnceAll?r:[]),disabled:i.disabled,finished:!1}}update(i){var s,r=this.pendingGameEvents.splice(0,this.pendingGameEvents.length);for(s of this.triggerInstances.values())if(!s.finished&&!s.disabled){let e=!0,t=[];for(var a of s.conditions){var n=a.check(i,r);if("boolean"==typeof n?n||(e=!1):n.length?t.push(...n):e=!1,a.blocking&&!e)break}if(e){var o=s.trigger;s.conditions.forEach(e=>e.reset?.());let e=[];if(o.tag.repeatType===$t.OnceAll){for(var h of t)s.remainingTargets.delete(h);if(s.remainingTargets.size)continue;e=t.length?[t[t.length-1]]:[]}else e=s.targets;this.executeActions(o,e,i),o.tag.repeatType!==$t.Repeat&&(s.finished=!0)}}}executeActions(t,i,s){for(var r of t.actions){let e=this.executorFactory.create(r,t);e.execute(s,i)}}setTriggerEnabled(e,t){let i=this.triggerInstances.get(e);i&&(i.disabled=!t)}forceTrigger(e,t){e=this.triggerInstances.get(e);e&&this.executeActions(e.trigger,e.targets,t)}destroyTrigger(e){this.triggerInstances.delete(e)}destroyTag(e){let t=[];for(var[i,s]of this.triggerInstances)s.trigger.tag.id===e&&t.push(i);for(var r of t)this.destroyTrigger(r)}getGlobalVariable(e){return!!this.globalVariables.get(e)?.value}toggleGlobalVariable(e,t){let i=this.globalVariables.get(e);void 0===i?this.globalVariables.set(e,new vi("No name",t)):i.value=t}getLocalVariable(e){return!!this.localVariables.get(e)?.value}toggleLocalVariable(e,t){let i=this.localVariables.get(e);void 0===i?this.localVariables.set(e,new vi("No name",t)):i.value=t}dispose(){this.disposables.dispose()}}class qu{constructor(e){this.target=e,this.type=ss.TimerExpire}}class Xu{constructor(){this.ticks=0,this.running=!1}getSeconds(){return Math.floor(this.ticks/js.BASE_TICKS_PER_SECOND)}setSeconds(e){this.ticks=Math.max(0,Math.floor(js.BASE_TICKS_PER_SECOND*e))}addSeconds(e){this.ticks=Math.max(0,this.ticks+Math.floor(js.BASE_TICKS_PER_SECOND*e))}start(){this.running=!0}stop(){this.running=!1}isRunning(){return this.running}update(e){this.running&&(0<this.ticks?this.ticks--:(this.running=!1,e.events.dispatch(new qu(this))))}}($l=$l||{}).onAdd=Symbol(),(r=ql=ql||{})[r.NotStarted=0]="NotStarted",r[r.Started=1]="Started",r[r.Ended=2]="Ended";class Zu{constructor(e,t,i,s,r,a,n,o,h,l,c,u,d,p,g){this.updatableObjects=new Set,this.constructionWorkers=new Map,this.currentTick=0,this.currentTime=0,this.countdownTimer=new Xu,this._onEnd=new ao,this.afterTickCallbacks=[],this.events=new jl,this.traits=new Aa,this.debugText=new wl(""),this.world=e,this.map=t,this.rules=i,this.art=s,this.ai=r,this.id=a,this.startTimestamp=n,this.prng=rc.factory(a,n),this.gameOpts=o,this.gameModeType=h,this.playerList=l,this.unitSelection=c,this.alliances=u,this.desiredSpeed=new wl(js.computeGameSpeed(o.gameSpeed)),this.speed=new wl(this.desiredSpeed.value),this.nextObjectId=d,this.objectFactory=p,this.botManager=g,this.triggers=new $u}get onEnd(){return this._onEnd.asEvent()}addPlayer(e){this.playerList.addPlayer(e),this.constructionWorkers.set(e,this.createConstructionWorker(e))}getPlayer(e){return this.playerList.getPlayerAt(e)}getPlayerByName(e){return this.playerList.getPlayerByName(e)}getAiPlayerName(e){let t;return t="number"==typeof e?e:this.gameOpts.aiPlayers.indexOf(e),`@@AI${t+1}@@`}getPlayerNumber(e){return this.playerList.getPlayerNumber(e)}getCombatants(){return this.playerList.getCombatants()}getCivilianPlayer(){return this.playerList.getCivilian()}getAllPlayers(){return this.playerList.getAll()}getNonNeutralPlayers(){return this.playerList.getNonNeutral()}areFriendly(e,t){return e.owner===t.owner||this.alliances.areAllied(e.owner,t.owner)}getWorld(){return this.world}createConstructionWorker(e){return new Ll(e,this.rules,this.art,this.map,this)}getConstructionWorker(e){var t=this.constructionWorkers.get(e);if(!t)throw new Error(`No construction worker found for player "${e.name}"`);return t}getUnitSelection(){return this.unitSelection}init(e){this.localPlayer=e,this.createMapObjects(),this.createPlayerInitialUnits(),this.map.terrain.computeAllPassabilityGraphs(),this.mapShroudTrait.init(this),this.crateGeneratorTrait.init(this),this.playerList.getAll().forEach(e=>e.credits=this.gameOpts.credits),this.rules.mpDialogSettings.alliesAllowed&&this.createInitialTeams()}start(){this.status=ql.Started,this.currentTick=0,this.currentTime=0,this.botManager.init(this),this.triggers.init(this)}createInitialTeams(){for(let t=0;t<this.gameOpts.maxSlots;t++){var i=[...this.gameOpts.humanPlayers,...this.gameOpts.aiPlayers].filter(e=>e?.teamId===t&&-3!==e.countryId).map(e=>Bs(e)?e.name:this.getAiPlayerName(e));if(1<i.length)for(let t=0;t<i.length-1;t++)for(let e=t+1;e<i.length;e++){var s=this.getPlayerByName(i[t]),r=this.getPlayerByName(i[e]),r=this.alliances.setAlliance(s,r,Xh.Formed);this.onAllianceChange(r,s,!0)}}}createMapObjects(){var e=this.rules.general.harvesterUnit.every(e=>!V(this.rules.getObject(e,xt.Vehicle).techLevel,0,this.rules.mpDialogSettings.techLevel)),t=this.map.getInitialMapObjects();this.createInitialMapTerrains(t.terrains,e),this.createInitialMapOverlays(t.overlays,e),this.createInitialMapSmudges(t.smudges),this.createInitialMapTechnos(t.technos)}createInitialMapTerrains(e,t){for(var i of e){var s,r,a=i.name;this.validateMapObjectRulesAndArt(a,xt.Terrain)&&((s=this.map.tiles.getByMapCoords(i.rx,i.ry))?(r=this.rules.getObject(a,xt.Terrain),t&&r.spawnsTiberium||(a=this.createObject(xt.Terrain,a),this.spawnObject(a,s))):console.warn(`Invalid map object location (${i.rx},${i.ry})`,i))}}createInitialMapOverlays(e,s){let r=new Map,a=new Map;for(var n of e){var o=this.rules.getOverlayName(n.id);if(this.validateMapObjectRulesAndArt(o,xt.Overlay)){let e=this.createObject(xt.Overlay,o);e.overlayId=n.id,e.value=n.value;let t=n.rx,i=n.ry;e.isBridge()&&e.isHighBridge()&&(e.position.tileElevation=4,t+=e.isXBridge()?0:-1,i+=e.isXBridge()?-1:0);var h=this.map.tiles.getByMapCoords(t,i);if(h)if(e.rules.tiberium&&(o=qa.getOverlayTibType(n.id),void 0!==(o=dn.calculateOverlayId(o,h))&&o!==n.id&&(e.dispose(),e=this.createObject(xt.Overlay,this.rules.getOverlayName(o)),e.overlayId=o,e.value=n.value)),Ha.isLowBridge(n.id))Ha.isBridgePlaceholder(n.id)||(r.set(h,n.value),1===n.value?a.set(h,e):e.dispose());else{if(e.isTiberium()){if(![oa.Ore,oa.Gems,oa.Vinifera].includes(qa.getOverlayTibType(e.overlayId))){console.warn(`Found unsupported TS tiberium overlay ${e.overlayId} @${h.rx},${h.ry}. Skipping.`);continue}if(this.map.getObjectsOnTile(h).find(e=>e.isTerrain())){e.dispose();continue}}s&&e.isTiberium()?e.dispose():this.spawnObject(e,h)}else console.warn(`Invalid map object location (${t},${i})`,n),e.dispose()}}for(var[t,i]of a){var l=i.isXBridge(),c=this.map.tiles.getByMapCoords(t.rx+(l?0:-1),t.ry+(l?-1:0)),l=this.map.tiles.getByMapCoords(t.rx+(l?0:1),t.ry+(l?1:0));c&&l&&(0===r.get(c)||2===r.get(l))?(i.value=0,this.spawnObject(i,c)):(i.dispose(),console.warn(`Invalid bridge segment @${t.rx},${t.ry}. Skipping.`))}var u,d=[...a.keys()].filter(e=>this.map.bridges.getPieceAtTile(e)?.headType!==qh.None),e=this.map.bridges.findMapHighBridgeHeadTiles();let p=this.map.bridges.findBridgeSpecsForHeadTiles([...d,...e]);for(u of p)for(var g of this.map.bridges.findBridgePieces(u))g.obj.bridgeTrait.bridgeSpec=u;var m,e=p.map(e=>this.map.bridges.findAllBridgeTiles(e)).flat(),f=Ha.bridgePlaceholderIds[0],y=this.rules.getOverlayName(f);for(m of e){let e=this.createObject(xt.Overlay,y);e.overlayId=f,this.spawnObject(e,m)}}createInitialMapSmudges(e){for(var t of e){var i=t.name,s=this.map.tiles.getByMapCoords(t.rx,t.ry);s?(i=this.createObject(xt.Smudge,i),this.spawnObject(i,s)):console.warn(`Invalid map object location (${t.rx},${t.ry})`,t)}}createInitialMapTechnos(e){let t=new Map(this.playerList.getAll().filter(e=>!!e.country).map(e=>[e.country.name,e])),s=this.map.getTags();for(let i of e){var r=i.name;if(this.validateMapObjectRulesAndArt(r,i.type)){var a=this.map.tiles.getByMapCoords(i.rx,i.ry);if(a){var n=t.get(i.owner);if(n){if(n.isNeutral){let t=this.createObject(i.type,r);i.tag&&(t.tag=s.find(e=>e.id===i.tag)),t.healthTrait.health=i.health/256*100;let e=!1;if(!t.healthTrait.health){if(!t.isBuilding()||!t.rules.leaveRubble){t.dispose();continue}e=!0}if(i.isInfantry()||i.isVehicle()||i.isAircraft()){t.direction=(-i.direction/256*360+360)%360,i.isInfantry()&&(t.position.subCell=i.subCell);let e=!1;i.onBridge&&(void 0===a.onBridgeLandType?console.warn(`Cannot place unit "${i.name}" on a bridge because `+`no bridge was found at ${a.rx}, ${a.ry}`):e=!0),t.onBridge=e,t.zone=_s(e?a.onBridgeLandType:a.landType),e&&(t.position.tileElevation+=this.map.tileOccupation.getBridgeOnTile(a)?.tileElevation??0),i.veterancy&&t.veteranTrait?.setRelativeXP(i.veterancy)}else t.poweredTrait?.setTurnedOn(i.poweredOn);this.changeObjectOwner(t,n),this.spawnObject(t,a),e&&this.destroyObject(t,void 0,!0)}}else console.warn(`Invalid owner "${i.owner}" for map object`,i)}else console.warn(`Invalid map object location (${i.rx},${i.ry})`,i)}}}validateMapObjectRulesAndArt(e,t){return this.rules.hasObject(e,t)?!!this.art.hasObject(e,t)||(console.warn(`Map object '${e}' has no art section. Skipping.`),!1):(console.warn(`Map object '${e}' has no rules section. Skipping.`),!1)}createPlayerInitialUnits(){let e=this.playerList.getCombatants().map(e=>e.country);var i=[...this.rules.infantryRules.values(),...this.rules.vehicleRules.values()].filter(t=>t.allowedToStartInMultiplayer&&!t.naval&&-1!==t.techLevel&&t.techLevel<=this.rules.mpDialogSettings.techLevel&&!this.rules.general.baseUnit.includes(t.name)&&e.some(e=>t.isAvailableTo(e)&&t.hasOwner(e)));for(let h of this.playerList.getCombatants()){var l=this.map.startingLocations[h.startLocation],c=this.map.tiles.getByMapCoords(l.x,l.y);let t=this.rules.general.baseUnit.find(e=>{let t=this.rules.getObject(e,xt.Vehicle);return t.isAvailableTo(h.country)&&t.hasOwner(h.country)});if(!t)throw new Error(`No suitable MCV found for player country ${h.country}`);l=this.rules.getObject(t,xt.Vehicle),l=this.createUnitForPlayer(l,h);this.spawnObject(l,c);let e=Fl.generate(this.gameOpts.unitCount,[...this.rules.vehicleRules.keys()],i,h.country);this.gameModeType===kt.Unholy&&e.push(...this.rules.general.baseUnit.filter(e=>e!==t).map(e=>({name:e,type:xt.Vehicle,count:1})));var u,d,p;let s=[],r=!1,a=new wo(this.map.tiles,this.map.mapBounds,c,4,4,e=>!this.map.getGroundObjectsOnTile(e).find(e=>!(e.isSmudge()||e.isOverlay()&&e.isTiberium()))&&0<this.map.terrain.getPassableSpeed(e,ei.Foot,!1)),n=new Map,o=0;for({name:u,type:d,count:p}of e){let i=p;for(;0<i;){let t;if(r||(t=a.getNextTile(),t?s.push(t):r=!0),r&&s.length){var g=s[o];let e=n.get(g);e||(e=new wo(this.map.tiles,this.map.mapBounds,g,1,0,e=>!this.map.getGroundObjectsOnTile(e).find(e=>!(e.isSmudge()||e.isOverlay()&&e.isTiberium()))&&0<this.map.terrain.getPassableSpeed(e,ei.Foot,!1)),n.set(g,e)),o=(o+1)%s.length,t=e.getNextTile()}if(t){var m,f=this.rules.getObject(u,d);if(d===xt.Vehicle){g=this.createUnitForPlayer(f,h);this.applyInitialVeteran(g,h),this.spawnObject(g,t),i--}else{if(d!==xt.Infantry)throw new Error("Should not reach this line");for(m of Ra.SUB_CELLS.slice(0,i)){let e=this.createUnitForPlayer(f,h);e.position.subCell=m,this.applyInitialVeteran(e,h),this.spawnObject(e,t),i--}}}else i--}}}}applyInitialVeteran(e,t){e.veteranTrait&&(this.rules.general.veteran.initialVeteran?e.veteranTrait.setVeteranLevel(ea.Elite):t.country.hasVeteranUnit(e.type,e.name)&&e.veteranTrait.setVeteranLevel(ea.Veteran))}createObject(e,t){return this.objectFactory.create(e,t,this.rules,this.art)}createUnitForPlayer(e,t){if(![xt.Aircraft,xt.Vehicle,xt.Infantry].includes(e.type))throw new Error(`Attempted to create an invalid unit type "${e.type}"`);let i=this.createObject(e.type,e.name);return this.changeObjectOwner(i,t),i.purchaseValue=this.sellTrait.computePurchaseValue(i.rules,t),i}createProjectile(e,t,i,s,r){let a=this.createObject(xt.Projectile,e);return a.fromWeapon=i,a.fromObject=t,a.fromPlayer=t.owner,a.target=s,a.isShrapnel=r,a}createLooseProjectile(e,t,i){var s=this.rules.getWeapon(e),r=s.projectile,a=this.rules.getProjectile(r),e=this.rules.getWarhead(s.warhead),e={minRange:0,projectileRules:a,range:Number.POSITIVE_INFINITY,rules:s,speed:tn.computeSpeed(s,a),type:hi.Primary,warhead:new Ya(e)};let n=this.createObject(xt.Projectile,r);return n.fromWeapon=e,n.fromObject=void 0,n.fromPlayer=t,n.target=i,n}createSuperWeapon(e,t,i=!1){var s=this.rules.getSuperWeapon(e);return new zs(e,s,t,i)}createTarget(e,t){return new uo(e,t,this.map.tileOccupation)}isValidTarget(e){if(e){if(!e.isSpawned||e.isCrashing)return!1;if(!(e.rules.legalTarget||e.isBuilding()&&e.rules.hospital))return!1;if(e.isBuilding()&&e.rules.invisibleInGame)return!1}return!0}spawnObject(e,t){if(e.isTechno()&&e.limboData)throw new Error(`Object ${e.name}#${e.id} is in limbo. Use unlimboObject instead or clear limboData first`);this.doSpawnObject(e,t)}unspawnObject(e){e.isTechno()&&e.owner&&e.owner.removeOwnedObject(e),this.doUnspawnObject(e)}limboObject(e,t){e.limboData=t,this.doUnspawnObject(e)}unlimboObject(e,t,i=!1){var s=e.limboData;if(!s)throw new Error(`Object ${e.name}#${e.id} has no limboData attached`);e.limboData=void 0,this.doSpawnObject(e,t);let r=this.getUnitSelection();s.selected&&!i&&r.addToSelection(e),void 0!==s.controlGroup&&r.addUnitsToGroup(s.controlGroup,[e],!1)}doSpawnObject(t,e){var i,s;t.position.tile=e,t.isBuilding()&&(s=t.art.foundationCenter,i=e.rx+s.x,s=e.ry+s.y,t.centerTile=this.map.tiles.getByMapCoords(i,s)??this.map.tiles.getPlaceholderTile(i,s)),this.world.spawnObject(t),(t.cachedTraits.tick.length||t.isProjectile()||t.isDebris()||t.isTechno())&&this.updatableObjects.add(t),t.isTechno()&&this.map.technosByTile.add(t),t.isProjectile()||t.isDebris()||this.map.tileOccupation.occupyTileRange(e,t),t.art.canHideThings&&this.map.tileOcclusion.addOccluder(t),t.onSpawn(this),this.traits.filter(Qh).forEach(e=>{e[Qh.onSpawn](t,this)}),this.events.dispatch(new Hl(t))}doUnspawnObject(t){var e=t.tile;t.isProjectile()||t.isDebris()||this.map.tileOccupation.unoccupyTileRange(e,t),t.art.canHideThings&&this.map.tileOcclusion.removeOccluder(t),t.isTechno()&&(this.unitSelection.cleanupUnit(t),this.map.technosByTile.remove(t)),this.world.removeObject(t),this.updatableObjects.delete(t),t.onUnspawn(this),this.traits.filter(Yh).forEach(e=>{e[Yh.onUnspawn](t,this)}),this.events.dispatch(new Vl(t))}destroyObject(t,i,e=!1,s=!1){if(t.isDestroyed)throw new Error(`Object with ID "${t.id}" is already destroyed`);if(t.isTechno()){let e=t.mindControllableTrait?.getOriginalOwner()??t.owner;!i||t.isBuilding()&&!e.isCombatant()||(i.player.addUnitsKilled(t.type,1),i.player===e||this.alliances.areAllied(i.player,e)||(i.player.score+=t.rules.points)),e.isNeutral||e.addUnitsLost(t.type,1)}if(t.isDestroyed=!0,t.healthTrait&&(t.healthTrait.health=0),t.onDestroy(this,i,e),this.traits.filter(el).forEach(e=>{e[el.onDestroy](t,this,i)}),i?.obj?.traits.filter(Fn).forEach(e=>{e[Fn.onDestroy](i.obj,t,i.weapon,this)}),this.events.dispatch(new Ul(t,i,s)),t.isBuilding()&&t.rules.leaveRubble&&t.deathType!==Vr.Temporal){t.owner.removeOwnedObject(t),this.unitSelection.cleanupUnit(t);s=this.map.tileOccupation.calculateTilesForGameObject(t.tile,t);this.map.terrain.invalidateTiles(s),t.art.canHideThings&&this.map.tileOcclusion.removeOccluder(t),this.updatableObjects.delete(t),t.onUnspawn(this),this.traits.filter(Yh).forEach(e=>{e[Yh.onUnspawn](t,this)}),this.events.dispatch(new Vl(t))}else if(t.isSpawned)this.unspawnObject(t);else if(t.isTechno()&&t.owner){if(!t.limboData)throw new Error(`Object with ID "${t.id}" should be in limbo but has no limboData`);t.owner.removeOwnedObject(t)}t.dispose()}getObjectById(e){return this.world.getObjectById(e)}changeObjectOwner(t,e){const i=t.owner;i&&i.removeOwnedObject(t),e.addOwnedObject(t),i&&i!==e&&(this.traits.filter(Kh).forEach(e=>{e[Kh.onChange](t,i,this)}),t.onOwnerChange(i,this),this.events.dispatch(new zl(t,i)))}addObjectTrait(t,i){t.addTrait(i),this.traits.filter($l).forEach(e=>{e[$l.onAdd](t,i,this)})}onAllianceChange(t,e,i){this.events.dispatch(new Gl(t,i?tl.Formed:tl.Broken,e)),this.traits.filter(Jh).forEach(e=>{e[Jh.onChange](t,i,this)})}update(){if(this.status!==ql.NotStarted){this.botManager.update(this),this.status!==ql.Ended&&(void 0===this.lastGameEndCheck||1e3<=this.currentTime-this.lastGameEndCheck)&&(this.checkGameEndConditions(),this.lastGameEndCheck=this.currentTime);for(var e of[...this.updatableObjects])e.isSpawned&&e.update(this);if(this.playerList.getCombatants().forEach(e=>e.cheerCooldownTicks=Math.max(0,e.cheerCooldownTicks-1)),this.traits.filter(Es).forEach(e=>{e[Es.onTick](this)}),this.localPlayer&&!this.localPlayer.isObserver&&!this.localPlayer.defeated){var t=this.unitSelection.getSelectedUnits();if(1===t.length){let i=t[0];if(i.isTechno()&&i.owner!==this.localPlayer){let t=this.mapShroudTrait.getPlayerShroud(this.localPlayer);this.map.tileOccupation.calculateTilesForGameObject(i.tile,i).find(e=>!t.isShrouded(e,i.tileElevation))||(this.unitSelection.deselectAll(),this.unitSelection.cleanupUnit(i))}}}for(var i of this.afterTickCallbacks)i();this.afterTickCallbacks.length=0,this.triggers.update(this),this.countdownTimer.update(this),this.currentTick++,this.currentTime+=1e3/js.BASE_TICKS_PER_SECOND}}afterTick(e){this.afterTickCallbacks.push(e)}checkGameEndConditions(){this.updateDefeatedPlayers(this.playerList.getCombatants()),(this.localPlayer?.defeated&&!this.localPlayer.isObserver||!this.alliances.getHostilePlayers().length&&1<this.gameOpts.humanPlayers.length+this.gameOpts.aiPlayers.length)&&this.end()}end(){this.status!==ql.Ended&&(this.status=ql.Ended,this._onEnd.dispatch(this,void 0))}updateDefeatedPlayers(e){let s=this.stalemateDetectTrait?.isStale()&&0===this.stalemateDetectTrait.getCountdownTicks(),r=this.gameOpts.shortGame;e.forEach(t=>{let i;if(s)i=!0;else{let e;e=r?(e=[...t.getOwnedObjectsByType(xt.Building,!0)].some(e=>!e.rules.insignificant),e||t.getOwnedObjects(!0).some(e=>this.rules.general.baseUnit.includes(e.name))):t.getOwnedObjects(!0).some(e=>!e.rules.insignificant&&!e.limboData?.inTransport),i=!e}var e;i&&(t.defeated=!0,(e=this.alliances.getHostilePlayers().some(e=>!e.first.isAi||!e.second.isAi))&&(t.isObserver=!0),this.removeAllPlayerAssets(t),this.events.dispatch(new Wl(t)),e&&(this.mapShroudTrait.getPlayerShroud(t)?.revealAll(),e=t.radarTrait.isDisabled(),t.radarTrait.setDisabled(!1),e&&this.events.dispatch(new Bl(t,!0))))})}removeAllPlayerAssets(e){e.getOwnedObjects().forEach(e=>{e.isDestroyed||e.isBuilding()&&e.wallTrait||this.destroyObject(e,void 0,!0)}),e.getOwnedObjects(!0).forEach(e=>{e.isDestroyed||(e.limboData?.inTransport||e.isBuilding()&&e.wallTrait?this.changeObjectOwner(e,this.getCivilianPlayer()):this.destroyObject(e,void 0,!0))})}generateRandomInt(e,t){return this.prng.generateRandomInt(e,t)}generateRandom(){return this.prng.generateRandom()}getHash(){return G([...new Uint8Array(new Float64Array([this.prng.getLastRandom()]).buffer),this.nextObjectId.value,...this.world.getAllObjects().map(e=>e.getHash()),...this.playerList.getAll().map(e=>e.getHash()),this.alliances.getHash(),...this.traits.getAll().map(e=>e.getHash?.()??0)])}debugGetState(){return{currentTick:this.currentTick,lastRandom:this.prng.getLastRandom(),nextObjectId:this.nextObjectId.value,objects:this.world.getAllObjects().map(e=>e.debugGetState()),players:this.playerList.getAll().map(e=>e.debugGetState()),alliances:this.alliances.debugGetState(),traits:this.traits.getAll().reduce((e,t)=>{var i=t.debugGetState?.();return void 0!==i&&(e[t.constructor.name]=i),e},{})}}dispose(){this.world.getAllObjects().forEach(e=>e.dispose()),this.playerList.getAll().forEach(e=>e.dispose()),this.constructionWorkers.forEach(e=>e.dispose()),this.botManager.dispose(),this.triggers.dispose(),this.map.dispose(),this.traits.dispose()}}class Qu{constructor(e){this.map=e,this.radSites=new Map,this.radLevelByTile=new Map,this._onChange=new ao}get onChange(){return this._onChange.asEvent()}getRadLevel(e){return this.radLevelByTile.get(e)}[Es.onTick](e){var t;this.radLevelByTile.size&&(t=e.rules.radiation,void 0===this.nextDamage?this.nextDamage=Math.max(0,t.radApplicationDelay-1):this.nextDamage<=0?(this.applyDamage(e),this.nextDamage=Math.max(0,t.radApplicationDelay)):this.nextDamage--,void 0===this.nextDecay?this.nextDecay=Math.max(0,t.radLevelDelay-1):this.nextDecay<=0?(this.applyDecay(Math.ceil(t.radLevelDelay/t.radDurationMultiple)),this.radLevelByTile.size?this.nextDecay=Math.max(0,t.radLevelDelay):this.nextDecay=void 0):this.nextDecay--)}applyDamage(a){let n=a.rules.radiation,o=new Ya(a.rules.getWarhead(n.radSiteWarhead));this.radLevelByTile.forEach((e,t)=>{var i,s,r=Math.min(n.radLevelMax,e)*n.radLevelFactor;for(i of a.map.getGroundObjectsOnTile(t).filter(e=>e.isUnit()&&!(e.isInfantry()&&e.stance===Ls.Paradrop&&1<e.tileElevation)))o.canDamage(i,t,i.zone)&&(0<(s=o.computeDamage(r,i))&&o.inflictDamage(s,i,void 0,a,!0))})}applyDecay(s){var e=new Set(this.radLevelByTile.keys());this.radLevelByTile.clear(),this.radSites.forEach(({radLevel:e,radius:t},i)=>{e-=s;e<=0?this.radSites.delete(i):(this.radSites.set(i,{radLevel:e,radius:t}),this.setRadLevelAround(i,t,e))}),this._onChange.dispatch(this,e)}createRadSite(e,t,i){(t-=this.radSites.get(e)?.radLevel??0)<=0||(this.radSites.set(e,{radLevel:(this.radSites.get(e)?.radLevel??0)+t,radius:i}),(t=this.setRadLevelAround(e,i,t)).size&&this._onChange.dispatch(this,t))}setRadLevelAround(e,t,i){let s=new As(this.map.tileOccupation),r=new Us(this.map.tiles,this.map.mapBounds,e,{width:1,height:1},0,t,e=>!!e,!1);var a;let n=new Set;for(;a=r.getNextTile();){var o=s.tileDistance(e,a);o<=t&&(o=Math.ceil(H(i,0*i,o/t)),this.radLevelByTile.set(a,Math.min(1e3,(this.radLevelByTile.get(a)??0)+o)),n.add(a))}return n}getRadSiteLevel(e){return this.radSites.get(e)?.radLevel}}class Yu{constructor(){this.factories=new Map}registerFactory(e,t){this.factories.set(e,t)}create(e){let t=this.factories.get(e);if(!t)throw new Error(`No factory registered for action type ${e}`);return t.create()}}class Ku{constructor(e){this.player=e,this.selectedUnits=new Set}update(e){var t,i=[...e].reverse().find(e=>e.owner!==this.player);i&&(e=[i]),this.selectedUnits.clear();for(t of e)t.rules.selectable&&this.selectedUnits.add(t)}getSelectedUnits(){return[...this.selectedUnits].filter(e=>!e.isDestroyed&&!e.isCrashing)}isSelected(e){return this.selectedUnits.has(e)}}class Ju{constructor(){this.unitSelectionByPlayer=new Map}getOrCreateSelection(e){let t=this.unitSelectionByPlayer.get(e);return t||(t=new Ku(e),this.unitSelectionByPlayer.set(e,t)),t}}(r=Xl=Xl||{})[r.NoAction=0]="NoAction",r[r.DropPlayer=1]="DropPlayer",r[r.ObserveGame=2]="ObserveGame",r[r.ResignGame=3]="ResignGame",r[r.DebugCommand=4]="DebugCommand",r[r.PlaceBuilding=5]="PlaceBuilding",r[r.SellBuilding=6]="SellBuilding",r[r.ToggleRepair=7]="ToggleRepair",r[r.SelectUnits=8]="SelectUnits",r[r.OrderUnits=9]="OrderUnits",r[r.UpdateQueue=10]="UpdateQueue",r[r.ToggleAlliance=11]="ToggleAlliance",r[r.ActivateSuperWeapon=12]="ActivateSuperWeapon",r[r.PingLocation=13]="PingLocation";class ed{constructor(e){this.actionType=e}unserialize(e){}serialize(){return new Uint8Array}print(){return""}}class td extends ed{constructor(){super(Xl.NoAction)}process(){}}class id{create(){return new td}}class sd{constructor(e){this.target=e,this.type=ss.BuildingPlace}}class rd{constructor(e,t,i){this.name=e,this.player=t,this.tile=i,this.type=ss.BuildingFailedPlace}}(Zl=Zl||{}).onPlace=Symbol();class ad extends ed{constructor(e){super(Xl.PlaceBuilding),this.game=e}unserialize(e){let t=new v(e);this.buildingRules=this.game.rules.getTechnoByInternalId(t.readUint32(),xt.Building),this.tile={x:t.readUint16(),y:t.readUint16()}}serialize(){let e=new v(8);return e.writeUint32(this.buildingRules.index),e.writeUint16(this.tile.x),e.writeUint16(this.tile.y),e.toUint8Array()}print(){return`Place building ${this.buildingRules.name} at tile (${this.tile.x}, ${this.tile.y})`}process(){var e=this.game.map.tiles.getByMapCoords(this.tile.x,this.tile.y);if(e){var t=this.player;const i=this.tryPlaceBuilding(t,e);i?(this.game.traits.filter(Zl).forEach(e=>{e[Zl.onPlace](i,this.game)}),this.game.events.dispatch(new sd(i))):this.game.events.dispatch(new rd(this.buildingRules.name,t,e))}else console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}tryPlaceBuilding(s,r){var a=this.buildingRules;if(s.production){let i=s.production.getQueueForObject(a);if(i.status===yn.Ready&&i.getFirst().rules===a){let t=this.game.getConstructionWorker(s);if(s.production.isAvailableForProduction(a)&&t.canPlaceAt(a.name,r,{normalizedTile:!0})){r=t.placeAt(a.name,r,!0);s.addUnitsBuilt(xt.Building,1),i.shift(a,1);let e=s.production.getPrimaryFactory(es.BuildingType);return e&&(e.factoryTrait.status=kn.Delivering),r[0]}}}}}class nd{constructor(e){this.game=e}create(){return new ad(this.game)}}class od extends ed{constructor(e){super(Xl.SellBuilding),this.game=e}unserialize(e){this.buildingId=new v(e).readUint32()}serialize(){return new v(4).writeUint32(this.buildingId).toUint8Array()}print(){return`Sell building ${this.buildingId}`}process(){var t=this.player;if(this.game.getWorld().hasObjectId(this.buildingId)){let e=this.game.getObjectById(this.buildingId);e.isBuilding()&&(t!==e.owner||e.isDestroyed||e.buildStatus!==Cn.Ready||e.warpedOutTrait.isActive()||this.game.sellTrait.sell(e))}}}class hd{constructor(e){this.game=e}create(){return new od(this.game)}}const ld=[Bn.Occupy,Bn.Dock,Bn.Attack,Bn.Capture,Bn.Repair,Bn.EnterTransport,Bn.PlaceBomb,Bn.Deploy,Bn.Gather];(r=Ql=Ql||{})[r.Default=0]="Default",r[r.Mini=1]="Mini",r[r.Scroll=2]="Scroll",r[r.NoScroll=10]="NoScroll",r[r.Select=18]="Select",r[r.Move=31]="Move",r[r.NoMove=41]="NoMove",r[r.MoveMini=42]="MoveMini",r[r.NoActionMini=52]="NoActionMini",r[r.AttackRange=53]="AttackRange",r[r.AttackNoRange=58]="AttackNoRange",r[r.AttackMini=63]="AttackMini",r[r.Guard=68]="Guard",r[r.GuardMini=73]="GuardMini",r[r.Unknown1=78]="Unknown1",r[r.Unknown2=88]="Unknown2",r[r.Occupy=89]="Occupy",r[r.NoOccupy=99]="NoOccupy",r[r.OccupyMini=100]="OccupyMini",r[r.Deploy=110]="Deploy",r[r.NoDeploy=119]="NoDeploy",r[r.Unknown3=120]="Unknown3",r[r.Sell=129]="Sell",r[r.SellMini=139]="SellMini",r[r.NoSell=149]="NoSell",r[r.RepairMove=150]="RepairMove",r[r.SideRepair=170]="SideRepair",r[r.NoRepair=190]="NoRepair",r[r.Unknown4=191]="Unknown4",r[r.Unknown5=199]="Unknown5",r[r.Dynamite=204]="Dynamite",r[r.Unknown6=209]="Unknown6",r[r.Unknown7=214]="Unknown7",r[r.Unknown8=219]="Unknown8",r[r.Unknown9=224]="Unknown9",r[r.Unknown10=229]="Unknown10",r[r.Unknown11=234]="Unknown11",r[r.Unknwon12=239]="Unknwon12",r[r.Unknown13=249]="Unknown13",r[r.Para=259]="Para",r[r.Unknown14=269]="Unknown14",r[r.Storm=279]="Storm",r[r.Unknown15=299]="Unknown15",r[r.C4=309]="C4",r[r.Nuke=319]="Nuke",r[r.Unknown16=329]="Unknown16",r[r.Power=339]="Power",r[r.Unknown17=345]="Unknown17",r[r.Iron=346]="Iron",r[r.Unknown18=351]="Unknown18",r[r.Unknown19=356]="Unknown19",r[r.Chrono=357]="Chrono",r[r.DefuseBomb=369]="DefuseBomb",r[r.NoAction=384]="NoAction",r[r.Pan=385]="Pan",r[r.Unknown21=394]="Unknown21",r[r.AttackMove=404]="AttackMove",r[r.Unknown23=413]="Unknown23",r[r.Unknown24=422]="Unknown24",r[r.Unknown25=431]="Unknown25",r[r.Unknown26=432]="Unknown26",r[r.Unknown27=433]="Unknown27",r[r.Unknown28=434]="Unknown28",r[r.Beacon=435]="Beacon",(r=Yl=Yl||{})[r.None=0]="None",r[r.Move=1]="Move",r[r.Attack=2]="Attack",r[r.Enter=3]="Enter",r[r.Capture=4]="Capture",r[r.SpecialAttack=5]="SpecialAttack";class cd{constructor(e){this.orderType=e,this.targetOptional=!0,this.minimapAllowed=!0,this.singleSelectionRequired=!1,this.terminal=!1,this.feedbackType=Yl.None}getPointerType(e,t){return e?Ql.Mini:Ql.Default}set(e,t){return this.sourceObject=e,this.target=t,this}isValid(){return!0}isAllowed(){return!0}onAdd(e,t){return!0}}class ud{constructor(e,t){this.from=e,this.to=t,this.type=ss.ObjectMorph}}class dd extends Gs{constructor(e){super(),this.game=e}onStart(e){if(!this.morphInto)throw new Error("morphInto not set");e.isBuilding()&&e.buildStatus!==Cn.BuildDown&&this.morphInto.type!==xt.Building&&this.children.push(new Dl),e.isVehicle()&&this.morphInto.type===xt.Building&&this.children.push(new vr(180))}onTick(t){if(!this.morphInto)throw new Error("morphInto not set");let e=this.game.getUnitSelection();var i=e.isSelected(t),s=e.getOrCreateSelectionModel(t).getControlGroupNumber(),r=this.morphInto;let a;if(r.type===xt.Building){if(t.isVehicle()&&t.parasiteableTrait?.isInfested())return!0;var n=t.tile;let e=this.game.getConstructionWorker(t.owner);if(!e.canPlaceAt(this.morphInto.name,n,{ignoreAdjacent:!0,ignoreObjects:[t]}))return!0;this.game.unspawnObject(t),t.dispose(),[a]=e.placeAt(this.morphInto.name,n),a.healthTrait.health=t.healthTrait.health}else{let e=t.unitOrderTrait.getTasks().filter(e=>e instanceof ka);this.game.unspawnObject(t),t.dispose(),a=this.game.createUnitForPlayer(this.morphInto,t.owner),a.direction=180,a.healthTrait.health=t.healthTrait.health;n=t.art.foundationCenter;this.game.spawnObject(a,this.game.map.tiles.getByMapCoords(t.tile.rx+n.x,t.tile.ry+n.y)),e.forEach(e=>a.unitOrderTrait.addTask(e))}return a.purchaseValue=t.purchaseValue,t.replacedBy=a,i&&e.addToSelection(a),void 0!==s&&e.addUnitsToGroup(s,[a],!1),this.game.events.dispatch(new ud(t,a)),!0}}class pd extends dd{onStart(e){var t=e.rules.undeploysInto;if(!t)throw new Error(`Object type "${e.name}" doesn't undeploy into anything`);this.morphInto=this.game.rules.getObject(t,xt.Vehicle),super.onStart(e)}}class gd{constructor(e){this.target=e,this.type=ss.RallyPointChange}}class md extends Gs{constructor(e,t){super(),this.game=e,this.target=t,this.preventOpportunityFire=!1,this.useChildTargetLines=!0,this.attackPerformed=!1}onStart(e){this.children.push(new ka(this.game,this.target.centerTile,!1,{closeEnoughTiles:1,pathFinderIgnoredBlockers:[this.target],stopOnBlocker:this.target}))}onTick(e){if(this.attackPerformed||this.isCancelling()||!e.attackTrait||e.attackTrait.isDisabled())return!0;if(e.moveTrait.lastMoveResult!==Xr.CloseEnough)return!0;var t=e.attackTrait.selectWeaponVersus(e,this.target,this.game,!0);return!t||(this.children.push(e.attackTrait.createAttackTask(this.game,this.target,this.target.tile,t,{force:!0})),!(this.attackPerformed=!0))}}class fd extends cd{constructor(e,t,i,s=!1){super(s?Bn.ForceMove:Bn.Move),this.game=e,this.map=t,this.unitSelection=i,this.forceMove=s,this.targetOptional=!1,this.feedbackType=Yl.Move}getPointerType(e){let t=this.isAllowed();var i,s,r,a;return!t||this.forceMove||this.sourceObject.isBuilding()||this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)||(i=!!this.target.getBridge(),s=this.sourceObject.rules.speedType,r=this.sourceObject.rules.movementZone===ri.Fly,a=this.map.getObjectsOnTile(this.target.tile).some(e=>(e.isInfantry()||e.isVehicle())&&e.disguiseTrait?.hasTerrainDisguise()),t=r?this.sourceObject.rules.airportBound||this.target.tile.landType===Jt.Cliff||0<this.map.terrain.getPassableSpeed(this.target.tile,ei.Amphibious,i)&&!a:0<this.map.terrain.getPassableSpeed(this.target.tile,s,i)&&!a&&!(this.target.obj?.isTechno()&&!this.game.areFriendly(this.target.obj,this.sourceObject))),e?t?Ql.MoveMini:Ql.NoActionMini:t?Ql.Move:Ql.NoMove}isValid(){return!(this.sourceObject.isBuilding()&&(!this.sourceObject.rules.undeploysInto||this.sourceObject.rules.constructionYard&&!this.game.gameOpts.mcvRepacks)&&!this.sourceObject.rallyTrait?.getRallyPoint())&&(this.forceMove||!this.target.obj||(this.target.obj.isOverlay()||this.target.obj.isBuilding())&&this.target.obj.rules.wall||this.target.obj.isTechno()&&this.target.obj.owner===this.sourceObject.owner&&this.unitSelection.isSelected(this.target.obj)||(this.target.obj.isInfantry()||this.target.obj.isVehicle())&&!!this.target.obj.disguiseTrait?.hasTerrainDisguise()||this.target.obj.isTechno()&&!this.game.areFriendly(this.target.obj,this.sourceObject))}isAllowed(){return(!this.sourceObject.isUnit()||!this.sourceObject.moveTrait.isDisabled())&&(this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)?this.sourceObject.rules.moveToShroud:!(!this.forceMove&&this.target.obj?.isTechno()&&this.target.obj.owner===this.sourceObject.owner&&this.unitSelection.isSelected(this.target.obj)))}process(){const e=this.sourceObject;if(!e.isBuilding()||!e.rallyTrait?.getRallyPoint()){var t=this.game.rules.general.closeEnough;return e.isBuilding()&&e.rules.undeploysInto?[new pd(this.game),new ka(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:t,forceMove:this.forceMove})]:e.isUnit()?this.isEnemyBuildingBlock()?[new md(this.game,this.target.obj)]:[new ka(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:t,forceMove:this.forceMove})]:void 0}}isEnemyBuildingBlock(){return this.forceMove&&this.sourceObject.isVehicle()&&!this.sourceObject.rules.consideredAircraft&&this.target.obj?.isBuilding()&&!this.game.areFriendly(this.sourceObject,this.target.obj)}onAdd(t,e){var i=this.sourceObject.isBuilding()&&this.sourceObject.rules.undeploysInto;if(i&&this.sourceObject.buildStatus===Cn.BuildUp)return this.sourceObject.unitOrderTrait.getTasks().find(e=>e instanceof jo)?.setCancellable(!0),!0;if(!i&&this.sourceObject.isBuilding()&&this.sourceObject.rallyTrait?.getRallyPoint())return this.sourceObject.rallyTrait.changeRallyPoint(this.target.tile,this.sourceObject,this.game),this.game.events.dispatch(new gd(this.sourceObject)),!1;if(!this.isEnemyBuildingBlock()&&!e&&this.isValid()&&this.isAllowed()){this.sourceObject.attackTrait?.cancelOpportunityFire();let e=t.find(e=>e.constructor===ka&&!e.isCancelling());if(e)return e.setForceMove(this.forceMove),e.updateTarget(this.target.tile,!!this.target.getBridge()),e.children.length&&e.children[0]instanceof go&&e.children[0].cancel(),t.splice(t.indexOf(e)+1),this.sourceObject.unitOrderTrait.clearOrders(),!1;if(this.sourceObject.isUnit()&&this.sourceObject.rules.movementZone===ri.Fly){let e=t.find(e=>[go,fo,mo].includes(e.constructor)&&!e.isCancelling());e&&e.forceCancel(this.sourceObject)&&t.splice(t.indexOf(e))}}return!0}}class yd extends dd{onStart(e){var t=e.rules.deploysInto;if(!t)throw new Error(`Object type "${e.name}" doesn't deploy into anything`);this.morphInto=this.game.rules.getObject(t,xt.Building),super.onStart(e)}onTick(e){return!!this.isCancelling()||super.onTick(e)}}class wd{constructor(e,t){this.unit=e,this.deployType=t,this.type=ss.UnitDeployUndeploy}}class Td{constructor(e){this.target=e,this.type=ss.PrimaryFactoryChange}}(r=Kl=Kl||{})[r.None=0]="None",r[r.OnlyPassengers=1]="OnlyPassengers",r[r.All=2]="All";class bd extends Gs{constructor(e,t){super(),this.game=e,this.soft=t,this.evacState=Kl.None,this.evacTries=0,this.turnPerformed=!1,this.preventLanding=!1}forceEvac(){this.evacState=Kl.All}onStart(e){if(!e.transportTrait)throw new Error(`Object "${e.name}" is not a valid transport`);var t=e.transportTrait;0<t.units.length&&(this.evacState=this.evacState!==Kl.OnlyPassengers&&1!==t.units.length||!e.rules.gunner?Kl.OnlyPassengers:Kl.All)}onTick(e){if(this.isCancelling()||this.evacState===Kl.None)return!0;if(e.zone===vs.Air)return this.children.push(new ma(()=>e.zone!==vs.Air)),!1;let t=e.transportTrait.units;if(!t.length||e.rules.gunner&&1===t.length&&this.evacState!==Kl.All)return!0;var i=t[t.length-1],s=this.findValidEvacTarget(e,i);if(s&&!this.turnPerformed){this.turnPerformed=!0;var r=(s.dir+180)%360;if(e.direction!==r)return this.children.push(new vr(r)),!1}return this.evacuateUnit(i,e,s)?(t.pop(),this.children.push(new ga(1/60)),!1):!(++this.evacTries<=3)||(this.children.push(new ga(.05)),!1)}evacuateUnit(e,t,i){if(!i)return!this.soft&&(e.position.tile=t.tile,e.position.tileElevation=t.tileElevation,e.onBridge=t.onBridge,e.zone=t.zone,this.game.destroyObject(e,{player:e.owner}),!0);var{spawnNode:s,moveNode:i}=i;return e.position.tileElevation=s.onBridge?.tileElevation??0,e.onBridge=!!s.onBridge,e.zone=this.game.map.getTileZone(s.tile,!s.onBridge),this.game.unlimboObject(e,s.tile),e.unitOrderTrait.unmarkNextQueuedOrder(),i?e.unitOrderTrait.addTask(new ka(this.game,i.tile,!!i.onBridge)):e.unitOrderTrait.addTask(new Sa(this.game)),this.game.events.dispatch(new ih(t)),!0}findValidEvacTarget(a,n){let o=this.game.map,h=new Xs(o);var l,c,u,d,p,t=a.onBridge?o.tileOccupation.getBridgeOnTile(a.tile):void 0,i=(a.direction+180)%360;let g;for(let e=0;e<=180;e+=45)for(l of e&&e<180?[i+e,i-e]:[i]){var m=br.toMapCoords(l);let i=a.tile,s=t,r;for(let t=1;t<=2;t++){if(2===t){if(!r)break;i=r.tile,s=r.onBridge}var f,y=a.tile.rx+Math.sign(m.x)*t,w=a.tile.ry+Math.sign(m.y)*t,T=o.tiles.getByMapCoords(y,w);if(!T||!o.mapBounds.isWithinBounds(T))break;let e=[o.tileOccupation.getBridgeOnTile(T)];e[0]&&e.push(void 0);for(f of e)if(c=T,u=f,d=s,p=i,0<o.terrain.getPassableSpeed(c,n.rules.speedType,!!u)&&h.isEligibleTile(c,u,d,p)&&!o.terrain.findObstacles({tile:c,onBridge:u},n).length){if(1!==t)return{spawnNode:r,moveNode:{tile:T,onBridge:f},dir:l};r={tile:T,onBridge:f},g={spawnNode:r,moveNode:void 0,dir:l}}}}if(g)return g}}class vd extends cd{constructor(e,t){super(t?Bn.Deploy:Bn.DeploySelected),this.game=e,this.targeted=t,this.minimapAllowed=!1,this.getPointerType=()=>this.isAllowed()?Ql.Deploy:Ql.NoDeploy,this.targetOptional=!t,this.singleSelectionRequired=t}isValid(){if(this.targeted&&(!this.target.obj||this.target.obj!==this.sourceObject))return!1;let e=this.sourceObject;return!!(e.isInfantry()&&e.deployerTrait&&![Ls.Cheer].includes(e.stance)||e.isVehicle()&&e.deployerTrait||e.isVehicle()&&e.rules.deploysInto||e.isVehicle()&&e.transportTrait||e.isBuilding()&&e.rules.factory&&!e.owner.production?.isPrimaryFactory(e)||e.isBuilding()&&e.garrisonTrait?.units.length)}isAllowed(){let t=this.sourceObject;if(t.isVehicle()&&t.transportTrait)return!!(t.transportTrait.units.length&&0<this.game.map.terrain.getPassableSpeed(t.tile,ei.Foot,t.onBridge));if((t.isInfantry()||t.isVehicle())&&t.deployerTrait)return!0;if(t.isVehicle()&&t.rules.deploysInto){if(t.parasiteableTrait?.isInfested())return!1;let e=this.game.getConstructionWorker(t.owner);if(t.moveTrait.currentWaypoint?.onBridge)return!1;var i=t.moveTrait.currentWaypoint?.tile??t.tile;return e.canPlaceAt(t.rules.deploysInto,i,{ignoreObjects:[t],ignoreAdjacent:!0})}if(t.isBuilding()&&t.rules.factory)return!0;if(t.isBuilding()&&t.garrisonTrait?.units.length)return!0;throw new Error("Shouldn't reach this point. Missed a case.")}process(){const e=this.sourceObject;return e.isVehicle()&&e.transportTrait?[new bd(this.game,!0)]:e.isBuilding()&&e.rules.factory?void 0:e.isVehicle()&&e.rules.deploysInto?[new yd(this.game)]:(e.isInfantry()||e.isVehicle())&&e.deployerTrait?[new ma(()=>{e.deployerTrait.toggleDeployed(),this.game.events.dispatch(new wd(e,e.deployerTrait.isDeployed()?"undeploy":"deploy"))})]:e.isBuilding()&&e.garrisonTrait?.units.length?[new ma(()=>{e.garrisonTrait.evacuate(this.game,!0)})]:void 0}onAdd(t,e){let i=this.sourceObject;if(i.isBuilding()&&i.rules.factory)return i.owner.production.setPrimaryFactory(i),this.game.events.dispatch(new Td(i)),!1;if(i.isVehicle()&&i.transportTrait&&!e&&this.isValid()&&this.isAllowed()){let e=t.find(e=>e.constructor===bd&&!e.isCancelling());if(e)return e.forceEvac(),!1}return!0}}class Sd{constructor(e){this.player=e,this.type=ss.Cheer}}class kd{constructor(e){this.target=e,this.type=ss.DeployNotAllowed}}class Od extends ed{constructor(e,t,i,s){super(Xl.OrderUnits),this.game=e,this.map=t,this.orderActionContext=i,this.orderFactory=s,this.queue=!1,this.isInvalid=!1}unserialize(t){let i=new v(t);this.orderType=i.readUint8();var s=i.readUint8();if(0!==s){var r=i.readUint16(),t=i.readUint16();this.queue=2<s&&Boolean(i.readUint8());let e;if(3<s){s=i.readUint32();if(!this.game.getWorld().hasObjectId(s))return void(this.isInvalid=!0);e=this.game.getObjectById(s)}else e=void 0;t=this.map.tiles.getByMapCoords(r,t);t?this.target=this.game.createTarget(e,t):this.isInvalid=!0}}serialize(){let e=new v(11);e.dynamicSize=!1,e.writeUint8(this.orderType);let t=0;e.writeUint8(t),this.target&&(e.writeUint16(this.target.tile.rx),e.writeUint16(this.target.tile.ry),t+=2,i=(this.target.obj||this.target.getBridge())?.id,!this.queue&&void 0===i||(e.writeUint8(Number(this.queue)),t+=1),void 0!==i&&(e.writeUint32(i),t+=1));var i=e.position;return 0<t&&(e.seek(1),e.writeUint8(t)),new Uint8Array(e.buffer,e.byteOffset,i)}print(){return this.isInvalid?"":`${Bn[this.orderType]} order `+(this.target?`[obj: ${(this.target.obj||this.target.getBridge())?.name||"<none>"}, `+`tile: ${this.target.tile.rx},${this.target.tile.ry}]`+(this.queue?"(queue)":""):"")}process(){if(!this.isInvalid){let n=this.player;const l=this.game.mapShroudTrait.getPlayerShroud(n);if(l){const c=this.target?.obj;if(c){let e=this.game.map.tileOccupation.calculateTilesForGameObject(c.tile,c);if(!e.find(e=>!l.isShrouded(e,c.tileElevation)))return}let e=this.validateOrders(n).slice(0,128),a=[],t=[],s=[],i=[],r=[];if(e.forEach(e=>{(e instanceof fd?t:e.orderType===Bn.Scatter?s:e.orderType===Bn.DeploySelected?i:e.orderType===Bn.Cheer?r:a).push(e)}),t.length&&this.target)if(t[0].isEnemyBuildingBlock())t.forEach(e=>a.push(e));else{let s=this.target.getBridge();var o=t[0].forceMove,h=t.map(e=>e.sourceObject);let r=new Xs(this.map).findPositions(h,this.target.tile,s,o);t.forEach(e=>{var t=r.get(e.sourceObject),i=!s||s.isHighBridge()?this.map.tileOccupation.getBridgeOnTile(t):s,t=this.game.createTarget(i,t);e.target=t,a.push(e)})}if(s.length){o=s.map(e=>e.sourceObject).filter(e=>e.isInfantry()||e.isVehicle());let i=new va(this.game).findPositions(o);s.forEach(e=>{var t=i.get(e.sourceObject);t&&(t=this.game.createTarget(t.onBridge,t.tile),e.target=t,a.push(e))})}if(i.length){let t=[];i.forEach(e=>{((e.sourceObject.isInfantry()||e.sourceObject.isVehicle())&&e.sourceObject.deployerTrait?t:a).push(e)});let e=t.filter(e=>!e.sourceObject.deployerTrait.isDeployed());e.length?e.forEach(e=>a.push(e)):t.forEach(e=>a.push(e))}r.length&&(n.cheerCooldownTicks||(n.cheerCooldownTicks=this.game.rules.general.maximumCheerRate,a.push(...r),this.game.events.dispatch(new Sd(n)))),a.forEach(e=>e.sourceObject.unitOrderTrait.addOrder(e,this.queue)),this.updateWaypointPaths(a)}}}validateOrders(e){let i=this.orderActionContext.getOrCreateSelection(e);var s,r=i.getSelectedUnits();let t=this.orderFactory.create(this.orderType,i);t.target=this.target;let a=[];for(s of r)if(!(s.owner!==e||s.rules.spawned||s.isDestroyed||s.isCrashing||s.isDisposed||s.warpedOutTrait.isActive()||(t.sourceObject=s,t instanceof vd&&t.isValid()&&!t.isAllowed()&&this.game.events.dispatch(new kd(s)),t.singleSelectionRequired&&1<r.length)))if(t.isValid()&&t.isAllowed()){let e=this.orderFactory.create(this.orderType,i);e.set(s,this.target),a.push(e)}else{let t=!1;for(var n of ld){let e=this.orderFactory.create(n,i);if(e.set(s,this.target),!(e.singleSelectionRequired&&1<r.length)&&(e.targetOptional===!this.target&&e.isValid()&&e.isAllowed())){a.push(e),t=!0;break}}if(!t&&this.target&&this.orderType!==Bn.Deploy){let e=this.orderFactory.create(Bn.Move,i);e.set(s,this.target),e.isValid()&&e.isAllowed()&&a.push(e)}}return a}updateWaypointPaths(i){if(this.queue&&this.target){let e=i.map(e=>e.sourceObject);var t=[...new Set(e.map(e=>e.unitOrderTrait.waypointPath).filter(ja))];if(t.length<=1){i={orderType:this.orderType,target:this.target,terminal:i.some(e=>e.terminal),next:void 0};if(0===t.length){let t={units:e,waypoints:[i]};e.forEach(e=>{e.unitOrderTrait.waypointPath=t})}else{let e=t[0];e.waypoints[e.waypoints.length-1].next=i,e.waypoints.push(i)}}}}}class _d extends ed{constructor(e,t){super(Xl.SelectUnits),this.orderActionContext=t}get unitIds(){return this._unitIds}set unitIds(e){this._unitIds=e.slice(0,128)}unserialize(t){let i=new v(t);this.unitIds=new Array(t.byteLength/4);for(let e=0;e<t.byteLength/4;e++)this.unitIds[e]=i.readUint32()}serialize(){let e=new v(4*this.unitIds.length);e.dynamicSize=!1;for(var t of this.unitIds)e.writeUint32(t);return e.toUint8Array()}print(){return`Select unit(s) [${this.unitIds.join(",")}]`}process(){let e=this.player,t=[];for(var i of this.unitIds){i=e.getOwnedObjectById(i);i&&t.push(i)}this.orderActionContext.getOrCreateSelection(e).update(t)}}class Id{constructor(e,t){this.game=e,this.orderActionContext=t}create(){return new _d(this.game,this.orderActionContext)}}class Cd extends ka{constructor(e,t){super(e,t.tile,!1,{ignoredBlockers:[t]}),this.target=t,this.cancellable=!1}canStopAtTile(e,t,i){return!this.game.map.tileOccupation.isTileOccupiedBy(t,this.target)&&super.canStopAtTile(e,t,i)}}class Ad extends ka{constructor(e,t){super(e,Ad.chooseTargetFoundationTile(t,e),!1,{ignoredBlockers:[t],closeEnoughTiles:0}),this.target=t}static chooseTargetFoundationTile(t,i){if(t.isBuilding()){let e=t.centerTile;return i.map.mapBounds.isWithinBounds(e)||(e=i.map.tileOccupation.calculateTilesForGameObject(t.tile,t).find(e=>i.map.mapBounds.isWithinBounds(e))??t.tile),e}return t.tile}hasReachedDestination(e){return super.hasReachedDestination(e)||this.canStopAtTile(e,e.tile,e.onBridge)}canStopAtTile(e,t,i){t=this.game.map.tileOccupation.isTileOccupiedBy(t,this.target);return(!this.isCancelling()||!t)&&!(!this.isCancelling()&&!t)}isCloseEnoughToDest(e,t,i){return this.game.map.tileOccupation.isTileOccupiedBy(t,this.target)}}class Bd{constructor(e){this.target=e,this.type=ss.BuildingGarrison}}class xd{constructor(e,t){this.target=e,this.source=t,this.type=ss.EnterObject}}class Ed extends Gs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1,this.preventOpportunityFire=!1}isAllowed(e){return!this.target.isDestroyed&&this.target.garrisonTrait?.canBeOccupied()&&this.target.garrisonTrait.units.length<this.target.garrisonTrait.maxOccupants&&!(this.target.garrisonTrait.units.length&&this.target.garrisonTrait.units[0].owner!==e.owner)&&!e.mindControllableTrait?.isActive()}onTick(e){if(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())return!0;let t=this.target.garrisonTrait;return this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)?!this.isAllowed(e)||this.isCancelling()?(this.children.push(new Cd(this.game,this.target)),!(this.aborted=!0)):(this.game.limboObject(e,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(e).getControlGroupNumber()}),t.units.length||(e.owner.buildingsCaptured++,this.game.changeObjectOwner(this.target,e.owner),this.game.events.dispatch(new Bd(this.target))),this.game.events.dispatch(new xd(this.target,e)),t.units.push(e),!0):!!this.movePerformed||(this.children.push(new Ad(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Pd{constructor(e){this.target=e,this.type=ss.UnitRecycle}}class Nd extends Gs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1}isAllowed(e){return e.rules.movementZone!==ri.Fly&&e.rules.locomotor!==si.Chrono&&0<this.game.sellTrait.computeRefundValue(e)&&this.target.rules.cloning&&!this.target.isDestroyed&&this.target.buildStatus===Cn.Ready&&e.owner===this.target.owner}onTick(e){return!!(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())||(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)?!this.isAllowed(e)||this.isCancelling()?(this.children.push(new Cd(this.game,this.target)),!(this.aborted=!0)):(this.game.sellTrait.sell(e),this.game.events.dispatch(new Pd(e)),this.game.events.dispatch(new xd(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Ad(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Md{constructor(e,t){this.target=e,this.source=t,this.type=ss.BuildingInfiltration}}class Dd extends Gs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1}isAllowed(e){return e.rules.infiltrate&&this.target.rules.spyable&&!this.target.isDestroyed&&this.target.buildStatus!==Cn.BuildDown&&!this.game.areFriendly(e,this.target)}onTick(e){return!!(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())||(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)?!this.isAllowed(e)||this.isCancelling()?(this.children.push(new Cd(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),e.agentTrait?.infiltrate(e,this.target,this.game),this.game.events.dispatch(new Md(this.target,e)),this.game.events.dispatch(new xd(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Ad(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}(r=Jl=Jl||{})[r.MoveToQueueingTile=0]="MoveToQueueingTile",r[r.WaitForTurn=1]="WaitForTurn",r[r.MoveToTarget=2]="MoveToTarget",r[r.EnterTarget=3]="EnterTarget",r[r.ClearTarget=4]="ClearTarget";class Rd extends Gs{constructor(e,t){super(),this.game=e,this.target=t,this.movePerformed=!1}isAllowed(e){return e.rules.movementZone!==ri.Fly&&e.healthTrait.health<100&&this.target.hospitalTrait&&!this.target.isDestroyed&&!this.target.warpedOutTrait.isActive()&&this.game.areFriendly(e,this.target)&&(!this.target.ammoTrait||0<this.target.ammoTrait.ammo)}onStart(e){if(!this.target.hospitalTrait)throw new Error(`Target ${this.target.name} is not a valid hospital`);0<this.target.hospitalTrait.addToHealQueue(e)?this.state=Jl.MoveToQueueingTile:this.state=Jl.MoveToTarget}onEnd(e){!this.target.isDestroyed&&e.isSpawned&&this.target.hospitalTrait.removeFromHealQueue(e)}onTick(i){if(this.isCancelling()&&this.state!==Jl.EnterTarget||this.state===Jl.ClearTarget||i.moveTrait.isDisabled())return!0;if(this.state===Jl.MoveToQueueingTile){let t=new Xs(this.game.map);var e=new Us(this.game.map.tiles,this.game.map.mapBounds,this.target.tile,this.target.getFoundation(),1,1,e=>0<this.game.map.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&t.isEligibleTile(e,void 0,void 0,this.target.tile)).getNextTile();return!e||(this.children.push(new ka(this.game,e,!1,{closeEnoughTiles:5})),this.children.push(new ma(()=>{[Xr.Success,Xr.CloseEnough].includes(i.moveTrait.lastMoveResult)||this.cancel()})),this.state=Jl.WaitForTurn,this.queueingTile=e,!1)}if(this.state===Jl.WaitForTurn){if(!this.target.hospitalTrait.unitIsFirstInHealQueue(i))return!1;this.queueingTile=void 0,this.state=Jl.MoveToTarget}if(this.state===Jl.MoveToTarget){if(!this.isAllowed(i))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(i.tile,this.target))return!!this.movePerformed||(this.children.push(new Ad(this.game,this.target)),!(this.movePerformed=!0));this.state=Jl.EnterTarget}return this.state===Jl.EnterTarget&&(!this.isAllowed(i)||this.isCancelling()?(this.children.push(new Cd(this.game,this.target)),this.state=Jl.ClearTarget,!1):(this.game.limboObject(i,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(i).getControlGroupNumber()}),this.target.hospitalTrait.startHealing(i),this.game.events.dispatch(new xd(this.target,i)),!0))}getTargetLinesConfig(e){return{target:this.queueingTile?void 0:this.target,pathNodes:this.queueingTile?[{tile:this.queueingTile,onBridge:void 0}]:[]}}}class Ld extends cd{constructor(e){super(Bn.Occupy),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Yl.Capture}getPointerType(e){return e?this.isAllowed()?Ql.OccupyMini:Ql.NoActionMini:this.isAllowed()?Ql.Occupy:Ql.NoOccupy}isValid(){return!!(this.target.obj?.isSpawned&&this.target.obj?.isBuilding()&&this.sourceObject.isInfantry())&&(!!this.isInfantryRecycle(this.sourceObject,this.target.obj)||(this.target.obj.isBuilding()&&this.target.obj.hospitalTrait?this.game.areFriendly(this.sourceObject,this.target.obj)&&this.sourceObject.isInfantry():this.target.obj.garrisonTrait?this.target.obj.garrisonTrait.canBeOccupied()&&this.sourceObject.rules.occupier&&!(this.target.obj.garrisonTrait.units.length&&this.target.obj.garrisonTrait.units[0].owner!==this.sourceObject.owner)&&!this.sourceObject.mindControllableTrait?.isActive()&&!this.sourceObject.mindControllerTrait?.isActive():!(!this.target.obj.rules.spyable||!this.sourceObject.rules.infiltrate||this.game.areFriendly(this.sourceObject,this.target.obj))))}isInfantryRecycle(e,t){return t.rules.cloning&&e.owner===t.owner}isAllowed(){var e=this.target.obj,t=this.sourceObject;return this.isInfantryRecycle(t,e)?t.rules.movementZone!==ri.Fly&&t.rules.locomotor!==si.Chrono&&0<this.game.sellTrait.computeRefundValue(t):e.hospitalTrait?t.healthTrait.health<100&&t.rules.movementZone!==ri.Fly:!e.garrisonTrait||e.garrisonTrait.units.length<e.rules.maxNumberOccupants}process(){var e=this.target.obj,t=this.sourceObject;return this.isInfantryRecycle(t,e)?[new Nd(this.game,e)]:e.hospitalTrait?[new Rd(this.game,e)]:e.garrisonTrait?[new Ed(this.game,e)]:[new Dd(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof Ed||e instanceof Dd);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new As(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Fd extends Gs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1,this.preventOpportunityFire=!1}isAllowed(e){return!this.target.isDestroyed&&!this.target.invulnerableTrait.isActive()}onTick(e){if(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target))return!!this.movePerformed||(this.children.push(new Ad(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));if(!this.isAllowed(e)||this.isCancelling())return this.children.push(new Cd(this.game,this.target)),!(this.aborted=!0);var t=Math.floor(60*this.game.rules.combatDamage.c4Delay*js.BASE_TICKS_PER_SECOND);return this.target.c4ChargeTrait.setCharge(t,{player:e.owner,obj:e}),this.game.events.dispatch(new xd(this.target,e)),this.children.push(new Cd(this.game,this.target)),!(this.aborted=!0)}getTargetLinesConfig(e){return{target:this.target,pathNodes:[],isAttack:!0}}}class jd extends cd{constructor(e,{forceAttack:t,noIvanBomb:i}={}){super(t?Bn.ForceAttack:Bn.Attack),this.game=e,this.isC4=!1,this.forceAttack=!!t,this.ivanBombAllowed=!i||!!t,this.targetOptional=!1,this.feedbackType=Yl.None,this.rangeHelper=new As(this.game.map.tileOccupation),this.losHelper=new ho(this.game.map.tiles,e.map.tileOccupation)}getPointerType(e,t){if(!this.isAllowed())return e?Ql.NoActionMini:Ql.NoAction;if(this.isC4)return Ql.C4;var i=this.sourceObject.attackTrait?.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);if(i?.rules.sabotageCursor)return Ql.C4;if(this.ivanBombAllowed&&this.sourceObject.rules.ivan&&i?.warhead.rules.ivanBomb)return Ql.Dynamite;if(i?.warhead.rules.bombDisarm)return Ql.DefuseBomb;if(i&&i.rules.damage<0)return Ql.RepairMove;t=t.every(e=>{if(!e.attackTrait)return!0;var t=e.attackTrait.selectWeaponVersus(e,this.target,this.game,this.forceAttack);return!t||this.rangeHelper.isInWeaponRange(e,this.target.obj||this.target.tile,t,this.game.rules)&&this.losHelper.hasLineOfSight(e,this.target.obj||this.target.tile,t)});return e?Ql.AttackMini:t?Ql.AttackRange:Ql.AttackNoRange}isValid(){if(!this.sourceObject.attackTrait)return!1;if(this.forceAttack&&this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)&&!this.sourceObject.isBuilding())return!1;let e=this.target.obj;var t=this.game.map.getGroundObjectsOnTile(this.target.tile).find(e=>e.isTerrain());if(this.terminal=!e&&!t,this.sourceObject.c4&&e?.isBuilding()&&e.c4ChargeTrait&&(this.forceAttack||!this.game.areFriendly(e,this.sourceObject)||e.cabHutTrait))return this.isC4=!0,this.feedbackType=Yl.SpecialAttack,!0;if(this.isC4=!1,this.feedbackType=Yl.Attack,!this.game.isValidTarget(e))return!1;if(!e&&t?.rules.immune)return!1;if(!(e||this.target.tile!==this.sourceObject.tile||this.sourceObject.isUnit()&&this.sourceObject.zone===vs.Air))return!1;if(e===this.sourceObject)return!1;t=this.sourceObject.attackTrait.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);return!!t&&(!(!this.ivanBombAllowed&&t.warhead.rules.ivanBomb)&&(!(e?.isBuilding()&&e.cabHutTrait&&!t.warhead.rules.ivanBomb&&!t.warhead.rules.bombDisarm)&&(!!(this.sourceObject.isUnit()&&this.sourceObject.moveTrait&&!this.sourceObject.moveTrait.isDisabled()||this.rangeHelper.isInWeaponRange(this.sourceObject,e||this.target.tile,t,this.game.rules))&&(!(this.sourceObject.airSpawnTrait&&t.rules.spawner&&!this.game.map.isWithinBounds(this.target.tile))&&(!!this.forceAttack||(!e?.isBuilding()||!e.hospitalTrait)&&(!(!e||!e.healthTrait)&&(!e.isDestroyed&&!e.isCrashing&&(!(!e.isOverlay()||!(t.warhead.rules.wall||t.warhead.rules.wood&&e.rules.armor===ai.Wood))||e.isTechno()))))))))}isAllowed(){return!this.sourceObject.attackTrait.isDisabled()}process(){if(this.isC4)return[new Fd(this.game,this.target.obj)];var e=this.sourceObject.attackTrait.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);return[new go(this.game,this.target,e,{force:this.forceAttack})]}onAdd(t,e){let i=this.sourceObject;if(!e&&i.isUnit()&&this.isValid()&&this.isAllowed())if(i.rules.movementZone===ri.Fly){let e=t.find(e=>(e.constructor===ka||e.constructor===go)&&!e.isCancelling());e&&(i.moveTrait.currentWaypoint?.tile===this.target.tile||i.isAircraft()||e.constructor===go)&&e.forceCancel(i)&&t.splice(t.indexOf(e))}else{t.length&&i.isUnit()&&(i.rules.locomotor===si.Vehicle||i.rules.locomotor===si.Ship)&&(i.moveTrait.speedPenalty=.5);let e=t.find(e=>e.constructor===go&&!e.isCancelling());if(e?.getWeapon().warhead.rules.temporal)return e.setForceAttack(this.forceAttack),e.requestTargetUpdate(this.target),!1}return!0}}class Ud extends cd{constructor(e){super(Bn.Stop),this.game=e,this.getPointerType=()=>Ql.NoAction}isValid(){return this.sourceObject.isTechno()}isAllowed(){return!0}process(){return[new ma(e=>{!e.isUnit()||e.rules.locomotor!==si.Vehicle&&e.rules.locomotor!==si.Ship||(e.moveTrait.speedPenalty=0)})]}onAdd(e,t){let i=this.sourceObject;return t||!e.length||!i.isUnit()||i.rules.locomotor!==si.Vehicle&&i.rules.locomotor!==si.Ship||(i.moveTrait.speedPenalty=.5),i.isBuilding()&&i.rallyTrait?.getRallyPoint()&&(i.unitRepairTrait?.resetRallyPoint(i,this.game),i.factoryTrait?.resetRallyPoint(i,this.game)),!0}}class Wd extends cd{constructor(){super(Bn.Cheer),this.getPointerType=()=>Ql.NoAction}isValid(){return this.sourceObject.isInfantry()&&[Ls.None,Ls.Guard].includes(this.sourceObject.stance)}isAllowed(){return!0}process(){return[new cc]}}class zd extends cd{constructor(e){super(Bn.Dock),this.game=e,this.targetOptional=!1,this.feedbackType=Yl.Move}getPointerType(e){return e?this.isAllowed()?Ql.OccupyMini:Ql.NoActionMini:this.isAllowed()?Ql.Occupy:Ql.NoOccupy}isValid(){if(!this.target.obj?.isBuilding()||this.target.obj.isDestroyed||!this.target.obj.dockTrait||this.target.obj.buildStatus!==Cn.Ready||!this.sourceObject.isUnit()||this.target.obj.warpedOutTrait.isActive())return!1;var e=!(this.target.obj.rules.refinery||this.target.obj.unitRepairTrait);return this.game.areFriendly(this.target.obj,this.sourceObject)&&this.target.obj.dockTrait.isValidUnitForDock(this.sourceObject)&&!this.target.obj.dockTrait.isDocked(this.sourceObject)&&!(this.target.obj.unitRepairTrait&&!this.sourceObject.rules.dock.includes(this.target.obj.name)&&100===this.sourceObject.healthTrait.health)&&(!e||(0<(this.target.obj.dockTrait.getAvailableDockCount()??0)||this.target.obj.dockTrait.hasReservedDockForUnit(this.sourceObject)))}isAllowed(){return!0}process(){var e=this.target.obj;return e.rules.refinery&&this.sourceObject.isVehicle()&&this.sourceObject.harvesterTrait?[new eh(this.game,e,!0,!0)]:e.unitRepairTrait||this.sourceObject.rules.dock.includes(e.name)?[new fa(this.game,e)]:[]}}class Vd extends cd{constructor(e){super(Bn.Gather),this.game=e,this.targetOptional=!1,this.feedbackType=Yl.Move}getPointerType(e){return e?Ql.AttackMini:Ql.AttackNoRange}isValid(){return!(!this.sourceObject.isVehicle()||!this.sourceObject.harvesterTrait||this.sourceObject.moveTrait.isDisabled()||this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation))&&this.target.isOre}isAllowed(){return!0}process(){return[new Jo(this.game,this.target.tile,!0)]}}class Hd extends jd{constructor(e,t){super(e),this.map=t,this.orderType=Bn.AttackMove,this.targetOptional=!1,this.feedbackType=Yl.Move}getPointerType(t,i){if(this.isTargetted()){let e=super.getPointerType(t,i);return e!==Ql.AttackRange&&e!==Ql.AttackNoRange||(e=Ql.AttackMove),e}let e=this.isAllowed();var s,r;return e&&(s=!!this.target.getBridge(),r=this.sourceObject.rules.speedType,i=this.sourceObject.rules.movementZone===ri.Fly,e=i||0<this.map.terrain.getPassableSpeed(this.target.tile,r,s)||!!this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)),t?e?Ql.AttackMini:Ql.NoActionMini:e?Ql.AttackMove:Ql.NoMove}isValid(){var e=this.sourceObject.isUnit()&&!!this.sourceObject.attackTrait&&!this.sourceObject.rules.preventAttackMove&&!(this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)&&!this.sourceObject.rules.moveToShroud)&&(!this.isTargetted()||super.isValid());return this.feedbackType=Yl.Move,e}isAllowed(){return!(!this.isTargetted()&&this.sourceObject.moveTrait.isDisabled())&&super.isAllowed()}process(){if(this.isTargetted()){if(this.isC4)return[new Fd(this.game,this.target.obj)];var e=this.sourceObject.attackTrait.selectWeaponVersus(this.sourceObject,this.target,this.game);return[new mo(this.game,this.target,e)]}return[new fo(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})]}isTargetted(){return this.target.obj?.isTechno()}onAdd(t,e){let i=this.sourceObject;if(!e&&i.isUnit()&&this.isValid()&&this.isAllowed())if(i.rules.movementZone===ri.Fly){let e=t.find(e=>[ka,go,fo,mo].includes(e.constructor)&&!e.isCancelling());if(e)if(this.isTargetted())(i.moveTrait.currentWaypoint?.tile===this.target.tile||i.isAircraft()||e.constructor!==ka)&&e.forceCancel(i)&&t.splice(t.indexOf(e));else{if(e.constructor===fo)return e.updateTarget(this.target.tile,!!this.target.getBridge()),t.splice(t.indexOf(e)+1),i.unitOrderTrait.clearOrders(),!1;e.forceCancel(i)&&t.splice(t.indexOf(e))}}else this.isTargetted()&&t.length&&i.isUnit()&&(i.rules.locomotor===si.Vehicle||i.rules.locomotor===si.Ship)&&(i.moveTrait.speedPenalty=.5);return!0}}class Gd{constructor(e,t){this.target=e,this.source=t,this.type=ss.BuildingRepairFull}}class $d{constructor(e,t){this.source=e,this.tile=t,this.type=ss.BridgeRepair}}class qd extends Gs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1}isAllowed(e){return this.target.cabHutTrait?this.target.cabHutTrait.canRepairBridge():e.rules.engineer&&!this.target.isDestroyed&&this.target.rules.repairable&&this.target.healthTrait.health<100&&(!this.target.owner.isCombatant()||this.game.areFriendly(e,this.target))}onTick(e){return!!(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())||(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)?!this.isAllowed(e)||this.isCancelling()?(this.children.push(new Cd(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),this.target.cabHutTrait?(this.target.cabHutTrait.repairBridge(this.game,e.owner),this.game.events.dispatch(new $d(e.owner,this.target.centerTile))):(this.target.healthTrait.healToFull(e,this.game),this.game.events.dispatch(new Gd(this.target,e.owner))),this.game.events.dispatch(new xd(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Ad(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Xd extends cd{constructor(e){super(Bn.Repair),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Yl.Capture}getPointerType(e){return e?this.isAllowed()?Ql.OccupyMini:Ql.NoActionMini:this.isAllowed()?Ql.RepairMove:Ql.NoRepair}isValid(){return!!this.target.obj?.isBuilding()&&!this.target.obj.isDestroyed&&this.sourceObject.isInfantry()&&this.sourceObject.rules.engineer}isAllowed(){let e=this.target.obj;return e.cabHutTrait?e.cabHutTrait.canRepairBridge():!(!(e.rules.repairable&&e.healthTrait.health<100)||e.owner.isCombatant()&&!this.game.areFriendly(e,this.sourceObject))}process(){var e=this.target.obj;return[new qd(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof qd);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new As(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Zd extends cd{constructor(e,t){super(t?Bn.GuardArea:Bn.Guard),this.game=e,this.targeted=t,this.getPointerType=e=>e?this.isAllowed()?Ql.GuardMini:Ql.NoActionMini:this.isAllowed()?Ql.Guard:Ql.NoMove,this.terminal=!0,this.targetOptional=!t,this.minimapAllowed=t,this.feedbackType=t?Yl.Move:Yl.None}isValid(){return this.sourceObject.isUnit()&&(!!this.targetOptional||!this.sourceObject.moveTrait.isDisabled())&&!(this.target&&this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile,this.target.obj?.tileElevation)&&!this.sourceObject.rules.moveToShroud)}isAllowed(){return!0}process(){let t=this.targeted?this.target.tile:void 0;const e=this.sourceObject;let i=[];return t&&i.push(new ka(this.game,t,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})),e.isVehicle()&&e.harvesterTrait?i.push(new ma(()=>e.harvesterTrait.lastOreSite=void 0),new Jo(this.game,void 0,!0)):i.push(new ma(e=>{t&&![Xr.Success,Xr.CloseEnough].includes(this.sourceObject.moveTrait?.lastMoveResult)||(this.sourceObject.guardMode=!0)})),i}}class Qd extends cd{constructor(e){super(Bn.Scatter),this.game=e,this.getPointerType=()=>Ql.NoAction}isValid(){return(this.sourceObject.isInfantry()||this.sourceObject.isVehicle())&&this.sourceObject.rules.movementZone!==ri.Fly&&!this.sourceObject.moveTrait.isDisabled()}isAllowed(){return!0}process(){if(!this.target)throw new Error("Target should be set for executing a scatter order. See OrderUnitsAction.");return[new Sa(this.game,{tile:this.target.tile,toBridge:!!this.target.getBridge()})]}}class Yd{constructor(e){this.target=e,this.type=ss.EnterTransport}}(r=ec=ec||{})[r.MoveToQueueingTile=0]="MoveToQueueingTile",r[r.WaitForTurn=1]="WaitForTurn",r[r.MoveToTransport=2]="MoveToTransport",r[r.EnterTransport=3]="EnterTransport",r[r.ClearTransport=4]="ClearTransport";class Kd extends Gs{constructor(e,t){super(),this.game=e,this.target=t,this.movePerformed=!1,this.preventOpportunityFire=!1}isAllowed(e){return!this.target.isDestroyed&&!this.target.isCrashing&&this.game.areFriendly(this.target,e)&&e.zone!==vs.Air&&this.target.zone!==vs.Air&&this.target.transportTrait.unitFitsInside(e)&&this.target.moveTrait.moveState===qr.Idle&&!this.target.warpedOutTrait.isActive()&&!e.mindControllableTrait?.isActive()&&!e.mindControllerTrait?.isActive()}onStart(e){if(!this.target.transportTrait)throw new Error(`Unit ${this.target.name} is not a valid transport`);this.initialTargetTile=this.target.tile,0<this.target.transportTrait.addToLoadQueue(e)?this.state=ec.MoveToQueueingTile:this.state=ec.MoveToTransport}onEnd(e){this.target.isDestroyed||this.target.transportTrait?.removeFromLoadQueue(e)}onTick(n){if(this.isCancelling()&&this.state!==ec.EnterTransport||this.state===ec.ClearTransport||n.moveTrait.isDisabled())return!0;if(this.target.tile!==this.initialTargetTile||this.target.moveTrait.moveState!==qr.Idle)return!0;if(this.state===ec.MoveToQueueingTile){let s=new Xs(this.game.map),r=this.target.onBridge?this.game.map.tileOccupation.getBridgeOnTile(this.target.tile):void 0,a;var e=new Us(this.game.map.tiles,this.game.map.mapBounds,this.target.tile,this.target.getFoundation(),1,1,e=>{let t=[this.game.map.tileOccupation.getBridgeOnTile(e)];t[0]&&t.push(void 0);for(var i of t)if(0<this.game.map.terrain.getPassableSpeed(e,n.rules.speedType,!!i)&&s.isEligibleTile(e,i,r,this.target.tile))return a=i,!0;return!1}).getNextTile();return!e||(this.children.push(new ka(this.game,e,!!a,{closeEnoughTiles:5})),this.children.push(new ma(()=>{[Xr.Success,Xr.CloseEnough].includes(n.moveTrait.lastMoveResult)||this.cancel()})),this.queueingNode={tile:e,onBridge:a},this.state=ec.WaitForTurn,!1)}if(this.state===ec.WaitForTurn){if(!this.target.transportTrait.unitIsFirstInLoadQueue(n))return!1;this.queueingNode=void 0,this.state=ec.MoveToTransport}if(this.state===ec.MoveToTransport){if(!this.isAllowed(n))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(n.tile,this.target))return!!this.movePerformed||(this.children.push(new Ad(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));this.state=ec.EnterTransport}return this.state===ec.EnterTransport&&(!this.isAllowed(n)||this.isCancelling()?(this.children.push(new Cd(this.game,this.target)),this.state=ec.ClearTransport,!1):(this.game.limboObject(n,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(n).getControlGroupNumber(),inTransport:!0}),this.game.events.dispatch(new Yd(this.target)),this.game.events.dispatch(new xd(this.target,n)),this.target.transportTrait.units.push(n),!0))}getTargetLinesConfig(e){return{target:this.queueingNode?void 0:this.target,pathNodes:this.queueingNode?[this.queueingNode]:[]}}}class Jd extends cd{constructor(e){super(Bn.EnterTransport),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Yl.Enter}getPointerType(e){return e?this.isAllowed()?Ql.OccupyMini:Ql.NoActionMini:this.isAllowed()?Ql.Occupy:Ql.NoOccupy}isValid(){return!(!this.target.obj?.isVehicle()||!this.target.obj.transportTrait||this.target.obj.isDestroyed||this.target.obj===this.sourceObject||!this.game.areFriendly(this.target.obj,this.sourceObject)||!this.sourceObject.isVehicle()&&!this.sourceObject.isInfantry())}isAllowed(){let e=this.target.obj,t=this.sourceObject;return t.zone!==vs.Air&&e.zone!==vs.Air&&e.transportTrait.unitFitsInside(t)&&e.moveTrait.moveState===qr.Idle&&!e.warpedOutTrait.isActive()&&!t.mindControllableTrait?.isActive()&&!t.mindControllerTrait?.isActive()}process(){let e=this.sourceObject,t=this.target.obj;return this.game.map.terrain.getPassableSpeed(t.tile,e.rules.speedType,e.onBridge)?[new Kd(this.game,t)]:[new ma(()=>{t.unitOrderTrait.addTask(new ka(this.game,e.tile,e.onBridge)),t.unitOrderTrait.addTask(new ma(()=>{this.game.map.terrain.getPassableSpeed(t.tile,e.rules.speedType,e.onBridge)&&e.unitOrderTrait.addTask(new Kd(this.game,t))}))})]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof Kd);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new As(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class ep{constructor(e){this.target=e,this.type=ss.BuildingCapture}}class tp extends Gs{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1}isAllowed(e){return e.rules.engineer&&this.target.rules.capturable&&!this.target.isDestroyed&&this.target.buildStatus!==Cn.BuildDown&&!this.game.areFriendly(e,this.target)}onTick(e){return!!(this.isCancelling()&&!this.movePerformed||this.aborted||e.moveTrait.isDisabled())||(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)?!this.isAllowed(e)||this.isCancelling()?(this.children.push(new Cd(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),e.owner.buildingsCaptured++,this.game.changeObjectOwner(this.target,e.owner),this.game.events.dispatch(new ep(this.target)),this.game.events.dispatch(new xd(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Ad(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class ip extends cd{constructor(e){super(Bn.Capture),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Yl.Capture}getPointerType(e){return e?this.isAllowed()?Ql.OccupyMini:Ql.NoActionMini:this.isAllowed()?Ql.Occupy:Ql.NoOccupy}isValid(){return!(this.target.obj?.isDestroyed||!this.target.obj?.isBuilding()||!this.sourceObject.isInfantry())&&(this.target.obj.rules.capturable&&this.sourceObject.rules.engineer&&!this.game.areFriendly(this.sourceObject,this.target.obj))}isAllowed(){return!0}process(){return[new tp(this.game,this.target.obj)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof tp);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new As(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class sp{constructor(e,t){this.game=e,this.map=t}create(e,t){switch(e){case Bn.Deploy:return new vd(this.game,!0);case Bn.DeploySelected:return new vd(this.game,!1);case Bn.ForceMove:return new fd(this.game,this.map,t,!0);case Bn.Move:return new fd(this.game,this.map,t);case Bn.ForceAttack:return new jd(this.game,{forceAttack:!0});case Bn.Attack:return new jd(this.game,{noIvanBomb:!0});case Bn.PlaceBomb:return new jd(this.game);case Bn.AttackMove:return new Hd(this.game,this.map);case Bn.Capture:return new ip(this.game);case Bn.Occupy:return new Ld(this.game);case Bn.Stop:return new Ud(this.game);case Bn.Cheer:return new Wd;case Bn.Dock:return new zd(this.game);case Bn.Gather:return new Vd(this.game);case Bn.Repair:return new Xd(this.game);case Bn.Guard:return new Zd(this.game,!1);case Bn.GuardArea:return new Zd(this.game,!0);case Bn.Scatter:return new Qd(this.game);case Bn.EnterTransport:return new Jd(this.game);default:throw new Error(`Unhandled order type ${Bn[e]}`)}}}class rp{constructor(e,t,i){this.game=e,this.map=t,this.orderActionContext=i}create(){return new Od(this.game,this.map,this.orderActionContext,new sp(this.game,this.map))}}(r=tc=tc||{})[r.Add=0]="Add",r[r.Cancel=1]="Cancel",r[r.Pause=2]="Pause",r[r.Resume=3]="Resume";class ap extends ed{constructor(e){super(Xl.UpdateQueue),this.game=e}unserialize(e){let t=new v(e);var i;this.queueType=t.readUint8(),this.updateType=t.readUint8(),this.updateType!==tc.Add&&this.updateType!==tc.Cancel||(i=t.readUint32(),e=t.readUint8(),this.item=this.game.rules.getTechnoByInternalId(i,e),this.quantity=t.readUint16())}serialize(){let e=new v(9);if(e.dynamicSize=!1,e.writeUint8(this.queueType),e.writeUint8(this.updateType),this.updateType===tc.Add||this.updateType===tc.Cancel){if(void 0===this.quantity)throw new Error("Missing quantity");if(65535<this.quantity)throw new Error("Maximum quantity exceeded");e.writeUint32(this.item.index),e.writeUint8(this.item.type),e.writeUint16(this.quantity)}return new Uint8Array(e.buffer,e.byteOffset,e.position)}print(){return this.updateType===tc.Resume?`Resume queue ${fn[this.queueType]}`:this.updateType===tc.Add?`Add to queue ${this.item.name} x ${this.quantity}`:this.updateType===tc.Pause?`Put queue ${fn[this.queueType]} on hold.`:this.updateType===tc.Cancel?`Cancel ${this.item.name} x ${this.quantity}`:`Unhandled queue update type ${this.updateType}`}process(){let t=this.player,i=this.item,s=t.production.getQueue(this.queueType);if(this.updateType===tc.Resume)s.status===yn.OnHold&&(s.status=yn.Active);else if(this.updateType===tc.Add){let e=s.find(i);var r,a;(s.status===yn.Active||s.status===yn.Idle||s.status===yn.OnHold&&e[0]!==s.getFirst()||s.status===yn.Ready&&i.type!==xt.Building)&&(r=e.reduce((e,t)=>e+t.quantity,0),a=t.getOwnedObjectsByType(i.type,!0).filter(e=>e.name===i.name).length,(a=Number.isFinite(i.buildLimit)?Math.max(0,i.buildLimit-(a+r)):Number.POSITIVE_INFINITY)&&t.production.isAvailableForProduction(i)&&(n=Math.min(s.maxSize-s.currentSize,s.maxItemQuantity-r,a),0<(o=Math.min(this.quantity,n))&&s.push(i,o,i.cost)))}else if(this.updateType===tc.Cancel){if([yn.Ready,yn.OnHold,yn.Active].includes(s.status)){let e=s.find(i);var n,o;e.length&&(n=e.reduce((e,t)=>e+t.quantity,0),0<(o=Math.min(n,this.quantity))&&(s.pop(i,o),o===n&&(t.credits+=e[0].creditsSpent)))}}else this.updateType===tc.Pause&&s.status===yn.Active&&(s.status=yn.OnHold)}}class np{constructor(e){this.game=e}create(){return new ap(this.game)}}class op{constructor(e){this.target=e,this.type=ss.PlayerDropped}}class hp extends ed{constructor(e,t){super(Xl.DropPlayer),this.game=e,this.localPlayerName=t}process(){if(this.localPlayerName!==this.player.name){let e=this.player;e.defeated||(this.game.removeAllPlayerAssets(e),e.dropped=!0,this.game.events.dispatch(new op(e)))}}}class lp{constructor(e,t){this.game=e,this.localPlayerName=t}create(){return new hp(this.game,this.localPlayerName)}}class cp{constructor(e){this.target=e,this.type=ss.BuildingRepairStart}}class up extends ed{constructor(e){super(Xl.ToggleRepair),this.game=e}unserialize(e){this.buildingId=new v(e).readUint32()}serialize(){return new v(4).writeUint32(this.buildingId).toUint8Array()}print(){return`Toggle repair ${this.buildingId}`}process(){var e=this.player;if(this.game.getWorld().hasObjectId(this.buildingId)){let t=this.game.getObjectById(this.buildingId);if(t.isBuilding()&&e===t.owner&&!t.isDestroyed&&t.rules.repairable&&t.rules.clickRepairable&&100!==t.healthTrait.health){let e=t.traits.get(Ch);e.setDisabled(!e.isDisabled()),e.isDisabled()||this.game.events.dispatch(new cp(t))}}}}class dp{constructor(e){this.game=e}create(){return new up(this.game)}}class pp extends ed{constructor(e){super(Xl.ToggleAlliance),this.game=e}unserialize(e){this.toPlayer=this.game.getPlayer(e[0]),this.toggle=Boolean(e[1])}serialize(){return new Uint8Array([this.game.getPlayerNumber(this.toPlayer),this.toggle?1:0])}print(){return`Toggle alliance ${this.toggle?"on":"off"} with ${this.toPlayer.name}`}process(){var e=this.game.rules.mpDialogSettings;if(e.alliesAllowed&&e.allyChangeAllowed){var a,n=this.player,t=this.toPlayer,e=this.toggle;let i=n,s=t,r=this.game.alliances;if(!n.defeated&&r.canRequestAlliance(s)){let t=r.findByPlayers(i,s);t?t.status===Xh.Formed?e||(r.breakAlliance(i,s),this.game.onAllianceChange(t,i,!1)):t.status===Xh.Requested&&(t.players.first===s?e&&r.canFormAlliance(i,s)&&(r.acceptRequest(s,i),this.game.onAllianceChange(t,i,!0),1!==(n=this.game.getCombatants().filter(e=>e!==i&&!r.areAllied(i,e))).length||(a=r.findByPlayers(n[0],i))&&r.cancelRequest(a.players.first,a.players.second),1!==(a=this.game.getCombatants().filter(e=>e!==s&&!r.areAllied(s,e))).length||(a=r.findByPlayers(a[0],s))&&r.cancelRequest(a.players.first,a.players.second)):e||(r.cancelRequest(i,s),this.game.events.dispatch(new Gl(t,tl.Broken,i)),this.game.traits.filter(Jh).forEach(e=>{e[Jh.onChange](t,!1,this.game)}))):e&&r.canFormAlliance(i,s)&&((e=r.request(i,s))&&this.game.events.dispatch(new Gl(e,tl.Requested,i)))}}}}class gp{constructor(e){this.game=e}create(){return new pp(this.game)}}class mp extends ed{constructor(e){super(Xl.ActivateSuperWeapon),this.game=e}unserialize(e){let t=new v(e);this.superWeaponType=t.readUint8();e=t.readUint8();this.tile={x:t.readUint16(),y:t.readUint16()},this.tile2=2<e?{x:t.readUint16(),y:t.readUint16()}:void 0}serialize(){let e=new v(6+(this.tile2?4:0));return e.dynamicSize=!1,e.writeUint8(this.superWeaponType),e.writeUint8(this.tile2?4:2),e.writeUint16(this.tile.x),e.writeUint16(this.tile.y),this.tile2&&(e.writeUint16(this.tile2.x),e.writeUint16(this.tile2.y)),e.toUint8Array()}print(){return`Activate SuperW ${is[this.superWeaponType]} at tile (${this.tile.x}, ${this.tile.y})`+(this.tile2?`, (${this.tile2.x}, ${this.tile2.y})`:"")}process(){var e,t=this.player,i=this.game.map.tiles.getByMapCoords(this.tile.x,this.tile.y);i?(e=this.tile2?this.game.map.tiles.getByMapCoords(this.tile2.x,this.tile2.y):void 0,this.game.traits.get(ln).activateSuperWeapon(this.superWeaponType,t,this.game,i,e)):console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}}class fp{constructor(e){this.game=e}create(){return new mp(this.game)}}class yp{constructor(e,t){this.tile=e,this.player=t,this.type=ss.PingLocation}}class wp extends ed{constructor(e){super(Xl.PingLocation),this.game=e}unserialize(e){let t=new v(e);this.tile={x:t.readUint16(),y:t.readUint16()}}serialize(){let e=new v(4);return e.writeUint16(this.tile.x),e.writeUint16(this.tile.y),e.toUint8Array()}print(){return`Ping location at tile (${this.tile.x}, ${this.tile.y})`}process(){var e=this.player,t=this.game.map.tiles.getByMapCoords(this.tile.x,this.tile.y);if(t){this.game.events.dispatch(new yp(t,e));for(var i of[e,...this.game.alliances.getAllies(e)])this.game.events.dispatch(new xl(i,Qt.GenericNonCombat,t))}else console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}}class Tp{constructor(e){this.game=e}create(){return new wp(this.game)}}class bp{constructor(e){this.target=e,this.type=ss.PlayerResigned}}class vp extends ed{constructor(e){super(Xl.ObserveGame),this.game=e}process(){let e=this.player;var t;this.game.removeAllPlayerAssets(e),!e.isCombatant()||e.defeated||e.isObserver||(e.resigned=!0,e.defeated=!0,e.isObserver=!0,this.game.events.dispatch(new bp(e)),this.game.events.dispatch(new Wl(e)),this.game.mapShroudTrait.getPlayerShroud(e)?.revealAll(),t=e.radarTrait.isDisabled(),e.radarTrait.setDisabled(!1),t&&this.game.events.dispatch(new Bl(e,!0)))}}class Sp{constructor(e){this.game=e}create(){return new vp(this.game)}}class kp extends ed{constructor(e,t){super(Xl.ResignGame),this.game=e,this.localPlayerName=t}process(){if(this.localPlayerName!==this.player.name){let e=this.player;this.game.removeAllPlayerAssets(e),e.isCombatant()&&(e.resigned=!0,this.game.events.dispatch(new bp(e)))}}}class Op{constructor(e,t){this.game=e,this.localPlayerName=t}create(){return new kp(this.game,this.localPlayerName)}}(r=ic=ic||{})[r.SetGlobalDebugText=0]="SetGlobalDebugText",r[r.SetUnitDebugText=1]="SetUnitDebugText";class _p{constructor(e,t){this.type=e,this.params=t}}class Ip extends ed{constructor(e){super(Xl.DebugCommand),this.game=e}unserialize(e){let t=new v(e);e=t.readUint8();e===ic.SetUnitDebugText?this.command=new _p(e,{unitId:t.readUint32(),label:t.readCString()||void 0}):e===ic.SetGlobalDebugText?this.command=new _p(e,{text:t.readCString()}):console.warn(`Debug command ${e} not implemented`)}serialize(){let e=new v;if(e.writeUint8(this.command.type),this.command.type===ic.SetUnitDebugText){var t=this.command.params;e.writeUint32(t.unitId),e.writeCString(t.label||"")}else{if(this.command.type!==ic.SetGlobalDebugText)throw new Error(`Debug command ${this.command.type} not implemented`);t=this.command.params;e.writeCString(t.text)}return e.toUint8Array()}process(){if(this.command.type===ic.SetUnitDebugText){var{unitId:t,label:i}=this.command.params;if(this.game.getWorld().hasObjectId(t)){let e=this.game.getObjectById(t);e.isTechno()&&(e.debugLabel=i)}}else this.command.type===ic.SetGlobalDebugText?(i=this.command.params["text"],this.game.debugText.value=i):console.warn(`Debug command ${this.command.type} not implemented`)}}class Cp{constructor(e){this.game=e}create(){return new Ip(this.game)}}class Ap{register(e,t,i){var s=new Ju;e.registerFactory(Xl.NoAction,new id),e.registerFactory(Xl.PlaceBuilding,new nd(t)),e.registerFactory(Xl.SellBuilding,new hd(t)),e.registerFactory(Xl.ToggleRepair,new dp(t)),e.registerFactory(Xl.SelectUnits,new Id(t,s)),e.registerFactory(Xl.OrderUnits,new rp(t,t.map,s)),e.registerFactory(Xl.UpdateQueue,new np(t)),e.registerFactory(Xl.ToggleAlliance,new gp(t)),e.registerFactory(Xl.ActivateSuperWeapon,new fp(t)),e.registerFactory(Xl.PingLocation,new Tp(t)),e.registerFactory(Xl.DropPlayer,new lp(t,i)),e.registerFactory(Xl.ObserveGame,new Sp(t)),e.registerFactory(Xl.ResignGame,new Op(t,i)),e.registerFactory(Xl.DebugCommand,new Cp(t))}}class Bp{constructor(){this.detectors=new Set}[Qh.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.detect(e,t)}[Yh.onUnspawn](e,t){e.isTechno()&&(this.isGlobalDetector(e)&&(this.detectors.delete(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.undetect(e,t))}[Kh.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isDisguisable(e)&&(this.undetect(e,i),this.detect(e,i))}[Hr.onTileChange](e,t,i){this.isGlobalDetector(e)&&(this.updateAroundDetector(e,t,i),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&(this.undetect(e,t),this.detect(e,t))}[Ds.onPowerLow](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait&&!e.poweredTrait.isPoweredOn());this.updateAroundDetectors(i,e)}[Ds.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[Ds.onPowerChange](e,t){}updateAroundDetectors(e,t){let i=new Set;for(var s of e)for(var r of this.findTechnosAroundDetector(s,t,s.tile))i.add(r);for(var a of i)this.isDisguisable(a)&&(this.undetect(a,t),this.detect(a,t))}updateAroundDetector(e,t,i=e.tile){var s;for(s of this.findTechnosAroundDetector(e,t,i))this.isDisguisable(s)&&(this.undetect(s,t),this.detect(s,t))}findTechnosAroundDetector(e,t,i){var s=e.getFoundation(),s=Math.max(s.width,s.height),e=e.rules.detectDisguiseRange+s,s=new ks(i.rx,i.ry).addScalar(-e),e=new ks(i.rx,i.ry).addScalar(e);return t.map.technosByTile.queryRange(new jn(s,e))}detect(e,t){let i=new Set,s=new As(t.map.tileOccupation);for(var r of this.detectors)if(!t.areFriendly(r,e)){var a=r.owner,n=r.rules.detectDisguiseRange;if(!i.has(a))if(!(r.isBuilding()&&r.poweredTrait&&!r.poweredTrait.isPoweredOn())&&s.tileDistance(e,r.tile)<=n)for(var o of[a,...t.alliances.getAllies(a)])i.add(o)}for(var h of i)h.sharedDetectDisguiseTrait?.add(e)}undetect(e,t){for(var i of t.getCombatants())i.sharedDetectDisguiseTrait?.delete(e)}isGlobalDetector(e){return!(!e.isTechno()||!e.rules.detectDisguiseRange)}isDisguisable(e){return!(!e.isInfantry()&&!e.isVehicle()||!e.disguiseTrait)}}class xp{constructor(){this.detectors=new Set}[Qh.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isCloakable(e)&&this.detect(e,t)}[Yh.onUnspawn](e,t){e.isTechno()&&this.isGlobalDetector(e)&&this.detectors.delete(e)}[Kh.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isCloakable(e)&&this.detect(e,i)}[Hr.onTileChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,t),this.isCloakable(e)&&this.detect(e,t)}[$l.onAdd](e,t,i){e.isTechno()&&(t instanceof un?this.isCloakable(e)&&this.detect(e,i):t instanceof Eh&&this.isGlobalDetector(e)&&this.updateAroundDetector(e,i))}[Ds.onPowerLow](e,t){}[Ds.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[Ds.onPowerChange](e,t){}[Es.onTick](e){for(var t of e.getCombatants()){var i;for(i of t.getOwnedObjects())i.cloakableTrait&&!i.cloakableTrait.isCloaked()&&this.detect(i,e)}}updateAroundDetectors(e,t){let i=new Set;for(var s of e)for(var r of this.findTechnosAroundDetector(s,t))i.add(r);for(var a of i)this.isCloakable(a)&&this.detect(a,t)}updateAroundDetector(e,t){var i;for(i of this.findTechnosAroundDetector(e,t))this.isCloakable(i)&&this.detect(i,t)}findTechnosAroundDetector(e,t){var i=e.getFoundation(),s=Math.max(i.width,i.height),i=e.rules.sensorsSight+s,s=new ks(e.tile.rx,e.tile.ry).addScalar(-i),i=new ks(e.tile.rx,e.tile.ry).addScalar(i);return t.map.technosByTile.queryRange(new jn(s,i))}detect(e,t){let i=new As(t.map.tileOccupation);for(var s of this.detectors)if(!t.areFriendly(s,e)){var r=s.rules.sensorsSight;if(!(s.isBuilding()&&s.poweredTrait&&!s.poweredTrait.isPoweredOn())&&i.tileDistance(e,s.tile)<=r){r=e.cloakableTrait?.isCloaked();if(e.cloakableTrait.uncloak(t),r)for(var a of[s.owner,...t.alliances.getAllies(s.owner)])t.traits.get(El).addEventForPlayer(Qt.GenericNonCombat,a,e.tile,t);break}}}isGlobalDetector(e){return!(!e.isTechno()||!e.sensorsTrait&&!e.rules.sensorArray||!e.rules.sensorsSight)}isCloakable(e){return e.isTechno()&&!!e.cloakableTrait}}class Ep{constructor(){this.type=ss.StalemateDetect}}class Pp{constructor(){this.stale=!1,this.allPlayersCredits=new Map,this.resetCountdown()}isStale(){return this.stale}getCountdownTicks(){return this.countdownTicks}resetCountdown(){this.countdownTicks=Math.floor(60*Pp.graceMinutes*js.BASE_TICKS_PER_SECOND)}clearStale(){this.stale=!1,this.resetCountdown()}[Es.onTick](e){0<this.countdownTicks?this.countdownTicks--:this.stale||(this.stale=!0,this.resetCountdown(),e.events.dispatch(new Ep));for(var t of e.getCombatants()){var i=this.allPlayersCredits.get(t);i!==t.credits&&(this.allPlayersCredits.set(t,t.credits),t.credits>(i??0)&&t.production.hasAnyFactory()&&this.clearStale())}}[Sn.onProduce](){this.clearStale()}[Zl.onPlace](e){e.wallTrait||this.clearStale()}[el.onDestroy](e,t,i){!e.isBuilding()||e.owner.isNeutral||e.wallTrait||e.rules.insignificant||e.owner.defeated&&this.stale||i?.obj&&t.areFriendly(e,i.obj)||this.clearStale()}[Kh.onChange](e,t,i){e.isBuilding()&&!t.isNeutral&&(i.alliances.areAllied(e.owner,t)||this.clearStale())}}Pp.graceMinutes=10;class Np{constructor(e){this.prng=e}static factory(e,t){return new this(rc.factory(e,t))}generateColors(e){let t=[...e.humanPlayers,...e.aiPlayers].filter(ja),i=t.map(e=>e.colorId).filter(e=>-2!==e);e=Vn.length;let s=new Array(e).fill(0).map((e,t)=>t).filter(e=>!i.includes(e)),r=new Map;return t.forEach(e=>{if(-3!==e.countryId&&-2===e.colorId){if(s.length<1)throw new Error("Out of available colors to choose from");var t=this.prng.generateRandomInt(0,s.length-1);r.set(e,s[t]),s.splice(t,1)}}),r}generateCountries(e,t){let i=t.getMultiplayerCountries().length,s=[...e.humanPlayers,...e.aiPlayers].filter(ja),r=new Map;return s.forEach(e=>{-2===e.countryId&&r.set(e,this.prng.generateRandomInt(0,i-1))}),r}generateStartLocations(i,s){let e=[...i.humanPlayers,...i.aiPlayers].filter(ja),t=e.filter(e=>-2!==e.startPos).map(e=>e.startPos),r=[...s.keys()].filter(e=>!t.includes(e)),a=[];for(;r.length;){var n=r.length?this.prng.generateRandomInt(0,r.length-1):0;a.push(...r.splice(n,1))}if(a.unshift(...t),3<=a.length)for(var o of[1,2])if(!(t.length-1>=o)){let e=a.map(e=>s[e]),t=this.findFarthestPointFrom(e.slice(0,o),e.slice(o));var h=e.findIndex(e=>e.x===t.x&&e.y===t.y);a.splice(o,0,...a.splice(h,1))}if(4<=a.length)if(t.length-1<3){let e=a.map(e=>s[e]),t=this.findFarthestPointFrom(e.slice(2,3),e.slice(3));i=e.findIndex(e=>e.x===t.x&&e.y===t.y);a.splice(3,0,...a.splice(i,1))}a.splice(0,t.length);let l=new Map,c=-1;return e.forEach(e=>{if(-3!==e.countryId&&-2===e.startPos){if(c>=a.length-1)throw new RangeError("Map has fewer starting locations than players");l.set(e,a[++c])}}),l}findFarthestPointFrom(e,t){let s=e.map(e=>new ks(e.x,e.y)),r,a=0;if(!t.length)throw new Error("Search array must have at least one element");for(var n of t){let i=new ks(n.x,n.y);var o=s.reduce((e,t)=>e+i.distanceTo(t),0);o>=a&&(r=n,a=o)}return r}}class Mp{constructor(e,t){this.mapLighting=new Ti,this._onChange=new ao,this.ambientChangeRate=e.ambientChangeRate,this.ambientChangeStep=e.ambientChangeStep,t&&this.mapLighting.copy(t)}get onChange(){return this._onChange.asEvent()}setAmbientChangeRate(e){this.ambientChangeRate=e}setAmbientChangeStep(e){this.ambientChangeStep=e}setTargetAmbientIntensity(e){this.targetAmbient=e}getAmbient(){return this.mapLighting}[Es.onTick](){var e;void 0!==this.targetAmbient&&(this.ambientUpdateTicks??(this.ambientUpdateTicks=Math.floor(60*js.BASE_TICKS_PER_SECOND*this.ambientChangeRate)),this.ambientUpdateTicks<=0?(this.ambientUpdateTicks=void 0,e=this.mapLighting.ambient,(e=this.targetAmbient-e)?(e=Math.sign(e)*Math.min(this.ambientChangeStep,Math.abs(e)),this.mapLighting.ambient+=e,this._onChange.dispatch(this,this.mapLighting)):this.targetAmbient=void 0):this.ambientUpdateTicks--)}}class Dp{constructor(e){this.ini=e}getIni(){return this.ini}}var Rp,Lp,Fp=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},jp=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};class Up{constructor(e,t){this.name=e,this.country=t,Rp.set(this,!1)}setGameApi(e){this.gameApi=e}setActionsApi(e){this.actionsApi=e}setProductionApi(e){this.productionApi=e}setLogger(e){this.logger=e,this.logger.setDebugLevel(Fp(this,Rp,"f"))}setDebugMode(e){return jp(this,Rp,e,"f"),this.logger?.setDebugLevel(e),this}getDebugMode(){return Fp(this,Rp,"f")}onGameStart(e){}onGameTick(e){}onGameEvent(e,t){}}Rp=new WeakMap,(r=Lp=Lp||{})[r.Initial=0]="Initial",r[r.Deployed=1]="Deployed",r[r.Attacking=2]="Attacking",r[r.Defeated=3]="Defeated";class Wp extends Up{constructor(){super(...arguments),this.botState=Lp.Initial}onGameStart(t){var e=t.getTickRate();this.tickRatio=Math.ceil(e/5),this.enemyPlayers=t.getPlayers().filter(e=>e!==this.name&&!t.areAlliedPlayers(this.name,e))}onGameTick(e){if(e.getCurrentTick()%this.tickRatio==0)switch(this.botState){case Lp.Initial:{const i=e.getGeneralRules().baseUnit;if(e.getVisibleUnits(this.name,"self",e=>e.constructionYard).length){this.botState=Lp.Deployed;break}var t=e.getVisibleUnits(this.name,"self",e=>i.includes(e.name));t.length&&this.actionsApi.orderUnits([t[0]],Bn.DeploySelected);break}case Lp.Deployed:break;case Lp.Attacking:e.getVisibleUnits(this.name,"self",e=>e.isSelectableCombatant).length||(this.botState=Lp.Defeated,this.actionsApi.quitGame())}}}class zp{constructor(e){this.botsLib=e}create(e){if(!e.isAi)throw new Error(`Player "${e.name}" is not an AI`);switch(e.aiDifficulty){case Ss.Easy:return new Wp(e.name,e.country.name);case Ss.Medium:if(this.botsLib.SupalosaBot)return new this.botsLib.SupalosaBot(e.name,e.country.name);default:throw new Error(`Unsupported AI difficulty "${e.aiDifficulty}"`)}}}class Vp{constructor(){this.actions=[]}push(...e){this.actions.push(...e)}getLast(){return this.actions[this.actions.length-1]}dequeueAll(){var e=[...this.actions];return this.actions.length=0,e}dequeueLast(){return this.actions.pop()}clear(){this.actions.length=0}}var Hp=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},Gp=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class $p{constructor(e,t,i,s,r){Jp.add(this),Xp.set(this,void 0),Zp.set(this,void 0),Qp.set(this,void 0),Yp.set(this,void 0),Kp.set(this,void 0),Hp(this,Xp,t,"f"),Hp(this,Zp,i,"f"),Hp(this,Qp,e,"f"),Hp(this,Yp,s,"f"),Hp(this,Kp,r,"f")}placeBuilding(t,i,s){Gp(this,Jp,"m",eg).call(this,Xl.PlaceBuilding,e=>{e.buildingRules=Gp(this,Qp,"f").rules.getBuilding(t),e.tile={x:i,y:s}})}sellBuilding(t){Gp(this,Jp,"m",eg).call(this,Xl.SellBuilding,e=>{e.buildingId=t})}toggleRepairWrench(t){Gp(this,Jp,"m",eg).call(this,Xl.ToggleRepair,e=>{e.buildingId=t})}toggleAlliance(t,i){Gp(this,Jp,"m",eg).call(this,Xl.ToggleAlliance,e=>{e.toPlayer=Gp(this,Qp,"f").getPlayerByName(t),e.toggle=i})}pauseProduction(t){Gp(this,Jp,"m",eg).call(this,Xl.UpdateQueue,e=>{e.queueType=t,e.updateType=tc.Pause})}resumeProduction(t){Gp(this,Jp,"m",eg).call(this,Xl.UpdateQueue,e=>{e.queueType=t,e.updateType=tc.Resume})}queueForProduction(t,e,i,s){let r=Gp(this,Qp,"f").rules.getObject(e,i);Gp(this,Jp,"m",eg).call(this,Xl.UpdateQueue,e=>{e.queueType=t,e.updateType=tc.Add,e.item=r,e.quantity=s})}unqueueFromProduction(t,e,i,s){let r=Gp(this,Qp,"f").rules.getObject(e,i);Gp(this,Jp,"m",eg).call(this,Xl.UpdateQueue,e=>{e.queueType=t,e.updateType=tc.Cancel,e.item=r,e.quantity=s})}activateSuperWeapon(t,i,s){Gp(this,Jp,"m",eg).call(this,Xl.ActivateSuperWeapon,e=>{e.superWeaponType=t,e.tile={x:i.rx,y:i.ry},e.tile2=s?{x:s.rx,y:s.ry}:void 0})}orderUnits(t,i,s,r,a){Gp(this,Jp,"m",eg).call(this,Xl.SelectUnits,e=>{e.unitIds=t});let n;if(s){let e,t;if(r){e=void 0;var o=Gp(this,Qp,"f").map.tiles.getByMapCoords(s,r);if(!o)throw new Error(`No tile found at rx,ry=${s},${r}`);t=o,a&&(e=Gp(this,Qp,"f").map.tileOccupation.getBridgeOnTile(o))}else{if(!Gp(this,Qp,"f").getWorld().hasObjectId(s))return;e=Gp(this,Qp,"f").getObjectById(s),t=e.tile}n=Gp(this,Qp,"f").createTarget(e,t)}Gp(this,Jp,"m",eg).call(this,Xl.OrderUnits,e=>{e.orderType=i,e.target=n})}sayAll(e){Gp(this,Kp,"f")?.sayAll(Gp(this,Yp,"f").name,e)}setGlobalDebugText(t){Gp(this,Yp,"f").getDebugMode()&&Gp(this,Jp,"m",eg).call(this,Xl.DebugCommand,e=>{e.command=new _p(ic.SetGlobalDebugText,{text:t||""})})}setUnitDebugText(t,i){Gp(this,Yp,"f").getDebugMode()&&Gp(this,Jp,"m",eg).call(this,Xl.DebugCommand,e=>{e.command=new _p(ic.SetUnitDebugText,{unitId:t,label:i})})}quitGame(){Gp(this,Jp,"m",eg).call(this,Xl.ResignGame)}}var qp,Xp=new WeakMap,Zp=new WeakMap,Qp=new WeakMap,Yp=new WeakMap,Kp=new WeakMap,Jp=new WeakSet,eg=function(e,t){let i=Gp(this,Xp,"f").create(e);i.player=Gp(this,Qp,"f").getPlayerByName(Gp(this,Yp,"f").name),t?.(i),Gp(this,Zp,"f").push(i)},tg=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},ig=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};(r=qp=qp||{})[r.ObjectOwnerChange=0]="ObjectOwnerChange",r[r.ObjectSpawn=1]="ObjectSpawn",r[r.ObjectUnspawn=2]="ObjectUnspawn",r[r.ObjectDestroy=3]="ObjectDestroy";class sg{constructor(e){ng.add(this),rg.set(this,void 0),ag.set(this,[]),tg(this,rg,e,"f")}subscribe(e,t){let i=void 0,s;s="function"==typeof e?e:(i=e,t);t=ig(this,rg,"f").subscribe(e=>{e=ig(this,ng,"m",og).call(this,e);!e||void 0!==i&&i!==e.type||s(e)});return ig(this,ag,"f").push(t),t}dispose(){for(var e of ig(this,ag,"f"))e();ig(this,ag,"f").length=0}}var rg=new WeakMap,ag=new WeakMap,ng=new WeakSet,og=function(t){switch(t.type){case ss.ObjectOwnerChange:return{type:qp.ObjectOwnerChange,prevOwnerName:t.prevOwner.name,newOwnerName:t.target.owner.name,target:t.target.id};case ss.ObjectSpawn:return{type:qp.ObjectSpawn,target:t.gameObject.id};case ss.ObjectUnspawn:return{type:qp.ObjectUnspawn,target:t.gameObject.id};case ss.ObjectDestroy:{let e=t;return e.target.isProjectile()?void 0:{type:qp.ObjectDestroy,target:e.target.id,attackerInfo:e.attackerInfo?{playerName:e.attackerInfo.player.name,objId:e.attackerInfo.obj?.id,weaponName:e.attackerInfo.weapon?.rules.name}:void 0}}default:return}},hg=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},lg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class cg{constructor(e){pg.add(this),ug.set(this,void 0),dg.set(this,void 0),hg(this,ug,e,"f"),hg(this,dg,e.map,"f")}getRealMapSize(){return lg(this,dg,"f").tiles.getMapSize()}getStartingLocations(){return lg(this,dg,"f").startingLocations.map(e=>new ks(e.x,e.y))}getTheaterType(){return lg(this,dg,"f").getTheaterType()}getTile(e,t){t=lg(this,dg,"f").tiles.getByMapCoords(e,t);if(t&&lg(this,dg,"f").mapBounds.isWithinBounds(t))return t}getTilesInRect(e,t){let i=t?lg(this,dg,"f").tiles.getInRectangle(e,t):lg(this,dg,"f").tiles.getInRectangle(e);return i.filter(e=>lg(this,dg,"f").mapBounds.isWithinBounds(e))}getObjectsOnTile(e){return lg(this,dg,"f").getObjectsOnTile(e).map(e=>e.id)}hasBridgeOnTile(e){return!!e.onBridgeLandType}hasHighBridgeOnTile(e){return!!lg(this,dg,"f").tileOccupation.getBridgeOnTile(e)?.isHighBridge()}isPassableTile(e,t,i){return 0<lg(this,dg,"f").terrain.getPassableSpeed(e,t,i)}findPath(e,t,i,s){let r=lg(this,ug,"f").map.terrain.computePath(e,t.tile,t.onBridge,i.tile,i.onBridge,{bestEffort:s?.bestEffort,excludeTiles:s?.excludeNodes?e=>s.excludeNodes({tile:e.tile,onBridge:!!e.onBridge}):void 0,maxExpandedNodes:s?.maxExpandedNodes});return r.map(e=>({tile:e.tile,onBridge:!!e.onBridge}))}isVisibleTile(e,t,i=0){var s=lg(this,ug,"f").getPlayerByName(t);if(!s)throw new Error(`Player "${t}" doesn't exist`);return!lg(this,ug,"f").mapShroudTrait.getPlayerShroud(s)?.isShrouded(e,i)}getTileResourceData(e){e=lg(this,dg,"f").getObjectsOnTile(e).find(e=>e.isOverlay()&&e.isTiberium()||e.isTerrain()&&e.rules.spawnsTiberium);return e?lg(this,pg,"m",gg).call(this,e):void 0}getAllTilesResourceData(){var e;let t=[];for(e of lg(this,ug,"f").getWorld().getAllObjects()){var i=lg(this,pg,"m",gg).call(this,e);i&&t.push(i)}return t}}var ug=new WeakMap,dg=new WeakMap,pg=new WeakSet,gg=function(t){let i;if(t.isOverlay()&&t.isTiberium()){let e=t.traits.get(Xa);var s=e.getTiberiumType(),r=e.getBailCount();i={tile:t.tile,ore:s===ha.Ore?r:0,gems:s===ha.Gems?r:0,spawnsOre:!1}}else t.isTerrain()&&t.rules.spawnsTiberium&&(i={tile:t.tile,ore:0,gems:0,spawnsOre:!0});return i},mg=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},fg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class yg{constructor(e){wg.set(this,void 0),mg(this,wg,e,"f")}get allObjectRules(){return fg(this,wg,"f").allObjectRules}get buildingRules(){return fg(this,wg,"f").buildingRules}get infantryRules(){return fg(this,wg,"f").infantryRules}get vehicleRules(){return fg(this,wg,"f").vehicleRules}get aircraftRules(){return fg(this,wg,"f").aircraftRules}get terrainRules(){return fg(this,wg,"f").terrainRules}get overlayRules(){return fg(this,wg,"f").overlayRules}get countryRules(){return fg(this,wg,"f").countryRules}get general(){return fg(this,wg,"f").general}get ai(){return fg(this,wg,"f").ai}get crateRules(){return fg(this,wg,"f").crateRules}get combatDamage(){return fg(this,wg,"f").combatDamage}get radiation(){return fg(this,wg,"f").radiation}hasObject(e,t){return fg(this,wg,"f").hasObject(e,t)}getObject(e,t){return fg(this,wg,"f").getObject(e,t)}getBuilding(e){return fg(this,wg,"f").getBuilding(e)}getWeapon(e){return fg(this,wg,"f").getWeapon(e)}getWarhead(e){return fg(this,wg,"f").getWarhead(e)}getProjectile(e){return fg(this,wg,"f").getProjectile(e)}getOverlayName(e){return fg(this,wg,"f").getOverlayName(e)}getOverlayId(e){return fg(this,wg,"f").getOverlayId(e)}getOverlay(e){return fg(this,wg,"f").getOverlay(e)}getCountry(e){return fg(this,wg,"f").getCountry(e)}getMultiplayerCountries(){return fg(this,wg,"f").getMultiplayerCountries()}getIni(){return fg(this,wg,"f").getIni()}}var wg=new WeakMap,Tg=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},bg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class vg{constructor(e,t){Og.add(this),Sg.set(this,void 0),kg.set(this,void 0),Tg(this,Sg,e,"f"),Tg(this,kg,t,"f"),this.mapApi=new cg(e),this.rulesApi=new yg(e.rules)}isPlayerDefeated(e){return bg(this,Sg,"f").getPlayerByName(e).defeated}areAlliedPlayers(e,t){var i=bg(this,Sg,"f").getPlayerByName(e);if(!i)throw new Error(`Player "${e}" doesn't exist`);e=bg(this,Sg,"f").getPlayerByName(t);if(!e)throw new Error(`Player "${t}" doesn't exist`);return bg(this,Sg,"f").alliances.areAllied(i,e)}canPlaceBuilding(e,t,i){var s=bg(this,Sg,"f").getPlayerByName(e);if(!s)throw new Error(`Player "${e}" doesn't exist`);return bg(this,Sg,"f").getConstructionWorker(s).canPlaceAt(t,i,{normalizedTile:!0})}getBuildingPlacementData(e){e=bg(this,Sg,"f").art.getObject(e,xt.Building);return{foundation:e.foundation,foundationCenter:e.foundationCenter}}getPlayers(){return bg(this,Sg,"f").getNonNeutralPlayers().map(e=>e.name)}getPlayerData(e){let t=bg(this,Sg,"f").getPlayerByName(e);if(!t)throw new Error(`Player "${e}" doesn't exist`);return{name:t.name,country:t.country,startLocation:this.mapApi.getStartingLocations()[t.startLocation],isObserver:t.isObserver,isAi:t.isAi,isCombatant:t.isCombatant(),credits:t.credits,power:{total:t.powerTrait?.power??0,drain:t.powerTrait?.drain??0,isLowPower:t.powerTrait?.level===mn.Low},radarDisabled:!!t.radarTrait?.isDisabled()}}getAllTerrainObjects(){return bg(this,Sg,"f").getWorld().getAllObjects().filter(e=>e.isTerrain()).map(e=>e.id)}getAllUnits(t=()=>!0){return bg(this,Sg,"f").getWorld().getAllObjects().filter(e=>e.isTechno()&&t(e.rules)).map(e=>e.id)}getNeutralUnits(t=()=>!0){return bg(this,Sg,"f").getCivilianPlayer().getOwnedObjects().filter(e=>t(e.rules)).map(e=>e.id)}getUnitsInArea(e){return bg(this,Sg,"f").map.technosByTile.queryRange(e).map(e=>e.id)}getVisibleUnits(e,s,t=()=>!0){const r=bg(this,Sg,"f").getPlayerByName(e);if(!r)throw new Error(`Player "${e}" doesn't exist`);if("self"===s)return r.getOwnedObjects().filter(e=>t(e.rules)).map(e=>e.id);let a;if("allied"===s)a=e=>e.owner===r||bg(this,Sg,"f").alliances.areAllied(e.owner,r);else{if("hostile"!==s&&"enemy"!==s)throw new Error(`Unexpected type ${s}`);{let i=bg(this,Sg,"f").mapShroudTrait.getPlayerShroud(r);a=t=>bg(this,Sg,"f").map.tileOccupation.calculateTilesForGameObject(t.tile,t).some(e=>!i?.isShrouded(e,t.tileElevation))&&t.owner!==r&&!bg(this,Sg,"f").alliances.areAllied(t.owner,r)&&("enemy"!==s||t.owner.isCombatant())}}return bg(this,Sg,"f").getWorld().getAllObjects().filter(e=>e.isTechno()&&!e.isDestroyed&&a(e)&&t(e.rules)).map(e=>e.id)}getGameObjectData(t){if(bg(this,Sg,"f").getWorld().hasObjectId(t)){let e=bg(this,Sg,"f").getObjectById(t);return{id:e.id,type:e.type,name:e.name,rules:e.rules,tile:e.tile,tileElevation:e.tileElevation,worldPosition:e.position.worldPosition.clone(),foundation:e.getFoundation(),hitPoints:e.healthTrait?.getHitPoints(),maxHitPoints:e.healthTrait?.maxHitPoints,owner:e.isTechno()?e.owner.name:void 0}}}getUnitData(t){var i=this.getGameObjectData(t);if(i){let e=bg(this,Sg,"f").getObjectById(t);if(!e.isTechno())throw new Error(`Game object with id ${t} is not a Techno type`);return{...i,owner:e.owner.name,sight:e.sight,veteranLevel:e.veteranLevel,guardMode:e.guardMode,purchaseValue:e.purchaseValue,primaryWeapon:e.primaryWeapon?bg(this,Og,"m",_g).call(this,e.primaryWeapon):void 0,secondaryWeapon:e.secondaryWeapon?bg(this,Og,"m",_g).call(this,e.secondaryWeapon):void 0,deathWeapon:e.armedTrait?.deathWeapon?bg(this,Og,"m",_g).call(this,e.armedTrait.deathWeapon):void 0,attackState:e.attackTrait?.attackState,direction:e.direction,onBridge:e.isInfantry()||e.isVehicle()?e.onBridge:void 0,zone:e.isUnit()?e.zone:void 0,buildStatus:e.isBuilding()?e.buildStatus:void 0,factory:e.isBuilding()&&e.factoryTrait?{deliveringUnit:e.factoryTrait.deliveringUnit?.id,status:e.factoryTrait.status}:void 0,rallyPoint:e.isBuilding()?e.rallyTrait?.getRallyPoint():void 0,isPoweredOn:e.isBuilding()&&e.poweredTrait?.isPoweredOn(),hasWrenchRepair:e.isBuilding()&&!e.autoRepairTrait.isDisabled(),turretFacing:e.isBuilding()||e.isVehicle()?e.turretTrait?.facing:void 0,turretNo:e.isVehicle()?e.turretNo:void 0,garrisonUnitCount:e.isBuilding()?e.garrisonTrait?.units.length:void 0,garrisonUnitsMax:e.isBuilding()?e.garrisonTrait?.maxOccupants:void 0,passengerSlotCount:e.isVehicle()?e.transportTrait?.getOccupiedCapacity():void 0,passengerSlotMax:e.isVehicle()?e.transportTrait?.getMaxCapacity():void 0,isIdle:!e.unitOrderTrait.hasTasks(),canMove:e.isUnit()?!e.moveTrait.isDisabled():void 0,velocity:e.isUnit()?e.moveTrait.velocity.clone():void 0,stance:e.isInfantry()?e.stance:void 0,harvestedOre:e.isVehicle()?e.harvesterTrait?.ore:void 0,harvestedGems:e.isVehicle()?e.harvesterTrait?.gems:void 0,ammo:e.isAircraft()?e.ammo:void 0,isWarpedOut:e.warpedOutTrait.isActive(),mindControlledBy:e.mindControllableTrait?.getController()?.id,tntTimer:e.tntChargeTrait?.getTicksLeft()}}}getAllSuperWeaponData(){return bg(this,Sg,"f").getCombatants().map(t=>t.superWeaponsTrait.getAll().map(e=>({playerName:t.name,type:e.rules.type,status:e.status,timerSeconds:e.getTimerSeconds()}))).flat()}getGeneralRules(){return bg(this,Sg,"f").rules.general}getRulesIni(){return bg(this,Sg,"f").rules.getIni()}getArtIni(){return bg(this,Sg,"f").art.getIni()}getAiIni(){return bg(this,Sg,"f").ai.getIni()}generateRandomInt(e,t){if(bg(this,kg,"f"))return bg(this,Sg,"f").generateRandomInt(e,t);var i=this.generateRandom();return Math.round(i*(t-e))+e}generateRandom(){return bg(this,kg,"f")?bg(this,Sg,"f").generateRandom():Math.random()}getTickRate(){return bg(this,Sg,"f").speed.value*js.BASE_TICKS_PER_SECOND}getBaseTickRate(){return js.BASE_TICKS_PER_SECOND}getCurrentTick(){return bg(this,Sg,"f").currentTick}getCurrentTime(){return bg(this,Sg,"f").currentTime/1e3}}var Sg=new WeakMap,kg=new WeakMap,Og=new WeakSet,_g=function(e){return{type:e.type,rules:e.rules,projectileRules:e.projectileRules,warheadRules:e.warhead.rules,minRange:e.minRange,maxRange:e.range,speed:e.speed,cooldownTicks:e.getCooldownTicks()}},Ig=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},Cg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Ag{constructor(e,t){Mg.add(this),Pg.set(this,void 0),Ng.set(this,void 0),Ig(this,Pg,e,"f"),Ig(this,Ng,t,"f")}setDebugLevel(e){Cg(this,Pg,"f").setLevel(e?wr.DEBUG:wr.WARN)}debug(...e){Cg(this,Pg,"f").debug(Cg(this,Mg,"m",Dg).call(this),...e)}info(...e){Cg(this,Pg,"f").info(Cg(this,Mg,"m",Dg).call(this),...e)}log(...e){Cg(this,Pg,"f").log(Cg(this,Mg,"m",Dg).call(this),...e)}warn(...e){Cg(this,Pg,"f").warn(Cg(this,Mg,"m",Dg).call(this),...e)}error(...e){Cg(this,Pg,"f").error(Cg(this,Mg,"m",Dg).call(this),...e)}time(e){Cg(this,Pg,"f").time(e)}timeEnd(e){Cg(this,Pg,"f").timeEnd(e)}}var Bg,xg,Eg,Pg=new WeakMap,Ng=new WeakMap,Mg=new WeakSet,Dg=function(){return"["+function(e,t=!1){var i=Math.floor(e/3600);e-=3600*i;var s=Math.floor(e/60),e=e-=60*s;return[...i||!t?[i]:[],M(s,"00"),M(e,"00")].join(":")}(Math.floor(Cg(this,Ng,"f").getCurrentTime()))+"]"},Rg=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},Lg=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Fg{constructor(e){Bg.set(this,void 0),Rg(this,Bg,e,"f")}isAvailableForProduction(e){return Lg(this,Bg,"f").isAvailableForProduction(e)}getAvailableObjects(t){let e=Lg(this,Bg,"f").getAvailableObjects();return void 0!==t&&(e=e.filter(e=>this.getQueueTypeForObject(e)===t)),e}getQueueTypeForObject(e){return Lg(this,Bg,"f").getQueueTypeForObject(e)}getQueueData(e){let t=Lg(this,Bg,"f").getQueue(e);return{size:t.currentSize,maxSize:t.maxSize,status:t.status,type:t.type,items:t.getAll().map(e=>({rules:e.rules,quantity:e.quantity}))}}}Bg=new WeakMap;class jg{constructor(e,t,i,s,r,a){this.game=e,this.inputActions=t,this.replayRecorder=i,this.actionSerializer=s,this.actionFactory=r,this.actionLogger=a,this.errorState=!1}init(){this.gameTurnMillis=1e3/(this.game.speed.value*js.BASE_TICKS_PER_SECOND)}setErrorState(){this.errorState=!0}getErrorState(){return this.errorState}getTurnMillis(){return this.gameTurnMillis}doGameTurn(){if(!this.errorState){if(this.game.status!==ql.Ended){var t,e=this.inputActions.dequeueAll();const s=new Map;for(t of e){var i=this.actionSerializer.getActionPayload(t);let e=s.get(t.player);e||(e=[],s.set(t.player,e)),e.push(i)}this.replayRecorder.recordActions(this.game.currentTick,new Map([...s].map(([e,t])=>[this.game.getPlayerNumber(e),t]))),s.forEach((t,i)=>{if(!t.length){let e=new td;e.player=i,t.push(this.actionSerializer.getActionPayload(e))}}),this.processActions(s)}this.game.update()}}processActions(e){[...e].forEach(([i,e])=>e.forEach(e=>{let t=this.actionFactory.create(e.id);t.player=i,t.unserialize(e.params),t.process();e=t.print();e&&this.actionLogger?.debug(`(${i.name})@${this.game.currentTick}: ${e}`)}))}dispose(){}}(r=xg=xg||{})[r.Closed=0]="Closed",r[r.Open=1]="Open",r[r.OpenObserver=2]="OpenObserver",r[r.Player=3]="Player",r[r.Ai=4]="Ai";class Ug{encode(e){let s=[],r=0;return e.split("").forEach((e,t)=>{var i=e.charCodeAt(0)<<2*t-7*r,e=127&i,t=i>>7&127,i=i>>14&127;i&&r++,s.push(e,t),i&&s.push(i)}),s.push(0,0),2<=e.length&&s.push(0),s=s.map(e=>128^e),s.map(e=>String.fromCharCode(e)).join("")}decode(e){let i=e.split("").map(e=>e.charCodeAt(0));for(i=i.map(e=>128^e);0===i[i.length-1];)i.pop();let s=[],r=0,a=0;for(;i.length;){var n=s.length,o=i.shift(),h=i.shift();let e=0,t=!1;(-1!==[1,2,3].indexOf(i[0])||n>r+3)&&(e=i.shift(),r=n,t=!0);n=(e<<14|h<<7|o)>>2*n-7*a;s.push(127&n),t&&a++}return s.map(e=>String.fromCharCode(e)).join("")}}class Wg{encode(e){return e.match(/^[a-z0-9-_]+\.[a-z]{3}$/i)?e:N.encode(j(e))}decode(e){return e.match(/\.[a-z]{3}$/i)?e:U(N.decode(e))}}class zg{serializeOptions(e,t=!1){let i=e.gameMode,s=t?(new Ug).encode(e.mapTitle):N.encode(j(e.mapTitle)),r=(new Wg).encode(e.mapName);t=["0","0",6-e.gameSpeed,e.credits,e.unitCount,Number(e.shortGame),Number(e.superWeapons),Number(e.buildOffAlly),Number(e.mcvRepacks),Number(e.cratesAppear),i,Number(e.hostTeams??!1),s,e.maxSlots,Number(e.mapOfficial),e.mapSizeBytes,r,e.mapDigest].join(",");return`${t}:${e.humanPlayers.map(e=>`${e.name},${e.countryId},${e.colorId},${e.startPos},${e.teamId},0,0,0`).join(",")}:@:${this.serializeAiOpts(e.aiPlayers)},`}serializeAiOpts(e){return e.map(e=>e?`${e.difficulty},${e.countryId},${e.colorId},${e.startPos},${e.teamId}`:"0,-1,-1,-1,-1").join(",")}serializePingData(e){return e.length+","+e.map(e=>`${e.playerName},${e.ping}`).join(",")}serializeSlotData(e){return e.map(e=>{if(e.type===xg.Closed)return"@Closed@";if(e.type===xg.Open)return"@Open@";if(e.type===xg.OpenObserver)return"@OpenObserver@";if(e.type===xg.Ai){if(e.difficulty===Ss.Easy)return"@EasyAI@";if(e.difficulty===Ss.Medium)return"@MediumAI@";if(e.difficulty===Ss.Brutal)return"@HardAI@"}else if(e.type===xg.Player)return e.name;throw new Error(`Unexpected slot info with type ${xg[e.type]}`)}).join(",")+","}serializeLoadInfo(e){return e.map(e=>[e.name,e.status,e.loadPercent,e.ping,e.lagAllowanceMillis].join(",")).join(",")}serializePlayerActions(e){let t=new v;t.writeUint8(e.length);for(var{id:i,params:s}of e)if(t.writeUint8(i),t.writeUint16(s.byteLength),0<s.byteLength){if(s.byteLength>zg.MAX_ACTION_PAYLOAD_SIZE-t.position)throw console.error(`Action #${i} payload exceeds max data size`,s),new RangeError("Maximum payload data size exceeded");t.writeUint8Array(s)}return t.toUint8Array()}serializeAllPlayerActions(e,t){e.writeUint8(t.size);for(var[i,s]of t){e.writeUint8(i);var r=this.serializePlayerActions(s);if(e.writeUint16(r.byteLength),0<r.byteLength){if(r.byteLength>zg.MAX_ACTION_PAYLOAD_SIZE)throw console.error(`Player #${i} actions payload exceeds max data size`,s),new RangeError("Maximum payload data size exceeded");e.writeUint8Array(r)}}}serializeMapData(e){return R(e)}}zg.MAX_ACTION_PAYLOAD_SIZE=65536;class Vg{parseOptions(e){let t={},[i,s,,r]=e.split(":"),a=i.split(",");a.shift(),a.shift(),t.gameSpeed=6-Number(a.shift()),t.credits=Number(a.shift()),t.unitCount=Number(a.shift()),t.shortGame=Boolean(Number(a.shift())),t.superWeapons=Boolean(Number(a.shift())),t.buildOffAlly=Boolean(Number(a.shift())),t.mcvRepacks=Boolean(Number(a.shift())),t.cratesAppear=Boolean(Number(a.shift())),t.gameMode=Number(a.shift()),t.hostTeams=Boolean(Number(a.shift()));e=a.shift();return t.mapTitle=N.isBase64(e)?U(N.decode(e)):(new Ug).decode(e),t.maxSlots=Number(a.shift()),t.mapOfficial=Boolean(Number(a.shift())),t.mapSizeBytes=Number(a.shift()),t.mapName=(new Wg).decode(a.shift()),t.mapDigest=a.shift(),t.humanPlayers=this.parsePlayerOpts(s),t.aiPlayers=this.parseAiOpts(r?.slice(0,-1)),t}parsePlayerOpts(e){var i=e.split(",");if(i.length%8!=0)throw new Error(`Couldn't parse gameopt: unexpected players data length ${i.length}`);let s=[];for(let e=0,t=Math.floor(i.length/8);e<t;++e){var r={name:i[8*e],countryId:Number(i[8*e+1]),colorId:Number(i[8*e+2]),startPos:Number(i[8*e+3]),teamId:Number(i[8*e+4])};s.push(r)}return s}parseAiOpts(e){let i=[];if(e){var s=e.split(",");if(s.length%5!=0)throw new Error(`Couldn't parse gameopt: unexpected ai data length ${s.length}`);for(let e=0,t=Math.floor(s.length/5);e<t;++e){var r={difficulty:Number(s[5*e]),countryId:Number(s[5*e+1]),colorId:Number(s[5*e+2]),startPos:Number(s[5*e+3]),teamId:Number(s[5*e+4])};i.push(-1!==r.countryId?r:void 0)}}return i}parseTopic(e){var t=e.split(",");if(!(t.length<6)){var i=t[0],s=Number(t[1]),r=i[2],a=t[2],n=t[3],e=t[4],i=(new Wg).decode(t[5]);return{description:t[6]?U(N.decode(t[6])):"",modHash:s,modName:t[7]?U(N.decode(t[7])):void 0,aiPlayers:Number(a),maxPlayers:Number(r),observers:Number(n),observable:Boolean(Number(e)),mapName:i}}}parsePingData(e){var i=e.split(",").slice(1);if(i.length%2)throw new Error(`Couldn't parse gameopt: unexpected ping data length ${i.length}`);let s=[];for(let e=0,t=Math.floor(i.length/2);e<t;++e)s.push({playerName:i[2*e],ping:Number(i[2*e+1])});return s}parseSlotData(e){var i;let s=[];for(i of e.slice(1,-1).split(",")){let t={};if("@Closed@"===i)t.type=xg.Closed;else if("@Open@"===i)t.type=xg.Open;else if("@OpenObserver@"===i)t.type=xg.OpenObserver;else if(-1!==["@EasyAI@","@MediumAI@","@HardAI@"].indexOf(i)){t.type=xg.Ai;let e;if("@EasyAI@"===i)e=Ss.Easy;else if("@MediumAI@"===i)e=Ss.Medium;else{if("@HardAI@"!==i)throw new Error(`Couldn't parse gameopt: unknown slot type ${i}`);e=Ss.Brutal}t.difficulty=e}else t.type=xg.Player,t.name=i;s.push(t)}return s}parsePlayerActions(e){let t=new v(e);var i=t.readUint8();let s=[];for(let e=0;e<i;++e){var r=t.readUint8(),a=t.readUint16(),a=0<a?t.readUint8Array(a):new Uint8Array;s.push({id:r,params:a})}return s}parseAllPlayerActions(t){var i=t.readUint8();let s=new Map;for(let e=0;e<i;++e){var r=t.readUint8(),a=t.readUint16(),a=0<a?t.readUint8Array(a):new Uint8Array,a=this.parsePlayerActions(a);s.set(r,a)}return s}parseMapData(e){return F(e)}}class Hg{constructor(e,t){this.type=e,this.tickNo=t}}(r=Eg=Eg||{})[r.TurnActions=0]="TurnActions",r[r.ChatMessage=1]="ChatMessage",r[r.Taunt=2]="Taunt";class Gg extends Hg{constructor(e){super(Eg.ChatMessage,e)}serialize(){return this.payload.playerId+":"+N.encode(j(this.payload.message))}unserialize(e){var[t,e]=e.split(":"),t=Number(t),e=U(N.decode(e));this.payload={playerId:t,message:e}}}class $g extends Hg{constructor(e){super(Eg.Taunt,e)}serialize(){return this.payload.playerId+":"+this.payload.tauntNo}unserialize(e){var[t,e]=e.split(":"),t=Number(t),e=Number(e);this.payload={playerId:t,tauntNo:e}}}class qg extends Hg{constructor(e,t,i){super(Eg.TurnActions,i),this.gameOptsParser=e,this.gameOptsSerializer=t}serialize(){let e=new v;return this.gameOptsSerializer.serializeAllPlayerActions(e,new Map(this.payload)),t=e.toUint8Array(),N.encode(F(t));var t}unserialize(e){e=new v(L(e)),e=this.gameOptsParser.parseAllPlayerActions(e);this.payload=[...e]}}class Xg{constructor(e,t){this.gameOptsParser=e,this.gameOptsSerializer=t}create(e,t){switch(e){case Eg.TurnActions:return new qg(this.gameOptsParser,this.gameOptsSerializer,t);case Eg.ChatMessage:return new Gg(t);case Eg.Taunt:return new $g(t);default:throw new Error(`Unsupported replay event type "${e}" at game tick "${t}"`)}}}const Zg=[5,6];class Qg{constructor(){this.name="",this.events=[]}static sanitizeFileName(e,t="_"){return e.replace(/[\/\?<>\\:\*\|"]/g,t).replace(/[\x00-\x1f\x7f\x80-\x9f]/g,t).slice(0,this.maxNameLength)}init(e,t,i,s,r){this.gameId=e,this.gameTimestamp=t,this.gameOpts=i,this.engineVersion=s,this.modHash=r,this.name=Qg.sanitizeFileName(this.gameOpts.mapTitle+" "+(new Date).toISOString().replace(/(\.|,)\d+Z$/,"Z")),this.timestamp=Date.now()}writeEvent(...e){this.events.push(...e)}finish(e){this.endTick=e}getEvents(){return this.events}*flush(){if(!this.gameOpts)throw new Error("Game options must be set first");if(!this.engineVersion)throw new Error("Engine version is not set");if(void 0===this.modHash)throw new Error("Mod hash is not set");let e=new zg,t=this.getHeaderTag()+"\n";for(t+=`ENGINE ${this.engineVersion} ${this.modHash}\n`,t+=[this.gameId,this.gameTimestamp,e.serializeOptions(this.gameOpts)].join(" ")+"\n",yield t,t="";void 0===this.endTick||this.events.length;){for(var i of this.events)t+=i.tickNo+"="+i.type+"|"+i.serialize()+"\n";this.events.length=0,yield t,t=""}t+=this.getEndTag()+" "+this.endTick+"\n",this.debugInfo&&(t+=N.encode(j(this.debugInfo))+"\n"),yield t}serialize(){if(void 0===this.endTick)throw new Error("Replay is not finished");let e="";var t,i=this.events.slice();for(t of this.flush())e+=t;return this.events=i,e}async parseHeader(e){let t=0,i,s,r,a,n,o;var h;for await(h of"string"==typeof e?e.split("\n"):async function*(e){const t=new TextDecoder("utf-8");let i=e.stream().getReader(),{value:s,done:r}=await i.read();s=s?t.decode(s,{stream:!0}):"";let a=/\r\n|\n|\r/gm,n=0;for(;;){var o=a.exec(s);if(o)yield s.substring(n,o.index),n=a.lastIndex;else{if(r)break;o=s.substr(n);({value:s,done:r}=await i.read()),s=o+(s?t.decode(s,{stream:!0}):""),n=a.lastIndex=0}}n<s.length&&(yield s.substr(n))}(e)){if(0===t)i=this.readReplayVersion(h);else if(1===t){if(!h.match(Qg.engineLineRegex))throw new Error("Missing or invalid game engine version line");var l=h.split(" ");s=l[1],r=Number(i<4?"0":l[2])}else{if(2!==t)break;if(!h.match(/^([a-zA-Z0-9-]+) \d+ .*$/))throw new Error("Missing or invalid game id/time/opts line");var[c,u,l]=h.split(" ");a=c,n=Number(u),o=i<6?N.decode(l):l}t++}if(t<3)throw new Error("Bad replay header");return{replayVersion:i,engineVersion:s,modHash:r,gameId:a,gameTimestamp:n,gameOptsSerialized:o}}unserialize(e,t){let i=e.split("\n");var s=this.readReplayVersion(i.shift()||"");if(!Zg.includes(s))throw new Error(`Unsupported replay version ${s}`);let r=new Vg,a=i.shift();if(!a||!a.match(Qg.engineLineRegex))throw new Error("Missing or invalid game engine version line");var[,n,o]=a.split(" ");let h=i.shift();if(!h)throw new Error("Missing game id/time/opts line");e=h.match(/^([a-zA-Z0-9-]+) (\d+) (.*)$/);if(!e)throw new Error("Invalid game id/time/opts line");let[,l,c,u]=e;s<6&&(u=N.decode(u));s=r.parseOptions(u);this.init(l,Number(c),s,n,Number(o)),this.name=t.name,this.timestamp=t.timestamp;let d,p=!1;for(;d=i.shift();){if(d.startsWith(this.getEndTag())){p=!0;break}var g=d.match(/^(\d+)=(\d+)\|(.+)$/);if(!g)throw new Error(`Invalid event line "${d}"`);var[,m,f,g]=g,m=Number(m),f=Number(f);let e=new Xg(r,new zg).create(f,m);e.unserialize(g),this.writeEvent(e)}if(!p)throw new Error("Incomplete replay data");t=d.match(new RegExp(`^${this.getEndTag()} (\\d+)$`));if(!t)throw new Error("Invalid end tag");this.endTick=Number(t[1]),1<=i.length&&(this.debugInfo=U(N.decode(i[0])))}getHeaderTag(){return"RA2TSREPL_v6"}readReplayVersion(e){e=e.match(/^RA2TSREPL_v(\d+)$/);if(!e||e.length<2)throw new Error("Unknown replay format");return Number(e[1])}getEndTag(){return"END"}}Qg.extension=".rpl",Qg.maxNameLength=128,Qg.engineLineRegex=/^ENGINE \d+\.\d+( \d+)?$/;class Yg{constructor(e,t,i,s){this.replay=e,this.playerId=t,this.humanPlayers=i,this.actionSerializer=s}recordActions(t,i){if(Array.isArray(i)){let e=new qg(new Vg,new zg,t);e.payload=[[this.playerId,i.map(e=>this.actionSerializer.getActionPayload(e))]],this.replay.writeEvent(e)}else if(this.hasActualActions(i)){let e=new qg(new Vg,new zg,t);e.payload=[...i].map(([e,t])=>[e,t]),this.replay.writeEvent(e)}}recordChatMessage(e,t,i){let s=new Gg(e);s.payload={playerId:this.humanPlayers.findIndex(e=>e.name===t),message:i},this.replay.writeEvent(s)}recordTaunt(e,t,i){let s=new $g(e);s.payload={playerId:this.humanPlayers.findIndex(e=>e.name===t),tauntNo:i},this.replay.writeEvent(s)}hasActualActions(e){return!![...e.values()].find(e=>e.find(e=>e.id!==Xl.NoAction))}}class Kg{getActionPayload(e){return{id:e.actionType,params:e.serialize()}}}class Jg extends Error{constructor(e){super(),this.cancellationToken=e}}const em=Symbol(),tm=Symbol();em;tm;async function im(t){return new Promise(e=>{setTimeout(()=>e(),t)})}class sm{constructor(e,t){this.options=e,this.logger=t,this.timeout=5,this._onMessage=new ao,this._onError=new ao,this._onClose=new ao,this.messageBuffer=""}get onMessage(){return this._onMessage.asEvent()}get onError(){return this._onError.asEvent()}get onClose(){return this._onClose.asEvent()}async connect(s,r){let e=r?.timeoutSeconds?setTimeout(()=>this.close(),1e3*r.timeoutSeconds):void 0;return r?.cancelToken?.register(()=>{e&&(clearTimeout(e),this.close())}),new Promise((e,t)=>{this.socket=new WebSocket(s),"binary"===this.options.mode&&(this.socket.binaryType="blob");let i=e=>{this.socket.removeEventListener("error",i),r?.cancelToken?.isCancelled()?t(new Jg(r.cancelToken)):t(new sm.ConnectError(`Connection to "${s}" failed`))};this.socket.addEventListener("open",()=>{this.socket.removeEventListener("error",i),this.socket.addEventListener("error",e=>this.handleError(e)),this.handleOpen(),e()}),this.socket.addEventListener("error",i),this.socket.addEventListener("close",e=>this.handleClose(e)),this.socket.addEventListener("message",e=>{globalThis.Blob&&e.data instanceof Blob?this.parseData(e.data).then(e=>{this.handleMessage(e)}).catch(e=>{console.error("Failed to decode socket message.",e)}):this.handleMessage(e.data)})}).finally(()=>{e&&clearTimeout(e)})}handleOpen(){this.logger.info("Connection open to "+this.socket.url)}handleError(e){this.logger.error("Connection error",e),this._onError.dispatch(this,e)}handleClose(e){this.logger.info(`Connection closed (${this.socket.url})`,e),this._onClose.dispatch(this,e)}handleMessage(e){if("string"!=typeof e){if(e[0]===this.options.binaryRplPrefix)return void this._onMessage.dispatch(this,e.slice(1));e=F(e)}this.logger.enabledFor(wr.DEBUG)&&this.logger.debug("Got message:","string"==typeof e?this.options.logFilter?.(e)??e:e),e=this.messageBuffer+e,this.messageBuffer="";let t=e.split(/\r?\n/);e=t.pop();e.length&&(this.messageBuffer=e),t.filter(e=>!!e).forEach(e=>this._onMessage.dispatch(this,e))}parseData(s){return new Promise((e,t)=>{let i=new FileReader;i.onload=()=>e(new Uint8Array(i.result)),i.onerror=()=>t(),i.readAsArrayBuffer(s)})}async sendCommand(e,h){if(h.replyStartCode&&!h.replyEndCode)throw new Error("Invalid argument. Expected a reply end code, but got only a start code.");let l=[];return await this.sendRawCommand(e,(e,r,a,n)=>{let o=(e,t)=>{if("number"==typeof e)return t.code===e;let[i,s]=e;return t.code===i&&s(t)};if("string"!=typeof e){if(e[0]===this.options.binaryRplPrefix)return!1;e=F(e)}return h.replyRawText?(a(e.split(/\r?\n/).map(e=>({raw:e,time:r}))),!0):e.split(/\r?\n/).filter(e=>!!e).some(e=>(e=>{if(h.replyMatch){if(h.replyMatch.exec(e))return a([{raw:e,time:r}]),!0;if(!h.replyCodes)return!1}if(!h.replyEndCode&&!h.replyCodes)return a([{raw:e,time:r}]),!0;var[,t,...i]=e.split(" "),t=parseInt(t,10);let s={raw:e,code:t,params:i,time:r};if(h.replyEndCode)return h.replyCodes&&h.replyCodes.some(e=>o(e,s))?(a([s]),!0):(h.replyHeartbeatCodes&&-1!==h.replyHeartbeatCodes.indexOf(t)&&n(h.heartbeatTimeout),(t===h.replyStartCode||h.replyBodyCodes&&-1!==h.replyBodyCodes.indexOf(t)||t===h.replyEndCode)&&l.push(s),t===h.replyEndCode&&(a(l),!0));if(void 0===h.replyCodes)throw new Error("List of replyCodes must be specified when not using start/end codes");return!!h.replyCodes.some(e=>o(e,s))&&(a([s]),!0)})(e))},h.timeout)}async sendBinCommand(e,r){const a=this.options.binaryRplPrefix;if(!a)throw new Error("Must configure binary message reply prefix to send binary commands");const t=this.options.binaryReqPrefix;if(!t)throw new Error("Must configure binary message request prefix to send binary commands");if(e[0]!==t)throw new Error(`Binary command must start with the magic prefix 0x${t.toString(16)}`);return await this.sendRawCommand(e,(e,t,i)=>{if("string"==typeof e||e[0]!==a)return!1;var s=e[1];return-1!==r.replyCodes.indexOf(s)&&(i({code:s,data:e.slice(2),time:t}),!0)},r.timeout)}sendRawCommand(d,p,g){return new Promise((t,i)=>{let s=!1,r,a=e=>{clearTimeout(r),void 0!==e&&Number.isFinite(e)&&(r=setTimeout(h,1e3*(e??g??this.timeout)))},n=e=>{clearTimeout(r),t(e)},o=e=>{this.socket.removeEventListener("message",u),this.socket.removeEventListener("close",l),clearTimeout(r),r=void 0,i(e)},h=()=>{var e="string"==typeof d?this.options.logFilter?.(d)??d:`0x${d[1].toString(16)}`;o(new sm.NoReplyError(`Timeout reached for command ${e}`))},l=async()=>{for(;s;)await im(10);c||o(new sm.SocketError("Connection was closed prematurely"))},c=!1,u=e=>{if(!c){let t=Date.now();globalThis.Blob&&e.data instanceof Blob?(s=!0,this.parseData(e.data).then(e=>{s=!1,c||p(e,t,n,a)&&(c=!0,this.socket.removeEventListener("message",u),this.socket.removeEventListener("close",l))}).catch(e=>{s=!1,console.error("Failed to decode socket message.",e)})):p(e.data,t,n,a)&&(c=!0,this.socket.removeEventListener("message",u),this.socket.removeEventListener("close",l))}};if(this.socket&&this.socket.readyState===WebSocket.OPEN){r=setTimeout(h,1e3*(g??this.timeout)),this.socket.addEventListener("message",u),this.socket.addEventListener("close",l);try{this.sendMessage(d)}catch(e){o(e)}}else o(new sm.SocketError("Send command failed. Socket is not open."+(this.socket?` (readyState = ${this.socket.readyState})`:"")))})}sendMessage(e){if(!this.socket||this.socket.readyState!==WebSocket.OPEN)throw new sm.SocketError(`Socket is not open${this.socket?` (readyState = ${this.socket.readyState})`:""}`);this.logger.enabledFor(wr.DEBUG)&&this.logger.debug("Sent message:","string"==typeof e?this.options.logFilter?.(e)??e:e),"string"==typeof e&&(e+="\r\n");let t;t="binary"===this.options.mode&&"string"==typeof e?R(e):e,this.socket.send(t)}async ping(e){var t=Date.now();return(await this.sendCommand(`ping :${t}`,{replyMatch:new RegExp(`^:[^ ]+ PONG [^ :]+ :${t}`,"i"),timeout:e}))[0].time-t}close(){this.socket&&this.socket.close()}isOpen(){return this.socket&&this.socket.readyState===WebSocket.OPEN}}!function(e){class t extends Error{constructor(e){super(e)}}e.NoReplyError=t;class i extends Error{constructor(e){super(e)}}e.SocketError=i;class s extends Error{constructor(e){super(e)}}e.ConnectError=s}(sm=sm||{});class rm extends Error{constructor(e,t){super(e),this.code=t}}(r=(r=rm=rm||{}).Code||(r.Code={}))[r.Unknown=0]="Unknown",r[r.OutdatedClient=1]="OutdatedClient",r[r.BadLogin=2]="BadLogin",r[r.TooManyLoginAttempts=3]="TooManyLoginAttempts",r[r.AlreadyLoggedIn=4]="AlreadyLoggedIn",r[r.InstanceNonExistent=5]="InstanceNonExistent",r[r.InstanceAlreadyExists=6]="InstanceAlreadyExists",r[r.InstanceNotAllowed=7]="InstanceNotAllowed",r[r.InstanceAlreadyStarted=8]="InstanceAlreadyStarted",r[r.InstanceVersMismatch=9]="InstanceVersMismatch",r[r.CreatedTooManyInstances=10]="CreatedTooManyInstances";const am="#all";var nm;(r=nm=nm||{})[r.Channel=0]="Channel",r[r.Page=1]="Page",r[r.Whisper=2]="Whisper";const om=new Map([[103,rm.Code.BadLogin],[104,rm.Code.TooManyLoginAttempts],[101,rm.Code.AlreadyLoggedIn],[201,rm.Code.InstanceAlreadyExists],[202,rm.Code.CreatedTooManyInstances],[401,rm.Code.InstanceNonExistent],[402,rm.Code.InstanceNotAllowed],[403,rm.Code.InstanceAlreadyStarted],[406,rm.Code.InstanceVersMismatch]]);class hm{constructor(e,t,i,s,r,a,n,o,h,l,c,u){this.game=e,this.gservCon=t,this.gameoptParser=i,this.gameoptSerializer=s,this.actionSerializer=r,this.actionFactory=a,this.inputActions=n,this.onDesync=o,this.actionLogger=h,this.debugLogger=l,this.replayRecorder=c,this.debugGameState=u,this.debugGameStateHistory=[],this.queuedRateChanges=[],this.errorState=!1,this.passiveMode=!1,this.receivedActions=new Map,this.receivedNetworkTurn=0,this.lagState=!1,this._onLagStateChange=new ao,this._onActionsSent=new ao,this._onActionsProcessed=new ao,this._onActionsReceived=new ao,this.receiveActions=e=>{let t=new v(e);var i=t.readUint32(),e=this.gameoptParser.parseAllPlayerActions(t);this.receivedNetworkTurn=i,this.receivedActions.set(i,e),this._onActionsReceived.dispatch(void 0,i)},this.handleGameDesync=()=>{this.setErrorState(),this.onDesync()}}get onLagStateChange(){return this._onLagStateChange.asEvent()}get onActionsSent(){return this._onActionsSent.asEvent()}get onActionsProcessed(){return this._onActionsProcessed.asEvent()}get onActionsReceived(){return this._onActionsReceived.asEvent()}init(){this.gameTurnMillis=1e3/(this.game.desiredSpeed.value*js.BASE_TICKS_PER_SECOND),this.currentNetworkTurn=0,this.currentSubTurn=0,this.gservCon.onGameActions.subscribe(this.receiveActions),this.gservCon.onGameDesync.subscribe(this.handleGameDesync),this.debug(`Init: gameTurnMillis = ${this.gameTurnMillis}`)}canAdvanceNetworkTurn(){return this.currentNetworkTurn<2||this.receivedActions.has(this.currentNetworkTurn-2)}setErrorState(){this.errorState=!0}getErrorState(){return this.errorState}setRate(e){if(this.debug(`Recv rate: ${e.rate} (turn ${e.turnNo})`),0===this.currentSubTurn&&0===this.currentNetworkTurn&&0===e.turnNo)this.updateRate(e.rate);else{if(e.turnNo<this.currentNetworkTurn-2)throw new Error("Rate change has turn number more than two turns in the past.");this.queuedRateChanges.push(e)}}updateRate(e){var t;this.networkTurnMillis=(t=this.gameTurnMillis,Math.max(1,Math.ceil(e/t))*t),this.hashCheckTurnInterval=Math.ceil(hm.PREFERRED_HASH_CHECK_MILLIS/this.networkTurnMillis),console.log(`Rate set to ${e} (${this.networkTurnMillis}ms) @ ${this.currentNetworkTurn}`)}setPassiveMode(e){this.debug(`Send passive: ${e}`),this.passiveMode=e,this.gservCon.sendPlayerActive(!e)}getTurnMillis(){return this.gameTurnMillis}doGameTurn(e){if(!this.errorState){if(!this.networkTurnMillis)throw new Error("Network turn rate should be set by now.");if(this.game.status!==ql.Ended){if(0===this.currentSubTurn){var t=this.queuedRateChanges[0];if(t&&t.turnNo+2===this.currentNetworkTurn&&(this.debug(`Process rate ${t.rate} (turn ${t.turnNo})`),this.updateRate(t.rate),this.queuedRateChanges.shift()),!this.canAdvanceNetworkTurn())return this.handleCommsLag(!0,e),this.debug(`Lag state: ${this.lagState}`),!1;this.debug("Advance turn"),this.commsLagStartTime&&0<e-this.commsLagStartTime&&console.log(`Waited ${Math.round(e-this.commsLagStartTime)}ms for other clients to catch up.`),this.handleCommsLag(!1,e),!this.passiveMode&&this.currentNetworkTurn>=this.receivedNetworkTurn&&this.sendActions(),2<=this.currentNetworkTurn&&(i=this.receivedActions.get(this.currentNetworkTurn-2),this.replayRecorder.recordActions(this.game.currentTick,i),this.processActions(i),this.receivedActions.delete(this.currentNetworkTurn-2),this._onActionsProcessed.dispatch(void 0,this.currentNetworkTurn-2)),this.game.update(),this.passiveMode||this.currentNetworkTurn%this.hashCheckTurnInterval!=0||this.gservCon.sendGameStateHash(this.currentNetworkTurn,this.game.getHash()),this.networkTurnMillis>this.gameTurnMillis?this.currentSubTurn++:this.currentNetworkTurn++}else this.debug("Update"),this.game.update(),this.currentSubTurn++,this.currentSubTurn>=this.networkTurnMillis/this.gameTurnMillis&&(this.currentSubTurn=0,this.currentNetworkTurn++);var i;this.debugGameState&&(i=this.networkTurnMillis/this.gameTurnMillis*this.hashCheckTurnInterval,this.debugGameStateHistory.length>i&&this.debugGameStateHistory.shift(),this.debugGameStateHistory.push(this.game.debugGetState()))}else this.game.update()}}handleCommsLag(e,t){e?(this.commsLagStartTime||(this.commsLagStartTime=t),1e3<t-this.commsLagStartTime&&this.updateLagState(!0)):(this.commsLagStartTime=void 0,this.updateLagState(!1))}updateLagState(e){e!==this.lagState&&(this.lagState=e,this._onLagStateChange.dispatch(void 0,e))}sendActions(){let e=this.inputActions.dequeueAll();e.length||e.push(new td);var t=this.gameoptSerializer.serializePlayerActions(e.map(e=>this.actionSerializer.getActionPayload(e)));this.debug(`Send actions: ${t}`),this.gservCon.sendPlayerActions(this.currentNetworkTurn,t),this._onActionsSent.dispatch(void 0,this.currentNetworkTurn)}processActions(e){[...e].forEach(([i,e])=>e.forEach(e=>{let t=this.actionFactory.create(e.id);t.player=this.game.getPlayer(i),t.unserialize(e.params),t.process();e=t.print();e&&this.actionLogger?.debug(`(${t.player.name})@${this.game.currentTick}: ${e}`)}))}debug(e){this.debugLogger?.(`${this.currentNetworkTurn}-${this.currentSubTurn}-${this.game.currentTick}: ${e}`)}dispose(){this.setErrorState(),this.gservCon.onGameActions.unsubscribe(this.receiveActions),this.gservCon.onGameDesync.unsubscribe(this.handleGameDesync)}}hm.PREFERRED_HASH_CHECK_MILLIS=1e3;const lm=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks");class cm{constructor(e){this.gameTurnMgr=e,this.isStarted=!1}start(){this.isStarted||(this.isStarted=!0,this.startTime=void 0,this.lastGameFrame=0)}async waitForTick(){return new Promise((e,t)=>this.doWaitForTick(e,t))}doWaitForTick(e,t){try{this.isStarted||e();var i=lm.performance.now(),s=this.updateDeltaGameFrames(i);if(0<s)if(!(!1===this.gameTurnMgr.doGameTurn(i)))return void e();setImmediate(()=>this.doWaitForTick(e,t))}catch(e){t(e)}}updateDeltaGameFrames(e){var t=this.gameTurnMgr.getTurnMillis(),i=t!==this.lastGameTurnMillis;this.lastGameTurnMillis=t,i&&(this.lastGameFrame=0,this.startTime=e);let s=0;return this.startTime?(i=e-this.startTime,t=Math.round(i/t),s=t-this.lastGameFrame,this.lastGameFrame=t):this.startTime=e,s}stop(){this.isStarted&&(this.isStarted=!1)}destroy(){this.stop()}}const um=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");var dm,pm,gm,mm,fm,ym,wm,Tm,bm=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i},vm=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)};class Sm{constructor(e,t,i,s,r,a,n,o,h){dm.set(this,void 0),pm.set(this,void 0),gm.set(this,void 0),mm.set(this,void 0),fm.set(this,void 0),ym.set(this,void 0),wm.set(this,void 0),Tm.set(this,void 0),bm(this,dm,e,"f"),bm(this,pm,t,"f"),bm(this,gm,new vg(t,!1),"f"),bm(this,mm,new sg(t.events),"f"),bm(this,fm,i,"f"),bm(this,ym,a,"f"),bm(this,wm,o,"f"),bm(this,Tm,h,"f"),vm(this,mm,"f").subscribe(t=>e.forEach(e=>e.onGameEvent(t,vm(this,gm,"f")))),e.forEach(e=>{e.setGameApi(vm(this,gm,"f")),e.setActionsApi(new $p(t,s,r,e,n)),e.setProductionApi(new Fg(t.getPlayerByName(e.name).production)),e.setLogger(new Ag(wr.get(e.name),vm(this,gm,"f"))),e.onGameStart(vm(this,gm,"f"))})}isFinished(){return vm(this,pm,"f").status===ql.Ended||vm(this,ym,"f").getErrorState()}async update(){if(vm(this,wm,"f"))await vm(this,wm,"f").waitForTick();else{if(!(vm(this,ym,"f")instanceof jg))throw new Error("Missing animation loop or turn manager");vm(this,ym,"f").doGameTurn()}vm(this,dm,"f").forEach(e=>e.onGameTick(vm(this,gm,"f")))}getCurrentTick(){return vm(this,gm,"f").getCurrentTick()}getTickRate(){return vm(this,gm,"f").getTickRate()}getPlayerStats(){return vm(this,pm,"f").getNonNeutralPlayers().filter(e=>!e.isObserver).map(t=>({name:t.name,country:t.country,ai:t.isAi||vm(this,dm,"f").some(e=>e.name===t.name),defeated:t.defeated,credits:t.credits,startLocation:t.startLocation}))}saveReplay(e){let t=vm(this,fm,"f");t.finish(vm(this,pm,"f").currentTick);var i=`${vm(this,pm,"f").gameOpts.mapName}_${Date.now()}${Qg.extension}`,s=t.serialize(),i=a.resolve(e??process.cwd(),i);um.writeFileSync(i,s,"utf-8"),process.stdout.write(`Replay saved to "${i}"\n`)}dispose(){vm(this,mm,"f").dispose(),vm(this,dm,"f").length=0,vm(this,Tm,"f")?.call(this)}}dm=new WeakMap,pm=new WeakMap,gm=new WeakMap,mm=new WeakMap,fm=new WeakMap,ym=new WeakMap,wm=new WeakMap,Tm=new WeakMap;class km{constructor(e,t,i){this.game=e,this.replayRecorder=t,this.gservCon=i,this.disposables=new Rl,this.handleGservMessage=e=>{e.to.type===nm.Channel&&e.to.name===am&&this.replayRecorder.recordChatMessage(this.game.currentTick,e.from,e.text)}}init(){this.gservCon.onChatMessage.subscribe(this.handleGservMessage),this.disposables.add(()=>this.gservCon.onChatMessage.unsubscribe(this.handleGservMessage))}sayAll(e,t){this.gservCon.isOpen()?this.gservCon.sayChannel(t):console.warn("Can't send chat message. Network connection is already closed.")}dispose(){this.disposables.dispose()}}class Om{constructor(e,t){this.game=e,this.replayRecorder=t}sayAll(e,t){this.replayRecorder.recordChatMessage(this.game.currentTick,e,t)}}class _m{static getGameRoute(e){return`#/game/${N.encode(JSON.stringify({gameId:e.gameId,gameTimestamp:e.gameTimestamp,gservUrl:e.gservUrl,playerName:e.playerName,gameOpts:e.gameOpts,tournament:e.tournament}))}`}static extractGameParams(e){return JSON.parse(N.decode(e))}}_m.modQueryStringName="mod";var Im=function(e,t,i,s){if("a"===i&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?s:"a"===i?s.call(e):s?s.value:t.get(e)},Cm=function(e,t,i,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,i):r?r.value=i:t.set(e,i),i};const Am=a.resolve((0,e.default)(),"./res");class Bm{constructor(){Rm.add(this),xm.set(this,void 0),Em.set(this,void 0),Pm.set(this,void 0),Nm.set(this,void 0),Mm.set(this,!1),Dm.set(this,void 0)}async init(e){Im(this,Rm,"m",Lm).call(this),globalThis.Blob||(globalThis.Blob=(await Promise.resolve().then(__webpack_require__.bind(__webpack_require__,91))).Blob);var t=await(0,n.getOriginPrivateDirectory)(o.default,a.resolve(e)),i=await(0,n.getOriginPrivateDirectory)(o.default,Am),e=await(0,n.getOriginPrivateDirectory)(o.default,process.cwd());Nt.initGameResSource(St.Local);let s=await Nt.initRfs(t);s.addDirectoryHandle(i),s.addDirectoryHandle(e);let r=await Nt.initVfs(s,wr.get("vfs"));await r.loadStandaloneFiles(),await r.loadExtraMixFiles(Nt.getActiveEngine()),await r.addMixFile("ra2cd.mix"),await r.loadImplicitMixFiles(Nt.getActiveEngine()),Nt.loadRules(),Cm(this,Dm,await Nt.loadMapList(),"f"),Cm(this,xm,Nt.getMpModes(),"f"),Cm(this,Mm,!0,"f")}getAvailableMaps(){if(!Im(this,Mm,"f"))throw new Error("API is not initialized. Call init() first.");return Im(this,Dm,"f").getAll().map(e=>e.fileName.toLowerCase())}getAvailableGameModes(e){if(!Im(this,Mm,"f"))throw new Error("API is not initialized. Call init() first.");let t=Im(this,Dm,"f").getByName(e);if(!t)throw new Error(`Map "${e}" is not available`);return t.gameModes.map(e=>e.id)}async createGame(e){return e.online?await Im(this,Rm,"m",jm).call(this,e):await Im(this,Rm,"m",Fm).call(this,e)}}var xm=new WeakMap,Em=new WeakMap,Pm=new WeakMap,Nm=new WeakMap,Mm=new WeakMap,Dm=new WeakMap,Rm=new WeakSet,Lm=function(){wr.useDefaults(),wr.setLevel(wr.ERROR);const e=process.env.DEBUG_LOGGING;var t;if(e)if(isNaN(e))for(t of e.split(","))wr.get(t).setLevel(wr.DEBUG);else wr.setLevel(Boolean(Number(e))?wr.DEBUG:wr.ERROR);Cm(this,Em,wr.get("ini"),"f"),Cm(this,Pm,wr.get("action"),"f"),Cm(this,Nm,wr.get("net"),"f")},Fm=async function(e){if(!Im(this,Mm,"f"))throw new Error("API is not initialized. Call init() first.");var t=await Im(this,Rm,"m",Wm).call(this,e),i=e.agents.filter(e=>e instanceof Up),s=new ki(await Nt.vfs.openFileWithRfs(t.mapName)),r=Math.floor(Date.now()/1e3),a=await Im(this,Rm,"m",Um).call(this,"0",r,t,s,void 0),e=new Vp,r=new Yu;(new Ap).register(r,a,void 0);let n=new Qg;n.init(a.id,a.startTimestamp,t,Nt.getVersion(),Nt.getModHash());s=new Kg,t=new Yg(n,0,a.gameOpts.humanPlayers,s);let o=new jg(a,e,t,s,r,Im(this,Pm,"f"));o.init();t=new Om(a,t);return new Sm(i,a,n,r,e,o,t)},jm=async function(e){if(!Im(this,Mm,"f"))throw new Error("API is not initialized. Call init() first.");if(!e.serverUrl)throw new Error("Must specify a serverUrl");if(!e.clientUrl)throw new Error("Must specify a clientUrl");let t=[];for(var i of e.agents){if(!i.name.match(/^[a-z0-9-_]+$/i))throw new Error(`Agent name "${i.name}" must contain only alphanumeric characters, dash (-) or underscore (_)`);i instanceof Up&&t.push(i)}if(!(e.agents[0]instanceof Up))throw new Error("The first object in the agents array must be a Bot instance in online mode");if(e.agents.slice(1).some(e=>e instanceof Up))throw new Error("Only the first player in the agents array can be a bot in online mode");var s=await Im(this,Rm,"m",Wm).call(this,e);let r=class{constructor(e){this._onLoadInfo=new ao,this._onGameStart=new ao,this._onGameActions=new ao,this._onGameDesync=new ao,this._onRateChange=new ao,this._onChatMessage=new ao,this._onTaunt=new ao,this._onPlayerDisconnect=new ao,this.handleMessage=t=>{if("string"==typeof t){let e=t.split(" ");var i,s;"ping"===e[0]?this.isOpen()&&this.con.sendMessage("pong"+(e[1]?" "+e[1]:"")):"privmsg"===e[1].toLowerCase()?this.handlePrivMsg(t):"600"===e[1]?this.handleLoadInfo(e[3]):"700"===e[1]?this.handleGameStart():"801"===e[1]?this._onGameDesync.dispatch(this):"802"===e[1]?([i,s]=e[3].slice(1).split(","),this._onRateChange.dispatch(this,{rate:Number(i),turnNo:Number(s)})):"803"===e[1]?this._onTaunt.dispatch(this,{from:e[0].replace(/^:/,""),tauntNo:Number(e[3].replace(/^:/,""))}):"804"===e[1]&&this._onPlayerDisconnect.dispatch(this,e[3].replace(/^:/,""))}else 1===t[0]&&this.handlePlayerActions(t.slice(1))},this.con=e}get onError(){return this.con.onError}get onClose(){return this.con.onClose}get onLoadInfo(){return this._onLoadInfo.asEvent()}get onGameStart(){return this._onGameStart.asEvent()}get onGameActions(){return this._onGameActions.asEvent()}get onGameDesync(){return this._onGameDesync.asEvent()}get onRateChange(){return this._onRateChange.asEvent()}get onChatMessage(){return this._onChatMessage.asEvent()}get onTaunt(){return this._onTaunt.asEvent()}get onPlayerDisconnect(){return this._onPlayerDisconnect.asEvent()}static factory(e){return new this(new sm({mode:"text",binaryRplPrefix:2,binaryReqPrefix:2,logFilter:e=>e.replace(/^(user [^ ]+) ([^ ]+)/i,"$1 <redacted>").replace(/^((:.+!.+@.+)?privmsg ([^ ]+ )+):(.+)\r?\n?$/i,"$1:<redacted>")},e))}getCurrentUser(){return this.currentUser}getServerName(){return this.serverName}async connect(e,t){return this.con.onMessage.subscribe(this.handleMessage),await this.con.connect(e,t)}close(){this.con.onMessage.unsubscribe(this.handleMessage),this.con.close(),this.currentUser=void 0}isOpen(){return this.con.isOpen()}async cvers(e){let t=await this.con.sendCommand(`cvers ${e} 2`,{replyCodes:[10,11]});if(11===t[0].code){e=t[0].params?t[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new rm(`Cvers error: ${e}`,rm.Code.OutdatedClient)}}async login(e,t){let i=await this.con.sendCommand(`user ${e} ${N.encode(t)}`,{replyCodes:[100,103,104,101]});if(100!==i[0].code){var s=om.get(i[0].code)??rm.Code.Unknown,t=i[0].params?i[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new rm(`Login error: ${t}`,s)}this.currentUser=e,this.serverName=i[0].raw.match(/^:([^\s]+)/)?.[1]||""}async createGame(e,t,i,s,r){if(i.includes(" "))throw new Error("Game opts string cannot include spaces");let a=await this.con.sendCommand(`create ${e} ${t} ${i} ${s} ${r}`,{replyCodes:[200,201,202,402]});if(200!==a[0].code){s=om.get(a[0].code)??rm.Code.Unknown,r=a[0].params?a[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new rm(`Create error: ${r}`,s)}}async joinGame(e,t,i){let s=await this.con.sendCommand(`join ${e} ${t} ${i}`,{replyCodes:[400,401,402,403,406]});if(400!==s[0].code){t=om.get(s[0].code)??rm.Code.Unknown,i=s[0].params?s[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new rm(`Join error: ${i}`,t)}}async gameOpts(){let e=await this.con.sendCommand("gameopts",{replyCodes:[500]});if(!e[0].params)throw new Error("Unexpected server reply for getopts command. Missing params.");return e[0].params.splice(1).join(" ").replace(/^:/,"")}sendLoadedPercent(e){this.con.sendMessage(`loaded ${e}`)}requestLoadInfo(){this.con.sendMessage("loadinfo")}sendGameStateHash(e,t){let i=new v(10);i.dynamicSize=!1,i.writeUint8(2),i.writeUint8(2),i.writeUint32(e),i.writeUint32(t),this.con.sendMessage(i.toUint8Array())}sendPlayerActive(e){this.con.sendMessage(`active ${e?1:0}`)}sendTaunt(e){this.con.sendMessage(`taunt ${e}`)}async ping(e){return await this.con.ping(e)}sendPlayerActions(e,t){let i=new v(6);i.writeUint8(2),i.writeUint8(1),i.writeUint32(e),i.writeUint8Array(t),this.con.sendMessage(i.toUint8Array())}sendMap(e){let t=new v(2);t.writeUint8(2),t.writeUint8(3),t.writeUint8Array((new zg).serializeMapData(e)),this.con.sendMessage(t.toUint8Array())}async getMap(){let e=new v(2);e.dynamicSize=!1,e.writeUint8(2),e.writeUint8(4);var t=await this.con.sendBinCommand(e.toUint8Array(),{replyCodes:[2],timeout:15});return(new Vg).parseMapData(t.data)}handleLoadInfo(e){this._onLoadInfo.dispatch(this,e.replace(/^:/,""))}handleGameStart(){this._onGameStart.dispatch(this,void 0)}handlePlayerActions(e){this._onGameActions.dispatch(this,e)}sayChannel(e){this.privmsg([am],e)}privmsg(e,t){if(!this.currentUser)throw new Error("Must login before sending messages");t.length&&(e=e.join(","),this.con.sendMessage(`privmsg ${e} :${t}`))}handlePrivMsg(e){var t=e.match(/^:([A-Za-z0-9-_]+) PRIVMSG ([A-Za-z0-9-_#']+) :(.*)/i);if(!t)throw new Error(`Unexpected PRIVMSG message format "${e}"`);var[,i,s,e]=t;let r;t=new Date;s===am?r={from:i,to:{type:nm.Channel,name:s},text:e,time:t}:s===this.currentUser&&(r={from:i,to:i===this.getServerName()?{type:nm.Page,name:s}:{type:nm.Channel,name:"#team"},text:e,time:t}),r&&this._onChatMessage.dispatch(this,r)}}.factory(Im(this,Nm,"f"));await r.connect(e.serverUrl),await r.cvers(Nt.getVersion()),await r.login(e.agents[0].name,e.botPassword);let a=new zg;var n,o=a.serializeOptions(s),h=b.randomUUID(),l=Math.floor(Date.now()/1e3);process.stdout.write("\nYou may use the following link(s) to join, after the game is created:\n\n");for(n of e.agents.slice(1))process.stdout.write(e.clientUrl.replace(/\/$/,"")+`/${_m.getGameRoute({gameId:h,gameTimestamp:l,gservUrl:e.serverUrl,playerName:n.name})}\n`);process.stdout.write("\n\nPress ENTER to create the game now...\n"),await new Promise(e=>process.stdin.once("data",e)),process.stdin.pause(),process.stdout.write("Creating game...\n"),await r.createGame(h,l,o,Nt.getVersion(),Nt.getModHash());let c=new Vg;var u=c.parseOptions(await r.gameOpts());let d=await Nt.vfs.openFileWithRfs(s.mapName);var p=new ki(d);s.mapOfficial||r.sendMap(d.readAsString());var g=e.agents[0].name;let m=await Im(this,Rm,"m",Um).call(this,h,l,u,p,g);o=new Kg,s=new Vp,p=new Yu;(new Ap).register(p,m,g);let f=new Qg;f.init(m.id,m.startTimestamp,u,Nt.getVersion(),Nt.getModHash());u=new Yg(f,0,m.gameOpts.humanPlayers,o);let y=new hm(m,r,c,a,o,p,s,()=>{console.error("Desync detected."),process.exit(1)},Im(this,Pm,"f"),void 0,u,!1);y.init();let w=new cm(y);r.onRateChange.subscribe(e=>y.setRate(e)),m.onEnd.subscribe(()=>{process.stdout.write("Game ended.\n"),w.destroy()}),process.stdout.write("\nGame created."),process.stdout.write("\nWaiting for players to join...\n"),await new Promise((e,t)=>{r.onGameStart.subscribeOnce(()=>{r.onClose.unsubscribe(t),w.start(),e()}),r.onClose.subscribeOnce(t),r.sendLoadedPercent(100)}),process.stdout.write("Game started.\n");let T=new km(m,u,r);T.init();return r.onClose.subscribeOnce(()=>y.dispose()),new Sm(t,m,f,p,s,y,T,w,()=>{w.destroy(),T.dispose(),Im(this,Nm,"f").setLevel(wr.OFF),r.close()})},Um=async function(e,t,i,s,r){if(!Im(this,Mm,"f"))throw new Error("API is not initialized. Call init() first.");var a=Nt.getIni(Im(this,xm,"f").getById(i.gameMode).rulesOverride);await Nt.loadTheater(s.theaterType);var n=Nt.getActiveEngine(),o=Nt.getTheaterSettings(n,s.theaterType),n=Nt.getTheaterIni(n,s.theaterType);let h=new Y(n);h.loadTileData(Nt.getTileData(),o.Extension);let l=class{static create(e,t,i,s,r,a,n,o,h,l,c,u,d,p,g,m){var f=i.clone().mergeWith(a).mergeWith(e);let y=new Hn(f,d);var w=new Xn(y,s,e,d),a=new Dp(r);y.applySpecialFlags(e.specialFlags),class{static sanitize(e,t){t=t.mpDialogSettings;e.credits=Math.floor(z(e.credits,t.minMoney,t.maxMoney)),e.gameSpeed=Math.floor(z(e.gameSpeed,0,6)),e.unitCount=Math.floor(z(e.unitCount,t.minUnitCount,t.maxUnitCount))}}.sanitize(h,y);let T=new Hn(i),b=T.getMultiplayerCountries(),v=[...T.getMultiplayerColors().values()],S=rc.factory(n,o),k=new dl(e,t,y,S.generateRandomInt.bind(S));f=new $h,s=l.getById(h.gameMode).type,d=new ml,r=new gl(d),i=new yl,e=new wl(1),t=new Gh(k.tiles,k.tileOccupation,k.bridges,e),l=new Yu,u=new zp(u),m=class{constructor(e,t,i,s,r){this.actionFactory=e,this.actionQueue=t,this.botFactory=i,this.botDebugIndex=s,this.actionLogger=r,this.bots=new Map,this.disposables=new Rl}static factory(e,t,i,s){return new this(e,new Vp,t,i,s)}init(t){this.gameApi=new vg(t,!0);let e=new sg(t.events);var i,s;for(i of t.getCombatants().filter(e=>e.isAi))this.bots.set(i,this.botFactory.create(i));this.updateDebugBotIndex(this.botDebugIndex.value,t);let r=e=>this.updateDebugBotIndex(e,t);this.botDebugIndex.onChange.subscribe(r),this.disposables.add(()=>this.botDebugIndex.onChange.unsubscribe(r)),e.subscribe(t=>this.bots.forEach(e=>e.onGameEvent(t,this.gameApi))),this.disposables.add(e);for(s of this.bots.values())s.setGameApi(this.gameApi),s.setActionsApi(new $p(t,this.actionFactory,this.actionQueue,s)),s.setProductionApi(new Fg(t.getPlayerByName(s.name).production)),s.setLogger(new Ag(wr.get(s.name),this.gameApi)),s.onGameStart(this.gameApi)}update(e){var t,i;for(t of this.actionQueue.dequeueAll()){t.process();var s=t.print();s&&this.actionLogger.debug(`(${t.player.name})@${e.currentTick}: ${s}`)}for(i of e.getCombatants().filter(e=>e.isAi))this.bots.get(i).onGameTick(this.gameApi)}updateDebugBotIndex(e,t){var i,s=0<e?t.getAiPlayerName(e):void 0;for(i of this.bots.values())i.setDebugMode(i.name===s)}dispose(){this.gameApi=void 0,this.bots.clear(),this.disposables.dispose()}}.factory(l,u,g,m);let O=new Zu(f,k,y,w,a,n,o,h,s,d,i,r,e,t,m);(new Ap).register(l,O,void 0),O.traits.add(new Il),O.sellTrait=new Al(O,y.general),O.traits.add(O.sellTrait),O.traits.add(new El);let _=new Nl(y,p);O.traits.add(_),O.mapShroudTrait=new Ml(k,r),O.traits.add(O.mapShroudTrait),O.mapRadiationTrait=new Qu(k),O.traits.add(O.mapRadiationTrait),O.mapLightingTrait=new Mp(y.audioVisual,k.getLighting()),O.traits.add(O.mapLightingTrait),O.traits.add(new ln),O.traits.add(new Bp),O.traits.add(new xp),O.crateGeneratorTrait=new Wn(h.cratesAppear),O.traits.add(O.crateGeneratorTrait),c||(O.stalemateDetectTrait=new Pp,O.traits.add(O.stalemateDetectTrait));let I=new _l(y,h,_.getAvailableObjects()),C=Np.factory(n,o),A=C.generateColors(h),B=C.generateCountries(h,T),x=C.generateStartLocations(h,k.startingLocations),E=[...h.humanPlayers,...h.aiPlayers].filter(ja);return E.forEach(e=>{let t,i,s;if(Bs(e)?(t=e.name,i=!1):(t=O.getAiPlayerName(e),i=!0,s=e.difficulty),-3!==e.countryId){var r=B.get(e)??e.countryId,a=A.get(e)??e.colorId,e=x.get(e)??e.startPos;if(-2===r)throw new Error("Random country should have been resolved by now");if(-2===a)throw new Error("Random color should have been resolved by now");if(-2===e)throw new Error("Random start location should have been resolved by now");r=b[r].name,r=Zn.factory(r,y),a=v[a];O.addPlayer(I.createCombatant(t,r,e,a,i,s))}else O.addPlayer(I.createObserver(t,y))}),O.addPlayer(I.createNeutral(y,"@@NEUTRAL@@")),O}}.create(s,h,Nt.getRules(),Nt.getArt(),Nt.getAi(),a,e,t,i,Im(this,xm,"f"),!1,{version:"0.0.0"},Im(this,Em,"f"),new wl(!1),new wl(0),Im(this,Pm,"f"));return l.init(r?l.getPlayerByName(r):void 0),l.start(),l},Wm=async function(t){let e=Im(this,Dm,"f").getAll().find(e=>e.fileName.toLowerCase()===t.mapName.toLowerCase());if(!e)throw new Error(`Map ${t.mapName} not found.`);if(!e.gameModes.find(e=>e.id===t.gameMode))throw new Error(`Map "${e.fileName}" doesn't support game mode ${t.gameMode}`);let i=await Nt.vfs.openFileWithRfs(t.mapName),s=new Hn(Nt.getRules()).getMultiplayerCountries();return{gameMode:t.gameMode,shortGame:t.shortGame,mcvRepacks:t.mcvRepacks,cratesAppear:t.cratesAppear,superWeapons:t.superWeapons,gameSpeed:t.gameSpeed,credits:t.credits,unitCount:t.unitCount,buildOffAlly:t.buildOffAlly,humanPlayers:t.agents.map((t,e)=>({name:t.name,countryId:s.findIndex(e=>e.name===t.country),colorId:e,startPos:-2,teamId:-2})),aiPlayers:new Array(8).fill(void 0),mapName:e.fileName,mapDigest:class{static compute(e){return he.calculateCrc(e.getBytes()).toString(16)}}.compute(i),mapSizeBytes:i.getSize(),mapTitle:e.fileName,maxSlots:e.maxSlots,mapOfficial:e.official}},r=__webpack_require__(949);class zm extends r.Euler{constructor(){super(...arguments),this.isEuler=!0}setFromRotationMatrix(e,t,i){var s=e.elements,r=s[0],a=s[4],n=s[8],o=s[1],h=s[5],l=s[9],c=s[2],e=s[6],s=s[10];return"XYZ"===(t=t||this._order)?(this._y=Yi.asin(z(n,-1,1)),Math.abs(n)<.99999?(this._x=Yi.atan2(-l,s),this._z=Yi.atan2(-a,r)):(this._x=Yi.atan2(e,h),this._z=0)):"YXZ"===t?(this._x=Yi.asin(-z(l,-1,1)),Math.abs(l)<.99999?(this._y=Yi.atan2(n,s),this._z=Yi.atan2(o,h)):(this._y=Yi.atan2(-c,r),this._z=0)):"ZXY"===t?(this._x=Yi.asin(z(e,-1,1)),Math.abs(e)<.99999?(this._y=Yi.atan2(-c,s),this._z=Yi.atan2(-a,h)):(this._y=0,this._z=Yi.atan2(o,r))):"ZYX"===t?(this._y=Yi.asin(-z(c,-1,1)),Math.abs(c)<.99999?(this._x=Yi.atan2(e,s),this._z=Yi.atan2(o,r)):(this._x=0,this._z=Yi.atan2(-a,h))):"YZX"===t?(this._z=Yi.asin(z(o,-1,1)),Math.abs(o)<.99999?(this._x=Yi.atan2(-l,h),this._y=Yi.atan2(-c,r)):(this._x=0,this._y=Yi.atan2(n,s))):"XZY"===t?(this._z=Yi.asin(-z(a,-1,1)),Math.abs(a)<.99999?(this._x=Yi.atan2(e,h),this._y=Yi.atan2(n,r)):(this._x=Yi.atan2(-l,s),this._y=0)):console.warn("THREE.Euler: .setFromRotationMatrix() given unsupported order: "+t),this._order=t,!1!==i&&this.onChangeCallback(),this}reorder(e){return Vm.setFromEuler(this),this.setFromQuaternion(Vm,e)}toVector3(e){return e?e.set(this._x,this._y,this._z):new rs(this._x,this._y,this._z)}}const Vm=new Ki;r=__webpack_require__(949);class Hm extends r.Spherical{setFromVector3(e){return this.radius=e.length(),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Yi.atan2(e.x,e.z),this.phi=Yi.acos(z(e.y/this.radius,-1,1))),this}}r=__webpack_require__(949);class Gm extends r.Cylindrical{setFromVector3(e){return this.radius=Yi.sqrt(e.x*e.x+e.z*e.z),this.theta=Yi.atan2(e.x,e.z),this.y=e.y,this}}const $m=new Bm})();var __webpack_exports__ApiEventType=__webpack_exports__.ApiEventType,__webpack_exports__ArmorType=__webpack_exports__.ArmorType,__webpack_exports__AttackState=__webpack_exports__.AttackState,__webpack_exports__Bot=__webpack_exports__.Bot,__webpack_exports__Box2=__webpack_exports__.Box2,__webpack_exports__BuildCat=__webpack_exports__.BuildCat,__webpack_exports__BuildStatus=__webpack_exports__.BuildStatus,__webpack_exports__Cylindrical=__webpack_exports__.Cylindrical,__webpack_exports__Euler=__webpack_exports__.Euler,__webpack_exports__FactoryStatus=__webpack_exports__.FactoryStatus,__webpack_exports__FactoryType=__webpack_exports__.FactoryType,__webpack_exports__GameInstanceApi=__webpack_exports__.GameInstanceApi,__webpack_exports__GameMath=__webpack_exports__.GameMath,__webpack_exports__InfDeathType=__webpack_exports__.InfDeathType,__webpack_exports__LandTargeting=__webpack_exports__.LandTargeting,__webpack_exports__LandType=__webpack_exports__.LandType,__webpack_exports__LocomotorType=__webpack_exports__.LocomotorType,__webpack_exports__Matrix4=__webpack_exports__.Matrix4,__webpack_exports__MovementZone=__webpack_exports__.MovementZone,__webpack_exports__NavalTargeting=__webpack_exports__.NavalTargeting,__webpack_exports__ObjectType=__webpack_exports__.ObjectType,__webpack_exports__OrderType=__webpack_exports__.OrderType,__webpack_exports__PipColor=__webpack_exports__.PipColor,__webpack_exports__PrereqCategory=__webpack_exports__.PrereqCategory,__webpack_exports__PublicApi=__webpack_exports__.PublicApi,__webpack_exports__Quaternion=__webpack_exports__.Quaternion,__webpack_exports__QueueStatus=__webpack_exports__.QueueStatus,__webpack_exports__QueueType=__webpack_exports__.QueueType,__webpack_exports__RadarEventType=__webpack_exports__.RadarEventType,__webpack_exports__SideType=__webpack_exports__.SideType,__webpack_exports__SpeedType=__webpack_exports__.SpeedType,__webpack_exports__Spherical=__webpack_exports__.Spherical,__webpack_exports__StanceType=__webpack_exports__.StanceType,__webpack_exports__SuperWeaponStatus=__webpack_exports__.SuperWeaponStatus,__webpack_exports__SuperWeaponType=__webpack_exports__.SuperWeaponType,__webpack_exports__TagRepeatType=__webpack_exports__.TagRepeatType,__webpack_exports__TerrainType=__webpack_exports__.TerrainType,__webpack_exports__TheaterType=__webpack_exports__.TheaterType,__webpack_exports__Vector2=__webpack_exports__.Vector2,__webpack_exports__Vector3=__webpack_exports__.Vector3,__webpack_exports__VeteranAbility=__webpack_exports__.VeteranAbility,__webpack_exports__VeteranLevel=__webpack_exports__.VeteranLevel,__webpack_exports__VhpScan=__webpack_exports__.VhpScan,__webpack_exports__WeaponType=__webpack_exports__.WeaponType,__webpack_exports__ZoneType=__webpack_exports__.ZoneType,__webpack_exports__cdapi=__webpack_exports__.cdapi;export{__webpack_exports__ApiEventType as ApiEventType,__webpack_exports__ArmorType as ArmorType,__webpack_exports__AttackState as AttackState,__webpack_exports__Bot as Bot,__webpack_exports__Box2 as Box2,__webpack_exports__BuildCat as BuildCat,__webpack_exports__BuildStatus as BuildStatus,__webpack_exports__Cylindrical as Cylindrical,__webpack_exports__Euler as Euler,__webpack_exports__FactoryStatus as FactoryStatus,__webpack_exports__FactoryType as FactoryType,__webpack_exports__GameInstanceApi as GameInstanceApi,__webpack_exports__GameMath as GameMath,__webpack_exports__InfDeathType as InfDeathType,__webpack_exports__LandTargeting as LandTargeting,__webpack_exports__LandType as LandType,__webpack_exports__LocomotorType as LocomotorType,__webpack_exports__Matrix4 as Matrix4,__webpack_exports__MovementZone as MovementZone,__webpack_exports__NavalTargeting as NavalTargeting,__webpack_exports__ObjectType as ObjectType,__webpack_exports__OrderType as OrderType,__webpack_exports__PipColor as PipColor,__webpack_exports__PrereqCategory as PrereqCategory,__webpack_exports__PublicApi as PublicApi,__webpack_exports__Quaternion as Quaternion,__webpack_exports__QueueStatus as QueueStatus,__webpack_exports__QueueType as QueueType,__webpack_exports__RadarEventType as RadarEventType,__webpack_exports__SideType as SideType,__webpack_exports__SpeedType as SpeedType,__webpack_exports__Spherical as Spherical,__webpack_exports__StanceType as StanceType,__webpack_exports__SuperWeaponStatus as SuperWeaponStatus,__webpack_exports__SuperWeaponType as SuperWeaponType,__webpack_exports__TagRepeatType as TagRepeatType,__webpack_exports__TerrainType as TerrainType,__webpack_exports__TheaterType as TheaterType,__webpack_exports__Vector2 as Vector2,__webpack_exports__Vector3 as Vector3,__webpack_exports__VeteranAbility as VeteranAbility,__webpack_exports__VeteranLevel as VeteranLevel,__webpack_exports__VhpScan as VhpScan,__webpack_exports__WeaponType as WeaponType,__webpack_exports__ZoneType as ZoneType,__webpack_exports__cdapi as cdapi};