@chronodivide/game-api 0.36.0 → 0.38.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_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:()=>r});const r=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],r=1;r<t.length;r++)for(e in t[r])e in i||!t[r].hasOwnProperty(e)||(i[e]=t[r][e]);return i}var r,o={VERSION:"1.4.1"},s={},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){r&&this.enabledFor(e)&&r(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){r=e},o.setLevel=function(e){for(var t in n.setLevel(e),s)s.hasOwnProperty(t)&&s[t].setLevel(e)},o.getLevel=function(){return n.getLevel()},o.get=function(e){return s[e]||(s[e]=new a(i({name:e},n.context)))},o.createDefaultHandler=function(s){(s=s||{}).formatter=s.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,r=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(r,[i+": "+((new Date).getTime()-n[i])+"ms"])):(t.level===o.WARN&&console.warn?r=console.warn:t.level===o.ERROR&&console.error?r=console.error:t.level===o.INFO&&console.info?r=console.info:t.level===o.DEBUG&&console.debug&&(r=console.debug),s.formatter(e,t),a(r,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,r,s;for(this.init_seed(19650218),i=1,r=0,s=this.N>t?this.N:t;s;s--){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[r]+r,this.mt[i]>>>=0,r++,++i>=this.N&&(this.mt[0]=this.mt[this.N-1],i=1),t<=r&&(r=0)}for(s=this.N-1;s;s--){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],r=0;r<i.length;++r)i[r].callback===t&&i.splice(r,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 r=0;r<i.length;++r){var s=i[r];s.callback.apply(s.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 r=E(e,t),s=o.hasOwnProperty(r);(s||b(e,t))&&(s||(o[r]=0),s="@"+ ++o[r],r=E(e+s,t+s));return new B(e,t,i,r)}:function(e,t,i){var r=E(e,t);return new B(e,t,i,r)},i=[],l=v,s=v,c=v,u=v,r={addNode:g,addLink:function(e,t,i){c();var r=m(e)||g(e),s=m(t)||g(t),i=h(e,t,i);a.push(i),A(r,i),e!==t&&A(s,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:k,forEachLinkedNode:function(e,t,i){var r=m(e);if(r&&r.links&&"function"==typeof t)return(i?function(e,t,i){for(var r=0;r<e.length;++r){var s=e[r];if(s.fromId===t&&i(n.get(s.toId),s))return!0}}:function(e,t,i){for(var r=0;r<e.length;++r){var s=e[r],a=s.fromId===t?s.toId:s.fromId;if(i(n.get(a),s))return!0}})(r.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(),k(function(e){f(e.id)}),u()},hasLink:b,hasNode:m,getLink:b};return O(r),function(){var e=r.on;r.on=function(){return r.beginUpdate=c=S,r.endUpdate=u=_,l=d,s=p,(r.on=e).apply(r,arguments)}}(),r;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,s(i,"update")):(i=new C(e,t),s(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 r=0;r<i.length;++r)T(i[r])}return n.delete(e),s(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),r=m(e.toId);return i&&0<=(t=I(e,i.links))&&i.links.splice(t,1),r&&0<=(t=I(e,r.links))&&r.links.splice(t,1),l(e,"remove"),u(),!0}function b(e,t){var i,r=m(e);if(!r||!r.links)return null;for(i=0;i<r.links.length;++i){var s=r.links[i];if(s.fromId===e&&s.toId===t)return s}return null}function v(){}function S(){t+=1}function _(){0===--t&&0<i.length&&(r.fire("changed",i),i.length=0)}function k(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 O=i(367);function I(e,t){if(!t)return-1;if(t.indexOf)return t.indexOf(e);for(var i=t.length,r=0;r<i;r+=1)if(t[r]===e)return r;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,r){this.fromId=e,this.toId=t,this.data=i,this.id=r}function E(e,t){return e.toString()+"👉 "+t.toString()}},603:e=>{function r(e,t){if(!(this instanceof r))return new r(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||s,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 s(){}function a(e,t){return e-t}(e.exports=r).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,r=this.setNodeId,s=t[e];0<e;){var a=e-1>>1,n=t[a];if(0<=i(s,n))break;r(t[e]=n,e),e=a}r(t[e]=s,e)},_down:function(e){for(var t=this.data,i=this.compare,r=this.length>>1,s=t[e],a=this.setNodeId;e<r;){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,s))break;a(t[e]=h,e),e=n}a(t[e]=s,e)}}},142:(e,t,i)=>{e.exports=function(y,e){var w=(e=e||{}).oriented,T=e.bestEffort,b=e.heuristic;b=b||k.heuristic;var v=e.distance;v=v||k.distance;var S=r();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===O){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,r=new _({compare:k.compareFScore,setNodeId:k.setHeapIndex}),s=new _({compare:k.compareFScore,setNodeId:k.setHeapIndex}),t=S.createNewState(a);o.set(e,t),t.fScore=b(a,n),t.distanceToSource=0,r.push(t),t.open=O;e=S.createNewState(n);e.fScore=b(n,a),e.distanceToSource=0,s.push(e),e.open=I;var h,l,c=Number.POSITIVE_INFINITY,u=r,d=O,p=t;for(;0<r.length&&(0<s.length||T);){var g=(u=r.length<s.length||!s.length&&T?(d=O,r):(d=I,s)).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=[],r=e;r;)i.push(r.node),r=r.parent;for(var s=t;s;)i.unshift(s.node),s=s.parent;return i}function f(e,t,i){var r,s=o.get(e.id);s||(s=S.createNewState(e),o.set(e.id,s)),s.closed||((e=(e=s).open)&&e!==d?(r=s.distanceToSource+i.distanceToSource)<c&&(h=s,l=i,c=r):(e=i.distanceToSource+v(s.node,i.node,t))>=s.distanceToSource||(r=d===O?n:a,t=e+b(s.node,r,s),c<=t||(s.fScore=t,0===s.open&&(u.push(s),u.updateItem(s.heapIndex),s.open=d),s.parent=i,s.distanceToSource=e,r===n&&t-e<p.fScore-p.distanceToSource&&(p=s))))}}}};var _=i(603),r=i(573),s=i(884),k=i(8),O=1,I=2,C=k.NO_PATH;e.exports.l2=s.l2,e.exports.l1=s.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=r();return{find:function(e,t){var i=c.getNode(e);if(!i)throw new Error("fromId is not defined in this graph: "+e);var r=c.getNode(t);if(!r)throw new Error("toId is not defined in this graph: "+t);f.reset();var s,a=new Map,n=new y({compare:w.compareFScore,setNodeId:w.setHeapIndex}),t=f.createNewState(i);a.set(e,t),t.fScore=g(i,r),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}(s=n.pop(),r))return b(s);if(p<++h)break;s.closed=!0,c.forEachLinkedNode(s.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=s.distanceToSource+m(s.node,e,t))>=i.distanceToSource||(i.parent=s,i.distanceToSource=t,i.fScore=t+g(i.node,r,i),i.fScore-i.distanceToSource<o.fScore-o.distanceToSource&&(o=i),n.updateItem(i.heapIndex)))}}}};var y=i(603),r=i(573),s=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=s.l2,e.exports.l1=s.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 s(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,r=[];return{createNewState:function(e){var t=r[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 s(e),r[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||k.heuristic;var v=e.distance;v=v||k.distance;var S=s();return{find:function(e,t){var r=y.getNode(e);if(!r)throw new Error("fromId is not defined in this graph: "+e);var s=y.getNode(t);if(!s)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 _({compare:k.compareF1Score,setNodeId:k.setH1}),l=new _({compare:k.compareF2Score,setNodeId:k.setH2}),c=Number.POSITIVE_INFINITY,u=S.createNewState(r);o.set(e,u),u.g1=0;var d=b(r,s);u.f1=d,h.push(u);u=S.createNewState(s);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(r,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,s)<c&&y.forEachLinkedNode(p.node.id,n),0<l.length&&(g=l.peek().f2)),!T||!a););return function(e){if(!e)return O;var t=[e.node],i=e.p1;for(;i;)t.push(i.node),i=i.p1;var r=e.p2;for(;r;)t.unshift(r.node),r=r.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,s),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(r,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 _=i(603),r=i(884),k=i(8),s=i(808),O=k.NO_PATH;e.exports.l2=r.l2,e.exports.l1=r.l1},808:e=>{function s(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,r=[];return{createNewState:function(e){var t=r[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 s(e),r[i]=t);return i++,t},reset:function(){i=0}}}},45:(e,t,i)=>{e.exports={aStar:i(118),aGreedy:i(142),nba:i(377)}},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__,{ActionsApi:()=>vl,AiRules:()=>sr,ApiEventType:()=>Sl,ArmorType:()=>ri,AttackState:()=>en,Bot:()=>nc,BuildCat:()=>Hi,BuildStatus:()=>Cn,CombatDamageRules:()=>ir,Country:()=>Pr,CountryRules:()=>Ti,CrateRules:()=>hr,CrewRules:()=>Ii,DMislRules:()=>Ni,FactoryStatus:()=>Da,FactoryType:()=>Gi,GameApi:()=>Ql,GameInstanceApi:()=>ip,GeneralRules:()=>Di,HoverRules:()=>Ri,InfDeathType:()=>Jt,IniFile:()=>c,IniSection:()=>h,LandTargeting:()=>To,LandType:()=>Yt,LightningStormRules:()=>Ei,LocomotorType:()=>ti,MapApi:()=>Fl,MissileRules:()=>Pi,MovementZone:()=>ii,NavalTargeting:()=>bo,ObjectRules:()=>bi,ObjectType:()=>At,OrderType:()=>Un,OverlayRules:()=>Yi,ParadropRules:()=>Bi,PipColor:()=>ei,PrereqCategory:()=>Qt,PrismRules:()=>Ci,ProductionApi:()=>ac,ProjectileRules:()=>Wi,PublicApi:()=>wp,QueueStatus:()=>ha,QueueType:()=>oa,RadarEventType:()=>Zt,RadarRules:()=>_i,RadiationRules:()=>nr,RepairRules:()=>ki,RulesApi:()=>Gl,SideType:()=>qt,SpeedType:()=>Kt,StanceType:()=>kr,SuperWeaponStatus:()=>yc,SuperWeaponType:()=>qi,TechnoRules:()=>Xi,TerrainRules:()=>Ki,TerrainType:()=>Xt,TheaterType:()=>I,ThreatRules:()=>Ai,V3RocketRules:()=>xi,VeteranAbility:()=>ai,VeteranLevel:()=>bs,VeteranRules:()=>Oi,VhpScan:()=>ni,WarheadRules:()=>Ui,WeaponRules:()=>vi,WeaponType:()=>si,ZoneType:()=>_r,cdapi:()=>Tp});__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 r=this.parseNumber(i);return void 0===r?(console.warn(`Invalid value for key ${e}. "${i}" is not a valid number or percentage string.`),t):r}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 r=this.getString(e).trim();return r=r.replace(/\,$/,""),r?r.split(t):i}getNumberArray(e,t=/\,\s*/,i=[]){let r=this.getString(e).trim();if(!r)return i;let s=[];for(var a of r.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;s.push(n)}return s}getFixedArray(e,t=/\,\s*/,i=[]){return this.getNumberArray(e,t,i).map(e=>this.toFixedPointPrecision(e))}getEnum(e,t,i,r=!1){let s=this.getString(e).trim();if(!s)return i;if(r){let e=Object.getOwnPropertyNames(t);r=e.find(e=>e.toLowerCase()===s.toLowerCase());return r?t[r]:i}return t.hasOwnProperty(s)?t[s]:i}getEnumArray(e,r,t=/\,\s*/,s=[],a=!1){let n=this.getString(e).trim();if(!n)return s;let o=[];for(let i of n.split(t)){if(!i)return s;let t=!1;if(a){let e=Object.getOwnPropertyNames(r);var h=e.find(e=>e.toLowerCase()===i.toLowerCase());h&&(o.push(r[h]),t=!0)}else r.hasOwnProperty(i)&&(o.push(r[i]),t=!0);if(!t)return console.warn(`Invalid value "${i}" for key "${e}".`),s}return o}getHighestNumericIndex(){let i=0,r;return this.entries.forEach((e,t)=>{r=parseInt(t,10),r>i&&(i=r)}),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={},r=o,s,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 s=this.unsafe(t[1]),void(r=o[s]=o[s]||{});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),r[e]?Array.isArray(r[e])||(r[e]=[r[e]]):r[e]=[]),Array.isArray(r[e])?r[e].push(t):r[e]=t}}}),Object.keys(o).filter((e,t,i)=>{if(!o[e]||"object"!=typeof o[e]||Array.isArray(o[e]))return!1;let r=this.dotSplit(e),s=o,a=r.pop();var n=a.replace(/\\\./g,".");return r.forEach(function(e,t,i){s[e]&&"object"==typeof s[e]||(s[e]={}),s=s[e]}),(s!==o||n!==a)&&(s[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(s){if(s=(s||"").trim(),this.isQuoted(s))return s=s.substr(1,s.length-2);{let i=!1,r="";for(let e=0,t=s.length;e<t;e++){var a=s.charAt(e);if(i)-1!=="\\;#".indexOf(a)?r+=a:r+="\\"+a,i=!1;else{if(-1!==";#".indexOf(a))break;"\\"===a?i=!0:r+=a}}return i&&(r+="\\"),r=r.trim(),r}}}class w{constructor(e,t,i=w.LITTLE_ENDIAN){this.endianness=i,this.position=0,this._dynamicSize=!0,this._byteLength=0,this.failurePosition=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||1)}get dynamicSize(){return this._dynamicSize}set dynamicSize(e){e||this._trimAlloc(),this._dynamicSize=e}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){if(this._trimAlloc(),!this._buffer)throw new Error;return 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._buffer&&(this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength)}get dataView(){if(!this._dataView)throw new Error;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=w.BIG_ENDIAN,this}_realloc(t){if(this._dynamicSize){var i=this._byteOffset+this.position+t;if(!this._buffer)throw new Error;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 r=new ArrayBuffer(e),t=new Uint8Array(this._buffer);const s=new Uint8Array(r,0,t.length);s.set(t),this.buffer=r,this._byteLength=i}}}_trimAlloc(){if(!this._buffer)throw new Error;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){if(this._realloc(4*e),!this._buffer)throw new Error;var i=new Int32Array(this._buffer,this.byteOffset+this.position,e);return w.arrayToNative(i,void 0===t?this.endianness:t),this.position+=4*e,i}mapInt16Array(e,t){if(this._realloc(2*e),!this._buffer)throw new Error;var i=new Int16Array(this._buffer,this.byteOffset+this.position,e);return w.arrayToNative(i,void 0===t?this.endianness:t),this.position+=2*e,i}mapInt8Array(e){if(this._realloc(e),!this._buffer)throw new Error;var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e,t}mapUint32Array(e,t){if(this._realloc(4*e),!this._buffer)throw new Error;var i=new Uint32Array(this._buffer,this.byteOffset+this.position,e);return w.arrayToNative(i,void 0===t?this.endianness:t),this.position+=4*e,i}mapUint16Array(e,t){if(this._realloc(2*e),!this._buffer)throw new Error;var i=new Uint16Array(this._buffer,this.byteOffset+this.position,e);return w.arrayToNative(i,void 0===t?this.endianness:t),this.position+=2*e,i}mapUint8Array(e){if(this._realloc(e),!this._buffer)throw new Error;var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e,t}mapFloat64Array(e,t){if(this._realloc(8*e),!this._buffer)throw new Error;var i=new Float64Array(this._buffer,this.byteOffset+this.position,e);return w.arrayToNative(i,void 0===t?this.endianness:t),this.position+=8*e,i}mapFloat32Array(e,t){if(this._realloc(4*e),!this._buffer)throw new Error;var i=new Float32Array(this._buffer,this.byteOffset+this.position,e);return w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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 w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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 w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._dataView)throw new Error;e=this._dataView.getInt32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readInt16(e){if(!this._dataView)throw new Error;e=this._dataView.getInt16(this.position,void 0===e?this.endianness:e);return this.position+=2,e}readInt8(){if(!this._dataView)throw new Error;var e=this._dataView.getInt8(this.position);return this.position+=1,e}readUint32(e){if(!this._dataView)throw new Error;e=this._dataView.getUint32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readUint16(e){if(!this._dataView)throw new Error;e=this._dataView.getUint16(this.position,void 0===e?this.endianness:e);return this.position+=2,e}readUint8(){if(!this._dataView)throw new Error;var e=this._dataView.getUint8(this.position);return this.position+=1,e}readFloat32(e){if(!this._dataView)throw new Error;e=this._dataView.getFloat32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readFloat64(e){if(!this._dataView)throw new Error;e=this._dataView.getFloat64(this.position,void 0===e?this.endianness:e);return this.position+=8,e}writeInt32(e,t){if(this._realloc(4),!this._dataView)throw new Error;return this._dataView.setInt32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeInt16(e,t){if(this._realloc(2),!this._dataView)throw new Error;return this._dataView.setInt16(this.position,e,void 0===t?this.endianness:t),this.position+=2,this}writeInt8(e){if(this._realloc(1),!this._dataView)throw new Error;return this._dataView.setInt8(this.position,e),this.position+=1,this}writeUint32(e,t){if(this._realloc(4),!this._dataView)throw new Error;return this._dataView.setUint32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeUint16(e,t){if(this._realloc(2),!this._dataView)throw new Error;return this._dataView.setUint16(this.position,e,void 0===t?this.endianness:t),this.position+=2,this}writeUint8(e){if(this._realloc(1),!this._dataView)throw new Error;return this._dataView.setUint8(this.position,e),this.position+=1,this}writeFloat32(e,t){if(this._realloc(4),!this._dataView)throw new Error;return this._dataView.setFloat32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeFloat64(e,t){if(this._realloc(8),!this._dataView)throw new Error;return this._dataView.setFloat64(this.position,e,void 0===t?this.endianness:t),this.position+=8,this}static memcpy(e,t,i,r,s){const a=new Uint8Array(e,t,s);s=new Uint8Array(i,r,s);a.set(s)}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(r){const s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);for(let i=0;i<r.byteLength;i+=r.BYTES_PER_ELEMENT)for(let e=i+r.BYTES_PER_ELEMENT-1,t=i;e>t;e--,t++){var a=s[t];s[t]=s[e],s[e]=a}return r}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("")}readStruct(t){const i={};var r,s=this.position;for(let e=0;e<t.length;e+=2){if(r=t[e+1],void 0===(r=this.readType(r,i)))return 0===this.failurePosition&&(this.failurePosition=this.position),void(this.position=s);i[t[e]]=r}return i}readUCS2String(e,t){return w.createStringFromArray(this.readUint16Array(e,t))}writeUCS2String(e,t,i){void 0===i&&(i=e.length);let r=0;for(;r<e.length&&r<i;r++)this.writeUint16(e.charCodeAt(r),t);for(;r<i;r++)this.writeUint16(0);return this}readString(e,t){return void 0===t||"ASCII"===t?w.createStringFromArray(this.mapUint8Array(void 0===e?this.byteLength-this.position:e)):(new TextDecoder).decode(this.mapUint8Array(e))}writeString(t,e,i){if(void 0===e||"ASCII"===e)if(void 0!==i){let e;var r=Math.min(t.length,i);for(e=0;e<r;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;if(!this._buffer)throw new Error;var i=new Uint8Array(this._buffer,this._byteOffset+this.position);let r=t;void 0!==e&&(r=Math.min(e,t));let s=0;for(;s<r&&0!==i[s];s++);var a=w.createStringFromArray(this.mapUint8Array(s));return void 0!==e?this.position+=r-s:s!==t&&(this.position+=1),a}writeCString(t,i){if(void 0!==i){let e;var r=Math.min(t.length,i);for(e=0;e<r;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}readType(e,i){if("function"==typeof e)return e(this,i);if(!("object"!=typeof e||e instanceof Array))return e.get(this,i);if(e instanceof Array&&3!==e.length)return this.readStruct(e);let r=void 0,t=void 0,s="ASCII";var a,n=this.position;switch("string"==typeof e&&/:/.test(e)&&(e=(a=e.split(":"))[0],a=a[1],t=parseInt(void 0!==i[a]?i[a]:a,10)),"string"==typeof e&&/,/.test(e)&&(e=(a=e.split(","))[0],s=a[1]),t=t||0,e){case"uint8":r=this.readUint8();break;case"int8":r=this.readInt8();break;case"uint16":r=this.readUint16(this.endianness);break;case"int16":r=this.readInt16(this.endianness);break;case"uint32":r=this.readUint32(this.endianness);break;case"int32":r=this.readInt32(this.endianness);break;case"float32":r=this.readFloat32(this.endianness);break;case"float64":r=this.readFloat64(this.endianness);break;case"uint16be":r=this.readUint16(w.BIG_ENDIAN);break;case"int16be":r=this.readInt16(w.BIG_ENDIAN);break;case"uint32be":r=this.readUint32(w.BIG_ENDIAN);break;case"int32be":r=this.readInt32(w.BIG_ENDIAN);break;case"float32be":r=this.readFloat32(w.BIG_ENDIAN);break;case"float64be":r=this.readFloat64(w.BIG_ENDIAN);break;case"uint16le":r=this.readUint16(w.LITTLE_ENDIAN);break;case"int16le":r=this.readInt16(w.LITTLE_ENDIAN);break;case"uint32le":r=this.readUint32(w.LITTLE_ENDIAN);break;case"int32le":r=this.readInt32(w.LITTLE_ENDIAN);break;case"float32le":r=this.readFloat32(w.LITTLE_ENDIAN);break;case"float64le":r=this.readFloat64(w.LITTLE_ENDIAN);break;case"cstring":r=this.readCString(t);break;case"string":r=this.readString(t,s);break;case"u16string":r=this.readUCS2String(t,this.endianness);break;case"u16stringle":r=this.readUCS2String(t,w.LITTLE_ENDIAN);break;case"u16stringbe":r=this.readUCS2String(t,w.BIG_ENDIAN);break;default:if(3===e.length){const d=e[1],p=e[2];let t=0;if(t="function"==typeof p?p(i,this,e):"string"==typeof p&&void 0!==i[p]?parseInt(i[p],10):parseInt(p,10),"string"==typeof d){var o=d.replace(/(le|be)$/,"");let e=void 0;switch(/le$/.test(d)?e=w.LITTLE_ENDIAN:/be$/.test(d)&&(e=w.BIG_ENDIAN),"*"===p&&(t=void 0),t=t||0,o){case"uint8":r=this.readUint8Array(t);break;case"uint16":r=this.readUint16Array(t,e);break;case"uint32":r=this.readUint32Array(t,e);break;case"int8":r=this.readInt8Array(t);break;case"int16":r=this.readInt16Array(t,e);break;case"int32":r=this.readInt32Array(t,e);break;case"float32":r=this.readFloat32Array(t,e);break;case"float64":r=this.readFloat64Array(t,e);break;case"cstring":case"utf16string":case"string":if(void 0===t)for(r=[];!this.isEof();){var h=this.readType(d,i);if(void 0===h)break;r.push(h)}else{r=new Array(t);for(let e=0;e<t;e++)r[e]=this.readType(d,i)}}}else if("*"===p)for(r=[];;){var l=this.position;try{var c=this.readType(d,i);if(void 0===c){this.position=l;break}r.push(c)}catch(e){this.position=l;break}}else{t=t||0,r=new Array(t);for(let e=0;e<t;e++){var u=this.readType(d,i);if(void 0===u)return;r[e]=u}}break}}return void 0!==t&&(this.position=n+t),r}writeStruct(t,i,e=!1){e&&(t=w.defWriteStruct(t,i));for(let e=0;e<t.length;e+=2){var r=t[e+1];this.writeType(r,i[t[e]],i)}return this}static defWriteStruct(i,r){const s=[];for(let e=i.length-2;0<=e;e-=2){let t=i[e+1];var a=i[e];if("string"==typeof t&&/,.+:[A-Za-z_]/.test(t)){let e=t.split(":");var n=e[1];e=e[0].split(","),t=e[0];const o=(new TextEncoder).encode(r[a]);r[n]=o.length,s.push(e=>e.writeUint8Array(o))}else s.push(t);s.push(a)}return s.reverse()}writeType(e,t,i){if("function"==typeof e)return e(this,t,i),this;if("object"==typeof e&&!(e instanceof Array))return e.set(this,t,i),this;let r=void 0,s="ASCII";var a,n=this.position;switch("string"==typeof e&&/:/.test(e)&&(e=(a=e.split(":"))[0],a=a[1],r=parseInt(void 0!==i[a]?i[a]:a,10)),"string"==typeof e&&/,/.test(e)&&(e=(a=e.split(","))[0],s=a[1]),e){case"uint8":this.writeUint8(t);break;case"int8":this.writeInt8(t);break;case"uint16":this.writeUint16(t,this.endianness);break;case"int16":this.writeInt16(t,this.endianness);break;case"uint32":this.writeUint32(t,this.endianness);break;case"int32":this.writeInt32(t,this.endianness);break;case"float32":this.writeFloat32(t,this.endianness);break;case"float64":this.writeFloat64(t,this.endianness);break;case"uint16be":this.writeUint16(t,w.BIG_ENDIAN);break;case"int16be":this.writeInt16(t,w.BIG_ENDIAN);break;case"uint32be":this.writeUint32(t,w.BIG_ENDIAN);break;case"int32be":this.writeInt32(t,w.BIG_ENDIAN);break;case"float32be":this.writeFloat32(t,w.BIG_ENDIAN);break;case"float64be":this.writeFloat64(t,w.BIG_ENDIAN);break;case"uint16le":this.writeUint16(t,w.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(t,w.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(t,w.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(t,w.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(t,w.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(t,w.LITTLE_ENDIAN);break;case"cstring":this.writeCString(t,r);break;case"string":this.writeString(t,s,r);break;case"u16string":this.writeUCS2String(t,this.endianness,r);break;case"u16stringle":this.writeUCS2String(t,w.LITTLE_ENDIAN,r);break;case"u16stringbe":this.writeUCS2String(t,w.BIG_ENDIAN,r);break;default:if(3===e.length){var o=e[1];for(const h of t)this.writeType(o,h,i);break}this.writeStruct(e,t)}return void 0!==r&&(this.position=n,this._realloc(r),this.position=n+r),this}}w.BIG_ENDIAN=!1,w.LITTLE_ENDIAN=!0,w.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 w(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 w(e);return i._trimAlloc=()=>{},new this(i,t)}static factory(e,t,i=0,r=e.byteLength){r=new DataView(e.buffer,e.byteOffset+i,r);const s=new w(r);return s._trimAlloc=()=>{},new this(s,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,r,s;var a;for(t in e)if(e.hasOwnProperty(t)){for(s in i=e[t],r=new h(t),i)i.hasOwnProperty(s)&&(a=i[s],r.set(s,a));this.sections.set(t,r)}}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"].indexOf(e)}mergeWith(e){return e.sections.forEach((e,t)=>{let r=this.getOrCreateSection(t);if(this.isValueArray(t)){let i=r.getHighestNumericIndex()+1;e.entries.forEach((e,t)=>{r.set((i++).toString(),e)})}else e.entries.forEach((e,t)=>{r.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 r=new Uint8Array(i*e),s=0;for(let t=0;t<this.height&&!(t>=e);t++)for(let e=0;e<this.width;e++)e>=i||(r[s++]=this.imageData[t*this.width+e]);return t.imageData=r,t.x=this.x,t.y=this.y,t}}class r{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 s=e.stream;if(0===s.readInt16()){this.width=s.readInt16(),this.height=s.readInt16(),this.numImages=s.readInt16();let r=[];for(let e=0;e<this.numImages;++e)r.push(this.readFrameHeader(s));this.images=[];for(let i=0;i<this.numImages;++i){var{compressionType:a,imageDataStartOffset:n,x:o,y:h,width:l,height:c}=r[i];let e=i<this.numImages-1?r[i+1].imageDataStartOffset:s.byteLength;e<n&&(e=s.byteLength);var u=e-n;s.seek(n);u=this.readImageData(s,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(),r=e.readInt16(),s=e.readInt16(),a=e.readUint8();return e.readUint8(),e.readUint8(),e.readUint8(),e.readInt32(),e.readInt32(),{x:t,y:i,width:r,height:s,compressionType:a,imageDataStartOffset:e.readInt32()}}readImageData(r,e,s,t,i){var a=e*s;if(t<=1){var n=new Uint8Array(r.buffer,r.byteOffset+r.position,a);return r.position+=a,n}if(2===t){let t=0,i=new Uint8Array(a);for(let e=0;e<s;++e){var o=r.readUint16()-2;i.set(new Uint8Array(r.buffer,r.byteOffset+r.position,o),t),r.position+=o,t+=o}return i}if(3!==t)return new Uint8Array;t=new Uint8Array(r.buffer,r.byteOffset+r.position,i);return r.position+=i,class{static decode(r,s,t){let a=new Uint8Array(s*t),n=0,o=0;for(let e=0;e<t;e++){let t=(r[n+1]<<8|r[n])-2;n+=2;let i=0;for(;0<t--;){let e=r[n++];if(0!==e)i++,a[o++]=e;else for(t--,e=r[n++],i+e>s&&(e=s-i&255),i+=e;0!=e--;)a[o++]=0}}return a}}.decode(t,e,s)}getImage(e){if(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 r;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 s=__webpack_require__(949).Vector3;const u=[new s(.54946297,-183e-6,-.835518),new s(.00014400001,.54940403,-.83555698),new s(-.54940403,-68000001e-12,-.83555698),new s(106e-6,-.54946297,-.835518),new s(.94900799,.00031599999,-.31525001),new s(-186e-6,.94899702,-.31528401),new s(-.94899702,.00031800001,-.31528401),new s(-447e-6,-.94900799,-.31525001),new s(.95084399,-279e-6,.30967101),new s(202e-6,.95084798,.30965701),new s(-.95084798,-70000002e-12,.30965701),new s(147e-6,-.95084399,.30967101),new s(.55237001,-11e-6,.83359897),new s(19999999e-12,.55238003,.833592),new s(-.55238003,57000001e-12,.83359301),new s(-66000001e-12,-.55237001,.83359897)],p=[new s(.67121398,.19849201,-.714194),new s(.26964301,.58439398,-.76536),new s(-.040546,.096988,-.99445897),new s(-.57242799,-.091913998,-.81478697),new s(-.17140099,-.57270998,-.80163902),new s(.36255699,-.30299899,-.88133103),new s(.81034702,-.34897199,-.470698),new s(.103962,.93867201,-.328767),new s(-.324047,.58766901,-.74137598),new s(-.80086499,.34046099,-.49264699),new s(-.66549802,-.59014702,-.45698899),new s(.314767,-.803002,-.506073),new s(.97262901,.151076,-.17655),new s(.680291,.68423599,-.26272699),new s(-.52007902,.82777703,-.210483),new s(-.96164399,-.179001,-.207847),new s(-.262714,-.937451,-.22840101),new s(.219707,-.97130102,.091124997),new s(.92380798,-.229975,.30608699),new s(-.082488999,.97065997,.225866),new s(-.59179801,.69678998,.40528899),new s(-.92529601,.36660099,.097111002),new s(-.705051,-.68777502,.172828),new s(.7324,-.68036699,-.026304999),new s(.85516202,.37458199,.358311),new s(.47300601,.83648002,.276705),new s(-.097617,.65411198,.750072),new s(-.90412402,-.153725,.39865801),new s(-.211916,-.85808998,.46773201),new s(.50022697,-.67440802,.543091),new s(.584539,-.110249,.80384099),new s(.43737301,.45464399,.77588898),new s(-.042440999,.083318003,.995619),new s(-.59625101,.22013199,.77202803),new s(-.506455,-.39697701,.76544899),new s(.070569001,-.47847399,.87526202)],g=[new s(.45651099,-.073968001,-.88663799),new s(.50769401,.38511699,-.77067),new s(.095431998,.22666401,-.96928602),new s(-.35876599,.54318798,-.75910097),new s(-.361276,.13299499,-.92292601),new s(-.48311701,-.32406601,-.813375),new s(-.018073,-.197559,-.980124),new s(.3211,-.501477,-.80337799),new s(.79949099,.069615997,-.59662998),new s(.390971,.77130598,-.50222403),new s(.080782004,.61448997,-.784778),new s(-.73275,.41143101,-.54203498),new s(-.73525399,.0091019999,-.67773098),new s(-.80249399,-.39490801,-.44727099),new s(-.13413,-.58915502,-.79680902),new s(.71955299,-.37622699,-.58369303),new s(.96687502,.173593,-.187132),new s(.760831,.51910597,-.38944301),new s(-.114642,.87551898,-.46938601),new s(-.53236699,.76885903,-.354177),new s(-.96226698,.024977,-.27095801),new s(-.46738699,-.721986,-.51018202),new s(.058449998,-.85235399,-.51968902),new s(.49823299,-.74374002,-.44566301),new s(.93915099,-.27024499,-.212044),new s(.58393198,.80944198,-.061857),new s(.183797,.97322798,-.138007),new s(-.88435501,.45221901,-.115822),new s(-.943178,-.33206701,.012138),new s(-.69844002,-.70656699,-.113772),new s(-.228411,-.95470601,-.190694),new s(.73156399,-.675861,-.089588001),new s(.96925098,.046804,.24158201),new s(.85564703,.50347698,.119916),new s(-.25115299,.96794701,-80999998e-12),new s(-.64779502,.75674897,.087711997),new s(-.96916401,.14519399,.1991),new s(-.41479301,-.88896698,.194126),new s(.25077501,-.961178,-.115109),new s(.47862899,-.84259301,.246883),new s(.89004397,-.39614201,.225595),new s(.52405101,.76235998,.37970701),new s(.11962,.94548202,.30291),new s(-.76085001,.49007499,.42536199),new s(-.86978501,-.20215,.450122),new s(-.70946699,-.60242403,.36570701),new s(.019308999,-.95887101,.28318599),new s(.626113,-.564677,.53770101),new s(.769943,-.126663,.62541503),new s(.76419097,.35070199,.54131401),new s(-.001878,.74136698,.67109799),new s(-.37088001,.81836802,.43900099),new s(-.71390897,.12865201,.68831801),new s(-.295165,-.73866397,.60601401),new s(.186195,-.73836899,.648184),new s(.387523,-.35878301,.84917599),new s(.481022,.124846,.86777401),new s(.391808,.54505599,.741216),new s(-.0035359999,.36559799,.93076599),new s(-.42049801,.484961,.76680797),new s(-.35490301,.019470001,.93470001),new s(-.54783702,-.35920799,.75554299),new s(-.106662,-.445115,.88909799),new s(.086796001,-.059307002,.99445897)],m=[new s(.52657801,-.35962099,-.77031702),new s(.150482,.43598399,.88728398),new s(.414195,.73825502,-.53237402),new s(.075152002,.91624898,-.393498),new s(-.316149,.93073601,-.18379299),new s(-.77381903,.62333399,-.11251),new s(-.90084201,.42853701,-.069568001),new s(-.99894202,-.010971,.044665001),new s(-.979761,-.15767001,-.123324),new s(-.91127402,-.362371,-.19562),new s(-.62406898,-.72094101,-.301301),new s(-.310173,-.80934501,-.498752),new s(.146613,-.81581903,-.55941403),new s(-.71651602,-.69435602,-.066887997),new s(.50397199,-.114202,-.85613698),new s(.45549101,.87262702,-.176211),new s(-.00501,-.114373,-.99342501),new s(-.104675,-.327701,-.93896502),new s(.56041199,.75258899,-.34575599),new s(-.060575999,.82162797,-.566796),new s(-.30234101,.79700702,-.522847),new s(-.671543,.67074001,-.314863),new s(-.77840102,-.12835699,.61450499),new s(-.92404997,.278382,-.261985),new s(-.69977301,-.55049098,-.45527801),new s(-.56824797,-.51718903,-.64000797),new s(.054097999,-.93286401,-.356143),new s(.75838202,.57289302,-.31088799),new s(.0036200001,.30502599,-.95233703),new s(-.060849998,-.98688602,-.14951099),new s(.63523,.045478001,-.77098298),new s(.52170497,.241309,-.81828701),new s(.26940399,.63542497,-.72364098),new s(.045676,.67275399,-.738455),new s(-.180511,.67465699,-.71571898),new s(-.397131,.63664001,-.66104198),new s(-.55200398,.47251499,-.687038),new s(-.77217001,.08309,-.62996),new s(-.669819,-.119533,-.73284),new s(-.54045498,-.31844401,-.77878201),new s(-.38613501,-.522789,-.75999397),new s(-.261466,-.68856698,-.676395),new s(-.019412,-.69610298,-.71767998),new s(.30356899,-.48184401,-.82199299),new s(.68193901,-.19512901,-.70490003),new s(-.24488901,-.116562,-.96251899),new s(.80075902,-.022979001,-.59854603),new s(-.37027499,.095583998,-.92399102),new s(-.33067101,-.32657799,-.88543999),new s(-.16322,-.52757901,-.83367902),new s(.12639,-.313146,-.941257),new s(.34954801,-.27222601,-.89649802),new s(.23991799,-.085825004,-.96699202),new s(.390845,.081537001,-.91683799),new s(.25526699,.26869699,-.92878503),new s(.146245,.48043799,-.86474901),new s(-.32601601,.47845599,-.81534898),new s(-.46968201,-.112519,-.87563598),new s(.81844002,-.25852001,-.51315099),new s(-.474318,.292238,-.83043301),new s(.778943,.39584199,-.48637101),new s(.62409401,.39377299,-.67487001),new s(.74088597,.203834,-.63995302),new s(.48021701,.565768,-.67029703),new s(.38093001,.42453501,-.82137799),new s(-.093422003,.50112402,-.86031801),new s(-.236485,.29619801,-.92538702),new s(-.131531,.093959004,-.98684901),new s(-.82356203,.29577699,-.48400599),new s(.61106598,-.624304,-.486664),new s(.069495998,-.52033001,-.85113299),new s(.226522,-.66487902,-.711775),new s(.47130799,-.56890398,-.67395699),new s(.38842499,-.74262398,-.54556),new s(.78367501,-.48072901,-.39338499),new s(.962394,.135676,-.235349),new s(.876607,.172034,-.449406),new s(.63340503,.58979303,-.50094098),new s(.182276,.80065799,-.57072097),new s(.177003,.76413399,.62029701),new s(-.544016,.675515,-.49772099),new s(-.67929697,.28646699,-.67564201),new s(-.59039098,.091369003,-.801929),new s(-.82436001,-.13312399,-.55018902),new s(-.71579403,-.33454201,-.61296099),new s(.17428599,-.89248401,.416049),new s(-.082528003,-.83712298,-.54075301),new s(.28333101,-.88087398,-.37918901),new s(.675134,-.42662701,-.60181701),new s(.84372002,-.512335,-.160156),new s(.97730398,-.098555997,-.18752),new s(.846295,.522672,-.102947),new s(.67714101,.72132498,-.145501),new s(.32096499,.87089199,-.37219399),new s(-.178978,.911533,-.37023601),new s(-.44716901,.82670099,-.341474),new s(-.70320302,.496328,-.50908101),new s(-.97718102,.063562997,-.202674),new s(-.87817001,-.412938,.241455),new s(-.83583099,-.35855001,-.415728),new s(-.499174,-.69343299,-.51959199),new s(-.188789,-.92375302,-.33322501),new s(.19225401,-.96936101,-.152896),new s(.51594001,-.783907,-.34539199),new s(.90592498,-.30095199,-.29787099),new s(.99111199,-.127746,.037106998),new s(.99513501,.098424003,-.0043830001),new s(.76012301,.64627701,.067367002),new s(.205221,.95958,-.192591),new s(-.042750001,.97951299,-.19679099),new s(-.43801701,.89892697,.0084920004),new s(-.82199401,.48078501,-.30523899),new s(-.89991701,.081710003,-.42833701),new s(-.92661202,-.144618,-.347096),new s(-.79365999,-.55779201,-.24283899),new s(-.43134999,-.84777898,-.30855799),new s(-.0054919999,-.96499997,.26219299),new s(.58790499,-.80402601,-.088940002),new s(.69949299,-.66768599,-.254765),new s(.88930303,.359795,-.282291),new s(.780972,.197037,.59267199),new s(.52012098,.50669599,.68755698),new s(.40389499,.69396102,.59605998),new s(-.154983,.89923602,.40909001),new s(-.65733802,.53716803,.528543),new s(-.74619502,.33409101,.575827),new s(-.62495202,-.049144,.77911502),new s(.31814101,-.254715,.913185),new s(-.555897,.405294,.725752),new s(-.79443401,.099405997,.59916002),new s(-.64036101,-.68946302,.33849499),new s(-.12671299,-.73409498,.66711998),new s(.105457,-.78081697,.61579502),new s(.40799299,-.48091599,.77605498),new s(.69513601,-.54512,.468647),new s(.97319102,-.0064889998,.229908),new s(.94689399,.317509,-.050799001),new s(.56358302,.82561201,.027183),new s(.325773,.94542301,.0069490001),new s(-.171821,.98509699,-.0078149997),new s(-.67044097,.73993897,.054768998),new s(-.822981,.55496198,.121322),new s(-.96619302,.117857,.229307),new s(-.95376903,-.29470399,.058945),new s(-.86438698,-.50272799,-.010015),new s(-.53060901,-.84200603,-.097365998),new s(-.162618,-.98407501,.071772002),new s(.081446998,-.99601102,.036439002),new s(.74598402,-.66596299,.00076199998),new s(.94205701,-.32926899,-.064106002),new s(.93970197,-.28108999,.194803),new s(.77121401,.55067003,.319363),new s(.641348,.73069,.23402099),new s(.080682002,.99669099,.0098789996),new s(-.046725001,.97664303,.20972501),new s(-.53107601,.82100099,.209562),new s(-.69581503,.65599,.29243499),new s(-.97612202,.216709,-.014913),new s(-.96166098,-.14412899,.23331399),new s(-.772084,-.61364698,.165299),new s(-.44960001,-.83605999,.314426),new s(-.39269999,-.91461599,.096247002),new s(.390589,-.91947001,.044890001),new s(.58252901,-.79919797,.148127),new s(.866431,-.48981199,.096864),new s(.90458697,.111498,.41145),new s(.95353699,.23232999,.191806),new s(.497311,.77080297,.398177),new s(.194066,.95631999,.218611),new s(.422876,.882276,.206797),new s(-.373797,.84956598,.37217399),new s(-.53449702,.71402299,.4522),new s(-.881827,.23716,.40759799),new s(-.904948,-.014069,.42528901),new s(-.751827,-.51281703,.41445801),new s(-.50101501,-.69791698,.51175803),new s(-.23519,-.92592299,.295555),new s(.228983,-.95393997,.193819),new s(.734025,-.63489801,.241062),new s(.91375297,-.063253,-.40131599),new s(.90573502,-.161487,.391875),new s(.85892999,.342446,.38074899),new s(.62448603,.60758102,.49077699),new s(.28926399,.85747898,.42550799),new s(.069968,.90216899,.42567101),new s(-.28617999,.94069999,.182165),new s(-.57401299,.80511898,-.14930899),new s(.111258,.099717997,-.98877603),new s(-.30539301,-.94422799,-.12316),new s(-.60116601,-.78957599,.123163),new s(-.290645,-.81213999,.50591898),new s(-.064920001,-.87716299,.47578499),new s(.408301,-.862216,.29978901),new s(.56609702,-.72556603,.39126399),new s(.83936399,-.427387,.33586901),new s(.81889999,-.041305002,.57244802),new s(.71978402,.41499701,.55649698),new s(.88174403,.45027,.140659),new s(.40182301,-.89822,-.17815199),new s(-.054019999,.79134399,.60898),new s(-.29377401,.76399398,.57446498),new s(-.450798,.61034697,.65135098),new s(-.63822103,.186694,.74687302),new s(-.87287003,-.25712699,.41470799),new s(-.58725703,-.52170998,.618828),new s(-.35365799,-.64197397,.680291),new s(.041648999,-.61127299,.79032302),new s(.348342,-.77918297,.52108699),new s(.499167,-.62244099,.602826),new s(.79001898,-.30383101,.53250003),new s(.66011798,.060733002,.74870199),new s(.60492098,.29416099,.73996001),new s(.38569701,.37934601,.84103203),new s(.239693,.207876,.94833201),new s(.012623,.25853199,.96591997),new s(-.100557,.457147,.88368797),new s(.046967,.62858802,.77631903),new s(-.43039101,-.44540501,.785097),new s(-.43429101,-.196228,.87913901),new s(-.25663701,-.336867,.90590203),new s(-.131372,-.15891001,.97851402),new s(.102379,-.208767,.972592),new s(.195687,-.450129,.87125802),new s(.62731898,-.42314801,.65377098),new s(.68743902,-.171583,.70568198),new s(.27592,-.021255,.96094602),new s(.45936701,.15746599,.87417799),new s(.285395,.583184,.76055598),new s(-.81217402,.46030301,.35846099),new s(-.189068,.64122301,.743698),new s(-.338875,.47648001,.811252),new s(-.92099398,.347186,.176727),new s(.040638998,.024465,.99887401),new s(-.73913199,-.35374701,.57318997),new s(-.60351199,-.28661501,.74405998),new s(-.188676,-.547059,.81555402),new s(-.026045,-.39782,.91709399),new s(.26789701,-.649041,.71202302),new s(.518246,-.28489101,.80638599),new s(.493451,-.066532999,.86722499),new s(-.328188,.140251,.93414301),new s(.328188,.140251,.93414301),new s(-.328188,.140251,.93414301),new s(-.328188,.140251,.93414301),new s(-.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 T{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=[],r=new f(this.sizeX+1,this.sizeY+1,this.sizeZ+1);for(let e=0,t=this.spans.length;e<t;e++){var s=this.spans[e].voxels;for(let e=0,t=s.length;e<t;e++){var a=s[e];i.push(a),r.add(a)}}return{voxels:i,voxelField:r}}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 b{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)}}b.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 s=e.stream;if(this.sections=[],!(s.byteLength<b.size)){let r=new b;if(r.read(s),r.headerCount&&r.tailerCount&&r.tailerCount===r.headerCount){for(let e=0;e<r.headerCount;++e){const n=new T;this.readSectionHeader(n,s),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=s.position;s.seek(s.position+r.bodySize);let t=[];for(let e=0;e<r.tailerCount;++e)t[e]=this.readSectionTailer(this.sections[e],s);let i=0;for(let e=0;e<r.headerCount;++e)s.seek(a),i+=this.readSectionBodySpans(this.sections[e],t[e],s);this.voxelCount=i}}}readSectionHeader(e,t){e.name=t.readCString(16),t.readUint32(),t.readUint32(),t.readUint32()}readSectionTailer(e,t){var i=t.readUint32(),r=t.readUint32(),s=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:r,dataSpanOffset:s}}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:r,sizeY:s,sizeZ:a}=e;let n=new Array(s);for(let t=0;t<s;++t){n[t]=new Array(r);for(let e=0;e<r;++e)n[t][e]=i.readInt32()}let o=new Array(s);for(let t=0;t<s;++t){o[t]=new Array(r);for(let e=0;e<r;++e)o[t][e]=i.readInt32()}let h=e.spans=[],l=0;for(let t=0;t<s;++t)for(let e=0;e<r;++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,r,s,a){if(-1===e||-1===t)return[];let n=[];for(let t=0;t<s;){t+=a.readUint8();var o=a.readUint8();for(let e=0;e<o;++e){var h={x:i,y:r,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 T).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);(s=_=_||{})[s.ExtraData=1]="ExtraData",s[s.ZData=2]="ZData",s[s.DamagedData=4]="DamagedData";const B=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 r=e.readInt32();this.extraX=e.readInt32(),this.extraY=e.readInt32(),this.extraWidth=e.readInt32(),this.extraHeight=e.readInt32();var s=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=(s&_.ZData)===_.ZData,this.hasZData&&(e.position+=t*i/2),this.hasExtraData=(s&_.ExtraData)===_.ExtraData,this.hasExtraData&&(s=Math.abs(this.extraWidth*this.extraHeight),this.extraData=new Uint8Array(e.buffer,e.byteOffset+e.position,s),e.position+=s),this.hasZData&&this.hasExtraData&&0<r&&r<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 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,r=new Uint8Array(t.buffer,t.byteOffset+t.position,4*i);this.images=[];for(let e=0;e<i;e++){var s=r[4*e+3]<<24|r[4*e+2]<<16|r[4*e+1]<<8|r[4*e];t.seek(s);s=new E(t,this.blockWidth,this.blockHeight);this.images.push(s)}}}class x{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")}}function N(e,t="0000"){e=""+e;return t.substring(0,t.length-e.length)+e}function R(e,t){return e.toLowerCase()===t.toLowerCase()}function M(t){var i=t.length;let r=new Uint8Array(i);for(let e=0;e<i;e++)r[e]=t.charCodeAt(e);return r}function D(e){return M(x.decode(e))}function L(t){var i=t.length;let r="";for(let e=0;e<i;e++){var s=t.charCodeAt(e);r+=String.fromCharCode(s>>8),r+=String.fromCharCode(255&s)}return r}function F(t){var i=t.length;let r="";for(let e=0;e<i;e+=2){var s=(t.charCodeAt(e)<<8)+t.charCodeAt(e+1);r+=String.fromCharCode(s)}return r}class j{constructor(e,t,i){this.r=e,this.g=t,this.b=i}static fromRgb(e,t,i){return new j(e,t,i)}static fromHsv(e,t,i){let r=0,s=0,a=0;if(e=e/255*360%360,i/=255,0===(t/=255))r=i,s=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:r=i,s=l,a=o;break;case 1:r=h,s=i,a=o;break;case 2:r=o,s=i,a=l;break;case 3:r=o,s=h,a=i;break;case 4:r=l,s=o,a=i;break;case 5:r=i,s=o,a=h}}return j.fromRgb(Math.floor(255*r),Math.floor(255*s),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 j(this.r,this.g,this.b)}}function U(e,t){return Math.round(Math.random()*(t-e))+e}function W(e,t,i){return Math.min(i,Math.max(e,t))}function V(e,t,i){return t<=e&&e<=i}function z(e,t){if(!e)return e;var i=10**t,t=Math.abs(e-(0<e?Math.ceil(e):Math.floor(e)));return 0<t&&t<=Number.EPSILON&&(e+=Math.sign(e)*Number.EPSILON),0<=e?Math.floor(e*i)/i:Math.ceil(e*i)/i}function H(i){let r=2166136261;for(let e=0,t=i.length;e<t;++e)r^=i[e],r+=(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24);return r>>>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(j.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 r of e)t[i]=r.r,t[i+1]=r.g,t[i+2]=r.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=16;e<32;e++)this.colors[e].r=Math.floor(t.r/255*i[e-16]*4),this.colors[e].g=Math.floor(t.g/255*i[e-16]*4),this.colors[e].b=Math.floor(t.b/255*i[e-16]*4);return this._hash=this.computeHash(this.colors),this}}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=!1){if(this.files.length){var i=this.files[U(0,this.files.length-1)];return i.images[Math.min(e,i.images.length-1)].hasDamagedData?this.files[Math.min(t?1:0,this.files.length-1)]:i}}}class q{constructor(e,t,i){this.fileName=e,this.setName=t,this.tilesInSet=i,this.entries=[]}}class Z{constructor(e,t,i,r){this.name=e,this.subTile=t,this.offsetX=i,this.offsetY=r}}(s=k=k||{})[s.TopLeft=0]="TopLeft",s[s.BottomRight=1]="BottomRight",s[s.TopRight=2]="TopRight",s[s.BottomLeft=3]="BottomLeft",s[s.MiddleTlBr=4]="MiddleTlBr",s[s.MiddleTrBl=5]="MiddleTrBl";const Q=new Map([[k.TopLeft,["BridgeTopLeft1","BridgeTopLeft2"]],[k.BottomRight,["BridgeBottomRight1","BridgeBottomRight2"]],[k.TopRight,["BridgeTopRight1","BridgeTopRight2"]],[k.BottomLeft,["BridgeBottomLeft1","BridgeBottomLeft2"]],[k.MiddleTlBr,["BridgeMiddle1"]],[k.MiddleTrBl,["BridgeMiddle2"]]]);class X{constructor(e,t){this.theaterIni=e,this.theaterSettings=t,this.tileSets=[],this.orderedEntries=[],this.highBridgeSetNums=[this.getGeneralValue("BridgeSet"),this.getGeneralValue("WoodBridgeSet")],this.cliffSetNums=[this.getGeneralValue("CliffSet"),this.getGeneralValue("CliffRamps"),this.getGeneralValue("WaterCliffs"),this.getGeneralValue("DestroyableCliffs")]}getTile(e){return this.orderedEntries[e]}getTileImage(e,t){let i=this.getTile(e);if(!i)throw new Error(`TileNum ${e} not found`);e=i.getTmpFile(t);if(!e||t>=e.images.length)throw new Error(`SubTile ${t} not found`);return e.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,r=0){let s=0;return this.tileSets.some((e,t)=>t===i?(s+=r,!0):(s+=e.entries.length,!1)),s}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){this.tileSets.length=0,this.orderedEntries.length=0,this.initTileSets(e),this.initAnimations()}initTileSets(a){let e=0,t;for(var i;;){if(i="TileSet"+N(e,"0000"),t=this.theaterIni.getSection(i),!t)break;e++;let s=new q(t.getString("FileName"),t.getString("SetName"),t.getNumber("TilesInSet"));this.tileSets.push(s);for(let r=1;r<=s.tilesInSet;r++){let i=new $(s,r-1);var n="a".charCodeAt(0);for(let t=n-1;t<="z".charCodeAt(0);t++)if(!(t>=n&&"Bridges"===s.setName)){let e=s.fileName+N(r,"00");t>=n&&(e+=String.fromCharCode(t)),e+=this.theaterSettings.Extension;var o=a.get(e);if(!o)break;i.addFile(o)}s.entries.push(i),this.orderedEntries.push(i)}}}initAnimations(){var r=this.theaterIni.getOrderedSections();for(let e=this.tileSets.length;e<r.length;++e){let t=r[e],i=this.tileSets.find(e=>e.setName===t.name);if(i)for(let e=1;e<=i.tilesInSet;++e){var s=`Tile${N(e,"00")}`,a=`${s}Anim`,n=t.getString(a);n?(s=new Z(n,t.getNumber(`${s}AttachesTo`),t.getNumber(`${s}XOffset`),t.getNumber(`${s}YOffset`)),i.entries[e-1].setAnimation(s)):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"),r=this.getGeneralValue("PaveTile"),s=this.getGeneralValue("ShorePieces"),a=this.getGeneralValue("WaterBridge"),n=this.getGeneralValue("PavedRoads"),o=this.getGeneralValue("Medians");return!(e===i&&t===s||t===i&&e===s)&&(!(e===i&&t===a||t===i&&e===a)&&(!(e===r&&t===n||t===r&&e===n)&&!(e===r&&t===o||t===r&&e===o)))}getHighBridgeHeadType(e){for(var[t,i]of Q)for(var r of i)if(this.getGeneralValue(r)===e+1)return t}getOppositeHighBridgeHeadType(e){switch(e){case k.TopLeft:return k.BottomRight;case k.TopRight:return k.BottomLeft;case k.BottomLeft:return k.TopRight;case k.BottomRight:return k.TopLeft;case k.MiddleTlBr:case k.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&&![k.MiddleTlBr,k.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&&[k.MiddleTlBr,k.MiddleTrBl].includes(e)}return!1}}(s=O=O||{})[s.None=0]="None",s[s.Iso=1]="Iso",s[s.Unit=2]="Unit",s[s.Overlay=3]="Overlay",s[s.Anim=4]="Anim",s[s.Custom=5]="Custom",s[s.Default=6]="Default";class Y{constructor(e,t,i,r,s,a,n,o,h){this.type=e,this.settings=t,this.palettes=i,this.isoPalette=r,this.ovlPalette=s,this.unitPalette=a,this.animPalette=n,this.libPalette=o,this.tileSets=h}static factory(e,t,i,r,s){var a=s.get(i.IsoPaletteName);if(!a)throw new Error(`Missing palette "${i.IsoPaletteName}"`);var n=s.get(i.OverlayPaletteName);if(!n)throw new Error(`Missing palette "${i.OverlayPaletteName}"`);var o=s.get(i.UnitPaletteName);if(!o)throw new Error(`Missing palette "${i.UnitPaletteName}"`);var h=s.get("anim.pal");if(!h)throw new Error("Missing anim palette");var l=s.get(i.LibPaletteName);if(!l)throw new Error(`Missing lib palette ${i.LibPaletteName}`);let c=new X(t,i);return c.loadTileData(r),new this(e,i,s,a,n,o,h,l,c)}getPalette(e,t){switch(e){case O.Anim:return this.animPalette;case O.Overlay:return this.ovlPalette;case O.Unit:return this.unitPalette;case O.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:O.Iso;return this.isoPalette}}}(s=I=I||{})[s.None=0]="None",s[s.Temperate=1]="Temperate",s[s.Urban=2]="Urban",s[s.Snow=4]="Snow",s[s.Lunar=8]="Lunar",s[s.Desert=16]="Desert",s[s.NewUrban=32]="NewUrban",s[s.All=63]="All";class K{constructor(){this.fileData=new Map}fromVirtualFile(e,t){var i,r;for([i,r]of t.entries){var s=this.buildWavData(e.stream,r);this.fileData.set(i,s)}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 w;var r,s,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)&&(r=11100*o*(t.sampleRate/22050|0),s=t.chunkSize,a=1017*(n=Math.max(2,Math.ceil(t.length/s))),n=n*s,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(r),i.writeInt16(s),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 s=new J;let e=t.readString(16);var r=e.indexOf("\0");0!==r&&(e=e.substr(0,r)),s.filename=e+".wav",s.offset=t.readUint32(),s.length=t.readUint32(),s.sampleRate=t.readUint32(),s.flags=t.readUint32(),s.chunkSize=t.readUint32(),this.entries.set(s.filename,s)}}}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 r=i[t++%i.length],s=i[t++%i.length],a=i[t++%i.length],n=i[t++%i.length];this.m_p[e]^=r<<24|s<<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),r=e.length/2|0,s=0;for(;0<r--;){var a=te(e[s]),n=te(e[s+1]);[a,n]=t(a,n),i[s++]=te(a),i[s++]=te(n)}return i}_encrypt(e,t){let i=e,r=t;i^=this.m_p[0];let s=!1;for(let e=1;e<=16;e++,s=!s)s?i=this.round(i,r,e):r=this.round(r,i,e);return r^=this.m_p[17],[r,i]}_decrypt(e,t){let i=e,r=t;i^=this.m_p[17];let s=!1;for(let e=16;1<=e;e--,s=!s)s?i=this.round(i,r,e):r=this.round(r,i,e);return r^=this.m_p[0],[r,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",se=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,r){let s;s=0!=(128&t[0])?255:0;const a=new Uint8Array(e.buffer,e.byteOffset);let n=4*r;for(;n>i;n--)a[n-1]=s;for(;0<n;n--)a[n-1]=t[i-n]}key_to_bignum(e,t,i){let r,s,a=0;if(2===t[a]){if(a++,0!=(128&t[a])){for(r=0,s=0;s<(127&t[a]);s++)r=(r<<8>>>0|t[a+s+1])>>>0;a+=1+(127&t[a])}else r=t[a],a++;r<=4*i&&this.move_key_to_big(e,t.subarray(a),r,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 r,s;if(0===(i=this.len_bignum(e,t)))return 0;for(r=32*i,s=2147483648;0==(s&e[i-1]);)s>>>=1,r--;return r}init_pubkey(){let e=0,t;var i;const r=new Uint8Array(256);for(this.init_bignum(this.pubkey.key2,65537,64),t=0;e<re.length;)i=(((se[re.charCodeAt(e++)]>>>0<<6>>>0|255&se[re.charCodeAt(e++)])>>>0<<6>>>0|255&se[re.charCodeAt(e++)])>>>0<<6>>>0|255&se[re.charCodeAt(e++)])>>>0,r[t++]=i>>16&255,r[t++]=i>>8&255,r[t++]=255&i;this.key_to_bignum(this.pubkey.key1,r,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,r){for(let e=0;e<r;e++)t[e]=i[e]}shr_bignum(e,t,i){let r;var s=t/32|0;if(0<s){for(r=0;r<i-s;r++)e[r]=e[r+s];for(;r<i;r++)e[r]=0;t%=32}if(0!==t){for(r=0;r<i-1;r++)e[r]=(e[r]>>>t|e[r+1]<<32-t>>>0)>>>0;e[r]=e[r]>>>t}}shl_bignum(e,t,i){let r;var s=t/32|0;if(0<s){for(r=i-1;r>s;r--)e[r]=e[r-s];for(;0<r;r--)e[r]=0;t%=32}if(0!==t){for(r=i-1;0<r;r--)e[r]=(e[r]<<t>>>0|e[r-1]>>>32-t)>>>0;e[0]=e[0]<<t>>>0}}sub_bignum(e,t,i,r,s){var a,n;s+=s;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!=--s;)a=o[c],n=h[c],l[c]=a-n-r&65535,r=0!=(a-n-r&65536)?1:0,c++;return r}sub_bignum_word(e,t,i,r,s){var a,n;let o=0;for(;-1!=--s;)a=t[o],n=i[o],e[o]=a-n-r&65535,r=0!=(a-n-r&65536)?1:0,o++;return r}inv_bignum(e,t,i){const r=new Uint32Array(64);var s;let a,n,o=0;for(this.init_bignum(r,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,s=4*((n-1)/32|0)>>>0,r[s/4|0]=r[s/4|0]|1<<(n-1&31)>>>0;0<n;)n--,this.shl_bignum(r,1,i),-1!==this.cmp_bignum(r,t,i)&&(this.sub_bignum(r,r,t,0,i),e[o]=e[o]|a>>>0),a>>>=1,0===a&&(o--,a=2147483648);this.init_bignum(r,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,r){let s,a;var n=new Uint16Array(t.buffer,t.byteOffset);let o=a=0;for(s=0;s<r;s++)a=i*n[o]+e[o]+a,e[o]=65535&a,o++,a>>>=16;e[o]+=65535&a}mul_bignum(e,t,i,r){let s;var a=new Uint16Array(i.buffer,i.byteOffset);let n=new Uint16Array(e.buffer,e.byteOffset);this.init_bignum(e,0,2*r);let o=0;for(s=0;s<2*r;s++)this.mul_bignum_word(n.subarray(o),t,a[o],2*r),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,r,s){let a;var n=this.glob1,o=this.glob2;if(this.mul_bignum(this.glob2,t,r,s),this.glob2[2*s]=0,(r=2*this.len_bignum(this.glob2,2*s+1))>=this.glob1_len_x2){this.inc_bignum(this.glob2,2*s+1),this.neg_bignum(this.glob2,2*s+1),a=1+r-this.glob1_len_x2;let e=new Uint16Array(o.buffer),t=a,i=1+r;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*s),0==(32768&e[i])&&0!==this.sub_bignum_word(l,l,new Uint16Array(n.buffer),0,2*s)&&e[i]--)}this.neg_bignum(this.glob2,s),this.dec_bignum(this.glob2,s)}this.mov_bignum(e,this.glob2,s)}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,r,s){var a,n=new Uint32Array(64);let o,h,l=0;for(this.init_bignum(e,1,s),a=this.len_bignum(r,s),this.init_two_dw(r,a),o=this.bitlen_bignum(i,a)<<24>>24,r=((o+31)/32|0)>>>0,h=1<<(o-1)%32>>>1,l+=r-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(s)}memcpy(e,t,i){let r=0;for(;0!=i--;)e[r]=t[r],r++}process_predata(e,t,i){var r=new Uint32Array(64),s=new Uint32Array(64);let a=0,n=0;for(var o=(this.pubkey.len-1)/8|0;1+o<=t;)this.init_bignum(r,0,64),this.memcpy(new Uint8Array(r.buffer),e.subarray(a),1+o),this.calc_a_key(s,r,this.pubkey.key2,this.pubkey.key1,64),this.memcpy(i.subarray(n),new Uint8Array(s.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 r=e;for(let e=0,t=i.length;e<t;e++)r=(r>>>8^this.lookUp[255&r^i[e]])>>>0;return r=(r^e)>>>0,r}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,r=i>>2;if(0!=(3&i)){t+=String.fromCharCode(i-(r<<2));let e=3-(3&i);for(;0!=e--;)t+=t[r<<2]}return oe.calculateCrc(M(t))}}he.size=12,(s=C=C||{})[s.Checksum=65536]="Checksum",s[s.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),r=e.readUint32Array(2);const s=new ie(i);let a=new w(s.decrypt(r));t=a.readUint16();a.readUint32(),e.position=this.headerStart;i=6+t*he.size,t=(3+i)/4|0,r=e.readUint32Array(t+t%2);a=new w(s.decrypt(r));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 r=new he(t.readUint32(),t.readUint32(),t.readUint32());this.index.set(r.hash,r)}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===Ct.YurisRevenge&&await this.addMixFile("langmd.mix"),await this.addMixFile("language.mix"),e===Ct.YurisRevenge&&await this.addMixFile("ra2md.mix"),await this.addMixFile("ra2.mix"),e===Ct.YurisRevenge&&await this.addMixFile("cachemd.mix"),await this.addMixFile("cache.mix"),e===Ct.YurisRevenge&&await this.addMixFile("loadmd.mix"),await this.addMixFile("load.mix"),e===Ct.YurisRevenge&&await this.addMixFile("localmd.mix"),await this.addMixFile("local.mix"),e===Ct.YurisRevenge&&await this.addMixFile("ntrlmd.mix"),await this.addMixFile("neutral.mix"),e===Ct.YurisRevenge&&await this.addMixFile("audiomd.mix"),await this.addMixFile("audio.mix"),await this.addBagFile("audio.bag"),await this.addMixFile("conquer.mix"),e===Ct.YurisRevenge&&(await this.addMixFile("conqmd.mix"),await this.addMixFile("genermd.mix")),await this.addMixFile("generic.mix"),e===Ct.YurisRevenge&&await this.addMixFile("isogenmd.mix"),await this.addMixFile("isogen.mix"),e===Ct.YurisRevenge&&await this.addMixFile("cameomd.mix"),await this.addMixFile("cameo.mix"),e===Ct.YurisRevenge&&await this.addMixFile("multimd.mix"),await this.addMixFile("multi.mix")}async loadExtraMixFiles(i){let r=new Set;for await(var e of this.rfs.getEntries())r.add(e.toLowerCase());for(var s of["ecache","expand","elocal"])for(let t=99;0<=t;t--){let e=[`${s}${N(t,"00")}.mix`];i===Ct.YurisRevenge&&e.push(`${s}md${N(t,"00")}.mix`);for(var a of e)r.has(a)&&await this.addMixFile(a)}let t=[".mmx"];i===Ct.YurisRevenge&&t.push(".yro");for(const n of t)for(const o of r)o.endsWith(n)&&this.addArchive(new le((await this.rfs.openFile(o)).stream),o)}async loadStandaloneFiles(e){let i=["ini","csf"],r=new Set(e?.exclude),s=[];for await(var a of this.rfs.getEntries()){let t=a.toLowerCase();i.some(e=>t.endsWith("."+e))&&!r.has(t)&&s.push(await this.rfs.openFile(a,!0))}if(s.length){let e=new ue;for(var t of s)e.addFile(t);this.addArchive(e,"mem.archive")}}}class pe extends Error{constructor(e){super("Storage quota exceeded",e),this.name="StorageQuotaError"}}class ge{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(R(t,e))return t}async fixEntryCase(e){if(!this.caseSensitive)for await(var t of this.getEntries())if(R(t,e)){e=t;break}return e}async getRawFile(t,e=!1,i){let r;try{var s=e?t:await this.fixEntryCase(t);r=await this.handle.getFileHandle(s)}catch(e){if("NotFoundError"===e.name)throw new ce(`File "${t}" not found in directory "${this.handle.name}"`,{cause:e});if(e instanceof DOMException)throw new l(`File "${t}" could not be read (${e.name})`,{cause:e});throw e}t=await r.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,r){r=r??(i instanceof File?i.name:i.filename);try{var s=await this.fixEntryCase(r);await this.deleteFile(s,!0);let e=await this.handle.getFileHandle(s,{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 DOMException)throw new l(`File "${r}" 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 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 r;try{r=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 DOMException)throw new l(`Directory "${t}" could not be read (${e.name})`,{cause:e});throw e}return new ge(r,e)}async getOrCreateDirectory(t,e=this.caseSensitive){var i=e?t:await this.fixEntryCase(t);try{return new ge(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 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 DOMException)throw new l(`Directory "${t}" could not be deleted (${e.name})`,{cause:e});throw e}}}class me{constructor(){this.directories=[]}addRootDirectoryHandle(e){this.rootDirectory=this.addDirectoryHandle(e),this.rootDirectoryHandle=e}getRootDirectoryHandle(){return this.rootDirectoryHandle}addDirectoryHandle(e){e=new ge(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 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 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 fe{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 ye="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function we(r,e,s,t){if(-1<["32f","64"].indexOf(e)&&-1<["32f","64"].indexOf(t))s.set(r);else{Se(e),Se(t);let i=function(e,t){let i=function(e){return e};e!=t&&(i=["32f","64"].includes(e)?be:["32f","64"].includes(t)?ve:Te);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,r,!0);for(let e=0,t=r.length;e<t;e++)s[e]=i(r[e],a);_e(t,s,!1)}}function Te(e,t){return e=0<e?parseInt(e/t.oldMax*t.newMax,10):parseInt(e/t.oldMin*t.newMin,10)}function be(e,t){return parseInt(0<e?e*t.newMax:e*t.newMin,10)}function ve(e,t){return 0<e?e/t.oldMax:e/t.oldMin}function Se(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 r=t?-128:128;for(let e=0,t=i.length;e<t;e++)i[e]=i[e]+=r}}const ke=[-1,-1,-1,-1,2,4,6,8,-1,-1,-1,-1,2,4,6,8],Oe=[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 Ie(i){var r={index:0,predicted:0,step:7};let s=new Uint8Array(i.length),a=[],n=0,o=0;for(let e=0,t=i.length;e<t;e++)e%505==0&&0!=e&&(s.set(function(i,r){let s=function(e,t){Ae(e,t);let i=[];return i.push(255&e),i.push(e>>8&255),i.push(t.index),i.push(0),i}(i[0],r);for(let e=3,t=i.length;e<t;e+=2){var a=Ae(i[e],r),n=Ae(i[e+1],r);s.push(n<<4|a)}return s}(a,r),n),n+=256,a=[],o++),a.push(i[e]);let e=i.length/2;return e%2&&e++,s.slice(0,e+512+4*o)}function Ce(t,e=256){var i={index:0,predicted:0,step:7};let r=new Int16Array(2*t.length),s=[],a=0,n=t.length,o=0;for(;0<n;){var h=Math.min(n,e);for(let e=0;e<h;e++)s.push(t[o]),o++;var l=function(i,r){r.predicted=function(e){return 32767<e?e-65536:e}(i[1]<<8|i[0]),r.index=i[2],r.step=Oe[r.index];let s=[r.predicted];for(let e=4,t=i.length;e<t;e++){var a=i[e],n=a>>4,a=n<<4^a;s.push(Be(a,r)),s.push(Be(n,r))}return s}(s,i);r.set(l,a),a+=l.length,s=[],n-=e}return r.slice(0,a)}function Ae(e,t){let i=e-t.predicted,r=0;0<=i?r=0:(r=8,i=-i);let s=Oe[t.index],a=s>>3;return i>s&&(r|=4,i-=s,a+=s),s>>=1,i>s&&(r|=2,i-=s,a+=s),s>>=1,i>s&&(r|=1,a+=s),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+=ke[7&e],i.index<0?i.index=0:88<i.index&&(i.index=88)}(r,a,t),r}function Be(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+=ke[e],t.index<0?t.index=0:88<t.index&&(t.index=88);t.step=Oe[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 r=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)r[e]=function(e){let t;var i,r=~(e=-32768==e?-32767:e)>>8&128;return r||(e*=-1),32635<e&&(e=32635),t=256<=e?(i=Ee[e>>8&127])<<4|e>>i+3&15:e>>4,85^t^r}(i[e]);return r}function xe(i){let r=new Int16Array(i.length);for(let e=0,t=i.length;e<t;e++)r[e]=function(e){let t=0;0!=(128&(e^=85))&&(e&=-129,t=-1);var i=4+((240&e)>>4);let r=0;return r=4!=i?1<<i|(15&e)<<i-4|1<<i-5:e<<1|1,r=0===t?r:-r,8*r*-1}(i[e]);return r}const Ne=132,Re=32635,Me=[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],De=[0,132,396,924,1980,4092,8316,16764];function Le(i){let r=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)r[e]=(s=i[e],a=void 0,0!=(a=s>>8&128)&&(s=-s),(s+=Ne)>Re&&(s=Re),~(a|(a=Me[s>>7&255])<<4|s>>a+3&15));var s,a;return r}function Fe(i){let r=new Int16Array(i.length);for(let e=0,t=i.length;e<t;e++)r[e]=function(e){var t,i;let r;return t=128&(e=~e),i=e>>4&7,e=15&e,r=De[i]+(e<<3+i),0!=t&&(r=-r),r}(i[e]);return r}function je(t,i,r=0,s=t.length){for(let e=r;e<s;e+=i)!function(t,i,r){i--;for(let e=0;e<i;e++){var s=t[r+e];t[r+e]=t[r+i],t[r+i]=s,i--}}(t,i,e)}function Ue(e,i,r=0){let s=0;for(var t=e.length;s<t;){var a=e.codePointAt(s);if(a<128)i[r]=a,r++;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,s++),i[r]=(a>>6*e)+t,r++;0<e;)i[r]=128|a>>6*(e-1)&63,r++,e--}s++}return r}const We=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,r,s=0){r=this.clamp_(Math.round(r));for(let e=0,t=this.offset;e<t;e++)i[s]=255&Math.floor(r/We[e]),s++;return s}unpack_(t,i=0){let r=0;for(let e=0;e<this.offset;e++)r+=t[i+e]*We[e];return r}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 ze{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 r=((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 s=Math.min(Math.floor(Math.log(t)/Math.LN2),1023),a=He(t/Math.pow(2,s)*Math.pow(2,this.fbits));return t!=t?(a=Math.pow(2,this.fbits-1),s=(1<<this.ebits)-1):0!==t&&(t>=Math.pow(2,1-this.bias)?(2<=a/Math.pow(2,this.fbits)&&(s+=1,a=1),a=s>this.bias?(s=(1<<this.ebits)-1,0):(s+=this.bias,He(a)-Math.pow(2,this.fbits))):(a=He(t/Math.pow(2,1-this.bias-this.fbits)),s=0)),this.packFloatBits_(e,i,r,s,a)}unpack(t,i){var e=(1<<this.ebits)-1;let r,s="";for(let e=this.offset-1;0<=e;e--){var a=t[e+i].toString(2);s+="00000000".substring(a.length)+a}var n="1"==s.charAt(0)?-1:1;s=s.substring(1);let o=parseInt(s.substring(0,this.ebits),2);return s=s.substring(this.ebits),o==e?0!==parseInt(s,2)?NaN:1/0*n:(r=0===o?(o+=1,parseInt(s,2)):parseInt("1"+s,2),n*r*this.fbias*Math.pow(2,o-this.bias))}packFloatBits_(e,t,i,r,s){let a=[];a.push(i);for(let e=this.ebits;0<e;--e)a[e]=r%2?1:0,r=Math.floor(r/2);var n=a.length;for(let e=this.fbits;0<e;--e)a[n+e]=s%2?1:0,s=Math.floor(s/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 He(e){var t=Math.floor(e),e=e-t;return!(e<.5)&&(.5<e||t%2)?t+1:t}function Ge(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,r=191,s=!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]&&(r=159)):240<=a&&a<=244?(t=3,240===o[n]&&(i=144),244===o[n]&&(r=143)):s=!0,a&=(1<<8-t-1)-1;for(let e=0;e<t;e++)(o[n]<i||o[n]>r)&&(s=!0),a=a<<6|63&o[n],n++;s?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 $e(e){var t=[];return Ue(e,t),t}function qe(e,t,i=0){return Ue(e,t,i)}function Ze(e,t,i,r=0){let s=et((t=t||{}).bits,t.fp,t.signed);var a=Math.ceil(t.bits/8);let n=0;for(var o=r,h=e.length;n<h;n++)r=s.pack(i,e[n],r);return t.be&&je(i,a,o,r),r}function Qe(e,t,i,r=0,s=e.length){var a,n=et((t=t||{}).bits,t.fp,t.signed);s=function(e,t,i){i=(t-e)%i;return t-i}(r,s,n.offset),t.be?(a=new Uint8Array(e),t.be&&je(a,n.offset,r,s),Je(a,i,r,s,n)):Je(e,i,r,s,n)}function Xe(e,t,i,r=0){return Ze([e],t,i,r)}function Ye(e,t){var i=[];return Xe(e,t,i,0),i}function Ke(e,t,i=0){var r=[];return Qe(e,t,r,i,i+Math.ceil(t.bits/8)),r[0]}function Je(i,r,s,a,n){var o=n.offset;for(let e=0,t=s;t<a;t+=o,e++)r[e]=n.unpack(i,t)}function et(e,t,i){return t&&32==e?new ze(8,23):t&&64==e?new ze(11,52):new Ve(e,i)}function tt(e,t){let i=$e(e);for(let e=i.length;e<t;e++)i.push(0);return i}(class bp 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 r=this.signature.subChunks;let s=[];for(let e=0;e<r.length;e++)if(r[e].chunkId==t){if(!i)return r[e];s.push(r[e])}return"LIST"==t&&s.length?s:null}readString(e,t){e=Ge(e,this.head,this.head+t);return this.head+=t,e}readUInt32(e){return e=Ke(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=Ge(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,Ge(e,t,t+4)}getChunkSize_(e,t){return this.head+=4,Ke(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 bp;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=Ge(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 r=i[e];this.LIST.push({chunkId:r.chunkId,chunkSize:r.chunkSize,format:r.format,subChunks:[]});for(let e=0;e<r.subChunks.length;e++)this.readLISTSubChunks_(r.subChunks[e],r.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=Ge(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 Ge(t,i,this.head-1)}readUInt16_(e){return e=Ke(e,this.uInt16,this.head),this.head+=2,e}});function it(e,t,i){return!(i<1||4294967295<e*(t/8)*i)}class rt extends class extends class bp 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 r=this.signature.subChunks;let s=[];for(let e=0;e<r.length;e++)if(r[e].chunkId==t){if(!i)return r[e];s.push(r[e])}return"LIST"==t&&s.length?s:null}readString(e,t){e=Ge(e,this.head,this.head+t);return this.head+=t,e}readUInt32(e){return e=Ke(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=Ge(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,Ge(e,t,t+4)}getChunkSize_(e,t){return this.head+=4,Ke(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 bp;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=Ge(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 r=i[e];this.LIST.push({chunkId:r.chunkId,chunkSize:r.chunkSize,format:r.format,subChunks:[]});for(let e=0;e<r.subChunks.length;e++)this.readLISTSubChunks_(r.subChunks[e],r.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=Ge(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 Ge(t,i,this.head-1)}readUInt16_(e){return e=Ke(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_(),$e(this.data.chunkId),Ye(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 r=new Uint8Array(i+12),s=0;s=qe(this.container,r,s),s=Xe(i+4,this.uInt32,r,s),s=qe(this.format,r,s);for(let e=0;e<t.length;e++)r.set(t[e],s),s+=t[e].length;return r}getBextBytes_(){let e=[];return this.enforceBext_(),this.bext.chunkId&&(this.bext.chunkSize=602+this.bext.codingHistory.length,e=e.concat($e(this.bext.chunkId),Ye(602+this.bext.codingHistory.length,this.uInt32),tt(this.bext.description,256),tt(this.bext.originator,32),tt(this.bext.originatorReference,32),tt(this.bext.originationDate,10),tt(this.bext.originationTime,8),Ye(this.bext.timeReference[0],this.uInt32),Ye(this.bext.timeReference[1],this.uInt32),Ye(this.bext.version,this.uInt16),tt(this.bext.UMID,64),Ye(this.bext.loudnessValue,this.uInt16),Ye(this.bext.loudnessRange,this.uInt16),Ye(this.bext.maxTruePeakLevel,this.uInt16),Ye(this.bext.maxMomentaryLoudness,this.uInt16),Ye(this.bext.maxShortTermLoudness,this.uInt16),tt(this.bext.reserved,180),tt(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=$e(this.iXML.value),this.iXML.chunkSize=t.length,e=e.concat($e(this.iXML.chunkId),Ye(this.iXML.chunkSize,this.uInt32),t)),this.enforceByteLen_(e),e}getDs64Bytes_(){let e=[];return this.ds64.chunkId&&(e=e.concat($e(this.ds64.chunkId),Ye(this.ds64.chunkSize,this.uInt32),Ye(this.ds64.riffSizeHigh,this.uInt32),Ye(this.ds64.riffSizeLow,this.uInt32),Ye(this.ds64.dataSizeHigh,this.uInt32),Ye(this.ds64.dataSizeLow,this.uInt32),Ye(this.ds64.originationTime,this.uInt32),Ye(this.ds64.sampleCountHigh,this.uInt32),Ye(this.ds64.sampleCountLow,this.uInt32))),this.enforceByteLen_(e),e}getCueBytes_(){let e=[];var t;return this.cue.chunkId&&(t=this.getCuePointsBytes_(),e=e.concat($e(this.cue.chunkId),Ye(t.length+4,this.uInt32),Ye(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(Ye(this.cue.points[e].dwName,this.uInt32),Ye(this.cue.points[e].dwPosition,this.uInt32),$e(this.cue.points[e].fccChunk),Ye(this.cue.points[e].dwChunkStart,this.uInt32),Ye(this.cue.points[e].dwBlockStart,this.uInt32),Ye(this.cue.points[e].dwSampleOffset,this.uInt32));return t}getSmplBytes_(){let e=[];var t;return this.smpl.chunkId&&(t=this.getSmplLoopsBytes_(),e=e.concat($e(this.smpl.chunkId),Ye(t.length+36,this.uInt32),Ye(this.smpl.dwManufacturer,this.uInt32),Ye(this.smpl.dwProduct,this.uInt32),Ye(this.smpl.dwSamplePeriod,this.uInt32),Ye(this.smpl.dwMIDIUnityNote,this.uInt32),Ye(this.smpl.dwMIDIPitchFraction,this.uInt32),Ye(this.smpl.dwSMPTEFormat,this.uInt32),Ye(this.smpl.dwSMPTEOffset,this.uInt32),Ye(this.smpl.dwNumSampleLoops,this.uInt32),Ye(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(Ye(this.smpl.loops[e].dwName,this.uInt32),Ye(this.smpl.loops[e].dwType,this.uInt32),Ye(this.smpl.loops[e].dwStart,this.uInt32),Ye(this.smpl.loops[e].dwEnd,this.uInt32),Ye(this.smpl.loops[e].dwFraction,this.uInt32),Ye(this.smpl.loops[e].dwPlayCount,this.uInt32));return t}getFactBytes_(){let e=[];return this.fact.chunkId&&(e=e.concat($e(this.fact.chunkId),Ye(this.fact.chunkSize,this.uInt32),Ye(this.fact.dwSampleLength,this.uInt32))),this.enforceByteLen_(e),e}getFmtBytes_(){if(this.fmt.chunkId){var e=[].concat($e(this.fmt.chunkId),Ye(this.fmt.chunkSize,this.uInt32),Ye(this.fmt.audioFormat,this.uInt16),Ye(this.fmt.numChannels,this.uInt16),Ye(this.fmt.sampleRate,this.uInt32),Ye(this.fmt.byteRate,this.uInt32),Ye(this.fmt.blockAlign,this.uInt16),Ye(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(Ye(this.fmt.cbSize,this.uInt16))),18<this.fmt.chunkSize&&(e=e.concat(Ye(this.fmt.validBitsPerSample,this.uInt16))),20<this.fmt.chunkSize&&(e=e.concat(Ye(this.fmt.dwChannelMask,this.uInt32))),24<this.fmt.chunkSize&&(e=e.concat(Ye(this.fmt.subformat[0],this.uInt32),Ye(this.fmt.subformat[1],this.uInt32),Ye(this.fmt.subformat[2],this.uInt32),Ye(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($e(this.LIST[e].chunkId),Ye(i.length+4,this.uInt32),$e(this.LIST[e].format),i)}return this.enforceByteLen_(t),t}getLISTSubChunksBytes_(i,r){let s=[];for(let e=0,t=i.length;e<t;e++)"INFO"==r?s=s.concat(this.getLISTINFOSubChunksBytes_(i[e])):"adtl"==r&&(s=s.concat(this.getLISTadtlSubChunksBytes_(i[e]))),this.enforceByteLen_(s);return s}getLISTINFOSubChunksBytes_(e){let t=[];var i=tt(e.value,e.value.length);return t=t.concat($e(e.chunkId),Ye(i.length+1,this.uInt32),i),t.push(0),t}getLISTadtlSubChunksBytes_(e){let t=[];var i;return-1<["labl","note"].indexOf(e.chunkId)?(i=tt(e.value,e.value.length),t=t.concat($e(e.chunkId),Ye(i.length+4+1,this.uInt32),Ye(e.dwName,this.uInt32),i),t.push(0)):"ltxt"==e.chunkId&&(t=t.concat(this.getLtxtChunkBytes_(e))),t}getLtxtChunkBytes_(e){return[].concat($e(e.chunkId),Ye(e.value.length+20,this.uInt32),Ye(e.dwName,this.uInt32),Ye(e.dwSampleLength,this.uInt32),Ye(e.dwPurposeID,this.uInt32),Ye(e.dwCountry,this.uInt16),Ye(e.dwLanguage,this.uInt16),Ye(e.dwDialect,this.uInt16),Ye(e.dwCodePage,this.uInt16),tt(e.value,e.value.length))}get_PMXBytes_(){let e=[];var t;return this._PMX.chunkId&&(t=$e(this._PMX.value),this._PMX.chunkSize=t.length,e=e.concat($e(this._PMX.chunkId),Ye(this._PMX.chunkSize,this.uInt32),t)),this.enforceByteLen_(e),e}getJunkBytes_(){let e=[];return this.junk.chunkId?e.concat($e(this.junk.chunkId),Ye(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,r,s){s=s||{},this.clearHeaders(),this.newWavFile_(e,t,i,r,s)}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(r,s,t=Float64Array){let a=[];for(let e=0;e<s;e++)a[e]=new t(r.length/s);for(let i=0;i<s;i++)for(let e=i,t=0;e<r.length;e+=s,t++)a[i][t]=r[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 Ke(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");Xe(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,r,s){s.container||(s.container="RIFF"),this.container=s.container,this.bitDepth=i,r=function(s){let a=[];if(0<s.length)if(s[0].constructor!==Number){a=new Float64Array(s[0].length*s.length);for(let i=0,e=s[0].length,r=0;i<e;i++)for(let e=0,t=s.length;e<t;e++,r++)a[r]=s[e][i]}else a=s;return a}(r),this.updateDataType_();var a=this.dataType.bits/8;this.data.samples=new Uint8Array(r.length*a),Ze(r,this.dataType,this.data.samples,0),this.makeWavHeader_(i,e,t,a,this.data.samples.length,s),this.data.chunkId="data",this.data.chunkSize=this.data.samples.length,this.validateWavHeader_()}makeWavHeader_(e,t,i,r,s,a){"4"==e?this.createADPCMHeader_(e,t,i,r,s,a):"8a"==e||"8m"==e?this.createALawMulawHeader_(e,t,i,r,s,a):-1==Object.keys(this.WAV_AUDIO_FORMATS).indexOf(e)||2<t?this.createExtensibleHeader_(e,t,i,r,s,a):this.createPCMHeader_(e,t,i,r,s,a)}createPCMHeader_(e,t,i,r,s,a){this.container=a.container,this.chunkSize=36+s,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*r*i,blockAlign:t*r,bitsPerSample:parseInt(e,10),cbSize:0,validBitsPerSample:0,dwChannelMask:0,subformat:[]}}createADPCMHeader_(e,t,i,r,s,a){this.createPCMHeader_(e,t,i,r,s,a),this.chunkSize=40+s,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*s}}createExtensibleHeader_(e,t,i,r,s,a){this.createPCMHeader_(e,t,i,r,s,a),this.chunkSize=60+s,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,r,s,a){this.createPCMHeader_(e,t,i,r,s,a),this.chunkSize=40+s,this.fmt.chunkSize=20,this.fmt.cbSize=2,this.fmt.validBitsPerSample=8,this.fact={chunkId:"fact",chunkSize:4,dwSampleLength:s}}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(!it(this.fmt.numChannels,this.fmt.bitsPerSample,this.fmt.sampleRate))throw new Error("Invalid sample rate.")}}class st 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 r={};if(null!==i)for(let e=0,t=this.LIST[i].subChunks.length;e<t;e++)r[this.LIST[i].subChunks[e].chunkId]=this.LIST[i].subChunks[e].value;return r}getLISTIndex(i){for(let e=0,t=this.LIST.length;e<t;e++)if(this.LIST[e].format==i)return e;return null}getTagIndex_(r){let s={LIST:null,TAG:null};for(let i=0,e=this.LIST.length;i<e;i++)if("INFO"==this.LIST[i].format){s.LIST=i;for(let e=0,t=this.LIST[i].subChunks.length;e<t;e++)if(this.LIST[i].subChunks[e].chunkId==r){s.TAG=e;break}break}return s}}class at extends st{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 r=this.cue.points.length;this.cue.points=[];for(let e=0;e<r;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,r){var s=this.getLISTIndex("adtl");if(null!==s)for(let e=0,t=this.LIST[s].subChunks.length;e<t;e++)this.LIST[s].subChunks[e].dwName==i&&(this.LIST[s].subChunks[e].value=r)}getCuePoints_(){let i=[];for(let t=0;t<this.cue.points.length;t++){var r=this.cue.points[t];let e=this.getDataForCuePoint_(r.dwName);e.label=e.value||"",e.dwPosition=r.dwPosition,e.fccChunk=r.fccChunk,e.dwChunkStart=r.dwChunkStart,e.dwBlockStart=r.dwBlockStart,e.dwSampleOffset=r.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,r,s){for(let e=0,t=this.LIST[r].subChunks.length;e<t;e++){var a;this.LIST[r].subChunks[e].dwName==s&&(a=this.LIST[r].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 r=!1;for(let e=0;e<t.length;e++)t[e].dwSampleOffset>i.dwSampleOffset&&!r?(this.setCuePoint_(i,e+1),this.setCuePoint_(t[e],e+2),r=!0):this.setCuePoint_(t[e],r?e+2:e+1);r||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 nt{constructor(e,t,i){var r;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_=(r=i.sincWindow||ot,function(e){return(0!==(t=e)?Math.sin(Math.PI*t)/(Math.PI*t):1)*r(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),r=[this.getTangent_(i,t),this.getTangent_(i+1,t)],s=[this.getClippedInput_(i,t),this.getClippedInput_(i+1,t)],t=(e-=i)*e,i=e*t;return(2*i-3*t+1)*s[0]+(i-2*t+e)*r[0]+(-2*i+3*t)*s[1]+(i-t)*r[1]}sinc(t,i){t=this.scaleFactor_*t;var e=Math.floor(t),r=e-this.sincFilterSize_+1,s=e+this.sincFilterSize_;let a=0;for(let e=r;e<=s;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 ot(e){return Math.exp(-e/2*e/2)}const ht={point:!1,linear:!1,cubic:!0,sinc:!0},lt={IIR:16,FIR:71},ct={IIR:class{constructor(t,i,r){let s=[];for(let e=0;e<t;e++)s.push(this.getCoeffs_({Fs:i,Fc:r,Q:.5/Math.sin(Math.PI/(2*t)*(e+.5))}));this.stages=[];for(let e=0;e<s.length;e++)this.stages[e]={b0:s[e].b[0],b1:s[e].b[1],b2:s[e].b[2],a1:s[e].a[0],a2:s[e].a[1],k:s[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 r=2*Math.PI*e.Fc/e.Fs;return i.alpha=Math.sin(r)/(2*e.Q),i.cw=Math.cos(r),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 r=2*Math.PI*i/e;let s=0;this.filters=[];for(let e=0;e<=t;e++)e-t/2==0?this.filters[e]=r:(this.filters[e]=Math.sin(r*(e-t/2))/(e-t/2),this.filters[e]*=.54-.46*Math.cos(2*Math.PI*e/t)),s+=this.filters[e];for(let e=0;e<=t;e++)this.filters[e]/=s;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 ut(e,t,i,r=null){r=r||{};var s=new Float64Array(e.length*((i-t)/t+1));r.method=r.method||"cubic";var a=new nt(e.length,s.length,{method:r.method,tension:r.tension||0,sincFilterSize:r.sincFilterSize||6,sincWindow:r.sincWindow||void 0,clip:r.clip||"mirror"});if(void 0===r.LPF&&(r.LPF=ht[r.method]),r.LPF){r.LPFType=r.LPFType||"IIR";const n=ct[r.LPFType];t<i?function(i,r,s,a){for(let e=0,t=r.length;e<t;e++)r[e]=a.filter(s.interpolate(e,i));a.reset();for(let e=r.length-1;0<=e;e--)r[e]=a.filter(r[e])}(e,s,a,new n(r.LPForder||lt[r.LPFType],i,t/2)):function(i,e,t,r){for(let e=0,t=i.length;e<t;e++)i[e]=r.filter(i[e]);r.reset();for(let e=i.length-1;0<=e;e--)i[e]=r.filter(i[e]);dt(i,e,t)}(e,s,a,new n(r.LPForder||lt[r.LPFType],t,i/2))}else dt(e,s,a);return s}function dt(i,r,s){for(let e=0,t=r.length;e<t;e++)r[e]=s.interpolate(e,i)}class pt extends at{toRIFF(){var e=new Float64Array(gt(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(gt(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(gt(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",Ie(e),{container:this.correctContainer_()})}fromIMAADPCM(e="16"){let s;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),r=0;for(let e=0;e<a;e++)e&&e%4==0&&(r+=4),t[e]=this.data.samples[r+e],i[e]=this.data.samples[r+e+4];s=[Ce(t,this.fmt.blockAlign/2),Ce(i,this.fmt.blockAlign/2)]}else s=Ce(this.data.samples,this.fmt.blockAlign);this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",s,{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toALaw(){this.assure16Bit_();var e=new Int16Array(gt(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",xe(this.data.samples),{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toMuLaw(){this.assure16Bit_();var e=new Int16Array(gt(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",Le(e),{container:this.correctContainer_()})}fromMuLaw(e="16"){this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",Fe(this.data.samples),{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toBitDepth(e,t=!0){let i=e,r=this.bitDepth;t||("32f"!=e&&(i=this.dataType.bits.toString()),r=""+this.dataType.bits),this.assureUncompressed_();var s=this.getSamples(!0),t=new Float64Array(s.length);we(s,r,t,i),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,e,t,{container:this.correctContainer_()})}toSampleRate(t,i){this.validateResample_(t);var r=this.getSamples();let s=[];if(r.constructor===Float64Array)s=ut(r,this.fmt.sampleRate,t,i);else for(let e=0;e<r.length;e++)s.push(ut(r[e],this.fmt.sampleRate,t,i));this.fromExisting_(this.fmt.numChannels,t,this.bitDepth,s,{container:this.correctContainer_()})}validateResample_(e){if(!it(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,r,s){var a=new at;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,r,s)}}function gt(e,t){let i=e/t;return i%2&&i++,i}class mt extends pt{constructor(e){super(),e&&this.fromBuffer(e)}fromBase64(e){this.fromBuffer(function(i){let r=new Uint8Array(256);for(let e=0;e<ye.length;e++)r[ye.charCodeAt(e)]=e;let e=.75*i.length;"="===i[i.length-1]&&(e--,"="===i[i.length-2]&&e--);let s=new Uint8Array(e);for(let e=0,t=0;e<i.length;e+=4){var a=r[i.charCodeAt(e)],n=r[i.charCodeAt(e+1)],o=r[i.charCodeAt(e+2)],h=r[i.charCodeAt(e+3)];s[t++]=a<<2|n>>4,s[t++]=(15&n)<<4|o>>2,s[t++]=(3&o)<<6|63&h}return s}(e))}toBase64(){return function(t){let i="";for(let e=0;e<t.length;e+=3)i+=ye[t[e]>>2],i+=ye[(3&t[e])<<4|t[e+1]>>4],i+=ye[(15&t[e+1])<<2|t[e+2]>>6],i+=ye[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 ft{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 mt(e);return"4"===t.bitDepth&&t.fromIMAADPCM(),t.toBuffer()}isRawImaAdpcm(){return this.rawData&&"4"===new mt(this.rawData).bitDepth}}class yt{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 wt{constructor(e){this.file=e}asFile(){return new File([this.file],this.file.name,{type:"audio/mp3"})}}const Tt=(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"]);s=["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"];Tt.set("sidec01.mix",s).set("sidec02.mix",s);var bt,vt,s=["reportbug.shp"];Tt.set("sidec01cd.mix",s).set("sidec02cd.mix",s),(s=bt=bt||{})[s.Archive=0]="Archive",s[s.Cdn=1]="Cdn",s[s.Local=2]="Local";class St{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}}(s=vt=vt||{})[s.Battle=0]="Battle",s[s.ManBattle=1]="ManBattle",s[s.FreeForAll=2]="FreeForAll",s[s.Unholy=3]="Unholy",s[s.Cooperative=4]="Cooperative";class _t{constructor(e,t){this.modeIniLoader=t,this.entries=new Map,this.loadIni(e)}loadIni(e){e.getOrderedSections().forEach(r=>{let s=vt[r.name]??vt.Battle;[...r.entries.keys()].forEach(e=>{let t=r.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:s,label:t[0],description:t[1],rulesOverride:e,mapFilter:t[3],randomMapsAllowed:t[4],aiAllowed:i<3,mpDialogSettings:(new St).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 kt{fromIni(t,e){return this.fileName=t.getString("File")||t.name.toLowerCase()+".map",this.uiName=t.getString("Description"),this.maxSlots=t.getNumber("MaxPlayers"),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(/\(\d(-\d)?\)$/)||(e+=` (2${2<t?"-"+t:""})`),e}fromMapFile(e,t){var i=e.readAsString();let r=e.filename;const s=new c(this.extractIniSection("Basic",i)).getSection("Basic");if(!s)throw new Error(`Map "${r}" is missing the [Basic] section`);return this.fileName=r,this.uiName="NOSTR:"+(s.getString("Name")||r.replace(/\.[^.]+$/,"")),this.maxSlots=s.getNumber("MaxPlayer"),this.gameModes=t.filter(e=>s.getArray("GameMode").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 Ot{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 kt).fromIni(t,this.gameModes.getAll())})),this.dedupeEntries(),this}addFromMapFile(e){this.manifests.push((new kt).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 Ot(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 It{getMatrix(e){return this.matrices[e]}}var Ct,At,Bt=__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 r=i.readInt32(),s=i.readInt32();for(let e=0;e<s;++e){let e=new It;e.name=i.readCString(16),e.matrices=new Array(r),this.sections.push(e)}for(let t=0;t<r;++t)for(let e=0;e<s;++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 Bt.Matrix4).fromArray(i).transpose()}}(s=Ct=Ct||{})[s.AutoDetect=0]="AutoDetect",s[s.TiberianSun=1]="TiberianSun",s[s.Firestorm=2]="Firestorm",s[s.RedAlert2=3]="RedAlert2",s[s.YurisRevenge=4]="YurisRevenge";class Pt{static getVersion(){return"0.43.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 me;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 getTheaterSettings(e,t){if(!this.theaterSettings.has(e))throw new Error(`Unknown engineType "${e}`);return this.theaterSettings.get(e).filter(e=>e.Type===t)[0]}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 r,s=Pt.getTheaterSettings(t,e);if(Pt.gameResSource!==bt.Cdn)for(var a of s.Mixes)await Pt.vfs.addMixFile(a);return Pt.theaters.has(e)?i=Pt.theaters.get(e):(r=Pt.getTheaterIni(t,e),t=Pt.getTileData(),i=Y.factory(e,r,s,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=Tt.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");let i=this.iniFiles.get(e),r=this.iniFiles.get(t);if(!i)throw new Error(`Rules "${e}" not found`);if(!r)throw new Error(`Art "${t}" not found`);e=this.iniFiles.get(Pt.customRulesFileName),t=this.iniFiles.get(Pt.customArtFileName);if(!e)throw new Error(`Rules "${Pt.customRulesFileName}" not found`);if(!t)throw new Error(`Art "${Pt.customArtFileName}" not found`);Pt.art=r.clone().mergeWith(t),Pt.rules=i.clone().mergeWith(e),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,r,s=this.theaterSettings.get(this.getActiveEngine());if(!s)throw new Error(`Unsupported engineType "${this.getActiveEngine()}`);for(t of s)e.push(this.getFileNameVariant(t.TheaterIni));let a=this.getMpModes();for(i of a.getAll())e.push(i.rulesOverride);let n=new oe;for(r of e){if(!this.vfs.fileExists(r))throw new Error(`File ${r} not found`);var o=this.vfs.openFile(r).stream;n.append(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}return n.append(M(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 getFileNameVariant(e){var t=this.getActiveEngine();let i;if(t===Ct.YurisRevenge)i="md";else{if(t!==Ct.RedAlert2)throw new Error(`Unsupported engine type ${Ct[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,t,i,r=this.getMpModes();let s=new Ot(r);s.addFromIni(this.getIni(this.getFileNameVariant("missions.pkt")));for(e of this.vfs.listArchives()){var a=e.toLowerCase().replace(/\.[^.]+$/,"")+".pkt";this.vfs.fileExists(a)&&s.addFromIni(new c(this.vfs.openFile(a)))}let n=new Ot(r);if(this.rfs)for await(var o of this.rfs.getEntries())try{o.endsWith("pkt")?(t=new c(await this.rfs.openFile(o,!0)),s.addFromIni(t)):(o.endsWith("mpr")||o.endsWith("map"))&&(i=await this.rfs.openFile(o,!0),n.addFromMapFile(i))}catch(e){console.warn(`Couldn't read file "${o}"`,e)}return n.sortByName(),s.mergeWith(n),this.mapList=s,s}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 Ct.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 async getOrCreateDir(e,t=!1){let i=this.rfs?.getRootDirectory();if(i)return 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.theaters.clear(),this.tileData.clear(),this.voxels.clear(),this.voxelAnims.clear()}}Pt.UI_ANIM_SPEED=2,Pt.rfsSettings={menuVideoFileName:"ra2ts_l.webm",splashImgFileName:"glsl.png",modDir:"mods",musicDir:"music",tauntsDir:"Taunts",cacheDir:"cache",replayDir:"replays"},Pt.images=new fe(e=>new r(e)),Pt.voxels=new fe(e=>new S(e)),Pt.voxelAnims=new fe(e=>new Et(e)),Pt.sounds=new fe(e=>new ft(e)),Pt.themes=new yt(e=>new wt(e),!1),Pt.taunts=new yt(async e=>new ft(new Uint8Array(await e.arrayBuffer()))),Pt.iniFiles=new fe(e=>new c(e)),Pt.tileData=new fe(e=>new P(e)),Pt.palettes=new fe(e=>new G(e)),Pt.theaters=new Map,Pt.theaterSettings=(new Map).set(Ct.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(Ct.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",(s=At=At||{})[s.None=0]="None",s[s.Aircraft=1]="Aircraft",s[s.Building=2]="Building",s[s.Infantry=3]="Infantry",s[s.Overlay=4]="Overlay",s[s.Smudge=5]="Smudge",s[s.Terrain=6]="Terrain",s[s.Vehicle=7]="Vehicle",s[s.Animation=8]="Animation",s[s.Projectile=9]="Projectile",s[s.VoxelAnim=10]="VoxelAnim",s[s.Debris=11]="Debris";class xt{constructor(e){this.type=e}isStructure(){return this.type===At.Building}isVehicle(){return this.type===At.Vehicle}isInfantry(){return this.type===At.Infantry}isAircraft(){return this.type===At.Aircraft}isTerrain(){return this.type===At.Terrain}isSmudge(){return this.type===At.Smudge}isOverlay(){return this.type===At.Overlay}isNamed(){return"name"in this}isTechno(){return"health"in this}}class Nt extends xt{}class Rt extends Nt{}class Mt extends Rt{constructor(){super(At.Building)}}class Dt extends Rt{constructor(){super(At.Vehicle)}}class Lt extends Rt{constructor(){super(At.Infantry)}}class Ft extends Rt{constructor(){super(At.Aircraft)}}class jt extends Nt{constructor(){super(At.Terrain)}}class Ut extends Nt{constructor(){super(At.Smudge)}}class Wt extends xt{constructor(){super(At.Overlay)}}class Vt{static decode(e,t){t=new Uint8Array(t);return this.decodeInto(e,t),t}static decodeInto(e,t){let i=new w(new DataView(e.buffer,e.byteOffset,e.byteLength)),r=0;for(;;){var s=i.readUint8();if(0==(128&s)){var a=i.readUint8(),n=3+((112&s)>>4);this.replicatePrevious(t,r,r-(((15&s)<<8)+a),n),r+=n}else if(0==(64&s)){n=63&s;if(0==n)return r;t.set(i.readUint8Array(n),r),r+=n}else{s=63&s;if(62==s)for(var o=i.readInt16(),h=i.readUint8(),l=r+o;r<l;r++)t[r]=h;else if(63==s){o=i.readInt16();let e=i.readInt16();if(e>=r)throw new Error(`srcIndex >= destIndex ${e} ${r}`);for(var c=r+o;r<c;r++)t[r]=t[e++]}else{s=3+s;let e=i.readInt16();if(e>=r)throw new Error(`srcIndex >= destIndex ${e} ${r}`);for(var u=r+s;r<u;r++)t[r]=t[e++]}}}}static replicatePrevious(t,i,r,s){if(i<r)throw new Error(`srcIndex > destIndex ${r} ${i}`);if(i-r==1)for(let e=0;e<s;e++)t[i+e]=t[i-1];else for(let e=0;e<s;e++)t[i+e]=t[r+e]}}var zt,Ht,Gt,$t,qt,Zt,Qt,Xt,Yt,Kt,Jt,ei,ti,ii,ri,si,ai,ni,oi=__webpack_require__(251).default;class hi{static decompress(e,t){e={inputBuffer:e,outputBuffer:null},t=oi.decompress(e,{outputSize:t});if(0!==t)throw new Error(`MiniLzo decode failed with code ${t}`);return e.outputBuffer}}class li{static decode(e,t,i=5){t=new Uint8Array(t);return this.decodeInto(e,t,i),t}static decodeInto(e,i,r=5){var t=i.length;let s=0,a=0;for(;a<t;){var n=e[s+1]<<8|e[s];s+=2;var o=e[s+1]<<8|e[s];if(s+=2,!n||!o)break;let t;t=80===r?Vt.decode(e.subarray(s,s+n),o):hi.decompress(e.subarray(s,s+n),o);for(let e=0;e<o;++e)i[a+e]=t[e];s+=n,a+=o}}}function ci(e){switch(e){case zt.Indexed:return 1;case zt.Rgb:return 3;case zt.Rgba:return 4;default:throw new Error(`Unsupported pixel format ${e}`)}}(s=zt=zt||{})[s.Rgb=1]="Rgb",s[s.Rgba=2]="Rgba",s[s.Indexed=3]="Indexed";class ui{constructor(e,t,i,r=zt.Rgba){var s=ci(r);this.data=i||new Uint8Array(s*e*t),this.pixelFormat=r,this.width=e,this.height=t}drawIndexedImage(t,e,i){var r=ci(this.pixelFormat);const s=this.data;var a=this.width,n=r*a,o=r*a*this.height;let h=0+n*i+r*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&&(s[h]=c,3<=r&&(s[h+1]=0,s[h+2]=0),4===r&&(s[h+3]=255)),h+=r,l++}h+=n-t.width*r}}}class di extends ui{constructor(e,t,i){super(e,t,i,zt.Rgb)}}(s=Ht=Ht||{})[s.OnceAny=0]="OnceAny",s[s.OnceAll=1]="OnceAll",s[s.Repeat=2]="Repeat";class pi{read(e){let t=[];for(var[i,r]of e.entries){var s=r.split(",");s.length<3?console.warn(`Invalid tag ${i}=${r}. Skipping.`):(r=Number(s[0]),void 0!==Ht[r]?(s={id:i,repeatType:r,name:s[1],triggerId:s[2]},t.push(s)):console.warn(`Invalid repeat value ${r} for tag id ${i}. Skipping.`))}return t}}Gt=Gt||{},Gt[Gt.AnyEvent=8]="AnyEvent",$t=$t||{},$t[$t.PlaySoundFxAt=99]="PlaySoundFxAt";class gi{read(e,t,i,r){let s=this.readTriggers(e,r),a=this.readEvents(t),n=this.readActions(i),o=[...r.values()];for(let t of s.values()){var h=a.get(t.id);h&&t.events.push(...h);h=n.get(t.id);h&&t.actions.push(...h);h=o.find(e=>e.triggerId===t.id);h&&(t.tag=h)}return s}readTriggers(i,r){let s=[];for(let[t,e]of i.entries){var a,n=e.split(",");n.length<8?console.warn(`Invalid trigger ${t}=${e}. Skipping.`):(a=r.find(e=>e.triggerId===t))?(a={id:t,houseName:n[0],attachedTriggerId:"<none>"!==n[1]?n[1]:void 0,name:n[2],disabled:Boolean(Number(n[3])),difficulties:{easy:Boolean(Number(n[4])),medium:Boolean(Number(n[5])),hard:Boolean(Number(n[6]))},events:[],actions:[],tag:a},s.push(a)):console.warn(`Trigger ${t} has no associated tag. Skipping.`)}return s}readEvents(e){let s=new Map;for(var[a,t]of e.entries){let r=t.split(",");if(r.length<4)console.warn(`Invalid event ${a}=${t}. Skipping.`);else{var n=Number(r.shift());let t=[],i=!0;for(let e=0;e<n;e++){var o=Number(r.shift());if(void 0===Gt[o]){console.warn(`Invalid event type ${o} for event id ${a}. Skipping.`),i=!1;break}var h=Number(r.shift()),h={triggerId:a,eventIndex:e,type:o,params:r.splice(0,h)};t.push(h)}i&&s.set(a,t)}}return s}readActions(e){let s=new Map;for(var[a,t]of e.entries){let r=t.split(",");if(r.length<9||(r.length-1)%8!=0)console.warn(`Invalid action ${a}=${t}. Skipping.`);else{var n=Number(r.shift());let t=[],i=!0;for(let e=0;e<n;e++){var o=Number(r.shift());if(void 0===$t[o]){console.warn(`Unknown action type ${o}. Skipping.`),i=!1;break}o={triggerId:a,type:o,params:r.splice(0,7)};t.push(o)}i&&s.set(a,t)}}return s}}class mi{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 fi 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")}"`);return this.readTiles(),this.readWaypoints(),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.startingLocations=this.readStartingLocations(this.waypoints),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 mi).read(e),this.ionLighting=(new mi).read(e,"Ion"),this.ionLighting.forceTint=!0}readTagsAndTriggers(){this.tags=(new pi).read(this.getOrCreateSection("Tags"));var e=this.getOrCreateSection("Triggers"),t=this.getOrCreateSection("Events"),i=this.getOrCreateSection("Actions");this.triggers=(new gi).read(e,t,i,this.tags)}readTiles(){let e=this.getSection("IsoMapPack5");if(!e)throw new Error("[IsoMapPack5] section not found");var t=D(e.getConcatenatedValues()),i=(2*this.fullSize.width-1)*this.fullSize.height,r=new Uint8Array(11*i+4);li.decodeInto(t,r);let s=new w(r.buffer),a=2*this.fullSize.width-1;var n,o,h,l,r=this.fullSize.height,c=(e,t)=>t*a+e;this.tiles=new Array(a*r);for(let e=0;e<i;e++){var u=s.readUint16(),d=s.readUint16(),p=Math.max(0,s.readInt16());s.readInt16();var g=s.readUint8(),m=s.readUint8();s.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(){let e=this.getSection("Basic");if(null!=e&&e.getBool("MultiplayerOnly")){var t,i,r,s,a;this.waypoints=[];for([t,i]of this.getOrCreateSection("Waypoints").entries){let e;isNaN(r=parseInt(t,10))||isNaN(e=parseInt(i,10))||(s=Math.floor(e/1e3),a=e-1e3*s,this.waypoints.push({number:r,rx:a,ry:s}))}}}readStructures(e){this.structures=[];for(var[,t]of e.entries){t=t.split(",");if(!(t.length<=15)){let e=new Mt;e.owner=t[0],e.name=t[1],e.health=Number(t[2]),e.rx=Number(t[3]),e.ry=Number(t[4]),this.structures.push(e)}}}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 Dt;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.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 Lt;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.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 Ft;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.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 jt;e.name=i,e.rx=t%1e3,e.ry=Math.floor(t/1e3),this.terrains.push(e)}}}readOverlays(){this.overlays=[];let t=this.getSection("OverlayPack");if(t){var i=D(t.getConcatenatedValues()),r=new Uint8Array(1<<18);li.decodeInto(i,r,80);let e=this.getSection("OverlayDataPack");if(e){var i=D(e.getConcatenatedValues()),s=new Uint8Array(1<<18);li.decodeInto(i,s,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=r[a];if(255!==n){a=s[a];let e=new Wt;e.id=n,e.value=a,e.rx=o,e.ry=h,this.overlays.push(e)}}}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 Ut;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,r]=e.getArray("Size").map(e=>Number(e)),s=D(t.getConcatenatedValues()),r=new di(i,r);return li.decodeInto(s,r.data),r}}}(s=qt=qt||{})[s.GDI=0]="GDI",s[s.Nod=1]="Nod",s[s.Civilian=2]="Civilian",s[s.Mutant=3]="Mutant";const yi=(new Map).set("GDI",qt.GDI).set("Nod",qt.Nod).set("Civilian",qt.Civilian).set("Mutant",qt.Mutant),wi=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 Ti{readIni(e){this.name=e.name,this.uiName=e.getString("UIName"),this.uiTooltip=e.get("UITooltip")||wi.get(this.name);var t=e.getString("Side");if(!t)throw new Error(`Missing Side for country "${this.name}"`);t=yi.get(t);if(void 0===t)throw new Error(`Unknown side "${t}" for country "${this.name}"`);this.side=t,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 bi{constructor(e,t){this.type=e,this.ini=t,this.parse()}static iniSpeedToLeptonsPerTick(e){return 255*e/64}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===At.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}}bi.IMAGE_NONE="none";class vi{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=bi.iniSpeedToLeptonsPerTick(e),this.suicide=this.rules.getBool("Suicide"),this.useSparkParticles=this.rules.getBool("UseSparkParticles"),this.warhead=this.rules.getString("Warhead")}}class Si{readIni(e){this.ini=e,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")}}(s=Zt=Zt||{})[s.GenericCombat=0]="GenericCombat",s[s.GenericNonCombat=1]="GenericNonCombat",s[s.DropZone=2]="DropZone",s[s.BaseUnderAttack=3]="BaseUnderAttack",s[s.HarvesterUnderAttack=4]="HarvesterUnderAttack",s[s.EnemyObjectSensed=5]="EnemyObjectSensed";class _i{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 ki{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 Oi{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 Ii{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 Ci{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 Ai{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 Bi{readIni(e){return 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.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 r=[];for(let e=0;e<t.length;++e)0<i[e]&&r.push({inf:t[e],num:i[e]});return r}getParadropSquads(e){switch(e){case qt.GDI:return this.allyParaDrop;case qt.Nod:return this.sovParaDrop;default:throw new Error(`Unhandled side type "${e}"`)}}}class Ei{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 Pi{}class xi extends Pi{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 Ni extends Pi{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 Ri{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}}(s=Qt=Qt||{})[s.Power=0]="Power",s[s.Factory=1]="Factory",s[s.Barracks=2]="Barracks",s[s.Radar=3]="Radar",s[s.Tech=4]="Tech",s[s.Proc=5]="Proc";const Mi=(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 Di{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.getNumber("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 Ii).readIni(e),this.defaultMirageDisguises=e.getArray("DefaultMirageDisguises"),this.dMisl=(new Ni).readIni(e),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 Ri).readIni(e),this.infantryBlinkDisguiseTime=e.getNumber("InfantryBlinkDisguiseTime"),this.lightningStorm=(new Ei).readIni(e),this.lowPowerPenaltyModifier=e.getNumber("LowPowerPenaltyModifier",1),this.minLowPowerProductionSpeed=e.getNumber("MinLowPowerProductionSpeed",.5),this.maxLowPowerProductionSpeed=e.getNumber("MaxLowPowerProductionSpeed",1),this.maximumCheerRate=e.getNumber("MaximumCheerRate"),this.maximumQueuedObjects=e.getNumber("MaximumQueuedObjects"),this.maxWaypointPathLength=e.getNumber("MaxWaypointPathLength"),this.multipleFactory=e.getNumber("MultipleFactory",1),this.normalTargetingDelay=e.getNumber("NormalTargetingDelay"),this.padAircraft=e.getArray("PadAircraft"),this.parachuteMaxFallRate=e.getNumber("ParachuteMaxFallRate"),this.paradrop=(new Bi).readIni(e),this.prism=(new Ci).readIni(e),this.purifierBonus=e.getNumber("PurifierBonus"),this.radar=(new _i).readIni(e),this.refundPercent=e.getNumber("RefundPercent"),this.repair=(new ki).readIni(e),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 Ai).readIni(e),this.treeStrength=e.getNumber("TreeStrength"),this.v3Rocket=(new xi).readIni(e),this.veteran=(new Oi).readIni(e),this.wallBuildSpeedCoefficient=e.getNumber("WallBuildSpeedCoefficient"),this.readPrereqCategories(e)}readPrereqCategories(e){for(var[t,i]of Mi){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}"`)}}}(s=Xt=Xt||{})[s.Default=0]="Default",s[s.Tunnel=5]="Tunnel",s[s.Railroad=6]="Railroad",s[s.Rock1=7]="Rock1",s[s.Rock2=8]="Rock2",s[s.Water=9]="Water",s[s.Shore=10]="Shore",s[s.Pavement=11]="Pavement",s[s.Dirt=12]="Dirt",s[s.Clear=13]="Clear",s[s.Rough=14]="Rough",s[s.Cliff=15]="Cliff",(s=Yt=Yt||{})[s.Clear=0]="Clear",s[s.Road=1]="Road",s[s.Rock=2]="Rock",s[s.Beach=3]="Beach",s[s.Rough=4]="Rough",s[s.Railroad=5]="Railroad",s[s.Water=6]="Water",s[s.Wall=7]="Wall",s[s.Tiberium=8]="Tiberium",s[s.Cliff=9]="Cliff";const Li=new Map([[Xt.Default,Yt.Clear],[Xt.Clear,Yt.Clear],[Xt.Tunnel,Yt.Cliff],[Xt.Railroad,Yt.Railroad],[Xt.Rock1,Yt.Rock],[Xt.Rock2,Yt.Rock],[Xt.Water,Yt.Water],[Xt.Shore,Yt.Beach],[Xt.Pavement,Yt.Road],[Xt.Dirt,Yt.Road],[Xt.Rough,Yt.Rough],[Xt.Cliff,Yt.Cliff]]);function Fi(e){if(!Li.has(e))throw new Error(`Unknown terrain type ${e}`);return Li.get(e)}(s=Kt=Kt||{})[s.Foot=0]="Foot",s[s.Track=1]="Track",s[s.Wheel=2]="Wheel",s[s.Hover=3]="Hover",s[s.Float=4]="Float",s[s.FloatBeach=5]="FloatBeach",s[s.Amphibious=6]="Amphibious",s[s.Winged=7]="Winged";class ji{constructor(){this.speedModifiers=new Map}readIni(t){return this.buildable=t.getBool("Buildable",!1),[...t.entries.keys()].forEach(e=>{void 0!==Kt[e]&&this.speedModifiers.set(Kt[e],t.getNumber(e))}),this}getSpeedModifier(e){if(e===Kt.Foot&&0===this.speedModifiers.get(Kt.Track))return 0;let t=this.speedModifiers.get(e);return void 0===t&&(t=1),t}}(s=Jt=Jt||{})[s.None=0]="None",s[s.Gunfire=1]="Gunfire",s[s.Explode=2]="Explode",s[s.ExplodeAlt=3]="ExplodeAlt",s[s.Fire=4]="Fire",s[s.Electro=5]="Electro",s[s.HeadExplode=6]="HeadExplode",s[s.Nuke=7]="Nuke";class Ui{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.cellSpread=this.rules.getNumber("CellSpread"),this.conventional=this.rules.getBool("Conventional"),this.culling=this.rules.getBool("Culling"),this.electricAssault=this.rules.getBool("ElectricAssault"),this.emEffect=this.rules.getBool("EMEffect"),this.infDeath=this.rules.getNumber("InfDeath",Jt.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 Wi extends bi{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=bi.iniRotToDegsPerTick(e),this.iniRot=e,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")}}(s=ei=ei||{})[s.Green=0]="Green",s[s.Yellow=1]="Yellow",s[s.White=2]="White",s[s.Red=3]="Red",s[s.Blue=4]="Blue",(s=ti=ti||{})[s.Statue=0]="Statue",s[s.Aircraft=1]="Aircraft",s[s.Chrono=2]="Chrono",s[s.Hover=3]="Hover",s[s.Infantry=4]="Infantry",s[s.Jumpjet=5]="Jumpjet",s[s.Missile=6]="Missile",s[s.Ship=7]="Ship",s[s.Vehicle=8]="Vehicle";const Vi=new Map([["{4A582746-9839-11d1-B709-00A024DDAFD1}",ti.Aircraft],["{4A582747-9839-11d1-B709-00A024DDAFD1}",ti.Chrono],["{4A582742-9839-11d1-B709-00A024DDAFD1}",ti.Hover],["{4A582744-9839-11d1-B709-00A024DDAFD1}",ti.Infantry],["{92612C46-F71F-11d1-AC9F-006008055BB5}",ti.Jumpjet],["{B7B49766-E576-11d3-9BD9-00104B972FE8}",ti.Missile],["{2BEA74E1-7CCA-11d3-BE14-00104B62A16C}",ti.Ship],["{4A582741-9839-11d1-B709-00A024DDAFD1}",ti.Vehicle]]),zi=new Map([[ti.Infantry,Kt.Foot],[ti.Ship,Kt.Float],[ti.Hover,Kt.Hover],[ti.Jumpjet,Kt.Winged],[ti.Aircraft,Kt.Winged],[ti.Missile,Kt.Winged]]);(s=ii=ii||{})[s.Amphibious=0]="Amphibious",s[s.AmphibiousCrusher=1]="AmphibiousCrusher",s[s.AmphibiousDestroyer=2]="AmphibiousDestroyer",s[s.Crusher=3]="Crusher",s[s.CrusherAll=4]="CrusherAll",s[s.Destroyer=5]="Destroyer",s[s.Fly=6]="Fly",s[s.Infantry=7]="Infantry",s[s.InfantryDestroyer=8]="InfantryDestroyer",s[s.Normal=9]="Normal",s[s.Subterranean=10]="Subterranean",s[s.Water=11]="Water",(s=ri=ri||{})[s.None=0]="None",s[s.Flak=1]="Flak",s[s.Plate=2]="Plate",s[s.Light=3]="Light",s[s.Medium=4]="Medium",s[s.Heavy=5]="Heavy",s[s.Wood=6]="Wood",s[s.Steel=7]="Steel",s[s.Concrete=8]="Concrete",s[s.Special_1=9]="Special_1",s[s.Special_2=10]="Special_2",(s=si=si||{})[s.Primary=0]="Primary",s[s.Secondary=1]="Secondary",s[s.DeathWeapon=2]="DeathWeapon",(s=ai=ai||{})[s.FASTER=0]="FASTER",s[s.STRONGER=1]="STRONGER",s[s.FIREPOWER=2]="FIREPOWER",s[s.SCATTER=3]="SCATTER",s[s.ROF=4]="ROF",s[s.SIGHT=5]="SIGHT",s[s.SELF_HEAL=6]="SELF_HEAL",(s=ni=ni||{})[s.None=0]="None",s[s.Normal=1]="Normal",s[s.Strong=2]="Strong";var Hi,Gi,$i,qi,Zi,Qi=__webpack_require__(949);(s=Hi=Hi||{})[s.Combat=0]="Combat",s[s.Tech=1]="Tech",s[s.Resource=2]="Resource",s[s.Power=3]="Power",(s=Gi=Gi||{})[s.None=0]="None",s[s.BuildingType=1]="BuildingType",s[s.InfantryType=2]="InfantryType",s[s.UnitType=3]="UnitType",s[s.NavalUnitType=4]="NavalUnitType",s[s.AircraftType=5]="AircraftType";class Xi extends bi{parse(){super.parse(),this.owner=this.ini.getArray("Owner");var e=this.ini.getNumber("AIBasePlanningSide");this.aiBasePlanningSide=-1!==e&&void 0!==qt[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",Hi,Hi.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.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===At.Building),this.clickRepairable=this.ini.getBool("ClickRepairable",this.type===At.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",Gi,Gi.None),this.factory===Gi.UnitType&&t&&(this.factory=Gi.NavalUnitType),this.weaponsFactory=this.ini.getBool("WeaponsFactory"),this.helipad=this.ini.getBool("Helipad"),this.hospital=this.ini.getBool("Hospital"),this.landTargeting=this.ini.getNumber("LandTargeting"),this.navalTargeting=this.ini.getNumber("NavalTargeting"),this.tooBigToFitUnderBridge=this.ini.getBool("TooBigToFitUnderBridge",this.type===At.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.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");let i=this.ini.getString("Primary");i&&"none"!==i.toLowerCase()&&(this.primary=i);let r=this.ini.getString("Secondary");r&&"none"!==r.toLowerCase()&&(this.secondary=r);let s=this.ini.getString("ElitePrimary");s&&"none"!==s.toLowerCase()&&(this.elitePrimary=s);let a=this.ini.getString("EliteSecondary");a&&"none"!==a.toLowerCase()&&(this.eliteSecondary=a),this.weaponCount=this.ini.getNumber("WeaponCount"),this.deathWeapon=this.ini.getString("DeathWeapon"),this.deathWeaponDamageModifier=this.ini.getNumber("DeathWeaponDamageModifier",1),this.veteranAbilities=new Set(this.ini.getEnumArray("VeteranAbilities",ai)),this.eliteAbilities=new Set([...this.veteranAbilities,...this.ini.getEnumArray("EliteAbilities",ai)]),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=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 n=this.ini.getBool("Landable");this.landable=n,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;e=this.ini.getString("Locomotor");if(e?(t=Vi.get(e))?this.locomotor=t:(console.warn(`Object rules "${this.name}" has invalid Locomotor "${e}"`),this.locomotor=ti.Statue):this.locomotor=ti.Statue,this.locomotor!==ti.Statue){let e=zi.get(this.locomotor);void 0===e&&(this.type===At.Aircraft||this.consideredAircraft?e=Kt.Winged:this.type===At.Vehicle?e=this.crusher?Kt.Track:Kt.Wheel:this.type===At.Infantry&&(e=Kt.Foot)),this.speedType=this.ini.getEnum("SpeedType",Kt,e)}this.speed=bi.iniSpeedToLeptonsPerTick(this.ini.getNumber("Speed")),this.movementZone=this.ini.getEnum("MovementZone",ii,ii.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",si.Secondary),this.undeployDelay=this.ini.getNumber("UndeployDelay"),this.fraidycat=this.ini.getBool("Fraidycat",!1),this.isHuman=!this.ini.getBool("NotHuman"),this.organic=this.type===At.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!==At.Building),this.crewed=this.ini.getBool("Crewed"),this.parasiteable=this.ini.getBool("Parasiteable",this.type!==At.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",ni,ni.None,!0),this.pip=this.ini.getEnum("Pip",ei,ei.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===At.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(Xi.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===At.Aircraft&&!n)&&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!==At.Aircraft),this.leadershipRating=this.ini.getNumber("LeadershipRating",5),this.allowedToStartInMultiplayer=this.ini.getBool("AllowedToStartInMultiplayer",!0),this.rot=bi.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=bi.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");n=this.ini.getNumberArray("DamageSmokeOffset",void 0,[0,0,0]);this.damageSmokeOffset=new Qi.Vector3(n[0],n[2]/Math.SQRT2,n[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}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.ini.getString(`Weapon${e+1}`)||void 0}getEliteWeaponAtIndex(e){return this.ini.getString(`EliteWeapon${e+1}`)||void 0}}Xi.MAX_SIGHT=11,Xi.MAGIC_SPEED_MULT=.65;class Yi extends bi{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",Yt,Yt.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)}}(s=$i=$i||{})[s.All=7]="All",s[s.Right=1]="Right",s[s.Left=2]="Left",s[s.Bottom=4]="Bottom";class Ki extends bi{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",$i.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",$i.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===$i.All)return e;let r=[];for(t of e)!function(e,t){switch(e){case 0:case 1:return 1;case 2:return 0!=(t&$i.Right);case 3:return 0!=(t&$i.Left);case 4:return 0!=(t&$i.Bottom);default:throw new Error(`Invalid subCell "${e}`)}}(t,i)||r.push(t);return r}}class Ji extends bi{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 er extends bi{parse(){super.parse(),this.damage=this.ini.getNumber("Damage"),this.damageRadius=this.ini.getNumber("DamageRadius"),this.elasticity=this.ini.getNumber("Elasticity"),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 tr{create(e,t){switch(e){case At.Aircraft:case At.Building:case At.Infantry:case At.Vehicle:return new Xi(e,t);case At.Overlay:return new Yi(e,t);case At.Terrain:return new Ki(e,t);case At.Smudge:return new Ji(e,t);case At.VoxelAnim:return new er(e,t);default:return new bi(e,t)}}}class ir{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.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 rr{readIni(e){return this.value=e.getNumber("Value"),this}}class sr{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 ar{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 nr{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")}}(s=qi=qi||{})[s.MultiMissile=0]="MultiMissile",s[s.IronCurtain=1]="IronCurtain",s[s.LightningStorm=2]="LightningStorm",s[s.ChronoSphere=3]="ChronoSphere",s[s.ChronoWarp=4]="ChronoWarp",s[s.ParaDrop=5]="ParaDrop",s[s.AmerParaDrop=6]="AmerParaDrop";class or{readIni(e){return this.disableableFromShell=e.getBool("DisableableFromShell"),this.isPowered=e.getBool("IsPowered",!0),this.preClick=e.getBool("PreClick"),this.preDependent=e.getEnum("PreDependent",qi,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",qi,void 0),this.uiName=e.getString("UIName"),this.weaponType=e.getString("WeaponType")||void 0,this}}class hr{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}}(s=Zi=Zi||{})[s.Armor=0]="Armor",s[s.Firepower=1]="Firepower",s[s.HealBase=2]="HealBase",s[s.Money=3]="Money",s[s.Reveal=4]="Reveal",s[s.Speed=5]="Speed",s[s.Veteran=6]="Veteran",s[s.Unit=7]="Unit";class lr{constructor(){this.powerups=[]}readIni(e){for(var[s,a]of e.entries){let[e,t,i,r]=a.split(",");var n=Number(e),a=Zi[s];void 0!==a||0===n?this.powerups.push({type:a,probShares:n,animName:"<none>"!==t.toLowerCase()?t:void 0,waterAllowed:"yes"===i,data:r}):console.warn(`Unknown powerup "${s}". Skipping.`)}return this}}const cr=["Gold","DarkRed","DarkBlue","DarkGreen","Orange","DarkSky","Purple","Magenta"];class ur{constructor(e,t){this.ini=e,this.logger=t,this.buildingTypes=new Set,this.vehicleTypes=new Set,this.infantryTypes=new Set,this.aircraftTypes=new Set,this.terrainTypes=new Set,this.overlayTypes=new Map,this.overlayIdsByType=new Map,this.animationTypes=new Set,this.voxelAnimTypes=new Set,this.smudgeTypes=new Set,this.warheadTypes=new Set,this.tiberiumTypes=new Map,this.superWeaponTypes=new Set,this.countryNames=new Set,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 lr,this.colors=new Map,this.general=new Di,this.ai=new sr,this.crateRules=new hr,this.elevationModel=new ar,this.mpDialogSettings=new St,this.audioVisual=new Si,this.combatDamage=new ir,this.radiation=new nr,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}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 vi(i),this.cachedWeaponRules.set(e,t)}return t}getWarhead(e){let t=this.warheadRules.get(e);var i;if(t||(i=this.ini.getSection(e))&&(t=new Ui(i),this.warheadRules.set(e,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 Wi(At.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}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}getCountry(e){if(!this.countryNames.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 cr.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===Yt.Cliff?"Rock":Yt[e],t=(new ji).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.superWeaponTypes.has(e))throw new Error(`Unknown superweapon type "${e}"`);return this.superWeaponRules.get(e)}getIni(){return this.ini}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.readObjectTypes("VoxelAnims",this.voxelAnimTypes),this.readOverlayTypes(),this.readColors(),this.readCountryNames(),this.readWarheadTypes(),this.readTiberiumTypes(),this.readSuperWeaponTypes(),this.allObjectRules.set(At.Building,this.buildingRules).set(At.Infantry,this.infantryRules).set(At.Vehicle,this.vehicleRules).set(At.Aircraft,this.aircraftRules).set(At.Terrain,this.terrainRules).set(At.Overlay,this.overlayRules).set(At.Smudge,this.smudgeRules).set(At.VoxelAnim,this.voxelAnimRules),this.readObjects(At.Building,this.buildingTypes,this.buildingRules),this.readObjects(At.Infantry,this.infantryTypes,this.infantryRules),this.readObjects(At.Vehicle,this.vehicleTypes,this.vehicleRules),this.readObjects(At.Aircraft,this.aircraftTypes,this.aircraftRules),this.readObjects(At.Terrain,this.terrainTypes,this.terrainRules),this.readObjects(At.Overlay,new Set(this.overlayTypes.values()),this.overlayRules),this.readObjects(At.Smudge,this.smudgeTypes,this.smudgeRules),this.readObjects(At.VoxelAnim,this.voxelAnimTypes,this.voxelAnimRules),this.readCountries(),this.readWarheads(),this.readPowerups(),this.readTiberiums(),this.readSuperWeapons()}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(e,t){let i=this.ini.getSection(e);if(!i)throw new Error(`Missing [${e}] section`);i.entries.forEach(e=>{t.add(e)})}readOverlayTypes(){let e=this.ini.getSection("OverlayTypes");if(!e)throw new Error("Missing [OverlayTypes] section");let t=0;e.entries.forEach(e=>{this.overlayIdsByType.set(e,t),this.overlayTypes.set(t++,e)})}readCountryNames(){let e=this.ini.getSection("Countries");if(!e)throw new Error("Missing [Countries] section");e.entries.forEach(e=>{this.countryNames.add(e)})}readWarheadTypes(){let e=this.ini.getSection("Warheads");if(!e)throw new Error("Missing [Warheads] section");e.entries.forEach(e=>{this.warheadTypes.add(e)})}readTiberiumTypes(){let e=this.ini.getSection("Tiberiums");if(!e)throw new Error("Missing [Tiberiums] section");e.entries.forEach((e,t)=>{this.tiberiumTypes.set(Number(t),e)})}readSuperWeaponTypes(){let e=this.ini.getSection("SuperWeaponTypes");if(!e)throw new Error("Missing [SuperWeaponTypes] section");e.entries.forEach((e,t)=>{this.superWeaponTypes.add(e)})}readColors(){let e=this.ini.getSection("Colors");if(!e)throw new Error("Missing [Colors] section");e.entries.forEach((e,t)=>{var[i,r,e]=e.split(","),e=j.fromHsv(parseInt(i,10),parseInt(r,10),parseInt(e,10));this.colors.set(t,e)})}readObjects(i,e,r){e.forEach(e=>{var t=this.ini.getSection(e);t?(t=(new tr).create(i,t),r.set(e,t)):this.logger?.debug(`${At[i]} type "${e}" has no rules section`)})}readCountries(){this.countryNames.forEach(e=>{var t=this.ini.getSection(e);if(!t)throw new Error(`Missing ini section for country ${e}`);let i=new Ti;i.readIni(t),this.countryRules.set(e,i)})}readWarheads(){this.warheadTypes.forEach(e=>{var t=this.ini.getSection(e);t?(t=new Ui(t),this.warheadRules.set(e,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 rr).readIni(t))})}readSuperWeapons(){this.superWeaponTypes.forEach(e=>{var t=this.ini.getSection(e);if(!t)throw new Error(`Missing rules section for superweapon type ${e}`);this.superWeaponRules.set(e,(new or).readIni(t))})}}var dr,pr,gr=__webpack_require__(949);class mr{static init(e){mr.worldOrigin=e}static worldToScreen(e,t){if(!mr.worldOrigin)throw new Error("Coords not initialized with world origin");return{x:(e-=mr.worldOrigin.x)-(t-=mr.worldOrigin.y)-1,y:(e+t-1)/2}}static screenToWorld(e,t){if(!mr.worldOrigin)throw new Error("Coords not initialized with world origin");return{x:(e+2*t)/2+1+mr.worldOrigin.x,y:(2*t-e)/2+mr.worldOrigin.y}}static tileToWorld(e,t){return{x:e*mr.ISO_TILE_SIZE,y:t*mr.ISO_TILE_SIZE}}static worldToTile(e,t){return{x:Math.floor(e/mr.ISO_TILE_SIZE),y:Math.floor(t/mr.ISO_TILE_SIZE)}}static worldToLeptons(e){return e*mr.LEPTONS_PER_TILE/mr.ISO_TILE_SIZE}static leptonsToWorld(e){return e/mr.LEPTONS_PER_TILE*mr.ISO_TILE_SIZE}static vecWorldToLeptons(e){return e.clone().multiplyScalar(mr.LEPTONS_PER_TILE/mr.ISO_TILE_SIZE)}static vecLeptonsToWorld(e){return e.clone().multiplyScalar(mr.ISO_TILE_SIZE/mr.LEPTONS_PER_TILE)}static vecWorldToScreen(e){let t=mr.worldToScreen(e.x,e.z);return t.y-=e.y/mr.zScale,t}static vecWorldToGround(e){return new gr.Vector2(e.x,e.z)}static vecGroundToWorld(e){return new gr.Vector3(e.x,0,e.y)}static tileHeightToWorld(e){return e*(mr.ISO_TILE_SIZE/2)*mr.zScale+1}static tileHeightToScreen(e){return e*(mr.ISO_TILE_SIZE/2)+1/mr.zScale}static worldToTileHeight(e){return(e-1)/mr.zScale/(mr.ISO_TILE_SIZE/2)}static tileToScreen(e,t){t=mr.tileToWorld(e,t);return mr.worldToScreen(t.x,t.y)}static tile3dToWorld(e,t,i){t=mr.tileToWorld(e,t),i=mr.tileHeightToWorld(i);return new gr.Vector3(t.x,i,t.y)}static tile3dToScreen(e,t,i){t=mr.tileToWorld(e,t);let r=mr.worldToScreen(t.x,t.y);return r.y-=i*(mr.ISO_TILE_SIZE/2)+1/mr.zScale,r}static screenTileToScreen(e,t){return{x:e*mr.ISO_TILE_SIZE,y:t*mr.ISO_TILE_SIZE/2}}static screenToScreenTile(e,t){return{x:e/mr.ISO_TILE_SIZE,y:t/(mr.ISO_TILE_SIZE/2)}}static screenTileToWorld(e,t){t=mr.screenTileToScreen(e,t);return mr.screenToWorld(t.x,t.y)}static getScreenTileSize(){return{width:mr.tileToScreen(1,0).x-mr.tileToScreen(0,1).x,height:mr.tileToScreen(1,1).y-mr.tileToScreen(0,0).y}}static screenDistanceToWorld(e,t){var i=mr.screenToWorld(0,0),t=mr.screenToWorld(e,t);return{x:t.x-i.x,y:t.y-i.y}}static screenDistanceToLeptons(e,t){var{x:e,y:t}=mr.screenDistanceToWorld(e,t);return{x:e/mr.ISO_TILE_SIZE*mr.LEPTONS_PER_TILE,y:t/mr.ISO_TILE_SIZE*mr.LEPTONS_PER_TILE}}static getWorldTileSize(){return mr.ISO_TILE_SIZE}}mr.ISO_TILE_SIZE=30,mr.LEPTONS_PER_TILE=256,mr.ISO_CAMERA_ALPHA=Math.PI/6,mr.ISO_CAMERA_BETA=Math.PI/4,mr.COS_ISO_CAMERA_BETA=Math.cos(mr.ISO_CAMERA_BETA),mr.zScale=Math.cos(mr.ISO_CAMERA_BETA)/Math.cos(mr.ISO_CAMERA_ALPHA),(s=dr=dr||{})[s.Ready=0]="Ready",s[s.Guard=1]="Guard",s[s.Prone=2]="Prone",s[s.Walk=3]="Walk",s[s.FireUp=4]="FireUp",s[s.Down=5]="Down",s[s.Crawl=6]="Crawl",s[s.Up=7]="Up",s[s.FireProne=8]="FireProne",s[s.Idle1=9]="Idle1",s[s.Idle2=10]="Idle2",s[s.Die1=11]="Die1",s[s.Die2=12]="Die2",s[s.Hover=13]="Hover",s[s.Fly=14]="Fly",s[s.FireFly=15]="FireFly",s[s.Tumble=16]="Tumble",s[s.AirDeathStart=17]="AirDeathStart",s[s.AirDeathFalling=18]="AirDeathFalling",s[s.AirDeathFinish=19]="AirDeathFinish",s[s.Tread=20]="Tread",s[s.Swim=21]="Swim",s[s.WetAttack=22]="WetAttack",s[s.WetIdle1=23]="WetIdle1",s[s.WetIdle2=24]="WetIdle2",s[s.WetDie1=25]="WetDie1",s[s.WetDie2=26]="WetDie2",s[s.Deploy=27]="Deploy",s[s.Deployed=28]="Deployed",s[s.DeployedFire=29]="DeployedFire",s[s.DeployedIdle=30]="DeployedIdle",s[s.Undeploy=31]="Undeploy",s[s.Paradrop=32]="Paradrop",s[s.Cheer=33]="Cheer",s[s.Panic=34]="Panic";const fr=new Map([["E",5],["S",3],["W",1],["N",7]]);class yr{readIni(e){let t=new Map;for(var[i,r]of e.entries){i=dr[i];void 0!==i&&(r=r.split(","),r={type:i,startFrame:Number(r[0]),frameCount:Number(r[1]),facingMult:Number(r[2]),onlyFacing:r[3]?fr.get(r[3]):void 0},t.set(i,r))}return t}}(s=pr=pr||{})[s.None=0]="None",s[s.Global=1]="Global",s[s.Level=2]="Level",s[s.Ambient=3]="Ambient",s[s.Full=4]="Full",s[s.Default=5]="Default";class wr{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 wr([this.forward,this.lateral,this.vertical])}}var Tr,br,vr,Sr,_r,kr,Or,Ir,Cr,Ar=__webpack_require__(949);class Br{constructor(e,t,i){this.dockingOffsets=[],this.type=e,this.rules=t,this.art=i,this.init()}static getDefaultPalette(e){switch(e){case At.Building:case At.Aircraft:case At.Infantry:case At.Vehicle:case At.Projectile:case At.VoxelAnim:return O.Unit;case At.Overlay:return O.Overlay;case At.Smudge:case At.Terrain:return O.Iso;default:At.Animation;return O.Anim}}static getDefaultLighting(e){switch(e){case At.Animation:return pr.None;case At.Aircraft:case At.Building:case At.Infantry:case At.Vehicle:return pr.Ambient;case At.Projectile:case At.VoxelAnim:return pr.Global;case At.Overlay:case At.Smudge:case At.Terrain:default:return pr.Full}}static getDefaultRemapability(e){switch(e){case At.Aircraft:case At.Building:case At.Infantry:case At.Vehicle:return!0;case At.Overlay:case At.Smudge:case At.Terrain:case At.Animation:case At.Projectile:case At.VoxelAnim:return!1;default:throw new Error(`Unknown object type ${e}`)}}static getDefaultDrawOffset(e){switch(e){case At.Animation:case At.Building:case At.Vehicle:case At.Infantry:case At.Overlay:case At.Smudge:case At.Projectile:case At.VoxelAnim:return new Ar.Vector2(0,0);case At.Terrain:case At.Aircraft:return new Ar.Vector2(0,(mr.ISO_TILE_SIZE+1)/2);default:throw new Error(`Unknown object type ${e}`)}}static getDefaultShadow(e){switch(e){case At.Overlay:case At.Building:case At.Infantry:case At.Terrain:case At.Vehicle:case At.Aircraft:return!0;default:case At.Smudge:case At.Animation:case At.Projectile:case At.VoxelAnim:return!1}}static getDefaultHeight(e){switch(e){case At.Building:return 2;case At.Infantry:case At.Vehicle:case At.Aircraft:return 1;default:return 0}}static factory(e,t,i,r){var s=t.imageName;let a=i.getSection(s);a||(r?.debug(`Image ${s} (${At[e]}: ${t.name}) has no section in art.ini`),a=new h(s));let n=new this(e,t,a);return e===At.Infantry&&(!(e=a.getString("Sequence"))||(e=i.getSection(e))&&(n.sequences=(new yr).readIni(e))),n}init(){this.image=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 Ar.Vector2(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",Br.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",Br.getDefaultHeight(this.type)),this.isVoxel=this.art.getBool("Voxel"),this.occupyHeight=this.art.getNumber("OccupyHeight",this.height),this.type===At.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")}get imageName(){return(this.image||this.rules.imageName)+(this.rules.alternateArcticArt?"A":"")}get cameo(){let e=this.art.getString("Cameo")||Br.MISSING_CAMEO;return e.toLowerCase()}get altCameo(){let e=this.art.getString("AltCameo")||Br.MISSING_CAMEO;return e.toLowerCase()}get useTheaterExtension(){return this.art.getBool("Theater")}readPaletteAndLightingTypes(){this.paletteType=O.Default,this.lightingType=pr.Default,(this.rules instanceof Yi?this.rules.noUseTileLandType:void 0)&&(this.paletteType=O.Iso,this.lightingType=pr.Full),this.art.getBool("TerrainPalette")||this.art.getBool("ShouldUseCellDrawer")?this.paletteType=O.Iso:this.art.getBool("AnimPalette")?(this.paletteType=O.Anim,this.lightingType=pr.None):this.art.getString("Palette")&&(this.paletteType=O.Custom,this.customPaletteName=this.art.getString("Palette")),this.art.getBool("AltPalette")&&(this.paletteType=O.Unit),(this.rules instanceof Yi||this.rules instanceof Xi)&&this.rules.wall&&(this.paletteType=O.Unit,this.lightingType=pr.Ambient),(this.rules instanceof Ki||this.rules instanceof Xi)&&this.rules.gate&&(this.paletteType=O.Unit),this.rules instanceof Ki&&this.rules.spawnsTiberium&&(this.paletteType=O.Unit,this.lightingType=pr.None),this.rules instanceof Yi&&(this.rules.isVeins&&(this.paletteType=O.Unit,this.lightingType=pr.None),this.rules.isVeinholeMonster&&(this.paletteType=O.Unit,this.lightingType=pr.None),this.rules.tiberium&&(this.lightingType=pr.None),this.rules.land===Yt.Railroad&&(this.paletteType=O.Iso,this.lightingType=pr.Full),this.rules.crate&&(this.paletteType=O.Iso,this.lightingType=pr.Full)),this.paletteType===O.Default&&(this.paletteType=Br.getDefaultPalette(this.type)),this.lightingType===pr.Default&&(this.lightingType=Br.getDefaultLighting(this.type))}readRemapability(){this.remapable=Br.getDefaultRemapability(this.type),this.art.getBool("TerrainPalette")||this.art.getBool("AnimPalette")?this.remapable=!1:this.rules instanceof Wi&&this.rules.firersPalette&&(this.remapable=!0)}readFlatness(){let e=!1;this.type===At.Building||this.type===At.Animation?e=this.art.getBool("Flat"):this.type===At.Smudge&&(e=!0),this.rules instanceof Yi&&(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 r=this.art.getNumberArray(`Rotor${e+1}Axis`,void 0,[0,1,0]),r=new Ar.Vector3(-r[2],-r[0],r[1]).normalize();t.push({name:i[e],axis:r,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[r,s]=this.art.getNumberArray(t);i.push({x:r,y:s}),e++,t=`MuzzleFlash${e}`}this.muzzleFlash=i.length?i:void 0}readDockingOffsets(){if(this.type===At.Building){var t=this.rules.numberOfDocks;for(let e=0;e<t;e++){var[i,r,s]=this.art.getNumberArray(`DockingOffset${e}`,/\,\s*/,[0,0,0]);this.dockingOffsets.push(new Ar.Vector3(i,s,r))}}}readAddRemoveOccupy(e){let t=0,i=[];for(;;){var r=this.art.getNumberArray(e+ ++t);if(!r.length)break;i.push(new Ar.Vector2(r[0],r[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{x:Math.floor(this.foundation.width/2-.5),y:Math.floor(this.foundation.height/2-.5)}}getDrawOffset(){if(this.rules instanceof Ki&&this.rules.spawnsTiberium)return new Ar.Vector2(0,0);let e=Br.getDefaultDrawOffset(this.type);return this.rules instanceof Yi&&this.rules.isARock&&(e.y+=(mr.ISO_TILE_SIZE+1)/2),e}get hasShadow(){return this.art.getBool("Shadow",Br.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 wr(this.art.getNumberArray("PrimaryFireFLH"))}get elitePrimaryFireFlh(){var e=this.art.getNumberArray("ElitePrimaryFireFLH");return e.length?new wr(e):this.primaryFireFlh}get primaryFirePixelOffset(){return this.art.getNumberArray("PrimaryFirePixelOffset")}get secondaryFirePixelOffset(){return this.art.getNumberArray("SecondaryFirePixelOffset")}get secondaryFireFlh(){return new wr(this.art.getNumberArray("SecondaryFireFLH"))}get eliteSecondaryFireFlh(){var e=this.art.getNumberArray("EliteSecondaryFireFLH");return e.length?new wr(e):this.secondaryFireFlh}getSpecialWeaponFlh(e){return new wr(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}}Br.DEFAULT_LINE_TRAIL_DEC=16,Br.MISSING_CAMEO="xxicon";class Er{constructor(e,t,i){this.rules=e,this.artIni=t,this.logger=i,this.objectArt=new Map,this.parse()}hasObject(e,t){return this.objectArt.get(t)?.has(e)}getObject(e,t){t=this.objectArt.get(t)?.get(e);if(!t)throw new Error(`Missing art for object "${e}"`);return t}getOrCreateObject(e,t){return this.hasObject(e,t)?this.getObject(e,t):new Br(t,this.rules.hasObject(e,t)?this.rules.getObject(e,t):new bi(t,new h(e)),new h(e))}getAnimation(e){return this.getObject(e,At.Animation)}getProjectile(e){e=this.rules.getProjectile(e);return Br.factory(e.type,e,this.artIni,this.logger)}getIni(){return this.artIni}parse(){this.rules.allObjectRules.forEach((e,t)=>{let i=new Map;this.objectArt.set(t,i),e.forEach(e=>{var t;this.artIni.getSection(e.imageName)?(t=Br.factory(e.type,e,this.artIni),i.set(e.name,t)):this.logger?.debug(`${At[e.type]} "${e.name}" has no art section`)})});let e=[[At.Animation,this.rules.animationTypes]];e.forEach(([r,e])=>{let s=new Map;this.objectArt.set(r,s),e.forEach(e=>{var t,i=this.artIni.getSection(e);i?(t=new bi(r,new h(e)),i=new Br(r,t,i),s.set(e,i)):this.logger?.debug(`${At[r]} "${e}" has no art section`)})})}}class Pr{constructor(e){this.rules=e}static factory(e,t){return new this(t.getCountry(e))}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 At.Aircraft:i=this.rules.veteranAircraft;break;case At.Infantry:i=this.rules.veteranInfantry;break;case At.Vehicle:i=this.rules.veteranUnits;break;default:throw new Error(`Unsupported object type "${At[e]}"`)}return i.includes(t)}}(Tr=Tr||{}).onDestroy=Symbol();class xr{constructor(e,t,i,r,s,a,n,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.foundation=r,this.maxDistance=a,this.predicate=n,this.checkBounds=o,this.distance=s,this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){var r=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t))return t};do{var s=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>=s;e--)i=r(e,o),i&&(yield i);for(t=o-1;t>=a;t--)i=r(n,t),i&&(yield i);for(e=s;e<n;e++)i=r(e,a),i&&(yield i);for(t=1+a;t<o;t++)i=r(s,t),i&&(yield i)}else this.predicate(this.startTile)&&(yield this.startTile)}while(this.distance++,this.distance<=this.maxDistance)}}(br=br||{}).onDamage=Symbol(),(s=vr=vr||{})[s.Cheer=0]="Cheer",s[s.UnitDeployUndeploy=1]="UnitDeployUndeploy",s[s.WeaponFire=2]="WeaponFire",s[s.ObjectDestroy=3]="ObjectDestroy",s[s.ObjectSpawn=4]="ObjectSpawn",s[s.ObjectUnspawn=5]="ObjectUnspawn",s[s.ObjectMorph=6]="ObjectMorph",s[s.ObjectLiftOff=7]="ObjectLiftOff",s[s.ObjectLand=8]="ObjectLand",s[s.ObjectCrashing=9]="ObjectCrashing",s[s.ObjectDisguiseChange=10]="ObjectDisguiseChange",s[s.ObjectCloakChange=11]="ObjectCloakChange",s[s.ShipSubmergeChange=12]="ShipSubmergeChange",s[s.BridgeRepair=13]="BridgeRepair",s[s.BuildStatusChange=14]="BuildStatusChange",s[s.BuildingPlace=15]="BuildingPlace",s[s.BuildingFailedPlace=16]="BuildingFailedPlace",s[s.BuildingSell=17]="BuildingSell",s[s.BuildingRepairFull=18]="BuildingRepairFull",s[s.BuildingCapture=19]="BuildingCapture",s[s.BuildingInfiltration=20]="BuildingInfiltration",s[s.BuildingGarrison=21]="BuildingGarrison",s[s.BuildingEvacuate=22]="BuildingEvacuate",s[s.BuildingRepairStart=23]="BuildingRepairStart",s[s.UnitRepairStart=24]="UnitRepairStart",s[s.UnitRepairFinish=25]="UnitRepairFinish",s[s.UnitRecycle=26]="UnitRecycle",s[s.InflictDamage=27]="InflictDamage",s[s.WarheadDetonate=28]="WarheadDetonate",s[s.PlayerDefeated=29]="PlayerDefeated",s[s.PlayerResigned=30]="PlayerResigned",s[s.DeployNotAllowed=31]="DeployNotAllowed",s[s.PowerChange=32]="PowerChange",s[s.PowerLow=33]="PowerLow",s[s.PowerRestore=34]="PowerRestore",s[s.RadarOnOff=35]="RadarOnOff",s[s.ObjectOwnerChange=36]="ObjectOwnerChange",s[s.RadarEvent=37]="RadarEvent",s[s.InsufficientFunds=38]="InsufficientFunds",s[s.RallyPointChange=39]="RallyPointChange",s[s.PrimaryFactoryChange=40]="PrimaryFactoryChange",s[s.FactoryProduceUnit=41]="FactoryProduceUnit",s[s.ObjectTeleport=42]="ObjectTeleport",s[s.AllianceChange=43]="AllianceChange",s[s.UnitPromote=44]="UnitPromote",s[s.EnterTransport=45]="EnterTransport",s[s.LeaveTransport=46]="LeaveTransport",s[s.SuperWeaponReady=47]="SuperWeaponReady",s[s.SuperWeaponActivate=48]="SuperWeaponActivate",s[s.LightningStormManifest=49]="LightningStormManifest",s[s.LightningStormCloud=50]="LightningStormCloud",s[s.CratePickup=51]="CratePickup",s[s.PingLocation=52]="PingLocation",s[s.StalemateDetect=53]="StalemateDetect";class Nr{constructor(e,t){this.target=e,this.player=t,this.type=vr.BuildingEvacuate}}(s=Sr=Sr||{})[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Finished=2]="Finished",s[s.Cancelling=3]="Cancelling",s[s.Cancelled=4]="Cancelled";class Rr{constructor(){this.status=Sr.NotStarted,this.children=[],this.cancellable=!0,this.useChildTargetLines=!1,this.blocking=!0,this.waitingForChildrenToFinish=!1,this.preventOpportunityFire=!0,this.preventLanding=!0}isRunning(){return this.status===Sr.Running}isCancelling(){return this.status===Sr.Cancelling}setCancellable(e){return this.cancellable=e,this}onStart(e){}onEnd(e){}cancel(){if(this.cancellable)if(this.status===Sr.Running)this.status=Sr.Cancelling,this.children.length&&this.children.forEach(e=>e.cancel());else if(this.status===Sr.NotStarted&&(this.status=Sr.Cancelled,this.children.length))throw new Error("Should't have any children before starting a task")}getTargetLinesConfig(e){}}function Mr(e){return[Yt.Water,Yt.Beach].includes(e)?_r.Water:_r.Ground}(s=_r=_r||{})[s.Ground=0]="Ground",s[s.Air=1]="Air",s[s.Water=2]="Water",(s=kr=kr||{})[s.None=0]="None",s[s.Guard=1]="Guard",s[s.Prone=2]="Prone",s[s.Deployed=3]="Deployed",s[s.Paradrop=4]="Paradrop",s[s.Cheer=5]="Cheer",(Or=Or||{}).onTick=Symbol();class Dr{constructor(e,t,i){this.target=e,this.isChronoshift=t,this.prevTile=i,this.type=vr.ObjectTeleport}}(s=Ir=Ir||{})[s.None=0]="None",s[s.Normal=1]="Normal",s[s.Demolish=2]="Demolish",s[s.Crush=3]="Crush",s[s.Temporal=4]="Temporal",s[s.Sink=5]="Sink",(Cr=Cr||{}).onBeforeTeleport=Symbol();var Lr=__webpack_require__(949);function Fr(e,t){var i=e.center;return Math.pow(i.x-t.x,2)+Math.pow(i.y-t.y,2)<=Math.pow(e.radius,2)}function jr(e,t){let i=new Lr.Box2(new Lr.Vector2(e.x,e.y),new Lr.Vector2(e.x+e.width,e.y+e.height));return i.containsPoint(new Lr.Vector2(t.x,t.y))}function Ur(e,t){var i=Lr.Math.degToRad(Math.floor(t)),t=z(Math.cos(i),10),i=z(Math.sin(i),10);return e.set(e.x*t-e.y*i,e.x*i+e.y*t)}function Wr(e){let t=Lr.Math.radToDeg(e.angle());return Math.abs(Math.abs(t)-Math.floor(Math.abs(t))-.5)<.01&&(t+=.01),Math.round(t)}function Vr(e,t){t=2*Math.acos(Math.abs(Lr.Math.clamp(e.dot(t),-1,1)));let i=Lr.Math.radToDeg(t);return Math.abs(Math.abs(i)-Math.floor(Math.abs(i))-.5)<.01&&(i+=.01),Math.round(i)}function zr(e,t){e=Wr(e),t=Wr(t);return Math.min((e-t+360)%360,(t-e+360)%360)}function Hr(e,t){return Vr(Gr(e),Gr(t))}function Gr(e){return(new Lr.Quaternion).setFromRotationMatrix((new Lr.Matrix4).lookAt(e,new Lr.Vector3(0,0,0),new Lr.Vector3(0,1,0)))}function $r(e,t,i){var r,s=e.length(),a=Gr(t),n=Gr(e);r=i,0!==(a=Vr(t=n,i=a))&&(a=Math.min(1,r/a),function(e,t,i){if(0===i)return;if(1===i)return e.copy(t);var r=e.x,s=e.y,a=e.z,n=e.w;let o=n*t.w+r*t.x+s*t.y+a*t.z;o<0?(e.w=-t.w,e.x=-t.x,e.y=-t.y,e.z=-t.z,o=-o):e.copy(t);if(1<=o)return e.w=n,e.x=r,e.y=s,e.z=a;var h=1-o*o;if(h<=Number.EPSILON){var l=1-i;return e.w=l*n+i*e.w,e.x=l*r+i*e.x,e.y=l*s+i*e.y,e.z=l*a+i*e.z,e.normalize(),e.onChangeCallback()}t=Math.sqrt(h),l=z(Math.atan2(t,o),10),h=z(Math.sin((1-i)*l),10)/t,t=z(Math.sin(i*l),10)/t;e.w=n*h+e.w*t,e.x=r*h+e.x*t,e.y=s*h+e.y*t,e.z=a*h+e.z*t,e.onChangeCallback()}(t,i,a)),e.set(0,0,1).applyQuaternion(n).setLength(s)}var qr=__webpack_require__(949);class Zr{static tick(e,t,i){if(e===t)return{facing:e,delta:0};var r=(e-t+360)%360,s=(t-e+360)%360;if(Math.min(r,s)<i)return{facing:t,delta:0};i*=s<=r?1:-1;return{facing:(e+i+360)%360,delta:i}}static fromMapCoords(e){return(-Wr(e)-90+720)%360}static toMapCoords(e){return Ur(new qr.Vector2(10,0),Zr.toWorldDeg(e)).normalize()}static toWorldDeg(e){return-(e+90)}}var Qr=__webpack_require__(949);class Xr{static computeInterceptPoint(e,t,i,r){let s=e.clone().sub(i);var a=r.length(),e=t*t-a*a,t=2*s.dot(r),a=-s.dot(s);if(t*t-4*e*a<0)return new Qr.Vector3;e=(-t+Math.sqrt(t*t-4*e*a))/(2*e);return r.clone().multiplyScalar(e).add(i)}static computeTurnCircle(e,t,i,r){r/=Qr.Math.degToRad(Math.abs(i));let s=Ur(t.clone(),90*-Math.sign(i));return{center:isFinite(r)?s.setLength(r).add(e):e.clone(),radius:r}}}class Yr{constructor(e){this.gameObject=e,this.type=vr.ObjectLiftOff}}class Kr{constructor(e){this.gameObject=e,this.type=vr.ObjectLand}}var Jr=__webpack_require__(949);class es{constructor(e){this.game=e,this.currentMoveDir=new Jr.Vector2,this.currentHorizSpeed=0}static tickStationary(t,i){if(t.zone===_r.Air){var r=t.tile.onBridgeLandType?i.map.tileOccupation.getBridgeOnTile(t.tile):void 0,s=!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)!==_r.Water&&0<i.map.terrain.getPassableSpeed(t.tile,Kt.Foot,!!t.tile.onBridgeLandType)&&0===i.map.terrain.findObstacles({tile:t.tile,onBridge:r},t).length);let e;e=s?(a=t.tile.z+(r?.tileElevation??0),mr.worldToLeptons(mr.tileHeightToWorld(a))):(n=t.tile.z+i.map.getGroundObjectsOnTile(t.tile).filter(e=>!(e.isInfantry()&&e.stance===kr.Paradrop)).reduce((e,t)=>Math.max(e,t.tileElevation+t.art.height),0),mr.worldToLeptons(mr.tileHeightToWorld(n))+t.rules.jumpjetHeight);var a,n,o=mr.worldToLeptons(t.position.worldPosition.y);e!==o?(a=t.rules.jumpjetClimb,n=Math.abs(e-o),n=Math.sign(e-o)*Math.min(a,n),t.position.moveByLeptons3(new Jr.Vector3(0,n,0))):s&&(t.zone=_r.Ground,t.onBridge=!!r,i.events.dispatch(new Kr(t)))}}static tickCrash(e,t,i){var r=2*e.rules.jumpjetCrash;return e.direction=(e.direction-6+360)%360,new Jr.Vector3(0,-r,0)}onNewWaypoint(e,t,i){this.currentMoveDir=Zr.toMapCoords(e.direction)}tick(e,t,i,r){e.zone!==_r.Air&&(e.onBridge=!1,e.zone=_r.Air,this.game.events.dispatch(new Yr(e))),r&&(i=this.computeCancelDest(e.tile,i));var s=e.position.getMapPosition();let a=i.clone().sub(s),n=this.findTilesToCheckForBlockers(e.tile,s,this.currentMoveDir,a.length());var o=n.map(e=>e.z+this.game.map.getGroundObjectsOnTile(e).filter(e=>!(e.isDestroyed||e.isInfantry()&&e.stance===kr.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=mr.worldToLeptons(mr.tileHeightToWorld(o)),c=mr.worldToLeptons(mr.tileHeightToWorld(o+h)),u=mr.worldToLeptons(e.position.worldPosition.y),d=Zr.fromMapCoords(a),p=a.length()<e.rules.jumpjetSpeed;let g=0;l<=u&&!p&&({facing:T,delta:r}=Zr.tick(e.direction,d,e.rules.jumpjetTurnRate),g=r,e.direction=T,this.currentMoveDir.copy(Zr.toMapCoords(e.direction))),e.isVehicle()&&(e.spinVelocity=g);let m,f=!1,y=0,w=0;var T=e.rules.jumpjetClimb;u<c?(y=Math.min(T,c-u),m=!1,this.currentHorizSpeed=0):(this.lastClearZ=o,o=l+e.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,e.rules.jumpjetSpeed),f=d===e.direction?(w=Math.min(T,a.length()),T>=a.length()):((s=T||g?Xr.computeTurnCircle(s,this.currentMoveDir,Math.sign(g)*e.rules.jumpjetTurnRate,T):void 0)&&Fr(s,i)?(w=0,this.currentHorizSpeed=0):w=T,!1));let b;b=p?(f=!0,a):this.currentMoveDir.clone().setLength(w);let v=new Jr.Vector3(b.x,y,b.y);p=mr.vecLeptonsToWorld(v).add(e.position.worldPosition);this.game.map.isWithinHardBounds(p)||(v.x=v.z=0);p=v.clone();return e.moveTrait.velocity.copy(p).multiplyScalar(mr.ISO_TILE_SIZE/mr.LEPTONS_PER_TILE),{distance:v,done:f&&m}}findTilesToCheckForBlockers(e,t,i,r){r=i.clone().setLength(Math.min(r,mr.LEPTONS_PER_TILE)).add(t).multiplyScalar(1/mr.LEPTONS_PER_TILE).floor(),t=this.game.map.tiles.getByMapCoords(r.x,r.y);if(!t||t===e)return[e];r=Math.sign(t.rx-e.rx),t=Math.sign(t.ry-e.ry);let s=[e],a;return r&&(a=this.game.map.tiles.getByMapCoords(e.rx+r,e.ry),a&&s.push(a)),t&&(a=this.game.map.tiles.getByMapCoords(e.rx,e.ry+t),a&&s.push(a)),r&&t&&(a=this.game.map.tiles.getByMapCoords(e.rx+r,e.ry+t),a&&s.push(a)),s}computeCancelDest(e,t){var i=t.clone().multiplyScalar(1/mr.LEPTONS_PER_TILE).floor().multiplyScalar(mr.LEPTONS_PER_TILE),i=t.clone().sub(i);return new Jr.Vector2(e.rx,e.ry).multiplyScalar(mr.LEPTONS_PER_TILE).add(i)}}class ts extends Rr{constructor(e){super(),this.ticks=e}onTick(){return!!this.isCancelling()||!(0<this.ticks--)}}class is{static computeGameSpeed(e){let t;return t=6===e?60:5===e?45:60/(6-e),t/is.BASE_TICKS_PER_SECOND}}is.BASE_TICKS_PER_SECOND=15;class rs extends ts{constructor(e){super(Math.floor(is.BASE_TICKS_PER_SECOND*e*60))}}class ss extends Rr{constructor(e){super(),this.cb=e}onTick(e){return this.cb(e),!0}}var as,ns=__webpack_require__(949);(s=as=as||{})[s.Idle=0]="Idle",s[s.MoveToQueueingTile=1]="MoveToQueueingTile",s[s.WaitForTurn=2]="WaitForTurn",s[s.MoveToDock=3]="MoveToDock",s[s.Docking=4]="Docking",s[s.Docked=5]="Docked";class os extends Rr{constructor(e,t){super(),this.game=e,this.target=t,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.dockingStatus=as.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=as.MoveToDock:void 0!==(t=this.target.dockTrait.getFirstAvailableDockNumber())?(this.target.dockTrait.reserveDockAt(e,t),this.dockingStatus=as.MoveToDock):this.target.helipadTrait?this.cancel():this.dockingStatus=as.MoveToQueueingTile}onEnd(e){this.dockingStatus!==as.Docked&&this.target.isSpawned&&(this.target.dockTrait.undockUnit(e),this.target.dockTrait.unreserveDockForUnit(e)),this.dockingStatus=as.Idle}onTick(e){if(this.isCancelling())return!0;if(!this.isValidTarget(this.target,e))return!0;if(this.dockingStatus===as.MoveToQueueingTile){var t=this.findReachableQueueingTile(e);if(!t)return!0;if(e.tile!==t)return this.children.push(new ca(this.game,t,!1,{closeEnoughTiles:5}),new ss(()=>{e.moveTrait.lastMoveResult===gs.Fail?this.cancel():e.moveTrait.lastMoveResult===gs.CloseEnough&&(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)||(this.dockingStatus=as.WaitForTurn))})),!1;this.dockingStatus=as.WaitForTurn}if(this.dockingStatus===as.WaitForTurn){t=this.target.dockTrait.getFirstAvailableDockNumber();if(void 0===t)return this.children.push(new rs(1/60)),!1;this.target.dockTrait.reserveDockAt(e,t),this.dockingStatus=as.MoveToDock}if(this.dockingStatus===as.MoveToDock){var i=this.target.dockTrait.getDockTile(this.target.dockTrait.getReservedDockForUnit(e));if(e.tile!==i)return this.children.push(new ca(this.game,i,!1,{closeEnoughTiles:0,strictCloseEnough:!0}),new ss(()=>{e.moveTrait.lastMoveResult===gs.Fail&&this.cancel()})),this.game.afterTick(()=>e.unitOrderTrait[Or.onTick](e,this.game)),!1;this.dockingStatus=as.Docking}if(this.dockingStatus!==as.Docking)return!1;i=this.target.dockTrait.getReservedDockForUnit(e);return this.target.dockTrait.unreserveDockForUnit(e),this.target.dockTrait.dockUnitAt(e,i),e.isAircraft()&&e.airportBoundTrait&&this.target.helipadTrait&&(e.airportBoundTrait.preferredAirport=this.target),this.dockingStatus=as.Docked,!0}isValidTarget(e,t){return e.isSpawned&&this.game.areFriendly(e,t)}findReachableQueueingTile(t){var e=this.target.getFoundation(),e=new ns.Vector2(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 xr(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===ii.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)}}var hs,ls,cs,us=__webpack_require__(949);(s=hs=hs||{})[s.None=0]="None",s[s.CircleStrafe=1]="CircleStrafe",s[s.HoverStrafe=2]="HoverStrafe";class ds{constructor(e){this.game=e,this.lastDestLeptons=new us.Vector2,this.currentMoveDir=new us.Vector2,this.currentHorizSpeed=0,this.maneuverType=hs.None,this.deceleratingToTurn=!1}static tickStationary(s,a){if(s.zone===_r.Air){var n=s.tile.onBridgeLandType?a.map.tileOccupation.getBridgeOnTile(s.tile):void 0;let e=s.rules.landable&&!s.unitOrderTrait.getCurrentTask()?.preventLanding,i=s.spawnLinkTrait?.getParent();e&&i?e=!((!i.isUnit()||!i.onBridge)&&n||i.tile!==s.tile):e&&!s.airportBoundTrait&&(e=a.map.getTileZone(s.tile)!==_r.Water&&0<a.map.terrain.getPassableSpeed(s.tile,Kt.Foot,!!s.tile.onBridgeLandType)&&0===a.map.terrain.findObstacles({tile:s.tile,onBridge:n},s).length);let r;if(e){let e=s.airportBoundTrait?.preferredAirport?.dockTrait;var o=e?.isDocked(s)||e?.hasReservedDockForUnit(s);if(!s.airportBoundTrait||o){var h=o?0:270;if(s.direction!==h)return void(s.direction=Zr.tick(s.direction,h,s.rules.rot).facing)}if(s.airportBoundTrait){let e=s.airportBoundTrait.preferredAirport;if(!e?.dockTrait?.isDocked(s))return e?.dockTrait?.getAvailableDockCount()||(e=s.airportBoundTrait.findAvailableAirport(s),s.airportBoundTrait.preferredAirport=e,e&&(h=e.dockTrait.getFirstAvailableDockNumber(),e.dockTrait.reserveDockAt(s,h))),void(e?(s.unitOrderTrait.addTask(new os(a,e)),s.unitOrderTrait[Or.onTick](s,a)):s.crashableTrait.crash(void 0))}let t;t=i?i.tile.z+i.tileElevation:s.tile.z+(n?.tileElevation??0),r=mr.worldToLeptons(mr.tileHeightToWorld(t))}else{var t=s.tile.z+(n?.tileElevation??0),l=s.rules.flightLevel??a.rules.general.flightLevel;r=mr.worldToLeptons(mr.tileHeightToWorld(t))+l}t=mr.worldToLeptons(s.position.worldPosition.y);r!==t?(l=Math.abs(r-t),l=Math.sign(r-t)*Math.min(30,l),s.position.moveByLeptons3(new us.Vector3(0,l,0))):e&&(s.zone=_r.Ground,i?i.airSpawnTrait.storeAircraft(s,a):s.onBridge=!!n,a.events.dispatch(new Kr(s)))}}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=mr.vecWorldToGround(mr.vecWorldToLeptons(e.moveTrait.velocity));return new us.Vector3(e.x,-30,e.y)}onNewWaypoint(e,t,i){this.currentHorizSpeed=mr.worldToLeptons(mr.vecWorldToGround(e.moveTrait.velocity).length())}tick(t,e,i,r){r&&(i=this.computeCancelDest(t.tile,i));var s=t.position.getMapPosition();let a=i.clone().sub(s);var n=a.length();this.lastDestLeptons.equals(i)||(this.lastDestLeptons.copy(i),r?this.maneuverType=hs.HoverStrafe:t.zone===_r.Air&&this.currentHorizSpeed<5?this.maneuverType=n>mr.LEPTONS_PER_TILE?hs.CircleStrafe:hs.HoverStrafe:this.maneuverType=hs.None,this.deceleratingToTurn=!1),t.zone!==_r.Air&&(t.onBridge=!1,t.zone=_r.Air,this.game.events.dispatch(new Yr(t)));var o=this.game.map.tileOccupation.getBridgeOnTile(t.tile),h=t.tile.z+(o?.tileElevation??0),l=t.rules.flightLevel??this.game.rules.general.flightLevel,r=mr.worldToLeptons(mr.tileHeightToWorld(h))+l,o=mr.worldToLeptons(t.position.worldPosition.y),c=Zr.fromMapCoords(a);t.direction===c&&this.maneuverType===hs.None&&n<=mr.LEPTONS_PER_TILE?this.maneuverType=hs.HoverStrafe:t.direction===c&&this.maneuverType===hs.CircleStrafe&&(this.maneuverType=hs.None);let u;switch(this.maneuverType){case hs.HoverStrafe:if(t.attackTrait?.currentTarget){let e=mr.vecWorldToGround(mr.vecWorldToLeptons(t.attackTrait.currentTarget.getWorldCoords()));u=Zr.fromMapCoords(e.sub(s))}else u=t.airportBoundTrait?.preferredAirport?.dockTrait?.hasReservedDockForUnit(t)?0:270;break;case hs.CircleStrafe:case hs.None:u=c;break;default:throw new Error(`Unknown maneuver type "${this.maneuverType}`)}var{facing:d,delta:p}=Zr.tick(t.direction,u,t.rules.rot);t.direction=d,t.roll=Math.sign(p)*t.rules.pitchAngle;let g;switch(this.maneuverType){case hs.HoverStrafe:g=c;break;case hs.CircleStrafe:g=(d-90*Math.sign(p)+360)%360;break;case hs.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}=Zr.tick(this.thrustFacing,g,h);this.thrustFacing=l,this.currentMoveDir.copy(Zr.toMapCoords(this.thrustFacing));let m=!1,f=0,y=0;let w=!0;r!==o&&(b=Math.abs(r-o),f=Math.sign(r-o)*Math.min(30,b),w=b<=30);let T=t.rules.speed*Xi.MAGIC_SPEED_MULT;n<=mr.LEPTONS_PER_TILE&&this.maneuverType!==hs.CircleStrafe&&(T=us.Math.lerp(1,T/2,Math.sqrt(n/mr.LEPTONS_PER_TILE))),this.deceleratingToTurn?this.currentHorizSpeed=Math.max(0,this.currentHorizSpeed-2):this.currentHorizSpeed=Math.min(this.currentHorizSpeed+2,T),this.lookAhead(s,this.currentMoveDir,n)||(this.currentHorizSpeed=0);var b=this.currentHorizSpeed;this.deceleratingToTurn=!1,m=h?(h=b||h?Xr.computeTurnCircle(s,this.currentMoveDir,Math.sign(h)*t.rules.rot,b):void 0,(0===b||Fr(h,i))&&(this.maneuverType===hs.HoverStrafe||n>mr.LEPTONS_PER_TILE)&&(this.deceleratingToTurn=!0),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 us.Vector3(v.x,f,v.y);n=mr.vecLeptonsToWorld(S).add(t.position.worldPosition);this.game.map.isWithinHardBounds(n)||(this.game.map.isWithinHardBounds(mr.vecLeptonsToWorld(i))||(m=w=!0),S.x=S.z=0);i=S.clone();return t.moveTrait.velocity.copy(i).multiplyScalar(mr.ISO_TILE_SIZE/mr.LEPTONS_PER_TILE),{distance:S,done:m&&w}}computeCancelDest(e,t){var i=t.clone().multiplyScalar(1/mr.LEPTONS_PER_TILE).floor().multiplyScalar(mr.LEPTONS_PER_TILE),i=t.clone().sub(i);return new us.Vector2(e.rx,e.ry).multiplyScalar(mr.LEPTONS_PER_TILE).add(i)}lookAhead(e,t,i){e=t.clone().setLength(Math.min(i,mr.LEPTONS_PER_TILE)).add(e).multiplyScalar(1/mr.LEPTONS_PER_TILE).floor();return this.game.map.tiles.getByMapCoords(e.x,e.y)}}(ls=ls||{}).onTileChange=Symbol(),(cs=cs||{}).onTileChange=Symbol();var ps,gs,ms,fs,ys,ws,Ts,bs,vs,Ss=__webpack_require__(949);(s=ps=ps||{})[s.Idle=0]="Idle",s[s.ReachedNextWaypoint=1]="ReachedNextWaypoint",s[s.PlanMove=2]="PlanMove",s[s.Moving=3]="Moving",(s=gs=gs||{})[s.Success=0]="Success",s[s.Cancel=1]="Cancel",s[s.CloseEnough=2]="CloseEnough",s[s.Fail=3]="Fail",(s=ms=ms||{})[s.Waiting=0]="Waiting",s[s.Resolved=1]="Resolved";const _s=e=>e instanceof ca||e.children[0]&&_s(e.children[0]);class ks{constructor(e,t){this.gameObject=e,this.tileOccupation=t,this.disabled=!1,this.speedPenalty=0,this.velocity=new Ss.Vector3,this.reservedPathNodes=[],this.moveState=ps.Idle,this.collisionState=ms.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!==ti.Hover?.75:1)*(1-this.speedPenalty)}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}isMoving(){return this.moveState===ps.Moving}isIdle(){return this.moveState===ps.Idle}isWaiting(){return this.collisionState===ms.Waiting}[Or.onTick](e,t){var i;this.moveState!==ps.Idle&&this.collisionState===ms.Resolved&&((i=e.unitOrderTrait.getCurrentTask())&&_s(i)||(this.velocity.set(0,0,0),this.moveState=ps.Idle,this.locomotor=void 0,!i&&!e.attackTrait?.currentTarget&&e.isVehicle()&&e.turretTrait&&(e.turretTrait.desiredFacing=e.direction))),this.moveState===ps.Idle&&(e.rules.locomotor===ti.Jumpjet?es.tickStationary(e,t):e.isAircraft()&&e.rules.locomotor===ti.Aircraft&&ds.tickStationary(e,t))}[Tr.onDestroy](e,t){this.unreservePathNodes()}teleportUnitToTile(e,t,i,r,s){let a=this.gameObject;var n=a.tile;a.traits.filter(Cr).forEach(e=>{e[Cr.onBeforeTeleport](a,s,i,r)}),a.position.tileElevation=a.tileElevation,a.position.tile=e,a.position.subCell=a.position.desiredSubCell,this.handleTileChange(n,t,!0,s,!0),r||(this.unreservePathNodes(),this.speedPenalty=0,this.velocity.set(0,0,0),this.moveState=ps.Idle,this.collisionState=ms.Resolved,this.locomotor=void 0,this.currentWaypoint=void 0,this.lastTargetOffset=void 0,this.lastVelocity=void 0,this.lastMoveResult=gs.Cancel,a.isVehicle()&&(a.spinVelocity=0,a.turretTrait&&(a.turretTrait.desiredFacing=a.direction))),this.lastTeleportTick=s.currentTick,s.events.dispatch(new Dr(a,i,n))}handleTileChange(t,e,i,r,s=!1){const a=this.gameObject;if(r.map.tileOccupation.unoccupyTileRange(t,a),r.map.tileOccupation.occupyTileRange(a.tile,a),r.map.technosByTile.updateObject(a),a.zone!==_r.Air){var n=a.onBridge?r.map.tileOccupation.getBridgeOnTile(t):void 0,o=a.onBridge?t.onBridgeLandType:t.landType,h=e?a.tile.onBridgeLandType:a.tile.landType;o!==h&&(0<r.rules.getLandRules(h).getSpeedModifier(a.rules.speedType)||a.rules.speedType===Kt.Amphibious||s)&&(a.zone=Mr(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.rules.crusher)for(l of r.map.getGroundObjectsOnTile(a.tile).filter(e=>(!e.isUnit()||e.onBridge===a.onBridge)&&e.rules.crushable&&!(e.isInfantry()&&e.stance===kr.Paradrop)&&(!(e.isTechno()&&!i)||!r.areFriendly(e,a))))l.isDestroyed||(l.isInfantry()&&(l.infDeathType=Jt.None),a.isVehicle()&&l.isOverlay()&&l.rules.wall&&a.applyRocking(0,.5),l.deathType=Ir.Crush,r.destroyObject(l,{player:a.owner,obj:a}));!r.crateGeneratorTrait||a.onBridge||(e=r.map.tileOccupation.getGroundObjectsOnTile(a.tile).find(e=>e.isOverlay()&&e.rules.crate))&&r.crateGeneratorTrait.pickupCrate(a,e,r)}r.traits.filter(ls).forEach(e=>{e[ls.onTileChange](a,r,t,s)}),a.traits.filter(cs).forEach(e=>{e[cs.onTileChange](a,r,t,s)})}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 Os{constructor(){this.suppressionTicks=0}isSuppressed(){return 0<this.suppressionTicks}supress(){this.suppressionTicks=30}[Or.onTick](){0<this.suppressionTicks&&this.suppressionTicks--}}class Is{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()}}(fs=fs||{}).onChange=Symbol(),(ys=ys||{}).onSpawn=Symbol(),(ws=ws||{}).onUnspawn=Symbol(),(Ts=Ts||{}).onAttack=Symbol();class Cs{constructor(e,t,i,r){this.traits=new Is,this.cachedTraits={tick:[]},this.isCrashing=!1,this.isDestroyed=!1,this.deathType=Ir.Normal,this.isDisposed=!1,this.isSpawned=!1,this.type=e,this.name=t,this.rules=i,this.art=r}get tile(){return this.position.tile}get tileElevation(){return this.position.tileElevation}getFoundation(){return{width:1,height:1}}isSmudge(){return this.type===At.Smudge}isOverlay(){return this.type===At.Overlay}isTerrain(){return this.type===At.Terrain}isProjectile(){return this.type===At.Projectile}isDebris(){return this.type===At.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[Or.onTick](this,e)}onSpawn(t){this.isSpawned=!0,this.traits.filter(ys).forEach(e=>{e[ys.onSpawn](this,t)})}onUnspawn(t){this.isSpawned=!1,this.traits.filter(ws).forEach(e=>{e[ws.onUnspawn](this,t)})}onDestroy(t,i,r){this.traits.filter(Tr).forEach(e=>{e[Tr.onDestroy](this,t,i,r)})}onOwnerChange(t,i){this.traits.filter(fs).forEach(e=>{e[fs.onChange](this,t,i)})}onAttack(t,i){this.traits.filter(Ts).forEach(e=>{e[Ts.onAttack](this,i,t)})}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}}(s=bs=bs||{})[s.None=0]="None",s[s.Veteran=1]="Veteran",s[s.Elite=2]="Elite";class As extends Cs{constructor(e,t,i,r){super(e,t,i,r),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(Xi.MAX_SIGHT,this.rules.sight*(this.veteranTrait?.getVeteranSightMultiplier()??1))}get veteranLevel(){return this.veteranTrait?.veteranLevel??bs.None}resetGuardModeToIdle(){this.guardMode=this.rules.defaultToGuardArea,this.guardArea=void 0}update(e){if(this.warpedOutTrait.isActive())for(var t of this.cachedTraits.tick)t.ticksWhenWarpedOut&&t[Or.onTick](this,e);else super.update(e)}isTechno(){return!0}}class Bs{constructor(){this.cooldownTicks=Number.POSITIVE_INFINITY,this._actionDueThisTick=!1}[Or.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 da(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*is.BASE_TICKS_PER_SECOND)}}class Es{constructor(e){this.gameObject=e,this.type=vr.ObjectCrashing}}(vs=vs||{}).onCrash=Symbol();class Ps{constructor(e){this.gameObject=e,this.crashingEvtSent=!1,this.crashState={}}[Or.onTick](i,r){if(i.isCrashing){if(this.crashingEvtSent||(this.crashingEvtSent=!0,i.traits.filter(vs).forEach(e=>e[vs.onCrash](i,r)),r.events.dispatch(new Es(i))),i.rules.locomotor!==ti.Jumpjet&&i.rules.locomotor!==ti.Aircraft)throw new Error(`Crashing logic not implemented for locomotor ${ti[i.rules.locomotor]}`);{let e;if(i.rules.locomotor===ti.Jumpjet)e=es.tickCrash(i,r,this.crashState);else{if(i.rules.locomotor!==ti.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=ds.tickCrash(i,r,this.crashState)}let t=!1;var s,a=mr.vecLeptonsToWorld(e).add(i.position.worldPosition);r.map.isWithinHardBounds(a)?(s=i.tile,i.position.moveByLeptons3(e),i.tile!==s&&i.moveTrait.handleTileChange(s,void 0,!1,r),s=(a=i.tile.onBridgeLandType?r.map.tileOccupation.getBridgeOnTile(i.tile):void 0)?.tileElevation??0,i.position.tileElevation=Math.max(i.position.tileElevation,s),i.position.tileElevation===s&&(i.zone=r.map.getTileZone(i.tile),i.onBridge=!!a,t=!0)):t=!0,t&&r.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 xs{infiltrate(e,t,i){var r;t.rules.radar&&![...t.owner.buildings].some(e=>e.rules.spySat)&&i.mapShroudTrait.resetShroud(t.owner,i),0<t.rules.power&&(r=i.rules.general.spyPowerBlackout,t.owner.powerTrait?.setBlackoutFor(r,i)),t.superWeaponTrait&&t.superWeaponTrait.getSuperWeapon(t)?.resetTimer(),0<t.rules.storage&&(r=W(i.rules.general.spyMoneyStealPercent,0,1),r=Math.floor(t.owner.credits*r),t.owner.credits-=r,e.owner.credits+=r),!i.rules.ai.buildTech.includes(t.name)||void 0!==(i=t.rules.aiBasePlanningSide)&&e.owner.production.addStolenTech(i),[Gi.InfantryType,Gi.UnitType].includes(t.factoryTrait?.type)&&e.owner.production?.addVeteranType(t.factoryTrait.type)}}class Ns{constructor(){this.firepower=1,this.armor=1,this.speed=1}}class Rs extends As{constructor(e,t,i){super(At.Infantry,e,t,i),this.direction=0,this.onBridge=!1,this.zone=_r.Ground,this._stance=kr.None,this.isFiring=!1,this.isPanicked=!1,this.infDeathType=Jt.Gunfire,this.crateBonuses=new Ns}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,r){let s=new this(e,t,i);return s.moveTrait=new ks(s,r),s.traits.add(s.moveTrait),s.rules.crashable&&(s.crashableTrait=new Ps(s),s.traits.add(s.crashableTrait)),s.rules.proneWhenAttacked&&(s.suppressionTrait=new Os,s.traits.add(s.suppressionTrait)),s.rules.agent&&(s.agentTrait=new xs,s.traits.add(s.agentTrait)),s.idleActionTrait=new Bs,s.traits.add(s.idleActionTrait),s}get stance(){return this._stance===kr.None&&this.suppressionTrait?.isSuppressed()?kr.Prone:this._stance}set stance(e){this._stance=e,this.moveTrait.setDisabled([kr.Deployed,kr.Cheer].includes(e)),this.attackTrait?.setDisabled([kr.Paradrop,kr.Cheer].includes(e))}isUnit(){return!0}isInfantry(){return!0}}function Ms(t,i){for(let e=t.length-1;0<=e;e--)if(i(t[e],e,t))return e;return-1}Rs.SUB_CELLS=[2,4,3];class Ds{constructor(e){this.map=e}findPositions(e,r,s){let a=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 n=[],o=this.findCenterTile([...i.objects]);i.objects.forEach(t=>{var i=this.map.tiles.getByMapCoords(r.rx+t.tile.rx-o.rx,r.ry+t.tile.ry-o.ry),e=i?.onBridgeLandType?this.map.tileOccupation.getBridgeOnTile(i):void 0;if(!i||!this.map.mapBounds.isWithinBounds(i)||a.has(i)&&!this.tileHasRoom(t,a.get(i))||t.rules.movementZone===ii.Fly&&!t.rules.balloonHover&&!this.map.terrain.getPassableSpeed(i,Kt.Amphibious,!!e)||t.rules.movementZone!==ii.Fly&&!this.isEligibleTile(i,e,s,r))n.push(t);else{let e=a.get(i);void 0===e&&(e=[],a.set(i,e)),e.push(t)}}),t.forEach(e=>n.push(...e.objects));let h=new xr(this.map.tiles,this.map.mapBounds,r,{width:1,height:1},1,5,()=>!0),l;for(;n.length&&(l=h.getNextTile());){var c=n[0],u=this.map.tileOccupation.getBridgeOnTile(l);if((!a.has(l)||this.tileHasRoom(c,a.get(l)))&&((c.rules.movementZone!==ii.Fly||c.rules.balloonHover||this.map.terrain.getPassableSpeed(l,Kt.Amphibious,!!u))&&(c.rules.movementZone===ii.Fly||this.isEligibleTile(l,u,s,r)))){let e=a.get(l);void 0===e&&(e=[],a.set(l,e)),e.push(n.shift())}}let d=new Map;if(a.forEach((e,t)=>{e.forEach(e=>d.set(e,t))}),n.forEach(e=>d.set(e,r)),d.size!==e.length)throw new Error("We should have computed a number of positions equal to the number of input objects");return d}tileHasRoom(e,t){if(e.isInfantry()){if(t.find(e=>!e.isInfantry()))return!1;e=e.rules.movementZone===ii.Fly?1:3;return t.filter(e=>e.isInfantry()).length>=e?!1:!0}return!t.length}isEligibleTile(e,t,i,r){return i?.isHighBridge()||t?.isHighBridge()?e.z+(t?.tileElevation??0)===r.z+(i?.tileElevation??0):!(!i&&!t)||Math.abs(e.z-r.z)<2}clusterObjects(e){let s=new Map;e.forEach(e=>{var t=e.tile.rx+"_"+e.tile.ry;s.set(t,[...s.get(t)||[],e])});let t=[],a=new Set(e);for(;a.size;){let e=new Set,r=[];var i=[...a][0].tile;for(s.get(i.rx+"_"+i.ry).forEach(e=>{r.push(e)});r.length;){var n=r.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=s.get(n.tile.rx+i+"_"+(n.tile.ry+t));e&&e.length&&e.forEach(e=>{a.has(e)&&(a.delete(e),r.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 r=this.map.tiles.getByMapCoords(t,i);if(!r&&(r=e.find(e=>Math.abs(e.tile.rx-t)<=1&&Math.abs(e.tile.ry-i)<=1)?.tile,!r))throw new Error("At least one adjacent object should have been found");return r}}class Ls extends Rr{constructor(e,t){super(),this.game=e,this.fromDirection=t,this.resolved=!1,this.chainPushIssued=!1}onEnd(e){e.moveTrait.collisionState=ms.Resolved}onTick(i){if(this.timeoutTicks=void 0===this.timeoutTicks?0:this.timeoutTicks+1,40<this.timeoutTicks||this.resolved||this.isCancelling())return!0;let r=this.game.map,t=new Ds(r),s=i.onBridge?r.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=Ur(this.fromDirection.clone(),e).round(),o=r.tiles.getByMapCoords(i.tile.rx+Math.sign(o.x),i.tile.ry+Math.sign(o.y));if(o&&r.mapBounds.isWithinBounds(o)&&(n=!s||s.isHighBridge()?r.tileOccupation.getBridgeOnTile(o):void 0,i.rules.movementZone===ii.Fly||!r.terrain.findObstacles({tile:o,onBridge:n},i).length&&t.isEligibleTile(o,n,s,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 ca(this.game,a,!!n,{closeEnoughTiles:0,strictCloseEnough:!0})),!1);{if(this.chainPushIssued)return this.children.push(new ts(5)),!1;let t=r.tiles.getByMapCoords(i.tile.rx+Math.sign(this.fromDirection.x),i.tile.ry+Math.sign(this.fromDirection.y));if(!t||!r.mapBounds.isWithinBounds(t))return!0;n=!s||s.isHighBridge()?r.tileOccupation.getBridgeOnTile(t):void 0;let e=r.tileOccupation.getGroundObjectsOnTile(t).filter(e=>e.isUnit()&&e.owner===i.owner&&e.tile===t&&e.onBridge===!!n&&!(e.isInfantry()&&e.stance===kr.Paradrop)&&!(e.isAircraft()&&e.missileSpawnTrait));return e.find(e=>e.moveTrait.collisionState===ms.Waiting||e.unitOrderTrait.hasTasks())?(this.children.push(new ts(5)),i.moveTrait.collisionState=ms.Waiting,i.moveTrait.moveState=ps.PlanMove,!1):(e.forEach(e=>{e.unitOrderTrait.addTask(new Ls(this.game,this.fromDirection))}),this.children.push(new ts(1)),i.moveTrait.collisionState=ms.Waiting,i.moveTrait.moveState=ps.PlanMove,!(this.chainPushIssued=!0))}}}var Fs=__webpack_require__(949);const js=e=>void 0!==e.position,Us=e=>void 0!==e.addScalar;class Ws{constructor(e){this.tileOccupation=e}isInWeaponRange(e,t,i,r,s){var a=s??e;if(i.rules.limboLaunch&&2<Math.abs((js(a)?a.position.tileElevation+a.tile.z:a.z)-(js(t)?t.position.tileElevation+t.tile.z:t.z)))return!1;var{minRange:s,range:r}=this.computeWeaponRangeVsTarget(a,t,i,r);return i.rules.cellRangefinding?this.isInTileRange(a,t,s,r):e.isUnit()&&e.rules.movementZone===ii.Fly?this.isInRange2(a,t,s,r):this.isInRange3(a,t,s,r)}computeWeaponRangeVsTarget(e,t,i,r){let s=0;var a,n;return!js(t)||!t.isBuilding()||i.projectileRules.arcing||i.projectileRules.vertical||i.warhead.rules.ivanBomb||1<(n=t.getFoundation()).width&&1<n.height&&(s+=Math.ceil(Math.min(n.width,n.height)/2)),!i.projectileRules.subjectToElevation||i.projectileRules.arcing&&!js(t)||(a=js(e)?e.tile.z+e.tileElevation:e.z,(n=js(t)?t.tile.z+t.tileElevation:t.z)<a&&(s+=r.elevationModel.getBonus(a,n))),i.projectileRules.isAntiAir&&js(e)&&e.isTechno()&&js(t)&&t.isUnit()&&t.zone===_r.Air&&(s+=e.rules.airRangeBonus),{minRange:i.minRange,range:i.range+s}}isInRange(e,t,i,r,s=!1){return s?this.isInTileRange(e,t,i,r):e.isUnit()&&e.rules.movementZone===ii.Fly?this.isInRange2(e,t,i,r):this.isInRange3(e,t,i,r)}isInRange3(e,t,i,r){return V(this.distance3(e,t)/mr.ISO_TILE_SIZE,i,r)}isInRange2(e,t,i,r){return V(this.distance2(e,t)/mr.ISO_TILE_SIZE,i,r)}distance3(e,t){let i=js(e)?e.position.worldPosition:Us(e)?e:mr.tile3dToWorld(e.rx+.5,e.ry+.5,e.z);t=js(t)?t.position.worldPosition:Us(t)?t:mr.tile3dToWorld(t.rx+.5,t.ry+.5,t.z);return i.distanceTo(t)}distance2(e,t){let i=js(e)?new Fs.Vector2(e.position.worldPosition.x,e.position.worldPosition.z):Us(e)?new Fs.Vector2(e.x,e.z):new Fs.Vector2(e.rx+.5,e.ry+.5).multiplyScalar(mr.ISO_TILE_SIZE);t=js(t)?new Fs.Vector2(t.position.worldPosition.x,t.position.worldPosition.z):Us(t)?new Fs.Vector2(t.x,t.z):new Fs.Vector2(t.rx+.5,t.ry+.5).multiplyScalar(mr.ISO_TILE_SIZE);return i.distanceTo(t)}isInTileRange(e,t,i,r){return V(this.tileDistance(e,t),i,r)}tileDistance(e,t){var i,e=js(e)?this.tileOccupation.calculateTilesForGameObject(e.tile,e):Array.isArray(e)?e:[e],r=js(t)?this.tileOccupation.calculateTilesForGameObject(t.tile,t):Array.isArray(t)?t:[t];let s=new Fs.Vector2,a=new Fs.Vector2,n=Number.POSITIVE_INFINITY;for(i of e)for(var o of r){s.set(i.rx,i.ry),a.set(o.rx,o.ry);o=s.distanceTo(a);o<=n&&(n=o)}return n}}const Vs=__webpack_require__(163);var zs=__webpack_require__(949);class Hs{constructor(e){this.game=e,this.ignoresTerrain=!0,this.distanceToWaypoint=new zs.Vector2}onNewWaypoint(e,t){}tick(e,t){this.distanceToWaypoint.copy(t).sub(e.position.getMapPosition());var i=this.game.rules.general;return i.chronoTrigger&&(i=(t=this.distanceToWaypoint.length())<i.chronoRangeMinimum?i.chronoMinimumDelay:t/i.chronoDistanceFactor,e.warpedOutTrait.setTimed(i,!1,this.game)),{distance:new zs.Vector3(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!0,isTeleport:!0}}}class Gs extends Rr{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}=Zr.tick(e.direction,this.direction,t);return e.direction=i,e.spinVelocity=t,!1}}var $s,qs=__webpack_require__(949);(s=$s=$s||{})[s.None=0]="None",s[s.Start=1]="Start",s[s.Normal=2]="Normal",s[s.End=3]="End",s[s.Single=4]="Single";class Zs{constructor(e){this.game=e,this.hasMomentum=!1,this.moveOnCurve=!1,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=$s.None}selectNextWaypoint(i,r){if(this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==$s.End?$s.Normal:$s.Start,this.initialPosition=i.position.getMapPosition(),this.currentWaypointType!==$s.Start?i.moveTrait.speedPenalty=0:this.currentSpeed=0,1<r.length){var s=r[r.length-1],a=r[r.length-2],e=new qs.Vector2(s.tile.rx-i.tile.rx,s.tile.ry-i.tile.ry),n=Math.abs(Wr(e)-Wr(new qs.Vector2(a.tile.rx-s.tile.rx,a.tile.ry-s.tile.ry)));if(!Math.abs(Zr.fromMapCoords(e)-i.direction)&&0<n&&n<90&&this.hasMomentum){this.moveOnCurve=!0,this.currentWaypointType=2===r.length?this.currentWaypointType===$s.Start?$s.Single:$s.End:$s.Normal;let e=this.initialPosition;i=new qs.Vector2(s.tile.rx+.5,s.tile.ry+.5).multiplyScalar(mr.LEPTONS_PER_TILE);let t=new qs.Vector2(a.tile.rx+.5,a.tile.ry+.5).multiplyScalar(mr.LEPTONS_PER_TILE);n=e.clone().lerp(i,.5),s=t.clone().lerp(i,.5);return this.steerCurve=new qs.CurvePath,this.steerCurve.add(new qs.LineCurve(e,n)),this.steerCurve.add(new qs.QuadraticBezierCurve(n,i,s)),this.steerCurve.add(new qs.LineCurve(s,t)),this.lastPosition=e,a}}else this.currentWaypointType=this.currentWaypointType===$s.Start?$s.Single:$s.End;return this.hasMomentum=!0,this.moveOnCurve=!1,r[r.length-1]}onNewWaypoint(e,t,i){let r=(new qs.Vector2).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=this.moveOnCurve?this.steerCurve.getLength():r.length();t=Zr.fromMapCoords(r);if(t!==e.direction&&(this.pointTurretToTarget(e,i),!this.moveOnCurve))return e.moveTrait.velocity.set(0,0,0),[new Gs(t)]}tick(i,r,s){this.pointTurretToTarget(i,s);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;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,this.carryOverDistance&&(a=this.carryOverDistance);var n=i.position.getMapPosition();let o;if(this.moveOnCurve){var s=this.steerCurve.getLength(),h=Math.min(this.distanceTravelled+a,s);this.carryOverDistance=Math.max(0,this.distanceTravelled+a-s),this.distanceTravelled=h;let e=this.steerCurve.getPointAt(this.distanceTravelled/s),t=this.steerCurve.getTangentAt(this.distanceTravelled/s);h=t.clone().setLength(a);i.moveTrait.velocity.set(h.x,0,h.y).multiplyScalar(mr.getWorldTileSize()/mr.LEPTONS_PER_TILE);var s=i.rules.rot,{facing:h,delta:s}=Zr.tick(i.direction,Zr.fromMapCoords(t),s);i.direction=h,i.spinVelocity=s;s=this.lastPosition;this.lastPosition=e.clone(),o=e.sub(s)}else{let e=(new qs.Vector2).copy(r).sub(n);n=Math.min(e.length(),a);o=e.clone().setLength(n);let t=o.clone();this.carryOverDistance&&t.add(mr.vecWorldToGround(mr.vecWorldToLeptons(i.moveTrait.velocity))),i.moveTrait.velocity.set(t.x,0,t.y).multiplyScalar(mr.getWorldTileSize()/mr.LEPTONS_PER_TILE),this.distanceTravelled+=n,this.carryOverDistance=Math.max(0,a-e.length())}return{distance:new qs.Vector3(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 r=t.position.getMapPosition();let e=(new qs.Vector2).copy(i).sub(r);e.length()&&(r=Zr.fromMapCoords(e),t.turretTrait.desiredFacing=r)}}applyAcceleration(e,t,i,r){if(this.currentWaypointType===$s.Single)return.3*i;if(this.currentWaypointType!==$s.End)return Math.min(t+e.rules.accelerationFactor*i,i);return this.moveOnCurve&&this.currentWaypointType===$s.End&&(r=r<=.5?0:2*(r-.5)),qs.Math.lerp(1,i,1-r)}}var Qs=__webpack_require__(949);class Xs{constructor(e){this.game=e,this.currentMoveDirection=new Qs.Vector2,this.distanceToWaypoint=new Qs.Vector2,this.carryOverDistance=0}onNewWaypoint(e,t){this.currentMoveDirection.copy(t).sub(e.position.getMapPosition());t=Zr.fromMapCoords(this.currentMoveDirection);t!==e.direction&&(e.direction=t)}onWaypointUpdate(e,t){this.onNewWaypoint(e,t)}tick(e,t){let i=e.moveTrait.baseSpeed*Xi.MAGIC_SPEED_MULT;e.stance===kr.Prone&&(i/=2),e.isPanicked&&(i*=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,i*=r,this.carryOverDistance&&(i=this.carryOverDistance,this.carryOverDistance=0),this.distanceToWaypoint.copy(t).sub(e.position.getMapPosition());t=this.distanceToWaypoint.clone().setLength(i);e.moveTrait.velocity.set(t.x,0,t.y).multiplyScalar(mr.getWorldTileSize()/mr.LEPTONS_PER_TILE);t=Math.min(this.distanceToWaypoint.length(),i);return this.carryOverDistance=Math.max(0,i-this.distanceToWaypoint.length()),this.distanceToWaypoint.setLength(t),{distance:new Qs.Vector3(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!this.distanceToWaypoint.length()||!!this.carryOverDistance}}}var Ys,Ks=__webpack_require__(949);(s=Ys=Ys||{})[s.None=0]="None",s[s.Start=1]="Start",s[s.Normal=2]="Normal",s[s.End=3]="End",s[s.Single=4]="Single";class Js{constructor(e){this.hoverRules=e,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=Ys.None,this.nextWaypointDir=new Ks.Vector2}selectNextWaypoint(e,t){var i;return this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==Ys.End?Ys.Normal:Ys.Start,this.initialPosition=e.position.getMapPosition(),this.currentWaypointType===Ys.Start&&(this.currentSpeed=0),t.length<=1?(this.currentWaypointType=this.currentWaypointType===Ys.Start?Ys.Single:Ys.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 r=(new Ks.Vector2).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=r.length();t=this.maxSpeed=e.moveTrait.baseSpeed*Xi.MAGIC_SPEED_MULT,e=60*this.hoverRules.acceleration*is.BASE_TICKS_PER_SECOND;this.acceleration=t/e;e=60*this.hoverRules.brake*is.BASE_TICKS_PER_SECOND;this.deceleration=t/e}tick(e,t){var i=e.position.getMapPosition();let r=t.clone().sub(i);t=r.length(),i=this.maxSpeed;this.currentWaypointType===Ys.Single?this.currentSpeed=i/2:this.currentWaypointType===Ys.End?(s=this.computeBrakeDistance(this.currentSpeed,this.deceleration),this.totalDistanceToTravel-this.distanceTravelled<=s&&(this.currentSpeed=Math.max(0,this.currentSpeed-this.deceleration))):this.currentSpeed=Math.min(this.currentSpeed+this.acceleration,i);var s=Zr.fromMapCoords(r),i=Zr.fromMapCoords(this.nextWaypointDir);let a=s,n=e.rules.rot;this.currentWaypointType===Ys.Normal&&s!==i&&(s=(o=zr(this.nextWaypointDir,Zr.toMapCoords(e.direction)))/n,s=Math.max(this.currentSpeed*s,this.totalDistanceToTravel),this.totalDistanceToTravel-this.distanceTravelled<=s&&(a=i,n=o/((this.totalDistanceToTravel-this.distanceTravelled)/this.currentSpeed)));var o=Zr.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=r.clone().setLength(o),c=l.clone();return this.carryOverDistance&&c.add(mr.vecWorldToGround(mr.vecWorldToLeptons(e.moveTrait.velocity))),e.moveTrait.velocity.set(c.x,0,c.y).multiplyScalar(mr.ISO_TILE_SIZE/mr.LEPTONS_PER_TILE),this.distanceTravelled+=o,this.carryOverDistance=Math.max(0,h-t),{distance:new Ks.Vector3(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)}}var ea,ta=__webpack_require__(949);(s=ea=ea||{})[s.Boost=0]="Boost",s[s.Midcourse=1]="Midcourse",s[s.Terminal=2]="Terminal";class ia{constructor(e,t){this.game=e,this.missileRules=t,this.flightPhase=ea.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=mr.vecWorldToLeptons(mr.tile3dToWorld(i.tile.rx+.5,i.tile.ry+.5,t)),this.cruiseAltitude=mr.worldToLeptons(mr.tileHeightToWorld(t))+this.missileRules.altitude,i}onNewWaypoint(e,t,i){}tick(i,e,t){let r=mr.vecWorldToLeptons(i.position.worldPosition),s=this.targetPosition.clone().sub(r);i.zone!==_r.Air&&(i.onBridge=!1,i.zone=_r.Air,this.game.events.dispatch(new Yr(i)));let a;var n;a=this.currentVelocity?(n=i.rules.speed*Xi.MAGIC_SPEED_MULT,Math.min(this.currentVelocity.length()+this.missileRules.acceleration,n)):(p=this.missileRules.acceleration,this.missileRules.lazyCurve?this.currentVelocity=new ta.Vector3(s.x,0,s.z):this.currentVelocity=mr.vecGroundToWorld(Zr.toMapCoords(i.direction)),$r(this.currentVelocity,new ta.Vector3(this.currentVelocity.x,1e8,this.currentVelocity.z),i.pitch),p),this.currentVelocity.setLength(a);let o=!1;switch(this.flightPhase){case ea.Boost:if(!(mr.worldToLeptons(i.position.worldPosition.y)>=this.cruiseAltitude)){o=!1;break}this.flightPhase=ea.Midcourse;case ea.Midcourse:var h,l=new ta.Vector2(s.x,s.z).length();if(!this.missileRules.lazyCurve){$r(this.currentVelocity,new ta.Vector3(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)),$r(this.currentVelocity,new ta.Vector3(s.x,this.currentVelocity.y,s.z),i.rules.rot),i.direction=Zr.fromMapCoords(mr.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*Hr(this.currentVelocity,new ta.Vector3(this.currentVelocity.x,0,this.currentVelocity.z)),l/(r.y-this.targetPosition.y)<1&&(this.flightPhase=ea.Terminal);break}this.flightPhase=ea.Terminal;var c=r.clone().add(this.currentVelocity.clone().setLength(l/3/z(Math.cos(ta.Math.degToRad(i.pitch)),10))),u=this.targetPosition.clone().lerp(r,.15).setY(c.y);this.descentCurve=new ta.CubicBezierCurve3(r,c,u,this.targetPosition);case ea.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(r));u=t.clone().setY(0);i.pitch=Math.sign(t.y-u.y)*Hr(u,t),o=1<=(this.descentTravelled+c)/d}else{$r(this.currentVelocity,s,i.rules.rot),i.direction=Zr.fromMapCoords(mr.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*Hr(this.currentVelocity,new ta.Vector3(this.currentVelocity.x,0,this.currentVelocity.z));d=s.length()-c;(d<a||d<1)&&(this.currentVelocity.copy(s.clone().addScalar(-c)),o=!0)}break;default:throw new Error(`Unhandled flight phase "${this.flightPhase}"`)}var p=mr.vecLeptonsToWorld(r.clone().add(this.currentVelocity));return this.game.map.isWithinHardBounds(p)?(i.moveTrait.velocity.copy(this.currentVelocity).multiplyScalar(mr.ISO_TILE_SIZE/mr.LEPTONS_PER_TILE),{distance:this.currentVelocity,done:o}):(this.game.destroyObject(i),{done:!0,distance:new ta.Vector3})}}class ra{constructor(e){this.game=e}create(e){var t=e.rules.locomotor;switch(t){case ti.Infantry:return new Xs(this.game);case ti.Jumpjet:return new es(this.game);case ti.Vehicle:case ti.Ship:return new Zs(this.game);case ti.Chrono:return e.isVehicle()&&e.harvesterTrait&&e.rules.teleporter?new Zs(this.game):new Hs(this.game);case ti.Aircraft:return new ds(this.game);case ti.Missile:return new ia(this.game,this.game.rules.general.getMissileRules(e.name));case ti.Hover:return new Js(this.game.rules.general.hover);default:throw new Error(`Unhandled locomotor type ${t}`)}}}class sa{constructor(e,t,i,r,s,a,n=!1,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=r,this.rng=s,this.predicate=a,this.includeStartTile=n,this.checkBounds=o,this.pool=[],this.pool=new Array(Math.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,r=this.pool.splice(i,1)[0],i=r%t,r=Math.floor(r/t),r=e(this.startTile.rx-this.maxDistance+i,this.startTile.ry-this.maxDistance+r);r&&(yield r)}}}var aa,na,oa,ha,la=__webpack_require__(949);class ca extends Rr{constructor(e,t,i,r){super(),this.game=e,this.targetTile=t,this.toBridge=i,this.options=r,this.preventOpportunityFire=!1,this.logger=Vs.get("move"),this.destinationLeptons=new la.Vector2,this.currentWaypointLeptons=new la.Vector2,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:[]}}onStart(e){if(e.moveTrait.currentWaypoint)throw new Error("Nested move tasks are not supported");void 0===e.moveTrait.locomotor&&(e.moveTrait.locomotor=new ra(this.game).create(e)),e.moveTrait.lastTargetOffset?this.targetOffset=e.moveTrait.lastTargetOffset:this.targetOffset=e.position.getTileOffset(),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=ps.ReachedNextWaypoint,e.moveTrait.lastMoveResult=void 0,e.moveTrait.lastTargetOffset=void 0,e.moveTrait.lastVelocity=void 0}computePath(e,t){let i;e.rules.movementZone===ii.Fly?(i=this.computeAirPath(e),this.targetLinesConfig.pathNodes=i.map(({tile:e,onBridge:t})=>({tile:e,onBridge:t})),this.targetLinesConfig.pathNodes[0].onBridge=this.toBridge?this.game.map.tileOccupation.getBridgeOnTile(this.targetTile):void 0):(i=t.ignoresTerrain?this.computeDirectJumpPath(e):(this.blockedPathNodes=this.blockedPathNodes.filter(e=>e.obj.isSpawned&&e.node.tile===e.obj.tile),this.computeGroundPath(e)),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 r=this.targetTile,s=this.toBridge?i.tileOccupation.getBridgeOnTile(this.targetTile):void 0,a=this.options?.ignoredBlockers;var n=new xr(i.tiles,i.mapBounds,r,{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!==r&&(r=n,s=i.tileOccupation.getBridgeOnTile(r)),[{tile:r,onBridge:s},{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===ps.Moving&&t.moveTrait.currentWaypoint&&(e=t.moveTrait.currentWaypoint.tile,i=t.moveTrait.currentWaypoint.onBridge);let r;var s=this.toBridge?this.game.map.tileOccupation.getBridgeOnTile(this.targetTile):void 0,a=this.nodeIsBlockedForPathfinding({tile:this.targetTile,onBridge:s},t);if(Math.abs(e.rx-this.targetTile.rx)<=1&&Math.abs(e.ry-this.targetTile.ry)<=1&&new Ds(this.game.map).isEligibleTile(e,i,s,this.targetTile)&&a)r=[];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:s},obj:n}),r=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 r}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*mr.LEPTONS_PER_TILE,e.ry*mr.LEPTONS_PER_TILE).add(t)}canStopAtTile(t,i,r){if(t.zone===_r.Air){if((!t.isAircraft()||!t.airportBoundTrait)&&!t.rules.spawned&&this.game.map.getObjectsOnTile(i).filter(e=>e.isBuilding()&&!e.dockTrait?.hasReservedDockForUnit(t)&&!t.rules.dock.includes(e.name)||e.isUnit()&&e.tile===i&&e.moveTrait.moveState!==ps.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===r&&e.moveTrait.moveState!==ps.Moving&&e!==t);if(2<e.length||e.find(e=>e.position.subCell===t.position.subCell))return!1}return!(t.zone!==_r.Air&&t.rules.tooBigToFitUnderBridge&&!r&&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 r=new Ws(this.game.map.tileOccupation);return!(r.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=ms.Resolved,e.moveTrait.currentWaypoint=void 0,e.position.getTileOffset().equals(this.targetOffset)||(e.moveTrait.lastTargetOffset=this.targetOffset)}forceCancel(e){return!(!this.cancellable||this.children.some(e=>!e.cancellable))&&(this.status!==Sr.Running&&this.status!==Sr.Cancelling||(e.moveTrait.unreservePathNodes(),e.moveTrait.lastMoveResult=gs.Cancel,this.onEnd(e),e.moveTrait.lastTargetOffset=this.targetOffset,e.moveTrait.lastVelocity=e.moveTrait.velocity.clone()),this.status=Sr.Cancelled,!0)}onTick(s){if(s.moveTrait.isDisabled()&&s.moveTrait.moveState===ps.ReachedNextWaypoint)return!!this.isCancelling()&&(s.moveTrait.lastMoveResult=gs.Cancel,!0);this.needsPathUpdate&&(s.moveTrait.moveState===ps.PlanMove&&(this.inPlanningForTicks=void 0,s.moveTrait.currentWaypoint=void 0,s.moveTrait.collisionState=ms.Resolved,s.moveTrait.moveState=ps.ReachedNextWaypoint,s.moveTrait.velocity.set(0,0,0)),this.computePath(s,s.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(s.moveTrait.moveState===ps.ReachedNextWaypoint){s.moveTrait.unreservePathNodes();var t=this.path.findIndex(e=>e===s.moveTrait.currentWaypoint);if(-1!==t?this.path.splice(t):this.path.pop(),s.moveTrait.currentWaypoint=void 0,this.isCancelling()?!this.cancelProcessed:this.hasReachedDestination(s)){var a=!this.isCancelling()&&!this.isCloseEnoughToDest(s,s.tile,this.options?.closeEnoughTiles);if(!a&&this.canStopAtTile(s,s.tile,s.onBridge))return s.moveTrait.lastMoveResult=this.isCancelling()?gs.Cancel:gs.Success,!0;{if(5<this.unreachableTargets.length)return s.moveTrait.lastMoveResult=gs.Fail,this.log(s,"bail_max_unreachable_dest"),!0;let e=s.tile,t=s.onBridge?i.tileOccupation.getBridgeOnTile(e):void 0;a&&(e=this.targetTile,t=this.toBridge?i.tileOccupation.getBridgeOnTile(e):void 0);var n=this.findRelocationTile(e,t,s);if(!n)return s.moveTrait.lastMoveResult=a?gs.Fail:gs.CloseEnough,this.log(s,"bail_no_free_dest"),!0;a=!t||t.isHighBridge()?i.tileOccupation.getBridgeOnTile(n):void 0;return this.updateTarget(n,!!a),this.isCancelling()&&(this.cancelProcessed=!0,this.cancelRepositionPending=!0),!1}}if(this.cancelProcessed&&!this.path.length)return s.moveTrait.lastMoveResult=gs.Cancel,!0;this.cancelProcessed=!1,s.moveTrait.moveState=ps.PlanMove;let e=s.moveTrait.locomotor;s.moveTrait.currentWaypoint=e.selectNextWaypoint?e.selectNextWaypoint(s,this.path):this.path[this.path.length-1],this.currentWaypointLeptons.set(s.moveTrait.currentWaypoint.tile.rx,s.moveTrait.currentWaypoint.tile.ry).multiplyScalar(mr.LEPTONS_PER_TILE).add(this.targetOffset);n=e.onNewWaypoint(s,this.currentWaypointLeptons,this.destinationLeptons);if(n)return this.children.push(...n),!1}if(s.moveTrait.moveState===ps.PlanMove){if(this.isCancelling()&&!this.cancelRepositionPending)return s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=ps.ReachedNextWaypoint,this.onTick(s);if(this.inPlanningForTicks=void 0===this.inPlanningForTicks?0:this.inPlanningForTicks+1,200<this.inPlanningForTicks)return this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,s.moveTrait.velocity.set(0,0,0),this.log(s,"repath_plan_timeout"),!1;if(s.rules.movementZone!==ii.Fly&&!s.moveTrait.locomotor.ignoresTerrain){let t=this.path.slice(this.path.indexOf(s.moveTrait.currentWaypoint)).reverse();var r,e,o=s.moveTrait.velocity.length();for(r of t){if(!i.terrain.getPassableSpeed(r.tile,s.rules.speedType,!!r.onBridge,this.options?.ignoredBlockers))return this.needsPathUpdate=!0,s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=ps.ReachedNextWaypoint,this.onTick(s);if(this.game.crateGeneratorTrait&&!r.onBridge){var h=i.getGroundObjectsOnTile(r.tile).find(e=>e.isOverlay()&&e.rules.crate);if(h)if(this.game.crateGeneratorTrait.pickupCrate(s,h,this.game)===Zi.Unit){h=this.game.map.getGroundObjectsOnTile(r.tile).find(e=>e.isUnit()&&!e.onBridge);if(h)return this.needsPathUpdate=!0,this.blockedPathNodes.push({node:r,obj:h}),s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=ps.ReachedNextWaypoint,this.onTick(s)}}for(e of i.terrain.findObstacles(r,s).filter(e=>!this.options?.ignoredBlockers?.includes(e.obj))){if(e.static)return this.needsPathUpdate=!0,s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=ps.ReachedNextWaypoint,this.onTick(s);if(e.obj.rules.crushable){if(!(s.rules.speedType!==Kt.Track||!s.rules.crusher||e.obj.isTechno()&&this.game.areFriendly(e.obj,s)))continue;if(!e.obj.isTechno())return this.needsPathUpdate=!0,s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=ps.ReachedNextWaypoint,this.onTick(s)}if(e.obj.isTerrain()){if(!s.isInfantry())throw new Error(`Obstacle ${e.obj.name} should be a blocker for non infantry`);var l=this.findFreeSubCell(s,r);return void 0!==l?this.relocateToSubCell(s,l):(this.needsPathUpdate=!0,this.blockedPathNodes.push({node:r,obj:e.obj}),s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=ps.ReachedNextWaypoint),this.onTick(s)}if(!e.obj.isTechno())throw new Error(`Unexpected obstacle of type ${e.obj.type}`);const m=e.obj;var c=m.isUnit()?m.moveTrait.velocity.length():0;if(!m.isAircraft()||m.zone!==_r.Ground||!this.options?.ignoredBlockers?.some(e=>e.isBuilding()&&e.dockTrait?.isDocked(m))){if(1===t.length&&m.isUnit()&&c&&o&&o<=c&&s.direction===m.direction&&m.tile===r.tile&&m.moveTrait.currentWaypoint?.tile!==r.tile)break;if(m.isBuilding()||m.moveTrait.moveState===ps.Idle||m.moveTrait.collisionState!==ms.Resolved){if(!o&&s.moveTrait.collisionState!==ms.Resolved&&m.isUnit()&&m.moveTrait.collisionState!==ms.Resolved)return 200<this.inPlanningForTicks+1&&(this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,this.log(s,"repath_waited_too_long_blocker "+m.id),s.moveTrait.velocity.set(0,0,0)),!1;{if(m.isInfantry()&&s.isInfantry()&&m.moveTrait.collisionState===ms.Resolved){var u=this.findFreeSubCell(s,r);if(void 0!==u)return this.relocateToSubCell(s,u),this.onTick(s)}l=Ms(this.path.slice(0,this.path.indexOf(r)),e=>!i.terrain.findObstacles(e,s).length);if(-1===l){if(this.canStopAtTile(s,s.tile,s.onBridge)&&this.isCloseEnoughToDest(s,s.tile,this.options?.closeEnoughTiles))return s.moveTrait.lastMoveResult=gs.CloseEnough,this.log(s,"bail_waypoints_blocked_close_enough"),!0;if(!(0===this.options?.closeEnoughTiles||Math.abs(s.tile.rx-this.targetTile.rx)<=1&&Math.abs(s.tile.ry-this.targetTile.ry)<=1))return this.needsPathUpdate=!0,this.blockedPathNodes.push(...this.path.slice(0,this.path.indexOf(r)+1).map(e=>({node:e,obj:i.terrain.findObstacles(e,s)[0].obj}))),s.moveTrait.velocity.set(0,0,0),this.log(s,"repath_waypoints_blocked_too_far"),!1}let e;if(e=-1!==l?(u=this.path[l],i.terrain.computePath(s.rules.speedType,s.tile,s.onBridge,u.tile,!!u.onBridge,{maxExpandedNodes:15,bestEffort:!1,excludeTiles:e=>!!i.terrain.findObstacles(e,s).length})):[],e.length||m.owner!==s.owner||1!==t.length)return e.length?(this.path.splice(l,this.path.length,...e),s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=ps.ReachedNextWaypoint,this.onTick(s)):((d=this.selectWeaponVsObstacle(s,m))?(this.children.push(s.attackTrait.createAttackTask(this.game,m,m.tile,d,{passive:!0,holdGround:!0})),s.moveTrait.velocity.set(0,0,0)):this.options?.forceWaitOnPathBlocked&&1===t.length?(this.children.push(new ts(40)),this.inPlanningForTicks=0,s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=ms.Waiting):(this.needsPathUpdate=!0,this.blockedPathNodes.push({node:r,obj:m}),m.isBuilding()&&(this.allObstaclesAreBlockers=!0),this.log(s,"repath_unavoidable_blocker "+m.id),s.moveTrait.velocity.set(0,0,0)),!1);d=m.unitOrderTrait.hasTasks();if(this.pushTried||m.isBuilding()||m.moveTrait.collisionState===ms.Waiting||d||m.isAircraft()&&m.missileSpawnTrait)return!this.options?.forceWaitOnPathBlocked&&(m.isBuilding()||d&&m.moveTrait.moveState===ps.Idle||200<this.inPlanningForTicks+40)?(this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,this.log(s,"repath_blocker_busy_wait_timeout "+m.id),s.moveTrait.velocity.set(0,0,0)):(this.children.push(new ts(40)),this.options?.forceWaitOnPathBlocked?this.inPlanningForTicks=0:this.inPlanningForTicks+=40,s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=ms.Waiting),!1;var d,d=new la.Vector2(m.tile.rx-s.tile.rx,m.tile.ry-s.tile.ry);return this.pushTried=!0,m.unitOrderTrait.addTask(new Ls(this.game,d)),this.children.push(new ts(1)),s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=ms.Waiting,this.log(s,"push "+m.id),!1}}if(!o)return 40<this.inPlanningForTicks&&(s.moveTrait.collisionState=ms.Waiting),!1;if(180===Math.abs(s.direction-m.direction))return s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=ms.Waiting,!1;if(Math.abs(s.direction-m.direction)<=45&&1.5*c<o){c=this.path.indexOf(r);if(5<=c){let e=Ms(this.path.slice(0,c-5),e=>!i.terrain.findObstacles(e,s).length);if(-1!==e){c=this.path[e],c=i.terrain.computePath(s.rules.speedType,s.tile,s.onBridge,c.tile,!!c.onBridge,{maxExpandedNodes:15,bestEffort:!1,excludeTiles:t=>!!i.terrain.findObstacles(t,s).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),s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=ps.ReachedNextWaypoint,this.onTick(s)}}return s.moveTrait.collisionState=ms.Waiting,s.moveTrait.velocity.set(0,0,0),!1}return s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=ms.Waiting,!1}}}if(s.rules.speedType===Kt.Track&&o){var p,g=this.path.indexOf(s.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(ai.SCATTER)&&!this.game.areFriendly(e,s)))p.unitOrderTrait.hasTasks()||p.unitOrderTrait.addTask(new da(this.game))}}s.moveTrait.reservedPathNodes.length||(s.moveTrait.reservedPathNodes.push(...t),t.forEach(e=>{i.tileOccupation.occupySingleTile(e.tile,s)}))}s.moveTrait.moveState=ps.Moving,this.inPlanningForTicks=void 0,this.unreachableTargets.length=0,this.pushTried=!1,s.moveTrait.collisionState===ms.Waiting&&(s.moveTrait.collisionState=ms.Resolved)}if(s.moveTrait.moveState===ps.Moving){let e=s.moveTrait.locomotor,{distance:t,done:i,isTeleport:r}=e.tick(s,this.currentWaypointLeptons,this.destinationLeptons,this.isCancelling()&&!this.cancelRepositionPending);if(r&&s.traits.filter(Cr).forEach(e=>{e[Cr.onBeforeTeleport](s,this.game,!0,!0)}),t.length()&&(a=s.tile,t.y?s.position.moveByLeptons3(t):s.position.moveByLeptons(t.x,t.z),s.tile!==a&&(n=s.onBridge?this.game.map.tileOccupation.getBridgeOnTile(a):void 0,n=(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===s.tile))?g.onBridge:n||s.moveTrait.currentWaypoint.onBridge?this.game.map.tileOccupation.getBridgeOnTile(s.tile):void 0,s.moveTrait.handleTileChange(a,n,!1,this.game,r),r&&(s.moveTrait.lastTeleportTick=this.game.currentTick,this.game.events.dispatch(new Dr(s,!0,a))))),i)return s.moveTrait.moveState=ps.ReachedNextWaypoint,this.onTick(s)}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(r,s,a){let n=this.game.map,i;if(a.rules.movementZone===ii.Fly){let e=new sa(n.tiles,n.mapBounds,r,1,this.game,e=>!0);i=e.getNextTile()}else{let e=new Ds(n),t=new xr(n.tiles,n.mapBounds,r,{width:1,height:1},0,5,t=>{let i=!s||s.isHighBridge()?n.tileOccupation.getBridgeOnTile(t):void 0;return!this.unreachableTargets.find(e=>e.tile===t&&e.toBridge===!!i)&&(a.zone===_r.Air||!n.terrain.findObstacles({tile:t,onBridge:i},a).length&&e.isEligibleTile(t,i,s,r))&&this.canStopAtTile(a,t,!!i)});i=t.getNextTile()}return i}findFreeSubCell(t,i){let e=this.game.map.getGroundObjectsOnTile(i.tile);var r=e.filter(e=>e.isInfantry()&&e.onBridge===!!i.onBridge&&e!==t).map(e=>e.position.desiredSubCell),s=e.filter(e=>e.isTerrain()).map(e=>e.rules.getOccupiedSubCells(this.game.map.getTheaterType())).flat();let a=[...r,...s];return Rs.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(mr.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 ra(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}`)}}class ua{constructor(e){this.game=e,this.movePositionHelper=new Ds(e.map)}findPositions(e,t){let i=new Set,r=new Map;for(var s of e){var a=this.findFreeMovePosition(s,i,t);a&&(r.set(s,a),i.add(a.tile))}return r}findFreeMovePosition(i,e,{ignoredBlockers:t,excludedTiles:r,noSlopes:s}={}){let a=this.game.map,n=i.onBridge?a.tileOccupation.getBridgeOnTile(i.tile):void 0,o=new sa(a.tiles,a.mapBounds,i.tile,1,this.game,e=>{if(r?.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))&&(!s||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 da extends Rr{constructor(e,t,i){super(),this.game=e,this.target=t,this.options=i}onStart(i){if(!i.moveTrait.isDisabled()&&i.rules.movementZone!==ii.Fly){let e,t;if(this.target)({tile:e,toBridge:t}=this.target);else{i=new ua(this.game).findPositions([i],this.options).get(i);if(!i)return;e=i.tile,t=!!i.onBridge}this.children.push(new ca(this.game,e,t,{closeEnoughTiles:0,ignoredBlockers:this.options?.ignoredBlockers}))}}onTick(e){return!0}}class pa{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}[br.onDamage](e,t){e.healthTrait.health<=100*this.evacThreshold&&this.evacuate(t)}[Tr.onDestroy](e,t,i,r){if(r){for(var s of this.units)t.destroyObject(s,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(r,s=!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 xr(r.map.tiles,r.map.mapBounds,a.tile,a.art.foundation,1,1,e=>0<r.map.terrain.getPassableSpeed(e,t,!1)&&Math.abs(e.z-a.tile.z)<2&&!r.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),r.unlimboObject(o,h),o.unitOrderTrait.addTask(new da(r))):s||(r.destroyObject(o,{player:o.owner}),n.splice(l,1))}}var i=a.owner;n.length||a.isDestroyed||r.changeObjectOwner(a,r.getNeutralPlayer()),r.events.dispatch(new Nr(a,i))}}}class ga{constructor(){this.facing=0,this.desiredFacing=0}isRotating(){return this.facing!==this.desiredFacing}[Or.onTick](e){this.desiredFacing!==this.facing&&(e=e.rules.rot,this.facing=Zr.tick(this.facing,this.desiredFacing,e||Number.POSITIVE_INFINITY).facing)}}class ma{constructor(e,t){this.target=e,this.status=t,this.type=vr.BuildStatusChange}}class fa{constructor(e){this.target=e,this.type=vr.PowerLow}}class ya{constructor(e){this.target=e,this.type=vr.PowerRestore}}class wa{constructor(e,t,i){this.target=e,this.power=t,this.drain=i,this.type=vr.PowerChange}}(s=aa=aa||{}).onPowerLow=Symbol(),s.onPowerRestore=Symbol(),s.onPowerChange=Symbol(),(s=na=na||{})[s.Low=0]="Low",s[s.Normal=1]="Normal";class Ta{constructor(e){this.player=e,this.power=0,this.drain=0,this.level=na.Normal,this.blackoutFrames=0,this.powerByObject=new Map}isLowPower(){return this.level===na.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,r){var s=t.rules.power;if(s){if(s<0)"add"!==i&&"remove"!==i||(this.drain+="add"===i?-s:s);else{let e=0;if("add"===i){var a=Math.ceil(s*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?(s=Math.ceil(s*t.healthTrait.health/100),this.powerByObject.set(t,s),s-a):(this.powerByObject.delete(t),-a)}this.power+=e}this.updateLevel(r),r.traits.filter(aa).forEach(e=>{e[aa.onPowerChange](this.player,r)}),r.events.dispatch(new wa(this.player,this.power,this.drain))}}updateLevel(t){var e=this.level;this.level=this.power>=this.drain&&!this.blackoutFrames?na.Normal:na.Low,this.level!==e&&(e===na.Normal&&this.level===na.Low&&(t.traits.filter(aa).forEach(e=>{e[aa.onPowerLow](this.player,t)}),t.events.dispatch(new fa(this.player))),e===na.Low&&this.level===na.Normal&&(t.traits.filter(aa).forEach(e=>{e[aa.onPowerRestore](this.player,t)}),t.events.dispatch(new ya(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 ba{constructor(e){this.obj=e}isCharged(){return!!this.obj.isBuilding()&&!!this.obj.overpoweredTrait?.hasChargersToPowerOn()}isPoweredOn(e=!1){return!(e||!this.isCharged())||(!this.obj.rules.power&&this.obj.rules.needsEngineer?this.obj.owner.playable:!!this.obj.owner.powerTrait&&this.obj.owner.powerTrait?.level!==na.Low)}dispose(){this.obj=void 0}}class va{constructor(){this.listeners=new Set}subscribe(e){this.listeners.add(e)}subscribeOnce(i){let r=(e,t)=>{i(e,t),this.unsubscribe(r),r=void 0};this.subscribe(r)}unsubscribe(e){this.listeners.delete(e)}dispatch(t,i){this.listeners.forEach(e=>e(i,t))}asEvent(){return this}}(s=oa=oa||{})[s.Structures=0]="Structures",s[s.Armory=1]="Armory",s[s.Infantry=2]="Infantry",s[s.Vehicles=3]="Vehicles",s[s.Aircrafts=4]="Aircrafts",s[s.Ships=5]="Ships",(s=ha=ha||{})[s.Idle=0]="Idle",s[s.Active=1]="Active",s[s.OnHold=2]="OnHold",s[s.Ready=3]="Ready";class Sa{constructor(e,t,i){this.type=e,this._maxSize=t,this.maxItemQuantity=i,this.items=[],this.size=0,this._status=ha.Idle,this._onUpdate=new va}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,r=0;for(;i<=this.size&&r<this.items.length;){let e=this.items[r];i+=e.quantity,i>this.size&&(e.quantity-=i-this.size),0<e.quantity&&r++}this._maxSize=e,this.items[r]&&this.items.splice(r),t!==this.size&&(this.size||(this._status=ha.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 r=this.find(e).reduce((e,t)=>e+t.quantity,0);t=Math.min(this.maxItemQuantity-r,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===ha.Idle&&(this._status=ha.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 r=this.find(e);if(!r.length)throw new Error(`Can't remove non-existent item ${e.name} from queue ${oa[this.type]}`);var s;if(r.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?r.shift():r.pop();e.quantity<=a?(s=this.getFirst()===e,this.items.splice(this.items.indexOf(e),1),s&&(this._status=ha.Active),a-=e.quantity):(e.quantity-=a,a=0)}this.size-=t,t&&(this.size||(this._status=ha.Idle),this._onUpdate.dispatch(this))}notifyUpdated(){this._onUpdate.dispatch(this)}}class _a extends ca{constructor(e,t,i,r){super(e,i,!1,{ignoredBlockers:[t],closeEnoughTiles:0,strictCloseEnough:!0,forceWaitOnPathBlocked:t.factoryTrait?.type!==Gi.InfantryType}),this.factory=t,this.rallyPoint=r,this.preventOpportunityFire=!0,this.cancellable=!1}canStopAtTile(e,t,i){return!this.game.map.tileOccupation.isTileOccupiedBy(t,this.factory)&&super.canStopAtTile(e,t,i)}onTick(e){return e.moveTrait.moveState===ps.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)}}var ka,Oa,Ia,Ca,Aa=__webpack_require__(949);class Ba{constructor(e,t,i,r,s,a=()=>!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=s,this.predicate=a,this.dirVec=new Aa.Vector2(10,0),this.finished=!1,this.diagonal=!0,this.distance=r}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 Aa.Vector2,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}}}(ka=ka||{}).onSell=Symbol();class Ea{[ws.onUnspawn](e){this.undock(e),this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[fs.onChange](e){e.owner!==this.dock?.owner&&this.undock(e),e.owner!==this.reservedDock?.owner&&this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[Cr.onBeforeTeleport](e,t,i,r){r||this.undock(e)}undock(e){this.dock&&!this.dock.isDisposed&&this.dock.dockTrait.undockUnit(e)}dispose(){this.dock=void 0,this.reservedDock=void 0}}function Pa(e){return null!=e}class xa extends Rr{constructor(...e){super(),this.children.push(...e)}onTick(e){return!0}}class Na{constructor(e,t,i,r){this.building=e,this.tiles=t,this.numberOfDocks=i,this.dockingOffsets=r,this.ticksWhenWarpedOut=!0,this.unitsByDockNumber=new Array(i).fill(void 0),this.reservedDocks=new Array(i).fill(void 0)}[ys.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}}[ws.onUnspawn](){for(let e=0;e<this.numberOfDocks;e++)this.unreserveDockAt(e)}[Or.onTick](){for(let e=0;e<this.numberOfDocks;e++){var t=this.unitsByDockNumber[e];t&&t.tile!==this.getDockTile(e)&&this.undockUnit(t)}}[Tr.onDestroy](e,t,i,r){var s=(e.rules.unitRepair||e.helipadTrait)&&!e.rules.naval&&!i?.weapon?.warhead.rules.temporal;if(s)for(var a of this.unitsByDockNumber)a&&!a.isDestroyed&&(s?t.destroyObject(a,i,r):this.undockUnit(a))}[ka.onSell](r,s){if(r.helipadTrait&&this.hasDockedUnits()){var a,e,n;let t=[],i=0;for(a of[...r.owner.buildings].filter(e=>e.helipadTrait&&(e.dockTrait?.getAvailableDockCount()??!1)&&e!==r)){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 os(s,n)):e.unitOrderTrait.addTask(new xa(new ca(s,e.tile,!1),new ss(e=>{e.crashableTrait?e.crashableTrait.crash({player:r.owner}):s.destroyObject(e,{player:r.owner})})).setCancellable(!1))),i++}else{var t,i=r.rules.unitRepair&&!r.rules.naval;for(t of this.unitsByDockNumber)t&&(i?s.sellTrait.sell(t):this.undockUnit(t))}}[fs.onChange](e,t,i){for(var r of this.unitsByDockNumber)r&&i.changeObjectOwner(r,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]}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)/mr.LEPTONS_PER_TILE),Math.floor((t.y+e.z)/mr.LEPTONS_PER_TILE))}isValidUnitForDock(e){return(this.building.unitRepairTrait&&e.isVehicle()&&(!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}`);(this.unitsByDockNumber[t]=e).traits.get(Ea).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(Ea).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(Pa)}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(Ea).reservedDock?.dockTrait.unreserveDockForUnit(e),e.traits.get(Ea).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(Ea).reservedDock=void 0)}unreserveDockForUnit(e){e=this.reservedDocks.indexOf(e);-1!==e&&this.unreserveDockAt(e)}hasReservedDockForUnit(e){return!!this.reservedDocks.includes(e)}getReservedDockForUnit(e){e=this.reservedDocks.indexOf(e);if(-1!==e)return e}dispose(){this.building=void 0}}class Ra{constructor(e){this.target=e,this.type=vr.FactoryProduceUnit}}(s=Oa=Oa||{})[s.All=0]="All",s[s.Ground=1]="Ground",s[s.Air=2]="Air";class Ma{constructor(e){this.tiles=e,this.tileOccupation=[],this.emptyTiles=new Set,this._onChange=new va;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){this.tileOccupation[e.rx][e.ry].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.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===Yt.Rock)return Yt.Rock;var t,i=Fi(e.terrainType);for(t of this.tileOccupation[e.rx][e.ry]){if((t.isOverlay()||t.isBuilding())&&t.rules.wall)return Yt.Wall;if(t.isOverlay()&&t.isTiberium())return Yt.Tiberium;if(t.isOverlay()&&t.rules.land!==Yt.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()?Yt.Road:t.rules.land}getTileZone(e,t=!1){return Mr(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===_r.Air||t.push(i);return t}getAirObjectsOnTile(e){let t=[];for(var i of this.tileOccupation[e.rx][e.ry])i.isUnit()&&i.zone===_r.Air&&t.push(i);return t}getObjectsOnTileByLayer(e,t){if(t===Oa.Ground)return this.getGroundObjectsOnTile(e);if(t===Oa.Air)return this.getAirObjectsOnTile(e);if(t===Oa.All)return this.getObjectsOnTile(e);throw new Error(`Unhandled layer type "${t}"`)}getEmptyTiles(){return[...this.emptyTiles]}}(Ia=Ia||{}).onChange=Symbol(),(Ca=Ca||{}).onProduce=Symbol();var Da,La,Fa=__webpack_require__(949);(s=Da=Da||{})[s.Idle=0]="Idle",s[s.Delivering=1]="Delivering";class ja{constructor(e,t=!1){this.type=e,this.isCloningVats=t,this.status=Da.Idle}[ys.onSpawn](e,t){this.resetRallyPoint(e,t)}resetRallyPoint(e,t){var i;[Gi.BuildingType,Gi.AircraftType].includes(this.type)||(i=this.computeDefaultRallyPoint(e,this.type,t.map),e.rallyTrait?.changeRallyPoint(i,e,t))}[Ia.onChange](t,e,i){if(t.owner.production){let e=[];e=this.type===Gi.BuildingType?[oa.Structures,oa.Armory]:[t.owner.production.getQueueTypeForFactory(this.type)];for(var r of e)t.owner.production.getQueue(r).notifyUpdated()}}[Or.onTick](i,r){if(this.status===Da.Delivering){if(!this.deliveringUnit||this.deliveringUnit.isDestroyed){if(this.buildingProductionTicks=this.buildingProductionTicks??1,0<this.buildingProductionTicks--)return;this.buildingProductionTicks=void 0}else if(r.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=Da.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===Gi.UnitType)&&this.type!==Gi.BuildingType){let e=i.owner.production.getQueueForFactory(this.type);if(e&&e.status===ha.Ready){let t=e.getFirst();if(this.type===Gi.AircraftType){let e=this.produceAircraftAt(i,t,r);var s;if(!e)for(s of[...i.owner.buildings].filter(e=>e.factoryTrait?.type===Gi.AircraftType&&e.helipadTrait)){if(e)break;e=this.produceAircraftAt(s,t,r)}if(!e)return}else if(this.produceGroundUnitAt(i,t,r),!this.isCloningVats&&this.type===Gi.InfantryType){let e=[...i.owner.buildings].find(e=>e.factoryTrait&&e.rules.cloning);e?.factoryTrait.status===Da.Idle&&e?.factoryTrait.produceGroundUnitAt(e,t,r)}i.owner.unitsBuilt++,t.creditsSpent=0,t.progress=0,e.shift(t.rules,1),e.currentSize&&(e.status=ha.Active)}}}}produceGroundUnitAt(e,t,i){let r=i.createUnitForPlayer(t.rules,e.owner);t.rules.trainable&&e.owner.canProduceVeteran(r.rules)&&r.veteranTrait?.setVeteranLevel(bs.Veteran),r.isInfantry()&&(r.position.subCell=Rs.SUB_CELLS[0]);let s=e.rallyTrait.findRallyPointforUnit(r,this.computeInternalRallyPoint(e,this.type,e.rallyTrait.getRallyPoint(),i.map),i.map),a;var n;a=this.type===Gi.NavalUnitType?s:(n=this.computeExitCoords(e,this.type),i.map.tiles.getByMapCoords(Math.floor(n.rx),Math.floor(n.ry))),r.rules.consideredAircraft&&(s=a);let o;if(e.rallyTrait.getRallyPoint()!==s&&(o=e.rallyTrait.findRallyNodeForUnit(r,i.map)),r.isInfantry()){let t=i.map.tileOccupation.getObjectsOnTileByLayer(o?.tile??s,r.rules.consideredAircraft?Oa.Air:Oa.Ground).filter(e=>e.isInfantry()&&e.moveTrait.moveState!==ps.Moving).map(e=>e.position.subCell);r.position.subCell=Rs.SUB_CELLS.find(e=>!t.includes(e))??Rs.SUB_CELLS[0]}r.direction=270,i.spawnObject(r,a),i.traits.filter(Ca).forEach(e=>{e[Ca.onProduce](r,i)}),i.events.dispatch(new Ra(r)),r.rules.consideredAircraft?(n=o??{tile:s,onBridge:void 0},r.unitOrderTrait.addTask(new ca(i,n.tile,!!n.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))):r.unitOrderTrait.addTask(new _a(i,e,s,o)),this.status=Da.Delivering,this.deliveringUnit=r}produceAircraftAt(e,t,i){let r=e.traits.find(Na);if(!r)return!1;var s=r.getFirstAvailableDockNumber();if(void 0===s)return!1;let a=i.createUnitForPlayer(t.rules,e.owner);t.rules.trainable&&e.owner.canProduceVeteran(a.rules)&&a.veteranTrait?.setVeteranLevel(bs.Veteran);t=r.getDockOffset(s);return a.position.moveToLeptons(e.position.getMapPosition()),a.position.moveByLeptons3(t),i.spawnObject(a,a.position.tile),r.dockUnitAt(a,s),a.isAircraft()&&a.airportBoundTrait&&(a.airportBoundTrait.preferredAirport=e),i.traits.filter(Ca).forEach(e=>{e[Ca.onProduce](a,i)}),i.events.dispatch(new Ra(a)),!0}computeExitCoords(e,t){if(t===Gi.InfantryType)return this.computeBarracksDefaultExitCoords(e);if(t===Gi.UnitType)return this.computeWarFactoryExitCoords(e);throw new Error(`Unsupported factory type ${Gi[t]}`)}computeInternalRallyPoint(e,t,i,r){let s,a;if(t===Gi.NavalUnitType)a=this.computeNavalInternalRallyPoint(e,i,r);else{if(t===Gi.InfantryType)s=this.computeBarracksInternalRallyCoords(e);else{if(t!==Gi.UnitType)throw new Error(`Unsupported factory type ${Gi[t]}`);s=this.computeWarFactoryInternalRallyCoords(e)}a=r.tiles.getByMapCoords(s.rx,s.ry)}return a??this.findTileAdjacentToBuilding(e,r)}computeDefaultRallyPoint(e,t,i){let r,s;if(t===Gi.NavalUnitType)s=this.computeNavalDefaultRallyPoint(e,i);else{if(t===Gi.InfantryType)r=this.computeBarracksInternalRallyCoords(e);else{if(t!==Gi.UnitType)throw new Error(`Unsupported factory type ${Gi[t]}`);r=this.computeWarFactoryDefaultRallyCoords(e)}s=i.tiles.getByMapCoords(r.rx,r.ry)}return s??this.findTileAdjacentToBuilding(e,i)}findTileAdjacentToBuilding(e,t){return new xr(t.tiles,t.mapBounds,e.tile,e.getFoundation(),1,1,()=>!0).getNextTile()}computeBarracksDefaultExitCoords(e){var t=e.getFoundation();let i,r;return t.width<=2||t.height<=2?(i=t.width-1,r=t.height-1,e.rules.gdiBarracks&&2<t.width&&(i=Math.floor(t.width/2))):(i=0,r=t.height-1),{rx:e.tile.rx+i,ry:e.tile.ry+r}}computeBarracksInternalRallyCoords(e){var t=e.getFoundation();let{rx:i,ry:r}=this.computeBarracksDefaultExitCoords(e);return!(t.width<=2||t.height<=2)||e.rules.gdiBarracks?r+=1:e.rules.nodBarracks&&(i+=t.width<=2?1:0,r+=t.height<=2?1:0),{rx:i,ry:r}}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 Ba(t.tiles,t.mapBounds,e.centerTile,5,5,e=>e.terrainType===Xt.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 Fa.Vector2(t.rx,t.ry).sub(new Fa.Vector2(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 Ua{constructor(e,t,i,r,s,a,n,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.foundation=r,this.maxDistance=a,this.predicate=n,this.checkBounds=o,this.distance=s,this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){var r=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t))return t};do{var s=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=r(s,t),i&&(yield i);for(e=s;e<n;e++)i=r(e,a),i&&(yield i);for(t=o-1;t>=a;t--)i=r(n,t),i&&(yield i);for(e=n;e>=s;e--)i=r(e,o),i&&(yield i)}else this.predicate(this.startTile)&&(yield this.startTile)}while(this.distance++,this.distance<=this.maxDistance)}}class Wa{[ys.onSpawn](i,r){let e;if(r.rules.hasObject(i.rules.freeUnit,At.Vehicle))e=r.rules.getObject(i.rules.freeUnit,At.Vehicle);else{if(!r.rules.hasObject(i.rules.freeUnit,At.Infantry))return void console.warn(`Free unit "${i.rules.freeUnit}" is not a vehicle or infantry type.`);e=r.rules.getObject(i.rules.freeUnit,At.Infantry)}let s=r.createUnitForPlayer(e,i.owner),a;var t=new Ua(r.map.tiles,r.map.mapBounds,i.tile,i.getFoundation(),1,1,e=>{var t=0<r.map.terrain.getPassableSpeed(e,s.rules.speedType,!1)&&Math.abs(e.z-i.tile.z)<2&&!r.map.terrain.findObstacles({tile:e,onBridge:void 0},s).length;return!a&&t&&(a=e),t&&!r.map.getObjectsOnTile(e).find(e=>e.isOverlay())}).getNextTile()??a;if(!t)return i.owner.removeOwnedObject(s),void s.dispose();r.spawnObject(s,t)}}class Va{[ka.onSell](e,t){this.spawnSurvivors(e,t)}[Tr.onDestroy](e,t,i,r){r||i?.obj===e&&i.weapon?.rules.suicide||e.isVehicle()&&e.moveTrait.isMoving()||e.crashableTrait||this.spawnSurvivors(e,t)}spawnSurvivors(r,s){var t=s.rules.general.crew,e=r.owner.country.side;let i,a;if(e===qt.GDI)i=t.alliedSurvivorDivisor,a=t.alliedCrew;else{if(e!==qt.Nod)return;i=t.sovietSurvivorDivisor,a=t.sovietCrew}let n=Math.ceil(r.rules.cost*t.survivorRate/i);r.isVehicle()&&(n=Math.min(1,n));let o=[];for(let e=0;e<n;e++)(0===e||s.generateRandom()>=t.crewEscape)&&o.push(a);if(r.rules.constructionYard&&(o=[...o,s.rules.general.engineer]),0<o.length){var h,l=s.map.tiles.getInRectangle(r.tile,r.getFoundation());let i=[...l];for(h of o){var c=s.rules.getObject(h,At.Infantry);if(s.map.terrain.getPassableSpeed(r.tile,c.speedType,!r.isBuilding()&&r.onBridge,void 0,!0)){let e=s.createUnitForPlayer(c,r.owner),t=i.length?i.splice(s.generateRandomInt(0,i.length-1),1)[0]:void 0;t=t||l[s.generateRandomInt(0,l.length-1)],e.isInfantry()&&(e.position.subCell=Rs.SUB_CELLS[0]),e.veteranTrait&&r.owner.canProduceVeteran(e.rules)&&e.veteranTrait.setVeteranLevel(bs.Veteran),s.spawnObject(e,t),r.isBuilding()&&e.unitOrderTrait.addTask(new da(s,void 0,{ignoredBlockers:r.isDestroyed?void 0:[r]}))}}}}}(s=La=La||{})[s.NotBridge=0]="NotBridge",s[s.Concrete=1]="Concrete",s[s.Wood=2]="Wood";class za{static getOverlayBridgeType(e){return V(e,this.minHighBridgeConcreteId,this.maxHighBridgeConcreteId)||V(e,this.minLowBridgeConcreteId,this.maxLowBridgeConcreteId)?La.Concrete:V(e,this.minHighBridgeWoodId,this.maxHighBridgeWoodId)||V(e,this.minLowBridgeWoodId,this.maxLowBridgeWoodId)?La.Wood:La.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===La.Concrete)i=this.minLowBridgeConcreteId;else{if(e!==La.Wood)throw new Error("Not implemented");i=this.minLowBridgeWoodId}return i+(t?0:9)}static calculateHighBridgeOverlayId(e,t){let i;if(e===La.Concrete)i=this.minHighBridgeConcreteId;else{if(e!==La.Wood)throw new Error("Not implemented");i=this.minHighBridgeWoodId}return i+(t?0:1)}}za.minLowBridgeWoodId=74,za.maxLowBridgeWoodId=99,za.minLowBridgeConcreteId=205,za.maxLowBridgeConcreteId=230,za.minHighBridgeConcreteId=24,za.maxHighBridgeConcreteId=25,za.minHighBridgeWoodId=237,za.maxHighBridgeWoodId=238,za.bridgePlaceholderIds=[100,101,231,232];class Ha{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(i,r){var s=this.findClosestBridgeBounds();if(!s)throw new Error("No bridge bounds found");var e=this.bridges.findDestroyedPieceTiles(s),t=s.start.rx!==s.end.rx;let a;a=s.isHigh?za.calculateHighBridgeOverlayId(s.type,t):za.calculateLowBridgeOverlayId(s.type,t);var n,o,h=i.rules.getOverlayName(a);for(n of e){let e=i.createObject(At.Overlay,h);e.overlayId=a,e.value=0,e.position.tileElevation=s.isHigh?4:0,i.spawnObject(e,n);for(let t of this.bridges.getPieceTiles(this.bridges.getPieceAtTile(n)))if(s.isHigh){let e=i.map.getGroundObjectsOnTile(t).filter(e=>e.tile===t&&e.isUnit()&&!e.unitOrderTrait.hasTasks()&&e.rules.tooBigToFitUnderBridge);e.forEach(e=>e.unitOrderTrait.addTask(new da(i)))}else for(o of i.map.getGroundObjectsOnTile(t))o.isUnit()&&(i.map.terrain.getPassableSpeed(t,o.rules.speedType,!0)?(o.zone=_r.Ground,o.onBridge=!0):o.isDestroyed||i.destroyObject(o,{player:r}))}}demolishBridge(e,t){var i=this.getBridgePieces();if(i)for(var r of i)r.obj.isLowBridge()&&e.map.getTileZone(r.obj.tile,!0)!==_r.Water||r.obj.isDestroyed||(r.obj.deathType=Ir.Demolish,e.destroyObject(r.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 Ga{constructor(){this.isActive=!1,this.produceCashCooldown=0}[ys.onSpawn](e){e.owner.playable&&(this.isActive=!0)}[fs.onChange](e,t){!t.playable&&e.owner.playable&&(e.owner.credits+=e.rules.produceCashStartup,this.isActive=!0,this.produceCashCooldown=e.rules.produceCashDelay)}[Or.onTick](e){this.isActive&&(this.produceCashCooldown--,this.produceCashCooldown<=0&&(this.produceCashCooldown=e.rules.produceCashDelay,e.owner.credits+=e.rules.produceCashAmount))}}class $a{constructor(){this.linkedDamageHandled=!1}[br.onDamage](e,t,i,r){if(!this.linkedDamageHandled){var s=Math.floor(i/2);if(s)for(var a of t.map.tiles.getAllNeighbourTiles(e.tile))if(a.landType===Yt.Wall){let e=t.map.getObjectsOnTile(a).find(e=>(e.isBuilding()||e.isOverlay())&&e.wallTrait);e.wallTrait.linkedDamageHandled=!0,e.healthTrait.inflictDamage(s,r,t),e.wallTrait.linkedDamageHandled=!1,e.healthTrait.health||t.destroyObject(e,r)}}}}function qa(i,r,s,a,n){let o=[];n=n||((e,t)=>{o.push({x:e,y:t})});var e=s-i,t=a-r,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=r;u<0?e>=s:e<=s;e+=u)n(e,t),c+=l,c<<1>=h&&(t+=d,c-=h);else for(let e=i,t=r;d<0?t>=a:t<=a;t+=d)n(e,t),c+=h,c<<1>=l&&(e+=u,c-=l);return o}const Za=e=>void 0!==e.position;class Qa{constructor(e,t){this.tiles=e,this.tileOccupation=t}hasLineOfSight(e,t,i){var r=i.warhead.rules.wall||!i.projectileRules.subjectToWalls,s=i.projectileRules.subjectToCliffs,a=i.rules.spawner;let n=0,o=!1;if(!r||s||a){var h,l,c=Za(e)?e.tile:e,t=Za(t)?t.tile:t;for({x:h,y:l}of qa(c.rx,c.ry,t.rx,t.ry)){var u=this.tiles.getByMapCoords(h,l);if(!r&&u.landType===Yt.Wall)return!1;if(s)if(u.landType===Yt.Cliff){if(u.z>c.z)return!1;o=!0}else{if(u.z>c.z&&o)return!1;o=!1}if(a&&n<2&&this.tileOccupation.getBridgeOnTile(u)?.isHighBridge())return!1;n++}}return!0}}var Xa=__webpack_require__(949);class Ya extends ca{constructor(e,t,i,r){super(e,t instanceof Cs?t.isBuilding()?t.centerTile:t.tile:t,i,{pathFinderIgnoredBlockers:t instanceof Cs?[t]:void 0}),this.target=t,this.weapon=r,this.recalcMinRange=!0,this.cancelRequested=!1,this.bomberInitialLock=!1,this.rangeHelper=new Ws(e.map.tileOccupation),this.losHelper=new Qa(e.map.tiles,e.map.tileOccupation)}onStart(i){let e=this.target,r=this.game.map;if(e instanceof Cs&&e.isBuilding()&&i.rules.movementZone!==ii.Fly){let t=e.tile;var s=e instanceof Cs?e.getFoundation():{width:1,height:1},s=new xr(r.tiles,r.mapBounds,t,s,1,5,e=>0<r.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&Math.abs(e.z-t.z)<2).getNextTile();s&&this.rangeHelper.tileDistance(e,s)>Math.SQRT2&&this.updateTarget(s,!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===ii.Fly&&e.rules.locomotor===ti.Aircraft&&e.rules.fighter&&1<this.weapon.projectileRules.iniRot}isBombingRun(e){return e.rules.movementZone===ii.Fly&&e.rules.locomotor===ti.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 sa(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!==_r.Air&&this.target instanceof Cs&&this.game.map.tileOccupation.isTileOccupiedBy(e,this.target)&&(!this.target.isUnit()||this.target.tile===e&&this.target.moveTrait.moveState!==ps.Moving))return!1;if(t.zone!==_r.Air){if(!super.canStopAtTile(t,e,i))return!1}else if(this.game.map.tileOccupation.getAirObjectsOnTile(e).filter(e=>e.isUnit()&&e.moveTrait.moveState!==ps.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===_r.Air?e.position.computeSubCellOffset(e.position.desiredSubCell):e.position.getTileOffset(),{minRange:r,range:s}=this.rangeHelper.computeWeaponRangeVsTarget(t,this.target,this.weapon,this.game.rules),i=mr.tile3dToWorld(t.rx+i.x/mr.LEPTONS_PER_TILE,t.ry+i.y/mr.LEPTONS_PER_TILE,t.z+e.position.tileElevation);return(e.isUnit()&&e.rules.movementZone===ii.Fly?this.rangeHelper.isInRange2(i,this.target,r,s):this.rangeHelper.isInRange3(i,this.target,r,s))&&this.losHelper.hasLineOfSight(t,this.target,this.weapon)}findRelocationTile(t,i,r){if(r.rules.movementZone!==ii.Fly)return super.findRelocationTile(t,i,r);{i=this.game.map;let e=new sa(i.tiles,i.mapBounds,t,1,this.game,e=>this.isCancelling()||this.isCloseEnoughToDest(r,e));return e.getNextTile()}}retarget(e,t){var i=e instanceof Cs?e.isBuilding()?e.centerTile:e.tile:e;this.updateTarget(i,t),this.target=e,this.options?.ignoredBlockers&&(this.options.ignoredBlockers=e instanceof Cs?[e]:void 0),this.options??(this.options={}),this.options.pathFinderIgnoredBlockers=e instanceof Cs?[e]:void 0,this.recalcMinRange=!0}onTick(r){if(this.recalcMinRange){this.recalcMinRange=!1;var s=this.findMinRangeRelocationTile(r,this.targetTile);if(s!==this.targetTile){if(!s)return this.cancel(),!1;this.updateTarget(s,!!s.onBridgeLandType)}}if(this.shouldAirStrafe(r)&&!this.isCancelling()&&(this.updateTarget(this.target instanceof Cs?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target,!1),!this.isAirStrafeCloseEnough(r)||(n=this.findStrafeDestination(r,this.targetTile))&&this.updateTarget(n,!1)),this.isBombingRun(r)&&!this.isCancelling()&&(!r.ammo||this.weapon.getBurstsFired()||this.bomberInitialLock)&&!this.bomberManeuverTile){this.bomberInitialLock=!1;let e=r.position.getMapPosition();s=this.target instanceof Cs?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target;let t=new Xa.Vector2(s.rx+.5,s.ry+.5).clone().multiplyScalar(mr.LEPTONS_PER_TILE).sub(e),i=e.clone().add(t.setLength(t.length()+7*mr.LEPTONS_PER_TILE));var a,n=i.multiplyScalar(1/mr.LEPTONS_PER_TILE).floor();for(a of qa(n.x,n.y,r.tile.rx,r.tile.ry)){var o=this.game.map.tiles.getByMapCoords(a.x,a.y);if(o){this.bomberManeuverTile=o;break}}this.bomberManeuverTile??(this.bomberManeuverTile=s),this.updateTarget(this.bomberManeuverTile,!1)}return this.bomberManeuverTile&&this.bomberCanReturn(r.tile)&&(this.bomberManeuverTile=void 0),this.cancelRequested&&(this.bomberManeuverTile||(this.cancelRequested=!1,this.cancel())),this.isBombingRun(r)&&this.isCancelling()?(this.forceCancel(r),!0):super.onTick(r)}forceCancel(e){return!this.bomberManeuverTile&&super.forceCancel(e)}findMinRangeRelocationTile(e,t){var{minRange:i,range:r}=this.rangeHelper.computeWeaponRangeVsTarget(e,this.target,this.weapon,this.game.rules);return e.rules.locomotor===ti.Chrono?this.rangeHelper.isInRange(e,this.target,r-1,r,this.weapon.rules.cellRangefinding)?t:this.findTileInRange(e,t,r-1,2*r)??t:this.rangeHelper.isInRange(e,this.target,i,Number.POSITIVE_INFINITY,this.weapon.rules.cellRangefinding)?t:this.findTileInRange(e,t,2*i,r-i)}findTileInRange(t,e,i,r){let s=this.game.map;var a,i=new Xa.Vector2(t.tile.rx-e.rx,t.tile.ry-e.ry).setLength(i).floor().add(new Xa.Vector2(e.rx,e.ry));let n;for(a of qa(i.x,i.y,e.rx,e.ry))if(n=s.tiles.getByMapCoords(a.x,a.y),n)break;if(n){let e=new xr(s.tiles,s.mapBounds,n,{width:1,height:1},0,r,e=>this.rangeHelper.isInWeaponRange(t,this.target,this.weapon,this.game.rules,e)&&this.losHelper.hasLineOfSight(e,this.target,this.weapon)&&0<s.terrain.getPassableSpeed(e,t.rules.speedType,!!e.onBridgeLandType)&&!s.terrain.findObstacles({tile:e,onBridge:!!e.onBridgeLandType},t).length);return e.getNextTile()}}}class Ka{tick(e,t){this.tickChildren(e,t)}startTask(e,t){if(e.status!==Sr.NotStarted)throw new Error(`Attempted to start a task with status ${e.status}`);e.status=Sr.Running,e.onStart(t)}tickTask(e,t){let i=this.tickChildren(e.children,t);var r=e.children.find(e=>e.blocking);if(!i&&r)return!1;if(!t.isSpawned)return!1;if(e.status===Sr.NotStarted)throw new Error("Attempted tick on a non-started task");if(e.isRunning()||e.isCancelling()){var s=e.isCancelling(),a=!!e.waitingForChildrenToFinish||e.onTick(t);e.children.length&&!r&&a&&(i=e.children.every(e=>e.status===Sr.Cancelled||e.status===Sr.Finished),e.waitingForChildrenToFinish=!i);a=a&&i;return a&&(e.onEnd(t),e.status=s?Sr.Cancelled:Sr.Finished),a}return!0}tickChildren(r,s){let a=!0;if(r.length){let t=new Set,i;for(;s.isSpawned&&(i=r.find(e=>!t.has(e)));){let e;if(i.status===Sr.NotStarted&&this.startTask(i,s),i.status===Sr.Running||i.status===Sr.Cancelling)e=!0===this.tickTask(i,s);else{if(i.status!==Sr.Cancelled)throw new Error(`Unhandled task status ${Sr[i.status]}`);e=!0}if(e){var n=r.indexOf(i);-1!==n&&r.splice(n,1)}else{if(a=!1,i.blocking)break;t.add(i)}}}return a}}class Ja{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===Yt.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:mr.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)}}var en,tn=__webpack_require__(949);(s=en=en||{})[s.Idle=0]="Idle",s[s.CheckRange=1]="CheckRange",s[s.PrepareToFire=2]="PrepareToFire",s[s.FireUp=3]="FireUp",s[s.Firing=4]="Firing",s[s.JustFired=5]="JustFired";class rn{constructor(e,t){this.disabled=!1,this.attackState=en.Idle,this.passiveScanCooldownTicks=0,this.taskRunner=new Ka,this.distributedFireHistory=new Map,this.rangeHelper=new Ws(t),this.losHelper=new Qa(e,t)}isIdle(){return this.attackState===en.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}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===qt.GDI?e.primaryWeapon:e.secondaryWeapon??e.primaryWeapon:void 0:e.isBuilding()&&e.overpoweredTrait?e.overpoweredTrait.getWeapon():e.primaryWeapon;return i}selectWeaponVersus(e,t,i,r=!1,s=!1){var a=t.tile;const n=t instanceof Ja?t.obj:t;t=this.getAvailableWeapons(e,s,n?.isOverlay()||r&&!n);return this.selectWeaponFromList(e,n,a,t,i,r,s,!1)}selectWeaponFromList(e,t,i,r,s,a,n,o){if((!t?.isInfantry()&&!t?.isVehicle()||!t.disguiseTrait||this.canAttackThroughDisguise(e,t,t.disguiseTrait,s,a,n,o))&&(t?.isBuilding()&&t.overpoweredTrait&&t.owner===e.owner&&r.find(e=>e.warhead.rules.electricAssault)&&(r=r.filter(e=>e.warhead.rules.electricAssault)),!(n&&t?.isAircraft()&&t.missileSpawnTrait&&t.zone!==_r.Air))){var h=t?.isTechno()?t.rules.armor:void 0;for(const l of r)if(l.targeting.canTarget(t,i,s,a,n)&&(void 0===h||this.checkArmor(l.warhead.rules,h,n)))return l}}getAvailableWeapons(e,t,i){let r;var s;return r=(e.isInfantry()||e.isVehicle())&&e.rules.deployFire&&e.armedTrait?(s=e.armedTrait.getDeployFireWeapon(),[e.deployerTrait?.isDeployed()?s.rules.areaFire?void 0:s:s===e.secondaryWeapon?e.primaryWeapon:e.secondaryWeapon]):e.isBuilding()&&e.garrisonTrait?e.garrisonTrait.isOccupied()?[e.owner.country.side===qt.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],r.filter(e=>e&&!e.rules.neverUse)}canAttackThroughDisguise(e,t,i,r,s,a,n){if(!s&&i.hasTerrainDisguise()&&!r.areFriendly(e,t)&&!e.owner.sharedDetectDisguiseTrait?.has(t))return!1;if(a){if(n&&t.moveTrait.isIdle()&&!e.rules.detectDisguise&&!r.areFriendly(t,e))return!1;i=i.getDisguise();if(i?.owner&&!e.rules.detectDisguise&&!e.owner.sharedDetectDisguiseTrait?.has(t)&&(i.owner===e.owner||r.alliances.areAllied(e.owner,i.owner)))return!1}return!0}checkArmor(e,t,i){var r=e.ivanBomb||e.bombDisarm?1:e.verses.get(t);return void 0===r?(console.warn(`Unhandled ArmorType ${ri[t]} in warhead ${e.name}`),!1):!(100*r<=(i?1:0))}createAttackTask(e,t,i,r,s){return new an(e,e.createTarget(t,i),r,s)}[Or.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 an?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===ii.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,r;!o&&a.guardMode&&e&&a.owner.isCombatant()&&(t=a.armedTrait?.computeGuardScanRange(e),i=a.guardArea?.tile,r=50);let s=!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===ii.Fly&&!a.guardMode||a.rules.movementZone!==ii.Fly&&e.isUnit()&&e.zone===_r.Air||(a.isInfantry()||a.isVehicle())&&!!a.disguiseTrait||!a.owner.isCombatant(),disallowTurning:o,leashTiles:r,passive:!0});o?this.opportunityFireTask=l:a.unitOrderTrait.addTask(l),s=!0,o||!a.guardMode||a.guardArea||(a.guardArea={tile:a.tile,onBridge:!!a.isUnit()&&a.onBridge})}}s||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),s=!0)),!s&&!o&&a.guardArea&&a.isUnit()&&a.moveTrait&&!a.moveTrait.isDisabled()&&a.guardArea.tile!==a.tile&&a.unitOrderTrait.addTasks(new ca(n,a.guardArea.tile,a.guardArea.onBridge),new ss(()=>{[gs.Success,gs.CloseEnough].includes(a.moveTrait.lastMoveResult)||a.resetGuardModeToIdle(),a.guardArea=void 0}))}}}[br.onDamage](e,t,i,r){this.isDisabled()||!this.retaliateTarget&&!this.opportunityFireTask&&r&&r.obj&&r.weapon&&this.shouldRetaliate(e,t,i,r.obj,r.weapon.warhead)&&(this.retaliateTarget=r.obj)}[Cr.onBeforeTeleport](e,t,i,r){r||(this.attackState=en.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;if(e.isUnit()&&e.rules.opportunityFire){if(e.unitOrderTrait.hasTasks()&&e.unitOrderTrait.getTasks()[0].preventOpportunityFire)return!1}else if(e.unitOrderTrait.hasTasks())return!1;return!0}shouldRetaliate(e,t,i,r,s){return!(i<1||t.areFriendly(e,r)||!e.rules.canRetaliate||!e.primaryWeapon||s.rules.temporal||r.rules.missileSpawn||e.unitOrderTrait.hasTasks()||!t.isValidTarget(r)||(r.isInfantry()||r.isVehicle())&&r.disguiseTrait&&!e.rules.detectDisguise||e.mindControllerTrait?.isAtCapacity()||!this.selectWeaponVersus(e,r,t,!1)||(e.isBuilding()||r.isBuilding()?this.rangeHelper.tileDistance(e,r):this.rangeHelper.distance2(e,r)/mr.ISO_TILE_SIZE)>e.sight)}scanForTarget(e,t,i,r,s,a=!1){let n={},o=Number.NEGATIVE_INFINITY;var h=this.getAvailableWeapons(e,!0,!1),t=r??(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)&&(r?this.rangeHelper.isInRange(e,u,c.minRange,r,c.rules.cellRangefinding)&&(!s||this.rangeHelper.isInRange2(s,u,0,r)):this.rangeHelper.isInWeaponRange(e,u,c,i.rules))&&(a||this.losHelper.hasLineOfSight(e,u,c))&&(l=this.rangeHelper.distance3(e,u)/mr.ISO_TILE_SIZE,(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 r=e.getFoundation();const s=new tn.Vector2(e.tile.rx,e.tile.ry),a=new tn.Vector2(e.tile.rx+r.width-1,e.tile.ry+r.height-1);s.addScalar(-t),a.addScalar(t);t=new tn.Box2(s,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,r,s){let a=[e.primaryWeapon,e.secondaryWeapon].filter(Pa).map(e=>e.warhead.rules.verses.get(t.rules.armor)??0).reduce((e,t)=>Math.max(e,t),0)*s.targetEffectivenessCoefficientDefault;return e.attackTrait?.currentTarget?.obj===t&&(a*=-1),a+=e.rules.specialThreatValue*s.targetSpecialThreatCoefficientDefault,a+=(i.warhead.rules.verses.get(e.rules.armor)??0)*s.myEffectivenessCoefficientDefault,a+=e.healthTrait.health/100*s.targetStrengthCoefficientDefault,a+=r*s.targetDistanceCoefficientDefault,t.rules.distributedFire&&(a-=1e6*(this.distributedFireHistory.get(e)??0)),t.rules.vhpScan===ni.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()}}var sn=__webpack_require__(949);class an extends Rr{constructor(e,t,i,r={}){super(),this.game=e,this.target=t,this.weapon=i,this.options=r,this.moveExecuted=!1,this.moveAttempts=0,this.rangeCheckCooldown=0,this.lastInRangeTargetPosition=new sn.Vector3,this.lastInRangeSelfPosition=new sn.Vector3,this.initialIndirectTarget=!1,this.forceDropTarget=!1,this.rangeHelper=new Ws(e.map.tileOccupation),this.losHelper=new Qa(e.map.tiles,e.map.tileOccupation),this.targetLinesConfig={pathNodes:[]},this.updateTargetLines(this.target,!0)}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,r;t.attackTrait.attackState=en.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:r}=this.findReachableMeleePosition(this.target.tile,!!this.target.getBridge(),{width:1,height:1},t),!i&&r&&(this.lastValidTargetPosition=r,this.updateTargetLines(this.game.createTarget(r.onBridge,r.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:r}=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,r&&(this.lastValidTargetPosition=r,this.updateTargetLines(this.game.createTarget(r.onBridge,r.tile),!1))))),this.rangeHelper.isInWeaponRange(t,this.target.obj??this.target.tile,this.weapon,this.game.rules)&&t.isUnit()&&t.rules.movementZone===ii.Fly&&t.zone!==_r.Air&&(t.rules.hoverAttack||t.isAircraft())&&this.children.push(new ca(this.game,t.tile,!1).setCancellable(!1))}else this.cancel()}findReachableMeleePosition(r,e,t,s){let i=this.game.map,a=i.tileOccupation,n=e?a.getBridgeOnTile(r):void 0,o=new Ds(i),h=s.rules.movementZone===ii.Fly,l=(e,t)=>h||0<i.terrain.getPassableSpeed(e,s.rules.speedType,!!t)&&o.isEligibleTile(e,t,n,r)&&!i.terrain.findObstacles({tile:e,onBridge:t},s).length,c,u=new xr(i.tiles,i.mapBounds,r,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(s,r,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=en.Idle,e.attackTrait.currentTarget=void 0;var t=this.game.rules.general.prism.type;e.isBuilding()&&e.name===t&&this.weapon.type!==si.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!==ii.Fly)return!1;if(!this.cancellable||this.children.some(e=>!e.cancellable))return!1;if(this.status===Sr.Running||this.status===Sr.Cancelling){if(this.children.filter(e=>e instanceof ca).some(e=>!e.forceCancel(t)))return!1;this.onEnd(t),(t.isInfantry()||t.isVehicle())&&(t.isFiring=!1)}return this.status=Sr.Cancelled,!0}onTick(t){let i=t.attackTrait;(t.isInfantry()||t.isVehicle())&&i.attackState!==en.Firing&&(t.isFiring=!1);let r=this.target.obj,s=this.children.find(e=>e instanceof Ya);if(this.isCancelling()&&i.attackState!==en.FireUp)return!t.airSpawnTrait?.isLaunchingMissiles()&&(s?.cancel(),!0);let a=!1;if(i.attackState===en.FireUp){if(i.isDisabled())return!0;i.attackState=en.Firing,a=!0}if(i.attackState===en.Firing){if(this.initialIndirectTarget&&!this.game.map.getObjectsOnTile(this.target.tile).find(e=>e.isOverlay()&&!e.isBridgePlaceholder()||e.isTerrain()))return this.cancel(),this.onTick(t);if(a){var n=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(t,n,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(t,n,this.weapon))return i.attackState=en.CheckRange,this.onTick(t)}if(this.weapon.rules.limboLaunch){if((r?.isVehicle()||r?.isAircraft())&&r.parasiteableTrait?.isInfested())return!0;if(t.rules.movementZone!==ii.Fly&&r?.isUnit()&&r.zone===_r.Air)return!0}if(this.target.tile.onBridgeLandType&&t.tile.onBridgeLandType&&t.isUnit()&&(this.game.map.tileOccupation.getBridgeOnTile(this.target.tile)?.isHighBridge()||this.game.map.tileOccupation.getBridgeOnTile(t.tile)?.isHighBridge()))if((r?r.isUnit()&&(r.zone===_r.Air||r.onBridge):this.target.isBridge())!==(t.zone===_r.Air||t.onBridge)&&this.game.map.bridges.findHighBridgeBoundary(t.tile)?.tile===this.game.map.bridges.findHighBridgeBoundary(this.target.tile)?.tile)return!0;let e=1;n=this.game.rules.general.prism.type;if(t.isBuilding()&&t.name===n&&this.weapon.type!==si.Secondary&&(n=this.countSupportBeamsAndFireDownTowers(t,n),e=1+n*this.game.rules.general.prism.supportModifier),this.weapon.rules.spawner&&(t.isVehicle()||t.isAircraft())&&t.parasiteableTrait?.isParalyzed())return!0;if(0===t.ammo)return t.isAircraft()&&(t.rules.fighter||t.rules.spawned)&&s?.cancel(),!0;if(this.weapon.fire(this.target,this.game,e),this.weapon.rules.limboLaunch){if(s){if(!s.forceCancel(t))throw new Error("Force cancel was unsuccessful");t.moveTrait.lastTargetOffset=void 0,t.moveTrait.lastVelocity=void 0}return!0}return this.weapon.rules.fireOnce?!0:!(!this.options.passive||!t.rules.distributedFire)||(i.attackState=en.JustFired,!1)}if(i.attackState===en.JustFired)return i.attackState=en.PrepareToFire,this.onTick(t);this.needsTargetUpdate&&(this.target=this.needsTargetUpdate,r=this.target.obj,this.needsTargetUpdate=void 0,this.onTargetChange(t),r||s?.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(t));let o=this.game.isValidTarget(r)&&!this.shouldDropTarget(r);if(o){let e=this.weapon.targeting.canTarget(r,this.target.tile,this.game,!!this.options.force,!!this.options.passive);if(!e||!t.armedTrait.isEquippedWithWeapon(this.weapon)){var h=i.selectWeaponVersus(t,this.target,this.game,this.options.force,this.options.passive);if(h){if(this.setWeapon(h),i.attackState!==en.CheckRange)return i.attackState=en.CheckRange,this.onTick(t);e=!0}else e=!1}o=e}if(o&&(l=this.lastTargetTpCheck,r?.isUnit()&&l&&r.moveTrait.lastTeleportTick>=l?(o=!1,this.rangeCheckCooldown=0):this.lastTargetTpCheck=this.game.currentTick),o&&r&&(this.lastValidTargetPosition={tile:r.tile,onBridge:this.target.getBridge()}),o||(this.targetLinesConfig.isAttack=!1),i.attackState===en.CheckRange){if(0<this.rangeCheckCooldown)return this.rangeCheckCooldown--,!1;let e=this.target.obj?o?this.target.obj:this.lastValidTargetPosition.tile:this.target.tile;var l=this.target.obj?o?this.target.obj.isBuilding()?this.target.obj.centerTile:this.target.obj.tile:this.lastValidTargetPosition.tile:this.target.tile;if(!this.rangeHelper.isInWeaponRange(t,e,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(t,e,this.weapon)||t.isUnit()&&t.rules.balloonHover&&!t.rules.hoverAttack&&!s&&t.tile!==l||t.isAircraft()&&this.weapon.projectileRules.iniRot<=1&&!s){if(!t.isUnit()||this.options.holdGround)return!0;if(s){if(s.target!==this.target.obj||o)if(o&&this.target.obj&&this.rangeHelper.tileDistance(this.target.obj,this.lastSelfMoveTargetTile)>this.weapon.range)s.retarget(this.target.obj,!!this.target.getBridge()),this.lastSelfTileBeforeMove=t.tile,this.lastSelfMoveTargetTile=this.target.obj?.tile??this.target.tile;else{if(void 0!==this.options.leashTiles&&this.rangeHelper.tileDistance(this.initialSelfPosition.tile,t.tile)>this.options.leashTiles)return s.cancel(),!0;var c=e instanceof Cs&&e.isUnit()?e.moveTrait.baseSpeed:0,u=Math.ceil((this.rangeHelper.tileDistance(t,e)-(this.weapon.range+1))/((t.moveTrait.baseSpeed+c)/mr.LEPTONS_PER_TILE));0<u&&(this.rangeCheckCooldown=Math.min(is.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),i.currentTarget=e,s.retarget(e.tile,e.isBridge()),this.updateTargetLines(e,!1)}return!1}if(!t.moveTrait||t.moveTrait.isDisabled())return!0;if(this.isCancelling())return!0;if(t.tile===this.lastSelfTileBeforeMove||this.moveExecuted&&t.moveTrait.lastMoveResult===gs.Fail?this.moveAttempts++:this.moveAttempts=0,this.weapon.rules.limboLaunch&&t.rules.defaultToGuardArea&&r&&this.moveExecuted&&t.moveTrait.lastMoveResult===gs.Fail&&this.rangeHelper.isInRange(t,r,0,t.armedTrait.computeGuardScanRange(this.weapon),!0))return!0;if(3<this.moveAttempts)return!0;0<this.moveAttempts&&this.children.push(new rs(1/60));c=e,u=r&&!o?this.lastValidTargetPosition.onBridge:this.target.getBridge();return s=new Ya(this.game,c,!!u,this.weapon),s.blocking=!1,this.children.push(s),this.moveExecuted=!0,this.lastSelfTileBeforeMove=t.tile,this.lastSelfMoveTargetTile=c instanceof Cs?c.tile:c,this.onTick(t)}if(this.moveExecuted=!1,this.moveAttempts=0,s&&(t.rules.balloonHover&&!t.rules.hoverAttack||t.rules.fighter||t.rules.spawned||t.rules.movementZone===ii.Fly&&!this.rangeHelper.isInRange2(t,this.target.obj??this.target.tile,this.weapon.minRange,this.weapon.range-1)||s.cancel()),s&&(t.isInfantry()&&!t.rules.balloonHover||this.weapon.rules.spawner))return!1;if(s?.children.some(e=>!e.cancellable)&&this.weapon.rules.limboLaunch)return!1;if(s&&s.shouldAirStrafe(t)&&this.target.obj?.isUnit()&&this.target.obj.moveTrait.isMoving()&&1<this.weapon.range&&!this.rangeHelper.isInRange2(t,this.target.obj,this.weapon.minRange,this.weapon.range-1))return!1;i.attackState=en.PrepareToFire}if(i.attackState!==en.PrepareToFire)return!1;if(!o||i.isDisabled())return s?.cancel(),!0;u=this.target.getWorldCoords(),c=t.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),i.attackState=en.CheckRange,this.onTick(t);if(!(this.weapon.rules.omniFire||t.rules.omniFire&&t.rules.fighter)){var c=(new sn.Vector3).copy(u).sub(c),e=Zr.fromMapCoords(new sn.Vector2(c.x,c.z)),c=this.weapon.projectileRules.rot?45:11.25;if((t.isVehicle()||t.isBuilding())&&t.turretTrait){if(t.turretTrait.desiredFacing=e,Math.abs(e-t.turretTrait.facing)>=c)return!1}else if(Math.abs(e-t.direction)>=c){if(t.isAircraft())return t.direction=Zr.tick(t.direction,e,t.rules.rot).facing,!1;if(s)return!1;if(t.isVehicle())return!!this.options.disallowTurning||(this.children.push(new Gs(e)),!1);t.direction=e}}if(!this.losHelper.hasLineOfSight(t,this.target.obj||this.target.tile,this.weapon))return i.attackState=en.CheckRange,this.onTick(t);if(i.isOnCooldown(t))return!1;if(this.weapon.warhead.rules.temporal&&t.temporalTrait.getTarget()===this.target.obj)return!1;if(this.weapon.rules.suicide&&this.weapon.type!==si.DeathWeapon)return this.game.destroyObject(t,{player:t.owner,obj:t,weapon:this.weapon}),!0;e=this.game.rules.general.prism.type;return t.isBuilding()&&t.name===e&&this.weapon.type!==si.Secondary&&this.fireUpPrismSupportTowers(t,e),(t.isInfantry()||t.isVehicle())&&(t.isFiring=!0),t.art.fireUp?(this.children.push(new ts(t.art.fireUp).setCancellable(!1)),i.attackState=en.FireUp,!1):(i.attackState=en.Firing,this.onTick(t))}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(At.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,r=t.owner.getOwnedObjectsByType(At.Building).filter(e=>e.name===i&&e.attackTrait?.currentTarget?.obj===t);for(e of r)e.unitOrderTrait.getCurrentTask()?.cancel();return Math.min(this.game.rules.general.prism.supportMax,r.length)}getTargetLinesConfig(){return this.targetLinesConfig}}class nn{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()}[Or.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 an&&((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 on{constructor(e,t){this.target=e,this.from=t,this.type=vr.UnitRepairFinish}}class hn{constructor(e){this.target=e,this.type=vr.UnitRepairStart}}var ln,cn,un,dn=__webpack_require__(949);(s=ln=ln||{})[s.Idle=0]="Idle",s[s.Repairing=1]="Repairing";class pn{constructor(){this.status=ln.Idle,this.cooldownTicks=0,this.lastRepairTickSuccessful=!1}[ys.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))}[Or.onTick](t,i){if(t.dockTrait&&(!t.rules.needsEngineer||t.owner.playable))if(!t.dockTrait.hasDockedUnits()||t.dockTrait.getDockedUnits().some(e=>e.zone===_r.Air)||t.poweredTrait&&!t.poweredTrait.isPoweredOn())this.status=ln.Idle;else if(this.cooldownTicks<=0){var r,s,a=i.rules.general.repair,a=t.rules.unitReload?a.reloadRate:a.uRepairRate;this.cooldownTicks+=is.BASE_TICKS_PER_SECOND*a*60;let e=!1;for(r of t.dockTrait.getDockedUnits())r.zone!==_r.Air&&(r.healthTrait.health<100&&i.areFriendly(r,t)?(this.tickRepair(r,i,t)&&(e=!0),!e||this.status!==ln.Idle&&this.lastRepairTickSuccessful||t.helipadTrait||i.events.dispatch(new hn(r))):((s=t.rallyTrait.findRallyNodeForUnit(r,i.map))&&(t.dockTrait.undockUnit(r),r.unitOrderTrait.addTask(new ca(i,s.tile,!!s.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))),t.helipadTrait||i.events.dispatch(new on(r,t))));this.lastRepairTickSuccessful=e,this.status=e?ln.Repairing:ln.Idle}else this.cooldownTicks--}tickRepair(e,t,i){var r=t.rules.general.repair,s=Math.floor(r.repairStep),a=r.repairPercent;let n;if(a){r=a*e.purchaseValue/e.healthTrait.maxHitPoints,a=Math.min(i.owner.credits,Math.max(1,Math.floor(r*s)));if(n=r&&a?Math.floor(a/r):s,!a)return!1;i.owner.credits-=a}else n=s;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 dn.Vector2(e.tile.rx,e.tile.ry+i.height);return t.tiles.getByMapCoords(i.x,i.y)??e.tile}}class gn{getRallyPoint(){return this.rallyPoint}changeRallyPoint(e,t,i){i=this.findValidRallyPoint(t,e,i.map);i&&(this.rallyPoint=i)}findValidRallyPoint(i,e,r){let t=new xr(r.tiles,r.mapBounds,e,{width:1,height:1},0,20,e=>i.rules.naval===(e.terrainType===Xt.Water)&&!r.tileOccupation.isTileOccupiedBy(e,i)),s=t.getNextTile();if(!s&&i.factoryTrait?.type===Gi.NavalUnitType){var{width:a,height:n}=i.getFoundation();for(let t=0;t<a;t++)for(let e=0;e<n;e++){var o=r.tiles.getByMapCoords(i.tile.rx+t,i.tile.ry+e);if(0<r.terrain.getPassableSpeed(o,Kt.Float,!1)){s=o;break}}}return s}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,r,s){let a=i.rules.naval?void 0:r.tileOccupation.getBridgeOnTile(e),n=i.rules.movementZone===ii.Fly,t=new xr(r.tiles,r.mapBounds,e,{width:1,height:1},0,5,e=>{var t=!a||a.isHighBridge()?r.tileOccupation.getBridgeOnTile(e):void 0;return!((n?[]:r.terrain.findObstacles({tile:e,onBridge:t},i)).length||s&&r.getObjectsOnTile(e).find(e=>e.isBuilding()&&!e.isDestroyed)||!(n||0<r.terrain.getPassableSpeed(e,i.rules.speedType,!!t)))});return t.getNextTile()??e}}class mn{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 fn{constructor(){this.timer=new mn}hasCharge(){return this.timer.isActive()}setCharge(e,t){this.hasCharge()||(this.timer.setActiveFor(e),this.attackerInfo=t)}[Or.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=Ir.Demolish,t.destroyObject(e,this.attackerInfo,!0))))}}class yn{[fs.onChange](e,t,i){this.checkAircraftsForPlayer(t,i)}[ws.onUnspawn](e,t){this.checkAircraftsForPlayer(e.owner,t)}checkAircraftsForPlayer(e,t){let i=t.rules.general.padAircraft;var r;for(r of e.getOwnedObjectsByType(At.Aircraft).filter(e=>i.includes(e.name)))r.airportBoundTrait&&(r.airportBoundTrait.preferredAirport=void 0)}}class wn{[Or.onTick](t,i){if(t.dockTrait&&t.dockTrait.hasDockedUnits()&&!t.dockTrait.getDockedUnits().every(e=>!this.canReloadUnit(e)))if(void 0===this.cooldownTicks&&(this.cooldownTicks=is.BASE_TICKS_PER_SECOND*i.rules.general.repair.reloadRate*60),this.cooldownTicks<=0){this.cooldownTicks=is.BASE_TICKS_PER_SECOND*i.rules.general.repair.reloadRate*60;let e=t.dockTrait.getDockedUnits();var r;for(r of 0===e[0].ammo?e.slice(0,1):e)this.canReloadUnit(r)&&r.ammoTrait.ammo++}else this.cooldownTicks--}canReloadUnit(e){return!(!e.ammoTrait||!e.rules.manualReload||e.ammoTrait.isFull()||e.zone===_r.Air)}}class Tn extends xa{constructor(e){super(new rs(e),new ss(e=>e.buildStatus=Cn.Ready)),this.cancellable=!1}}class bn{constructor(e){this.name=e}getSuperWeapon(e){return e.owner.superWeaponsTrait?.get(this.name)}[ys.onSpawn](e,t){this.addSuperWeaponToPlayerIfNeeded(e.owner,t)}[ws.onUnspawn](e,t){this.removeSuperWeaponFromPlayerIfNeeded(e.owner)}[fs.onChange](e,t,i){this.removeSuperWeaponFromPlayerIfNeeded(t),this.addSuperWeaponToPlayerIfNeeded(e.owner,i)}addSuperWeaponToPlayerIfNeeded(t,i){if(!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(At.Building).some(e=>e.superWeaponTrait?.name===this.name)||t.remove(this.name))}}(s=cn=cn||{})[s.Unexplored=0]="Unexplored",s[s.TemporaryReveal=1]="TemporaryReveal",s[s.Explored=2]="Explored",un=un||{},un[un.Darken=8]="Darken";class vn{constructor(){this.invalidations=new Map,this.temporaryReveals=new Map,this.fullInvalidation=!1,this._onChange=new va}get onChange(){return this._onChange.asEvent()}fromTiles(e){var t,i=this.size=e.getMapSize();this.tiles=new Uint8Array(i.width*i.height),this.tiles.fill(cn.Unexplored),this.tileElevation=new Uint8Array(i.width*i.height);for(t of e.getAll())this.tileElevation[t.rx+t.ry*i.width]=t.z;return this}clone(){let e=new vn;return e.tiles=this.tiles.slice(),e.size=this.size,e.tileElevation=this.tileElevation,e}copy(e){this.tiles=e.tiles.slice(),this.size=e.size,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){return this.getShroudType(e)===cn.Unexplored}getShroudType(e){return 7&this.tiles[e.rx+e.ry*this.size.width]}isFlagged(e,t){return 0!=(this.tiles[e.rx+e.ry*this.size.width]&t)}getShroudTypeByCoords(e,t){return 7&this.tiles[e+t*this.size.width]}invalidateFull(){this.fullInvalidation=!0}invalidate(e,t,i){let r=this.invalidations.get(e);r||(r={centerTile:e,elevation:0,radius:0},this.invalidations.set(e,r)),r.elevation=Math.max(r.elevation,t),r.radius=Math.max(r.radius,i)}revealFrom(e){var t=e.sight;t&&this.invalidate(e.tile,e.tileElevation+e.tile.z,t)}revealAround(e,t){this.invalidate(e,Number.POSITIVE_INFINITY,t)}unrevealAround(e,t){var i=[];this.setValueAround(e,t,Number.POSITIVE_INFINITY,i,cn.Unexplored,cn.Explored),this._onChange.dispatch(this,{type:"incremental",tiles:i})}revealTemporarily(e){this.temporaryReveals.set(e.tile,5*is.BASE_TICKS_PER_SECOND)}revealObject(e){this.invalidate(e.tile,Number.POSITIVE_INFINITY,4.25)}toggleFlagsAround(e,t,i,r){var s=[];this.setValueAround(e,t,Number.POSITIVE_INFINITY,s,void 0,void 0,r?{setFlags:i}:{clearFlags:i}),this._onChange.dispatch(this,{type:"incremental",tiles:s})}update(){let i=[];if(this.invalidations.size){for(var e of this.invalidations.values())this.setValueAround(e.centerTile,e.radius,e.elevation,i,cn.Explored,[cn.Unexplored,cn.TemporaryReveal]);this.invalidations.clear()}this.temporaryReveals.size&&this.temporaryReveals.forEach((e,t)=>{e<=0?(this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,cn.Unexplored,cn.TemporaryReveal),this.temporaryReveals.delete(t)):(e===5*is.BASE_TICKS_PER_SECOND&&this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,cn.TemporaryReveal,cn.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",tiles:i})}setValueAround(r,s,a,n,o,h=void 0,{setFlags:l,clearFlags:c}={}){var e=Math.ceil(s),t=r.rx-e,u=r.rx+e,d=r.ry-e,p=r.ry+e,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-r.rx)*(i-r.rx)+(t-r.ry)*(t-r.ry)>s*s+1||this.tileElevation[m]>=a+4||(this.tiles[m]=(o??f)|e,f===o&&y===e||n.push({x:i,y:t})))}}revealAll(){this.tiles.fill(cn.Explored),this._onChange.dispatch(this,{type:"clear"})}reset(){this.tiles.fill(cn.Unexplored),this._onChange.dispatch(this,{type:"cover"})}}var Sn=__webpack_require__(949);class _n{constructor(e){this.radiusTiles=e,this.refreshTicks=0}[Or.onTick](e,t){0<this.refreshTicks&&this.refreshTicks--,this.refreshTicks<=0&&this.update(e,t)}[ys.onSpawn](e,t){this.markGapTilesForFriendlies(e,e.owner,t,!0)}[ws.onUnspawn](e,t){this.markGapTilesForFriendlies(e,e.owner,t,!1),this.update(e,t)}[fs.onChange](e,t,i){this.markGapTilesForFriendlies(e,t,i,!1),this.markGapTilesForFriendlies(e,e.owner,i,!0),this.update(e,i)}[Ia.onChange](e,t,i){this.markGapTilesForFriendlies(e,e.owner,t,!i),i&&this.update(e,t)}markGapTilesForFriendlies(i,e,r,t){let s=[e,...r.alliances.getAllies(e)],a;for(var n of s){let e=r.mapShroudTrait.getPlayerShroud(n);if(e&&(e.toggleFlagsAround(i.tile,this.radiusTiles,un.Darken,t),!t)){if(!a){let t=new Ws(r.map.tileOccupation);a=s.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,un.Darken,!0)}}}update(t,i){this.refreshTicks=5*is.BASE_TICKS_PER_SECOND;let r;var s,a,n,o,h=t.owner.buildings.has(t)&&t.poweredTrait?.isPoweredOn();for(s of i.getCombatants())if(s!==t.owner&&!i.alliances.areAllied(t.owner,s)){let e=i.mapShroudTrait.getPlayerShroud(s);if(e)if(h){e.unrevealAround(t.tile,this.radiusTiles),r||(n=this.radiusTiles+Xi.MAX_SIGHT,a=new Sn.Vector2(t.tile.rx,t.tile.ry).addScalar(-n),n=new Sn.Vector2(t.tile.rx,t.tile.ry).addScalar(n),r=i.map.technosByTile.queryRange(new Sn.Box2(a,n)));for(o of r)o.owner===s||i.alliances.areAllied(o.owner,s)?e.revealFrom(o):o.rules.revealToAll&&e.revealObject(o)}else[...s.buildings].some(e=>e.rules.spySat)&&e.revealAround(t.tile,this.radiusTiles)}}}const kn=is.BASE_TICKS_PER_SECOND;class On{constructor(e){this.radiusTiles=e,this.detectionLines=[],this.nextScan=kn}[Or.onTick](e,t){e.owner.powerTrait?.isLowPower()?this.disable():(0<this.nextScan&&this.nextScan--,this.nextScan<=0&&(this.nextScan=kn,this.detectionLines=this.scan(e,t)))}[Ia.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 r=[],s=new Ws(i.map.tileOccupation);var a,n,o,h=e=>s.distance2(e,t)/mr.ISO_TILE_SIZE<=this.radiusTiles;for(a of e)for(var l of a.getOwnedObjects())l.attackTrait?.currentTarget?h((n=l.attackTrait.currentTarget).obj??n.tile)&&r.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),r.push({source:l,target:n})):(o=o.pathNodes[0])&&h(o.tile)&&(o=i.createTarget(o.onBridge,o.tile),r.push({source:l,target:o})));return r}}class In{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 ${At[this.unit.type]}#${this.unit.id}}`);this.unit=e,this.healTicks=5*is.BASE_TICKS_PER_SECOND}[Or.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 on(i,e))))}[Tr.onDestroy](e,t,i){this.unit&&(t.destroyObject(this.unit,i,!0),this.unit=void 0)}evacuate(t,i,r){let e;var s={x:i.tile.rx,y:i.tile.ry+i.art.foundation.height},s=r.map.tiles.getByMapCoords(s.x,s.y);s&&r.map.isWithinBounds(s)&&this.canEvacuateTo(s,t,i,r)&&(e=s),e=e||new xr(r.map.tiles,r.map.mapBounds,i.tile,i.art.foundation,1,1,e=>this.canEvacuateTo(e,t,i,r)).getNextTile(),e?(r.unlimboObject(t,e),t.unitOrderTrait.addTask(new da(r))):r.destroyObject(t,{player:t.owner})}canEvacuateTo(e,t,i,r){return 0<r.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&Math.abs(e.z-i.tile.z)<2&&!r.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length}}var Cn,An,Bn,En=__webpack_require__(949);(s=Cn=Cn||{})[s.BuildUp=0]="BuildUp",s[s.Ready=1]="Ready",s[s.BuildDown=2]="BuildDown";class Pn extends As{constructor(e,t,i){super(At.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,r,s,a){let n=new this(e,t,r);return t.canBeOccupied&&(n.garrisonTrait=new pa(n,i.audioVisual.conditionRed,t.maxNumberOccupants),n.traits.add(n.garrisonTrait)),t.canC4&&!t.wall&&(n.c4ChargeTrait=new fn,n.traits.add(n.c4ChargeTrait)),t.bridgeRepairHut&&(n.cabHutTrait=new Ha(n,a),n.traits.add(n.cabHutTrait)),t.crewed&&(n.crewedTrait=new Va,n.traits.add(n.crewedTrait)),t.turret&&(n.turretTrait=new ga,n.traits.add(n.turretTrait)),t.overpowerable&&(n.overpoweredTrait=new nn(n),n.traits.add(n.overpoweredTrait)),(t.powered&&0!==t.power||t.needsEngineer)&&(n.poweredTrait=new ba(n),n.traits.add(n.poweredTrait)),(t.factory||t.cloning)&&(n.factoryTrait=new ja(t.cloning?Gi.InfantryType:t.factory,t.cloning),n.traits.add(n.factoryTrait)),t.superWeapon&&(n.superWeaponTrait=new bn(t.superWeapon),n.traits.add(n.superWeaponTrait)),t.numberOfDocks&&(n.dockTrait=new Na(n,s,t.numberOfDocks,r.dockingOffsets),n.traits.add(n.dockTrait),t.helipad&&(n.helipadTrait=new yn,n.traits.add(n.helipadTrait)),(t.unitRepair||t.unitReload)&&(n.unitRepairTrait=new pn,n.traits.add(n.unitRepairTrait)),t.unitReload&&(n.unitReloadTrait=new wn,n.traits.add(n.unitReloadTrait))),t.hospital&&(n.hospitalTrait=new In,n.traits.add(n.hospitalTrait)),(t.factory||t.cloning||t.numberOfDocks)&&(n.rallyTrait=new gn,n.traits.add(n.rallyTrait)),t.freeUnit&&n.traits.add(new Wa),t.produceCashStartup&&n.traits.add(new Ga),t.wall&&(n.wallTrait=new $a,n.traits.add(n.wallTrait)),t.gapGenerator&&(n.gapGeneratorTrait=new _n(t.gapRadiusInCells),n.traits.add(n.gapGeneratorTrait)),t.psychicDetectionRadius&&(n.psychicDetectorTrait=new On(t.psychicDetectionRadius),n.traits.add(n.psychicDetectorTrait)),n}isBuilding(){return!0}getFoundation(){return this.art.foundation}getFoundationCenterOffset(){var e=this.getFoundation();return new En.Vector2(e.width/2*mr.LEPTONS_PER_TILE,e.height/2*mr.LEPTONS_PER_TILE)}update(e){this.buildStatus!==Cn.BuildUp||this.unitOrderTrait.hasTasks()||this.unitOrderTrait.addTask(new Tn(e.rules.general.buildupTime)),this.buildStatus!==this.lastBuildStatus&&(this.lastBuildStatus=this.buildStatus,e.events.dispatch(new ma(this,this.buildStatus))),this.attackTrait?.setDisabled(this.buildStatus!==Cn.Ready||!!this.poweredTrait&&!this.poweredTrait.isPoweredOn()),super.update(e)}}class xn extends Cs{constructor(e,t,i){super(At.Terrain,e,t,i)}static factory(e,t,i){return new this(e,t,i)}}(s=An=An||{})[s.NotSpecial=0]="NotSpecial",s[s.Riparius=1]="Riparius",s[s.Cruentus=2]="Cruentus",s[s.Vinifera=4]="Vinifera",s[s.Aboreus=8]="Aboreus",s[s.Ore=1]="Ore",s[s.Gems=2]="Gems",s[s.All=15]="All";class Nn{static getOverlayTibType(e){return this.isRiparius(e)?An.Riparius:this.isCruentus(e)?An.Cruentus:this.isVinifera(e)?An.Vinifera:this.isAboreus(e)?An.Aboreus:An.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}}Nn.minIdRiparius=102,Nn.maxIdRiparius=127,Nn.minIdCruentus=27,Nn.maxIdCruentus=38,Nn.minIdVinifera=127,Nn.maxIdVinifera=146,Nn.minIdAboreus=147,Nn.maxIdAboreus=166;class Rn extends Cs{constructor(e,t,i){super(At.Overlay,e,t,i)}static factory(e,t,i){let r=new this(e,t,i);return t.wall&&(r.wallTrait=new $a,r.traits.add(r.wallTrait)),r}isTiberium(){return Nn.getOverlayTibType(this.overlayId)!==An.NotSpecial}isBridge(){return za.isBridge(this.overlayId)}isXBridge(){return za.isXBridge(this.overlayId)}isHighBridge(){return za.isHighBridge(this.overlayId)}isLowBridge(){return za.isLowBridge(this.overlayId)}isBridgePlaceholder(){return za.isBridgePlaceholder(this.overlayId)}getFoundation(){let e={width:1,height:1};return this.isBridge()&&(this.isXBridge()?e.height+=2:e.width+=2),e}}class Mn extends Cs{constructor(e,t,i){super(At.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}}}(s=Bn=Bn||{})[s.Riparius=0]="Riparius",s[s.Cruentus=1]="Cruentus",s[s.Vinifera=2]="Vinifera",s[s.Aboreus=3]="Aboreus",s[s.Ore=0]="Ore",s[s.Gems=1]="Gems";class Dn extends ca{constructor(e,t,i,r){super(e,i??t,!1,{closeEnoughTiles:i?void 0:0,strictCloseEnough:!i}),this.teleportTile=t,this.teleportCondition=r}onStart(e){if(super.onStart(e),!e.harvesterTrait||e.rules.locomotor!==ti.Chrono)throw new Error(`Vehicle ${e.name} is not a chrono miner`)}onTick(e){return!e.moveTrait.isDisabled()&&(!(this.isCancelling()||e.moveTrait.moveState!==ps.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===_r.Air&&(e.zone=_r.Ground,e.position.tileElevation=0),!0))}}class Ln{constructor(e){this.gameObject=e}getTiberiumType(){var e=Nn.getOverlayTibType(this.gameObject.overlayId);switch(e){case An.Ore:return Bn.Ore;case An.Gems:return Bn.Gems;case An.Vinifera:return Bn.Ore;default:throw new Error(`Unsupported tiberium type ${e}`)}}collectBail(){if(this.getBailCount()<=0)throw new Error("Attempted to collect an ore bail, but there are none left");return this.gameObject.value--,this.getTiberiumType()}spawnBails(e){this.gameObject.value=Math.min(Ln.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}}Ln.maxBails=11;class Fn extends Rr{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 Ws(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=Wn.MovingToOreSite,e.harvesterTrait.lastGatherExplicit=this.explicitOrder}onEnd(e){e.harvesterTrait.status!==Wn.LookingForOreSite&&(e.harvesterTrait.status=Wn.Idle)}onTick(i){if(this.isCancelling())return!0;let r=i.harvesterTrait;if(r.status===Wn.MovingToOreSite){if(this.target=this.initialTarget?.landType===Yt.Tiberium?this.initialTarget:this.findClosestReachableOreSite(i,r.lastOreSite??i.tile,!0),r.lastOreSite=this.target,!this.target){r.status=Wn.LookingForOreSite;let e=this.getRefineryOnTile(i.tile);if(e&&1===i.unitOrderTrait.getTasks().length){let t=i.rules.movementZone===ii.Fly;var s=new xr(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();s&&i.unitOrderTrait.addTasks(new ca(this.game,s,!1),new ss(()=>{[gs.Success,gs.CloseEnough,gs.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new rs(1/60))}))}return!0}var a=this.game.rules.general.closeEnough,s=this.rangeHelper.tileDistance(i.tile,this.target)<=a;if(i.tile!==this.target&&(i.tile.landType!==Yt.Tiberium||!s||this.strictTarget)){if(i.tile!==this.target&&s&&i.tile.landType!==Yt.Tiberium){s=this.findClosestReachableOreSite(i,i.tile,!1,!0);if(s)this.target=s,r.lastOreSite=this.target;else{if(!this.forceMoveTried)return this.forceMoveTried=!0,this.children.push(new ca(this.game,this.target,!1,{closeEnoughTiles:0,strictCloseEnough:!0})),!1;if(this.forceMoveTried=!1,!r.isEmpty())return this.returnOreIfPossible(i),!0;s=this.findClosestReachableOreSite(i,i.tile,!0,!0);if(!s)return r.status=Wn.LookingForOreSite,!0;this.target=s,r.lastOreSite=this.target}}return this.children.push(new ca(this.game,this.target,!1,{closeEnoughTiles:a}),new ss(()=>{[gs.Success,gs.CloseEnough,gs.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new rs(5/60))})),!1}this.target=i.tile,r.lastOreSite=this.target,r.status=Wn.Harvesting,this.forceMoveTried=!1,this.strictTarget=!1}if(r.status!==Wn.Harvesting)return!1;{if(r.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,r.lastOreSite??i.tile,!1)||r.isEmpty()?(r.status=Wn.MovingToOreSite,this.onTick(i)):(this.returnOreIfPossible(i),!0);let t=e.traits.get(Ln);a=t.collectBail();if(t.getBailCount()||this.game.unspawnObject(e),a===Bn.Ore)r.ore++;else{if(a!==Bn.Gems)throw new Error(`Unsupported tiberium type ${a}`);r.gems++}return[...i.owner.buildings].some(e=>e.rules.refinery)||this.explicitOrder?(this.children.push(new rs(1/60)),!1):!0}}findClosestReachableOreSite(t,i,e,r=!1){let s=t.rules.movementZone===ii.Fly;var a=e=>e.landType===Yt.Tiberium&&(!r||(s||!this.game.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length));if(a(i))return i;let n=1;if(!e){let e=new sa(this.game.map.tiles,this.game.map.mapBounds,i,1,this.game,a,!1);var o=e.getNextTile();if(o)return o;n=2}e=e?this.scanFarRadius:this.scanNearRadius;let h=new xr(this.game.map.tiles,this.game.map.mapBounds,i,{width:1,height:1},n,e,a);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 Gn(this.game))}getTargetLinesConfig(e){return{pathNodes:this.initialTarget?[{tile:this.initialTarget,onBridge:void 0}]:[]}}}var jn,Un,Wn,Vn,zn,Hn=__webpack_require__(949);class Gn extends Rr{constructor(e,t,i=!1,r=!1){super(),this.game=e,this.forceTarget=t,this.resetLastOreSite=i,this.explicitOrder=r,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.rangeHelper=new Ws(e.map.tileOccupation)}onStart(e){if(!e.isVehicle()||!e.harvesterTrait)throw new Error(`Unit ${e.name} is not a harvester.`);e.harvesterTrait.status=Wn.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!==Wn.LookingForRefinery&&(e.harvesterTrait.status=Wn.Idle)}onTick(r){if(this.isCancelling())return!0;let s=r.harvesterTrait;if(s.status===Wn.LookingForRefinery)return!0;if(s.status===Wn.MovingToRefinery){if(!this.target||!this.isValidTargetRefinery(this.target,r)||r.tile!==this.findRefineryDockingTile(this.target)){var a=this.forceTarget??this.findClosestReachableRefinery(r);if(!a)return s.status=Wn.LookingForRefinery,!0;this.target&&this.target!==a&&this.target.dockTrait.hasReservedDockForUnit(r)&&this.target.dockTrait.unreserveDockForUnit(r),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(r)));let i=this.findRefineryDockingTile(this.target);var n=this.rangeHelper.tileDistance(r,i);if(void 0===e||t||n>this.game.rules.general.harvesterTooFarDistance&&!this.explicitOrder){var o=this.findReachableQueueingTile(r);return o?(r.tile!==o&&this.children.push(r.rules.teleporter?new Dn(this.game,i,o,()=>this.chronoMinerCanTeleport(r,i,this.target)):new ca(this.game,o,!1),new ss(()=>{r.moveTrait.lastMoveResult===gs.Fail?s.status=Wn.LookingForRefinery:r.moveTrait.lastMoveResult===gs.CloseEnough&&this.children.push(new rs(5/60))})),!1):!0}if(this.target.dockTrait.hasReservedDockForUnit(r)||this.target.dockTrait.reserveDockAt(r,e),void 0===this.reservedDockNumber&&(this.reservedDockNumber=this.target.dockTrait.getReservedDockForUnit(r)),r.tile!==i)return this.children.push(r.rules.teleporter?new Dn(this.game,i,void 0,()=>this.chronoMinerCanTeleport(r,i,this.target)):new ca(this.game,i,!1,{closeEnoughTiles:0,strictCloseEnough:!0}),new ss(()=>{r.moveTrait.lastMoveResult===gs.Fail&&(s.status=Wn.LookingForRefinery)})),!1;s.status=Wn.Docking}if(!this.isValidTargetRefinery(this.target,r))return s.status=Wn.MovingToRefinery,this.forceTarget=void 0,this.onTick(r);if(s.status===Wn.Docking){if(270!==r.direction)return this.children.push(new Gs(270)),!1;this.target.dockTrait.dockUnitAt(r,this.reservedDockNumber),this.reservedDockNumber=void 0,s.status=Wn.PreparingToUnload}if(s.status===Wn.PreparingToUnload)return this.preventOpportunityFire=!0,this.children.push(new rs(2/60)),s.status=Wn.Unloading,!1;if(s.status!==Wn.Unloading)return!1;a=s.ore*this.game.rules.getTiberium(Bn.Ore).value+s.gems*this.game.rules.getTiberium(Bn.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),s.ore=0,s.gems=0,1===r.unitOrderTrait.getTasks().length&&r.unitOrderTrait.addTask(new Fn(this.game)),!0}isValidTargetRefinery(e,t){return e.isSpawned&&this.game.areFriendly(e,t)&&!e.warpedOutTrait.isActive()}findClosestReachableRefinery(i){let r=this.rangeHelper,e=[...i.owner.buildings].filter(e=>e.rules.refinery&&e.dockTrait&&!e.warpedOutTrait.isActive()).sort((e,t)=>r.distance2(i,e)-r.distance2(i,t));var t=e[0],s=e.find(e=>0<e.dockTrait.getAvailableDockCount());return!s||t&&r.tileDistance(i,s.centerTile)-r.tileDistance(i,t.centerTile)>this.game.rules.general.harvesterTooFarDistance?t:s}findReachableQueueingTile(t){if(this.target.art.queueingCell){var e=new Hn.Vector2(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 xr(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===_r.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 r=this.rangeHelper;t=r.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))))}}(jn=jn||{}).onPush=Symbol(),(s=Un=Un||{})[s.Move=0]="Move",s[s.ForceMove=1]="ForceMove",s[s.Attack=2]="Attack",s[s.ForceAttack=3]="ForceAttack",s[s.AttackMove=4]="AttackMove",s[s.Guard=5]="Guard",s[s.GuardArea=6]="GuardArea",s[s.Capture=7]="Capture",s[s.Occupy=8]="Occupy",s[s.Deploy=9]="Deploy",s[s.DeploySelected=10]="DeploySelected",s[s.Stop=11]="Stop",s[s.Cheer=12]="Cheer",s[s.Dock=13]="Dock",s[s.Gather=14]="Gather",s[s.Repair=15]="Repair",s[s.Scatter=16]="Scatter",s[s.EnterTransport=17]="EnterTransport",s[s.PlaceBomb=18]="PlaceBomb",(s=Wn=Wn||{})[s.Idle=0]="Idle",s[s.LookingForOreSite=1]="LookingForOreSite",s[s.MovingToOreSite=2]="MovingToOreSite",s[s.Harvesting=3]="Harvesting",s[s.LookingForRefinery=4]="LookingForRefinery",s[s.MovingToRefinery=5]="MovingToRefinery",s[s.Docking=6]="Docking",s[s.PreparingToUnload=7]="PreparingToUnload",s[s.Unloading=8]="Unloading";class $n{constructor(e){this.storage=e,this.ore=0,this.gems=0,this.status=Wn.Idle,this.lastGatherExplicit=!1,this.autoGatherOnNextIdle=!1,this.ticksSinceLastRefineryCheck=0,this.ticksSinceLastOreCheck=0}[ys.onSpawn](e,t){e.owner.isCombatant()&&t.afterTick(()=>{e.unitOrderTrait.addTask(new Fn(t))})}[fs.onChange](e,t,i){!t.isCombatant()&&e.owner.isCombatant()&&i.afterTick(()=>{e.unitOrderTrait.addTask(new Fn(i))})}[Or.onTick](e,t){this.status===Wn.LookingForRefinery?this.ticksSinceLastRefineryCheck++>5*is.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastRefineryCheck=0,e.unitOrderTrait.hasTasks()?this.ticksSinceLastRefineryCheck=-25*is.BASE_TICKS_PER_SECOND:[...e.owner.buildings].some(e=>e.rules.refinery)||this.lastGatherExplicit?e.unitOrderTrait.addTask(new Gn(t)):this.status=Wn.Idle):this.status===Wn.LookingForOreSite?this.ticksSinceLastOreCheck++>20*is.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastOreCheck=0,e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new Fn(t))):this.status===Wn.Idle&&this.autoGatherOnNextIdle&&e.unitOrderTrait.isIdle()&&e.tile.landType===Yt.Tiberium&&(this.autoGatherOnNextIdle=!1,e.unitOrderTrait.addTask(new Fn(t,e.tile,!0)))}[Cr.onBeforeTeleport](e,t,i,r){!r&&e.owner.isCombatant()&&(this.status=Wn.Idle,this.lastOreSite=void 0,i&&e.rules.teleporter&&t.afterTick(()=>{e.unitOrderTrait.addTask(new(this.isFull()?Gn:Fn)(t))}))}[jn.onPush](e,t){this.autoGatherOnNextIdle=[Un.AttackMove,Un.Move,Un.ForceMove,Un.Scatter].includes(t),[Wn.LookingForRefinery,Wn.LookingForOreSite].includes(this.status)&&(this.status=Wn.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 qn{constructor(e){this.target=e,this.type=vr.LeaveTransport}}class Zn{constructor(e){this.obj=e,this.units=[],this.loadQueue=[]}unitFitsInside(e){return e.rules.size<=this.obj.rules.sizeLimit&&e.rules.size<=this.getAvailableCapacity()}getAvailableCapacity(){return this.obj.rules.passengers-this.units.reduce((e,t)=>e+t.rules.size,0)}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)}[Or.onTick](e,t){this.loadQueue=this.loadQueue.filter(e=>!e.isDestroyed&&!e.isCrashing)}[Tr.onDestroy](e,t,i,r){var s=!!e.armedTrait?.deathWeapon,a=i?.weapon?.warhead.rules.parasite;if(r||s||e.zone===_r.Air||a)for(var n of this.units)s&&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 da(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 qn(t))}}getHash(){return H(this.units.map(e=>e.getHash()))}debugGetState(){return this.units.map(e=>e.debugGetState())}dispose(){this.obj=void 0}}class Qn{[Or.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===bs.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}}}(Vn=Vn||{}).onHeal=Symbol();class Xn{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=to+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}[Or.onTick](r,s){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?to+2:e.getCooldownTicks();let t=e.rules.damage;this.parasite.veteranTrait&&(t*=this.parasite.veteranTrait.getVeteranDamageMultiplier());let i=e.warhead.computeDamage(t,r);this.canBeCulled(r,this.parasite,e,s)&&(i=r.healthTrait.getHitPoints()),e.warhead.inflictDamage(i,r,{player:this.parasite.owner,obj:this.parasite,weapon:e},s),r.isCrashing?(this.parasiteWeapon.expireCooldown(),this.evictOrDestroyParasite(r,s)):!r.isDestroyed&&r.isVehicle()&&r.zone!==_r.Air&&e.warhead.rules.rocker&&r.applyRocking(90*(.5<=s.generateRandom()?1:-1),1)}}canBeCulled(e,t,i,r){if(!i.warhead.rules.culling)return!1;r=r.rules.audioVisual,r=t.veteranTrait?.isElite()?r.conditionYellow:r.conditionRed;return e.healthTrait.health<=100*r}[Vn.onHeal](e,t,i,r){var s;!this.parasite||this.parasite.isDestroyed||r===e||e.isAircraft()&&r?.rules.unitReload||(this.parasite.rules.organic?(s=this.parasite,this.evictOrDestroyParasite(e,t),this.stunParasite(s,t)):(this.parasite.deathType=Ir.None,t.destroyObject(this.parasite,r?{player:r.owner,obj:r}:void 0),this.uninfest()))}[br.onDamage](e,t,i,r){r?.obj!==this.parasite&&(this.lastExternalDamageInflicted=i,this.lastExternalDamageTick=t.currentTick)}[Ts.onAttack](i,r,s){if(this.parasite&&!this.parasite.isDestroyed&&r?.weapon?.warhead.rules.sonic){var a=this.parasite;this.evictOrDestroyParasite(i,s),this.stunParasite(a,s);let e=r.weapon.warhead;e.canDamage(a,a.tile,a.zone)&&(i=e.computeDamage(r.weapon.rules.damage,a),e.inflictDamage(i,a,r,s));let t=r.obj?.unitOrderTrait.getCurrentTask();t instanceof an&&t.getWeapon().warhead.rules.sonic&&t.cancel()}}[Tr.onDestroy](e,t,i,r){this.parasite&&!this.parasite.isDestroyed&&(r||!this.parasite.invulnerableTrait.isActive()&&this.shouldSupressParasite(t,this.parasite,i)?(this.parasite.deathType=Ir.None,t.destroyObject(this.parasite,i,r),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}[Cr.onBeforeTeleport](e,t,i,r){i&&r&&this.parasite&&!this.parasite.isDestroyed&&(this.parasiteWeapon.expireCooldown(),r=this.parasite,this.evictOrDestroyParasite(e,t,!0),r.isDestroyed||this.stunParasite(r,t))}stunParasite(e,t){e.unitOrderTrait.addTaskToFront(new rs(10/60).setCancellable(!1)),e.isVehicle()&&e.submergibleTrait&&(e.submergibleTrait.emerge(e,t),e.cloakableTrait?.uncloak(t),e.submergibleTrait.setCooldown(10*is.BASE_TICKS_PER_SECOND))}evictOrDestroyParasite(r,s,a=!1){if(this.parasite&&!this.parasite.isDestroyed){var e=r.zone===_r.Air;if(e&&this.parasite.rules.movementZone!==ii.Fly||!e&&!s.map.terrain.getPassableSpeed(r.tile,this.parasite.rules.speedType,r.onBridge)&&!s.map.getObjectsOnTile(r.tile).find(e=>e.isBuilding()))this.parasite.deathType=Ir.None,s.destroyObject(this.parasite,{player:r.owner,obj:r});else{let t=r.tile,i=r.onBridge;if(!a&&!r.isDestroyed||this.parasite.rules.organic){let e=new xr(s.map.tiles,s.map.mapBounds,t,{width:1,height:1},1,1,e=>0<s.map.terrain.getPassableSpeed(e,this.parasite.rules.speedType,i)&&!s.map.terrain.findObstacles({tile:e,onBridge:i},this.parasite).length);a=e.getNextTile();if(!a)return this.parasite.deathType=Ir.None,s.destroyObject(this.parasite,{player:r.owner,obj:r}),void this.uninfest();t=a}this.parasite.onBridge=i,this.parasite.position.subCell=this.parasite.isInfantry()?r.position.subCell:0,this.parasite.zone=s.map.getTileZone(t,!i),this.parasite.position.tileElevation=i?s.map.tileOccupation.getBridgeOnTile(t).tileElevation:0,this.parasite.resetGuardModeToIdle(),s.unlimboObject(this.parasite,t,!0)}this.uninfest()}}destroyParasite(e,t){this.parasite&&(this.parasite.deathType=Ir.None,t.destroyObject(this.parasite,e),this.uninfest())}dispose(){this.gameObject=void 0}}class Yn{constructor(e){this.target=e,this.type=vr.ShipSubmergeChange}}class Kn{constructor(){this.isActive=!1}isSubmerged(){return this.isActive}setCooldown(e){this.cooldownTicks=e}[Or.onTick](e,t){this.isActive||e.parasiteableTrait?.isInfested()||(e.attackTrait&&e.attackTrait.attackState!==en.Idle&&!e.moveTrait.isMoving()?this.cooldownTicks=Math.max(this.cooldownTicks??0,5*is.BASE_TICKS_PER_SECOND):this.cooldownTicks??(this.cooldownTicks=Math.floor(60*t.rules.general.cloakDelay*is.BASE_TICKS_PER_SECOND)),0<this.cooldownTicks&&this.cooldownTicks--,this.cooldownTicks<=0&&(this.isActive=!0,t.events.dispatch(new Yn(e))))}[br.onDamage](e,t){this.emerge(e,t)}emerge(e,t){this.isActive&&(this.isActive=!1,this.cooldownTicks=void 0,t.events.dispatch(new Yn(e)))}}class Jn{constructor(){this.prevHoverBobLeptons=0}[ys.onSpawn](e,t){this.setBaseElevation(e,t)}[cs.onTileChange](e,t,i,r){r&&(this.prevHoverBobLeptons=0,this.setBaseElevation(e,t))}setBaseElevation(e,t){e.position.tileElevation=(e.onBridge?t.map.tileOccupation.getBridgeOnTile(e.tile)?.tileElevation??0:0)+mr.worldToTileHeight(mr.leptonsToWorld(t.rules.general.hover.height))}[Or.onTick](e,t){var i=this.computeHoverBobLeptons(t.currentTick,t.rules.general.hover),t=i-this.prevHoverBobLeptons;this.prevHoverBobLeptons=i;i=mr.tileHeightToWorld(e.position.tileElevation);e.position.tileElevation=mr.worldToTileHeight(i+mr.leptonsToWorld(t))}computeHoverBobLeptons(e,t){e=e/is.BASE_TICKS_PER_SECOND/(60*t.bob);return.1*t.height*z(Math.sin(2*e*Math.PI),10)}}class eo{constructor(){this.tilt={pitch:0,yaw:0}}[ys.onSpawn](e){this.tilt=this.computeTilt(e.tile.rampType)}[cs.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 to=34;class io extends As{constructor(e,t,i){super(At.Vehicle,e,t,i),this.direction=0,this.spinVelocity=0,this.crateBonuses=new Ns,this.turretNo=0,this.onBridge=!1,this.isSinker=!1,this.isFiring=!1,this.zone=t.naval?_r.Water:_r.Ground}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,r,s){let a=new this(e,t,i);return a.isSinker=!t.underwater&&(t.weight>=r.general.shipSinkingWeight||!t.naval),a.moveTrait=new ks(a,s),a.traits.add(a.moveTrait),t.crashable&&(a.crashableTrait=new Ps(a),a.traits.add(a.crashableTrait)),t.crewed&&(a.crewedTrait=new Va,a.traits.add(a.crewedTrait)),t.harvester&&(a.harvesterTrait=new $n(t.storage),a.traits.add(a.harvesterTrait)),t.passengers&&(a.transportTrait=new Zn(a),a.traits.add(a.transportTrait),t.gunner&&(a.gunnerTrait=new Qn,a.traits.add(a.gunnerTrait))),t.turret&&(a.turretTrait=new ga,a.traits.add(a.turretTrait)),t.consideredAircraft&&!t.landable||a.traits.add(new Ea),t.parasiteable&&(a.parasiteableTrait=new Xn(a),a.traits.add(a.parasiteableTrait)),t.naval&&t.underwater&&(a.submergibleTrait=new Kn,a.traits.add(a.submergibleTrait)),t.locomotor===ti.Hover&&a.traits.add(new Jn),t.isTilter&&!t.consideredAircraft&&(a.tilterTrait=new eo,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??to,facing:e,factor:t}}}class ro{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 so{setParent(e){this.parent=e}getParent(){return this.parent}[Or.onTick](r,s){if(this.parent&&r.attackTrait&&r.primaryWeapon){let e=this.parent.attackTrait?.currentTarget,t=r.unitOrderTrait.getCurrentTask(),i=new Ws(s.map.tileOccupation);var a=this.parent.armedTrait?.getWeapons().find(e=>e.rules.spawner);r.ammo&&!(e&&r.attackTrait.currentTarget?e.equals(r.attackTrait.currentTarget):e===r.attackTrait.currentTarget||!e&&this.parent.isUnit()&&(this.parent.unitOrderTrait.getCurrentTask()instanceof ca||this.parent.unitOrderTrait.getCurrentTask()instanceof an))&&(!e||a&&i.isInWeaponRange(this.parent,e.obj??e.tile,a,s.rules))?e&&r.primaryWeapon.targeting.canTarget(e.obj,e.tile,s,!0,!1)?!t||t instanceof ca?(r.unitOrderTrait.cancelAllTasks(),r.unitOrderTrait.addTask(r.attackTrait.createAttackTask(s,e.obj,e.tile,r.primaryWeapon,{force:!0}))):r.attackTrait.attackState!==en.Idle&&t.requestTargetUpdate(e):t?t instanceof ca||t.cancel():this.tryMoveToParent(r,this.parent,s):this.tryMoveToParent(r,this.parent,s)}}tryMoveToParent(t,i,r){if(t.tile!==i.tile){let e=t.unitOrderTrait.getCurrentTask();e?e instanceof ca&&e.updateTarget(i.tile,!!i.isUnit()&&i.onBridge):t.unitOrderTrait.addTask(new ca(r,i.tile,!!i.isUnit()&&i.onBridge,{closeEnoughTiles:0,strictCloseEnough:!0}))}}}(s=zn=zn||{})[s.None=0]="None",s[s.Ground=1]="Ground",s[s.Wall=2]="Wall",s[s.Cliff=3]="Cliff",s[s.OnBridge=4]="OnBridge",s[s.UnderBridge=5]="UnderBridge",s[s.Shore=6]="Shore";class ao{setWarhead(e){return this.warhead=e,this}setDamage(e){return this.damage=e,this}setLauncher(e){return this.launcher=e,this}[Tr.onDestroy](e,t){this.warhead&&this.damage&&this.launcher&&this.warhead.detonate(t,this.damage,e.tile,e.tileElevation,e.position.worldPosition,e.zone,zn.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}}var no=__webpack_require__(949);class oo{constructor(){this.enabled=!0}setEnabled(e){this.enabled=e}[Or.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 xa(new ca(t,i,!1),new ss(e=>t.unspawnObject(e))).setCancellable(!1)))}chooseExitTile(e,t){var i=t.map.tiles.getMapSize(),i=.5<t.generateRandom()?new no.Vector2(Math.floor(i.width/2),0):new no.Vector2(0,Math.floor(i.height/2)),e=new no.Vector2(e.rx,e.ry);let r=qa(e.x,e.y,i.x,i.y).map(e=>t.map.tiles.getByMapCoords(e.x,e.y)).filter(Pa);for(;r.length;){var s=r[r.length-1],s=mr.tileToWorld(s.rx+.5,s.ry+.5);if(t.map.isWithinHardBounds(new no.Vector2(s.x,s.y)))break;r.pop()}if(!r.length)throw new Error("No valid exit tile found");return r[r.length-1]}}class ho extends As{constructor(e,t,i,r){super(At.Aircraft,e,t,i),this.pitch=0,this.yaw=0,this.roll=0,this.onBridge=!1,this.zone=_r.Ground,this.crateBonuses=new Ns,this.generalRules=r}get sight(){return this.rules.spawned?super.sight:super.sight+(this.zone===_r.Air&&0<super.sight?this.generalRules.aircraftFogReveal:0)}get direction(){return this.yaw}set direction(e){this.yaw=e}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,r,s){let a=new this(e,t,i,r.general);return a.rules.airportBound&&a.rules.dock.length&&(a.airportBoundTrait=new ro(a.rules.dock),a.traits.add(a.airportBoundTrait)),a.rules.missileSpawn||(a.crashableTrait=new Ps(a),a.traits.add(a.crashableTrait)),a.rules.spawned&&(a.rules.missileSpawn?(a.missileSpawnTrait=new ao,a.traits.add(a.missileSpawnTrait)):(a.spawnLinkTrait=new so,a.traits.add(a.spawnLinkTrait))),a.moveTrait=new ks(a,s),a.traits.add(a.moveTrait),t.dock.length&&a.traits.add(new Ea),t.landable&&e!==r.general.paradrop.paradropPlane||a.traits.add(new oo),t.parasiteable&&(a.parasiteableTrait=new Xn(a),a.traits.add(a.parasiteableTrait)),a}isUnit(){return!0}isAircraft(){return!0}}class lo{constructor(e){this.gameObject=e,this.orders=[],this.queuedOrders=new Set,this.tasks=[],this.taskRunner=new Ka}[Or.onTick](i,e){if(i.isSpawned){var r=this.hasTasks(),t=this.tasks.find(e=>!e.isCancelling());r&&this.taskRunner.tick(this.tasks,i);var s,a=this.orders.length;if(a&&(!r||!t)){let e,t=!1;for(;e=this.orders[0];)if(e.isValid()&&e.isAllowed()&&((s=e.process())&&(this.queuedOrders.has(e)&&(this.tasks.push(new ts(5)),this.tasks.push(new ss(()=>{i.resetGuardModeToIdle()}))),this.tasks.push(...s),r||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&&!r&&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))}}[fs.onChange](){this.clearOrders(),this.cancelAllTasks()}[Cr.onBeforeTeleport](e,t,i,r){i&&!r&&(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!==Sr.NotStarted),this.tasks.forEach(e=>e.cancel())),this.orders.push(t),e&&this.queuedOrders.add(t),this.gameObject.traits.filter(jn).forEach(e=>{e[jn.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)}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 co=[[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]];var uo,po,go=__webpack_require__(949);class mo{constructor(e){this.tiles=e,this._worldPosition=new go.Vector3,this._tileOffset=new go.Vector2,this._centerOffset=new go.Vector2,this.desiredSubCell=0,this._tileElevation=0,this._onPositionChange=new va}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/mr.LEPTONS_PER_TILE-.5),t=Math.sign(this._tileOffset.y/mr.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 go.Vector2(this._tile.rx*mr.LEPTONS_PER_TILE+this._tileOffset.x+this._centerOffset.x,this._tile.ry*mr.LEPTONS_PER_TILE+this._tileOffset.y+this._centerOffset.y)}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){var i=Math.floor(e),r=Math.floor(t),s=!this._tile||this._tile.rx!==i||this._tile.ry!==r;if(s){var a=this.tiles.getByMapCoords(i,r);if(!a)throw new RangeError(`Attempted move to a non-existent tile: [${i},${r}]`);this._tile=a}this._tileOffset.set((e-i)*mr.LEPTONS_PER_TILE,(t-r)*mr.LEPTONS_PER_TILE),this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:s})}moveToLeptons(e){this.moveToTileCoords(e.x/mr.LEPTONS_PER_TILE,e.y/mr.LEPTONS_PER_TILE)}moveByLeptons(e,t){if(!this._tile)throw new Error("Tile is not set");this.moveToTileCoords(this._tile.rx+(this._tileOffset.x+e)/mr.LEPTONS_PER_TILE,this._tile.ry+(this._tileOffset.y+t)/mr.LEPTONS_PER_TILE)}moveByLeptons3(e){var t=this.worldPosition.y;this.moveByLeptons(e.x,e.z),this.setAbsoluteElevationWorld(t+e.y/mr.LEPTONS_PER_TILE*mr.ISO_TILE_SIZE)}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,r=2*Math.floor((e-1)/2)-1,t={width:i*mr.LEPTONS_PER_TILE/4,height:r*mr.LEPTONS_PER_TILE/4});var r=mr.LEPTONS_PER_TILE/2;return new go.Vector2(r+t.width,r+t.height)}interpolateRampHeight(e,t,i){var r=co[i],s=r[1],i=r[0];return s*(1-e)*(1-t)+r[2]*e*(1-t)+i*(1-e)*t+r[3]*e*t}updateWorldPosition(t,e){var i=(e.x+this._centerOffset.x)/mr.LEPTONS_PER_TILE,r=(e.y+this._centerOffset.y)/mr.LEPTONS_PER_TILE,e=mr.tileToWorld(t.rx+i,t.ry+r);let s;if(void 0!==this._tileElevation){let e=0;0!==t.rampType&&(e=this.interpolateRampHeight(i,r,t.rampType)),s=mr.tileHeightToWorld(t.z+e+this._tileElevation)}else s=this._absoluteElevation;this._worldPosition.set(e.x,s,e.y),void 0===this._tileElevation&&(this._computedTileElevation=this.computeTileElevationFromWorldPos())}computeTileElevationFromWorldPos(){if(!this._tile)return 0;var e=mr.worldToTileHeight(this._worldPosition.y),t=(this._tileOffset.x+this._centerOffset.x)/mr.LEPTONS_PER_TILE,i=(this._tileOffset.y+this._centerOffset.y)/mr.LEPTONS_PER_TILE;let r=0;return 0!==this._tile.rampType&&(r=this.interpolateRampHeight(t,i,this._tile.rampType)),e-this._tile.z-r}clone(){let e=new mo(this.tiles);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}}(uo=uo||{}).onAttack=Symbol();class fo{constructor(e,t,i,r){this.target=e,this.position=t,this.explodeAnim=i,this.isLightningStrike=r,this.type=vr.WarheadDetonate}}(s=po=po||{})[s.Top=0]="Top",s[s.TopLeft=1]="TopLeft",s[s.TopRight=2]="TopRight",s[s.Left=3]="Left",s[s.Right=4]="Right",s[s.BottomLeft=5]="BottomLeft",s[s.Bottom=6]="Bottom",s[s.BottomRight=7]="BottomRight";class yo{constructor(i,r,e){this.tileSets=r,this.generalRules=e;let s=this.rSize={width:0,height:0},a=this.dSize={width:0,height:0};for(let e=0,t=i.length;e<t;++e)s.width=Math.max(s.width,i[e].rx),s.height=Math.max(s.height,i[e].ry),a.width=Math.max(s.width,i[e].dx),a.height=Math.max(s.height,i[e].dy);s.width++,s.height++,a.width++,a.height++;let n=this.tilesByRxy=new Array(s.width*s.height);n.fill(void 0);let o=this.tilesByDxy=new Array(a.width*a.height);o.fill(void 0);let h=this.tiles=new Array(i.length),l=[],c=this.bridgeSetTiles=[],u=new Set(Object.values(Xt));for(let e=0,t=i.length;e<t;++e){var d=i[e],p=r.getTileImage(d.tileNum,d.subTile),g=p.terrainType;if(!u.has(g))throw new Error(`Tile (${d.rx}, ${d.ry}) has unknown terrain type "${g}"`);var m={...d,terrainType:g,landType:Fi(g),onBridgeLandType:void 0,rampType:p.rampType,id:d.rx+"_"+d.ry,occluded:!1},f=m.rx,y=m.ry,g=m.dx,p=m.dy;h[e]=m,n[f+y*s.width]=m,(o[g+p*a.width]=m).terrainType!==Xt.Cliff&&!r.isCliffTile(m.tileNum)||l.push(m),r.isHighBridgeBoundaryTile(d.tileNum)&&c.push(m)}this.computeLandBehindCliffTiles(l),this.maxTileHeight=this.computeMaxTileHeight(),this.cutoffTileHeight=Math.max(9,this.computeCutoffTileHeight())}computeLandBehindCliffTiles(e){e.forEach(i=>{var r=this.generalRules.cliffBackImpassability;for(let t=0;t<=r;t++)for(let e=0;e<=r;e++)if(t||e){const s=this.getByMapCoords(i.rx-t,i.ry-e);s&&1<=t&&t===e&&s.z<i.z&&0===s.rampType&&([[1,0],[0,1]].some(([e,t])=>{t=this.getByMapCoords(s.rx-e,s.ry-t);return t?.terrainType===Xt.Cliff&&t.z===s.z})||(s.landType=Yt.Rock))}})}getTileRadarColor(e){let t=this.tileSets.getTileImage(e.tileNum,e.subTile);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}getMaxTileHeight(){return this.maxTileHeight}computeMaxTileHeight(){return this.reduce((e,t)=>Math.max(e,t.z),0)}getCutoffTileHeight(){return this.cutoffTileHeight}computeCutoffTileHeight(){var t=this.dSize.width-1;let i=this.dSize.height-1,r=0,s=!0;for(;s&&0<i;){for(let e=1;e<t-3;e++){var a=this.getByDisplayCoords(e,i);a&&(s=!1,a.z>r&&(r=a.z))}s&&i--}return r}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(Pa)}getNeighbourTile(e,t){var i=e.rx,r=e.ry;switch(t){case po.Bottom:return this.getByMapCoords(i+1,r+1);case po.Top:return this.getByMapCoords(i-1,r-1);case po.Left:return this.getByMapCoords(i-1,r+1);case po.Right:return this.getByMapCoords(i+1,r-1);case po.BottomLeft:return this.getByMapCoords(i,r+1);case po.BottomRight:return this.getByMapCoords(i+1,r);case po.TopLeft:return this.getByMapCoords(i-1,r);case po.TopRight:return this.getByMapCoords(i,r-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(i,r){let s=[];for(let t=0;t<r.width;t++)for(let e=0;e<r.height;e++){var a=i.rx+t,n=i.ry+e,o=this.getByMapCoords(a,n);if(!o)throw new RangeError(`Tile out of bounds (${a}, ${n})`);s.push(o)}return s}}class wo{destroyOre(i,r,s){if(r.landType===Yt.Tiberium&&(s.art.hasObject(i,At.Animation)?s.art.getAnimation(i):void 0)?.crater){let t=s.map.getObjectsOnTile(r).find(e=>e.isOverlay()&&e.isTiberium());if(t){r=Math.ceil(Ln.maxBails/2),r=i.startsWith("S_CLSN")?r:s.generateRandomInt(1,r);let e=t.traits.get(Ln);e.removeBails(r),e.getBailCount()||s.unspawnObject(t)}}}spawnSmudges(e,s,a){if(s.landType===Yt.Clear&&0===s.rampType&&a.map.mapBounds.isWithinBounds(s)&&!a.map.getObjectsOnTile(s).find(e=>!e.isUnit())){e=a.art.hasObject(e,At.Animation)?a.art.getAnimation(e):void 0;if(e?.crater){let t=e?.forceBigCraters?2:1,i=e?.scorch,r=[po.Bottom,po.BottomLeft,po.BottomRight].every(e=>a.map.tiles.getNeighbourTile(s,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)&&!r));e.length&&(e=e[a.generateRandomInt(0,e.length-1)].name,e=a.createObject(At.Smudge,e),a.spawnObject(e,s))}}}}var To,bo,vo=__webpack_require__(949);class So{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!==_r.Air||i===_r.Air)&&(!(!e.isUnit()&&i===_r.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()||!za.isLowBridgeHead(e.overlayId))))))))))))}computeDamage(t,i,r=!1){let s=t;if(0<t&&i.isTechno()&&i.invulnerableTrait.isActive())return 0;if(i.isAircraft()&&i.missileSpawnTrait&&i.zone!==_r.Air)return 0;if(this.rules.radiation||this.rules.temporal||!i.isInfantry()||i.stance!==kr.Prone||(s*=this.rules.proneDamage),i.isTechno()||i.isOverlay()||i.isTerrain()){let e=i.isTerrain()?ri.Wood:i.rules.armor;i.isOverlay()&&i.isBridge()&&((t=za.getOverlayBridgeType(i.overlayId))===La.Wood?e=ri.Wood:t===La.Concrete&&(e=ri.Concrete)),r&&i.isOverlay()&&(i.isBridge()||i.rules.wall)||(s*=this.rules.verses.get(e)),0<s&&i.isTechno()&&i.veteranTrait&&(s/=i.veteranTrait.getVeteranArmorMultiplier()),0<s&&i.isUnit()&&(s/=i.crateBonuses.armor)}return(i.isOverlay()||i.isBuilding())&&i.rules.wall&&(this.rules.wallAbsoluteDestroyer?s=Number.POSITIVE_INFINITY:this.rules.wall||this.rules.wood&&i.rules.armor===ri.Wood||(s=0)),i.isOverlay()&&i.isBridge()&&(this.rules.wall||(s=0)),s=0<s?Math.floor(s):Math.ceil(s),s}inflictDamage(e,t,i,r){let s=t.healthTrait;return e===Number.POSITIVE_INFINITY&&(e=s.getHitPoints()),s.inflictDamage(e,i,r),r.traits.filter(uo).forEach(e=>{e[uo.onAttack](t,i?.obj,r)}),t.onAttack(r,i),t.isTechno()&&!this.rules.temporal&&this.supressOrScatterTarget(t,r),!s.health&&(t.isInfantry()&&(t.infDeathType=this.rules.infDeath),this.rules.temporal&&(t.deathType=Ir.Temporal),t.isUnit()&&t.crashableTrait&&t.zone===_r.Air&&!this.rules.temporal?t.crashableTrait.crash(i):r.destroyObject(t,i),!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 da(t)),e.isInfantry()&&e.unitOrderTrait.addTask(new ss(()=>e.isPanicked=!1).setCancellable(!1))):e.isInfantry()&&e.suppressionTrait?.supress()}createDummyWeaponInfo(){return{minRange:0,range:0,speed:Number.POSITIVE_INFINITY,type:si.Primary,rules:new vi(new h("Dummy")),projectileRules:new Wi(At.Projectile,new h("Dummy")),warhead:this}}detonate(i,e,t,r,s,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/mr.LEPTONS_PER_TILE:this.rules.cellSpread,v=this.rules.percentAtMax;let S=new Set,_=new Map,k=new Ws(i.map.tileOccupation),O=new xr(i.map.tiles,i.map.mapBounds,t,{width:1,height:1},0,Math.ceil(b),()=>!0);for(;g=O.getNextTile();)for(m of i.map.getObjectsOnTile(g))if((!S.has(m)||m.isBuilding())&&(n!==zn.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-r)||n===zn.OnBridge&&!m.isBridge()))){var I=z(I=m.isBuilding()?g===t?0:k.distance3(g,s)/mr.ISO_TILE_SIZE:m.isTerrain()||m.isOverlay()?k.distance3(g,t)/mr.ISO_TILE_SIZE:k.distance3(m,s)/mr.ISO_TILE_SIZE,3);if(!(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&&b<I||(S.add(m),_.set(m,m.isBuilding()?(_.get(m)||[]).concat(I):[I]))}}let C=!1,A;for(f of S)if(!f.isDestroyed&&!f.isCrashing){var B,E=this.computeDamage(e,f,c);if(E)for(var P of _.get(f)){let t=E;if(0<b&&Number.isFinite(t)&&(t=vo.Math.lerp(t,v*t,P/b)),Math.abs(t)<1&&(!b||.25<=t/E)&&(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&&P<1&&(A=f),this.inflictDamage(t,f,h,i))break;f.isVehicle()&&this.rules.rocker&&(0<(B=W(E/300,0,1))&&(P=Zr.fromMapCoords(f.position.getMapPosition().clone().sub(mr.vecWorldToGround(mr.vecWorldToLeptons(s))))-f.direction,f.applyRocking(P,B)))}}}else f.isTechno()&&f.invulnerableTrait.isActive()&&(C=!0)}y=y.rules.radLevel;y&&b&&i.mapRadiationTrait.createRadSite(t,y,b+1);p=p?void 0:C?i.rules.audioVisual.weaponNullifyAnim:this.pickExplodeAnim(e,A,a,i,c);if(!C&&a===_r.Ground){let e=new wo;p&&e.destroyOre(p,t,i),u&&e.spawnSmudges(u,t,i),p&&e.spawnSmudges(p,t,i)}i.events.dispatch(new fo(this,s,p,c))}pickExplodeAnim(t,i,r,s,a){if(t){if(a)return s.rules.audioVisual.weatherConBoltExplosion;if(this.rules.conventional&&r===_r.Water&&(!i||i.isBuilding()||i.isVehicle()&&i.submergibleTrait)){var n=s.rules.combatDamage.splashList;return n[W(Math.floor(t/50),0,n.length-1)]}n=this.rules.animList.length;let e;return n?(e=s.rules.combatDamage.c4Warhead===this.rules.name?n-1:this.rules.emEffect?s.generateRandomInt(0,n-1):W(Math.floor(t/25),0,n-1),this.rules.animList[e]):void 0}}}So.SPECIAL_WARHEAD_NAME="Special";class _o{constructor(e,t){this.weapon=e,this.gameObject=t,this.type=vr.WeaponFire}}(s=To=To||{})[s.LandOk=0]="LandOk",s[s.LandNotOk=1]="LandNotOk",s[s.LandSecondary=2]="LandSecondary",(s=bo=bo||{})[s.UnderwaterNever=0]="UnderwaterNever",s[s.UnderwaterSecondary=1]="UnderwaterSecondary",s[s.UnderwaterOnly=2]="UnderwaterOnly",s[s.OrganicSecondary=3]="OrganicSecondary",s[s.SealSpecial=4]="SealSpecial",s[s.NavalAll=5]="NavalAll",s[s.NavalNone=6]="NavalNone";class ko{constructor(e,t,i,r,s,a){this.weaponType=e,this.projectileRules=t,this.weaponRules=i,this.warheadRules=r,this.gameObject=s,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===si.Secondary?this.targetChecks.push((e,t,i,r,s)=>!(!s||!e?.isBuilding()||e.name!==a||e.owner!==this.gameObject.owner)):this.warheadRules.electricAssault?this.targetChecks.push((e,t,i,r,s)=>!(!r&&!s||!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,r,s)=>!s&&!!(!this.warheadRules.bombDisarm||e?.isTechno()&&e.tntChargeTrait?.hasCharge())):this.targetChecks.push((e,t,i,r)=>!((!r||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,r,s)=>!(s&&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,r)=>!!(!e&&r||e?.isInfantry()||(e?.isVehicle()||e?.isAircraft())&&e.parasiteableTrait)),this.warheadRules.mindControl&&this.targetChecks.push(e=>!(!e?.isTechno()||!e.mindControllableTrait))),this.targetChecks.push((e,t)=>this.canTargetZone(e,t))}canTarget(t,i,r,s,a){return this.targetChecks.every(e=>e(t,i,r,s,a))}canTargetZone(e,t){let i;if(e?.isUnit()){if(e?.isInfantry()&&e.stance===kr.Paradrop)return this.projectileRules.isAntiAir&&(this.projectileRules.isAntiGround||this.weaponType===si.Secondary);if(e.zone===_r.Air)return this.projectileRules.isAntiAir;if(this.weaponType===si.Secondary&&this.projectileRules.isAntiAir)return!1;i=e.zone}else i=t.landType===Yt.Water?_r.Water:_r.Ground;return i===_r.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 To.LandOk:return!0;case To.LandNotOk:return!1;case To.LandSecondary:return t===si.Secondary;default:throw new Error(`Unhandled LandTargeting value "${e}"`)}}canTargetNaval(e,t,i,r){switch(e){case bo.UnderwaterNever:return!i||!(i.isVehicle()&&i.submergibleTrait?.isSubmerged());case bo.UnderwaterSecondary:return i&&i.isVehicle()&&i.submergibleTrait&&!t.rules.spawned?r===si.Secondary:r===si.Primary;case bo.UnderwaterOnly:return!!(i&&i.isVehicle()&&i.submergibleTrait);case bo.OrganicSecondary:return i?.isTechno()&&i.rules.organic?r===si.Secondary:r===si.Primary;case bo.SealSpecial:return i?.isTechno()&&i.rules.naval&&!i.rules.organic&&(i.isBuilding()||i.rules.speedType===Kt.Float)?r===si.Secondary:r===si.Primary;case bo.NavalAll:return!0;case bo.NavalNone:return!1;default:throw new Error(`Unhandled NavalTargeting value "${e}"`)}}}var Oo=__webpack_require__(949);class Io{constructor(e,t,i,r,s,a,n){this.type=e,this.gameObject=t,this.rules=i,this.warhead=r,this.projectileRules=s,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,r,s){var a=r.getWeapon(e);let n=a.warhead;n===So.SPECIAL_WARHEAD_NAME&&(n=Io.findSpecialWarheadName(a,i,r));var o=new So(r.getWarhead(n)),e=r.getProjectile(a.projectile),r=new ko(t,e,a,o.rules,i,r.general);return new this(t,i,a,o,e,s||new wr,r)}static findSpecialWarheadName(e,t,i){let r;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)r=i.combatDamage.v3Warhead;else if(t.rules.spawns===i.general.dMisl.type)r=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,At.Aircraft);if(!t.primary)throw new Error(`Spawned unit "${t.name}" doesn't have a primary weapon`);r=i.getWeapon(t.primary).warhead}return r}get name(){return this.rules.name}get minRange(){return this.rules.minimumRange}get range(){return this.gameObject.isBuilding()&&!this.gameObject.overpoweredTrait&&this.type===si.Secondary&&this.gameObject.primaryWeapon?Math.min(this.gameObject.primaryWeapon.rules.range,this.rules.range):this.rules.range}get speed(){return this.projectileRules.arcing?.75*bi.iniSpeedToLeptonsPerTick(50):!this.projectileRules.rot||this.projectileRules.inviso||this.rules.isLaser||this.rules.isElectricBolt?Number.POSITIVE_INFINITY:this.rules.speed}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,s,a=1){let n=this.gameObject,o,h=0;if(!n.airSpawnTrait||!this.rules.spawner||(o=n.airSpawnTrait.prepareLaunch(n,r,s),h=n.airSpawnTrait.availableSpawns,o)){this.burstsLeft?(this.burstsLeft--,this.burstIndex++,this.lateralMuzzleMult*=-1):(this.useBurstDelay=!1,this.burstIndex=0,o?this.burstsLeft=h: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&&(o&&0<h?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]:s.generateRandomInt(3,5)),this.burstsLeft||this.resetBursts(),this.rules.limboLaunch&&(s.limboObject(this.gameObject,{selected:s.getUnitSelection().isSelected(this.gameObject),controlGroup:s.getUnitSelection().getOrCreateSelectionModel(this.gameObject).getControlGroupNumber()}),this.warhead.rules.parasite&&(r.obj?.isVehicle()||r.obj?.isAircraft())&&r.obj.parasiteableTrait&&(r.obj.parasiteableTrait.beingBoarded=!0));let e=o??s.createProjectile(this.projectileRules.name,this.gameObject,this,r,!1);e.isAircraft()||(e.baseDamageMultiplier=a*(this.gameObject.isUnit()?this.gameObject.crateBonuses.firepower:1));let t=this.flh.clone();t.lateral*=this.lateralMuzzleMult,e.position.moveToLeptons(n.position.getMapPosition()),e.position.tileElevation=n.position.tileElevation;let i=new Oo.Vector2(t.lateral,t.forward);var l=this.getMuzzleFacing()+this.distributedFireAngle;i=Ur(i,l);var a=Ur(a=new Oo.Vector2(0,n.art.turretOffset),n.direction);i.add(a),n.rules.radialFireSegments&&n.rules.distributedFire&&(a=Math.floor(180/n.rules.radialFireSegments),this.distributedFireAngle=(this.distributedFireAngle+a+90)%180-90),e.direction=l,n.isBuilding()&&n.rules.turretAnim&&n.rules.turretAnimX&&(u=mr.screenDistanceToLeptons(n.rules.turretAnimX,n.rules.turretAnimY),c=n.getFoundationCenterOffset(),e.position.moveByLeptons(-c.x+u.x,-c.y+u.y));var c=new Oo.Vector3(i.x,t.vertical,-i.y),u=mr.vecLeptonsToWorld(c).add(e.position.worldPosition);if(s.map.isWithinHardBounds(u)&&e.position.moveByLeptons3(c),e.tileElevation<0&&(e.position.tileElevation=0),e.isAircraft()?s.unlimboObject(e,e.position.tile):s.spawnObject(e,e.position.tile),this.rules.revealOnFire&&r.obj?.isTechno()){let e=s.mapShroudTrait.getPlayerShroud(r.obj.owner);e?.isShrouded(n.tile)&&e.revealTemporarily(n)}this.rules.decloakToFire&&this.gameObject.cloakableTrait?.uncloak(s),s.events.dispatch(new _o(this,this.gameObject))}}getMuzzleFacing(){let e=this.gameObject,t;return t=!e.isInfantry()&&!e.isAircraft()&&(e.isBuilding()||e.isVehicle())&&e.turretTrait?e.turretTrait.facing:e.direction,t}}class Co{constructor(e){this.tileOccupation=e}checkCollisions(e,t,i){var r,s=e.tile;let a,n;for(r of this.tileOccupation.getObjectsOnTile(s))r.isOverlay()&&r.isBridge()&&(a=r),r.isBuilding()&&(n=r);if(i.walls){if(e.tileElevation<=2&&s.landType===Yt.Wall)return zn.Wall;if(i.buildings&&n?.tile===s&&e.tileElevation<=1.1&&i.buildings(n.owner))return zn.Wall}if(i.shore&&s.landType!==Yt.Water)return zn.Shore;if(i.ground&&e.tileElevation<0)return zn.Ground;var o=e.tileElevation+s.z,h=t.tileElevation+t.tile.z;if(a?.isHighBridge()){var l=a.tile.z+a.tileElevation;if(l<h&&o<=l||h<l&&l-1<=o)return h<l?zn.UnderBridge:zn.OnBridge}else if(a?.isLowBridge()&&i.shore)return zn.UnderBridge;if(i.cliffs){t=s.z-t.tile.z;if(e.tileElevation<0&&4<=t)return zn.Cliff}return zn.None}computeDetonationZone(e,t,i){let r=this.tileOccupation.getBridgeOnTile(e);return i===zn.None&&t>1.5+(r?.tileElevation??0)?_r.Air:r&&1.5<t||e.terrainType!==Xt.Water||r?.isLowBridge()?_r.Ground:_r.Water}}var Ao,Bo,Eo,Po,xo,No,Ro,Mo,Do=__webpack_require__(949);(s=Ao=Ao||{})[s.Travel=0]="Travel",s[s.Impact=1]="Impact",s[s.Detonation=2]="Detonation";class Lo extends Cs{constructor(e,t,i,r){super(At.Projectile,e,t,i),this.tileOccupation=r,this.state=Ao.Travel,this.detonationTimer=0,this.collisionType=zn.None,this.direction=0,this.zone=_r.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 Do.Vector3,this.sonicVisitedObjects=new Map,this.collisionHelper=new Co(r)}get fromObject(){return this._fromObject}set fromObject(e){(this._fromObject=e).veteranTrait&&!e.isDestroyed&&(this.veteranDamageMult=e.veteranTrait.getVeteranDamageMultiplier())}get rot(){return this.fromWeapon.rules.isSonic?bi.iniRotToDegsPerTick(this.iniRot):this.rules.rot}get iniRot(){return this.fromWeapon.rules.isSonic?10:this.rules.iniRot}static factory(e,t,i,r){return new this(e,t,i,r)}onSpawn(a){var e;if(super.onSpawn(a),this.initialSelfPosition=this.position.worldPosition.clone(),!this.target.obj||this.fromWeapon.type===si.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 Ws(this.tileOccupation);var t=e.distance2(this.target.getWorldCoords(),this)/mr.ISO_TILE_SIZE;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!==bs.Elite||e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new da(a))}}else if(this.rules.vertical){let e=this.position.clone();e.tileElevation=this.fromWeapon.warhead.rules.nukeMaker?mr.worldToTileHeight(mr.leptonsToWorld(this.fromWeapon.projectileRules.detonationAltitude)):0,this.aimPoint=mr.vecWorldToLeptons(e.worldPosition)}else{let s=this.target.getWorldCoords();a.afterTick(()=>{let e=mr.vecWorldToLeptons(this.target.getWorldCoords().clone().sub(s));var t=e.length()>mr.LEPTONS_PER_TILE;let i=t?mr.vecWorldToLeptons(s):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):mr.vecWorldToLeptons(this.target.getWorldCoords());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 r=i.clone().sub(mr.vecWorldToLeptons(this.position.worldPosition));r.length()<this.fromWeapon.speed&&this.update(a)})}}adjustAimForBallisticScatter(e,t){let i=e.rules.combatDamage.ballisticScatter,r;r=this.rules.flakScatter?(this.rules.inviso&&(i*=2),e.generateRandom()*i):i/2+e.generateRandom()*(i/2);let s=r*mr.LEPTONS_PER_TILE;this.rules.flakScatter&&(n=t.clone().sub(mr.vecWorldToLeptons(this.initialSelfPosition)).length(),s*=n/(this.fromWeapon.range*mr.LEPTONS_PER_TILE));var a=Ur(new Do.Vector2(s,0),e.generateRandomInt(0,360)),n=mr.vecWorldToGround(t).add(a).multiplyScalar(1/mr.LEPTONS_PER_TILE).floor();e.map.tiles.getByMapCoords(n.x,n.y)&&t.add(new Do.Vector3(a.x,0,a.y))}calculateBallisticOvershootVsMoving(e,t){let i=mr.vecWorldToLeptons(this.target.getWorldCoords()).sub(mr.vecWorldToLeptons(this.initialSelfPosition));var r=zr(mr.vecWorldToGround(i),mr.vecWorldToGround(t.moveTrait.velocity)),t=(90<r?180-r:r)/90,r=i.length()/mr.LEPTONS_PER_TILE,t=t*r/5;return e.generateRandom()<=t?2*Math.min(1,r/5):0}calculateInaccurateBallisticOvershoot(e){return e.generateRandom()<=.5?2:0}update(n){if(void 0!==this.maxSpeed)if(super.update(n),this.state!==Ao.Impact){var r=this.velocity.clone(),o=this.position.clone();if(this.velocity.set(0,0,0),this.fromWeapon.rules.limboLaunch&&this.fromObject.isDestroyed)n.destroyObject(this);else{var h=this.updateSpeed(this.maxSpeed);this.speed=h;let a=this.target.getWorldCoords();if(this.lastTargetLockPosition&&(this.targetLockLost||a.clone().sub(this.lastTargetLockPosition).length()>=mr.ISO_TILE_SIZE)?(a=this.lastTargetLockPosition,this.targetLockLost=!0):this.lastTargetLockPosition=a.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*mr.LEPTONS_PER_TILE))return void this.detonate(n);if(this.homingMoveDir||(c=Zr.toMapCoords(this.direction),this.homingMoveDir=new Do.Vector3(c.x,0,c.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(n);this.limboTravelTicks++}}else if(!this.isInHomingRange(a,n))return void this.detonate(n);let e=new Ws(this.tileOccupation);var l=Math.floor(e.distance2(a,this)/mr.ISO_TILE_SIZE),c=2<l&&1<this.iniRot;let t=mr.vecWorldToLeptons(a.clone().sub(this.position.worldPosition)),i=0;this.homingTravelTicks<this.rules.courseLockDuration||(c?($r(this.homingMoveDir,new Do.Vector3(t.x,this.homingMoveDir.y,t.z),this.rot),this.rules.level||(u=W(Math.floor(this.initialTileDistToTarget)-1,0,2)+W(l-2,0,3)-this.position.tileElevation)&&(p=.25+6/this.iniRot*.1,i=mr.tileHeightToWorld(Math.sign(u)*Math.min(Math.abs(u),p))/mr.ISO_TILE_SIZE*mr.LEPTONS_PER_TILE)):$r(this.homingMoveDir,t,this.rot)),this.direction=Zr.fromMapCoords(new Do.Vector2(this.homingMoveDir.x,this.homingMoveDir.z));var l=t.length(),u=Math.min(l,h);this.homingTravelDistance+=u,this.homingTravelTicks++;let r=!1,s=zn.None;if(1<=u){let e=this.homingMoveDir.clone().setLength(u);i&&(e.y+=i),u===h&&this.velocity.copy(e).multiplyScalar(mr.ISO_TILE_SIZE/mr.LEPTONS_PER_TILE);var d=mr.vecLeptonsToWorld(e).add(this.position.worldPosition);n.map.mapBounds.isWithinHardBounds(d)?this.position.moveByLeptons3(e):r=!0,s=this.checkObstacles(o,n),(s||u<h)&&(r=!0)}else this.position.moveByLeptons3(t),r=!0;r&&(this.collisionType=s,this.detonate(n,s))}else{let t=this.aimPoint.clone().sub(mr.vecWorldToLeptons(this.position.worldPosition));this.rules.vertical||(this.direction=Zr.fromMapCoords(new Do.Vector2(t.x,t.z))),this.rules.arcing&&(t.y=0);var p=Math.min(t.length(),h);if(t.setLength(p),this.rules.arcing){let e=mr.vecWorldToGround(mr.vecWorldToLeptons(this.position.worldPosition.clone().sub(this.initialSelfPosition)).add(t));var l=this.aimPoint.clone().sub(mr.vecWorldToLeptons(this.initialSelfPosition)),s=e.length(),d=mr.vecWorldToGround(l).length(),u=l.y,l=n.rules.audioVisual.gravity,s=(u/d*h+l/2*d/h)*s/h-l*Math.pow(s/h,2)/2;t.y=s+mr.worldToLeptons(this.initialSelfPosition.y)-mr.worldToLeptons(this.position.worldPosition.y)}let e=!1;s=mr.vecLeptonsToWorld(t).add(this.position.worldPosition);n.map.isWithinHardBounds(s)?this.position.moveByLeptons3(t):e=!0;let i=zn.None;if(1<=p?(p!==h&&!this.overshootTiles||this.velocity.copy(t).multiplyScalar(mr.ISO_TILE_SIZE/mr.LEPTONS_PER_TILE),i=this.checkObstacles(o,n),(i||p<h)&&(e=!0)):e=!0,e){if(!i)if(this.overshootTiles){var g=mr.vecWorldToGround(r).setLength(this.overshootTiles*mr.LEPTONS_PER_TILE);if(Ur(g,n.generateRandomInt(-45,45)),s=mr.vecLeptonsToWorld(mr.vecGroundToWorld(g)).add(this.position.worldPosition),!n.map.isWithinHardBounds(s))return void n.unspawnObject(this);this.position.moveByLeptons(g.x,g.y)}else this.snapToTarget&&!this.targetLockLost&&this.position.moveByLeptons3(mr.vecWorldToLeptons(a.clone().sub(this.position.worldPosition)));this.collisionType=i,this.isNuke?(this.state=Ao.Impact,this.detonationTimer=2.5*is.BASE_TICKS_PER_SECOND):this.detonate(n,i)}}let e=this.fromWeapon.warhead;if(e.rules.sonic){var t,i,g=this.position.worldPosition.clone().add(this.velocity.clone().setLength(11)),g=mr.vecWorldToGround(g).multiplyScalar(1/mr.ISO_TILE_SIZE).floor(),m=n.map.tiles.getByMapCoords(g.x,g.y);if(m&&m!==this.fromObject.tile){var f,y=n.map.getTileZone(m);for(f of n.map.getGroundObjectsOnTile(m))if((!f.isUnit()||!f.onBridge)&&(!f.isTechno()||!f.rules.typeImmune||f.owner!==this.fromPlayer||f.name!==this.fromObject.name)&&(!f.isAircraft()||!f.rules.spawned)&&e.canDamage(f,m,y)){let e=this.sonicVisitedObjects.get(f)??new Set;e.add(m),this.sonicVisitedObjects.set(f,e)}}for([t,i]of this.sonicVisitedObjects)for(var w of i)n.map.tileOccupation.isTileOccupiedBy(w,t)&&(w=this.fromWeapon.rules.ambientDamage*this.veteranDamageMult*this.baseDamageMultiplier,w=e.computeDamage(w,t),e.inflictDamage(w,t,{player:this.fromPlayer,weapon:this.fromWeapon,obj:this.fromObject},n))}}}else 0<this.detonationTimer?this.detonationTimer--:this.detonate(n,this.collisionType)}isHoming(){return!!this.rot&&!this.rules.arcing}isInHomingRange(t,i){let r=!0,s=this.target.obj;if(s?.isUnit()){let e=new Ws(this.tileOccupation);i=e.computeWeaponRangeVsTarget(this.fromObject,s,this.fromWeapon,i.rules).range;this.fromWeapon.rules.limboLaunch?r=e.isInRange3(this.initialSelfPosition,t,0,i+.5):(t=mr.worldToLeptons(s.moveTrait.velocity.length()))&&(this.fromObject.rules.movementZone===ii.Fly?5<this.speed/t&&(r=e.isInRange2(this.initialSelfPosition,this.position.worldPosition,0,i)):isFinite(this.fromWeapon.speed)&&3.5<this.fromWeapon.speed/s.rules.speed&&(r=e.isInRange3(this.initialSelfPosition,this.position.worldPosition,0,i)))}return r}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 r=e*Xi.MAGIC_SPEED_MULT;return this.rules.arcing&&(r*=(1+i/6)/2,t=Math.floor(t),r*=t<=8?1:1+t/8*.5),this.fromWeapon.warhead.rules.sonic&&(r=Math.ceil(t*mr.LEPTONS_PER_TILE/21)),r}checkObstacles(e,t){return this.fromWeapon.rules.limboLaunch?zn.None:this.collisionHelper.checkCollisions(this.position,e,{cliffs:this.rules.subjectToCliffs,ground:this.isHoming(),shore:this.rules.level,walls:this.rules.subjectToWalls,buildings:e=>this.fromPlayer!==e&&!t.alliances.areAllied(this.fromPlayer,e)})}computeBaseDamage(e){var t=this.fromWeapon,i=t.warhead;let r=t.rules.damage;t.type===si.DeathWeapon&&i.rules.ivanBomb&&(r=e.rules.combatDamage.ivanDamage);let s=r*this.baseDamageMultiplier;return t.type===si.DeathWeapon&&(s*=this.fromObject.rules.deathWeaponDamageModifier),s*=this.veteranDamageMult,s}detonate(n,t=zn.None){var e=this.fromWeapon;let i=e.warhead;var r,s=this.zone=this.collisionHelper.computeDetonationZone(this.tile,this.tileElevation,t);let o=this.tile;e.type===si.DeathWeapon&&i.rules.ivanBomb&&(i=new So(n.rules.getWarhead(n.rules.combatDamage.ivanWarhead)));let a=this.computeBaseDamage(n);n.destroyObject(this),this.state=Ao.Detonation;let h=this.target.obj,l=!1;i.rules.parasite&&h?.isUnit()&&o===h.tile&&i.canDamage(h,o,s)&&(h.isInfantry()?a=Number.POSITIVE_INFINITY:h.parasiteableTrait&&(h.parasiteableTrait.infest(this.fromObject,this.fromWeapon),l=!0));let c=!0;if(l&&(c=!1),i.rules.sonic&&(c=!1),i.rules.ivanBomb&&(c=!1,!h?.isTechno()||!h.tntChargeTrait||h.tntChargeTrait.hasCharge()||h.isDestroyed||h.warpedOutTrait.isInvulnerable()||(r=n.rules.combatDamage.ivanTimedDelay,h.tntChargeTrait.setCharge(r,n.currentTick,{player:this.fromPlayer}))),i.rules.bombDisarm&&(c=!1,h?.isTechno()&&h.tntChargeTrait?.hasCharge()&&!h.isDestroyed&&h.tntChargeTrait.removeCharge()),i.rules.mindControl&&(c=!1,this.fromObject.isDestroyed||!h?.isTechno()||!h.mindControllableTrait||h.mindControllableTrait?.isActive()||n.areFriendly(h,this.fromObject)||!i.canDamage(h,o,s)||h.invulnerableTrait.isActive()||this.fromObject.mindControllerTrait.control(h,n)),i.rules.temporal&&(c=!1,!this.fromObject.isDestroyed&&h?.isTechno()&&i.canDamage(h,o,s)&&!h.invulnerableTrait.isActive()&&(i.inflictDamage(0,h,{player:this.fromPlayer,weapon:e,obj:this.fromObject},n),this.fromObject.temporalTrait.updateTarget(h,e,n))),i.rules.makesDisguise&&(c=!1,!this.fromObject.isDestroyed&&(this.fromObject.isInfantry()||this.fromObject.isVehicle())&&h?.isUnit()&&h.type===this.fromObject.type&&this.fromObject.disguiseTrait?.disguiseAs(h,this.fromObject,n)),i.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&&i.detonate(n,a,o,this.tileElevation,this.position.worldPosition,s,t,this.target,{player:this.fromPlayer,weapon:e,obj:this.fromObject},this.isShrapnel,!1,this.impactAnim),i.rules.nukeMaker){t=Io.factory("NukePayload",si.Primary,this.fromObject,n.rules);let e=n.createProjectile(t.projectileRules.name,this.fromObject,t,this.target,!1);e.isNuke=!0,e.impactAnim="NUKEBALL";t=this.target.tile;e.position.moveToTileCoords(t.rx+.5,t.ry+.5),e.position.tileElevation=this.position.tileElevation,n.spawnObject(e,t)}if(this.rules.shrapnelCount&&this.rules.shrapnelWeapon&&((this.target.obj?!this.target.obj.isBuilding():n.map.getGroundObjectsOnTile(this.target.tile).some(e=>e.isTerrain())&&!e.projectileRules.isAntiAir)||this.isShrapnel)){let t=n.rules.getWeapon(this.rules.shrapnelWeapon);var u,d=Io.factory(t.name,si.Primary,this.fromObject,n.rules);let i=this.rules.shrapnelCount,r=new Ws(n.map.tileOccupation),e=new xr(n.map.tiles,n.map.mapBounds,o,{width:1,height:1},1,t.range,e=>r.isInTileRange(o,e,t.minimumRange,t.range)),s=new Set;for(;0<Math.floor(i);){var p,g=e.getNextTile();if(!g)break;for(p of n.map.tileOccupation.getObjectsOnTileByLayer(g,d.projectileRules.isAntiAir?Oa.Air:Oa.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===kr.Paradrop))))if(!s.has(p)&&(s.add(p),i=Math.max(0,i-1-(p.isTechno()?.5:0)),Math.floor(i)<=0))break}for(u of s){var m=n.createTarget(u.isTerrain()?void 0:u,u.tile);this.createShrapnel(n,m,d)}i=Math.floor(i);let a=new sa(n.map.tiles,n.map.mapBounds,o,t.range,n,e=>r.isInTileRange(o,e,t.minimumRange,t.range));for(let e=0;e<i;e++){var f=a.getNextTile();if(!f)break;f=n.createTarget(void 0,f);this.createShrapnel(n,f,d)}}if(e.rules.limboLaunch&&!l){let s=this.fromObject;i.rules.parasite&&(this.target.obj.isVehicle()||this.target.obj?.isAircraft())&&this.target.obj.parasiteableTrait&&(this.target.obj.parasiteableTrait.beingBoarded=!1);let t,a;e=s.rules.movementZone===ii.Fly;if(e)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),r=new Ds(n.map),e=new xr(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,s.rules.speedType,!!t)&&r.isEligibleTile(e,t,i,o)&&(e===o||!n.map.terrain.findObstacles({tile:e,onBridge:i},s).length)});t=e.getNextTile(),a=!!t?.onBridgeLandType}t?(!e&&this.target.obj.isUnit()&&(s.onBridge=a,s.position.tileElevation=a?n.map.tileOccupation.getBridgeOnTile(t)?.tileElevation??0:0),n.unlimboObject(s,t),s.isInfantry()&&(s.position.subCell=this.target.obj.position.subCell),s.direction=this.direction):s.owner.removeOwnedObject(s)}}createShrapnel(e,t,i){let r=e.createProjectile(i.rules.projectile,this.fromObject,i,t,!0);r.veteranDamageMult=this.veteranDamageMult,r.position.moveToLeptons(this.position.getMapPosition()),r.position.tileElevation=this.position.tileElevation,e.spawnObject(r,r.position.tile)}computeAimPointVersusMovingTarget(t,i,r,s){let a=t.position.worldPosition,n=a.clone();i=mr.leptonsToWorld(i);if(i<3*t.moveTrait.velocity.length())return mr.vecWorldToLeptons(a);let o=Xr.computeInterceptPoint(r,i,a,t.moveTrait.velocity);if(o.length()){let e=o.clone().sub(a);r=e.length(),i=t.moveTrait.velocity.length(),r=i?Math.ceil(r/i):0;if(o=a.clone().add(e.setLength(r*i)),s.isWithinHardBounds(o))if(t.zone!==_r.Air){o.multiplyScalar(1/mr.ISO_TILE_SIZE);let e=t.position.clone();e.moveToTileCoords(o.x,o.z),n=e.worldPosition}else n=o;else n=a}return mr.vecWorldToLeptons(n)}}(s=Bo=Bo||{})[s.None=0]="None",s[s.PreparingToFire=1]="PreparingToFire",s[s.FiringUp=2]="FiringUp",s[s.Firing=3]="Firing";class Fo{constructor(e){this.gameObject=e,this.deployed=!1,this.deployFireDelay=0,this.deployFireState=Bo.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?kr.Deployed:kr.None),t?(this.deployFireState=Bo.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===Bo.FiringUp&&(e.isFiring=!1),this.deployFireState=Bo.None,this.deployWeapon=void 0)}}toggleDeployed(){this.setDeployed(!this.isDeployed())}[Or.onTick](e,t){if(void 0!==this.undeployDelay&&(0<this.undeployDelay&&this.undeployDelay--,this.undeployDelay<=0&&[Bo.None,Bo.PreparingToFire].includes(this.deployFireState)))return this.undeployDelay=void 0,void this.setDeployed(!1);if(this.deployWeapon&&this.deployFireState!==Bo.None){if(this.deployFireState===Bo.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=Bo.FiringUp}if(this.deployFireState===Bo.FiringUp){if(e.isFiring=!0,0<this.fireUpDelay--)return;this.deployFireState=Bo.Firing}var i;this.deployFireState===Bo.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=Bo.None,this.deployWeapon=void 0):this.deployFireState=Bo.PreparingToFire)}}computeDeployFireCooldown(t,i){if(t.rules.radLevel&&t.rules.areaFire){var r=this.gameObject.tile,r=i.mapRadiationTrait.getRadSiteLevel(r);if(!r)return 0;i=i.rules.radiation;let e=Math.max(0,r*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}}(Eo=Eo||{}).onChange=Symbol();class jo{constructor(e,t,i){this.target=e,this.attacker=t,this.damageHitPoints=i,this.type=vr.InflictDamage}}(Po=Po||{}).onChange=Symbol(),(s=xo=xo||{})[s.Green=0]="Green",s[s.Yellow=1]="Yellow",s[s.Red=2]="Red";class Uo{constructor(e,t,i,r){this.maxHitPoints=e,this.gameObject=t,this.conditionYellow=i,this.conditionRed=r,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?xo.Green:this.health>100*this.conditionRed?xo.Yellow:xo.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,r){var e=this.hitPoints;this.applyHitPoints(e-t,r),e!==this.hitPoints&&0<t&&(this.gameObject.traits.filter(br).forEach(e=>{e[br.onDamage](this.gameObject,r,t,i)}),r.events.dispatch(new jo(this.gameObject,i,t)))}healBy(e,i,r){if(e<0)throw new Error(`Can't heal by negative value ${e}`);if(this.hitPoints<this.maxHitPoints){var s=this.hitPoints;this.applyHitPoints(this.hitPoints+e,r),this.projectedHitPoints=this.hitPoints;let t=this.hitPoints-s;this.gameObject.traits.filter(Vn).forEach(e=>{e[Vn.onHeal]?.(this.gameObject,r,t,i)})}}healToFull(i,r){if(this.hitPoints<this.maxHitPoints){var e=this.hitPoints;this.applyHitPoints(this.maxHitPoints,r),this.projectedHitPoints=this.hitPoints;let t=this.hitPoints-e;this.gameObject.traits.filter(Vn).forEach(e=>{e[Vn.onHeal]?.(this.gameObject,r,t,i)})}}applyHitPoints(e,t){let i=this.health;this.setHitPoints(e),i!==this.health&&(t.traits.filter(Eo).forEach(e=>{e[Eo.onChange](this.gameObject,t,i)}),this.gameObject.traits.filter(Po).forEach(e=>{e[Po.onChange](this.gameObject,t,i)}))}projectDamage(e){if(e<0)throw new Error("Projected damage must be positive");this.projectedHitPoints=Math.max(-30,this.projectedHitPoints-e)}[Or.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 Wo{constructor(e){this.bridges=e,this.needsImageUpdate=!1,this.dominoHandled=!1}[br.onDamage](){this.needsImageUpdate=!0}[Or.onTick](e){this.needsImageUpdate&&(this.needsImageUpdate=!1,this.bridges.handlePieceHealthChange(this.bridges.getPieceAtTile(e.tile)))}[Tr.onDestroy](r,s,a){var e=this.bridges.getPieceAtTile(r.tile);this.dominoHandled||this.bridges.findDominoPieces(e).forEach(e=>{e.obj.traits.get(Wo).dominoHandled=!0,s.destroyObject(e.obj,a)});let t=s.map.tileOccupation.calculateTilesForGameObject(r.tile,r);t.forEach(e=>{let t=Fi(e.terrainType),i=s.rules.getLandRules(t);s.map.getGroundObjectsOnTile(e).forEach(e=>{e.isUnit()&&e.onBridge&&(r.isLowBridge()&&0<i.getSpeedModifier(e.rules.speedType)||e.isInfantry()&&e.stance===kr.Paradrop?(e.onBridge=!1,e.zone=Mr(t)):(e.isInfantry()&&(e.infDeathType=Jt.None),s.destroyObject(e,a,!0)))})})}}class Vo{static calculateOverlayId(e,t,i){let r;if("number"!=typeof e?(r=Nn.getOverlayTibType(e.id),t=e.rx,i=e.ry):r=e,r!==An.NotSpecial){var t=mr.tileToScreen(t,i),{x:i,y:t}=mr.screenToScreenTile(t.x,t.y),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,r===An.Ore?Nn.minIdRiparius+i:r===An.Gems?Nn.minIdCruentus+i:r===An.Vinifera?Nn.minIdVinifera+i:r===An.Aboreus?Nn.minIdAboreus+i:void 0}}}(s=No=No||{})[s.Idle=0]="Idle",s[s.Spawning=1]="Spawning";class zo{constructor(e){this.rules=e,this.ticksSinceLastSpawn=0,this.cooldownTicks=Math.floor(1/this.rules.animationProbability),this.status=No.Idle}[Or.onTick](e,t){this.status=No.Idle,this.ticksSinceLastSpawn++>this.cooldownTicks&&(this.ticksSinceLastSpawn=0,this.status=No.Spawning,this.spawnTiberium(e.tile,t))}spawnTiberium(r,s){for(let i=1;i<=2;i++){let e=new xr(s.map.tiles,s.map.mapBounds,r,{width:1,height:1},i,i,e=>[Yt.Clear,Yt.Road,Yt.Rough].includes(e.landType)&&!s.map.getGroundObjectsOnTile(e).find(e=>!e.isSmudge()&&!e.isUnit()));var a=e.getNextTile();if(a){var n=Vo.calculateOverlayId(An.Ore,a.rx,a.ry);if(void 0===n)throw new Error("Expected an overlayId");let e=s.createObject(At.Overlay,s.rules.getOverlayName(n));return e.overlayId=n,e.value=3,void s.spawnObject(e,a)}e=new xr(s.map.tiles,s.map.mapBounds,r,{width:1,height:1},i,i,e=>e.landType===Yt.Tiberium);let t;for(;!t;){var o=e.getNextTile();if(!o)break;t=s.map.getObjectsOnTile(o).find(e=>e.isOverlay()&&e.isTiberium()&&e.traits.get(Ln).getBailCount()+1<=Ln.maxBails)}if(t)return void t.traits.get(Ln).spawnBails(1)}}}class Ho{constructor(e=!1){this.freeRepair=e,this.disabled=!0,this.cooldownTicks=0,this.healLeftover=0}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}[Or.onTick](t,i){if(!this.isDisabled())if(100===t.healthTrait.health&&this.setDisabled(!0),this.cooldownTicks<=0){var r=i.rules.general.repair,s=t.isInfantry()?r.iRepairRate:t.isBuilding()?r.repairRate:r.uRepairRate;this.cooldownTicks+=is.BASE_TICKS_PER_SECOND*s*60;var a=t.isInfantry()?r.iRepairStep:r.repairStep,s=this.freeRepair?0:r.repairPercent;let e;s?(r=s*t.purchaseValue/t.healthTrait.maxHitPoints,s=Math.min(t.owner.credits,Math.max(1,Math.floor(r*a))),e=r&&s?s/r:a,s?t.owner.credits-=s: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--}[fs.onChange](){this.setDisabled(!0)}}(Ro=Ro||{}).onDestroy=Symbol();class Go{constructor(e){this.target=e,this.type=vr.UnitPromote}}class $o{constructor(e,t){this.gameObject=e,this.veteranRules=t,this.veteranLevel=bs.None,this.xp=0}[Ro.onDestroy](e,t,i,r){var 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)||!r.areFriendly(e,t))&&(this.veteranLevel>=this.veteranRules.veteranCap||(this.xp+=t.rules.cost*(t.veteranLevel+1),s=e.rules.cost*this.veteranRules.veteranRatio+1,this.xp>=s&&((t=(i=Math.min(this.veteranLevel+Math.floor(this.xp/s),this.veteranRules.veteranCap))-this.veteranLevel)&&(this.xp-=t*s,this.setVeteranLevel(i),r.events.dispatch(new Go(e)))))))}promote(e,t){e=Math.min(this.veteranLevel+e,this.veteranRules.veteranCap);e-this.veteranLevel&&(this.setVeteranLevel(e),t.events.dispatch(new Go(this.gameObject)))}isMaxLevel(){return this.veteranLevel===this.veteranRules.veteranCap}isElite(){return this.veteranLevel===bs.Elite}setVeteranLevel(e){this.veteranLevel=e,this.veteranLevel===bs.Elite&&this.gameObject.armedTrait?.toggleEliteWeapons(!0)}getVeteranSightMultiplier(){return this.getVeteranAbilityMultiplier(ai.SIGHT)}getVeteranSpeedMultiplier(){return this.getVeteranAbilityMultiplier(ai.FASTER)}getVeteranArmorMultiplier(){return this.getVeteranAbilityMultiplier(ai.STRONGER)}getVeteranDamageMultiplier(){return this.getVeteranAbilityMultiplier(ai.FIREPOWER)}getVeteranRofMultiplier(){return this.getVeteranAbilityMultiplier(ai.ROF)}hasVeteranAbility(e){return this.veteranLevel===bs.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=bs.Elite&&this.gameObject.rules.eliteAbilities.has(e)}getVeteranAbilityMultiplier(e){let t=1;return(this.veteranLevel===bs.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=bs.Elite&&this.gameObject.rules.eliteAbilities.has(e))&&(t=this.getVeteranRulesMultiplier(e)),t}getVeteranRulesMultiplier(e){switch(e){case ai.FASTER:return this.veteranRules.veteranSpeed;case ai.STRONGER:return this.veteranRules.veteranArmor;case ai.FIREPOWER:return this.veteranRules.veteranCombat;case ai.ROF:return this.veteranRules.veteranROF;case ai.SIGHT:return this.veteranRules.veteranSight;default:throw new Error(`Unhandled VeteranAbility ${e}`)}}dispose(){this.gameObject=void 0}}class qo{constructor(e,t){this.gameObject=e,this.rules=t,this.specialWeaponIndex=0;t=e.veteranLevel===bs.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?(s=e?t.art.elitePrimaryFireFlh:t.art.primaryFireFlh,this.primaryWeapon=Io.factory(i,si.Primary,t,this.rules,s)):this.primaryWeapon=void 0;var r,s=e&&t.rules.eliteSecondary||t.rules.secondary;s?(r=e?t.art.eliteSecondaryFireFlh:t.art.secondaryFireFlh,this.secondaryWeapon=Io.factory(s,si.Secondary,t,this.rules,r)):this.secondaryWeapon=void 0,(t.rules.explodes||t.crashableTrait)&&(r=t.rules.deathWeapon||!!t.crashableTrait&&this.secondaryWeapon?.rules.name||this.primaryWeapon?.rules.name||this.rules.combatDamage.deathWeapon,this.deathWeapon=Io.factory(r,si.DeathWeapon,t,this.rules))}selectSpecialWeapon(e,t=!1){let i=this.gameObject;var r=i.rules.weaponCount;if(r<1)throw new Error(`Object "${i.name}" doesn't support special weapons`);if(r-1<e)throw new RangeError(`Weapon index ${e} out of bounds (max ${r}) for object ${i.name}`);r=t&&i.rules.getEliteWeaponAtIndex(e)||i.rules.getWeaponAtIndex(e);if(!r)throw new Error(`Missing weapon at index ${e} for object "${i.name}"`);t=i.art.getSpecialWeaponFlh(e);this.primaryWeapon=Io.factory(r,si.Primary,i,this.rules,t),this.secondaryWeapon=void 0,this.specialWeaponIndex=e,this.deathWeapon=this.primaryWeapon.rules.suicide?Io.factory(i.rules.deathWeapon||this.primaryWeapon.name,si.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===si.Primary?this.primaryWeapon:this.secondaryWeapon}isEquippedWithWeapon(e){return[this.primaryWeapon,this.secondaryWeapon].includes(e)}getWeapons(){return[this.primaryWeapon,this.secondaryWeapon].filter(Pa)}[Or.onTick](){this.primaryWeapon&&this.primaryWeapon.tick(),this.secondaryWeapon&&this.secondaryWeapon.tick()}[Tr.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 Zo{constructor(){this.cooldownTicks=0}[Or.onTick](e,t){100!==e.healthTrait.health&&(e.rules.selfHealing||e.veteranTrait?.hasVeteranAbility(ai.SELF_HEAL))&&(this.cooldownTicks<=0?(this.cooldownTicks+=is.BASE_TICKS_PER_SECOND*t.rules.general.repair.repairRate*60,e.healthTrait.healBy(1,e,t)):this.cooldownTicks--)}}class Qo{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 Xo{constructor(e){this.target=e,this.type=vr.ObjectDisguiseChange}}class Yo{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===At.Terrain}disguiseAs(e,t,i){this.disguisedAs={rules:e.rules,owner:e.owner},this.isActive=!0,i.events.dispatch(new Xo(t))}revealDisguise(e,t){this.cooldownTicks=t.rules.general.infantryBlinkDisguiseTime,this.isActive=!1,t.events.dispatch(new Xo(e))}[ys.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,At.Infantry),this.disguisedAs={rules:i,owner:e.owner},this.isActive=!0))}getDefaultInfantryDisguise(e,t){switch(e){case qt.GDI:return t.alliedDisguise;case qt.Nod:return t.sovietDisguise;default:return}}[Or.onTick](e,t){e.rules.permaDisguise||(e.attackTrait?.attackState===en.JustFired||e.moveTrait.moveState!==ps.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 Xo(e))))}[br.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,At.Terrain)}}class Ko{constructor(){this.timer=new mn}isActive(){return this.timer.isActive()}setActiveFor(e,t){this.timer.setActiveFor(e,t)}[Or.onTick](e,t){this.timer.tick(t.currentTick)}}(Mo=Mo||{}).onChange=Symbol();class Jo{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(Mo).forEach(e=>{e[Mo.onChange](this.gameObject,i,t)}),this.gameObject.traits.filter(Ia).forEach(e=>{e[Ia.onChange](this.gameObject,i,t)})}expire(e){this.remainingTicks=0,this.notifyChange(!1,e)}isInvulnerable(){return this.isActive()&&this.invulnerable}[Or.onTick](e,t){0<this.remainingTicks&&(this.remainingTicks--,this.remainingTicks<=0&&this.notifyChange(!1,t))}dispose(){this.gameObject=void 0}}class eh{constructor(){this.timer=new mn}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()}[Or.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))}[Tr.onDestroy](e,t,i){this.timer.isActive()&&!i?.weapon?.warhead.rules.ivanBomb&&e.deathType!==Ir.None&&e.deathType!==Ir.Temporal&&(this.timer.reset(),this.detonateIvanWarhead(t,e))}detonateIvanWarhead(e,t){var i=e.rules.combatDamage.ivanDamage;let r=new So(e.rules.getWarhead(e.rules.combatDamage.ivanWarhead));var s=t.tile,a=t.tileElevation,n=t.isUnit()?t.zone:e.map.getTileZone(s),o=!!t.isUnit()&&t.onBridge;r.detonate(e,i,s,a,t.isBuilding()?mr.tile3dToWorld(s.rx+.5,s.ry+.5,s.z+a):t.position.worldPosition,n,o?zn.OnBridge:zn.None,e.createTarget(t,s),{...this.attackerInfo,weapon:void 0},!1,!1,void 0)}}class th{constructor(e){this.gameObject=e}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)}[ws.onUnspawn](e,t){this.controller&&(this.controller.mindControllerTrait.cleanTarget(e),!e.isDestroyed&&e.limboData&&this.restore(t))}dispose(){this.gameObject=void 0}}class ih{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)}[ws.onUnspawn](e,t){for(var i of this.targets)i.mindControllableTrait.restore(t);this.targets.length=0}dispose(){this.gameObject=void 0}}class rh{constructor(e){this.gameObject=e,this.ticksWhenWarpedOut=!0,this.attackers=new Set}[Or.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 r=i.temporalTrait.currentWeapon;if(!r)throw new Error(`Attacker "${i.name}" is no longer targeting "${e.name}"`);var s=r.rules.damage;if(this.eraseTicks-=s,this.eraseTicks<=0){e.deathType=Ir.Temporal,t.destroyObject(e,{player:i.owner,obj:i,weapon:r},!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 an||e instanceof ca)&&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}}[Tr.onDestroy](e,t){this.releaseCurrentTarget(t)}dispose(){this.gameObject=void 0,this.attackers.clear()}}class sh{constructor(e){this.target=e,this.type=vr.ObjectCloakChange}}class ah{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 sh(this.gameObject)))}resetCloakCooldown(){this.cooldownTicks=Math.floor(60*this.cloakDelayMinutes*is.BASE_TICKS_PER_SECOND)}[ys.onSpawn](e,t){this.resetCloakCooldown()}[Or.onTick](e,t){0<this.cooldownTicks&&this.cooldownTicks--,!(this.cooldownTicks<=0)||this.isActive||e.isVehicle()&&e.submergibleTrait&&!e.submergibleTrait.isSubmerged()||(this.isActive=!0,t.events.dispatch(new sh(this.gameObject)))}[br.onDamage](e,t){this.uncloak(t)}dispose(){this.gameObject=void 0}}class nh{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}[ys.onSpawn](t,i){var r=i.rules.getObject(t.rules.spawns,At.Aircraft);for(let e=0;e<t.rules.spawnsNumber;e++)this.pushNewSpawn(r,i,t)}[ws.onUnspawn](e,t){this.destroySpawns(t)}[Tr.onDestroy](e,t,i,r){this.destroySpawns(t,i,r)}pushNewSpawn(e,t,i){let r=t.createUnitForPlayer(e,i.owner);r.limboData={selected:!1,controlGroup:void 0},e.missileSpawn&&(r.pitch=90*t.rules.general.getMissileRules(e.name).pitchInitial),this.spawns.push(r),this.storage.push(r)}destroySpawns(e,t,i){for(var r of this.spawns)r.isDestroyed||(r.isSpawned&&!r.rules.missileSpawn&&r.crashableTrait?r.crashableTrait.crash(t):e.destroyObject(r,t,i));this.spawns.length=0,this.storage.length=0,this.missileLaunches.length=0}[Or.onTick](s,a){var t;if(this.spawns=this.spawns.filter(e=>!e.isDestroyed),this.missileLaunches=this.missileLaunches.filter(e=>!e.missile.isDestroyed),this.spawns.length<s.rules.spawnsNumber){var i=s.rules.spawnsNumber-this.spawns.length,r=a.rules.getObject(s.rules.spawns,At.Aircraft);for(let e=0;e<i;e++)r.missileSpawn&&e&&void 0===this.nextRegenTicks[e]?this.nextRegenTicks[e]=this.nextRegenTicks[0]:((t=this.nextRegenTicks)[e]??(t[e]=s.rules.spawnRegenRate),0<this.nextRegenTicks[e]&&this.nextRegenTicks[e]--),this.nextRegenTicks[e]<=0&&this.pushNewSpawn(r,a,s);this.nextRegenTicks=this.nextRegenTicks.filter(e=>0<e)}if(this.storage.length){if(this.nextReloadTicks??(this.nextReloadTicks=s.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=s.rules.spawnReloadRate}}else this.nextReloadTicks=void 0;for(let r of this.missileLaunches.slice()){var n=a.rules.general.getMissileRules(r.missile.name);if(r.pauseFrames??(r.pauseFrames=n.pauseFrames),0<r.pauseFrames&&r.pauseFrames--,r.pauseFrames<=0){var o=90*n.pitchFinal,n=90*(n.pitchFinal-n.pitchInitial)/n.tiltFrames;let i=r.missile;if(i.pitch<o)i.pitch=Math.min(o,i.pitch+n);else{i.unitOrderTrait.addTask(new xa(new ca(a,r.targetTile,!!r.targetBridge),new ss(()=>{var e,t;i.isDestroyed||(a.unspawnObject(i),i.dispose(),t=mr.vecGroundToWorld(Zr.toMapCoords(i.direction).multiplyScalar(mr.leptonsToWorld(1))),e=r.targetWorldPos.clone().add(t),t=a.map.getTileZone(r.targetTile),r.warhead.detonate(a,r.damage,r.targetTile,r.targetBridge?.tileElevation??0,e,t,r.targetBridge?zn.OnBridge:zn.None,r.target,{player:i.owner,obj:s,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(r),1)}}}}[fs.onChange](e,t,i){for(var r of this.spawns)r.isDestroyed||i.changeObjectOwner(r,e.owner)}[Ia.onChange](e,t,i){i&&this.removeMissileLaunches(t)}[Cr.onBeforeTeleport](e,t,i,r){r||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(r,s,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=r.veteranTrait?.isElite(),o=a.rules;if(r.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(r.rules.spawns!==o.general.dMisl.type)throw new Error(`Unhandled missile type "${r.rules.spawns}"`);e=n?o.combatDamage.dMislEliteWarhead:o.combatDamage.dMislWarhead,t=n?o.general.dMisl.eliteDamage:o.general.dMisl.damage}a=new So(a.rules.getWarhead(e));i.missileSpawnTrait.setDamage(t).setWarhead(a).setLauncher(r),this.missileLaunches.push({missile:i,targetTile:(s.obj?.isUnit()?s.obj:s).tile,targetBridge:s.getBridge(),targetWorldPos:s.getWorldCoords().clone(),target:s,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(r)}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 oh{[vs.onCrash](e,t){this.handleDestroy(e,t)}[Tr.onDestroy](e,t,i){i?.weapon?.warhead.rules.temporal||e.isCrashing||e.deathType!==Ir.Sink&&e.isSpawned&&this.handleDestroy(e,t)}handleDestroy(e,t){var i,r;(e.isVehicle()||e.isBuilding()||e.isOverlay())&&(i=e.isOverlay()?0:e.rules.minDebris,r=e.isOverlay()?t.rules.general.bridgeVoxelMax:e.rules.maxDebris,0<(r=t.generateRandomInt(i,r))&&this.spawnDebris(e,t,r))}spawnDebris(t,i,e){let r=t.isOverlay()?[]:t.isVehicle()?t.rules.debrisTypes:t.rules.debrisAnims;r.length||(r=i.rules.audioVisual.metallicDebris),r=r.filter(e=>i.rules.hasObject(e,At.VoxelAnim)||i.art.hasObject(e,At.Animation)),new Array(e).fill(0).map(()=>r[i.generateRandomInt(0,r.length-1)]).map(e=>i.createObject(At.Debris,e)).forEach(e=>{e.position.moveToLeptons(t.position.getMapPosition()),e.position.tileElevation=t.position.tileElevation,i.spawnObject(e,e.position.tile)})}}var hh=__webpack_require__(949);class lh extends Cs{constructor(e,t,i,r){super(At.Debris,e,t,i),this.direction=0,this.rotationAxis=new hh.Vector3,this.angularVelocity=0,this.zone=_r.Air,this.velocity=new hh.Vector3,this.collisionHelper=new Co(r)}static factory(e,t,i,r){return new this(e,t,i,r)}onSpawn(e){super.onSpawn(e),this.direction=e.generateRandomInt(0,359),this.xySpeed=hh.Math.lerp(0,this.rules.maxXYVel,e.generateRandom()),this.zSpeed=hh.Math.lerp(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=hh.Math.lerp(this.rules.minAngularVelocity,this.rules.maxAngularVelocity,e.generateRandom())}update(t){super.update(t);--this.zSpeed;var e=Zr.toMapCoords(this.direction).setLength(this.xySpeed),i=new hh.Vector3(e.x,this.zSpeed,e.y),r=this.position.clone(),e=mr.vecLeptonsToWorld(i).add(this.position.worldPosition);if(t.map.isWithinHardBounds(e)){this.position.moveByLeptons3(i);let e=!1;r=this.collisionHelper.checkCollisions(this.position,r,{cliffs:!0,ground:!0,shore:!1,walls:!0,buildings:!1});r&&(!([zn.Ground,zn.OnBridge].includes(r)&&0<this.rules.elasticity&&t.map.getTileZone(this.tile)!==_r.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?(this.velocity.set(0,0,0),this.detonate(t,r)):this.velocity.copy(i).multiplyScalar(mr.ISO_TILE_SIZE/mr.LEPTONS_PER_TILE)}else t.unspawnObject(this)}detonate(t,i=zn.None){var e,r=this.rules.warhead?t.rules.getWarhead(this.rules.warhead):void 0,s=this.zone=this.collisionHelper.computeDetonationZone(this.tile,this.tileElevation,i);let a;s===_r.Water?(e=t.rules.combatDamage.splashList,a=e[0]):(e=this.rules.expireAnim)&&t.rules.animationTypes.has(e)&&(a=e),this.explodeAnim=a;let n=new wo;if(a&&n.spawnSmudges(a,this.tile,t),t.destroyObject(this),r){let e=new So(r);e.detonate(t,this.rules.damage,this.tile,this.tileElevation,this.position.worldPosition,s,i,t.createTarget(void 0,this.tile),void 0,!1,!1,void 0,this.rules.damageRadius,!0)}}}class ch{constructor(e,t,i,r){this.tiles=e,this.tileOccupation=t,this.bridges=i,this.nextObjectId=r}create(e,t,i,r){let s,a;e===At.Smudge?(a=r.getOrCreateObject(t,At.Smudge),s=i.getObject(t,At.Smudge)):e===At.Debris?s=i.hasObject(t,At.VoxelAnim)?(a=r.getOrCreateObject(t,At.VoxelAnim),i.getObject(t,At.VoxelAnim)):(a=r.getAnimation(t),new er(At.Debris,r.getIni().getOrCreateSection(t))):a=e===At.Projectile?(s=i.getProjectile(t),s.inviso?new Br(At.Projectile,s,new h(t)):r.getProjectile(t)):(s=i.getObject(t,e),r.getObject(t,e));let n;switch(e){case At.Building:n=Pn.factory(t,s,i,a,this.tiles,this.bridges);break;case At.Infantry:n=Rs.factory(t,s,a,this.tileOccupation);break;case At.Vehicle:n=io.factory(t,s,a,i,this.tileOccupation);break;case At.Aircraft:n=ho.factory(t,s,a,i,this.tileOccupation);break;case At.Terrain:n=xn.factory(t,s,a);break;case At.Overlay:n=Rn.factory(t,s,a);break;case At.Smudge:n=Mn.factory(t,s,a);break;case At.Projectile:n=Lo.factory(t,s,a,this.tileOccupation);break;case At.Debris:n=lh.factory(t,s,a,this.tileOccupation);break;default:throw new Error("Not implemented")}if(n.id=this.nextObjectId.value++,n.position=new mo(this.tiles),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 qo(n,i),n.traits.add(n.armedTrait)),-1!==n.rules.ammo&&(o=n.rules.initialAmmo,n.ammoTrait=new Qo(n.rules.ammo,-1!==o?o:void 0),n.traits.add(n.ammoTrait)),n.unitOrderTrait=new lo(n),n.traits.addToFront(n.unitOrderTrait),(n.primaryWeapon||n.secondaryWeapon)&&(n.attackTrait=new rn(this.tiles,this.tileOccupation),n.traits.add(n.attackTrait)),(n.isInfantry()||n.isVehicle())&&n.rules.deployer&&(n.deployerTrait=new Fo(n),n.traits.add(n.deployerTrait)),(n.isInfantry()||n.isVehicle())&&n.rules.canDisguise&&(n.disguiseTrait=new Yo,n.traits.add(n.disguiseTrait)),n.rules.cloakable&&(n.cloakableTrait=new ah(n,i.general.cloakDelay),n.traits.add(n.cloakableTrait)),n.autoRepairTrait=new Ho(!n.isBuilding()),n.traits.add(n.autoRepairTrait),n.rules.trainable&&(n.veteranTrait=new $o(n,i.general.veteran),n.traits.add(n.veteranTrait)),(n.rules.selfHealing||n.rules.trainable)&&n.traits.add(new Zo),n.invulnerableTrait=new Ko,n.traits.add(n.invulnerableTrait),n.warpedOutTrait=new Jo(n),n.traits.add(n.warpedOutTrait),n.temporalTrait=new rh(n),n.traits.add(n.temporalTrait),n.rules.bombable&&(n.tntChargeTrait=new eh,n.traits.add(n.tntChargeTrait)),n.rules.immuneToPsionics||n.isBuilding()||(n.mindControllableTrait=new th(n),n.traits.add(n.mindControllableTrait)),[n.primaryWeapon,n.secondaryWeapon].some(e=>e?.warhead.rules.mindControl)&&(n.mindControllerTrait=new ih(n),n.traits.add(n.mindControllerTrait)),n.rules.spawns&&(n.airSpawnTrait=new nh,n.traits.add(n.airSpawnTrait)),n.rules.maxDebris&&n.traits.add(new oh)),n.isTechno()||n.isOverlay()||n.isTerrain()){var o=n.isOverlay()&&za.isBridge(i.getOverlayId(n.name));let e=n.rules.strength;!e&&n.isTerrain()&&(e=i.general.treeStrength),o&&(e=i.combatDamage.bridgeStrength),e&&(n.healthTrait=new Uo(e,n,i.audioVisual.conditionYellow,i.audioVisual.conditionRed),n.traits.add(n.healthTrait)),o&&(n.traits.add(new Wo(this.bridges)),za.getOverlayBridgeType(i.getOverlayId(n.name))===La.Concrete&&n.traits.add(new oh))}return n.isOverlay()&&n.isOverlay()&&Nn.getOverlayTibType(i.getOverlayId(n.name))!==An.NotSpecial&&n.traits.add(new Ln(n)),n.isTerrain()&&n.rules.spawnsTiberium&&n.traits.add(new zo(n.rules)),n.cachedTraits.tick.push(...n.traits.filter(Or)),n}}class uh{constructor(){this.allObjects=new Map,this._onObjectSpawned=new va,this._onObjectRemoved=new va}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 s=__webpack_require__(495),dh=__webpack_require__.n(s),ph=__webpack_require__(45);class gh{constructor(e,t,i,r,s){this.tiles=e,this.theaterType=t,this.mapBounds=i,this.tileOccupation=r,this.rules=s,this.passabilityGraphs=new Map,this.invalidatedTiles=new Map,this.handleTileOccupationUpdate=({tiles:e,object:i})=>{e=e.filter(e=>{let t=Kt.Foot;return i.isTerrain()&&i.rules.getOccupationBits(this.theaterType)!==$i.All&&(t=Kt.Wheel),i.isOverlay()&&i.isBridge()||this.isBlockerObject(i,e,!1,t)||this.isBlockerObject(i,e,!0,t)||i.isBuilding()&&i.rules.leaveRubble});e.length&&this.invalidateTiles(e)},r.onChange.subscribe(this.handleTileOccupationUpdate)}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,r,s,{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(r,s),d=!!l.hasNode(u);d||((h=new xr(this.tiles,this.mapBounds,r,{width:1,height:1},1,5,e=>0<this.getPassableSpeed(e,t,!1)&&Math.abs(e.z-r.z)<2&&!o?.({tile:e,onBridge:void 0,speed:100})).getNextTile())?(r=h,s=!1):(l.addNode(u,{tile:r,onBridge:void 0,speed:100}),a=Math.min(a,500)));let p=(0,ph.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 r=Math.abs(e.data.tile.rx-t.data.tile.rx),t=Math.abs(e.data.tile.ry-t.data.tile.ry);let s=r+t+(Math.SQRT2-2)*Math.min(r,t);return i?.parent&&(t=(r=i.parent.node).data.tile.rx-e.data.tile.rx,e=r.data.tile.ry-e.data.tile.ry,i.dirX=t,i.dirY=e,t===i.parent.dirX&&e===i.parent.dirY||(s+=.2)),s}}),g=p.find(this.getNodeId(e,i),this.getNodeId(r,s)).map(e=>({tile:e.data.tile,onBridge:e.data.onBridge}));return(g.length<2||o&&g.length&&(!n&&g[0].tile!==r||g[g.length-1].tile!==e))&&(g=[]),!d&&l.hasNode(u)&&l.removeNode(u),c.length&&this.updatePassability(c,t,l),g}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=dh()({multigraph:!0}),this.passabilityGraphs.set(t,i),this.tiles.forEach(e=>{this.computePassability(e,t,i)});return i}updatePassability(e,t,i,r=[]){let s=new Set;e.forEach(e=>{[e,this.tiles.getNeighbourTile(e,po.Right),this.tiles.getNeighbourTile(e,po.BottomRight),this.tiles.getNeighbourTile(e,po.Bottom),this.tiles.getNeighbourTile(e,po.BottomLeft)].filter(Pa).forEach(e=>s.add(e))}),e.forEach(e=>{i.removeNode(this.getNodeId(e,!1)),i.removeNode(this.getNodeId(e,!0))}),s.forEach(e=>{this.computePassability(e,t,i,r)})}computePassability(e,t,i,r=[]){var s=[po.Left,po.TopLeft,po.Top,po.TopRight];let a=this.getPassableSpeed(e,t,!1,r);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 s)this.connectTiles(e,void 0,n,t,i,r)}var h=this.tileOccupation.getBridgeOnTile(e);if(h&&(a=this.getPassableSpeed(e,t,!0,r),a)){var l,o=this.getNodeId(e,!0);i.hasNode(o)||i.addNode(o,{speed:a,tile:e,onBridge:h});for(l of s)this.connectTiles(e,h,l,t,i,r)}}connectTiles(t,i,r,s,a,n=[]){var o=this.tiles.getNeighbourTile(t,r);if(o){let e=this.tileOccupation.getBridgeOnTile(o);r=i||e?0:1;if(Math.abs(t.z+(i?.tileElevation??0)-(o.z+(e?.tileElevation??0)))>r){if(!e?.isHighBridge()&&!i?.isHighBridge()||0!==Math.abs(t.z-o.z)||!a.hasNode(this.getNodeId(t,!1)))return;i=e=void 0}s=this.getPassableSpeed(o,s,!!e,n);s&&(n=this.getNodeId(o,!!e),a.hasNode(n)||a.addNode(n,{speed:s,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,r=[],s=!1){if(!this.mapBounds.isWithinBounds(e))return 0;let a=i?e.onBridgeLandType:e.landType;if(void 0===a)return 0;a===Yt.Wall&&t===Kt.Track&&(a=Fi(e.terrainType));let n=this.rules.getLandRules(a);var o,h=n.getSpeedModifier(t);if(!h)return 0;if(!s)for(o of this.tileOccupation.getObjectsOnTile(e))if(this.isBlockerObject(o,e,i,t)&&!r.includes(o))return 0;return h}isBlockerObject(t,i,e,r){if(t.isTerrain()&&r===Kt.Foot&&t.rules.getOccupationBits(this.theaterType)!==$i.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 s=t.art.foundation;let e=t.rules.numberImpassableRows;return r===Kt.Foot?e=s.width:t.rules.weaponsFactory&&!e&&(e=s.width-1),jr({x:t.tile.rx,y:t.tile.ry,width:(e||s.width)-1,height:s.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())||r===Kt.Track&&t.rules.crushable)}findObstacles(t,e){var i,r,s=e.rules.speedType;let a=[];for(i of this.tileOccupation.getGroundObjectsOnTile(t.tile))i!==e&&(((r=this.isBlockerObject(i,t.tile,!!t.onBridge,s))||i.isUnit()&&(i.tile===t.tile&&i.onBridge===!!t.onBridge||i.moveTrait.reservedPathNodes.find(e=>e.tile===t.tile&&!!e.onBridge==!!t.onBridge))||s===Kt.Track&&i.rules.crushable||s===Kt.Foot&&i.isTerrain()||i.isBuilding()&&i.rules.gate)&&(r={obj:i,static:r},i.isInfantry()&&e.isInfantry()?i.position.desiredSubCell===e.position.desiredSubCell&&a.push(r):i.isTerrain()&&e.isInfantry()&&!i.rules.getOccupiedSubCells(this.theaterType).includes(e.position.desiredSubCell)||a.push(r)));return a}dispose(){this.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate)}}class mh{constructor(){this.mapBuildableSize={x:0,y:0,width:0,height:0},this.screenBounds={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}}fromMapFile(e,t){return 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/mr.ISO_TILE_SIZE,height:2*(e.fullSize.height-1)-1/mr.ISO_TILE_SIZE},this.localSize=this.computeLocalSize(e,t),this.rawLocalSize={...e.localSize},this.mapBuildableSize={x:this.localSize.x,y:this.localSize.y+4,width:this.localSize.width-2,height:this.localSize.height-8},this.screenBounds=this.computeScreenBounds(this.localSize),this}computeLocalSize(e,t){t=t.getCutoffTileHeight();return{x:2*e.localSize.x,y:2*e.localSize.y-4,height:Math.min(2*(e.localSize.height+5)-1,2*e.fullSize.height-2*(e.localSize.y-3)-t),width:2*e.localSize.width}}computeScreenBounds(e){var t=mr.screenTileToScreen(e.x,e.y),e=mr.screenTileToScreen(e.x+e.width,e.y+e.height-1);return{x:t.x,y:t.y,width:e.x-t.x,height:e.y-t.y}}getLocalSize(){return this.localSize}getRawLocalSize(){return this.rawLocalSize}getFullSize(){return this.fullSize}getClampedFullSize(){return this.clampedFullSize}getScreenBounds(){return this.screenBounds}isWithinBounds(e){return jr(this.mapBuildableSize,{x:e.dx,y:e.dy-e.z})}isWithinHardBounds(e){let t=mr.worldToScreen(e.x,e.z??e.y);t.x+=1,t.y+=.5;e=mr.screenToScreenTile(t.x,t.y);return jr(this.clampedFullSize,e)}}class fh{constructor(e,t,i,r,s,a,n,o=()=>!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=s,this.dirX=a,this.dirY=n,this.predicate=o,this.finished=!1,this.distance=r}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}}}var yh,wh=__webpack_require__(949);(s=yh=yh||{})[s.None=0]="None",s[s.Start=1]="Start",s[s.End=2]="End";class Th{constructor(e,t,i,r,s){this.tileSets=e,this.tiles=t,this.tileOccupation=i,this.mapBounds=r,this.rules=s,this.pieces=new Set,this.piecesByTile=new Map,this.handleTileOccupationUpdate=({object:t,type:i})=>{if(t.isOverlay()&&t.isBridge()){var r=t.tile;let e=this.piecesByTile.get(r);if("added"===i){if(e)throw new Error(`A bridge piece already exists at tile (${r.rx},${r.ry})`);var s=this.findBridgeAdjacentTiles(t);e={obj:t,prev:void 0,next:void 0,headType:this.computeHead(t,s.prev,s.next)},this.piecesByTile.set(r,e),this.pieces.add(e),this.connectPiece(e,s.prev,s.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 (${r.rx},${r.ry})`);t=e.prev,s=e.next;this.disconnectPiece(e),this.piecesByTile.delete(r),this.pieces.delete(e),t&&this.updateOverlayData(t),s&&this.updateOverlayData(s)}}},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=[],r=!1,e=t.next;if(t.headType===yh.None||e)for(;e;){if(i.push(e),e.headType!==yh.None){r=!0;break}e=e.next}else r=!0;if(r){r=!1,i.length=0;let e=t.prev;if(t.headType===yh.None||e)for(;e;){if(i.push(e),e.headType!==yh.None){r=!0;break}e=e.prev}else r=!0;if(r)return[]}return i}findBridgeAdjacentTiles(e){var t=e.isXBridge(),t=new wh.Vector2(Number(t),Number(!t));let i=new wh.Vector2(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 r=e.tile;if(e.isHighBridge()){r=r.z+e.tileElevation;return t?.z===r?yh.Start:i?.z===r?yh.End:yh.None}return za.isLowBridgeHead(e.overlayId)?za.isLowBridgeHeadStart(e.overlayId)?yh.Start:yh.End:yh.None}updateOverlayData(t){let i=t.obj,r=t.prev,s=t.next,a=!1;var n=i.isXBridge(),o=za.getOverlayBridgeType(i.overlayId);if(za.isLowBridgeHead(i.overlayId)){let e=0;za.isLowBridgeHeadStart(i.overlayId)?(e=n?20:22,s||e++):(e=n?18:24,r||e++),i.overlayId=(o===La.Wood?za.minLowBridgeWoodId:za.minLowBridgeConcreteId)+e,i.value=e,a=!0}else{let e;var h,l=(i.healthTrait?.health??100)<=50;e=t.headType!==yh.None?t.headType===yh.Start?s?l?6:(s.obj.healthTrait?.health??100)<=50?5:0:n?8:7:r?l?6:(r.obj.healthTrait?.health??100)<=50?4:0:n?7:8:(n||(h=r,r=s,s=h),r||s?r?s?(t=(r.obj.healthTrait?.health??100)<=50,h=(s.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===La.Wood?za.minLowBridgeWoodId:za.minLowBridgeConcreteId)+e,i.value=e,a=!0)}a&&(i.name=this.rules.getOverlayName(i.overlayId))}findClosestBridgeSpec(i){let e=new xr(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===yh.None)||!!this.tileSets.isHighBridgeBoundaryTile(e.tileNum)});var o=e.getNextTile();if(o){let r,t,s,a;var h=!this.tileOccupation.getBridgeOnTile(o);let e;if(h){var l=this.findHighBridgeBoundary(o);if(!l)return;r=l.tile,t=La.Concrete,this.tileSets.getSetNum(o.tileNum)===this.tileSets.getGeneralValue("WoodBridgeSet")&&(t=La.Wood),s=l.headType===k.TopLeft||l.headType===k.BottomRight,a=l.headType===k.TopLeft||l.headType===k.TopRight,e=l.headType}else{r=this.tileOccupation.getBridgeOnTile(o).tile;let e=this.getPieceAtTile(r);if(!e)throw new Error("Bridge head is not defined");var c=za.getOverlayBridgeType(e.obj.overlayId);if(c===La.NotBridge)throw new Error("Expected a bridge type");t=c,s=e.obj.isXBridge(),a=e.headType===yh.Start}var u=Number(s)*(a?1:-1),d=Number(!s)*(a?1:-1);let n;if(h){o=new fh(this.tiles,this.mapBounds,r,1,100,u,d,e=>e.z===r.z&&this.tileSets.isHighBridgeBoundaryTile(e.tileNum)).getNextTile(),c=this.tileSets.getSetNum(r.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=r.rx,g=r.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()!==s)return;e?.headType===(a?yh.End:yh.Start)&&(t=e),i++}n=t.obj.tile}return{start:a?r:n,end:a?n:r,type:t,isHigh:h}}}findHighBridgeBoundary(s){var a,e=this.tileSets.getTile(s.tileNum),n=this.tileSets.getHighBridgeHeadType(e.index);if(void 0!==n){let i=0,r=0;switch(n){case k.TopLeft:i=1,r=0;break;case k.BottomRight:i=-1,r=0;break;case k.TopRight:i=0,r=1;break;case k.BottomLeft:i=0,r=-1;break;case k.MiddleTlBr:i=1,r=0;break;case k.MiddleTrBl:i=0,r=1;break;default:throw new Error(`Unhandled head type "${n}"`)}let e=new xr(this.tiles,this.mapBounds,s,{width:1,height:1},0,5,e=>e.terrainType===Xt.Pavement&&e.z>=s.z&&e.tileNum===s.tileNum),t=[];for(;a=e.getNextTile();)t.push(a);if(t.sort((e,t)=>100*(i?i*(t.rx-e.rx):r*(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}" @ ${s.rx},${s.ry}`)}canBeRepaired(i){let e=this.createBridgePieceTileFinder(i,e=>!(this.getPieceAtTile(e)||this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===i.start.z)),r=!1,s;for(var a=i.start.rx!==i.end.rx?po.BottomLeft:po.BottomRight;s=e.getNextTile();){r=!0;let e=this.tiles.getNeighbourTile(s,a),t=this.tiles.getNeighbourTile(e,a);if(i.isHigh){if([s,e,t].find(e=>this.tileOccupation.getGroundObjectsOnTile(e).some(e=>e.isBuilding()&&!e.rules.invisibleInGame)))return!1}else if([s,e,t].find(e=>this.tileOccupation.getGroundObjectsOnTile(e).some(e=>!(e.isUnit()||e.isSmudge()||e.isOverlay()&&e.isBridgePlaceholder()))))return!1}return r}getPieceTiles(e){var t=e.obj.tile,i=e.obj.isXBridge()?po.BottomLeft:po.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 r=this.findHighBridgeBoundary(e);r&&i.add(r.tile)}return i}findMapNonBuildableTiles(e){let t=new Map;for(var i of e){i=this.findClosestBridgeSpec(i);i&&t.set(i.start.id+":"+i.end.id,i)}let r=[];for(var s of t.values()){var a,n=s.start.rx!==s.end.rx?po.BottomLeft:po.BottomRight;for(a of this.findNonBuildableTiles(s)){var o=this.tiles.getNeighbourTile(a,n),h=this.tiles.getNeighbourTile(o,n);r.push(a,o,h)}}return r}findBridgePieces(e){let t=this.createBridgePieceTileFinder(e,e=>!!this.getPieceAtTile(e)),i=[];for(var r;r=t.getNextTile();)i.push(this.getPieceAtTile(r));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 r;r=e.getNextTile();)i.push(r);return i}findNonBuildableTiles(t){let e=this.createBridgePieceTileFinder(t,e=>!(this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===t.start.z)),i=[];for(var r;r=e.getNextTile();)i.push(r);return i}createBridgePieceTileFinder(e,t){var i=e.start.rx!==e.end.rx;return new fh(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 bh=new(__webpack_require__(949).Vector2);class vh{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 r of this.regions)if(r.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 r of this.objects)e.containsPoint(r.key)&&t.push(r.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},r=this.generateRegions(),s=this.objects;this.objects=[],this.regions=[];for(t of r){let e=new vh(t,i);e.parentMap=this.parentMap,this.regions.push(e),e.parent=this}for(e of s)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 r=this.box.getCenter(bh);let s=i[0],a=s.clone();s.max.x=r.x,a.min.x=r.x,i.push(a);for(let e=0,t=i.length;e<t;e++)s=i[e],a=s.clone(),s.max.y=r.y,a.min.y=r.y,i.push(a);return i}}var Sh=__webpack_require__(949);class _h{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 r=[];var s=e.getFoundation();for(let t=1;t<=i;t++)for(let e=0;e<s.width;e++)r.push(new Sh.Vector2(e-t,-t));for(let t=1;t<=i;t++)for(let e=1;e<s.height;e++)r.push(new Sh.Vector2(-t,e-t));r.push(...e.art.addOccupy);for(let{x:t,y:i}of e.art.removeOccupy){var a=r.findIndex(e=>e.x===t&&e.y===i);-1!==a&&r.splice(a,1)}var n,o,h=e.tile;let l=[];for({x:n,y:o}of r){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 kh{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 r=u.getNeighbourTile(t,po.TopRight),s=u.getNeighbourTile(t,po.BottomRight),a=u.getNeighbourTile(t,po.BottomLeft),n=u.getNeighbourTile(t,po.TopLeft);r&&d.canConnectTiles(i,p.get(r))&&(e+=1),s&&d.canConnectTiles(i,p.get(s))&&(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,po.TopRight),h=u.getNeighbourTile(t,po.BottomRight),l=u.getNeighbourTile(t,po.BottomLeft),c=u.getNeighbourTile(t,po.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))}})}}var Oh,Ih=__webpack_require__(949);class Ch{constructor(e,t,i){this.mapFile=e,this.tiles=new yo(this.mapFile.tiles,t,i.general),this.mapBounds=(new mh).fromMapFile(this.mapFile,this.tiles),this.tileOccupation=new Ma(this.tiles),this.tileOcclusion=new _h(this.tiles),this.terrain=new gh(this.tiles,this.mapFile.theaterType,this.mapBounds,this.tileOccupation,i),this.bridges=new Th(t,this.tiles,this.tileOccupation,this.mapBounds,i);i=this.tiles.getMapSize();this.technosByTile=new vh(new Ih.Box2(new Ih.Vector2(0,0),new Ih.Vector2(i.width,i.height)),{getKey:e=>{e=e.isBuilding()?e.centerTile:e.tile;return new Ih.Vector2(e.rx,e.ry)},maxDepth:Math.ceil(Math.log2(Math.max(i.width,i.height)/5)),splitThreshold:10,joinThreshold:5}),this.mapFile.theaterType!==I.Snow&&kh.calculate(this.tiles,t)}get startingLocations(){return this.mapFile.startingLocations}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}getWaypoint(t){return this.mapFile.waypoints.find(e=>e.number===t)}isWithinBounds(e){return this.mapBounds.isWithinBounds(e)}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()}}const Ah=e=>"name"in e;(s=Oh=Oh||{})[s.Brutal=0]="Brutal",s[s.Medium=1]="Medium",s[s.Easy=2]="Easy";var Bh,Eh,Ph,xh,Nh,Rh,Mh,Dh,Lh,Fh;(new Map).set(Oh.Easy,"GUI:AIDummy");class jh{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}}(s=Bh=Bh||{})[s.Requested=0]="Requested",s[s.Formed=1]="Formed";class Uh{constructor(e){this.playerList=e,this.alliances=[]}findByPlayers(e,t){let i=new jh(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,Bh.Requested)}}cancelRequest(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==Bh.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!==Bh.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=Bh.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 r;if(r=this.findByPlayers(e,t))throw new Error(`An alliance already exists between players ${e.name} and ${t.name}`);return r={players:new jh(e,t),status:i},this.alliances.push(r),r}breakAlliance(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==Bh.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===Bh.Formed}getAllies(t){return this.filterByPlayer(t).filter(e=>e.status===Bh.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 r=new jh(t,i);return!!e.filter(e=>!e.equals(r)).length}getHostilePlayers(){var i,r=this.playerList.getCombatants();let s=[];for(let t=0;t<r.length;t++)for(let e=t+1;e<r.length;e++)this.getAllies(r[t]).includes(r[e])||(i=new jh(r[t],r[e]),s.push(i));return s}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 Wh{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())}getPlayable(){return this.players.filter(e=>e.playable)}getNeutral(){return this.players.find(e=>e.country?.side===qt.Civilian)}getAll(){return this.players}}(s=Eh=Eh||{})[s.None=0]="None",s[s.Hover=1]="Hover",s[s.Selected=2]="Selected",s[s.SelectedHover=3]="SelectedHover";class Vh{constructor(e){this.selectionLevel=Eh.None,e.isBuilding()&&e.rules.wall?this.maxSelectionLevel=Eh.None:this.maxSelectionLevel=e.rules.selectable?Eh.Selected|Eh.Hover:Eh.Hover}getSelectionLevel(){return this.selectionLevel}setSelectionLevel(e){this.selectionLevel=Math.min(this.maxSelectionLevel,e)}setHover(e){this.setSelectionLevel(e?this.selectionLevel|Eh.Hover:this.selectionLevel&~Eh.Hover)}setSelected(e){this.setSelectionLevel(e?this.selectionLevel|Eh.Selected:this.selectionLevel&~Eh.Selected)}isHovered(){return this.selectionLevel>>Eh.Hover&1}isSelected(){return this.selectionLevel>=Eh.Selected}getControlGroupNumber(){return this.controlGroupNumber}setControlGroupNumber(e){this.controlGroupNumber=e}}class zh{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 Vh(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 r=this.groups.get(e);r||(r=new Set,this.groups.set(e,r)),i&&([...r.values()].forEach(e=>this.selectionModelsByUnit.get(e)?.setControlGroupNumber(void 0)),r.clear());for(var s of t)r.add(s),this.getOrCreateSelectionModel(s).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 Hh{constructor(e){this._onChange=new va,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 Gh{constructor(e,t=void 0,i=0,r=new j(255,0,0)){this.name=e,this.country=t,this.startLocation=i,this.color=r,this.isAi=!1,this.defeated=!1,this.resigned=!1,this.objectsByType=new Map,this.objectsById=new Map,this.traits=new Is,this.credits=0,this.kills=0,this.score=0,this.unitsLost=0,this.unitsBuilt=0,this.cheerCooldownTicks=0,this.isObserver=!t,this.isNeutral=!!t&&!t.isPlayable()}get playable(){return!this.isNeutral}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(At.Building)}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 $h{constructor(){this.disabled=!0,this.activeEvents=[]}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}}const qh=(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 Zh{constructor(e,t,i,r,s){this.player=e,this.maxTechLevel=t,this.gameOpts=i,this.rules=r,this.allAvailableObjects=s,this.buildSpeedModifier=1,this.queues=new Map,this._onQueueUpdate=new va,this.primaryFactories=new Map,this.factoryCounts=new Map,this.veteranTypes=new Set,this.stolenTech=new Set}static factory(e,t,i,r){let s=new Zh(e,t.mpDialogSettings.techLevel,i,t,r);t=t.general.maximumQueuedObjects+1;return s.addQueue(oa.Structures,new Sa(oa.Structures,1,1)),s.addQueue(oa.Armory,new Sa(oa.Armory,1,1)),s.addQueue(oa.Infantry,new Sa(oa.Infantry,t,t)),s.addQueue(oa.Vehicles,new Sa(oa.Vehicles,t,t)),s.addQueue(oa.Ships,new Sa(oa.Ships,t,t)),s.addQueue(oa.Aircrafts,new Sa(oa.Aircrafts,0,t)),s}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 ${oa[e]}`);return t}getAllQueues(){return[...this.queues.values()]}getQueueTypeForObject(e){if(e.type===At.Building)return e.buildCat===Hi.Combat?oa.Armory:oa.Structures;if(e.type===At.Infantry)return oa.Infantry;if(e.type===At.Vehicle)return e.naval?oa.Ships:oa.Vehicles;if(e.type===At.Aircraft)return oa.Aircrafts;throw new Error(`Unsupported object type ${At[e.type]}`)}getQueueForObject(e){return this.getQueue(this.getQueueTypeForObject(e))}getQueueTypeForFactory(e){if(e===Gi.InfantryType)return oa.Infantry;if(e===Gi.UnitType)return oa.Vehicles;if(e===Gi.AircraftType)return oa.Aircrafts;if(e===Gi.NavalUnitType)return oa.Ships;throw new Error(`Unsupported factory type ${Gi[e]}`)}getFactoryTypeForQueueType(e){if(e===oa.Structures||e===oa.Armory)return Gi.BuildingType;if(e===oa.Infantry)return Gi.InfantryType;if(e===oa.Vehicles)return Gi.UnitType;if(e===oa.Aircrafts)return Gi.AircraftType;if(e===oa.Ships)return Gi.NavalUnitType;throw new Error(`Unsupported queue type ${oa[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!==Gi.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(qt.GDI):!e.requiresStolenSovietTech||this.stolenTech.has(qt.Nod)}getFactoryTypeFor(e){return e.type===At.Building?Gi.BuildingType:e.type===At.Infantry?Gi.InfantryType:e.type===At.Aircraft?Gi.AircraftType:e.naval?Gi.NavalUnitType:Gi.UnitType}meetsPrerequisites(e){let t=[...this.player.buildings].map(e=>e.name);var i;for(i of e.prerequisite)if(i=i.toUpperCase(),qh.has(i)){var r=qh.get(i);if(void 0===r)throw new Error(`Unknown prereqName ${i}`);var s,a=this.rules.general.prereqCategories.get(r);if(void 0===a)throw new Error(`Missing prerequisite category ${r} in rules`);let e=!1;for(s of a)if(-1!==t.indexOf(s)){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 ${Gi[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 Qh{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 Xh{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 Yh{constructor(e,t,i){this.rules=e,this.gameOpts=t,this.allAvailableObjects=i}createCombatant(e,t,i,r,s,a){let n=new Gh(e,t,i,r);return n.isAi=s,n.aiDifficulty=a,n.powerTrait=new Ta(n),n.traits.add(n.powerTrait),n.radarTrait=new $h,n.traits.add(n.radarTrait),n.superWeaponsTrait=new Qh,n.traits.add(n.superWeaponsTrait),n.production=Zh.factory(n,this.rules,this.gameOpts,this.allAvailableObjects),n.sharedDetectDisguiseTrait=new Xh,n}createObserver(e,t){let i=new Gh(e,void 0,void 0,t.colors.get("LightGrey"));return i.radarTrait=new $h,i.traits.add(i.radarTrait),i.radarTrait.setDisabled(!1),i}createNeutral(e,t){var i=[...e.countryRules.values()].find(e=>e.side===qt.Civilian);if(!i)throw new Error("Missing neutral country. No country found in rules with Civilian side");i=new Pr(i);let r=new Gh(t,i,void 0,e.colors.get("LightGrey"));return r.powerTrait=new Ta(r),r.traits.add(r.powerTrait),r}}(Ph=Ph||{}).onSpawn=Symbol(),(xh=xh||{}).onUnspawn=Symbol(),(Nh=Nh||{}).onChange=Symbol(),(Rh=Rh||{}).onTick=Symbol();class Kh{[Ph.onSpawn](e,t){e.isTechno()&&e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"add",t)}[xh.onUnspawn](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"remove",t)}[Eo.onChange](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"update",t)}[Nh.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))}[Mo.onChange](e,t,i){e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,i?"remove":"add",t)}[Rh.onTick](e){for(var t of e.getCombatants())t.powerTrait.updateBlackout(e)}isCapturablePower(e,t){return 0<e.rules.power&&!t.playable&&e.rules.needsEngineer}}class Jh{constructor(e){this.target=e,this.type=vr.BuildingSell}}class el{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(ka).forEach(e=>{e[ka.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 Jh(e)),e.dispose()}computeRefundValue(e){let t=0;return 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 tl{constructor(e,t){this.target=e,this.radarEnabled=t,this.type=vr.RadarOnOff}}class il{constructor(e,t,i){this.target=e,this.radarEventType=t,this.tile=i,this.type=vr.RadarEvent}}class rl{[Ph.onSpawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[xh.onUnspawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[aa.onPowerLow](e,t){this.updateRadarForPlayer(e,t)}[aa.onPowerRestore](e,t){this.updateRadarForPlayer(e,t)}[aa.onPowerChange](){}[Nh.onChange](e,t,i){e.rules.radar&&(this.updateRadarForPlayer(t,i),this.updateRadarForPlayer(e.owner,i))}[Mo.onChange](e,t){e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}updateRadarForPlayer(e,t){var i,r;e.radarTrait&&(i=e.radarTrait?.isDisabled(),r=![...e.buildings].find(e=>e.rules.radar&&!e.warpedOutTrait.isActive())||e.powerTrait.level===na.Low,e.radarTrait.setDisabled(r),i!==r&&t.events.dispatch(new tl(e,!r)))}[uo.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(r,e,s,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 Ws(a.map.tileOccupation);!!n.activeEvents.find(e=>e.type===r&&i.isInTileRange(s,e.tile,0,t.getEventSuppresionDistance(e.type)))||(n.activeEvents.push({startTick:a.currentTick,tile:s,type:r}),a.events.dispatch(new il(e,r,s)))}}}class sl{constructor(e){this.target=e,this.type=vr.InsufficientFunds}}class al{constructor(e,t){this.rules=e,this.speedCheat=t,this.availableObjectRules=new Set;t=60*e.general.buildSpeed*is.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)})}[Rh.onTick](e){for(var t of e.getCombatants())for(var i of t.production.getAllQueues())this.tickQueue(i,t,e)}[Ph.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===Gi.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t)):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[xh.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===Gi.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t))):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[Nh.onChange](e,t,i){var r;e.isBuilding()?(this.ensurePrerequisites(t),(r=e.rules.factory)&&(t.production?.getPrimaryFactory(r)===e&&t.production.crownPrimaryFactoryHeir(r),e.owner.production&&!e.owner.production.getPrimaryFactory(r)&&e.owner.production.setPrimaryFactory(e),t.production?.decrementFactoryCount(r),e.owner.production?.incrementFactoryCount(r),r===Gi.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))}[aa.onPowerLow](e){e.production&&(e.production.buildSpeedModifier=this.computeLowPowerBuildSpeedModifier(e.powerTrait.power,e.powerTrait.drain))}[aa.onPowerRestore](e){e.production&&(e.production.buildSpeedModifier=1)}[aa.onPowerChange](e){e.powerTrait?.level===na.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,r){i.production&&r.afterTick(()=>{var e=[...i.buildings].filter(e=>e.helipadTrait).reduce((e,t)=>e+t.dockTrait.numberOfDocks,0),t=i.getOwnedObjectsByType(At.Aircraft,!0).filter(e=>r.rules.general.padAircraft.includes(e.name)).length;i.production.getQueueForFactory(Gi.AircraftType).maxSize=Math.max(0,e-t)})}tickQueue(r,s,a){if(r.status===ha.Active){let e=!1,t=r.getFirst();var n=s.production.getFactoryTypeForQueueType(r.type),o=s.production.getFactoryCount(n),h=s.production.buildSpeedModifier,n=1/this.rules.general.multipleFactory**(o-1),o=t.rules.wall?1/this.rules.general.wallBuildSpeedCoefficient:1;let i=this.speedCheat.value?150:this.baseBuildSpeed*h*n*o;h=.06*60*is.BASE_TICKS_PER_SECOND,n=t.creditsEach?t.creditsEach/i:h;n/(60*is.BASE_TICKS_PER_SECOND)<.06&&(i=t.creditsEach/h);var l,o=s.credits,h=t.creditsEach-t.creditsSpent,h=Math.min(s.credits,i+t.creditsSpentLeftover,h);0<h?(l=Math.floor(h),t.creditsSpentLeftover=h-l,l&&(t.creditsSpent+=l,t.progress=t.creditsSpent/t.creditsEach,s.credits-=l,e=!0)):t.creditsEach||(l=t.progress*n,t.progress=Math.min(1,(1+l)/n),e=!0),e&&1===t.progress&&(r.status=ha.Ready),0<o&&!s.credits&&a.events.dispatch(new sl(s)),e&&r.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]}}(Mh=Mh||{}).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 vn).fromTiles(this.map.tiles);for(var r of t.getCombatants()){let e=i.clone();this.shroudByPlayer.set(r,e),this.revealObjects(e,r,t),e.update()}}[Rh.onTick](e){for(var[t,i]of this.shroudByPlayer)t.defeated&&!t.isObserver?this.shroudByPlayer.delete(t):i.update()}[Nh.onChange](e,t,i){if(e.isBuilding()&&e.rules.spySat&&(this.revealMap(e.owner,i),t.getOwnedObjectsByType(At.Building).find(e=>e.rules.spySat)||this.resetShroud(t,i)),e.isSpawned)for(var r of[e.owner,...i.alliances.getAllies(e.owner)])this.shroudByPlayer.get(r)?.revealFrom(e)}[Mh.onChange](t,e,i){if(e){let e=this.getPlayerShroud(t.players.first);var r,s,t=i.alliances.getAllies(t.players.first).map(e=>this.getPlayerShroud(e)).filter(Pa);for(r of t)e.merge(r);e.invalidateFull();for(s of t)s.copy(e),s.invalidateFull()}}[Ph.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(rl).addEventForPlayer(Zt.EnemyObjectSensed,i,e.centerTile,t))}e.gapGeneratorTrait&&this.gapGenerators.add(e)}}[xh.onUnspawn](e,t){e.isBuilding()&&(e.rules.spySat&&(e.owner.getOwnedObjectsByType(At.Building).find(e=>e.rules.spySat)||this.resetShroud(e.owner,t)),e.rules.revealToAll&&this.revealedToAll.delete(e),e.gapGeneratorTrait&&this.gapGenerators.delete(e))}[aa.onPowerLow](e,t){this.updateGaps(t,e)}[aa.onPowerRestore](e,t){this.updateGaps(t,e)}[aa.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 r;for(r of[...e.getOwnedObjects(),...i.alliances.getAllies(e).map(e=>e.getOwnedObjects()).flat()])t.revealFrom(r);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,un.Darken,!0)}dispose(){this.map.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate)}}class ol extends Rr{onTick(e){return!(e.buildStatus!==Cn.BuildDown&&(e.buildStatus=Cn.BuildDown,!e.rules.wall))||(this.children.push(new rs(.035)),!1)}}class hl{constructor(e,t,i,r,s,a){this.player=e,this.production=t,this.rules=i,this.art=r,this.map=s,this.game=a}getAdjacentRect(e,t,i){return{x:e.x-i,y:e.y-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():[]]){var r={x:t.tile.rx,y:t.tile.ry},s=this.rules.getBuilding(t.name),a=this.art.getObject(t.name,At.Building).foundation;s.baseNormal&&i.push(this.getAdjacentRect(r,a,e))}return i}meetsAdjacency(e,t){var i,r,s;for(i of this.getAdjacencyMap(t))if(r=e,s=i,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;return!1}canBuild(e){return this.production.isAvailableForProduction(this.rules.getBuilding(e))}canBuildAt(e,t,i,r=!1){var s=this.rules.getBuilding(e),a=this.art.getObject(e,At.Building);let n=[];var o=a.foundation,h=r?t:this.normalizePlacementTileCoords(e,t);let l=!0;t={x:h.rx,y:h.ry,width:o.width,height:o.height};s.constructionYard||this.meetsAdjacency(t,s.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:!(!this.map.isWithinBounds(u)||!l)&&(this.isTileBuildable(u,s,i)&&!this.game.mapShroudTrait.getPlayerShroud(this.player)?.isShrouded(u))})}if(s.wall&&n[0].buildable){let e=this.getWallConnectingTiles(h,s);e.forEach(e=>{n.push({rx:e.rx,ry:e.ry,buildable:!0})})}return n}placeAt(e,t,i=!1){let r=[],s=this.rules.getBuilding(e),a=i?t:this.normalizePlacementTile(e,t);if(s.wall){let t=[[a,s]],e=this.getWallConnectingTiles(a,s);e.forEach(e=>{e!==a&&t.push([e,s])});for(var n of t)r.push(this.executePlacement(n[0],n[1]));e.forEach(e=>{e=this.map.getObjectsOnTile(e).find(e=>e.isBuilding()&&e.name===s.name&&e.owner===this.player);this.connectWall(e)})}else{var o,t=this.executePlacement(a,s);r.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 r}normalizePlacementTileCoords(e,t){e=this.art.getObject(e,At.Building).foundationCenter;return{rx:t.rx-e.x,ry:t.ry-e.y}}normalizePlacementTile(e,t){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 xa(new ol,new ss(()=>{this.game.unspawnObject(e),e.rules.wall&&this.updateAdjacentWalls(e),t()})).setCancellable(!1))}executePlacement(e,t){let i=this.game.createObject(At.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,r){var s,a=r.guardRange+1;let n=[];for(s of[[0,1],[0,-1],[1,0],[-1,0]]){let t=[];for(let e=0;e<a;++e){var o={x:i.rx+s[0]*e,y:i.ry+s[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===r.name&&e.owner===this.player)){n=n.concat(t);break}if(!this.isTileBuildable(o,r))break;t.push(o)}}return n}getAdjacentBuildingData(e,t){var i;let r=[];for(i of[[0,1],[0,-1],[1,0],[-1,0]]){var s={x:e.rx+i[0],y:e.ry+i[1]},a=this.map.tiles.getByMapCoords(s.x,s.y);a&&((s=this.map.getObjectsOnTile(a).find(e=>e.isBuilding()&&e.name===t&&e.owner===this.player))&&r.push({direction:i,tile:a,building:s}))}return r}updateAdjacentWalls(t){let e=new Ba(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.getGroundObjectsOnTile(e).some(e=>!(i?.includes(e)||e.isBuilding()&&e.rules.invisibleInGame||e.isSmudge()))&&(t.waterBound?0<this.rules.getLandRules(e.landType).getSpeedModifier(Kt.Float):0===e.rampType&&this.rules.getLandRules(e.landType).buildable)}}class ll{static generate(e,t,i,r){var s,a=i.reduce((e,t)=>e+t.cost,0)/i.length*e;let n=[],o=a,h=(i=i.filter(e=>e.isAvailableTo(r)&&e.hasOwner(r))).filter(e=>t.includes(e.name));for(s of h){if(o<=0)break;var l=2/3/h.length,l=Math.ceil(l*a/s.cost);o-=l*s.cost,n.push({name:s.name,type:At.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:At.Infantry,count:d})}return n}}class cl{constructor(){this.dispatcher=new va,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,r;return r="function"==typeof e?e:(i=e,t),void 0===i?(this.dispatcher.subscribe(r),()=>this.unsubscribe(r)):this.subscribeType(i,r)}unsubscribe(e,t){let i=void 0,r;r="function"==typeof e?e:(i=e,t),void 0===i?this.dispatcher.unsubscribe(r):this.unsubscribeType(i,r)}subscribeType(e,t){let i=this.dispatchersByType.get(e);return i||(i=new va,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){this.gameObject=e,this.attackerInfo=t,this.type=vr.ObjectDestroy}}class dl{constructor(e){this.target=e,this.type=vr.PlayerDefeated}}(Dh=Dh||{}).onDestroy=Symbol();class pl{constructor(e,t){this.target=e,this.prevOwner=t,this.type=vr.ObjectOwnerChange}}class gl{constructor(e){this.gameObject=e,this.type=vr.ObjectUnspawn}}class ml{constructor(e){this.gameObject=e,this.type=vr.ObjectSpawn}}class fl{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}}(s=Lh=Lh||{})[s.NoAction=0]="NoAction",s[s.QuitGame=1]="QuitGame",s[s.ObserveGame=2]="ObserveGame",s[s.PlaceBuilding=3]="PlaceBuilding",s[s.SellBuilding=4]="SellBuilding",s[s.ToggleRepair=5]="ToggleRepair",s[s.SelectUnits=6]="SelectUnits",s[s.OrderUnits=7]="OrderUnits",s[s.UpdateQueue=8]="UpdateQueue",s[s.ToggleAlliance=9]="ToggleAlliance",s[s.ActivateSuperWeapon=10]="ActivateSuperWeapon",s[s.PingLocation=11]="PingLocation";class yl{constructor(e){this.actionType=e}unserialize(e){}serialize(){return[]}print(){return""}}(s=Fh=Fh||{})[s.Add=0]="Add",s[s.Cancel=1]="Cancel",s[s.Pause=2]="Pause",s[s.Resume=3]="Resume";class wl extends yl{constructor(e){super(Lh.UpdateQueue),this.game=e}unserialize(e){this.queueType=Number(e[0]),this.updateType=Number(e[1]),this.updateType!==Fh.Add&&this.updateType!==Fh.Cancel||(this.item=this.game.rules.getObject(e[2],Number(e[3])),this.quantity=Number(e[4]))}serialize(){let e=[""+this.queueType,""+this.updateType];return this.updateType!==Fh.Add&&this.updateType!==Fh.Cancel||e.push(""+this.item.name,""+this.item.type,""+this.quantity),e}print(){return this.updateType===Fh.Resume?`Resume queue ${oa[this.queueType]}`:this.updateType===Fh.Add?`Add to queue ${this.item.name} x ${this.quantity}`:this.updateType===Fh.Pause?`Put queue ${oa[this.queueType]} on hold.`:this.updateType===Fh.Cancel?`Cancel ${this.item.name} x ${this.quantity}`:`Unhandled queue update type ${this.updateType}`}process(){let t=this.game.getPlayerByName(this.playerName),i=this.item,r=t.production.getQueue(this.queueType);if(this.updateType===Fh.Resume)r.status===ha.OnHold&&(r.status=ha.Active);else if(this.updateType===Fh.Add){let e=r.find(i);var s;(r.status===ha.Active||r.status===ha.Idle||r.status===ha.OnHold&&e[0]!==r.getFirst()||r.status===ha.Ready&&i.type!==At.Building)&&(s=e.reduce((e,t)=>e+t.quantity,0),Number.isFinite(i.buildLimit)&&t.getOwnedObjectsByType(i.type,!0).filter(e=>e.name===i.name).length+s>=i.buildLimit||t.production.isAvailableForProduction(i)&&(a=Math.min(r.maxSize-r.currentSize,r.maxItemQuantity-s),0<(n=Math.min(this.quantity,a))&&r.push(i,n,i.cost)))}else if(this.updateType===Fh.Cancel){if([ha.Ready,ha.OnHold,ha.Active].includes(r.status)){let e=r.find(i);var a,n;e.length&&(a=e.reduce((e,t)=>e+t.quantity,0),0<(n=Math.min(a,this.quantity))&&(r.pop(i,n),n===a&&(t.credits+=e[0].creditsSpent)))}}else this.updateType===Fh.Pause&&r.status===ha.Active&&(r.status=ha.OnHold)}}var Tl=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},bl=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class vl{constructor(e,t,i,r){Cl.add(this),_l.set(this,void 0),kl.set(this,void 0),Ol.set(this,void 0),Il.set(this,void 0),Tl(this,_l,t,"f"),Tl(this,kl,i,"f"),Tl(this,Ol,e,"f"),Tl(this,Il,r,"f")}placeBuilding(t,i,r){bl(this,Cl,"m",Al).call(this,Lh.PlaceBuilding,e=>{e.name=t,e.tile={x:i,y:r}})}sellBuilding(t){bl(this,Cl,"m",Al).call(this,Lh.SellBuilding,e=>{e.buildingId=t})}toggleRepairWrench(t){bl(this,Cl,"m",Al).call(this,Lh.ToggleRepair,e=>{e.buildingId=t})}toggleAlliance(t,i){bl(this,Cl,"m",Al).call(this,Lh.ToggleAlliance,e=>{e.toPlayerName=t,e.toggle=i})}pauseProduction(t){bl(this,Cl,"m",Al).call(this,Lh.UpdateQueue,e=>{e.queueType=t,e.updateType=Fh.Pause})}resumeProduction(t){bl(this,Cl,"m",Al).call(this,Lh.UpdateQueue,e=>{e.queueType=t,e.updateType=Fh.Resume})}queueForProduction(t,e,i,r){let s=bl(this,Ol,"f").rules.getObject(e,i);bl(this,Cl,"m",Al).call(this,Lh.UpdateQueue,e=>{e.queueType=t,e.updateType=Fh.Add,e.item=s,e.quantity=r})}unqueueFromProduction(t,e,i,r){let s=bl(this,Ol,"f").rules.getObject(e,i);bl(this,Cl,"m",Al).call(this,Lh.UpdateQueue,e=>{e.queueType=t,e.updateType=Fh.Cancel,e.item=s,e.quantity=r})}activateSuperWeapon(t,i,r){bl(this,Cl,"m",Al).call(this,Lh.ActivateSuperWeapon,e=>{e.superWeaponType=t,e.tile={x:i.rx,y:i.ry},e.tile2=r?{x:r.rx,y:r.ry}:void 0})}orderUnits(t,i,r,s,a){bl(this,Cl,"m",Al).call(this,Lh.SelectUnits,e=>{e.unitIds=t});let n;if(r){let e,t;if(s){e=void 0;var o=bl(this,Ol,"f").map.tiles.getByMapCoords(r,s);if(!o)throw new Error(`No tile found at rx,ry=${r},${s}`);t=o,a&&(e=bl(this,Ol,"f").map.tileOccupation.getBridgeOnTile(o))}else e=bl(this,Ol,"f").getObjectById(r),t=e.tile;n=bl(this,Ol,"f").createTarget(e,t)}bl(this,Cl,"m",Al).call(this,Lh.OrderUnits,e=>{e.orderType=i,e.target=n})}quitGame(){bl(this,Cl,"m",Al).call(this,Lh.QuitGame)}}var Sl,_l=new WeakMap,kl=new WeakMap,Ol=new WeakMap,Il=new WeakMap,Cl=new WeakSet,Al=function(e,t){if(!bl(this,Il,"f"))throw new Error("Player name must be set before issuing any actions");let i=bl(this,_l,"f").create(e);i.playerName=bl(this,Il,"f"),t?.(i),bl(this,kl,"f").push(i)},Bl=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},El=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};(s=Sl=Sl||{})[s.ObjectOwnerChange=0]="ObjectOwnerChange",s[s.ObjectSpawn=1]="ObjectSpawn",s[s.ObjectUnspawn=2]="ObjectUnspawn",s[s.ObjectDestroy=3]="ObjectDestroy";class Pl{constructor(e){Rl.add(this),xl.set(this,void 0),Nl.set(this,[]),Bl(this,xl,e,"f")}subscribe(e,t){let i=void 0,r;r="function"==typeof e?e:(i=e,t);t=El(this,xl,"f").subscribe(e=>{e=El(this,Rl,"m",Ml).call(this,e);!e||void 0!==i&&i!==e.type||r(e)});return El(this,Nl,"f").push(t),t}dispose(){for(var e of El(this,Nl,"f"))e();El(this,Nl,"f").length=0}}var xl=new WeakMap,Nl=new WeakMap,Rl=new WeakSet,Ml=function(t){switch(t.type){case vr.ObjectOwnerChange:return{type:Sl.ObjectOwnerChange,prevOwnerName:t.prevOwner.name,newOwnerName:t.target.owner.name,target:t.target.id};case vr.ObjectSpawn:return{type:Sl.ObjectSpawn,target:t.gameObject.id};case vr.ObjectUnspawn:return{type:Sl.ObjectUnspawn,target:t.gameObject.id};case vr.ObjectDestroy:{let e=t;return e.gameObject.isProjectile()?void 0:{type:Sl.ObjectDestroy,target:e.gameObject.id,attackerInfo:e.attackerInfo?{playerName:e.attackerInfo.player.name,objId:e.attackerInfo.obj?.id,weaponName:e.attackerInfo.weapon?.rules.name}:void 0}}default:return}},Dl=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},Ll=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class Fl{constructor(e){Wl.add(this),jl.set(this,void 0),Ul.set(this,void 0),Dl(this,jl,e,"f"),Dl(this,Ul,e.map,"f")}getStartingLocations(){return Ll(this,Ul,"f").startingLocations}getTheaterType(){return Ll(this,Ul,"f").getTheaterType()}getTile(e,t){t=Ll(this,Ul,"f").tiles.getByMapCoords(e,t);if(t&&Ll(this,Ul,"f").mapBounds.isWithinBounds(t))return t}getTilesInRect(e,t){return Ll(this,Ul,"f").tiles.getInRectangle(e,t).filter(e=>Ll(this,Ul,"f").mapBounds.isWithinBounds(e))}getObjectsOnTile(e){return Ll(this,Ul,"f").getObjectsOnTile(e).map(e=>e.id)}hasBridgeOnTile(e){return!!e.onBridgeLandType}hasHighBridgeOnTile(e){return!!Ll(this,Ul,"f").tileOccupation.getBridgeOnTile(e)?.isHighBridge()}isPassableTile(e,t,i){return 0<Ll(this,Ul,"f").terrain.getPassableSpeed(e,t,i)}isVisibleTile(e,t){var i=Ll(this,jl,"f").getPlayerByName(t);if(!i)throw new Error(`Player "${t}" doesn't exist`);return!Ll(this,jl,"f").mapShroudTrait.getPlayerShroud(i)?.isShrouded(e)}getTileResourceData(e){e=Ll(this,Ul,"f").getObjectsOnTile(e).find(e=>e.isOverlay()&&e.isTiberium()||e.isTerrain()&&e.rules.spawnsTiberium);return e?Ll(this,Wl,"m",Vl).call(this,e):void 0}getAllTilesResourceData(){var e;let t=[];for(e of Ll(this,jl,"f").getWorld().getAllObjects()){var i=Ll(this,Wl,"m",Vl).call(this,e);i&&t.push(i)}return t}}var jl=new WeakMap,Ul=new WeakMap,Wl=new WeakSet,Vl=function(t){let i;if(t.isOverlay()&&t.isTiberium()){let e=t.traits.get(Ln);var r=e.getTiberiumType(),s=e.getBailCount();i={tile:t.tile,ore:r===Bn.Ore?s:0,gems:r===Bn.Gems?s:0,spawnsOre:!1}}else t.isTerrain()&&t.rules.spawnsTiberium&&(i={tile:t.tile,ore:0,gems:0,spawnsOre:!0});return i},zl=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},Hl=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class Gl{constructor(e){$l.set(this,void 0),zl(this,$l,e,"f")}get allObjectRules(){return Hl(this,$l,"f").allObjectRules}get buildingRules(){return Hl(this,$l,"f").buildingRules}get infantryRules(){return Hl(this,$l,"f").infantryRules}get vehicleRules(){return Hl(this,$l,"f").vehicleRules}get aircraftRules(){return Hl(this,$l,"f").aircraftRules}get terrainRules(){return Hl(this,$l,"f").terrainRules}get overlayRules(){return Hl(this,$l,"f").overlayRules}get countryRules(){return Hl(this,$l,"f").countryRules}get general(){return Hl(this,$l,"f").general}get ai(){return Hl(this,$l,"f").ai}get crateRules(){return Hl(this,$l,"f").crateRules}get combatDamage(){return Hl(this,$l,"f").combatDamage}get radiation(){return Hl(this,$l,"f").radiation}hasObject(e,t){return Hl(this,$l,"f").hasObject(e,t)}getObject(e,t){return Hl(this,$l,"f").getObject(e,t)}getBuilding(e){return Hl(this,$l,"f").getBuilding(e)}getWeapon(e){return Hl(this,$l,"f").getWeapon(e)}getWarhead(e){return Hl(this,$l,"f").getWarhead(e)}getProjectile(e){return Hl(this,$l,"f").getProjectile(e)}getOverlayName(e){return Hl(this,$l,"f").getOverlayName(e)}getOverlayId(e){return Hl(this,$l,"f").getOverlayId(e)}getOverlay(e){return Hl(this,$l,"f").getOverlay(e)}getCountry(e){return Hl(this,$l,"f").getCountry(e)}getMultiplayerCountries(){return Hl(this,$l,"f").getMultiplayerCountries()}getIni(){return Hl(this,$l,"f").getIni()}}var $l=new WeakMap,ql=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},Zl=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class Ql{constructor(e,t){tc.add(this),Jl.set(this,void 0),ec.set(this,void 0),ql(this,Jl,e,"f"),ql(this,ec,t,"f"),this.mapApi=new Fl(e),this.rulesApi=new Gl(e.rules)}isPlayerDefeated(e){return Zl(this,Jl,"f").getPlayerByName(e).defeated}areAlliedPlayers(e,t){var i=Zl(this,Jl,"f").getPlayerByName(e);if(!i)throw new Error(`Player "${e}" doesn't exist`);e=Zl(this,Jl,"f").getPlayerByName(t);if(!e)throw new Error(`Player "${t}" doesn't exist`);return Zl(this,Jl,"f").alliances.areAllied(i,e)}canPlaceBuilding(e,t,i){var r=Zl(this,Jl,"f").getPlayerByName(e);if(!r)throw new Error(`Player "${e}" doesn't exist`);let s=Zl(this,Jl,"f").getConstructionWorker(r).canBuildAt(t,i,void 0,!0);return!s.some(e=>!e.buildable)}getBuildingPlacementData(e){e=Zl(this,Jl,"f").art.getObject(e,At.Building);return{foundation:e.foundation,foundationCenter:e.foundationCenter}}getPlayers(){return Zl(this,Jl,"f").getPlayable().map(e=>e.name)}getPlayerData(e){let t=Zl(this,Jl,"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===na.Low},radarDisabled:!!t.radarTrait?.isDisabled()}}getAllTerrainObjects(){return Zl(this,Jl,"f").getWorld().getAllObjects().filter(e=>e.isTerrain()).map(e=>e.id)}getAllUnits(){return Zl(this,Jl,"f").getWorld().getAllObjects().filter(e=>e.isTechno()).map(e=>e.id)}getVisibleUnits(e,t,i=()=>!0){const r=Zl(this,Jl,"f").getPlayerByName(e);if(!r)throw new Error(`Player "${e}" doesn't exist`);if("self"===t)return r.getOwnedObjects().filter(e=>i(e.rules)).map(e=>e.id);let s;if("allied"===t)s=e=>e.owner===r||Zl(this,Jl,"f").alliances.areAllied(e.owner,r);else{if("hostile"!==t)throw new Error(`Unexpected type ${t}`);{let t=Zl(this,Jl,"f").mapShroudTrait.getPlayerShroud(r);s=e=>!t?.isShrouded(e.tile)&&e.owner!==r&&!Zl(this,Jl,"f").alliances.areAllied(e.owner,r)}}return Zl(this,Jl,"f").getWorld().getAllObjects().filter(e=>e.isTechno()&&s(e)&&i(e.rules)).map(e=>e.id)}getGameObjectData(t){if(Zl(this,Jl,"f").getWorld().hasObjectId(t)){let e=Zl(this,Jl,"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}}}getUnitData(t){var i=this.getGameObjectData(t);if(i){let e=Zl(this,Jl,"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?Zl(this,tc,"m",ic).call(this,e.primaryWeapon):void 0,secondaryWeapon:e.secondaryWeapon?Zl(this,tc,"m",ic).call(this,e.secondaryWeapon):void 0,deathWeapon:e.armedTrait?.deathWeapon?Zl(this,tc,"m",ic).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(),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,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 Zl(this,Jl,"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 Zl(this,Jl,"f").rules.general}getRulesIni(){return Zl(this,Jl,"f").rules.getIni()}getArtIni(){return Zl(this,Jl,"f").art.getIni()}generateRandomInt(e,t){if(Zl(this,ec,"f"))return Zl(this,Jl,"f").generateRandomInt(e,t);var i=this.generateRandom();return Math.round(i*(t-e))+e}generateRandom(){return Zl(this,ec,"f")?Zl(this,Jl,"f").generateRandom():Math.random()}getTickRate(){return Zl(this,Jl,"f").speed.value*is.BASE_TICKS_PER_SECOND}getCurrentTick(){return Zl(this,Jl,"f").currentTick}}var Xl,Yl,Kl,Jl=new WeakMap,ec=new WeakMap,tc=new WeakSet,ic=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()}},rc=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},sc=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class ac{constructor(e){Xl.set(this,void 0),rc(this,Xl,e,"f")}isAvailableForProduction(e){return sc(this,Xl,"f").isAvailableForProduction(e)}getAvailableObjects(t){let e=sc(this,Xl,"f").getAvailableObjects();return void 0!==t&&(e=e.filter(e=>this.getQueueTypeForObject(e)===t)),e}getQueueTypeForObject(e){return sc(this,Xl,"f").getQueueTypeForObject(e)}getQueueData(e){let t=sc(this,Xl,"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}))}}}Xl=new WeakMap;class nc{constructor(e,t){this.name=e,this.country=t}setGameApi(e){this.gameApi=e}setActionsApi(e){this.actionsApi=e}setProductionApi(e){this.productionApi=e}onGameStart(e){}onGameTick(e){}onGameEvent(e,t){}}(s=Yl=Yl||{})[s.Initial=0]="Initial",s[s.Deployed=1]="Deployed",s[s.Attacking=2]="Attacking",s[s.Defeated=3]="Defeated";class oc extends nc{constructor(){super(...arguments),this.botState=Yl.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 Yl.Initial:{const i=e.getGeneralRules().baseUnit;if(e.getVisibleUnits(this.name,"self",e=>e.constructionYard).length){this.botState=Yl.Deployed;break}var t=e.getVisibleUnits(this.name,"self",e=>i.includes(e.name));t.length&&this.actionsApi.orderUnits([t[0]],Un.DeploySelected);break}case Yl.Deployed:break;case Yl.Attacking:e.getVisibleUnits(this.name,"self",e=>e.isSelectableCombatant).length||(this.botState=Yl.Defeated,this.actionsApi.quitGame())}}}class hc{constructor(e,t,i,r){this.target=e,this.owner=t,this.atTile=i,this.atTile2=r,this.type=vr.SuperWeaponActivate}}class lc{constructor(e){this.target=e,this.type=vr.SuperWeaponReady}}(s=Kl=Kl||{})[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Finished=2]="Finished";class cc{constructor(e,t){this.owner=e,this.tile=t,this.status=Kl.NotStarted}onStart(e){}onTick(e){return!0}}class uc extends cc{constructor(e,t,i){super(e,t),this.weaponType=i}onStart(t){var i=this.owner.getOwnedObjectsByType(At.Building).find(e=>e.rules.nukeSilo);if(i){var r=t.rules.getWeapon(this.weaponType);let e=Io.factory(r.name,si.Primary,i,t.rules);e.fire(t.createTarget(void 0,this.tile),t)}}onTick(e){return!0}}var dc=__webpack_require__(949);class pc extends Rr{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,r=mr.worldToLeptons(mr.tileHeightToWorld(i)),s=mr.worldToLeptons(mr.tileHeightToScreen(e.tileElevation));return r<Math.max(r,s-t)?(e.position.moveByLeptons3(new dc.Vector3(0,-t,0)),!1):(e.position.tileElevation=i,e.stance=kr.None,this.game.map.terrain.getPassableSpeed(e.tile,e.rules.speedType,e.onBridge)||(e.infDeathType=Jt.None,this.game.destroyObject(e,void 0,!0)),!0)}}var gc,mc,fc,yc,wc,Tc=__webpack_require__(949);(s=gc=gc||{})[s.Spawning=0]="Spawning",s[s.EnRoute=1]="EnRoute",s[s.Dropping=2]="Dropping",s[s.TurningAround=3]="TurningAround";const bc=5*is.BASE_TICKS_PER_SECOND;class vc extends cc{constructor(e,t,i,r){super(e,t),this.paradropSquad=i,this.state=gc.Spawning,this.spawnDelay=r*bc}onStart(e){this.passengerRules=e.rules.getObject(this.paradropSquad.inf,At.Infantry),this.passengerCount=this.paradropSquad.num}computeFlightPath(e,t,i){let r=e.clone().sub(t);e=i.rules.general.paradrop.paradropRadius/mr.LEPTONS_PER_TILE,e=t.clone().add(r.clone().setLength(r.length()+2*e)).floor();let s=qa(t.x,t.y,e.x,e.y).map(e=>i.map.tiles.getByMapCoords(e.x,e.y)).filter(Pa);for(;s.length;){var a=s[0],a=mr.tileToWorld(a.rx+.5,a.ry+.5);if(i.map.isWithinHardBounds(new Tc.Vector2(a.x,a.y)))break;s.shift()}if(!s.length)throw new Error("No valid paradrop path found");return{fromTile:s[0],toTile:s[s.length-1]}}onTick(s){if(this.state===gc.Spawning){if(0<this.spawnDelay)return this.spawnDelay--,!1;var a=s.map.tiles.getMapSize(),n=[new Tc.Vector2(0,0),new Tc.Vector2(Math.floor(a.width/2),0),new Tc.Vector2(0,Math.floor(a.height/2))][s.generateRandomInt(0,2)];let t=this.passengerRules.speedType,e=new xr(s.map.tiles,s.map.mapBounds,this.tile,{width:1,height:1},0,50,e=>0<s.map.terrain.getPassableSpeed(e,t,!!e.onBridgeLandType));var o=this.targetTile=e.getNextTile();if(!o)return!0;let i=new Tc.Vector2(o.rx,o.ry);var{fromTile:h,toTile:a}=this.computeFlightPath(i,n,s),o=s.rules.general.paradrop.paradropPlane,n=s.rules.getObject(o,At.Aircraft);let r=this.pdPlane=s.createUnitForPlayer(n,this.owner);s.spawnObject(r,h),r.direction=Zr.fromMapCoords(i.clone().sub(new Tc.Vector2(h.rx,h.ry))),r.position.tileElevation=mr.worldToTileHeight(mr.leptonsToWorld(r.rules.flightLevel??s.rules.general.flightLevel)),r.zone=_r.Air,r.onBridge=!1,r.unitOrderTrait.addTask(new ca(s,a,!1)),r.traits.get(oo).setEnabled(!1),this.state=gc.EnRoute}if(!this.pdPlane||this.pdPlane.isDestroyed||this.pdPlane.isCrashing)return!0;o=this.targetTile;if(!this.pdPlane.unitOrderTrait.hasTasks())return this.state=gc.TurningAround,this.pdPlane.unitOrderTrait.addTask(new ca(s,o,!1)),!1;n=s.rules.general.paradrop.paradropRadius/mr.LEPTONS_PER_TILE;let e=new Ws(s.map.tileOccupation);h=e.isInTileRange(this.pdPlane.tile,o,0,n);if(this.state===gc.EnRoute&&h&&(this.state=gc.Dropping),this.state===gc.Dropping)if(h&&0<this.passengerCount){a=this.pdPlane.tile;let t=!!a.onBridgeLandType;if(!s.map.terrain.getPassableSpeed(a,this.passengerRules.speedType,t))return!1;let e=s.map.getGroundObjectsOnTile(a);if(e.some(e=>e.isVehicle()&&e.onBridge===t||e.isBuilding()&&!e.isDestroyed||e.isInfantry()&&e.stance===kr.Paradrop))return!1;n=this.findFreeSubCell(s,a);if(!n)return!1;this.passengerCount--;let i=s.createUnitForPlayer(this.passengerRules,this.owner);i.stance=kr.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(bs.Veteran),s.spawnObject(i,a),i.unitOrderTrait.addTask(new pc(s).setCancellable(!1))}else{if(!(0<this.passengerCount))return this.pdPlane.unitOrderTrait.getCurrentTask().forceCancel(this.pdPlane),this.pdPlane.traits.get(oo).setEnabled(!0),!0;this.state=gc.TurningAround,this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!!o.onBridgeLandType)}return this.state===gc.TurningAround&&h&&(o=this.computeFlightPath(new Tc.Vector2(o.rx,o.ry),new Tc.Vector2(this.pdPlane.tile.rx,this.pdPlane.tile.ry),s)["toTile"],this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!1),this.state=gc.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=Rs.SUB_CELLS.filter(e=>-1===i.indexOf(e));if(e.length)return 1<e.length?e[t.generateRandomInt(0,e.length-1)]:e[0]}}class Sc{constructor(e,t){this.art=e,this.init(t)}init(e){this.shadow=this.art.getBool("Shadow"),this.reverse=this.art.getBool("Reverse"),this.frameCount="number"==typeof e?e:this.shadow?e.numImages/2:e.numImages,this.end=this.art.getNumber("End",this.frameCount-1);e=this.art.getNumberArray("RandomRate").sort();2===e.length?this.rate=U(e[0],e[1])/60:this.rate=this.art.getNumber("Rate",60*Sc.defaultRate)/60,this.start=this.art.getNumber("Start",0),this.loopStart=this.art.getNumber("LoopStart",0),this.loopEnd=Math.max(this.loopStart,this.art.getNumber("LoopEnd",this.end+1)-1),this.loopCount=this.art.getNumber("LoopCount",1);e=this.art.getNumberArray("RandomLoopDelay").sort();this.randomLoopDelay=2===e.length?[e[0],e[1]]:void 0}getArt(){return this.art}setArt(e){this.art=e,this.init(this.frameCount)}}Sc.defaultRate=is.BASE_TICKS_PER_SECOND;class _c{constructor(e){this.position=e,this.type=vr.LightningStormCloud}}class kc{constructor(e){this.target=e,this.type=vr.LightningStormManifest}}(s=mc=mc||{})[s.Approaching=0]="Approaching",s[s.Manifesting=1]="Manifesting";class Oc extends cc{constructor(){super(...arguments),this.state=mc.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===mc.Approaching&&(0<this.manifestStartTimer?this.manifestStartTimer--:(this.state=mc.Manifesting,t.events.dispatch(new kc(this.tile)))),this.state===mc.Manifesting){var i,s=t.rules.general.lightningStorm;if(0<this.manifestEndTimer&&(this.manifestEndTimer--,0<this.nextDirectHitTimer&&this.nextDirectHitTimer--,this.nextDirectHitTimer<=0&&(this.nextDirectHitTimer=s.hitDelay,this.spawnCloudAt(this.tile,t)),0<this.nextRandomHitTimer&&this.nextRandomHitTimer--,this.nextRandomHitTimer<=0)){this.nextRandomHitTimer=s.scatterDelay;var a=Math.floor(s.cellSpread/2);let i=s.separation,r=new Ws(t.map.tileOccupation),e=new sa(t.map.tiles,t.map.mapBounds,this.tile,a,t,t=>!this.clouds.some(e=>r.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 r=s.warhead;let e=new So(t.rules.getWarhead(r));var n=i.tile,o=t.map.tileOccupation.getBridgeOnTile(n),h=o?.tileElevation??0,r=t.map.getTileZone(n);e.detonate(t,s.damage,n,h,mr.tile3dToWorld(n.rx+.5,n.ry+.5,n.z+h),r,o?zn.OnBridge:zn.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),i=t.art.getAnimation(t.rules.audioVisual.weatherConClouds[i]),i=new Sc(i.art,60),i=Math.floor(is.BASE_TICKS_PER_SECOND/i.rate*60);this.clouds.push({tile:e,durationTicks:i,ticksLeft:i});i=(t.map.tileOccupation.getBridgeOnTile(e)?.tileElevation??0)+mr.worldToTileHeight(mr.leptonsToWorld(t.rules.general.flightLevel)),i=mr.tile3dToWorld(e.rx+.5,e.ry+.5,e.z+i);t.events.dispatch(new _c(i))}}class Ic{constructor(){this.effects=[]}[Rh.onTick](e){for(var t of e.getCombatants()){var i;for(i of t.superWeaponsTrait.getAll())i.update(e)}for(var r of this.effects)r.status===Kl.NotStarted&&(r.onStart(e),r.status=Kl.Running),r.onTick(e)&&(r.status=Kl.Finished);this.effects=this.effects.filter(e=>e.status!==Kl.Finished)}[aa.onPowerLow](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!1)})}[aa.onPowerRestore](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!0)})}[aa.onPowerChange](e,t){}[Mo.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)}}class Cc extends cc{onStart(e){var t,i,r=e.rules.combatDamage.ironCurtainDuration,s={player:this.owner};let a=new xr(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,s):(i.invulnerableTrait.setActiveFor(r,e.currentTick),(i.isVehicle()||i.isAircraft())&&i.parasiteableTrait?.isInfested()&&i.parasiteableTrait.destroyParasite(s,e)))}onTick(e){return!0}}class Ac extends cc{constructor(e,t,i){super(e,t),this.tile2=i,this.objectsToTeleport=[]}onStart(i){this.delayTicks=i.rules.general.chronoDelay;let r=i.map.tiles;for(let t=-1;t<=1;t++)for(let e=-1;e<=1;e++){var s=r.getByMapCoords(this.tile.rx+t,this.tile.ry+e);if(s){var a,n=!!s.onBridgeLandType,o=r.getByMapCoords(this.tile2.rx+t,this.tile2.ry+e);for(a of i.map.getGroundObjectsOnTile(s))!a.isUnit()||a.tile!==s||a.onBridge!==n||a.isInfantry()&&a.stance===kr.Paradrop||a.isDisposed||(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,r=h?l.map.tileOccupation.getBridgeOnTile(h):void 0,s=l.map.getGroundObjectsOnTile(h),a=s.find(e=>e.isBuilding());var c=s.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.owner===o.owner;let e=!1,n=o.rules.speedType;o.rules.movementZone===ii.Fly&&(n=Kt.Wheel);var u=l.map.mapBounds.isWithinBounds(h);if(!(t||l.map.terrain.getPassableSpeed(h,n,!!r)&&u)){let t=!1;if(!c&&(0<l.map.terrain.getPassableSpeed(h,n,!!r,void 0,!0)||!u)){a&&(i=!0);let e=new xr(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,r=l.map.tileOccupation.getBridgeOnTile(h),s=l.map.getGroundObjectsOnTile(h),t=!0)}t||(o.moveTrait.teleportUnitToTile(h,r,!0,!1,l),o.warpedOutTrait.setActive(!1,!0,l),l.map.getTileZone(h)===_r.Water&&(o.deathType=Ir.Sink),l.destroyObject(o,{player:this.owner}),e=!0)}if(!e||c)for(let t of s)t.isDisposed||t.isUnit()&&(this.objectsToTeleport.some(({obj:e})=>e===t)||t.onBridge!==!!r&&t.tile===h||2<Math.abs(t.tileElevation-o.tileElevation)||(t.isInfantry()&&t.stance!==kr.Paradrop&&(t.deathType=Ir.Crush),l.destroyObject(t,{player:this.owner,obj:o})));e||(o.moveTrait.teleportUnitToTile(h,r,!0,!1,l),t&&a?.dockTrait&&(t=a.dockTrait.getAllDockTiles().indexOf(h),a.dockTrait.undockUnitAt(t),a.dockTrait.dockUnitAt(o,t)),i?o.warpedOutTrait.setTimed(l.rules.general.chronoDelay,!1,l):o.warpedOutTrait.setActive(!1,!0,l))}return!0}}(fc=fc||{}).onActivate=Symbol(),(s=yc=yc||{})[s.Charging=0]="Charging",s[s.Paused=1]="Paused",s[s.Ready=2]="Ready";class Bc{constructor(e,t,i){this.name=e,this.rules=t,this.owner=i,this.status=yc.Charging,this.rechargeTicks=60*t.rechargeTime*is.BASE_TICKS_PER_SECOND,this.chargeTicks=this.rechargeTicks}update(e){0<this.chargeTicks&&this.status!==yc.Paused&&(this.chargeTicks--,0===this.chargeTicks&&(this.status=yc.Ready,e.events.dispatch(new lc(this))))}activate(i,r,s){if(this.status===yc.Ready){this.status=yc.Charging,this.resetTimer();let t=[];switch(this.rules.type){case qi.AmerParaDrop:for(var[e,a]of i.rules.general.paradrop.amerParaDrop.entries())t.push(new vc(this.owner,r,a,e));break;case qi.ParaDrop:{let e=i.rules.general.paradrop.getParadropSquads(this.owner.country.side);for(var[n,o]of e.entries())t.push(new vc(this.owner,r,o,n));break}case qi.MultiMissile:if(!this.rules.weaponType)throw new Error("Missing WeaponType in super weapon rules");t.push(new uc(this.owner,r,this.rules.weaponType));break;case qi.LightningStorm:t.push(new Oc(this.owner,r));break;case qi.IronCurtain:t.push(new Cc(this.owner,r));break;case qi.ChronoSphere:if(!s)throw new Error("Missing tile2 action param");t.push(new Ac(this.owner,r,s))}for(var h of t)i.traits.get(Ic).addEffect(h);i.traits.filter(fc).forEach(e=>{e[fc.onActivate](this,i,r,s)}),i.events.dispatch(new hc(this,this.owner,r,s))}}pauseTimer(){this.status=yc.Paused}resumeTimer(){this.status=0<this.chargeTicks?yc.Charging:yc.Ready}resetTimer(){this.chargeTicks=this.rechargeTicks,this.status===yc.Ready&&(this.status=yc.Charging)}getTimerSeconds(){return this.chargeTicks/is.BASE_TICKS_PER_SECOND}getChargeProgress(){return(this.rechargeTicks-this.chargeTicks)/this.rechargeTicks}}(s=wc=wc||{})[s.Requested=0]="Requested",s[s.Formed=1]="Formed",s[s.Broken=2]="Broken";class Ec{constructor(e,t,i){this.alliance=e,this.changeType=t,this.from=i,this.type=vr.AllianceChange}}var Pc,s=__webpack_require__(948),xc=__webpack_require__.n(s);class Nc{constructor(e){this.prng=new(xc())(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}}(s=Pc=Pc||{})[s.NotStarted=0]="NotStarted",s[s.Started=1]="Started",s[s.Ended=2]="Ended";class Rc{constructor(e,t,i,r,s,a,n,o,h,l,c,u,d,p){this.updatableObjects=new Set,this.constructionWorkers=new Map,this.currentTick=0,this.currentTime=0,this._onEnd=new va,this.afterTickCallbacks=[],this.events=new cl,this.traits=new Is,this.world=e,this.map=t,this.rules=i,this.art=r,this.id=s,this.startTimestamp=a,this.prng=new Nc(Number(s+""+a)),this.gameOpts=n,this.gameModeType=o,this.playerList=h,this.unitSelection=l,this.alliances=c,this.desiredSpeed=new Hh(is.computeGameSpeed(n.gameSpeed)),this.speed=new Hh(this.desiredSpeed.value),this.nextObjectId=u,this.objectFactory=d,this.botManager=class{constructor(e,t,i,r,s){this.game=e,this.actionFactory=t,this.actionQueue=i,this.gameApi=r,this.eventsApi=s,this.bots=new Map}static factory(e,t){return new this(e,t,new fl,new Ql(e,!0),new Pl(e.events))}init(){var e,t;for(e of this.game.getCombatants().filter(e=>e.isAi))this.bots.set(e,new oc(e.name,e.country.name));this.eventsApi.subscribe(t=>this.bots.forEach(e=>e.onGameEvent(t,this.gameApi)));for(t of this.bots.values())t.setGameApi(this.gameApi),t.setActionsApi(new vl(this.game,this.actionFactory,this.actionQueue,t.name)),t.setProductionApi(new ac(this.game.getPlayerByName(t.name).production)),t.onGameStart(this.gameApi)}update(){var e,t;for(e of this.actionQueue.dequeueAll())e.process();for(t of this.game.getCombatants().filter(e=>e.isAi))this.bots.get(t).onGameTick(this.gameApi)}dispose(){this.eventsApi.dispose()}}.factory(this,p)}get onEnd(){return this._onEnd.asEvent()}addPlayer(e){this.playerList.addPlayer(e),e.isCombatant()&&this.constructionWorkers.set(e,this.createConstructionWorker(e,e.production))}getPlayer(e){return this.playerList.getPlayerAt(e)}getPlayerByName(e){return this.playerList.getPlayerByName(e)}getAiPlayerName(e){return`@@AI${this.gameOpts.aiPlayers.indexOf(e)+1}@@`}getPlayerNumber(e){return this.playerList.getPlayerNumber(e)}getCombatants(){return this.playerList.getCombatants()}getNeutralPlayer(){return this.playerList.getNeutral()}getPlayable(){return this.playerList.getPlayable()}areFriendly(e,t){return e.owner===t.owner||this.alliances.areAllied(e.owner,t.owner)}getWorld(){return this.world}createConstructionWorker(e,t){return new hl(e,t,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.computeTerrainPassability(),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=Pc.Started,this.currentTick=0,this.currentTime=0,this.botManager.init()}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=>Ah(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 r=this.getPlayerByName(i[t]),s=this.getPlayerByName(i[e]),s=this.alliances.setAlliance(r,s,Bh.Formed);this.onAllianceChange(s,r,!0)}}}createMapObjects(){var e=this.rules.general.harvesterUnit.every(e=>!V(this.rules.getObject(e,At.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 r,s,a=i.name;this.validateMapObjectRulesAndArt(a,At.Terrain)&&((r=this.map.tiles.getByMapCoords(i.rx,i.ry))?(s=this.rules.getObject(a,At.Terrain),t&&s.spawnsTiberium||(a=this.createObject(At.Terrain,a),this.spawnObject(a,r))):console.warn(`Invalid map object location (${i.rx},${i.ry})`,i))}}createInitialMapOverlays(e,s){let a=new Map,n=new Map;for(var o of e){var h=this.rules.getOverlayName(o.id);if(this.validateMapObjectRulesAndArt(h,At.Overlay)){let t=this.createObject(At.Overlay,h),e=o.id;!t.rules.tiberium||void 0!==(l=Vo.calculateOverlayId(o))&&l!==o.id&&(t=this.createObject(At.Overlay,this.rules.getOverlayName(l)),e=l),t.overlayId=e,t.value=o.value;let i=o.rx,r=o.ry;t.isBridge()&&t.isHighBridge()&&(t.position.tileElevation=4,i+=t.isXBridge()?0:-1,r+=t.isXBridge()?-1:0);var l=this.map.tiles.getByMapCoords(i,r);if(l){try{this.map.tileOccupation.calculateTilesForGameObject(l,t)}catch(e){if(e instanceof RangeError){console.warn(`Can't place overlay "${h}" at (${l.rx}, ${l.ry}) `+"because it's partially outside the map boundaries. Skipping."),t.dispose();continue}throw e}if(za.isLowBridge(o.id))za.isBridgePlaceholder(o.id)||(a.set(l,o.value),1===o.value?n.set(l,t):t.dispose());else{if(t.isTiberium()){if(![An.Ore,An.Gems,An.Vinifera].includes(Nn.getOverlayTibType(t.overlayId))){console.warn(`Found unsupported TS tiberium overlay ${t.overlayId} @${l.rx},${l.ry}. Skipping.`);continue}if(this.map.getObjectsOnTile(l).find(e=>e.isTerrain())){t.dispose();continue}}s&&t.isTiberium()?t.dispose():this.spawnObject(t,l)}}else console.warn(`Invalid map object location (${i},${r})`,o),t.dispose()}}for(var[t,i]of n){var r=i.isXBridge(),c=this.map.tiles.getByMapCoords(t.rx+(r?0:-1),t.ry+(r?-1:0)),r=this.map.tiles.getByMapCoords(t.rx+(r?0:1),t.ry+(r?1:0));c&&r&&(0===a.get(c)||2===a.get(r))?(i.value=0,this.spawnObject(i,c)):(i.dispose(),console.warn(`Invalid bridge segment @${t.rx},${t.ry}. Skipping.`))}var u,d=[...n.keys()].filter(e=>this.map.bridges.getPieceAtTile(e)?.headType!==yh.None),e=this.map.bridges.findMapHighBridgeHeadTiles(),e=this.map.bridges.findMapNonBuildableTiles([...d,...e]),p=za.bridgePlaceholderIds[0],g=this.rules.getOverlayName(p);for(u of e){let e=this.createObject(At.Overlay,g);e.overlayId=p,this.spawnObject(e,u)}}createInitialMapSmudges(e){for(var t of e){var i=t.name,r=this.map.tiles.getByMapCoords(t.rx,t.ry);r?(i=this.createObject(At.Smudge,i),this.spawnObject(i,r)):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]));for(var i of e){var r=i.name;if(this.validateMapObjectRulesAndArt(r,i.type)){var s=this.map.tiles.getByMapCoords(i.rx,i.ry);if(s){var a=t.get(i.owner);if(a){let t=this.createObject(i.type,r);try{this.map.tileOccupation.calculateTilesForGameObject(s,t)}catch(e){if(e instanceof RangeError){console.warn(`Can't place building "${r}" at (${s.rx}, ${s.ry}) `+"because it's partially outside the map boundaries. Skipping."),t.dispose();continue}throw e}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===s.onBridgeLandType?console.warn(`Cannot place unit "${i.name}" on a bridge because `+`no bridge was found at ${s.rx}, ${s.ry}`):e=!0),t.onBridge=e,t.zone=Mr(e?s.onBridgeLandType:s.landType),e&&(t.position.tileElevation+=this.map.tileOccupation.getBridgeOnTile(s)?.tileElevation??0)}this.changeObjectOwner(t,a),this.spawnObject(t,s),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,At.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,At.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===vt.Unholy&&e.push(...this.rules.general.baseUnit.filter(e=>e!==t).map(e=>({name:e,type:At.Vehicle,count:1})));var u,d,p;let r=[],s=!1,a=new Ba(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,Kt.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(s||(t=a.getNextTile(),t?r.push(t):s=!0),s){var g=r[o];let e=n.get(g);e||(e=new Ba(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,Kt.Foot,!1)),n.set(g,e)),o=(o+1)%r.length,t=e.getNextTile()}if(t){var m,f=this.rules.getObject(u,d);if(d===At.Vehicle){g=this.createUnitForPlayer(f,h);this.applyInitialVeteran(g,h),this.spawnObject(g,t),i--}else{if(d!==At.Infantry)throw new Error("Should not reach this line");for(m of Rs.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(bs.Elite):t.country.hasVeteranUnit(e.type,e.name)&&e.veteranTrait.setVeteranLevel(bs.Veteran))}createObject(e,t){return this.objectFactory.create(e,t,this.rules,this.art)}createUnitForPlayer(e,t){if(![At.Aircraft,At.Vehicle,At.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,r,s){let a=this.createObject(At.Projectile,e);return a.fromWeapon=i,a.fromObject=t,a.fromPlayer=t.owner,a.target=r,a.isShrapnel=s,a}createSuperWeapon(e,t){var i=this.rules.getSuperWeapon(e);return new Bc(e,i,t)}createTarget(e,t){return new Ja(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}computeTerrainPassability(){Object.keys(Kt).forEach(e=>{e=Number(e);isNaN(e)||e===Kt.Winged||this.map.terrain.computePassabilityGraph(e)})}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 r=e.limboData;if(!r)throw new Error(`Object ${e.name}#${e.id} has no limboData attached`);e.limboData=void 0,this.doSpawnObject(e,t);let s=this.getUnitSelection();r.selected&&!i&&s.addToSelection(e),void 0!==r.controlGroup&&s.addUnitsToGroup(r.controlGroup,[e],!1)}doSpawnObject(t,e){var i;t.position.tile=e,t.isBuilding()&&(i=t.art.foundationCenter,t.centerTile=this.map.tiles.getByMapCoords(e.rx+i.x,e.ry+i.y)),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(Ph).forEach(e=>{e[Ph.onSpawn](t,this)}),this.events.dispatch(new ml(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(xh).forEach(e=>{e[xh.onUnspawn](t,this)}),this.events.dispatch(new gl(t))}destroyObject(t,i,e=!1){if(t.isDestroyed)throw new Error(`Object with ID "${t.id}" is already destroyed`);if(i&&t.isTechno()&&(!t.isBuilding()||t.owner.isCombatant())&&(i.player.kills++,i.player===t.owner||this.alliances.areAllied(i.player,t.owner)||(i.player.score+=t.rules.points)),t.isTechno()&&t.owner.playable&&t.owner.unitsLost++,t.isDestroyed=!0,t.healthTrait&&(t.healthTrait.health=0),t.onDestroy(this,i,e),this.traits.filter(Dh).forEach(e=>{e[Dh.onDestroy](t,this,i)}),i?.obj?.traits.filter(Ro).forEach(e=>{e[Ro.onDestroy](i.obj,t,i.weapon,this)}),this.events.dispatch(new ul(t,i)),t.isBuilding()&&t.rules.leaveRubble&&t.deathType!==Ir.Temporal){t.owner.removeOwnedObject(t),this.unitSelection.cleanupUnit(t);e=this.map.tileOccupation.calculateTilesForGameObject(t.tile,t);this.map.terrain.invalidateTiles(e),t.art.canHideThings&&this.map.tileOcclusion.removeOccluder(t),this.updatableObjects.delete(t),t.onUnspawn(this),this.traits.filter(xh).forEach(e=>{e[xh.onUnspawn](t,this)}),this.events.dispatch(new gl(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(Nh).forEach(e=>{e[Nh.onChange](t,i,this)}),t.onOwnerChange(i,this),this.events.dispatch(new pl(t,i)))}onAllianceChange(t,e,i){this.events.dispatch(new Ec(t,i?wc.Formed:wc.Broken,e)),this.traits.filter(Mh).forEach(e=>{e[Mh.onChange](t,i,this)})}update(){if(this.status!==Pc.NotStarted){this.botManager.update(),this.currentTick++,this.currentTime+=1e3/is.BASE_TICKS_PER_SECOND,this.status!==Pc.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(Rh).forEach(e=>{e[Rh.onTick](this)}),this.localPlayer&&!this.localPlayer.isObserver&&!this.localPlayer.defeated){var t=this.unitSelection.getSelectedUnits();if(1===t.length){let e=t[0];if(e.isTechno()&&e.owner!==this.localPlayer){let t=this.mapShroudTrait.getPlayerShroud(this.localPlayer);this.map.tileOccupation.calculateTilesForGameObject(e.tile,e).find(e=>!t.isShrouded(e))||(this.unitSelection.deselectAll(),this.unitSelection.cleanupUnit(e))}}}for(var i of this.afterTickCallbacks)i();this.afterTickCallbacks.length=0}}afterTick(e){this.afterTickCallbacks.push(e)}checkGameEndConditions(){this.updateDefeatedPlayers(this.playerList.getCombatants()),(!this.localPlayer?.defeated||this.localPlayer.isObserver)&&this.alliances.getHostilePlayers().length||(this.status=Pc.Ended,this._onEnd.dispatch(this,void 0))}updateDefeatedPlayers(e){let r=this.stalemateDetectTrait?.isStale()&&0===this.stalemateDetectTrait.getCountdownTicks(),s=this.gameOpts.shortGame;e.forEach(t=>{let i;if(r)i=!0;else{let e;e=s?(e=[...t.getOwnedObjectsByType(At.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}i&&(t.defeated=!0,this.removeAllPlayerAssets(t),this.events.dispatch(new dl(t)))})}removeAllPlayerAssets(e){e.getOwnedObjects().forEach(e=>{e.isDestroyed||this.destroyObject(e,void 0,!0)}),e.getOwnedObjects(!0).forEach(e=>{e.isDestroyed||(e.limboData?.inTransport?this.changeObjectOwner(e,this.getNeutralPlayer()):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.botManager.dispose(),this.botManager=void 0,this.map.dispose(),this.traits.dispose()}}var Mc,Dc,Lc,Fc,jc,Uc,Wc=__webpack_require__(949);class Vc{constructor(e){this.map=e,this.radSites=new Map,this.radLevelByTile=new Map,this._onChange=new va}get onChange(){return this._onChange.asEvent()}getRadLevel(e){return this.radLevelByTile.get(e)}[Rh.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 So(a.rules.getWarhead(n.radSiteWarhead));this.radLevelByTile.forEach((e,t)=>{var i,r,s=Math.min(n.radLevelMax,e)*n.radLevelFactor;for(i of a.map.getGroundObjectsOnTile(t).filter(e=>e.isUnit()&&!(e.isInfantry()&&e.stance===kr.Paradrop&&1<e.tileElevation)))o.canDamage(i,t,i.zone)&&(0<(r=o.computeDamage(s,i))&&o.inflictDamage(r,i,void 0,a))})}applyDecay(r){var e=new Set(this.radLevelByTile.keys());this.radLevelByTile.clear(),this.radSites.forEach(({radLevel:e,radius:t},i)=>{e-=r;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 r=new Ws(this.map.tileOccupation),s=new xr(this.map.tiles,this.map.mapBounds,e,{width:1,height:1},0,t,e=>!!e,!1);var a;let n=new Set;for(;a=s.getNextTile();){var o=r.tileDistance(e,a);o<=t&&(o=Math.ceil(Wc.Math.lerp(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 zc{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 Hc{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 Gc{constructor(){this.unitSelectionByPlayer=new Map}getOrCreateSelection(e){let t=this.unitSelectionByPlayer.get(e);return t||(t=new Hc(e),this.unitSelectionByPlayer.set(e,t)),t}}class $c extends yl{constructor(){super(Lh.NoAction)}process(){}}class qc{create(){return new $c}}class Zc{constructor(e){this.target=e,this.type=vr.BuildingPlace}}class Qc{constructor(e,t,i){this.name=e,this.player=t,this.tile=i,this.type=vr.BuildingFailedPlace}}(Mc=Mc||{}).onPlace=Symbol();class Xc extends yl{constructor(e){super(Lh.PlaceBuilding),this.game=e}unserialize(e){this.name=e[0],this.tile={x:Number(e[1]),y:Number(e[2])}}serialize(){return[this.name,""+this.tile.x,""+this.tile.y]}print(){return`Place building ${this.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.game.getPlayerByName(this.playerName);const i=this.tryPlaceBuilding(t,e);i?(this.game.traits.filter(Mc).forEach(e=>{e[Mc.onPlace](i,this.game)}),this.game.events.dispatch(new Zc(i))):this.game.events.dispatch(new Qc(this.name,t,e))}else console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}tryPlaceBuilding(r,s){var a=this.game.rules.getBuilding(this.name);if(r.production){let i=r.production.getQueueForObject(a);if(i.status===ha.Ready&&i.getFirst().rules===a){let t=this.game.getConstructionWorker(r);if(t.canBuild(this.name)){let e=t.canBuildAt(this.name,s,void 0,!0);if(!e.filter(e=>!e.buildable).length){s=t.placeAt(this.name,s,!0);r.unitsBuilt++,i.shift(a,1);let e=r.production.getPrimaryFactory(Gi.BuildingType);return e&&(e.factoryTrait.status=Da.Delivering),s[0]}}}}}}class Yc{constructor(e){this.game=e}create(){return new Xc(this.game)}}class Kc extends yl{constructor(e){super(Lh.SellBuilding),this.game=e}unserialize(e){this.buildingId=Number(e[0])}serialize(){return[""+this.buildingId]}print(){return`Sell building ${this.buildingId}`}process(){var t=this.game.getPlayerByName(this.playerName);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 Jc{constructor(e){this.game=e}create(){return new Kc(this.game)}}class eu extends yl{constructor(e,t){super(Lh.SelectUnits),this.game=e,this.orderActionContext=t}unserialize(e){this.unitIds=e.map(Number)}serialize(){return this.unitIds.map(String)}print(){return`Select unit(s) [${this.unitIds.join(",")}]`}process(){let e=this.game.getPlayerByName(this.playerName),t=[];for(var i of this.unitIds){i=e.getOwnedObjectById(i);i&&t.push(i)}this.orderActionContext.getOrCreateSelection(e).update(t)}}class tu{constructor(e,t){this.game=e,this.orderActionContext=t}create(){return new eu(this.game,this.orderActionContext)}}const iu=[Un.Occupy,Un.Dock,Un.Attack,Un.Capture,Un.Repair,Un.EnterTransport,Un.PlaceBomb,Un.Deploy,Un.Gather];(s=Dc=Dc||{})[s.Default=0]="Default",s[s.Mini=1]="Mini",s[s.Scroll=2]="Scroll",s[s.NoScroll=10]="NoScroll",s[s.Select=18]="Select",s[s.Move=31]="Move",s[s.NoMove=41]="NoMove",s[s.MoveMini=42]="MoveMini",s[s.NoActionMini=52]="NoActionMini",s[s.AttackRange=53]="AttackRange",s[s.AttackNoRange=58]="AttackNoRange",s[s.AttackMini=63]="AttackMini",s[s.Guard=68]="Guard",s[s.GuardMini=73]="GuardMini",s[s.Unknown1=78]="Unknown1",s[s.Unknown2=88]="Unknown2",s[s.Occupy=89]="Occupy",s[s.NoOccupy=99]="NoOccupy",s[s.OccupyMini=100]="OccupyMini",s[s.Deploy=110]="Deploy",s[s.NoDeploy=119]="NoDeploy",s[s.Unknown3=120]="Unknown3",s[s.Sell=129]="Sell",s[s.SellMini=139]="SellMini",s[s.NoSell=149]="NoSell",s[s.RepairMove=150]="RepairMove",s[s.SideRepair=170]="SideRepair",s[s.NoRepair=190]="NoRepair",s[s.Unknown4=191]="Unknown4",s[s.Unknown5=199]="Unknown5",s[s.Dynamite=204]="Dynamite",s[s.Unknown6=209]="Unknown6",s[s.Unknown7=214]="Unknown7",s[s.Unknown8=219]="Unknown8",s[s.Unknown9=224]="Unknown9",s[s.Unknown10=229]="Unknown10",s[s.Unknown11=234]="Unknown11",s[s.Unknwon12=239]="Unknwon12",s[s.Unknown13=249]="Unknown13",s[s.Para=259]="Para",s[s.Unknown14=269]="Unknown14",s[s.Storm=279]="Storm",s[s.Unknown15=299]="Unknown15",s[s.C4=309]="C4",s[s.Nuke=319]="Nuke",s[s.Unknown16=329]="Unknown16",s[s.Power=339]="Power",s[s.Unknown17=345]="Unknown17",s[s.Iron=346]="Iron",s[s.Unknown18=351]="Unknown18",s[s.Unknown19=356]="Unknown19",s[s.Chrono=357]="Chrono",s[s.DefuseBomb=369]="DefuseBomb",s[s.NoAction=384]="NoAction",s[s.Pan=385]="Pan",s[s.Unknown21=394]="Unknown21",s[s.AttackMove=404]="AttackMove",s[s.Unknown23=413]="Unknown23",s[s.Unknown24=422]="Unknown24",s[s.Unknown25=431]="Unknown25",s[s.Unknown26=432]="Unknown26",s[s.Unknown27=433]="Unknown27",s[s.Unknown28=434]="Unknown28",s[s.Beacon=435]="Beacon",(s=Lc=Lc||{})[s.None=0]="None",s[s.Move=1]="Move",s[s.Attack=2]="Attack",s[s.Enter=3]="Enter",s[s.Capture=4]="Capture",s[s.SpecialAttack=5]="SpecialAttack";class ru{constructor(e){this.orderType=e,this.targetOptional=!0,this.minimapAllowed=!0,this.singleSelectionRequired=!1,this.terminal=!1,this.feedbackType=Lc.None}getPointerType(e,t){return e?Dc.Mini:Dc.Default}set(e,t){return this.sourceObject=e,this.target=t,this}isValid(){return!0}isAllowed(){return!0}onAdd(e,t){return!0}}class su{constructor(e,t){this.from=e,this.to=t,this.type=vr.ObjectMorph}}class au extends Rr{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!==At.Building&&this.children.push(new ol),e.isVehicle()&&this.morphInto.type===At.Building&&this.children.push(new Gs(180))}onTick(r){if(!this.morphInto)throw new Error("morphInto not set");let e=this.game.getUnitSelection();var t=e.isSelected(r),i=e.getOrCreateSelectionModel(r).getControlGroupNumber(),s=this.morphInto;let a;if(s.type===At.Building){if(r.isVehicle()&&r.parasiteableTrait?.isInfested())return!0;let t=r.tile,e=this.game.getConstructionWorker(r.owner),i=e.canBuildAt(this.morphInto.name,t);if(i.find(e=>!(e.buildable||e.rx===t.rx&&e.ry===t.ry)))return!0;this.game.unspawnObject(r),r.dispose(),[a]=e.placeAt(this.morphInto.name,t),a.healthTrait.health=r.healthTrait.health}else{let e=r.unitOrderTrait.getTasks().filter(e=>e instanceof ca);this.game.unspawnObject(r),r.dispose(),a=this.game.createUnitForPlayer(this.morphInto,r.owner),a.direction=180,a.healthTrait.health=r.healthTrait.health;s=r.art.foundationCenter;this.game.spawnObject(a,this.game.map.tiles.getByMapCoords(r.tile.rx+s.x,r.tile.ry+s.y)),e.forEach(e=>a.unitOrderTrait.addTask(e))}return a.purchaseValue=r.purchaseValue,r.replacedBy=a,t&&e.addToSelection(a),void 0!==i&&e.addUnitsToGroup(i,[a],!1),this.game.events.dispatch(new su(r,a)),!0}}class nu extends au{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,At.Vehicle),super.onStart(e)}}class ou{constructor(e){this.target=e,this.type=vr.RallyPointChange}}class hu extends ru{constructor(e,t,i,r=!1){super(r?Un.ForceMove:Un.Move),this.game=e,this.map=t,this.unitSelection=i,this.forceMove=r,this.targetOptional=!1,this.feedbackType=Lc.Move}getPointerType(e){let t=this.isAllowed();var i,r,s,a;return!t||this.sourceObject.isBuilding()||this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile)||(i=!!this.target.getBridge(),r=this.sourceObject.rules.speedType,s=this.sourceObject.rules.movementZone===ii.Fly,a=this.map.getObjectsOnTile(this.target.tile).some(e=>(e.isInfantry()||e.isVehicle())&&e.disguiseTrait?.hasTerrainDisguise()),t=s?this.sourceObject.rules.balloonHover||0<this.map.terrain.getPassableSpeed(this.target.tile,Kt.Amphibious,i)&&!a:0<this.map.terrain.getPassableSpeed(this.target.tile,r,i)&&!a&&!(this.target.obj?.isTechno()&&!this.game.areFriendly(this.target.obj,this.sourceObject))),e?t?Dc.MoveMini:Dc.NoActionMini:t?Dc.Move:Dc.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.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 nu(this.game),new ca(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:t})]:e.isUnit()?[new ca(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:t})]:void 0}}onAdd(t,e){if(this.sourceObject.isBuilding()&&this.sourceObject.rules.undeploysInto&&this.sourceObject.buildStatus===Cn.BuildUp)return this.sourceObject.unitOrderTrait.getTasks().find(e=>e instanceof Tn)?.setCancellable(!0),!0;if(this.sourceObject.isBuilding()&&this.sourceObject.rallyTrait?.getRallyPoint())return this.sourceObject.rallyTrait.changeRallyPoint(this.target.tile,this.sourceObject,this.game),this.game.events.dispatch(new ou(this.sourceObject)),!1;if(!e&&this.isValid()&&this.isAllowed()){this.sourceObject.attackTrait?.cancelOpportunityFire();let e=t.find(e=>e.constructor===ca&&!e.isCancelling());if(e)return e.updateTarget(this.target.tile,!!this.target.getBridge()),e.children.length&&e.children[0]instanceof an&&e.children[0].cancel(),t.splice(t.indexOf(e)+1),this.sourceObject.unitOrderTrait.clearOrders(),!1;if(this.sourceObject.isUnit()&&this.sourceObject.rules.movementZone===ii.Fly){let e=t.find(e=>e.constructor===an&&!e.isCancelling());e&&e.forceCancel(this.sourceObject)&&t.splice(t.indexOf(e))}}return!0}}class lu extends au{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,At.Building),super.onStart(e)}onTick(e){return!!this.isCancelling()||super.onTick(e)}}class cu{constructor(e,t){this.unit=e,this.deployType=t,this.type=vr.UnitDeployUndeploy}}class uu{constructor(e){this.target=e,this.type=vr.PrimaryFactoryChange}}(s=Fc=Fc||{})[s.None=0]="None",s[s.OnlyPassengers=1]="OnlyPassengers",s[s.All=2]="All";class du extends Rr{constructor(e,t){super(),this.game=e,this.soft=t,this.evacState=Fc.None,this.evacTries=0,this.turnPerformed=!1,this.preventLanding=!1}forceEvac(){this.evacState=Fc.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!==Fc.OnlyPassengers&&1!==t.units.length||!e.rules.gunner?Fc.OnlyPassengers:Fc.All)}onTick(e){if(this.isCancelling()||this.evacState===Fc.None)return!0;if(e.zone===_r.Air)return this.children.push(new ss(()=>e.zone!==_r.Air)),!1;let t=e.transportTrait.units;if(!t.length||e.rules.gunner&&1===t.length&&this.evacState!==Fc.All)return!0;var i=t[t.length-1],r=this.findValidEvacTarget(e,i);if(r&&!this.turnPerformed){this.turnPerformed=!0;var s=(r.dir+180)%360;if(e.direction!==s)return this.children.push(new Gs(s)),!1}return this.evacuateUnit(i,e,r)?(t.pop(),this.children.push(new rs(1/60)),!1):!(++this.evacTries<=3)||(this.children.push(new rs(.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:r,moveNode:i}=i;return e.position.tileElevation=r.onBridge?.tileElevation??0,e.onBridge=!!r.onBridge,e.zone=this.game.map.getTileZone(r.tile,!r.onBridge),this.game.unlimboObject(e,r.tile),e.unitOrderTrait.unmarkNextQueuedOrder(),i?e.unitOrderTrait.addTask(new ca(this.game,i.tile,!!i.onBridge)):e.unitOrderTrait.addTask(new da(this.game)),this.game.events.dispatch(new qn(t)),!0}findValidEvacTarget(a,n){let o=this.game.map,h=new Ds(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=Zr.toMapCoords(l);let i=a.tile,r=t,s;for(let t=1;t<=2;t++){if(2===t){if(!s)break;i=s.tile,r=s.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=r,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:s,moveNode:{tile:T,onBridge:f},dir:l};s={tile:T,onBridge:f},g={spawnNode:s,moveNode:void 0,dir:l}}}}if(g)return g}}class pu extends ru{constructor(e,t){super(t?Un.Deploy:Un.DeploySelected),this.game=e,this.targeted=t,this.minimapAllowed=!1,this.getPointerType=()=>this.isAllowed()?Dc.Deploy:Dc.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&&![kr.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 i=this.sourceObject;if(i.isVehicle()&&i.transportTrait)return!!(i.transportTrait.units.length&&0<this.game.map.terrain.getPassableSpeed(i.tile,Kt.Foot,i.onBridge));if((i.isInfantry()||i.isVehicle())&&i.deployerTrait)return!0;if(i.isVehicle()&&i.rules.deploysInto){if(i.parasiteableTrait?.isInfested())return!1;let e=this.game.getConstructionWorker(i.owner);if(i.moveTrait.currentWaypoint?.onBridge)return!1;var r=i.moveTrait.currentWaypoint?.tile??i.tile;let t=e.canBuildAt(i.rules.deploysInto,r,[i]);return!t.find(e=>!e.buildable)}if(i.isBuilding()&&i.rules.factory)return!0;if(i.isBuilding()&&i.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 du(this.game,!0)]:e.isBuilding()&&e.rules.factory?void 0:e.isVehicle()&&e.rules.deploysInto?[new lu(this.game)]:(e.isInfantry()||e.isVehicle())&&e.deployerTrait?[new ss(()=>{e.deployerTrait.toggleDeployed(),this.game.events.dispatch(new cu(e,e.deployerTrait.isDeployed()?"undeploy":"deploy"))})]:e.isBuilding()&&e.garrisonTrait?.units.length?[new ss(()=>{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 uu(i)),!1;if(i.isVehicle()&&i.transportTrait&&!e&&this.isValid()&&this.isAllowed()){let e=t.find(e=>e.constructor===du&&!e.isCancelling());if(e)return e.forceEvac(),!1}return!0}}class gu{constructor(e){this.player=e,this.type=vr.Cheer}}class mu{constructor(e){this.target=e,this.type=vr.DeployNotAllowed}}class fu extends yl{constructor(e,t,i,r){super(Lh.OrderUnits),this.game=e,this.map=t,this.orderActionContext=i,this.orderFactory=r,this.queue=!1,this.isInvalid=!1}unserialize(t){if(this.orderType=Number(t[0]),1!==t.length){let e;if(""!==t[1]){var i=Number(t[1]);if(!this.game.getWorld().hasObjectId(i))return void(this.isInvalid=!0);e=this.game.getObjectById(i)}else e=void 0;var[r,i]=t[2].split(","),i=this.map.tiles.getByMapCoords(Number(r),Number(i));this.target=this.game.createTarget(e,i),this.queue=Boolean(Number(t[3]||"0"))}}serialize(){let e=[""+this.orderType];var t;return this.target&&(t=(this.target.obj||this.target.getBridge())?.id,e.push(""+(void 0!==t?t:""),this.target.tile.rx+","+this.target.tile.ry,this.queue?"1":"0")),e}print(){return this.isInvalid?"":`${Un[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.game.getPlayerByName(this.playerName);const h=this.game.mapShroudTrait.getPlayerShroud(n);if(h){if(this.target?.obj){let e=this.game.map.tileOccupation.calculateTilesForGameObject(this.target.obj.tile,this.target.obj);if(!e.find(e=>!h.isShrouded(e)))return}let e=this.validateOrders(n).slice(0,128),a=[],t=[],r=[],i=[],s=[];if(e.forEach(e=>{(e instanceof hu?t:e.orderType===Un.Scatter?r:e.orderType===Un.DeploySelected?i:e.orderType===Un.Cheer?s:a).push(e)}),t.length&&this.target){let r=this.target.getBridge();var o=t.map(e=>e.sourceObject);let s=new Ds(this.map).findPositions(o,this.target.tile,r);t.forEach(e=>{var t=s.get(e.sourceObject),i=!r||r.isHighBridge()?this.map.tileOccupation.getBridgeOnTile(t):r,t=this.game.createTarget(i,t);e.target=t,a.push(e)})}if(r.length){o=r.map(e=>e.sourceObject).filter(e=>e.isInfantry()||e.isVehicle());let i=new ua(this.game).findPositions(o);r.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))}s.length&&(n.cheerCooldownTicks||(n.cheerCooldownTicks=this.game.rules.general.maximumCheerRate,a.push(...s),this.game.events.dispatch(new gu(n)))),a.forEach(e=>e.sourceObject.unitOrderTrait.addOrder(e,this.queue)),this.updateWaypointPaths(a)}}}validateOrders(e){let i=this.orderActionContext.getOrCreateSelection(e);var r,s=i.getSelectedUnits();let t=this.orderFactory.create(this.orderType,i);t.target=this.target;let a=[];for(r of s)if(!(r.owner!==e||r.rules.spawned||r.isDestroyed||r.isCrashing||r.isDisposed||r.warpedOutTrait.isActive()||(t.sourceObject=r,t instanceof pu&&t.isValid()&&!t.isAllowed()&&this.game.events.dispatch(new mu(r)),t.singleSelectionRequired&&1<s.length)))if(t.isValid()&&t.isAllowed()){let e=this.orderFactory.create(this.orderType,i);e.set(r,this.target),a.push(e)}else{let t=!1;for(var n of iu){let e=this.orderFactory.create(n,i);if(e.set(r,this.target),!(e.singleSelectionRequired&&1<s.length)&&(e.targetOptional===!this.target&&e.isValid()&&e.isAllowed())){a.push(e),t=!0;break}}if(!t&&this.target&&this.orderType!==Un.Deploy){let e=this.orderFactory.create(Un.Move,i);e.set(r,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(Pa))];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 yu extends ca{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 wu extends ca{constructor(e,t){super(e,wu.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 Tu{constructor(e){this.target=e,this.type=vr.BuildingGarrison}}class bu extends Rr{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1,this.preventOpportunityFire=!1}isAllowed(e){return 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 yu(this.game,this.target)),!(this.aborted=!0)):(this.game.limboObject(e,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(e).getControlGroupNumber()}),t.units.length||(this.game.changeObjectOwner(this.target,e.owner),this.game.events.dispatch(new Tu(this.target))),t.units.push(e),!0):!!this.movePerformed||(this.children.push(new wu(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class vu{constructor(e){this.target=e,this.type=vr.UnitRecycle}}class Su extends Rr{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1}isAllowed(e){return e.rules.movementZone!==ii.Fly&&e.rules.locomotor!==ti.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 yu(this.game,this.target)),!(this.aborted=!0)):(this.game.sellTrait.sell(e),this.game.events.dispatch(new vu(e)),!0):!!this.movePerformed||(this.children.push(new wu(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class _u{constructor(e,t){this.target=e,this.source=t,this.type=vr.BuildingInfiltration}}class ku extends Rr{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 yu(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),e.agentTrait?.infiltrate(e,this.target,this.game),this.game.events.dispatch(new _u(this.target,e)),!0):!!this.movePerformed||(this.children.push(new wu(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}(s=jc=jc||{})[s.MoveToQueueingTile=0]="MoveToQueueingTile",s[s.WaitForTurn=1]="WaitForTurn",s[s.MoveToTarget=2]="MoveToTarget",s[s.EnterTarget=3]="EnterTarget",s[s.ClearTarget=4]="ClearTarget";class Ou extends Rr{constructor(e,t){super(),this.game=e,this.target=t,this.movePerformed=!1}isAllowed(e){return e.rules.movementZone!==ii.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=jc.MoveToQueueingTile:this.state=jc.MoveToTarget}onEnd(e){!this.target.isDestroyed&&e.isSpawned&&this.target.hospitalTrait.removeFromHealQueue(e)}onTick(i){if(this.isCancelling()&&this.state!==jc.EnterTarget||this.state===jc.ClearTarget||i.moveTrait.isDisabled())return!0;if(this.state===jc.MoveToQueueingTile){let t=new Ds(this.game.map);var e=new xr(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 ca(this.game,e,!1,{closeEnoughTiles:5})),this.children.push(new ss(()=>{[gs.Success,gs.CloseEnough].includes(i.moveTrait.lastMoveResult)||this.cancel()})),this.state=jc.WaitForTurn,this.queueingTile=e,!1)}if(this.state===jc.WaitForTurn){if(!this.target.hospitalTrait.unitIsFirstInHealQueue(i))return!1;this.queueingTile=void 0,this.state=jc.MoveToTarget}if(this.state===jc.MoveToTarget){if(!this.isAllowed(i))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(i.tile,this.target))return!!this.movePerformed||(this.children.push(new wu(this.game,this.target)),!(this.movePerformed=!0));this.state=jc.EnterTarget}return this.state===jc.EnterTarget&&(!this.isAllowed(i)||this.isCancelling()?(this.children.push(new yu(this.game,this.target)),this.state=jc.ClearTarget,!1):(this.game.limboObject(i,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(i).getControlGroupNumber()}),this.target.hospitalTrait.startHealing(i),!0))}getTargetLinesConfig(e){return{target:this.queueingTile?void 0:this.target,pathNodes:this.queueingTile?[{tile:this.queueingTile,onBridge:void 0}]:[]}}}class Iu extends ru{constructor(e){super(Un.Occupy),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Lc.Capture}getPointerType(e){return e?this.isAllowed()?Dc.OccupyMini:Dc.NoActionMini:this.isAllowed()?Dc.Occupy:Dc.NoOccupy}isValid(){return!(this.target.obj?.isDestroyed||!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!==ii.Fly&&t.rules.locomotor!==ti.Chrono&&0<this.game.sellTrait.computeRefundValue(t):e.hospitalTrait?t.healthTrait.health<100&&t.rules.movementZone!==ii.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 Su(this.game,e)]:e.hospitalTrait?[new Ou(this.game,e)]:e.garrisonTrait?[new bu(this.game,e)]:[new ku(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof bu||e instanceof ku);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Ws(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Cu extends Rr{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 wu(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));if(!this.isAllowed(e)||this.isCancelling())return this.children.push(new yu(this.game,this.target)),!(this.aborted=!0);var t=Math.floor(60*this.game.rules.combatDamage.c4Delay*is.BASE_TICKS_PER_SECOND);return this.target.c4ChargeTrait.setCharge(t,{player:e.owner,obj:e}),this.children.push(new yu(this.game,this.target)),!(this.aborted=!0)}getTargetLinesConfig(e){return{target:this.target,pathNodes:[],isAttack:!0}}}class Au extends ru{constructor(e,{forceAttack:t,noIvanBomb:i}={}){super(t?Un.ForceAttack:Un.Attack),this.game=e,this.isC4=!1,this.forceAttack=!!t,this.ivanBombAllowed=!i||!!t,this.targetOptional=!1,this.feedbackType=Lc.None,this.rangeHelper=new Ws(this.game.map.tileOccupation),this.losHelper=new Qa(this.game.map.tiles,e.map.tileOccupation)}getPointerType(e,t){if(!this.isAllowed())return e?Dc.NoActionMini:Dc.NoAction;if(this.isC4)return Dc.C4;var i=this.sourceObject.attackTrait?.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);if(i?.rules.sabotageCursor)return Dc.C4;if(this.ivanBombAllowed&&this.sourceObject.rules.ivan&&i?.warhead.rules.ivanBomb)return Dc.Dynamite;if(i?.warhead.rules.bombDisarm)return Dc.DefuseBomb;if(i&&i.rules.damage<0)return Dc.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?Dc.AttackMini:t?Dc.AttackRange:Dc.AttackNoRange}isValid(){if(!this.sourceObject.attackTrait)return!1;if(this.forceAttack&&this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile)&&!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.rules.c4&&e?.isBuilding()&&e.c4ChargeTrait&&(this.forceAttack||!this.game.areFriendly(e,this.sourceObject)||e.cabHutTrait))return this.isC4=!0,this.feedbackType=Lc.SpecialAttack,!0;if(this.isC4=!1,this.feedbackType=Lc.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===_r.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.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 Cu(this.game,this.target.obj)];var e=this.sourceObject.attackTrait.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);return[new an(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===ii.Fly){let e=t.find(e=>(e.constructor===ca||e.constructor===an)&&!e.isCancelling());e&&(i.moveTrait.currentWaypoint?.tile===this.target.tile||i.isAircraft()||e.constructor===an)&&e.forceCancel(i)&&t.splice(t.indexOf(e))}else{t.length&&i.isUnit()&&(i.rules.locomotor===ti.Vehicle||i.rules.locomotor===ti.Ship)&&(i.moveTrait.speedPenalty=.5);let e=t.find(e=>e.constructor===an&&!e.isCancelling());if(e?.getWeapon().warhead.rules.temporal)return e.setForceAttack(this.forceAttack),e.requestTargetUpdate(this.target),!1}return!0}}class Bu extends ru{constructor(e){super(Un.Stop),this.game=e,this.getPointerType=()=>Dc.NoAction}isValid(){return this.sourceObject.isTechno()}isAllowed(){return!0}process(){return[new ss(e=>{!e.isUnit()||e.rules.locomotor!==ti.Vehicle&&e.rules.locomotor!==ti.Ship||(e.moveTrait.speedPenalty=0)})]}onAdd(e,t){let i=this.sourceObject;return t||!e.length||!i.isUnit()||i.rules.locomotor!==ti.Vehicle&&i.rules.locomotor!==ti.Ship||(i.moveTrait.speedPenalty=.5),i.isBuilding()&&i.rallyTrait?.getRallyPoint()&&(i.unitRepairTrait?.resetRallyPoint(i,this.game),i.factoryTrait?.resetRallyPoint(i,this.game)),!0}}class Eu extends Rr{constructor(){super(),this.executed=!1,this.cancellable=!1}onTick(e){return this.executed?(e.stance=kr.None,!0):!e.isInfantry()||!e.art.sequences?.has(dr.Cheer)||(e.stance!==kr.None&&e.stance!==kr.Guard||(e.stance=kr.Cheer,this.children.push(new rs(1/60).setCancellable(!1)),!(this.executed=!0)))}}class Pu extends ru{constructor(){super(Un.Cheer),this.getPointerType=()=>Dc.NoAction}isValid(){return this.sourceObject.isInfantry()&&[kr.None,kr.Guard].includes(this.sourceObject.stance)}isAllowed(){return!0}process(){return[new Eu]}}class xu extends ru{constructor(e){super(Un.Dock),this.game=e,this.targetOptional=!1,this.feedbackType=Lc.Move}getPointerType(e){return e?this.isAllowed()?Dc.OccupyMini:Dc.NoActionMini:this.isAllowed()?Dc.Occupy:Dc.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 Gn(this.game,e,!0,!0)]:e.unitRepairTrait||this.sourceObject.rules.dock.includes(e.name)?[new os(this.game,e)]:[]}}class Nu extends ru{constructor(e){super(Un.Gather),this.game=e,this.targetOptional=!1,this.feedbackType=Lc.Move}getPointerType(e){return e?Dc.AttackMini:Dc.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.isOre}isAllowed(){return!0}process(){return[new Fn(this.game,this.target.tile,!0)]}}class Ru extends ca{constructor(){super(...arguments),this.attackPerformed=!1,this.passedFirstWaypoint=!1}onTick(i){if(i.moveTrait.moveState===ps.Moving&&(this.passedFirstWaypoint=!0),i.moveTrait.moveState===ps.ReachedNextWaypoint&&i.attackTrait&&!i.attackTrait.isDisabled()&&!this.isCancelling()){let e=i.attackTrait.selectDefaultWeapon(i);if(e&&(this.passedFirstWaypoint||e&&!e.getCooldownTicks())){var r=i.attackTrait.scanForTarget(i,e,this.game);if(r.target){let{target:e,weapon:t}=r;if(!t.getCooldownTicks()){r=i.attackTrait.createAttackTask(this.game,e,e.tile,t,{holdGround:!0,passive:!0});return this.children.push(r),this.useChildTargetLines=!0,this.attackPerformed=!0,i.moveTrait.velocity.set(0,0,0),i.moveTrait.currentWaypoint=void 0,i.moveTrait.collisionState=ms.Waiting,!1}}}if(this.attackPerformed){if(!i.isSpawned)return this.forceCancel(i),!0;this.attackPerformed=!1,this.passedFirstWaypoint=!1,this.useChildTargetLines=!1,i.moveTrait.collisionState=ms.Resolved,this.updateTarget(this.targetTile,this.toBridge)}}return super.onTick(i)}}class Mu extends ru{constructor(e,t){super(Un.AttackMove),this.game=e,this.map=t,this.targetOptional=!1,this.feedbackType=Lc.Attack}getPointerType(e){let t=this.isAllowed();var i,r,s;return t&&(i=!!this.target.getBridge(),r=this.sourceObject.rules.speedType,s=this.sourceObject.rules.movementZone===ii.Fly,t=s||0<this.map.terrain.getPassableSpeed(this.target.tile,r,i)||!!this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile)),e?t?Dc.AttackMini:Dc.NoActionMini:t?Dc.AttackMove:Dc.NoMove}isValid(){return this.sourceObject.isUnit()&&!!this.sourceObject.attackTrait&&!this.sourceObject.rules.preventAttackMove&&!(this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile)&&!this.sourceObject.rules.moveToShroud)}isAllowed(){return!this.sourceObject.moveTrait.isDisabled()&&!this.sourceObject.attackTrait.isDisabled()}process(){return[new Ru(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})]}}class Du{constructor(e,t){this.target=e,this.source=t,this.type=vr.BuildingRepairFull}}class Lu{constructor(e,t){this.source=e,this.tile=t,this.type=vr.BridgeRepair}}class Fu extends Rr{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 yu(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 Lu(e.owner,this.target.centerTile))):(this.target.healthTrait.healToFull(e,this.game),this.game.events.dispatch(new Du(this.target,e.owner))),!0):!!this.movePerformed||(this.children.push(new wu(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class ju extends ru{constructor(e){super(Un.Repair),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Lc.Capture}getPointerType(e){return e?this.isAllowed()?Dc.OccupyMini:Dc.NoActionMini:this.isAllowed()?Dc.RepairMove:Dc.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 Fu(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof Fu);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Ws(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Uu extends ru{constructor(e,t){super(t?Un.GuardArea:Un.Guard),this.game=e,this.targeted=t,this.getPointerType=e=>e?this.isAllowed()?Dc.GuardMini:Dc.NoActionMini:this.isAllowed()?Dc.Guard:Dc.NoMove,this.terminal=!0,this.targetOptional=!t,this.minimapAllowed=t,this.feedbackType=t?Lc.Move:Lc.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.sourceObject.rules.moveToShroud)}isAllowed(){return!0}process(){let t=this.targeted?this.target.tile:void 0;const e=this.sourceObject;if(!t&&e.isVehicle()&&e.harvesterTrait)return[new ss(()=>e.harvesterTrait.lastOreSite=void 0),new Fn(this.game,void 0,!0)];let i=[];return t&&i.push(new ca(this.game,t,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})),i.push(new ss(e=>{t&&![gs.Success,gs.CloseEnough].includes(this.sourceObject.moveTrait?.lastMoveResult)||(this.sourceObject.guardMode=!0)})),i}}class Wu extends ru{constructor(e){super(Un.Scatter),this.game=e,this.getPointerType=()=>Dc.NoAction}isValid(){return(this.sourceObject.isInfantry()||this.sourceObject.isVehicle())&&this.sourceObject.rules.movementZone!==ii.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 da(this.game,{tile:this.target.tile,toBridge:!!this.target.getBridge()})]}}class Vu{constructor(e){this.target=e,this.type=vr.EnterTransport}}(s=Uc=Uc||{})[s.MoveToQueueingTile=0]="MoveToQueueingTile",s[s.WaitForTurn=1]="WaitForTurn",s[s.MoveToTransport=2]="MoveToTransport",s[s.EnterTransport=3]="EnterTransport",s[s.ClearTransport=4]="ClearTransport";class zu extends Rr{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!==_r.Air&&this.target.zone!==_r.Air&&this.target.transportTrait.unitFitsInside(e)&&this.target.moveTrait.moveState===ps.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=Uc.MoveToQueueingTile:this.state=Uc.MoveToTransport}onEnd(e){this.target.isDestroyed||this.target.transportTrait?.removeFromLoadQueue(e)}onTick(n){if(this.isCancelling()&&this.state!==Uc.EnterTransport||this.state===Uc.ClearTransport||n.moveTrait.isDisabled())return!0;if(this.target.tile!==this.initialTargetTile||this.target.moveTrait.moveState!==ps.Idle)return!0;if(this.state===Uc.MoveToQueueingTile){let r=new Ds(this.game.map),s=this.target.onBridge?this.game.map.tileOccupation.getBridgeOnTile(this.target.tile):void 0,a;var e=new xr(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)&&r.isEligibleTile(e,i,s,this.target.tile))return a=i,!0;return!1}).getNextTile();return!e||(this.children.push(new ca(this.game,e,!!a,{closeEnoughTiles:5})),this.children.push(new ss(()=>{[gs.Success,gs.CloseEnough].includes(n.moveTrait.lastMoveResult)||this.cancel()})),this.queueingNode={tile:e,onBridge:a},this.state=Uc.WaitForTurn,!1)}if(this.state===Uc.WaitForTurn){if(!this.target.transportTrait.unitIsFirstInLoadQueue(n))return!1;this.queueingNode=void 0,this.state=Uc.MoveToTransport}if(this.state===Uc.MoveToTransport){if(!this.isAllowed(n))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(n.tile,this.target))return!!this.movePerformed||(this.children.push(new wu(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));this.state=Uc.EnterTransport}return this.state===Uc.EnterTransport&&(!this.isAllowed(n)||this.isCancelling()?(this.children.push(new yu(this.game,this.target)),this.state=Uc.ClearTransport,!1):(this.game.limboObject(n,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(n).getControlGroupNumber(),inTransport:!0}),this.game.events.dispatch(new Vu(this.target)),this.target.transportTrait.units.push(n),!0))}getTargetLinesConfig(e){return{target:this.queueingNode?void 0:this.target,pathNodes:this.queueingNode?[this.queueingNode]:[]}}}class Hu extends ru{constructor(e){super(Un.EnterTransport),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Lc.Enter}getPointerType(e){return e?this.isAllowed()?Dc.OccupyMini:Dc.NoActionMini:this.isAllowed()?Dc.Occupy:Dc.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!==_r.Air&&e.zone!==_r.Air&&e.transportTrait.unitFitsInside(t)&&e.moveTrait.moveState===ps.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 zu(this.game,t)]:[new ss(()=>{t.unitOrderTrait.addTask(new ca(this.game,e.tile,e.onBridge)),t.unitOrderTrait.addTask(new ss(()=>{this.game.map.terrain.getPassableSpeed(t.tile,e.rules.speedType,e.onBridge)&&e.unitOrderTrait.addTask(new zu(this.game,t))}))})]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof zu);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Ws(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Gu{constructor(e){this.target=e,this.type=vr.BuildingCapture}}class $u extends Rr{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 yu(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),this.game.changeObjectOwner(this.target,e.owner),this.game.events.dispatch(new Gu(this.target)),!0):!!this.movePerformed||(this.children.push(new wu(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class qu extends ru{constructor(e){super(Un.Capture),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Lc.Capture}getPointerType(e){return e?this.isAllowed()?Dc.OccupyMini:Dc.NoActionMini:this.isAllowed()?Dc.Occupy:Dc.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 $u(this.game,this.target.obj)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof $u);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new Ws(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Zu{constructor(e,t){this.game=e,this.map=t}create(e,t){switch(e){case Un.Deploy:return new pu(this.game,!0);case Un.DeploySelected:return new pu(this.game,!1);case Un.ForceMove:return new hu(this.game,this.map,t,!0);case Un.Move:return new hu(this.game,this.map,t);case Un.ForceAttack:return new Au(this.game,{forceAttack:!0});case Un.Attack:return new Au(this.game,{noIvanBomb:!0});case Un.PlaceBomb:return new Au(this.game);case Un.AttackMove:return new Mu(this.game,this.map);case Un.Capture:return new qu(this.game);case Un.Occupy:return new Iu(this.game);case Un.Stop:return new Bu(this.game);case Un.Cheer:return new Pu;case Un.Dock:return new xu(this.game);case Un.Gather:return new Nu(this.game);case Un.Repair:return new ju(this.game);case Un.Guard:return new Uu(this.game,!1);case Un.GuardArea:return new Uu(this.game,!0);case Un.Scatter:return new Wu(this.game);case Un.EnterTransport:return new Hu(this.game);default:throw new Error(`Unhandled order type ${Un[e]}`)}}}class Qu{constructor(e,t,i){this.game=e,this.map=t,this.orderActionContext=i}create(){return new fu(this.game,this.map,this.orderActionContext,new Zu(this.game,this.map))}}class Xu{constructor(e){this.game=e}create(){return new wl(this.game)}}class Yu{constructor(e){this.target=e,this.type=vr.PlayerResigned}}class Ku extends yl{constructor(e,t){super(Lh.QuitGame),this.game=e,this.localPlayerName=t}process(){if(this.localPlayerName!==this.playerName){let e=this.game.getPlayerByName(this.playerName);this.game.removeAllPlayerAssets(e),e.isCombatant()&&(e.resigned=!0,this.game.events.dispatch(new Yu(e)))}}}class Ju{constructor(e,t){this.game=e,this.localPlayerName=t}create(){return new Ku(this.game,this.localPlayerName)}}class ed{constructor(e){this.target=e,this.type=vr.BuildingRepairStart}}class td extends yl{constructor(e){super(Lh.ToggleRepair),this.game=e}unserialize(e){this.buildingId=Number(e[0])}serialize(){return[""+this.buildingId]}print(){return`Toggle repair ${this.buildingId}`}process(){var e=this.game.getPlayerByName(this.playerName);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(Ho);e.setDisabled(!e.isDisabled()),e.isDisabled()||this.game.events.dispatch(new ed(t))}}}}class id{constructor(e){this.game=e}create(){return new td(this.game)}}class rd extends yl{constructor(e){super(Lh.ToggleAlliance),this.game=e}unserialize(e){this.toPlayerName=e[0],this.toggle=Boolean(Number(e[1]))}serialize(){return[this.toPlayerName,""+(this.toggle?1:0)]}print(){return`Toggle alliance ${this.toggle?"on":"off"} with ${this.toPlayerName}`}process(){var e=this.game.rules.mpDialogSettings;if(e.alliesAllowed&&e.allyChangeAllowed){var a,n=this.game.getPlayerByName(this.playerName),t=this.game.getPlayerByName(this.toPlayerName),e=this.toggle;let i=n,r=t,s=this.game.alliances;if(!n.defeated&&s.canRequestAlliance(r)){let t=s.findByPlayers(i,r);t?t.status===Bh.Formed?e||(s.breakAlliance(i,r),this.game.onAllianceChange(t,i,!1)):t.status===Bh.Requested&&(t.players.first===r?e&&s.canFormAlliance(i,r)&&(s.acceptRequest(r,i),this.game.onAllianceChange(t,i,!0),1!==(n=this.game.getCombatants().filter(e=>e!==i&&!s.areAllied(i,e))).length||(a=s.findByPlayers(n[0],i))&&s.cancelRequest(a.players.first,a.players.second),1!==(a=this.game.getCombatants().filter(e=>e!==r&&!s.areAllied(r,e))).length||(a=s.findByPlayers(a[0],r))&&s.cancelRequest(a.players.first,a.players.second)):e||(s.cancelRequest(i,r),this.game.events.dispatch(new Ec(t,wc.Broken,i)),this.game.traits.filter(Mh).forEach(e=>{e[Mh.onChange](t,!1,this.game)}))):e&&s.canFormAlliance(i,r)&&((e=s.request(i,r))&&this.game.events.dispatch(new Ec(e,wc.Requested,i)))}}}}class sd{constructor(e){this.game=e}create(){return new rd(this.game)}}class ad extends yl{constructor(e){super(Lh.ActivateSuperWeapon),this.game=e}unserialize(e){this.superWeaponType=Number(e[0]),this.tile={x:Number(e[1]),y:Number(e[2])},this.tile2=3<e.length?{x:Number(e[3]),y:Number(e[4])}:void 0}serialize(){return[this.superWeaponType,this.tile.x,this.tile.y,...this.tile2?[this.tile2.x,this.tile2.y]:[]].map(String)}print(){return`Activate SuperW ${qi[this.superWeaponType]} at tile (${this.tile.x}, ${this.tile.y})`+(this.tile2?`, (${this.tile2.x}, ${this.tile2.y})`:"")}process(){let e=this.game.getPlayerByName(this.playerName),t=e.superWeaponsTrait?.getAll().find(e=>e.rules.type===this.superWeaponType);var i,r;t&&t.status===yc.Ready&&((i=this.game.map.tiles.getByMapCoords(this.tile.x,this.tile.y))?(r=this.tile2?this.game.map.tiles.getByMapCoords(this.tile2.x,this.tile2.y):void 0,t.activate(this.game,i,r)):console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`))}}class nd{constructor(e){this.game=e}create(){return new ad(this.game)}}class od{constructor(e,t){this.tile=e,this.player=t,this.type=vr.PingLocation}}class hd extends yl{constructor(e){super(Lh.PingLocation),this.game=e}unserialize(e){this.tile={x:Number(e[0]),y:Number(e[1])}}serialize(){return[""+this.tile.x,""+this.tile.y]}print(){return`Ping location at tile (${this.tile.x}, ${this.tile.y})`}process(){var e=this.game.getPlayerByName(this.playerName),t=this.game.map.tiles.getByMapCoords(this.tile.x,this.tile.y);if(t){this.game.events.dispatch(new od(t,e));for(var i of[e,...this.game.alliances.getAllies(e)])this.game.events.dispatch(new il(i,Zt.GenericNonCombat,t))}else console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}}class ld{constructor(e){this.game=e}create(){return new hd(this.game)}}class cd extends yl{constructor(e){super(Lh.ObserveGame),this.game=e}process(){let e=this.game.getPlayerByName(this.playerName);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 Yu(e)),this.game.events.dispatch(new dl(e)),this.game.mapShroudTrait.getPlayerShroud(e)?.revealAll(),t=e.radarTrait.isDisabled(),e.radarTrait.setDisabled(!1),t&&this.game.events.dispatch(new tl(e,!0)))}}class ud{constructor(e){this.game=e}create(){return new cd(this.game)}}class dd{register(e,t,i){var r=new Gc;e.registerFactory(Lh.NoAction,new qc),e.registerFactory(Lh.PlaceBuilding,new Yc(t)),e.registerFactory(Lh.SellBuilding,new Jc(t)),e.registerFactory(Lh.ToggleRepair,new id(t)),e.registerFactory(Lh.SelectUnits,new tu(t,r)),e.registerFactory(Lh.OrderUnits,new Qu(t,t.map,r)),e.registerFactory(Lh.UpdateQueue,new Xu(t)),e.registerFactory(Lh.ToggleAlliance,new sd(t)),e.registerFactory(Lh.ActivateSuperWeapon,new nd(t)),e.registerFactory(Lh.PingLocation,new ld(t)),e.registerFactory(Lh.QuitGame,new Ju(t,i)),e.registerFactory(Lh.ObserveGame,new ud(t))}}var pd=__webpack_require__(949);class gd{constructor(){this.detectors=new Set}[Ph.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.detect(e,t)}[xh.onUnspawn](e,t){e.isTechno()&&(this.isGlobalDetector(e)&&(this.detectors.delete(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.undetect(e,t))}[Nh.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isDisguisable(e)&&(this.undetect(e,i),this.detect(e,i))}[ls.onTileChange](e,t,i){if(this.isGlobalDetector(e))throw new Error("Detector units not implemented");this.isDisguisable(e)&&(this.undetect(e,t),this.detect(e,t))}[aa.onPowerLow](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait&&!e.poweredTrait.isPoweredOn());this.updateAroundDetectors(i,e)}[aa.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[aa.onPowerChange](e,t){}updateAroundDetectors(e,t){let i=new Set;for(var r of e)for(var s of this.findTechnosAroundDetector(r,t))i.add(s);for(var a of i)this.isDisguisable(a)&&(this.undetect(a,t),this.detect(a,t))}updateAroundDetector(e,t){var i;for(i of this.findTechnosAroundDetector(e,t))this.isDisguisable(i)&&(this.undetect(i,t),this.detect(i,t))}findTechnosAroundDetector(e,t){var i=e.getFoundation(),r=Math.max(i.width,i.height),i=e.rules.detectDisguiseRange+r,r=new pd.Vector2(e.tile.rx,e.tile.ry).addScalar(-i),i=new pd.Vector2(e.tile.rx,e.tile.ry).addScalar(i);return t.map.technosByTile.queryRange(new pd.Box2(r,i))}detect(e,t){let i=new Set,r=new Ws(t.map.tileOccupation);for(var s of this.detectors)if(!t.areFriendly(s,e)){var a=s.owner,n=s.rules.detectDisguiseRange;if(!i.has(a))if(!(s.isBuilding()&&s.poweredTrait&&!s.poweredTrait.isPoweredOn())&&r.tileDistance(e,s.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)}}var md=__webpack_require__(949);class fd{constructor(){this.detectors=new Set}[Ph.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isCloakable(e)&&this.detect(e,t)}[xh.onUnspawn](e,t){e.isTechno()&&this.isGlobalDetector(e)&&this.detectors.delete(e)}[Nh.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isCloakable(e)&&this.detect(e,i)}[ls.onTileChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,t),this.isCloakable(e)&&this.detect(e,t)}[aa.onPowerLow](e,t){}[aa.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[aa.onPowerChange](e,t){}[Rh.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 r of e)for(var s of this.findTechnosAroundDetector(r,t))i.add(s);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(),r=Math.max(i.width,i.height),i=e.rules.sensorsSight+r,r=new md.Vector2(e.tile.rx,e.tile.ry).addScalar(-i),i=new md.Vector2(e.tile.rx,e.tile.ry).addScalar(i);return t.map.technosByTile.queryRange(new md.Box2(r,i))}detect(e,t){let i=new Ws(t.map.tileOccupation);for(var r of this.detectors)if(!t.areFriendly(r,e)){var s=r.rules.sensorsSight;if(!(r.isBuilding()&&r.poweredTrait&&!r.poweredTrait.isPoweredOn())&&i.tileDistance(e,r.tile)<=s){s=e.cloakableTrait?.isCloaked();if(e.cloakableTrait.uncloak(t),s)for(var a of[r.owner,...t.alliances.getAllies(r.owner)])t.traits.get(rl).addEventForPlayer(Zt.GenericNonCombat,a,e.tile,t);break}}}isGlobalDetector(e){return!(!e.isTechno()||!e.rules.sensors&&!e.rules.sensorArray||!e.rules.sensorsSight)}isCloakable(e){return e.isTechno()&&!!e.cloakableTrait}}class yd{constructor(e,t,i){this.target=e,this.player=t,this.tile=i,this.type=vr.CratePickup}}var wd=__webpack_require__(949);class Td{constructor(){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,r=!1,s=!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)===_r.Water;t?(u||(i=c),s=u):u?r=s=!0:t=i=c}else if(t&&!c)break}t&&(e.push(t),i&&i!==t&&e.push(i),r||s||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}[Rh.onTick](t){for(var e of this.crates)e.ticksLeft--,e.ticksLeft<=0&&(t.unspawnObject(e.obj),e.obj.dispose());this.crates=this.crates.filter(e=>0<e.ticksLeft);for(let e=0;e<this.minCrates-this.crates.length&&this.spawnCrate(this.allTiles,t);e++);}spawnCrate(t,i){var r=i.rules.crateRules,s=this.chooseSpawnTile(t,i);if(s){var a=i.map.getTileZone(s,!0)===_r.Water,t=this.choosePowerup(a,i.rules.powerups.powerups,i);if(t){a=a?r.waterCrateImg:r.crateImg;let e=i.createObject(At.Overlay,a);e.overlayId=i.rules.getOverlayId(a),e.value=0,i.spawnObject(e,s);i=60*r.crateRegen*is.BASE_TICKS_PER_SECOND*(.5+1.5*i.generateRandom());return this.crates.push({obj:e,powerup:t,ticksLeft:i}),e}}}chooseSpawnTile(e,t){return t.generateRandom()<(this.mapEdgeIsWater?1/3:2/3)&&(e=this.availEdgeTiles),this.chooseRandomTile(e,t)}chooseRandomTile(e,t){let i;let r=0;for(;i=e[t.generateRandomInt(0,e.length-1)],r++,r<100&&!this.canPlaceCrateOnTile(t,i););if(100<=r){var s=t.map.tileOccupation.getEmptyTiles();if(!s.length)return;i=s[t.generateRandomInt(0,s.length-1)]}return i}canPlaceCrateOnTile(e,t){return e.map.mapBounds.isWithinBounds(t)&&!e.map.getGroundObjectsOnTile(t).length&&0<e.map.terrain.getPassableSpeed(t,Kt.Amphibious,!1)&&t.terrainType!==Xt.Shore&&0===t.rampType}choosePowerup(t,i,r){if((i=t?i.filter(e=>e.waterAllowed):i).length){var s,t=i.reduce((e,t)=>e+t.probShares,0),a=r.generateRandomInt(0,t);let e=0;for(s of i)if(e+=s.probShares,a<e)return s}}pickupCrate(e,t,i){let r=this.crates.find(e=>e.obj===t);if(r){this.crates.splice(this.crates.indexOf(r),1),i.unspawnObject(r.obj),r.obj.dispose();let t=this.grantPowerup(e,r.powerup,r.obj.tile,i);var s;return void 0!==t&&(s=i.rules.powerups.powerups.find(e=>e.type===t),i.events.dispatch(new yd(s,e.owner,r.obj.tile))),this.spawnCrate(this.allTiles,i),t}}grantPowerup(e,t,i,r){let s=e.owner,a=!1;if(s.isCombatant()){if(t.type===Zi.Unit){let e;if(![...s.buildings].some(e=>e.rules.constructionYard)&&r.rules.crateRules.freeMCV){let t=r.rules.general.baseUnit;if(!s.getOwnedObjects(!0).some(e=>t.includes(e.name))&&s.credits>=[...r.rules.ai.buildPower,...r.rules.ai.buildRefinery].map(e=>r.rules.getBuilding(e)).filter(e=>e.aiBasePlanningSide===s.country.side).reduce((e,t)=>e+t.cost,0)){var n=t.find(e=>{let t=r.rules.getObject(e,At.Vehicle);return t.isAvailableTo(s.country)&&t.hasOwner(s.country)});if(!n)throw new Error(`No suitable MCV found for player country ${s.country}`);e=r.rules.getObject(n,At.Vehicle)}}if(e||(n=r.rules.crateRules.unitCrateType?[r.rules.getObject(r.rules.crateRules.unitCrateType,At.Vehicle)]:[...r.rules.vehicleRules.values()].filter(e=>e.crateGoodie&&0<r.map.terrain.getPassableSpeed(i,e.speedType,!1))).length&&(e=n[r.generateRandomInt(0,n.length-1)]),e){let t=r.createUnitForPlayer(e,s);var o=new xr(r.map.tiles,r.map.mapBounds,i,{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();o?(r.spawnObject(t,o),a=!0):(s.removeOwnedObject(t),t.dispose())}}else if(t.type===Zi.Money){if(!t.data)throw new Error("Money powerup missing data field");s.credits+=Math.floor(Number(t.data)*(.55+2*r.generateRandom()*.45)),a=!0}else if(t.type===Zi.HealBase){var h;for(h of s.getOwnedObjects(!0))h.isDestroyed||h.healthTrait.healToFull(void 0,r);a=!0}else if(t.type===Zi.Reveal)r.mapShroudTrait.revealMap(s,r),a=!0;else if(t.type===Zi.Veteran){if(e.veteranTrait&&!e.veteranTrait.isMaxLevel()){a=!0;var l,c=Number(t.data);for(l of this.getUnitsInCrateRadius(r,i,s))l.veteranTrait?.promote(c,r)}}else if(t.type===Zi.Armor){if(1===e.crateBonuses.armor){a=!0;var u,d=Number(t.data);for(u of this.getUnitsInCrateRadius(r,i,s))1===u.crateBonuses.armor&&(u.crateBonuses.armor=d)}}else if(t.type===Zi.Firepower){if(1===e.crateBonuses.firepower){a=!0;var p,g=Number(t.data);for(p of this.getUnitsInCrateRadius(r,i,s))1===p.crateBonuses.firepower&&(p.crateBonuses.firepower=g)}}else{if(t.type!==Zi.Speed)return void console.warn(`Unhandled powerup type "${Zi[t.type]}"`);if(1===e.crateBonuses.speed){a=!0;var m,f=Number(t.data);for(m of this.getUnitsInCrateRadius(r,i,s))1===m.crateBonuses.speed&&(m.crateBonuses.speed=f)}}if(!a){o=r.rules.powerups.powerups.find(e=>e.type===Zi.Money&&0<e.probShares);if(o)return this.grantPowerup(e,o,i,r)}return t.type}}getUnitsInCrateRadius(e,t,i){let r=e.rules.crateRules.crateRadius,s=new Ws(e.map.tileOccupation);return e.map.technosByTile.queryRange((new wd.Box2).setFromCenterAndSize(new wd.Vector2(t.rx,t.ry),new wd.Vector2(r,r))).filter(e=>e.owner===i&&e.isUnit()&&s.tileDistance(e,t)<=r)}}class bd{constructor(){this.type=vr.StalemateDetect}}class vd{constructor(){this.stale=!1,this.allPlayersCredits=new Map,this.resetCountdown()}isStale(){return this.stale}getCountdownTicks(){return this.countdownTicks}resetCountdown(){this.countdownTicks=Math.floor(60*vd.graceMinutes*is.BASE_TICKS_PER_SECOND)}clearStale(){this.stale=!1,this.resetCountdown()}[Rh.onTick](e){0<this.countdownTicks?this.countdownTicks--:this.stale||(this.stale=!0,this.resetCountdown(),e.events.dispatch(new bd));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())}}[Ca.onProduce](){this.clearStale()}[Mc.onPlace](e){e.wallTrait||this.clearStale()}[Dh.onDestroy](e,t,i){!e.isBuilding()||e.owner.isNeutral||e.wallTrait||e.rules.insignificant||i?.obj&&t.areFriendly(e,i.obj)||this.clearStale()}[Nh.onChange](e,t,i){e.isBuilding()&&!t.isNeutral&&(i.alliances.areAllied(e.owner,t)||this.clearStale())}}vd.graceMinutes=5;var Sd,_d,kd=__webpack_require__(949);class Od{constructor(e){this.prng=e}static factory(e,t){return new this(new Nc(Number(e+""+t)))}generateColors(e){let t=[...e.humanPlayers,...e.aiPlayers].filter(Pa),i=t.map(e=>e.colorId).filter(e=>-2!==e);e=cr.length;let r=new Array(e).fill(0).map((e,t)=>t).filter(e=>!i.includes(e)),s=new Map;return t.forEach(e=>{if(-3!==e.countryId&&-2===e.colorId){if(r.length<1)throw new Error("Out of available colors to choose from");var t=this.prng.generateRandomInt(0,r.length-1);s.set(e,r[t]),r.splice(t,1)}}),s}generateCountries(e,t){let i=t.getMultiplayerCountries().length,r=[...e.humanPlayers,...e.aiPlayers].filter(Pa),s=new Map;return r.forEach(e=>{-2===e.countryId&&s.set(e,this.prng.generateRandomInt(0,i-1))}),s}generateStartLocations(i,r){let e=[...i.humanPlayers,...i.aiPlayers].filter(Pa),t=e.filter(e=>-2!==e.startPos).map(e=>e.startPos),s=[...r.keys()].filter(e=>!t.includes(e)),a=[];for(;s.length;){var n=s.length?this.prng.generateRandomInt(0,s.length-1):0;a.push(...s.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=>r[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=>r[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 r=e.map(e=>new kd.Vector2(e.x,e.y)),s,a=0;if(!t.length)throw new Error("Search array must have at least one element");for(var n of t){let i=new kd.Vector2(n.x,n.y);var o=r.reduce((e,t)=>e+i.distanceTo(t),0);o>=a&&(s=n,a=o)}return s}}class Id{constructor(e,t,i,r,s,a){this.game=e,this.inputActions=t,this.replayRecorder=i,this.actionSerializer=r,this.actionFactory=s,this.actionLogger=a,this.errorState=!1}init(){this.gameTurnMillis=1e3/(this.game.speed.value*is.BASE_TICKS_PER_SECOND)}setErrorState(){this.errorState=!0}getErrorState(){return this.errorState}getTurnMillis(){return this.gameTurnMillis}doGameTurn(){if(!this.errorState){if(this.game.status!==Pc.Ended){var t,e=this.inputActions.dequeueAll();const r=new Map;for(t of e){var i=this.actionSerializer.getActionPayload(t);let e=r.get(t.playerName);e||(e=[],r.set(t.playerName,e)),e.push(i)}this.replayRecorder.recordActions(this.game.currentTick,r),r.forEach((t,i)=>{if(!t.length){let e=new $c;e.playerName=i,t.push(this.actionSerializer.getActionPayload(e))}}),this.processActions(r)}this.game.update()}}processActions(e){[...e].forEach(([i,e])=>e.forEach(e=>{let t=this.actionFactory.create(e.id);t.playerName=i,t.unserialize(e.params),t.process();e=t.print();e&&this.actionLogger?.debug(`(${i}): ${e}`)}))}dispose(){}}(s=Sd=Sd||{})[s.Closed=0]="Closed",s[s.Open=1]="Open",s[s.OpenObserver=2]="OpenObserver",s[s.Player=3]="Player",s[s.Ai=4]="Ai";class Cd{encode(e){let r=[],s=0;return e.split("").forEach((e,t)=>{var i=e.charCodeAt(0)<<2*t-7*s,e=127&i,t=i>>7&127,i=i>>14&127;i&&s++,r.push(e,t),i&&r.push(i)}),r.push(0,0),2<=e.length&&r.push(0),r=r.map(e=>128^e),r.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 r=[],s=0,a=0;for(;i.length;){var n=r.length,o=i.shift(),h=i.shift();let e=0,t=!1;(-1!==[1,2,3].indexOf(i[0])||n>s+3)&&(e=i.shift(),s=n,t=!0);n=(e<<14|h<<7|o)>>2*n-7*a;r.push(127&n),t&&a++}return r.map(e=>String.fromCharCode(e)).join("")}}class Ad{serializeOptions(e){let t=e.gameMode,i=(new Cd).encode(e.mapTitle);var r=["0","0",6-e.gameSpeed,e.credits,e.unitCount,Number(e.shortGame),Number(e.superWeapons),Number(e.buildOffAlly),Number(e.mcvRepacks),Number(e.cratesAppear),t,"0",i,e.maxSlots,"1",e.mapSizeBytes,e.mapName,e.mapDigest].join(",");return`${r}:${e.humanPlayers.map(e=>`${e.name},${e.countryId},${e.colorId},${e.startPos},${e.teamId},0,0,0`).join(",")}:@:${e.aiPlayers.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===Sd.Closed)return"@Closed@";if(e.type===Sd.Open)return"@Open@";if(e.type===Sd.OpenObserver)return"@OpenObserver@";if(e.type===Sd.Ai){if(e.difficulty===Oh.Easy)return"@EasyAI@";if(e.difficulty===Oh.Medium)return"@MediumAI@";if(e.difficulty===Oh.Brutal)return"@HardAI@"}else if(e.type===Sd.Player)return e.name;throw new Error(`Unexpected slot info with type ${Sd[e.type]}`)}).join(",")+","}serializeLoadInfo(e){return e.map(e=>[e.name,e.status,e.loadPercent,e.ping].join(",")).join(",")}serializePlayerActions(e){return e.map(e=>e.id+"."+e.params.join(".")).join(";")}serializeAllPlayerActions(e,t){return e+"="+[...t].map(([e,t])=>{return`${e}:${this.serializePlayerActions(t)}`}).join("$")}}class Bd{parseOptions(e){let i={},[t,r,,s]=e.split(":"),a=t.split(",");a.shift(),a.shift(),i.gameSpeed=6-Number(a.shift()),i.credits=Number(a.shift()),i.unitCount=Number(a.shift()),i.shortGame=Boolean(Number(a.shift())),i.superWeapons=Boolean(Number(a.shift())),i.buildOffAlly=Boolean(Number(a.shift())),i.mcvRepacks=Boolean(Number(a.shift())),i.cratesAppear=Boolean(Number(a.shift())),i.gameMode=Number(a.shift()),a.shift(),i.mapTitle=(new Cd).decode(a.shift()),i.maxSlots=Number(a.shift()),a.shift(),i.mapSizeBytes=Number(a.shift()),i.mapName=a.shift(),i.mapDigest=a.shift();var n=r.split(",");if(n.length%8!=0)throw new Error(`Couldn't parse gameopt: unexpected players data length ${n.length}`);i.humanPlayers=[];for(let e=0,t=Math.floor(n.length/8);e<t;++e){var o={name:n[8*e],countryId:Number(n[8*e+1]),colorId:Number(n[8*e+2]),startPos:Number(n[8*e+3]),teamId:Number(n[8*e+4])};i.humanPlayers.push(o)}var h=s.slice(0,-1).split(",");if(h.length%5!=0)throw new Error(`Couldn't parse gameopt: unexpected ai data length ${h.length}`);i.aiPlayers=[];for(let e=0,t=Math.floor(h.length/5);e<t;++e){var l={difficulty:Number(h[5*e]),countryId:Number(h[5*e+1]),colorId:Number(h[5*e+2]),startPos:Number(h[5*e+3]),teamId:Number(h[5*e+4])};i.aiPlayers.push(-1!==l.countryId?l:void 0)}return 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 r=[];for(let e=0,t=Math.floor(i.length/2);e<t;++e)r.push({playerName:i[2*e],ping:Number(i[2*e+1])});return r}parseSlotData(e){var i;let r=[];for(i of e.slice(1,-1).split(",")){let t={};if("@Closed@"===i)t.type=Sd.Closed;else if("@Open@"===i)t.type=Sd.Open;else if("@OpenObserver@"===i)t.type=Sd.OpenObserver;else if(-1!==["@EasyAI@","@MediumAI@","@HardAI@"].indexOf(i)){t.type=Sd.Ai;let e;if("@EasyAI@"===i)e=Oh.Easy;else if("@MediumAI@"===i)e=Oh.Medium;else{if("@HardAI@"!==i)throw new Error(`Couldn't parse gameopt: unknown slot type ${i}`);e=Oh.Brutal}t.difficulty=e}else t.type=Sd.Player,t.name=i;r.push(t)}return r}parsePlayerActions(e){return e.split(";").map(e=>{var[t,...e]=e.split(".");return{id:Number(t),params:""!==e[0]?e:[]}})}parseAllPlayerActions(e){let i=new Map,[t,r]=e.split("=");return r.split("$").map(e=>{var[t,e]=e.split(":");i.set(t,this.parsePlayerActions(e))}),{turn:Number(t),actions:i}}}class Ed{constructor(e,t){this.type=e,this.tickNo=t}}(s=_d=_d||{})[s.TurnActions=0]="TurnActions",s[s.ChatMessage=1]="ChatMessage",s[s.Taunt=2]="Taunt";class Pd extends Ed{constructor(e){super(_d.ChatMessage,e)}serialize(){return this.payload.playerId+":"+x.encode(L(this.payload.message))}unserialize(e){var[t,e]=e.split(":"),t=Number(t),e=F(x.decode(e));this.payload={playerId:t,message:e}}}class xd extends Ed{constructor(e){super(_d.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 Nd extends Ed{constructor(e,t,i){super(_d.TurnActions,i),this.gameOptsParser=e,this.gameOptsSerializer=t}serialize(){return this.payload.map(([e,t])=>{return`${e}:${this.gameOptsSerializer.serializePlayerActions(t)}`}).join("$")}unserialize(e){let t=[];for(var i of e.split("$")){var[r,i]=i.split(":"),i=this.gameOptsParser.parsePlayerActions(i);t.push([Number(r),i])}this.payload=t}}class Rd{constructor(e,t){this.gameOptsParser=e,this.gameOptsSerializer=t}create(e,t){switch(e){case _d.TurnActions:return new Nd(this.gameOptsParser,this.gameOptsSerializer,t);case _d.ChatMessage:return new Pd(t);case _d.Taunt:return new xd(t);default:throw new Error(`Unsupported replay event type "${e}" at game tick "${t}"`)}}}const Md=[3,4];class Dd{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,r,s){this.gameId=e,this.gameTimestamp=t,this.gameOpts=i,this.engineVersion=r,this.modHash=s,this.name=Dd.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}serialize(){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");if(void 0===this.endTick)throw new Error("Replay is not finished");let e=new Ad,t=this.getHeaderTag()+"\n";t+=`ENGINE ${this.engineVersion} ${this.modHash}\n`,t+=[this.gameId,this.gameTimestamp,x.encode(e.serializeOptions(this.gameOpts))].join(" ")+"\n";for(var i of this.events)t+=i.tickNo+"="+i.type+"|"+i.serialize()+"\n";return t+=this.getEndTag()+" "+this.endTick+"\n",this.debugInfo&&(t+=x.encode(L(this.debugInfo))+"\n"),t}async parseHeader(e){let t=0,i,r,s,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:r,done:s}=await i.read();r=r?t.decode(r,{stream:!0}):"";let a=/\r\n|\n|\r/gm,n=0;for(;;){var o=a.exec(r);if(o)yield r.substring(n,o.index),n=a.lastIndex;else{if(s)break;o=r.substr(n);({value:r,done:s}=await i.read()),r=o+(r?t.decode(r,{stream:!0}):""),n=a.lastIndex=0}}n<r.length&&(yield r.substr(n))}(e)){if(0===t)i=this.readReplayVersion(h);else if(1===t){if(!h.match(Dd.engineLineRegex))throw new Error("Missing or invalid game engine version line");var l=h.split(" ");r=l[1],s=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=x.decode(l)}t++}if(t<3)throw new Error("Bad replay header");return{replayVersion:i,engineVersion:r,modHash:s,gameId:a,gameTimestamp:n,gameOptsSerialized:o}}unserialize(e,t){let i=e.split("\n");var r=this.readReplayVersion(i.shift()||"");if(!Md.includes(r))throw new Error("Unsupported replay version");let s=new Bd,a=i.shift();if(!a||!a.match(Dd.engineLineRegex))throw new Error("Missing or invalid game engine version line");let[,n,o]=a.split(" ");r<4&&(o="0");let h=i.shift();if(!h||!h.match(/^\d+ \d+ .*$/))throw new Error("Missing or invalid game id/time/opts line");var[l,e,r]=h.split(" "),r=s.parseOptions(x.decode(r));this.init(Number(l),Number(e),r,n,Number(o)),this.name=t.name,this.timestamp=t.timestamp;let c,u=!1;for(;c=i.shift();){if(c.startsWith(this.getEndTag())){u=!0;break}var d=c.match(/^(\d+)=(\d+)\|(.+)$/);if(!d)throw new Error(`Invalid event line "${c}"`);var[,p,g,d]=d,p=Number(p),g=Number(g);let e=new Rd(s,new Ad).create(g,p);e.unserialize(d),this.writeEvent(e)}if(!u)throw new Error("Incomplete replay data");t=c.match(new RegExp(`^${this.getEndTag()} (\\d+)$`));if(!t)throw new Error("Invalid end tag");this.endTick=Number(t[1]),1<=i.length&&(this.debugInfo=F(x.decode(i[0])))}getHeaderTag(){return"RA2TSREPL_v4"}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"}}Dd.extension=".rpl",Dd.maxNameLength=128,Dd.engineLineRegex=/^ENGINE \d+\.\d+( \d+)?$/;class Ld{constructor(e,t,i,r){this.replay=e,this.playerId=t,this.humanPlayers=i,this.actionSerializer=r}recordActions(t,i){if(Array.isArray(i)){let e=new Nd(new Bd,new Ad,t);e.payload=[[this.playerId,i.map(e=>this.actionSerializer.getActionPayload(e))]],this.replay.writeEvent(e)}else if(this.hasActualActions(i)){let e=new Nd(new Bd,new Ad,t);e.payload=[...i].map(([t,e])=>[this.humanPlayers.findIndex(e=>e.name===t),e]),this.replay.writeEvent(e)}}recordChatMessage(e,t,i){let r=new Pd(e);r.payload={playerId:this.humanPlayers.findIndex(e=>e.name===t),message:i},this.replay.writeEvent(r)}recordTaunt(e,t,i){let r=new xd(e);r.payload={playerId:this.humanPlayers.findIndex(e=>e.name===t),tauntNo:i},this.replay.writeEvent(r)}hasActualActions(e){return!![...e.values()].find(e=>e.find(e=>e.id!==Lh.NoAction))}}class Fd{getActionPayload(e){return{id:e.actionType,params:e.serialize()}}}class jd{constructor(e,t){this.options=e,this.logger=t,this.timeout=5,this._onMessage=new va,this._onError=new va,this._onClose=new va}get onMessage(){return this._onMessage.asEvent()}get onError(){return this._onError.asEvent()}get onClose(){return this._onClose.asEvent()}async connect(r){return new Promise((e,t)=>{this.socket=new WebSocket(r),"binary"===this.options.mode&&(this.socket.binaryType="blob");let i=e=>{this.socket.removeEventListener("error",i),t(new jd.ConnectError(`Connection to "${r}" 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){this.logger.debug("Got message:",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(r){return new Promise((e,t)=>{let i=new FileReader;i.onload=()=>e(i.result),i.onerror=()=>t(),i.readAsBinaryString(r)})}sendCommand(u,d){if(d.replyStartCode&&!d.replyEndCode)throw new Error("Invalid argument. Expected a reply end code, but got only a start code.");return new Promise((t,i)=>{let r=[],s,a=e=>{clearTimeout(s),t(e)},n=e=>{this.socket.removeEventListener("message",c),this.socket.removeEventListener("close",o),clearTimeout(s),s=void 0,i(e)};let o=()=>{n(new jd.SocketError("Connection was closed prematurely"))},h=e=>e.split(/\r?\n/).filter(e=>!!e).some(e=>(e=>{if(!d.replyEndCode&&!d.replyCodes)return a([{raw:e}]),!0;var[,t,...i]=e.split(" "),t=parseInt(t,10),i={raw:e,code:t,params:i};if(d.replyEndCode)return d.replyCodes&&-1!==d.replyCodes.indexOf(t)?(a([i]),!0):((t===d.replyStartCode||d.replyBodyCodes&&-1!==d.replyBodyCodes.indexOf(t)||t===d.replyEndCode)&&r.push(i),t===d.replyEndCode&&(a(r),!0));if(void 0===d.replyCodes)throw new Error("List of replyCodes must be specified when not using start/end codes");return-1!==d.replyCodes.indexOf(t)&&(a([i]),!0)})(e)),l=!1,c=e=>{l||(globalThis.Blob&&e.data instanceof Blob?this.parseData(e.data).then(e=>{l||h(e)&&(l=!0,this.socket.removeEventListener("message",c),this.socket.removeEventListener("close",o))}).catch(e=>{console.error("Failed to decode socket message.",e)}):h(e.data)&&(l=!0,this.socket.removeEventListener("message",c),this.socket.removeEventListener("close",o)))};if(this.socket&&this.socket.readyState===WebSocket.OPEN){var e=(void 0!==d.timeout?d:this).timeout;s=setTimeout(()=>{n(new jd.NoReplyError(`Timeout reached for command ${u}`))},1e3*e),this.socket.addEventListener("message",c),this.socket.addEventListener("close",o);try{this.sendMessage(u)}catch(e){n(e)}}else n(new jd.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 jd.SocketError(`Socket is not open${this.socket?` (readyState = ${this.socket.readyState})`:""}`);this.logger.debug("Sent message:",e),e+="\r\n";let t;t="binary"===this.options.mode?M(e):e,this.socket.send(t)}close(){this.socket&&this.socket.close()}isOpen(){return this.socket&&this.socket.readyState===WebSocket.OPEN}}jd.MAX_CHANNELNAME_LEN=30,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 r extends Error{constructor(e){super(e)}}e.ConnectError=r}(jd=jd||{});class Ud extends Error{constructor(e,t){super(e),this.code=t}}(s=(s=Ud=Ud||{}).Code||(s.Code={}))[s.InstanceNonExistent=0]="InstanceNonExistent",s[s.InstanceAlreadyExists=1]="InstanceAlreadyExists";var Wd;(s=Wd=Wd||{})[s.Public=0]="Public",s[s.Private=1]="Private",s[s.Page=2]="Page";class Vd{constructor(e,t,i,r,s,a,n,o,h,l,c,u){this.game=e,this.gservCon=t,this.gameoptParser=i,this.gameoptSerializer=r,this.actionSerializer=s,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.lagState=!1,this._onLagStateChange=new va,this._onActionsSent=new va,this._onActionsProcessed=new va,this._onActionsReceived=new va,this.receiveActions=e=>{var t=this.gameoptParser.parseAllPlayerActions(e);this.receivedActions.set(t.turn,t.actions),this.debug(`Recv actions: ${e}`),this._onActionsReceived.dispatch(void 0,t.turn)},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*is.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(Vd.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!==Pc.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.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();if(e.length||e.push(new $c),e.some(e=>e.actionType===Lh.QuitGame))return this.setErrorState(),void this.debug("Send actions: quit");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.playerName=i,t.unserialize(e.params),t.process();e=t.print();e&&this.actionLogger?.debug(`(${i}): ${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)}}Vd.PREFERRED_HASH_CHECK_MILLIS=1e3;const zd=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks");class Hd{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=zd.performance.now(),r=this.updateDeltaGameFrames(i);if(0<r)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 r=0;return this.startTime?(i=e-this.startTime,t=Math.round(i/t),r=t-this.lastGameFrame,this.lastGameFrame=t):this.startTime=e,r}stop(){this.isStarted&&(this.isStarted=!1)}destroy(){this.stop()}}const Gd=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");var $d,qd,Zd,Qd,Xd,Yd,Kd,Jd,ep=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},tp=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class ip{constructor(e,t,i,r,s,a,n,o){$d.set(this,void 0),qd.set(this,void 0),Zd.set(this,void 0),Qd.set(this,void 0),Xd.set(this,void 0),Yd.set(this,void 0),Kd.set(this,void 0),Jd.set(this,void 0),ep(this,$d,e,"f"),ep(this,qd,t,"f"),ep(this,Zd,new Ql(t,!1),"f"),ep(this,Qd,new Pl(t.events),"f"),ep(this,Xd,i,"f"),ep(this,Yd,a,"f"),ep(this,Kd,n,"f"),ep(this,Jd,o,"f"),tp(this,Qd,"f").subscribe(t=>e.forEach(e=>e.onGameEvent(t,tp(this,Zd,"f")))),e.forEach(e=>{e.setGameApi(tp(this,Zd,"f")),e.setActionsApi(new vl(t,r,s,e.name)),e.setProductionApi(new ac(t.getPlayerByName(e.name).production)),e.onGameStart(tp(this,Zd,"f"))})}isFinished(){return tp(this,qd,"f").status===Pc.Ended||tp(this,Yd,"f").getErrorState()}async update(){if(tp(this,Kd,"f"))await tp(this,Kd,"f").waitForTick();else{if(!(tp(this,Yd,"f")instanceof Id))throw new Error("Missing animation loop or turn manager");tp(this,Yd,"f").doGameTurn()}tp(this,$d,"f").forEach(e=>e.onGameTick(tp(this,Zd,"f")))}getCurrentTick(){return tp(this,Zd,"f").getCurrentTick()}getTickRate(){return tp(this,Zd,"f").getTickRate()}getPlayerStats(){return tp(this,qd,"f").getPlayable().filter(e=>!e.isObserver).map(t=>({name:t.name,country:t.country,ai:t.isAi||tp(this,$d,"f").some(e=>e.name===t.name),defeated:t.defeated,credits:t.credits,startLocation:t.startLocation}))}saveReplay(e){let t=tp(this,Xd,"f");t.finish(tp(this,qd,"f").currentTick);var i=`${tp(this,qd,"f").gameOpts.mapName}_${Date.now()}${Dd.extension}`,r=t.serialize(),i=a.resolve(e??process.cwd(),i);Gd.writeFileSync(i,r,"utf-8"),process.stdout.write(`Replay saved to "${i}"\n`)}dispose(){tp(this,Qd,"f").dispose(),tp(this,$d,"f").length=0,tp(this,Jd,"f")?.call(this)}}$d=new WeakMap,qd=new WeakMap,Zd=new WeakMap,Qd=new WeakMap,Xd=new WeakMap,Yd=new WeakMap,Kd=new WeakMap,Jd=new WeakMap;var rp,sp,ap,np,op,hp,lp,cp,up,dp,pp,gp,mp=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},fp=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};const yp=a.resolve((0,e.default)(),"./res");class wp{constructor(){rp.add(this),sp.set(this,void 0),ap.set(this,void 0),np.set(this,void 0),op.set(this,void 0),hp.set(this,!1),lp.set(this,void 0)}async init(e){mp(this,rp,"m",cp).call(this);var t=await(0,n.getOriginPrivateDirectory)(o.default,a.resolve(e)),i=await(0,n.getOriginPrivateDirectory)(o.default,yp),e=await(0,n.getOriginPrivateDirectory)(o.default,process.cwd());Pt.initGameResSource(bt.Local);let r=await Pt.initRfs(t);r.addDirectoryHandle(i),r.addDirectoryHandle(e);let s=await Pt.initVfs(r,Vs.get("vfs"));await s.loadStandaloneFiles(),await s.loadExtraMixFiles(Pt.getActiveEngine()),await s.addMixFile("ra2cd.mix"),await s.loadImplicitMixFiles(Pt.getActiveEngine()),Pt.loadRules(),fp(this,lp,await Pt.loadMapList(),"f"),fp(this,sp,Pt.getMpModes(),"f"),fp(this,hp,!0,"f")}getAvailableMaps(){if(!mp(this,hp,"f"))throw new Error("API is not initialized. Call init() first.");return mp(this,lp,"f").getAll().map(e=>e.fileName.toLowerCase())}getAvailableGameModes(e){if(!mp(this,hp,"f"))throw new Error("API is not initialized. Call init() first.");let t=mp(this,lp,"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?mp(this,rp,"m",dp):mp(this,rp,"m",up)).call(this,e)}}sp=new WeakMap,ap=new WeakMap,np=new WeakMap,op=new WeakMap,hp=new WeakMap,lp=new WeakMap,rp=new WeakSet,cp=function(){Vs.useDefaults(),Vs.setLevel(Vs.ERROR);const e=process.env.DEBUG_LOGGING;var t;if(e)if(isNaN(e))for(t of e.split(","))Vs.get(t).setLevel(Vs.DEBUG);else Vs.setLevel(Boolean(Number(e))?Vs.DEBUG:Vs.ERROR);fp(this,ap,Vs.get("ini"),"f"),fp(this,np,Vs.get("action"),"f"),fp(this,op,Vs.get("net"),"f")},up=async function(e){if(!mp(this,hp,"f"))throw new Error("API is not initialized. Call init() first.");var t=mp(this,rp,"m",gp).call(this,e),i=e.agents.filter(e=>e instanceof nc),r=await mp(this,rp,"m",pp).call(this,0,0,t,void 0),s=new fl,a=new zc;(new dd).register(a,r,void 0);let n=new Dd;n.init(r.id,r.startTimestamp,t,Pt.getVersion(),Pt.getModHash());e=new Fd,t=new Ld(n,0,r.gameOpts.humanPlayers,e);let o=new Id(r,s,t,e,a,mp(this,np,"f"));return o.init(),new ip(i,r,n,a,s,o)},dp=async function(e){if(!mp(this,hp,"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 nc&&t.push(i)}if(!(e.agents[0]instanceof nc))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 nc))throw new Error("Only the first player in the agents array can be a bot in online mode");var r=mp(this,rp,"m",gp).call(this,e);let s=class{constructor(e){this._onLoadInfo=new va,this._onGameStart=new va,this._onGameActions=new va,this._onGameDesync=new va,this._onRateChange=new va,this._onChatMessage=new va,this._onTaunt=new va,this.handleMessage=e=>{let t=e.split(" ");var i;"ping"===t[0]?this.isOpen()&&this.con.sendMessage("pong"):"privmsg"===t[1].toLowerCase()?this.handlePrivMsg(e):"page"===t[1].toLowerCase()?this.handlePage(e):"600"===t[1]?this.handleLoadInfo(t[3]):"700"===t[1]?this.handleGameStart():"800"===t[1]?this.handlePlayerActions(t[3]):"801"===t[1]?this._onGameDesync.dispatch(this):"802"===t[1]?([i,e]=t[3].slice(1).split(","),this._onRateChange.dispatch(this,{rate:Number(i),turnNo:Number(e)})):"803"===t[1]&&this._onTaunt.dispatch(this,{from:t[0].replace(/^:/,""),tauntNo:Number(t[3].replace(/^:/,""))})},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()}static factory(e){return new this(new jd({mode:"text"},e))}getCurrentUser(){return this.currentUser}async connect(e){return this.con.onMessage.subscribe(this.handleMessage),this.con.connect(e)}close(){this.con.onMessage.unsubscribe(this.handleMessage),this.con.close(),this.currentUser=void 0}isOpen(){return this.con.isOpen()}async login(e){await this.con.sendCommand(`user ${e}`,{replyCodes:[100]}),this.currentUser=e}async createGame(e,t,i,r,s){let a=await this.con.sendCommand(`create ${e} ${t} ${x.encode(i)} ${r} ${s}`,{replyCodes:[200,201]});if(201===a[0].code){s=a[0].params?a[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new Ud(`Create error: ${s}`,Ud.Code.InstanceAlreadyExists)}}async joinGame(e,t,i){let r=await this.con.sendCommand(`join ${e} ${t} ${i}`,{replyCodes:[400,401]});if(401===r[0].code){i=r[0].params?r[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new Ud(`Join error: ${i}`,Ud.Code.InstanceNonExistent)}}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 x.decode(e[0].params.splice(1).join(" ").replace(/^:/,""))}sendLoadedPercent(e){this.con.sendMessage(`loaded ${e}`)}requestLoadInfo(){this.con.sendMessage("loadinfo")}sendGameStateHash(e,t){this.con.sendMessage(`h ${e} ${t}`)}sendPlayerActive(e){this.con.sendMessage(`active ${e?1:0}`)}sendTaunt(e){this.con.sendMessage(`taunt ${e}`)}async ping(e){return this.con.sendCommand("ping",{replyCodes:[900],timeout:e})}sendPlayerActions(e,t){this.con.sendMessage(`a ${e} ${t}`)}handleLoadInfo(e){this._onLoadInfo.dispatch(this,e.replace(/^:/,""))}handleGameStart(){this._onGameStart.dispatch(this,void 0)}handlePlayerActions(e){this._onGameActions.dispatch(this,e.slice(1))}sayChannel(e){this.privmsg(["#all"],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,e,t]=t;let r;"#all"===e?r={type:Wd.Public,from:i,text:t}:e===this.currentUser&&(r={type:Wd.Private,from:i,text:t}),r&&this._onChatMessage.dispatch(this,r)}handlePage(e){var t=e.match(/^:([A-Za-z0-9-_]+) PAGE [A-Za-z0-9-_#']+ :(.*)/i);if(!t)throw new Error(`Unexpected PAGE message format "${e}"`);var[,e,t]=t,e={text:t,from:e,type:Wd.Page};this._onChatMessage.dispatch(this,e)}}.factory(mp(this,op,"f"));await s.connect(e.serverUrl),await s.login(e.agents[0].name);let a=new Ad;var n=a.serializeOptions(r),o=Date.now(),h=Number(o+"0");await s.createGame(h,0,n,Pt.getVersion(),Pt.getModHash()),await s.joinGame(h,Pt.getVersion(),Pt.getModHash());let l=new Bd;var c=l.parseOptions(await s.gameOpts()),u=e.agents[0].name;let d=await mp(this,rp,"m",pp).call(this,h,0,c,u);r=new Fd,n=new fl,h=new zc;(new dd).register(h,d,u);let p=new Dd;p.init(d.id,d.startTimestamp,c,Pt.getVersion(),Pt.getModHash());var g,c=new Ld(p,0,d.gameOpts.humanPlayers,r);let m=new Vd(d,s,l,a,r,h,n,()=>{console.error("Desync detected."),process.exit(1)},mp(this,np,"f"),void 0,c,!1);m.init();let f=new Hd(m);s.onRateChange.subscribe(e=>m.setRate(e)),d.onEnd.subscribe(()=>{process.stdout.write("Game ended.\n"),f.destroy()}),process.stdout.write("\nGame created. Use the following links to join:\n\n");for(g of e.agents.slice(1))process.stdout.write(`${e.clientUrl.replace(/\/$/,"")}/#/game/${o}/${encodeURIComponent(g.name)}\n`);process.stdout.write("\nWaiting for players to join...\n"),await new Promise((e,t)=>{s.onGameStart.subscribeOnce(()=>{s.onClose.unsubscribe(t),f.start(),e()}),s.onClose.subscribeOnce(t),s.sendLoadedPercent(100)}),process.stdout.write("Game started.\n");return s.onClose.subscribeOnce(()=>m.dispose()),new ip(t,d,p,h,n,m,f,()=>{f.destroy(),mp(this,op,"f").setLevel(Vs.OFF),s.close()})},pp=async function(e,t,i,r){if(!mp(this,hp,"f"))throw new Error("API is not initialized. Call init() first.");var s=new fi(Pt.vfs.openFile(i.mapName)),a=Pt.getIni(mp(this,sp,"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 X(n,o);h.loadTileData(Pt.getTileData());let l=class{static create(e,t,i,r,s,a,n,o,h,l,c,u){var d=i.clone().mergeWith(s).mergeWith(e);let p=new ur(d,c);var g=new Er(p,r,c);(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(o,p);let m=new ur(i),f=m.getMultiplayerCountries(),y=[...m.getMultiplayerColors().values()];var w=new Ch(e,t,p),s=new uh,d=h.getById(o.gameMode).type,r=new Wh,c=new Uh(r),i=new zh,e=new Hh(1),t=new ch(w.tiles,w.tileOccupation,w.bridges,e),h=new zc;let T=new Rc(s,w,p,g,a,n,o,d,r,i,c,e,t,h);(new dd).register(h,T,void 0),T.traits.add(new Kh),T.sellTrait=new el(T,p.general),T.traits.add(T.sellTrait),T.traits.add(new rl);let b=new al(p,u);T.traits.add(b),T.mapShroudTrait=new nl(w,c),T.traits.add(T.mapShroudTrait),T.mapRadiationTrait=new Vc(w),T.traits.add(T.mapRadiationTrait),T.traits.add(new Ic),T.traits.add(new gd),T.traits.add(new fd),o.cratesAppear&&(T.crateGeneratorTrait=new Td,T.traits.add(T.crateGeneratorTrait)),l||(T.stalemateDetectTrait=new vd,T.traits.add(T.stalemateDetectTrait));let v=new Yh(p,o,b.getAvailableObjects()),S=Od.factory(a,n),_=S.generateColors(o),k=S.generateCountries(o,m),O=S.generateStartLocations(o,w.startingLocations),I=[...o.humanPlayers,...o.aiPlayers].filter(Pa);return I.forEach(e=>{let t,i,r;if(Ah(e)?(t=e.name,i=!1):(t=T.getAiPlayerName(e),i=!0,r=e.difficulty),-3!==e.countryId){var s=k.get(e)??e.countryId,a=_.get(e)??e.colorId,e=O.get(e)??e.startPos;if(-2===s)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");s=f[s].name,s=Pr.factory(s,p),a=y[a];T.addPlayer(v.createCombatant(t,s,e,a,i,r))}else T.addPlayer(v.createObserver(t,p))}),T.addPlayer(v.createNeutral(p,"@@NEUTRAL@@")),T}}.create(s,h,Pt.getRules(),Pt.getArt(),a,e,t,i,mp(this,sp,"f"),!1,mp(this,ap,"f"),new Hh(!1));return mr.init({x:0,y:l.map.mapBounds.getFullSize().width*mr.getWorldTileSize()/2}),l.init(r?l.getPlayerByName(r):void 0),l.start(),l},gp=function(t){let e=mp(this,lp,"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=Pt.vfs.openFile(t.mapName),r=new ur(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:r.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}};const Tp=new wp})();var __webpack_exports__ActionsApi=__webpack_exports__.ActionsApi,__webpack_exports__AiRules=__webpack_exports__.AiRules,__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__BuildCat=__webpack_exports__.BuildCat,__webpack_exports__BuildStatus=__webpack_exports__.BuildStatus,__webpack_exports__CombatDamageRules=__webpack_exports__.CombatDamageRules,__webpack_exports__Country=__webpack_exports__.Country,__webpack_exports__CountryRules=__webpack_exports__.CountryRules,__webpack_exports__CrateRules=__webpack_exports__.CrateRules,__webpack_exports__CrewRules=__webpack_exports__.CrewRules,__webpack_exports__DMislRules=__webpack_exports__.DMislRules,__webpack_exports__FactoryStatus=__webpack_exports__.FactoryStatus,__webpack_exports__FactoryType=__webpack_exports__.FactoryType,__webpack_exports__GameApi=__webpack_exports__.GameApi,__webpack_exports__GameInstanceApi=__webpack_exports__.GameInstanceApi,__webpack_exports__GeneralRules=__webpack_exports__.GeneralRules,__webpack_exports__HoverRules=__webpack_exports__.HoverRules,__webpack_exports__InfDeathType=__webpack_exports__.InfDeathType,__webpack_exports__IniFile=__webpack_exports__.IniFile,__webpack_exports__IniSection=__webpack_exports__.IniSection,__webpack_exports__LandTargeting=__webpack_exports__.LandTargeting,__webpack_exports__LandType=__webpack_exports__.LandType,__webpack_exports__LightningStormRules=__webpack_exports__.LightningStormRules,__webpack_exports__LocomotorType=__webpack_exports__.LocomotorType,__webpack_exports__MapApi=__webpack_exports__.MapApi,__webpack_exports__MissileRules=__webpack_exports__.MissileRules,__webpack_exports__MovementZone=__webpack_exports__.MovementZone,__webpack_exports__NavalTargeting=__webpack_exports__.NavalTargeting,__webpack_exports__ObjectRules=__webpack_exports__.ObjectRules,__webpack_exports__ObjectType=__webpack_exports__.ObjectType,__webpack_exports__OrderType=__webpack_exports__.OrderType,__webpack_exports__OverlayRules=__webpack_exports__.OverlayRules,__webpack_exports__ParadropRules=__webpack_exports__.ParadropRules,__webpack_exports__PipColor=__webpack_exports__.PipColor,__webpack_exports__PrereqCategory=__webpack_exports__.PrereqCategory,__webpack_exports__PrismRules=__webpack_exports__.PrismRules,__webpack_exports__ProductionApi=__webpack_exports__.ProductionApi,__webpack_exports__ProjectileRules=__webpack_exports__.ProjectileRules,__webpack_exports__PublicApi=__webpack_exports__.PublicApi,__webpack_exports__QueueStatus=__webpack_exports__.QueueStatus,__webpack_exports__QueueType=__webpack_exports__.QueueType,__webpack_exports__RadarEventType=__webpack_exports__.RadarEventType,__webpack_exports__RadarRules=__webpack_exports__.RadarRules,__webpack_exports__RadiationRules=__webpack_exports__.RadiationRules,__webpack_exports__RepairRules=__webpack_exports__.RepairRules,__webpack_exports__RulesApi=__webpack_exports__.RulesApi,__webpack_exports__SideType=__webpack_exports__.SideType,__webpack_exports__SpeedType=__webpack_exports__.SpeedType,__webpack_exports__StanceType=__webpack_exports__.StanceType,__webpack_exports__SuperWeaponStatus=__webpack_exports__.SuperWeaponStatus,__webpack_exports__SuperWeaponType=__webpack_exports__.SuperWeaponType,__webpack_exports__TechnoRules=__webpack_exports__.TechnoRules,__webpack_exports__TerrainRules=__webpack_exports__.TerrainRules,__webpack_exports__TerrainType=__webpack_exports__.TerrainType,__webpack_exports__TheaterType=__webpack_exports__.TheaterType,__webpack_exports__ThreatRules=__webpack_exports__.ThreatRules,__webpack_exports__V3RocketRules=__webpack_exports__.V3RocketRules,__webpack_exports__VeteranAbility=__webpack_exports__.VeteranAbility,__webpack_exports__VeteranLevel=__webpack_exports__.VeteranLevel,__webpack_exports__VeteranRules=__webpack_exports__.VeteranRules,__webpack_exports__VhpScan=__webpack_exports__.VhpScan,__webpack_exports__WarheadRules=__webpack_exports__.WarheadRules,__webpack_exports__WeaponRules=__webpack_exports__.WeaponRules,__webpack_exports__WeaponType=__webpack_exports__.WeaponType,__webpack_exports__ZoneType=__webpack_exports__.ZoneType,__webpack_exports__cdapi=__webpack_exports__.cdapi;export{__webpack_exports__ActionsApi as ActionsApi,__webpack_exports__AiRules as AiRules,__webpack_exports__ApiEventType as ApiEventType,__webpack_exports__ArmorType as ArmorType,__webpack_exports__AttackState as AttackState,__webpack_exports__Bot as Bot,__webpack_exports__BuildCat as BuildCat,__webpack_exports__BuildStatus as BuildStatus,__webpack_exports__CombatDamageRules as CombatDamageRules,__webpack_exports__Country as Country,__webpack_exports__CountryRules as CountryRules,__webpack_exports__CrateRules as CrateRules,__webpack_exports__CrewRules as CrewRules,__webpack_exports__DMislRules as DMislRules,__webpack_exports__FactoryStatus as FactoryStatus,__webpack_exports__FactoryType as FactoryType,__webpack_exports__GameApi as GameApi,__webpack_exports__GameInstanceApi as GameInstanceApi,__webpack_exports__GeneralRules as GeneralRules,__webpack_exports__HoverRules as HoverRules,__webpack_exports__InfDeathType as InfDeathType,__webpack_exports__IniFile as IniFile,__webpack_exports__IniSection as IniSection,__webpack_exports__LandTargeting as LandTargeting,__webpack_exports__LandType as LandType,__webpack_exports__LightningStormRules as LightningStormRules,__webpack_exports__LocomotorType as LocomotorType,__webpack_exports__MapApi as MapApi,__webpack_exports__MissileRules as MissileRules,__webpack_exports__MovementZone as MovementZone,__webpack_exports__NavalTargeting as NavalTargeting,__webpack_exports__ObjectRules as ObjectRules,__webpack_exports__ObjectType as ObjectType,__webpack_exports__OrderType as OrderType,__webpack_exports__OverlayRules as OverlayRules,__webpack_exports__ParadropRules as ParadropRules,__webpack_exports__PipColor as PipColor,__webpack_exports__PrereqCategory as PrereqCategory,__webpack_exports__PrismRules as PrismRules,__webpack_exports__ProductionApi as ProductionApi,__webpack_exports__ProjectileRules as ProjectileRules,__webpack_exports__PublicApi as PublicApi,__webpack_exports__QueueStatus as QueueStatus,__webpack_exports__QueueType as QueueType,__webpack_exports__RadarEventType as RadarEventType,__webpack_exports__RadarRules as RadarRules,__webpack_exports__RadiationRules as RadiationRules,__webpack_exports__RepairRules as RepairRules,__webpack_exports__RulesApi as RulesApi,__webpack_exports__SideType as SideType,__webpack_exports__SpeedType as SpeedType,__webpack_exports__StanceType as StanceType,__webpack_exports__SuperWeaponStatus as SuperWeaponStatus,__webpack_exports__SuperWeaponType as SuperWeaponType,__webpack_exports__TechnoRules as TechnoRules,__webpack_exports__TerrainRules as TerrainRules,__webpack_exports__TerrainType as TerrainType,__webpack_exports__TheaterType as TheaterType,__webpack_exports__ThreatRules as ThreatRules,__webpack_exports__V3RocketRules as V3RocketRules,__webpack_exports__VeteranAbility as VeteranAbility,__webpack_exports__VeteranLevel as VeteranLevel,__webpack_exports__VeteranRules as VeteranRules,__webpack_exports__VhpScan as VhpScan,__webpack_exports__WarheadRules as WarheadRules,__webpack_exports__WeaponRules as WeaponRules,__webpack_exports__WeaponType as WeaponType,__webpack_exports__ZoneType as ZoneType,__webpack_exports__cdapi as cdapi};
1
+ 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:()=>r});const r=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],r=1;r<t.length;r++)for(e in t[r])e in i||!t[r].hasOwnProperty(e)||(i[e]=t[r][e]);return i}var r,o={VERSION:"1.4.1"},s={},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){r&&this.enabledFor(e)&&r(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){r=e},o.setLevel=function(e){for(var t in n.setLevel(e),s)s.hasOwnProperty(t)&&s[t].setLevel(e)},o.getLevel=function(){return n.getLevel()},o.get=function(e){return s[e]||(s[e]=new a(i({name:e},n.context)))},o.createDefaultHandler=function(s){(s=s||{}).formatter=s.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,r=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(r,[i+": "+((new Date).getTime()-n[i])+"ms"])):(t.level===o.WARN&&console.warn?r=console.warn:t.level===o.ERROR&&console.error?r=console.error:t.level===o.INFO&&console.info?r=console.info:t.level===o.DEBUG&&console.debug&&(r=console.debug),s.formatter(e,t),a(r,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,r,s;for(this.init_seed(19650218),i=1,r=0,s=this.N>t?this.N:t;s;s--){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[r]+r,this.mt[i]>>>=0,r++,++i>=this.N&&(this.mt[0]=this.mt[this.N-1],i=1),t<=r&&(r=0)}for(s=this.N-1;s;s--){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],r=0;r<i.length;++r)i[r].callback===t&&i.splice(r,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 r=0;r<i.length;++r){var s=i[r];s.callback.apply(s.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 r=E(e,t),s=o.hasOwnProperty(r);(s||b(e,t))&&(s||(o[r]=0),s="@"+ ++o[r],r=E(e+s,t+s));return new B(e,t,i,r)}:function(e,t,i){var r=E(e,t);return new B(e,t,i,r)},i=[],l=v,s=v,c=v,u=v,r={addNode:g,addLink:function(e,t,i){c();var r=m(e)||g(e),s=m(t)||g(t),i=h(e,t,i);a.push(i),C(r,i),e!==t&&C(s,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:k,forEachLinkedNode:function(e,t,i){var r=m(e);if(r&&r.links&&"function"==typeof t)return(i?function(e,t,i){for(var r=0;r<e.length;++r){var s=e[r];if(s.fromId===t&&i(n.get(s.toId),s))return!0}}:function(e,t,i){for(var r=0;r<e.length;++r){var s=e[r],a=s.fromId===t?s.toId:s.fromId;if(i(n.get(a),s))return!0}})(r.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(),k(function(e){f(e.id)}),u()},hasLink:b,hasNode:m,getLink:b};return O(r),function(){var e=r.on;r.on=function(){return r.beginUpdate=c=S,r.endUpdate=u=_,l=d,s=p,(r.on=e).apply(r,arguments)}}(),r;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,s(i,"update")):(i=new A(e,t),s(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 r=0;r<i.length;++r)T(i[r])}return n.delete(e),s(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),r=m(e.toId);return i&&0<=(t=I(e,i.links))&&i.links.splice(t,1),r&&0<=(t=I(e,r.links))&&r.links.splice(t,1),l(e,"remove"),u(),!0}function b(e,t){var i,r=m(e);if(!r||!r.links)return null;for(i=0;i<r.links.length;++i){var s=r.links[i];if(s.fromId===e&&s.toId===t)return s}return null}function v(){}function S(){t+=1}function _(){0===--t&&0<i.length&&(r.fire("changed",i),i.length=0)}function k(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 O=i(367);function I(e,t){if(!t)return-1;if(t.indexOf)return t.indexOf(e);for(var i=t.length,r=0;r<i;r+=1)if(t[r]===e)return r;return-1}function A(e,t){this.id=e,this.links=null,this.data=t}function C(e,t){e.links?e.links.push(t):e.links=[t]}function B(e,t,i,r){this.fromId=e,this.toId=t,this.data=i,this.id=r}function E(e,t){return e.toString()+"👉 "+t.toString()}},603:e=>{function r(e,t){if(!(this instanceof r))return new r(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||s,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 s(){}function a(e,t){return e-t}(e.exports=r).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,r=this.setNodeId,s=t[e];0<e;){var a=e-1>>1,n=t[a];if(0<=i(s,n))break;r(t[e]=n,e),e=a}r(t[e]=s,e)},_down:function(e){for(var t=this.data,i=this.compare,r=this.length>>1,s=t[e],a=this.setNodeId;e<r;){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,s))break;a(t[e]=h,e),e=n}a(t[e]=s,e)}}},142:(e,t,i)=>{e.exports=function(y,e){var w=(e=e||{}).oriented,T=e.bestEffort,b=e.heuristic;b=b||k.heuristic;var v=e.distance;v=v||k.distance;var S=r();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===O){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,r=new _({compare:k.compareFScore,setNodeId:k.setHeapIndex}),s=new _({compare:k.compareFScore,setNodeId:k.setHeapIndex}),t=S.createNewState(a);o.set(e,t),t.fScore=b(a,n),t.distanceToSource=0,r.push(t),t.open=O;e=S.createNewState(n);e.fScore=b(n,a),e.distanceToSource=0,s.push(e),e.open=I;var h,l,c=Number.POSITIVE_INFINITY,u=r,d=O,p=t;for(;0<r.length&&(0<s.length||T);){var g=(u=r.length<s.length||!s.length&&T?(d=O,r):(d=I,s)).pop();if(g.closed=!0,!(g.distanceToSource>c)&&(y.forEachLinkedNode(g.node.id,i),h&&l))return m(h,l)}return T?m(p):A;function m(e,t){for(var i=[],r=e;r;)i.push(r.node),r=r.parent;for(var s=t;s;)i.unshift(s.node),s=s.parent;return i}function f(e,t,i){var r,s=o.get(e.id);s||(s=S.createNewState(e),o.set(e.id,s)),s.closed||((e=(e=s).open)&&e!==d?(r=s.distanceToSource+i.distanceToSource)<c&&(h=s,l=i,c=r):(e=i.distanceToSource+v(s.node,i.node,t))>=s.distanceToSource||(r=d===O?n:a,t=e+b(s.node,r,s),c<=t||(s.fScore=t,0===s.open&&(u.push(s),u.updateItem(s.heapIndex),s.open=d),s.parent=i,s.distanceToSource=e,r===n&&t-e<p.fScore-p.distanceToSource&&(p=s))))}}}};var _=i(603),r=i(573),s=i(884),k=i(8),O=1,I=2,A=k.NO_PATH;e.exports.l2=s.l2,e.exports.l1=s.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=r();return{find:function(e,t){var i=c.getNode(e);if(!i)throw new Error("fromId is not defined in this graph: "+e);var r=c.getNode(t);if(!r)throw new Error("toId is not defined in this graph: "+t);f.reset();var s,a=new Map,n=new y({compare:w.compareFScore,setNodeId:w.setHeapIndex}),t=f.createNewState(i);a.set(e,t),t.fScore=g(i,r),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}(s=n.pop(),r))return b(s);if(p<++h)break;s.closed=!0,c.forEachLinkedNode(s.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=s.distanceToSource+m(s.node,e,t))>=i.distanceToSource||(i.parent=s,i.distanceToSource=t,i.fScore=t+g(i.node,r,i),i.fScore-i.distanceToSource<o.fScore-o.distanceToSource&&(o=i),n.updateItem(i.heapIndex)))}}}};var y=i(603),r=i(573),s=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=s.l2,e.exports.l1=s.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 s(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,r=[];return{createNewState:function(e){var t=r[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 s(e),r[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||k.heuristic;var v=e.distance;v=v||k.distance;var S=s();return{find:function(e,t){var r=y.getNode(e);if(!r)throw new Error("fromId is not defined in this graph: "+e);var s=y.getNode(t);if(!s)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 _({compare:k.compareF1Score,setNodeId:k.setH1}),l=new _({compare:k.compareF2Score,setNodeId:k.setH2}),c=Number.POSITIVE_INFINITY,u=S.createNewState(r);o.set(e,u),u.g1=0;var d=b(r,s);u.f1=d,h.push(u);u=S.createNewState(s);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(r,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,s)<c&&y.forEachLinkedNode(p.node.id,n),0<l.length&&(g=l.peek().f2)),!T||!a););return function(e){if(!e)return O;var t=[e.node],i=e.p1;for(;i;)t.push(i.node),i=i.p1;var r=e.p2;for(;r;)t.unshift(r.node),r=r.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,s),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(r,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 _=i(603),r=i(884),k=i(8),s=i(808),O=k.NO_PATH;e.exports.l2=r.l2,e.exports.l1=r.l1},808:e=>{function s(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,r=[];return{createNewState:function(e){var t=r[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 s(e),r[i]=t);return i++,t},reset:function(){i=0}}}},45:(e,t,i)=>{e.exports={aStar:i(118),aGreedy:i(142),nba:i(377)}},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__,{ActionsApi:()=>tc,AiRules:()=>nr,ApiEventType:()=>ic,ArmorType:()=>ri,AttackState:()=>no,Bot:()=>Wc,BuildCat:()=>$i,BuildStatus:()=>No,CombatDamageRules:()=>sr,Country:()=>Sn,CountryRules:()=>vi,CrateRules:()=>cr,CrewRules:()=>Ci,DMislRules:()=>Di,FactoryStatus:()=>Gn,FactoryType:()=>qi,GameApi:()=>Bc,GameInstanceApi:()=>im,GeneralRules:()=>Fi,HoverRules:()=>Mi,InfDeathType:()=>Jt,IniFile:()=>c,IniSection:()=>h,LandTargeting:()=>Da,LandType:()=>Yt,LightningStormRules:()=>Pi,LocomotorType:()=>ti,MapApi:()=>wc,MissileRules:()=>Ni,MovementZone:()=>ii,NavalTargeting:()=>Ma,ObjectRules:()=>Si,ObjectType:()=>Ct,OrderType:()=>Vo,OverlayRules:()=>Ji,ParadropRules:()=>xi,PipColor:()=>ei,PrereqCategory:()=>Qt,PrismRules:()=>Bi,ProductionApi:()=>jc,ProjectileRules:()=>zi,PublicApi:()=>wm,QueueStatus:()=>wn,QueueType:()=>yn,RadarEventType:()=>Zt,RadarRules:()=>Oi,RadiationRules:()=>hr,RepairRules:()=>Ii,RulesApi:()=>Oc,SideType:()=>qt,SpeedType:()=>Kt,StanceType:()=>Br,SuperWeaponStatus:()=>Or,SuperWeaponType:()=>Qi,Tag:()=>Tm,TagRepeatType:()=>Ht,TechnoRules:()=>Ki,TerrainRules:()=>er,TerrainType:()=>Xt,TheaterType:()=>I,ThreatRules:()=>Ei,V3RocketRules:()=>Ri,VeteranAbility:()=>ai,VeteranLevel:()=>Xs,VeteranRules:()=>Ai,VhpScan:()=>ni,WarheadRules:()=>Vi,WeaponRules:()=>_i,WeaponType:()=>si,ZoneType:()=>dr,cdapi:()=>bm});__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 r=this.parseNumber(i);return void 0===r?(console.warn(`Invalid value for key ${e}. "${i}" is not a valid number or percentage string.`),t):r}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 r=this.getString(e).trim();return r=r.replace(/\,$/,""),r?r.split(t):i}getNumberArray(e,t=/\,\s*/,i=[]){let r=this.getString(e).trim();if(!r)return i;let s=[];for(var a of r.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;s.push(n)}return s}getFixedArray(e,t=/\,\s*/,i=[]){return this.getNumberArray(e,t,i).map(e=>this.toFixedPointPrecision(e))}getEnum(e,t,i,r=!1){let s=this.getString(e).trim();if(!s)return i;if(r){let e=Object.getOwnPropertyNames(t);r=e.find(e=>e.toLowerCase()===s.toLowerCase());return r?t[r]:i}return t.hasOwnProperty(s)?t[s]:i}getEnumArray(e,r,t=/\,\s*/,s=[],a=!1){let n=this.getString(e).trim();if(!n)return s;let o=[];for(let i of n.split(t)){if(!i)return s;let t=!1;if(a){let e=Object.getOwnPropertyNames(r);var h=e.find(e=>e.toLowerCase()===i.toLowerCase());h&&(o.push(r[h]),t=!0)}else r.hasOwnProperty(i)&&(o.push(r[i]),t=!0);if(!t)return console.warn(`Invalid value "${i}" for key "${e}".`),s}return o}getHighestNumericIndex(){let i=0,r;return this.entries.forEach((e,t)=>{r=parseInt(t,10),r>i&&(i=r)}),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={},r=o,s,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 s=this.unsafe(t[1]),void(r=o[s]=o[s]||{});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),r[e]?Array.isArray(r[e])||(r[e]=[r[e]]):r[e]=[]),Array.isArray(r[e])?r[e].push(t):r[e]=t}}}),Object.keys(o).filter((e,t,i)=>{if(!o[e]||"object"!=typeof o[e]||Array.isArray(o[e]))return!1;let r=this.dotSplit(e),s=o,a=r.pop();var n=a.replace(/\\\./g,".");return r.forEach(function(e,t,i){s[e]&&"object"==typeof s[e]||(s[e]={}),s=s[e]}),(s!==o||n!==a)&&(s[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(s){if(s=(s||"").trim(),this.isQuoted(s))return s=s.substr(1,s.length-2);{let i=!1,r="";for(let e=0,t=s.length;e<t;e++){var a=s.charAt(e);if(i)-1!=="\\;#".indexOf(a)?r+=a:r+="\\"+a,i=!1;else{if(-1!==";#".indexOf(a))break;"\\"===a?i=!0:r+=a}}return i&&(r+="\\"),r=r.trim(),r}}}class w{constructor(e,t,i=w.LITTLE_ENDIAN){this.endianness=i,this.position=0,this._dynamicSize=!0,this._byteLength=0,this.failurePosition=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||1)}get dynamicSize(){return this._dynamicSize}set dynamicSize(e){e||this._trimAlloc(),this._dynamicSize=e}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){if(this._trimAlloc(),!this._buffer)throw new Error;return 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._buffer&&(this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength)}get dataView(){if(!this._dataView)throw new Error;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=w.BIG_ENDIAN,this}_realloc(t){if(this._dynamicSize){var i=this._byteOffset+this.position+t;if(!this._buffer)throw new Error;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 r=new ArrayBuffer(e),t=new Uint8Array(this._buffer);const s=new Uint8Array(r,0,t.length);s.set(t),this.buffer=r,this._byteLength=i}}}_trimAlloc(){if(!this._buffer)throw new Error;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){if(this._realloc(4*e),!this._buffer)throw new Error;var i=new Int32Array(this._buffer,this.byteOffset+this.position,e);return w.arrayToNative(i,void 0===t?this.endianness:t),this.position+=4*e,i}mapInt16Array(e,t){if(this._realloc(2*e),!this._buffer)throw new Error;var i=new Int16Array(this._buffer,this.byteOffset+this.position,e);return w.arrayToNative(i,void 0===t?this.endianness:t),this.position+=2*e,i}mapInt8Array(e){if(this._realloc(e),!this._buffer)throw new Error;var t=new Int8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e,t}mapUint32Array(e,t){if(this._realloc(4*e),!this._buffer)throw new Error;var i=new Uint32Array(this._buffer,this.byteOffset+this.position,e);return w.arrayToNative(i,void 0===t?this.endianness:t),this.position+=4*e,i}mapUint16Array(e,t){if(this._realloc(2*e),!this._buffer)throw new Error;var i=new Uint16Array(this._buffer,this.byteOffset+this.position,e);return w.arrayToNative(i,void 0===t?this.endianness:t),this.position+=2*e,i}mapUint8Array(e){if(this._realloc(e),!this._buffer)throw new Error;var t=new Uint8Array(this._buffer,this.byteOffset+this.position,e);return this.position+=e,t}mapFloat64Array(e,t){if(this._realloc(8*e),!this._buffer)throw new Error;var i=new Float64Array(this._buffer,this.byteOffset+this.position,e);return w.arrayToNative(i,void 0===t?this.endianness:t),this.position+=8*e,i}mapFloat32Array(e,t){if(this._realloc(4*e),!this._buffer)throw new Error;var i=new Float32Array(this._buffer,this.byteOffset+this.position,e);return w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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 w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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 w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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 w.memcpy(i.buffer,0,this.buffer,this.byteOffset+this.position,e*i.BYTES_PER_ELEMENT),w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._buffer)throw new Error;w.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){if(!this._dataView)throw new Error;e=this._dataView.getInt32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readInt16(e){if(!this._dataView)throw new Error;e=this._dataView.getInt16(this.position,void 0===e?this.endianness:e);return this.position+=2,e}readInt8(){if(!this._dataView)throw new Error;var e=this._dataView.getInt8(this.position);return this.position+=1,e}readUint32(e){if(!this._dataView)throw new Error;e=this._dataView.getUint32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readUint16(e){if(!this._dataView)throw new Error;e=this._dataView.getUint16(this.position,void 0===e?this.endianness:e);return this.position+=2,e}readUint8(){if(!this._dataView)throw new Error;var e=this._dataView.getUint8(this.position);return this.position+=1,e}readFloat32(e){if(!this._dataView)throw new Error;e=this._dataView.getFloat32(this.position,void 0===e?this.endianness:e);return this.position+=4,e}readFloat64(e){if(!this._dataView)throw new Error;e=this._dataView.getFloat64(this.position,void 0===e?this.endianness:e);return this.position+=8,e}writeInt32(e,t){if(this._realloc(4),!this._dataView)throw new Error;return this._dataView.setInt32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeInt16(e,t){if(this._realloc(2),!this._dataView)throw new Error;return this._dataView.setInt16(this.position,e,void 0===t?this.endianness:t),this.position+=2,this}writeInt8(e){if(this._realloc(1),!this._dataView)throw new Error;return this._dataView.setInt8(this.position,e),this.position+=1,this}writeUint32(e,t){if(this._realloc(4),!this._dataView)throw new Error;return this._dataView.setUint32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeUint16(e,t){if(this._realloc(2),!this._dataView)throw new Error;return this._dataView.setUint16(this.position,e,void 0===t?this.endianness:t),this.position+=2,this}writeUint8(e){if(this._realloc(1),!this._dataView)throw new Error;return this._dataView.setUint8(this.position,e),this.position+=1,this}writeFloat32(e,t){if(this._realloc(4),!this._dataView)throw new Error;return this._dataView.setFloat32(this.position,e,void 0===t?this.endianness:t),this.position+=4,this}writeFloat64(e,t){if(this._realloc(8),!this._dataView)throw new Error;return this._dataView.setFloat64(this.position,e,void 0===t?this.endianness:t),this.position+=8,this}static memcpy(e,t,i,r,s){const a=new Uint8Array(e,t,s);s=new Uint8Array(i,r,s);a.set(s)}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(r){const s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);for(let i=0;i<r.byteLength;i+=r.BYTES_PER_ELEMENT)for(let e=i+r.BYTES_PER_ELEMENT-1,t=i;e>t;e--,t++){var a=s[t];s[t]=s[e],s[e]=a}return r}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("")}readStruct(t){const i={};var r,s=this.position;for(let e=0;e<t.length;e+=2){if(r=t[e+1],void 0===(r=this.readType(r,i)))return 0===this.failurePosition&&(this.failurePosition=this.position),void(this.position=s);i[t[e]]=r}return i}readUCS2String(e,t){return w.createStringFromArray(this.readUint16Array(e,t))}writeUCS2String(e,t,i){void 0===i&&(i=e.length);let r=0;for(;r<e.length&&r<i;r++)this.writeUint16(e.charCodeAt(r),t);for(;r<i;r++)this.writeUint16(0);return this}readString(e,t){return void 0===t||"ASCII"===t?w.createStringFromArray(this.mapUint8Array(void 0===e?this.byteLength-this.position:e)):(new TextDecoder).decode(this.mapUint8Array(e))}writeString(t,e,i){if(void 0===e||"ASCII"===e)if(void 0!==i){let e;var r=Math.min(t.length,i);for(e=0;e<r;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;if(!this._buffer)throw new Error;var i=new Uint8Array(this._buffer,this._byteOffset+this.position);let r=t;void 0!==e&&(r=Math.min(e,t));let s=0;for(;s<r&&0!==i[s];s++);var a=w.createStringFromArray(this.mapUint8Array(s));return void 0!==e?this.position+=r-s:s!==t&&(this.position+=1),a}writeCString(t,i){if(void 0!==i){let e;var r=Math.min(t.length,i);for(e=0;e<r;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}readType(e,i){if("function"==typeof e)return e(this,i);if(!("object"!=typeof e||e instanceof Array))return e.get(this,i);if(e instanceof Array&&3!==e.length)return this.readStruct(e);let r=void 0,t=void 0,s="ASCII";var a,n=this.position;switch("string"==typeof e&&/:/.test(e)&&(e=(a=e.split(":"))[0],a=a[1],t=parseInt(void 0!==i[a]?i[a]:a,10)),"string"==typeof e&&/,/.test(e)&&(e=(a=e.split(","))[0],s=a[1]),t=t||0,e){case"uint8":r=this.readUint8();break;case"int8":r=this.readInt8();break;case"uint16":r=this.readUint16(this.endianness);break;case"int16":r=this.readInt16(this.endianness);break;case"uint32":r=this.readUint32(this.endianness);break;case"int32":r=this.readInt32(this.endianness);break;case"float32":r=this.readFloat32(this.endianness);break;case"float64":r=this.readFloat64(this.endianness);break;case"uint16be":r=this.readUint16(w.BIG_ENDIAN);break;case"int16be":r=this.readInt16(w.BIG_ENDIAN);break;case"uint32be":r=this.readUint32(w.BIG_ENDIAN);break;case"int32be":r=this.readInt32(w.BIG_ENDIAN);break;case"float32be":r=this.readFloat32(w.BIG_ENDIAN);break;case"float64be":r=this.readFloat64(w.BIG_ENDIAN);break;case"uint16le":r=this.readUint16(w.LITTLE_ENDIAN);break;case"int16le":r=this.readInt16(w.LITTLE_ENDIAN);break;case"uint32le":r=this.readUint32(w.LITTLE_ENDIAN);break;case"int32le":r=this.readInt32(w.LITTLE_ENDIAN);break;case"float32le":r=this.readFloat32(w.LITTLE_ENDIAN);break;case"float64le":r=this.readFloat64(w.LITTLE_ENDIAN);break;case"cstring":r=this.readCString(t);break;case"string":r=this.readString(t,s);break;case"u16string":r=this.readUCS2String(t,this.endianness);break;case"u16stringle":r=this.readUCS2String(t,w.LITTLE_ENDIAN);break;case"u16stringbe":r=this.readUCS2String(t,w.BIG_ENDIAN);break;default:if(3===e.length){const d=e[1],p=e[2];let t=0;if(t="function"==typeof p?p(i,this,e):"string"==typeof p&&void 0!==i[p]?parseInt(i[p],10):parseInt(p,10),"string"==typeof d){var o=d.replace(/(le|be)$/,"");let e=void 0;switch(/le$/.test(d)?e=w.LITTLE_ENDIAN:/be$/.test(d)&&(e=w.BIG_ENDIAN),"*"===p&&(t=void 0),t=t||0,o){case"uint8":r=this.readUint8Array(t);break;case"uint16":r=this.readUint16Array(t,e);break;case"uint32":r=this.readUint32Array(t,e);break;case"int8":r=this.readInt8Array(t);break;case"int16":r=this.readInt16Array(t,e);break;case"int32":r=this.readInt32Array(t,e);break;case"float32":r=this.readFloat32Array(t,e);break;case"float64":r=this.readFloat64Array(t,e);break;case"cstring":case"utf16string":case"string":if(void 0===t)for(r=[];!this.isEof();){var h=this.readType(d,i);if(void 0===h)break;r.push(h)}else{r=new Array(t);for(let e=0;e<t;e++)r[e]=this.readType(d,i)}}}else if("*"===p)for(r=[];;){var l=this.position;try{var c=this.readType(d,i);if(void 0===c){this.position=l;break}r.push(c)}catch(e){this.position=l;break}}else{t=t||0,r=new Array(t);for(let e=0;e<t;e++){var u=this.readType(d,i);if(void 0===u)return;r[e]=u}}break}}return void 0!==t&&(this.position=n+t),r}writeStruct(t,i,e=!1){e&&(t=w.defWriteStruct(t,i));for(let e=0;e<t.length;e+=2){var r=t[e+1];this.writeType(r,i[t[e]],i)}return this}static defWriteStruct(i,r){const s=[];for(let e=i.length-2;0<=e;e-=2){let t=i[e+1];var a=i[e];if("string"==typeof t&&/,.+:[A-Za-z_]/.test(t)){let e=t.split(":");var n=e[1];e=e[0].split(","),t=e[0];const o=(new TextEncoder).encode(r[a]);r[n]=o.length,s.push(e=>e.writeUint8Array(o))}else s.push(t);s.push(a)}return s.reverse()}writeType(e,t,i){if("function"==typeof e)return e(this,t,i),this;if("object"==typeof e&&!(e instanceof Array))return e.set(this,t,i),this;let r=void 0,s="ASCII";var a,n=this.position;switch("string"==typeof e&&/:/.test(e)&&(e=(a=e.split(":"))[0],a=a[1],r=parseInt(void 0!==i[a]?i[a]:a,10)),"string"==typeof e&&/,/.test(e)&&(e=(a=e.split(","))[0],s=a[1]),e){case"uint8":this.writeUint8(t);break;case"int8":this.writeInt8(t);break;case"uint16":this.writeUint16(t,this.endianness);break;case"int16":this.writeInt16(t,this.endianness);break;case"uint32":this.writeUint32(t,this.endianness);break;case"int32":this.writeInt32(t,this.endianness);break;case"float32":this.writeFloat32(t,this.endianness);break;case"float64":this.writeFloat64(t,this.endianness);break;case"uint16be":this.writeUint16(t,w.BIG_ENDIAN);break;case"int16be":this.writeInt16(t,w.BIG_ENDIAN);break;case"uint32be":this.writeUint32(t,w.BIG_ENDIAN);break;case"int32be":this.writeInt32(t,w.BIG_ENDIAN);break;case"float32be":this.writeFloat32(t,w.BIG_ENDIAN);break;case"float64be":this.writeFloat64(t,w.BIG_ENDIAN);break;case"uint16le":this.writeUint16(t,w.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(t,w.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(t,w.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(t,w.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(t,w.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(t,w.LITTLE_ENDIAN);break;case"cstring":this.writeCString(t,r);break;case"string":this.writeString(t,s,r);break;case"u16string":this.writeUCS2String(t,this.endianness,r);break;case"u16stringle":this.writeUCS2String(t,w.LITTLE_ENDIAN,r);break;case"u16stringbe":this.writeUCS2String(t,w.BIG_ENDIAN,r);break;default:if(3===e.length){var o=e[1];for(const h of t)this.writeType(o,h,i);break}this.writeStruct(e,t)}return void 0!==r&&(this.position=n,this._realloc(r),this.position=n+r),this}}w.BIG_ENDIAN=!1,w.LITTLE_ENDIAN=!0,w.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 w(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 w(e);return i._trimAlloc=()=>{},new this(i,t)}static factory(e,t,i=0,r=e.byteLength){r=new DataView(e.buffer,e.byteOffset+i,r);const s=new w(r);return s._trimAlloc=()=>{},new this(s,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,r,s;var a;for(t in e)if(e.hasOwnProperty(t)){for(s in i=e[t],r=new h(t),i)i.hasOwnProperty(s)&&(a=i[s],r.set(s,a));this.sections.set(t,r)}}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 r=this.getOrCreateSection(t);if(this.isValueArray(t)){let i=r.getHighestNumericIndex()+1;e.entries.forEach((e,t)=>{r.set((i++).toString(),e)})}else e.entries.forEach((e,t)=>{r.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 r=new Uint8Array(i*e),s=0;for(let t=0;t<this.height&&!(t>=e);t++)for(let e=0;e<this.width;e++)e>=i||(r[s++]=this.imageData[t*this.width+e]);return t.imageData=r,t.x=this.x,t.y=this.y,t}}class r{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 s=e.stream;if(0===s.readInt16()){this.width=s.readInt16(),this.height=s.readInt16(),this.numImages=s.readInt16();let r=[];for(let e=0;e<this.numImages;++e)r.push(this.readFrameHeader(s));this.images=[];for(let i=0;i<this.numImages;++i){var{compressionType:a,imageDataStartOffset:n,x:o,y:h,width:l,height:c}=r[i];let e=i<this.numImages-1?r[i+1].imageDataStartOffset:s.byteLength;e<n&&(e=s.byteLength);var u=e-n;s.seek(n);u=this.readImageData(s,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(),r=e.readInt16(),s=e.readInt16(),a=e.readUint8();return e.readUint8(),e.readUint8(),e.readUint8(),e.readInt32(),e.readInt32(),{x:t,y:i,width:r,height:s,compressionType:a,imageDataStartOffset:e.readInt32()}}readImageData(r,e,s,t,i){var a=e*s;if(t<=1){var n=new Uint8Array(r.buffer,r.byteOffset+r.position,a);return r.position+=a,n}if(2===t){let t=0,i=new Uint8Array(a);for(let e=0;e<s;++e){var o=r.readUint16()-2;i.set(new Uint8Array(r.buffer,r.byteOffset+r.position,o),t),r.position+=o,t+=o}return i}if(3!==t)return new Uint8Array;t=new Uint8Array(r.buffer,r.byteOffset+r.position,i);return r.position+=i,class{static decode(r,s,t){let a=new Uint8Array(s*t),n=0,o=0;for(let e=0;e<t;e++){let t=(r[n+1]<<8|r[n])-2;n+=2;let i=0;for(;0<t--;){let e=r[n++];if(0!==e)i++,a[o++]=e;else for(t--,e=r[n++],i+e>s&&(e=s-i&255),i+=e;0!=e--;)a[o++]=0}}return a}}.decode(t,e,s)}getImage(e){if(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 r;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 s=__webpack_require__(949).Vector3;const u=[new s(.54946297,-183e-6,-.835518),new s(.00014400001,.54940403,-.83555698),new s(-.54940403,-68000001e-12,-.83555698),new s(106e-6,-.54946297,-.835518),new s(.94900799,.00031599999,-.31525001),new s(-186e-6,.94899702,-.31528401),new s(-.94899702,.00031800001,-.31528401),new s(-447e-6,-.94900799,-.31525001),new s(.95084399,-279e-6,.30967101),new s(202e-6,.95084798,.30965701),new s(-.95084798,-70000002e-12,.30965701),new s(147e-6,-.95084399,.30967101),new s(.55237001,-11e-6,.83359897),new s(19999999e-12,.55238003,.833592),new s(-.55238003,57000001e-12,.83359301),new s(-66000001e-12,-.55237001,.83359897)],p=[new s(.67121398,.19849201,-.714194),new s(.26964301,.58439398,-.76536),new s(-.040546,.096988,-.99445897),new s(-.57242799,-.091913998,-.81478697),new s(-.17140099,-.57270998,-.80163902),new s(.36255699,-.30299899,-.88133103),new s(.81034702,-.34897199,-.470698),new s(.103962,.93867201,-.328767),new s(-.324047,.58766901,-.74137598),new s(-.80086499,.34046099,-.49264699),new s(-.66549802,-.59014702,-.45698899),new s(.314767,-.803002,-.506073),new s(.97262901,.151076,-.17655),new s(.680291,.68423599,-.26272699),new s(-.52007902,.82777703,-.210483),new s(-.96164399,-.179001,-.207847),new s(-.262714,-.937451,-.22840101),new s(.219707,-.97130102,.091124997),new s(.92380798,-.229975,.30608699),new s(-.082488999,.97065997,.225866),new s(-.59179801,.69678998,.40528899),new s(-.92529601,.36660099,.097111002),new s(-.705051,-.68777502,.172828),new s(.7324,-.68036699,-.026304999),new s(.85516202,.37458199,.358311),new s(.47300601,.83648002,.276705),new s(-.097617,.65411198,.750072),new s(-.90412402,-.153725,.39865801),new s(-.211916,-.85808998,.46773201),new s(.50022697,-.67440802,.543091),new s(.584539,-.110249,.80384099),new s(.43737301,.45464399,.77588898),new s(-.042440999,.083318003,.995619),new s(-.59625101,.22013199,.77202803),new s(-.506455,-.39697701,.76544899),new s(.070569001,-.47847399,.87526202)],g=[new s(.45651099,-.073968001,-.88663799),new s(.50769401,.38511699,-.77067),new s(.095431998,.22666401,-.96928602),new s(-.35876599,.54318798,-.75910097),new s(-.361276,.13299499,-.92292601),new s(-.48311701,-.32406601,-.813375),new s(-.018073,-.197559,-.980124),new s(.3211,-.501477,-.80337799),new s(.79949099,.069615997,-.59662998),new s(.390971,.77130598,-.50222403),new s(.080782004,.61448997,-.784778),new s(-.73275,.41143101,-.54203498),new s(-.73525399,.0091019999,-.67773098),new s(-.80249399,-.39490801,-.44727099),new s(-.13413,-.58915502,-.79680902),new s(.71955299,-.37622699,-.58369303),new s(.96687502,.173593,-.187132),new s(.760831,.51910597,-.38944301),new s(-.114642,.87551898,-.46938601),new s(-.53236699,.76885903,-.354177),new s(-.96226698,.024977,-.27095801),new s(-.46738699,-.721986,-.51018202),new s(.058449998,-.85235399,-.51968902),new s(.49823299,-.74374002,-.44566301),new s(.93915099,-.27024499,-.212044),new s(.58393198,.80944198,-.061857),new s(.183797,.97322798,-.138007),new s(-.88435501,.45221901,-.115822),new s(-.943178,-.33206701,.012138),new s(-.69844002,-.70656699,-.113772),new s(-.228411,-.95470601,-.190694),new s(.73156399,-.675861,-.089588001),new s(.96925098,.046804,.24158201),new s(.85564703,.50347698,.119916),new s(-.25115299,.96794701,-80999998e-12),new s(-.64779502,.75674897,.087711997),new s(-.96916401,.14519399,.1991),new s(-.41479301,-.88896698,.194126),new s(.25077501,-.961178,-.115109),new s(.47862899,-.84259301,.246883),new s(.89004397,-.39614201,.225595),new s(.52405101,.76235998,.37970701),new s(.11962,.94548202,.30291),new s(-.76085001,.49007499,.42536199),new s(-.86978501,-.20215,.450122),new s(-.70946699,-.60242403,.36570701),new s(.019308999,-.95887101,.28318599),new s(.626113,-.564677,.53770101),new s(.769943,-.126663,.62541503),new s(.76419097,.35070199,.54131401),new s(-.001878,.74136698,.67109799),new s(-.37088001,.81836802,.43900099),new s(-.71390897,.12865201,.68831801),new s(-.295165,-.73866397,.60601401),new s(.186195,-.73836899,.648184),new s(.387523,-.35878301,.84917599),new s(.481022,.124846,.86777401),new s(.391808,.54505599,.741216),new s(-.0035359999,.36559799,.93076599),new s(-.42049801,.484961,.76680797),new s(-.35490301,.019470001,.93470001),new s(-.54783702,-.35920799,.75554299),new s(-.106662,-.445115,.88909799),new s(.086796001,-.059307002,.99445897)],m=[new s(.52657801,-.35962099,-.77031702),new s(.150482,.43598399,.88728398),new s(.414195,.73825502,-.53237402),new s(.075152002,.91624898,-.393498),new s(-.316149,.93073601,-.18379299),new s(-.77381903,.62333399,-.11251),new s(-.90084201,.42853701,-.069568001),new s(-.99894202,-.010971,.044665001),new s(-.979761,-.15767001,-.123324),new s(-.91127402,-.362371,-.19562),new s(-.62406898,-.72094101,-.301301),new s(-.310173,-.80934501,-.498752),new s(.146613,-.81581903,-.55941403),new s(-.71651602,-.69435602,-.066887997),new s(.50397199,-.114202,-.85613698),new s(.45549101,.87262702,-.176211),new s(-.00501,-.114373,-.99342501),new s(-.104675,-.327701,-.93896502),new s(.56041199,.75258899,-.34575599),new s(-.060575999,.82162797,-.566796),new s(-.30234101,.79700702,-.522847),new s(-.671543,.67074001,-.314863),new s(-.77840102,-.12835699,.61450499),new s(-.92404997,.278382,-.261985),new s(-.69977301,-.55049098,-.45527801),new s(-.56824797,-.51718903,-.64000797),new s(.054097999,-.93286401,-.356143),new s(.75838202,.57289302,-.31088799),new s(.0036200001,.30502599,-.95233703),new s(-.060849998,-.98688602,-.14951099),new s(.63523,.045478001,-.77098298),new s(.52170497,.241309,-.81828701),new s(.26940399,.63542497,-.72364098),new s(.045676,.67275399,-.738455),new s(-.180511,.67465699,-.71571898),new s(-.397131,.63664001,-.66104198),new s(-.55200398,.47251499,-.687038),new s(-.77217001,.08309,-.62996),new s(-.669819,-.119533,-.73284),new s(-.54045498,-.31844401,-.77878201),new s(-.38613501,-.522789,-.75999397),new s(-.261466,-.68856698,-.676395),new s(-.019412,-.69610298,-.71767998),new s(.30356899,-.48184401,-.82199299),new s(.68193901,-.19512901,-.70490003),new s(-.24488901,-.116562,-.96251899),new s(.80075902,-.022979001,-.59854603),new s(-.37027499,.095583998,-.92399102),new s(-.33067101,-.32657799,-.88543999),new s(-.16322,-.52757901,-.83367902),new s(.12639,-.313146,-.941257),new s(.34954801,-.27222601,-.89649802),new s(.23991799,-.085825004,-.96699202),new s(.390845,.081537001,-.91683799),new s(.25526699,.26869699,-.92878503),new s(.146245,.48043799,-.86474901),new s(-.32601601,.47845599,-.81534898),new s(-.46968201,-.112519,-.87563598),new s(.81844002,-.25852001,-.51315099),new s(-.474318,.292238,-.83043301),new s(.778943,.39584199,-.48637101),new s(.62409401,.39377299,-.67487001),new s(.74088597,.203834,-.63995302),new s(.48021701,.565768,-.67029703),new s(.38093001,.42453501,-.82137799),new s(-.093422003,.50112402,-.86031801),new s(-.236485,.29619801,-.92538702),new s(-.131531,.093959004,-.98684901),new s(-.82356203,.29577699,-.48400599),new s(.61106598,-.624304,-.486664),new s(.069495998,-.52033001,-.85113299),new s(.226522,-.66487902,-.711775),new s(.47130799,-.56890398,-.67395699),new s(.38842499,-.74262398,-.54556),new s(.78367501,-.48072901,-.39338499),new s(.962394,.135676,-.235349),new s(.876607,.172034,-.449406),new s(.63340503,.58979303,-.50094098),new s(.182276,.80065799,-.57072097),new s(.177003,.76413399,.62029701),new s(-.544016,.675515,-.49772099),new s(-.67929697,.28646699,-.67564201),new s(-.59039098,.091369003,-.801929),new s(-.82436001,-.13312399,-.55018902),new s(-.71579403,-.33454201,-.61296099),new s(.17428599,-.89248401,.416049),new s(-.082528003,-.83712298,-.54075301),new s(.28333101,-.88087398,-.37918901),new s(.675134,-.42662701,-.60181701),new s(.84372002,-.512335,-.160156),new s(.97730398,-.098555997,-.18752),new s(.846295,.522672,-.102947),new s(.67714101,.72132498,-.145501),new s(.32096499,.87089199,-.37219399),new s(-.178978,.911533,-.37023601),new s(-.44716901,.82670099,-.341474),new s(-.70320302,.496328,-.50908101),new s(-.97718102,.063562997,-.202674),new s(-.87817001,-.412938,.241455),new s(-.83583099,-.35855001,-.415728),new s(-.499174,-.69343299,-.51959199),new s(-.188789,-.92375302,-.33322501),new s(.19225401,-.96936101,-.152896),new s(.51594001,-.783907,-.34539199),new s(.90592498,-.30095199,-.29787099),new s(.99111199,-.127746,.037106998),new s(.99513501,.098424003,-.0043830001),new s(.76012301,.64627701,.067367002),new s(.205221,.95958,-.192591),new s(-.042750001,.97951299,-.19679099),new s(-.43801701,.89892697,.0084920004),new s(-.82199401,.48078501,-.30523899),new s(-.89991701,.081710003,-.42833701),new s(-.92661202,-.144618,-.347096),new s(-.79365999,-.55779201,-.24283899),new s(-.43134999,-.84777898,-.30855799),new s(-.0054919999,-.96499997,.26219299),new s(.58790499,-.80402601,-.088940002),new s(.69949299,-.66768599,-.254765),new s(.88930303,.359795,-.282291),new s(.780972,.197037,.59267199),new s(.52012098,.50669599,.68755698),new s(.40389499,.69396102,.59605998),new s(-.154983,.89923602,.40909001),new s(-.65733802,.53716803,.528543),new s(-.74619502,.33409101,.575827),new s(-.62495202,-.049144,.77911502),new s(.31814101,-.254715,.913185),new s(-.555897,.405294,.725752),new s(-.79443401,.099405997,.59916002),new s(-.64036101,-.68946302,.33849499),new s(-.12671299,-.73409498,.66711998),new s(.105457,-.78081697,.61579502),new s(.40799299,-.48091599,.77605498),new s(.69513601,-.54512,.468647),new s(.97319102,-.0064889998,.229908),new s(.94689399,.317509,-.050799001),new s(.56358302,.82561201,.027183),new s(.325773,.94542301,.0069490001),new s(-.171821,.98509699,-.0078149997),new s(-.67044097,.73993897,.054768998),new s(-.822981,.55496198,.121322),new s(-.96619302,.117857,.229307),new s(-.95376903,-.29470399,.058945),new s(-.86438698,-.50272799,-.010015),new s(-.53060901,-.84200603,-.097365998),new s(-.162618,-.98407501,.071772002),new s(.081446998,-.99601102,.036439002),new s(.74598402,-.66596299,.00076199998),new s(.94205701,-.32926899,-.064106002),new s(.93970197,-.28108999,.194803),new s(.77121401,.55067003,.319363),new s(.641348,.73069,.23402099),new s(.080682002,.99669099,.0098789996),new s(-.046725001,.97664303,.20972501),new s(-.53107601,.82100099,.209562),new s(-.69581503,.65599,.29243499),new s(-.97612202,.216709,-.014913),new s(-.96166098,-.14412899,.23331399),new s(-.772084,-.61364698,.165299),new s(-.44960001,-.83605999,.314426),new s(-.39269999,-.91461599,.096247002),new s(.390589,-.91947001,.044890001),new s(.58252901,-.79919797,.148127),new s(.866431,-.48981199,.096864),new s(.90458697,.111498,.41145),new s(.95353699,.23232999,.191806),new s(.497311,.77080297,.398177),new s(.194066,.95631999,.218611),new s(.422876,.882276,.206797),new s(-.373797,.84956598,.37217399),new s(-.53449702,.71402299,.4522),new s(-.881827,.23716,.40759799),new s(-.904948,-.014069,.42528901),new s(-.751827,-.51281703,.41445801),new s(-.50101501,-.69791698,.51175803),new s(-.23519,-.92592299,.295555),new s(.228983,-.95393997,.193819),new s(.734025,-.63489801,.241062),new s(.91375297,-.063253,-.40131599),new s(.90573502,-.161487,.391875),new s(.85892999,.342446,.38074899),new s(.62448603,.60758102,.49077699),new s(.28926399,.85747898,.42550799),new s(.069968,.90216899,.42567101),new s(-.28617999,.94069999,.182165),new s(-.57401299,.80511898,-.14930899),new s(.111258,.099717997,-.98877603),new s(-.30539301,-.94422799,-.12316),new s(-.60116601,-.78957599,.123163),new s(-.290645,-.81213999,.50591898),new s(-.064920001,-.87716299,.47578499),new s(.408301,-.862216,.29978901),new s(.56609702,-.72556603,.39126399),new s(.83936399,-.427387,.33586901),new s(.81889999,-.041305002,.57244802),new s(.71978402,.41499701,.55649698),new s(.88174403,.45027,.140659),new s(.40182301,-.89822,-.17815199),new s(-.054019999,.79134399,.60898),new s(-.29377401,.76399398,.57446498),new s(-.450798,.61034697,.65135098),new s(-.63822103,.186694,.74687302),new s(-.87287003,-.25712699,.41470799),new s(-.58725703,-.52170998,.618828),new s(-.35365799,-.64197397,.680291),new s(.041648999,-.61127299,.79032302),new s(.348342,-.77918297,.52108699),new s(.499167,-.62244099,.602826),new s(.79001898,-.30383101,.53250003),new s(.66011798,.060733002,.74870199),new s(.60492098,.29416099,.73996001),new s(.38569701,.37934601,.84103203),new s(.239693,.207876,.94833201),new s(.012623,.25853199,.96591997),new s(-.100557,.457147,.88368797),new s(.046967,.62858802,.77631903),new s(-.43039101,-.44540501,.785097),new s(-.43429101,-.196228,.87913901),new s(-.25663701,-.336867,.90590203),new s(-.131372,-.15891001,.97851402),new s(.102379,-.208767,.972592),new s(.195687,-.450129,.87125802),new s(.62731898,-.42314801,.65377098),new s(.68743902,-.171583,.70568198),new s(.27592,-.021255,.96094602),new s(.45936701,.15746599,.87417799),new s(.285395,.583184,.76055598),new s(-.81217402,.46030301,.35846099),new s(-.189068,.64122301,.743698),new s(-.338875,.47648001,.811252),new s(-.92099398,.347186,.176727),new s(.040638998,.024465,.99887401),new s(-.73913199,-.35374701,.57318997),new s(-.60351199,-.28661501,.74405998),new s(-.188676,-.547059,.81555402),new s(-.026045,-.39782,.91709399),new s(.26789701,-.649041,.71202302),new s(.518246,-.28489101,.80638599),new s(.493451,-.066532999,.86722499),new s(-.328188,.140251,.93414301),new s(.328188,.140251,.93414301),new s(-.328188,.140251,.93414301),new s(-.328188,.140251,.93414301),new s(-.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 T{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=[],r=new f(this.sizeX+1,this.sizeY+1,this.sizeZ+1);for(let e=0,t=this.spans.length;e<t;e++){var s=this.spans[e].voxels;for(let e=0,t=s.length;e<t;e++){var a=s[e];i.push(a),r.add(a)}}return{voxels:i,voxelField:r}}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 b{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)}}b.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 s=e.stream;if(this.sections=[],!(s.byteLength<b.size)){let r=new b;if(r.read(s),r.headerCount&&r.tailerCount&&r.tailerCount===r.headerCount){for(let e=0;e<r.headerCount;++e){const n=new T;this.readSectionHeader(n,s),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=s.position;s.seek(s.position+r.bodySize);let t=[];for(let e=0;e<r.tailerCount;++e)t[e]=this.readSectionTailer(this.sections[e],s);let i=0;for(let e=0;e<r.headerCount;++e)s.seek(a),i+=this.readSectionBodySpans(this.sections[e],t[e],s);this.voxelCount=i}}}readSectionHeader(e,t){e.name=t.readCString(16),t.readUint32(),t.readUint32(),t.readUint32()}readSectionTailer(e,t){var i=t.readUint32(),r=t.readUint32(),s=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:r,dataSpanOffset:s}}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:r,sizeY:s,sizeZ:a}=e;let n=new Array(s);for(let t=0;t<s;++t){n[t]=new Array(r);for(let e=0;e<r;++e)n[t][e]=i.readInt32()}let o=new Array(s);for(let t=0;t<s;++t){o[t]=new Array(r);for(let e=0;e<r;++e)o[t][e]=i.readInt32()}let h=e.spans=[],l=0;for(let t=0;t<s;++t)for(let e=0;e<r;++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,r,s,a){if(-1===e||-1===t)return[];let n=[];for(let t=0;t<s;){t+=a.readUint8();var o=a.readUint8();for(let e=0;e<o;++e){var h={x:i,y:r,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 T).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,A,C=__webpack_require__(949);(s=_=_||{})[s.ExtraData=1]="ExtraData",s[s.ZData=2]="ZData",s[s.DamagedData=4]="DamagedData";const B=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 r=e.readInt32();this.extraX=e.readInt32(),this.extraY=e.readInt32(),this.extraWidth=e.readInt32(),this.extraHeight=e.readInt32();var s=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=(s&_.ZData)===_.ZData,this.hasZData&&(e.position+=t*i/2),this.hasExtraData=(s&_.ExtraData)===_.ExtraData,this.hasExtraData&&(s=Math.abs(this.extraWidth*this.extraHeight),this.extraData=new Uint8Array(e.buffer,e.byteOffset+e.position,s),e.position+=s),this.hasZData&&this.hasExtraData&&0<r&&r<e.byteLength&&(e.position+=Math.abs(this.extraWidth*this.extraHeight))}readRadarRgb(e,t,i){return new C.Color(B(e)/255,B(t)/255,B(i)/255)}}class x{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,r=new Uint8Array(t.buffer,t.byteOffset+t.position,4*i);this.images=[];for(let e=0;e<i;e++){var s=r[4*e+3]<<24|r[4*e+2]<<16|r[4*e+1]<<8|r[4*e];t.seek(s);s=new E(t,this.blockWidth,this.blockHeight);this.images.push(s)}}}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")}}function N(e,t="0000"){e=""+e;return t.substring(0,t.length-e.length)+e}function R(e,t){return e.toLowerCase()===t.toLowerCase()}function D(t){var i=t.length;let r=new Uint8Array(i);for(let e=0;e<i;e++)r[e]=t.charCodeAt(e);return r}function M(e){return D(P.decode(e))}function L(t){var i=t.length;let r="";for(let e=0;e<i;e++){var s=t.charCodeAt(e);r+=String.fromCharCode(s>>8),r+=String.fromCharCode(255&s)}return r}function F(t){var i=t.length;let r="";for(let e=0;e<i;e+=2){var s=(t.charCodeAt(e)<<8)+t.charCodeAt(e+1);r+=String.fromCharCode(s)}return r}class j{constructor(e,t,i){this.r=e,this.g=t,this.b=i}static fromRgb(e,t,i){return new j(e,t,i)}static fromHsv(e,t,i){let r=0,s=0,a=0;if(e=e/255*360%360,i/=255,0===(t/=255))r=i,s=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:r=i,s=l,a=o;break;case 1:r=h,s=i,a=o;break;case 2:r=o,s=i,a=l;break;case 3:r=o,s=h,a=i;break;case 4:r=l,s=o,a=i;break;case 5:r=i,s=o,a=h}}return j.fromRgb(Math.floor(255*r),Math.floor(255*s),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 j(this.r,this.g,this.b)}}function W(e,t){return Math.round(Math.random()*(t-e))+e}function U(e,t,i){return Math.min(i,Math.max(e,t))}function V(e,t,i){return t<=e&&e<=i}function z(e,t){if(!e)return e;var i=10**t,t=Math.abs(e-(0<e?Math.ceil(e):Math.floor(e)));return 0<t&&t<=Number.EPSILON&&(e+=Math.sign(e)*Number.EPSILON),0<=e?Math.floor(e*i)/i:Math.ceil(e*i)/i}function H(i){let r=2166136261;for(let e=0,t=i.length;e<t;++e)r^=i[e],r+=(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24);return r>>>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(j.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 r of e)t[i]=r.r,t[i+1]=r.g,t[i+2]=r.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=16;e<32;e++)this.colors[e].r=Math.floor(t.r/255*i[e-16]*4),this.colors[e].g=Math.floor(t.g/255*i[e-16]*4),this.colors[e].b=Math.floor(t.b/255*i[e-16]*4);return this._hash=this.computeHash(this.colors),this}}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=!1){if(this.files.length){var i=this.files[W(0,this.files.length-1)];return i.images[Math.min(e,i.images.length-1)].hasDamagedData?this.files[Math.min(t?1:0,this.files.length-1)]:i}}}class q{constructor(e,t,i){this.fileName=e,this.setName=t,this.tilesInSet=i,this.entries=[]}}class Z{constructor(e,t,i,r){this.name=e,this.subTile=t,this.offsetX=i,this.offsetY=r}}(s=k=k||{})[s.TopLeft=0]="TopLeft",s[s.BottomRight=1]="BottomRight",s[s.TopRight=2]="TopRight",s[s.BottomLeft=3]="BottomLeft",s[s.MiddleTlBr=4]="MiddleTlBr",s[s.MiddleTrBl=5]="MiddleTrBl";const Q=new Map([[k.TopLeft,["BridgeTopLeft1","BridgeTopLeft2"]],[k.BottomRight,["BridgeBottomRight1","BridgeBottomRight2"]],[k.TopRight,["BridgeTopRight1","BridgeTopRight2"]],[k.BottomLeft,["BridgeBottomLeft1","BridgeBottomLeft2"]],[k.MiddleTlBr,["BridgeMiddle1"]],[k.MiddleTrBl,["BridgeMiddle2"]]]);class X{constructor(e){this.theaterIni=e,this.tileSets=[],this.orderedEntries=[],this.highBridgeSetNums=[this.getGeneralValue("BridgeSet"),this.getGeneralValue("WoodBridgeSet")],this.cliffSetNums=[this.getGeneralValue("CliffSet"),this.getGeneralValue("CliffRamps"),this.getGeneralValue("WaterCliffs"),this.getGeneralValue("DestroyableCliffs")]}getTile(e){return this.orderedEntries[e]}getTileImage(e,t){let i=this.getTile(e);if(!i)throw new Error(`TileNum ${e} not found`);e=i.getTmpFile(t);if(!e||t>=e.images.length)throw new Error(`SubTile ${t} not found`);return e.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,r=0){let s=0;return this.tileSets.some((e,t)=>t===i?(s+=r,!0):(s+=e.entries.length,!1)),s}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 r="TileSet"+N(t,"0000");let e=this.theaterIni.getSection(r);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 s=new q(t.getString("FileName"),t.getString("SetName"),t.getNumber("TilesInSet"));this.tileSets.push(s);for(let r=1;r<=s.tilesInSet;r++){let i=new $(s,r-1);var o="a".charCodeAt(0);for(let t=o-1;t<="z".charCodeAt(0);t++)if(!(t>=o&&"Bridges"===s.setName)){let e=s.fileName+N(r,"00");t>=o&&(e+=String.fromCharCode(t)),e+=n;var h=a.get(e);if(!h)break;i.addFile(h)}s.entries.push(i),this.orderedEntries.push(i)}}}initAnimations(){var r=this.theaterIni.getOrderedSections();for(let e=this.tileSets.length;e<r.length;++e){let t=r[e],i=this.tileSets.find(e=>e.setName===t.name);if(i)for(let e=1;e<=i.tilesInSet;++e){var s=`Tile${N(e,"00")}`,a=`${s}Anim`,n=t.getString(a);n?(s=new Z(n,t.getNumber(`${s}AttachesTo`),t.getNumber(`${s}XOffset`),t.getNumber(`${s}YOffset`)),i.entries[e-1].setAnimation(s)):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"),r=this.getGeneralValue("PaveTile"),s=this.getGeneralValue("ShorePieces"),a=this.getGeneralValue("WaterBridge"),n=this.getGeneralValue("PavedRoads"),o=this.getGeneralValue("Medians");return!(e===i&&t===s||t===i&&e===s)&&(!(e===i&&t===a||t===i&&e===a)&&(!(e===r&&t===n||t===r&&e===n)&&!(e===r&&t===o||t===r&&e===o)))}getHighBridgeHeadType(e){for(var[t,i]of Q)for(var r of i)if(this.getGeneralValue(r)===e+1)return t}getOppositeHighBridgeHeadType(e){switch(e){case k.TopLeft:return k.BottomRight;case k.TopRight:return k.BottomLeft;case k.BottomLeft:return k.TopRight;case k.BottomRight:return k.TopLeft;case k.MiddleTlBr:case k.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&&![k.MiddleTlBr,k.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&&[k.MiddleTlBr,k.MiddleTrBl].includes(e)}return!1}}(s=O=O||{})[s.None=0]="None",s[s.Iso=1]="Iso",s[s.Unit=2]="Unit",s[s.Overlay=3]="Overlay",s[s.Anim=4]="Anim",s[s.Custom=5]="Custom",s[s.Default=6]="Default";class Y{constructor(e,t,i,r,s,a,n,o,h){this.type=e,this.settings=t,this.palettes=i,this.isoPalette=r,this.ovlPalette=s,this.unitPalette=a,this.animPalette=n,this.libPalette=o,this.tileSets=h}static factory(e,t,i,r,s){var a=s.get(i.IsoPaletteName);if(!a)throw new Error(`Missing palette "${i.IsoPaletteName}"`);var n=s.get(i.OverlayPaletteName);if(!n)throw new Error(`Missing palette "${i.OverlayPaletteName}"`);var o=s.get(i.UnitPaletteName);if(!o)throw new Error(`Missing palette "${i.UnitPaletteName}"`);var h=s.get("anim.pal");if(!h)throw new Error("Missing anim palette");var l=s.get(i.LibPaletteName);if(!l)throw new Error(`Missing lib palette ${i.LibPaletteName}`);let c=new X(t);return c.loadTileData(r,i.Extension),new this(e,i,s,a,n,o,h,l,c)}getPalette(e,t){switch(e){case O.Anim:return this.animPalette;case O.Overlay:return this.ovlPalette;case O.Unit:return this.unitPalette;case O.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:O.Iso;return this.isoPalette}}}(s=I=I||{})[s.None=0]="None",s[s.Temperate=1]="Temperate",s[s.Urban=2]="Urban",s[s.Snow=4]="Snow",s[s.Lunar=8]="Lunar",s[s.Desert=16]="Desert",s[s.NewUrban=32]="NewUrban",s[s.All=63]="All";class K{constructor(){this.fileData=new Map}fromVirtualFile(e,t){var i,r;for([i,r]of t.entries){var s=this.buildWavData(e.stream,r);this.fileData.set(i,s)}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 w;var r,s,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)&&(r=11100*o*(t.sampleRate/22050|0),s=t.chunkSize,a=1017*(n=Math.max(2,Math.ceil(t.length/s))),n=n*s,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(r),i.writeInt16(s),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 s=new J;let e=t.readString(16);var r=e.indexOf("\0");0!==r&&(e=e.substr(0,r)),s.filename=e+".wav",s.offset=t.readUint32(),s.length=t.readUint32(),s.sampleRate=t.readUint32(),s.flags=t.readUint32(),s.chunkSize=t.readUint32(),this.entries.set(s.filename,s)}}}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 r=i[t++%i.length],s=i[t++%i.length],a=i[t++%i.length],n=i[t++%i.length];this.m_p[e]^=r<<24|s<<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),r=e.length/2|0,s=0;for(;0<r--;){var a=te(e[s]),n=te(e[s+1]);[a,n]=t(a,n),i[s++]=te(a),i[s++]=te(n)}return i}_encrypt(e,t){let i=e,r=t;i^=this.m_p[0];let s=!1;for(let e=1;e<=16;e++,s=!s)s?i=this.round(i,r,e):r=this.round(r,i,e);return r^=this.m_p[17],[r,i]}_decrypt(e,t){let i=e,r=t;i^=this.m_p[17];let s=!1;for(let e=16;1<=e;e--,s=!s)s?i=this.round(i,r,e):r=this.round(r,i,e);return r^=this.m_p[0],[r,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",se=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,r){let s;s=0!=(128&t[0])?255:0;const a=new Uint8Array(e.buffer,e.byteOffset);let n=4*r;for(;n>i;n--)a[n-1]=s;for(;0<n;n--)a[n-1]=t[i-n]}key_to_bignum(e,t,i){let r,s,a=0;if(2===t[a]){if(a++,0!=(128&t[a])){for(r=0,s=0;s<(127&t[a]);s++)r=(r<<8>>>0|t[a+s+1])>>>0;a+=1+(127&t[a])}else r=t[a],a++;r<=4*i&&this.move_key_to_big(e,t.subarray(a),r,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 r,s;if(0===(i=this.len_bignum(e,t)))return 0;for(r=32*i,s=2147483648;0==(s&e[i-1]);)s>>>=1,r--;return r}init_pubkey(){let e=0,t;var i;const r=new Uint8Array(256);for(this.init_bignum(this.pubkey.key2,65537,64),t=0;e<re.length;)i=(((se[re.charCodeAt(e++)]>>>0<<6>>>0|255&se[re.charCodeAt(e++)])>>>0<<6>>>0|255&se[re.charCodeAt(e++)])>>>0<<6>>>0|255&se[re.charCodeAt(e++)])>>>0,r[t++]=i>>16&255,r[t++]=i>>8&255,r[t++]=255&i;this.key_to_bignum(this.pubkey.key1,r,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,r){for(let e=0;e<r;e++)t[e]=i[e]}shr_bignum(e,t,i){let r;var s=t/32|0;if(0<s){for(r=0;r<i-s;r++)e[r]=e[r+s];for(;r<i;r++)e[r]=0;t%=32}if(0!==t){for(r=0;r<i-1;r++)e[r]=(e[r]>>>t|e[r+1]<<32-t>>>0)>>>0;e[r]=e[r]>>>t}}shl_bignum(e,t,i){let r;var s=t/32|0;if(0<s){for(r=i-1;r>s;r--)e[r]=e[r-s];for(;0<r;r--)e[r]=0;t%=32}if(0!==t){for(r=i-1;0<r;r--)e[r]=(e[r]<<t>>>0|e[r-1]>>>32-t)>>>0;e[0]=e[0]<<t>>>0}}sub_bignum(e,t,i,r,s){var a,n;s+=s;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!=--s;)a=o[c],n=h[c],l[c]=a-n-r&65535,r=0!=(a-n-r&65536)?1:0,c++;return r}sub_bignum_word(e,t,i,r,s){var a,n;let o=0;for(;-1!=--s;)a=t[o],n=i[o],e[o]=a-n-r&65535,r=0!=(a-n-r&65536)?1:0,o++;return r}inv_bignum(e,t,i){const r=new Uint32Array(64);var s;let a,n,o=0;for(this.init_bignum(r,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,s=4*((n-1)/32|0)>>>0,r[s/4|0]=r[s/4|0]|1<<(n-1&31)>>>0;0<n;)n--,this.shl_bignum(r,1,i),-1!==this.cmp_bignum(r,t,i)&&(this.sub_bignum(r,r,t,0,i),e[o]=e[o]|a>>>0),a>>>=1,0===a&&(o--,a=2147483648);this.init_bignum(r,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,r){let s,a;var n=new Uint16Array(t.buffer,t.byteOffset);let o=a=0;for(s=0;s<r;s++)a=i*n[o]+e[o]+a,e[o]=65535&a,o++,a>>>=16;e[o]+=65535&a}mul_bignum(e,t,i,r){let s;var a=new Uint16Array(i.buffer,i.byteOffset);let n=new Uint16Array(e.buffer,e.byteOffset);this.init_bignum(e,0,2*r);let o=0;for(s=0;s<2*r;s++)this.mul_bignum_word(n.subarray(o),t,a[o],2*r),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,r,s){let a;var n=this.glob1,o=this.glob2;if(this.mul_bignum(this.glob2,t,r,s),this.glob2[2*s]=0,(r=2*this.len_bignum(this.glob2,2*s+1))>=this.glob1_len_x2){this.inc_bignum(this.glob2,2*s+1),this.neg_bignum(this.glob2,2*s+1),a=1+r-this.glob1_len_x2;let e=new Uint16Array(o.buffer),t=a,i=1+r;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*s),0==(32768&e[i])&&0!==this.sub_bignum_word(l,l,new Uint16Array(n.buffer),0,2*s)&&e[i]--)}this.neg_bignum(this.glob2,s),this.dec_bignum(this.glob2,s)}this.mov_bignum(e,this.glob2,s)}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,r,s){var a,n=new Uint32Array(64);let o,h,l=0;for(this.init_bignum(e,1,s),a=this.len_bignum(r,s),this.init_two_dw(r,a),o=this.bitlen_bignum(i,a)<<24>>24,r=((o+31)/32|0)>>>0,h=1<<(o-1)%32>>>1,l+=r-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(s)}memcpy(e,t,i){let r=0;for(;0!=i--;)e[r]=t[r],r++}process_predata(e,t,i){var r=new Uint32Array(64),s=new Uint32Array(64);let a=0,n=0;for(var o=(this.pubkey.len-1)/8|0;1+o<=t;)this.init_bignum(r,0,64),this.memcpy(new Uint8Array(r.buffer),e.subarray(a),1+o),this.calc_a_key(s,r,this.pubkey.key2,this.pubkey.key1,64),this.memcpy(i.subarray(n),new Uint8Array(s.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 r=e;for(let e=0,t=i.length;e<t;e++)r=(r>>>8^this.lookUp[255&r^i[e]])>>>0;return r=(r^e)>>>0,r}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,r=i>>2;if(0!=(3&i)){t+=String.fromCharCode(i-(r<<2));let e=3-(3&i);for(;0!=e--;)t+=t[r<<2]}return oe.calculateCrc(D(t))}}he.size=12,(s=A=A||{})[s.Checksum=65536]="Checksum",s[s.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&~(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 ne).decryptKey(t),r=e.readUint32Array(2);const s=new ie(i);let a=new w(s.decrypt(r));t=a.readUint16();a.readUint32(),e.position=this.headerStart;i=6+t*he.size,t=(3+i)/4|0,r=e.readUint32Array(t+t%2);a=new w(s.decrypt(r));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 r=new he(t.readUint32(),t.readUint32(),t.readUint32());this.index.set(r.hash,r)}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 r=new Set;for await(var e of this.rfs.getEntries())r.add(e.toLowerCase());for(var s of["ecache","expand","elocal"])for(let t=99;0<=t;t--){let e=[`${s}${N(t,"00")}.mix`];i===At.YurisRevenge&&e.push(`${s}md${N(t,"00")}.mix`);for(var a of e)r.has(a)&&await this.addMixFile(a)}let t=[".mmx"];i===At.YurisRevenge&&t.push(".yro");for(const n of t)for(const o of r)o.endsWith(n)&&this.addArchive(new le((await this.rfs.openFile(o)).stream),o)}async loadStandaloneFiles(e){let i=["ini","csf"],r=new Set(e?.exclude),s=[];for await(var a of this.rfs.getEntries()){let t=a.toLowerCase();i.some(e=>t.endsWith("."+e))&&!r.has(t)&&s.push(await this.rfs.openFile(a,!0))}if(s.length){let e=new ue;for(var t of s)e.addFile(t);this.addArchive(e,"mem.archive")}}}class pe extends Error{constructor(e){super("Storage quota exceeded",e),this.name="StorageQuotaError"}}class ge{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(R(t,e))return t}async fixEntryCase(e){if(!this.caseSensitive)for await(var t of this.getEntries())if(R(t,e)){e=t;break}return e}async getRawFile(t,e=!1,i){let r;try{var s=e?t:await this.fixEntryCase(t);r=await this.handle.getFileHandle(s)}catch(e){if("NotFoundError"===e.name)throw new ce(`File "${t}" not found in directory "${this.handle.name}"`,{cause:e});if(e instanceof DOMException)throw new l(`File "${t}" could not be read (${e.name})`,{cause:e});throw e}t=await r.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,r){r=r??(i instanceof File?i.name:i.filename);try{var s=await this.fixEntryCase(r);await this.deleteFile(s,!0);let e=await this.handle.getFileHandle(s,{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 DOMException)throw new l(`File "${r}" 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 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 r;try{r=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 DOMException)throw new l(`Directory "${t}" could not be read (${e.name})`,{cause:e});throw e}return new ge(r,e)}async getOrCreateDirectory(t,e=this.caseSensitive){var i=e?t:await this.fixEntryCase(t);try{return new ge(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 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 DOMException)throw new l(`Directory "${t}" could not be deleted (${e.name})`,{cause:e});throw e}}}class me{constructor(){this.directories=[]}addRootDirectoryHandle(e){this.rootDirectory=this.addDirectoryHandle(e),this.rootDirectoryHandle=e}getRootDirectoryHandle(){return this.rootDirectoryHandle}addDirectoryHandle(e){e=new ge(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 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 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 fe{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 ye="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function we(r,e,s,t){if(-1<["32f","64"].indexOf(e)&&-1<["32f","64"].indexOf(t))s.set(r);else{Se(e),Se(t);let i=function(e,t){let i=function(e){return e};e!=t&&(i=["32f","64"].includes(e)?be:["32f","64"].includes(t)?ve:Te);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,r,!0);for(let e=0,t=r.length;e<t;e++)s[e]=i(r[e],a);_e(t,s,!1)}}function Te(e,t){return e=0<e?parseInt(e/t.oldMax*t.newMax,10):parseInt(e/t.oldMin*t.newMin,10)}function be(e,t){return parseInt(0<e?e*t.newMax:e*t.newMin,10)}function ve(e,t){return 0<e?e/t.oldMax:e/t.oldMin}function Se(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 r=t?-128:128;for(let e=0,t=i.length;e<t;e++)i[e]=i[e]+=r}}const ke=[-1,-1,-1,-1,2,4,6,8,-1,-1,-1,-1,2,4,6,8],Oe=[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 Ie(i){var r={index:0,predicted:0,step:7};let s=new Uint8Array(i.length),a=[],n=0,o=0;for(let e=0,t=i.length;e<t;e++)e%505==0&&0!=e&&(s.set(function(i,r){let s=function(e,t){Ce(e,t);let i=[];return i.push(255&e),i.push(e>>8&255),i.push(t.index),i.push(0),i}(i[0],r);for(let e=3,t=i.length;e<t;e+=2){var a=Ce(i[e],r),n=Ce(i[e+1],r);s.push(n<<4|a)}return s}(a,r),n),n+=256,a=[],o++),a.push(i[e]);let e=i.length/2;return e%2&&e++,s.slice(0,e+512+4*o)}function Ae(t,e=256){var i={index:0,predicted:0,step:7};let r=new Int16Array(2*t.length),s=[],a=0,n=t.length,o=0;for(;0<n;){var h=Math.min(n,e);for(let e=0;e<h;e++)s.push(t[o]),o++;var l=function(i,r){r.predicted=function(e){return 32767<e?e-65536:e}(i[1]<<8|i[0]),r.index=i[2],r.step=Oe[r.index];let s=[r.predicted];for(let e=4,t=i.length;e<t;e++){var a=i[e],n=a>>4,a=n<<4^a;s.push(Be(a,r)),s.push(Be(n,r))}return s}(s,i);r.set(l,a),a+=l.length,s=[],n-=e}return r.slice(0,a)}function Ce(e,t){let i=e-t.predicted,r=0;0<=i?r=0:(r=8,i=-i);let s=Oe[t.index],a=s>>3;return i>s&&(r|=4,i-=s,a+=s),s>>=1,i>s&&(r|=2,i-=s,a+=s),s>>=1,i>s&&(r|=1,a+=s),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+=ke[7&e],i.index<0?i.index=0:88<i.index&&(i.index=88)}(r,a,t),r}function Be(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+=ke[e],t.index<0?t.index=0:88<t.index&&(t.index=88);t.step=Oe[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 xe(i){let r=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)r[e]=function(e){let t;var i,r=~(e=-32768==e?-32767:e)>>8&128;return r||(e*=-1),32635<e&&(e=32635),t=256<=e?(i=Ee[e>>8&127])<<4|e>>i+3&15:e>>4,85^t^r}(i[e]);return r}function Pe(i){let r=new Int16Array(i.length);for(let e=0,t=i.length;e<t;e++)r[e]=function(e){let t=0;0!=(128&(e^=85))&&(e&=-129,t=-1);var i=4+((240&e)>>4);let r=0;return r=4!=i?1<<i|(15&e)<<i-4|1<<i-5:e<<1|1,r=0===t?r:-r,8*r*-1}(i[e]);return r}const Ne=132,Re=32635,De=[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],Me=[0,132,396,924,1980,4092,8316,16764];function Le(i){let r=new Uint8Array(i.length);for(let e=0,t=i.length;e<t;e++)r[e]=(s=i[e],a=void 0,0!=(a=s>>8&128)&&(s=-s),(s+=Ne)>Re&&(s=Re),~(a|(a=De[s>>7&255])<<4|s>>a+3&15));var s,a;return r}function Fe(i){let r=new Int16Array(i.length);for(let e=0,t=i.length;e<t;e++)r[e]=function(e){var t,i;let r;return t=128&(e=~e),i=e>>4&7,e=15&e,r=Me[i]+(e<<3+i),0!=t&&(r=-r),r}(i[e]);return r}function je(t,i,r=0,s=t.length){for(let e=r;e<s;e+=i)!function(t,i,r){i--;for(let e=0;e<i;e++){var s=t[r+e];t[r+e]=t[r+i],t[r+i]=s,i--}}(t,i,e)}function We(e,i,r=0){let s=0;for(var t=e.length;s<t;){var a=e.codePointAt(s);if(a<128)i[r]=a,r++;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,s++),i[r]=(a>>6*e)+t,r++;0<e;)i[r]=128|a>>6*(e-1)&63,r++,e--}s++}return r}const Ue=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,r,s=0){r=this.clamp_(Math.round(r));for(let e=0,t=this.offset;e<t;e++)i[s]=255&Math.floor(r/Ue[e]),s++;return s}unpack_(t,i=0){let r=0;for(let e=0;e<this.offset;e++)r+=t[i+e]*Ue[e];return r}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 ze{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 r=((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 s=Math.min(Math.floor(Math.log(t)/Math.LN2),1023),a=He(t/Math.pow(2,s)*Math.pow(2,this.fbits));return t!=t?(a=Math.pow(2,this.fbits-1),s=(1<<this.ebits)-1):0!==t&&(t>=Math.pow(2,1-this.bias)?(2<=a/Math.pow(2,this.fbits)&&(s+=1,a=1),a=s>this.bias?(s=(1<<this.ebits)-1,0):(s+=this.bias,He(a)-Math.pow(2,this.fbits))):(a=He(t/Math.pow(2,1-this.bias-this.fbits)),s=0)),this.packFloatBits_(e,i,r,s,a)}unpack(t,i){var e=(1<<this.ebits)-1;let r,s="";for(let e=this.offset-1;0<=e;e--){var a=t[e+i].toString(2);s+="00000000".substring(a.length)+a}var n="1"==s.charAt(0)?-1:1;s=s.substring(1);let o=parseInt(s.substring(0,this.ebits),2);return s=s.substring(this.ebits),o==e?0!==parseInt(s,2)?NaN:1/0*n:(r=0===o?(o+=1,parseInt(s,2)):parseInt("1"+s,2),n*r*this.fbias*Math.pow(2,o-this.bias))}packFloatBits_(e,t,i,r,s){let a=[];a.push(i);for(let e=this.ebits;0<e;--e)a[e]=r%2?1:0,r=Math.floor(r/2);var n=a.length;for(let e=this.fbits;0<e;--e)a[n+e]=s%2?1:0,s=Math.floor(s/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 He(e){var t=Math.floor(e),e=e-t;return!(e<.5)&&(.5<e||t%2)?t+1:t}function Ge(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,r=191,s=!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]&&(r=159)):240<=a&&a<=244?(t=3,240===o[n]&&(i=144),244===o[n]&&(r=143)):s=!0,a&=(1<<8-t-1)-1;for(let e=0;e<t;e++)(o[n]<i||o[n]>r)&&(s=!0),a=a<<6|63&o[n],n++;s?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 $e(e){var t=[];return We(e,t),t}function qe(e,t,i=0){return We(e,t,i)}function Ze(e,t,i,r=0){let s=et((t=t||{}).bits,t.fp,t.signed);var a=Math.ceil(t.bits/8);let n=0;for(var o=r,h=e.length;n<h;n++)r=s.pack(i,e[n],r);return t.be&&je(i,a,o,r),r}function Qe(e,t,i,r=0,s=e.length){var a,n=et((t=t||{}).bits,t.fp,t.signed);s=function(e,t,i){i=(t-e)%i;return t-i}(r,s,n.offset),t.be?(a=new Uint8Array(e),t.be&&je(a,n.offset,r,s),Je(a,i,r,s,n)):Je(e,i,r,s,n)}function Xe(e,t,i,r=0){return Ze([e],t,i,r)}function Ye(e,t){var i=[];return Xe(e,t,i,0),i}function Ke(e,t,i=0){var r=[];return Qe(e,t,r,i,i+Math.ceil(t.bits/8)),r[0]}function Je(i,r,s,a,n){var o=n.offset;for(let e=0,t=s;t<a;t+=o,e++)r[e]=n.unpack(i,t)}function et(e,t,i){return t&&32==e?new ze(8,23):t&&64==e?new ze(11,52):new Ve(e,i)}function tt(e,t){let i=$e(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 r=this.signature.subChunks;let s=[];for(let e=0;e<r.length;e++)if(r[e].chunkId==t){if(!i)return r[e];s.push(r[e])}return"LIST"==t&&s.length?s:null}readString(e,t){e=Ge(e,this.head,this.head+t);return this.head+=t,e}readUInt32(e){return e=Ke(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=Ge(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,Ge(e,t,t+4)}getChunkSize_(e,t){return this.head+=4,Ke(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=Ge(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 r=i[e];this.LIST.push({chunkId:r.chunkId,chunkSize:r.chunkSize,format:r.format,subChunks:[]});for(let e=0;e<r.subChunks.length;e++)this.readLISTSubChunks_(r.subChunks[e],r.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=Ge(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 Ge(t,i,this.head-1)}readUInt16_(e){return e=Ke(e,this.uInt16,this.head),this.head+=2,e}});function it(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 r=this.signature.subChunks;let s=[];for(let e=0;e<r.length;e++)if(r[e].chunkId==t){if(!i)return r[e];s.push(r[e])}return"LIST"==t&&s.length?s:null}readString(e,t){e=Ge(e,this.head,this.head+t);return this.head+=t,e}readUInt32(e){return e=Ke(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=Ge(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,Ge(e,t,t+4)}getChunkSize_(e,t){return this.head+=4,Ke(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=Ge(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 r=i[e];this.LIST.push({chunkId:r.chunkId,chunkSize:r.chunkSize,format:r.format,subChunks:[]});for(let e=0;e<r.subChunks.length;e++)this.readLISTSubChunks_(r.subChunks[e],r.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=Ge(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 Ge(t,i,this.head-1)}readUInt16_(e){return e=Ke(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_(),$e(this.data.chunkId),Ye(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 r=new Uint8Array(i+12),s=0;s=qe(this.container,r,s),s=Xe(i+4,this.uInt32,r,s),s=qe(this.format,r,s);for(let e=0;e<t.length;e++)r.set(t[e],s),s+=t[e].length;return r}getBextBytes_(){let e=[];return this.enforceBext_(),this.bext.chunkId&&(this.bext.chunkSize=602+this.bext.codingHistory.length,e=e.concat($e(this.bext.chunkId),Ye(602+this.bext.codingHistory.length,this.uInt32),tt(this.bext.description,256),tt(this.bext.originator,32),tt(this.bext.originatorReference,32),tt(this.bext.originationDate,10),tt(this.bext.originationTime,8),Ye(this.bext.timeReference[0],this.uInt32),Ye(this.bext.timeReference[1],this.uInt32),Ye(this.bext.version,this.uInt16),tt(this.bext.UMID,64),Ye(this.bext.loudnessValue,this.uInt16),Ye(this.bext.loudnessRange,this.uInt16),Ye(this.bext.maxTruePeakLevel,this.uInt16),Ye(this.bext.maxMomentaryLoudness,this.uInt16),Ye(this.bext.maxShortTermLoudness,this.uInt16),tt(this.bext.reserved,180),tt(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=$e(this.iXML.value),this.iXML.chunkSize=t.length,e=e.concat($e(this.iXML.chunkId),Ye(this.iXML.chunkSize,this.uInt32),t)),this.enforceByteLen_(e),e}getDs64Bytes_(){let e=[];return this.ds64.chunkId&&(e=e.concat($e(this.ds64.chunkId),Ye(this.ds64.chunkSize,this.uInt32),Ye(this.ds64.riffSizeHigh,this.uInt32),Ye(this.ds64.riffSizeLow,this.uInt32),Ye(this.ds64.dataSizeHigh,this.uInt32),Ye(this.ds64.dataSizeLow,this.uInt32),Ye(this.ds64.originationTime,this.uInt32),Ye(this.ds64.sampleCountHigh,this.uInt32),Ye(this.ds64.sampleCountLow,this.uInt32))),this.enforceByteLen_(e),e}getCueBytes_(){let e=[];var t;return this.cue.chunkId&&(t=this.getCuePointsBytes_(),e=e.concat($e(this.cue.chunkId),Ye(t.length+4,this.uInt32),Ye(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(Ye(this.cue.points[e].dwName,this.uInt32),Ye(this.cue.points[e].dwPosition,this.uInt32),$e(this.cue.points[e].fccChunk),Ye(this.cue.points[e].dwChunkStart,this.uInt32),Ye(this.cue.points[e].dwBlockStart,this.uInt32),Ye(this.cue.points[e].dwSampleOffset,this.uInt32));return t}getSmplBytes_(){let e=[];var t;return this.smpl.chunkId&&(t=this.getSmplLoopsBytes_(),e=e.concat($e(this.smpl.chunkId),Ye(t.length+36,this.uInt32),Ye(this.smpl.dwManufacturer,this.uInt32),Ye(this.smpl.dwProduct,this.uInt32),Ye(this.smpl.dwSamplePeriod,this.uInt32),Ye(this.smpl.dwMIDIUnityNote,this.uInt32),Ye(this.smpl.dwMIDIPitchFraction,this.uInt32),Ye(this.smpl.dwSMPTEFormat,this.uInt32),Ye(this.smpl.dwSMPTEOffset,this.uInt32),Ye(this.smpl.dwNumSampleLoops,this.uInt32),Ye(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(Ye(this.smpl.loops[e].dwName,this.uInt32),Ye(this.smpl.loops[e].dwType,this.uInt32),Ye(this.smpl.loops[e].dwStart,this.uInt32),Ye(this.smpl.loops[e].dwEnd,this.uInt32),Ye(this.smpl.loops[e].dwFraction,this.uInt32),Ye(this.smpl.loops[e].dwPlayCount,this.uInt32));return t}getFactBytes_(){let e=[];return this.fact.chunkId&&(e=e.concat($e(this.fact.chunkId),Ye(this.fact.chunkSize,this.uInt32),Ye(this.fact.dwSampleLength,this.uInt32))),this.enforceByteLen_(e),e}getFmtBytes_(){if(this.fmt.chunkId){var e=[].concat($e(this.fmt.chunkId),Ye(this.fmt.chunkSize,this.uInt32),Ye(this.fmt.audioFormat,this.uInt16),Ye(this.fmt.numChannels,this.uInt16),Ye(this.fmt.sampleRate,this.uInt32),Ye(this.fmt.byteRate,this.uInt32),Ye(this.fmt.blockAlign,this.uInt16),Ye(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(Ye(this.fmt.cbSize,this.uInt16))),18<this.fmt.chunkSize&&(e=e.concat(Ye(this.fmt.validBitsPerSample,this.uInt16))),20<this.fmt.chunkSize&&(e=e.concat(Ye(this.fmt.dwChannelMask,this.uInt32))),24<this.fmt.chunkSize&&(e=e.concat(Ye(this.fmt.subformat[0],this.uInt32),Ye(this.fmt.subformat[1],this.uInt32),Ye(this.fmt.subformat[2],this.uInt32),Ye(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($e(this.LIST[e].chunkId),Ye(i.length+4,this.uInt32),$e(this.LIST[e].format),i)}return this.enforceByteLen_(t),t}getLISTSubChunksBytes_(i,r){let s=[];for(let e=0,t=i.length;e<t;e++)"INFO"==r?s=s.concat(this.getLISTINFOSubChunksBytes_(i[e])):"adtl"==r&&(s=s.concat(this.getLISTadtlSubChunksBytes_(i[e]))),this.enforceByteLen_(s);return s}getLISTINFOSubChunksBytes_(e){let t=[];var i=tt(e.value,e.value.length);return t=t.concat($e(e.chunkId),Ye(i.length+1,this.uInt32),i),t.push(0),t}getLISTadtlSubChunksBytes_(e){let t=[];var i;return-1<["labl","note"].indexOf(e.chunkId)?(i=tt(e.value,e.value.length),t=t.concat($e(e.chunkId),Ye(i.length+4+1,this.uInt32),Ye(e.dwName,this.uInt32),i),t.push(0)):"ltxt"==e.chunkId&&(t=t.concat(this.getLtxtChunkBytes_(e))),t}getLtxtChunkBytes_(e){return[].concat($e(e.chunkId),Ye(e.value.length+20,this.uInt32),Ye(e.dwName,this.uInt32),Ye(e.dwSampleLength,this.uInt32),Ye(e.dwPurposeID,this.uInt32),Ye(e.dwCountry,this.uInt16),Ye(e.dwLanguage,this.uInt16),Ye(e.dwDialect,this.uInt16),Ye(e.dwCodePage,this.uInt16),tt(e.value,e.value.length))}get_PMXBytes_(){let e=[];var t;return this._PMX.chunkId&&(t=$e(this._PMX.value),this._PMX.chunkSize=t.length,e=e.concat($e(this._PMX.chunkId),Ye(this._PMX.chunkSize,this.uInt32),t)),this.enforceByteLen_(e),e}getJunkBytes_(){let e=[];return this.junk.chunkId?e.concat($e(this.junk.chunkId),Ye(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,r,s){s=s||{},this.clearHeaders(),this.newWavFile_(e,t,i,r,s)}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(r,s,t=Float64Array){let a=[];for(let e=0;e<s;e++)a[e]=new t(r.length/s);for(let i=0;i<s;i++)for(let e=i,t=0;e<r.length;e+=s,t++)a[i][t]=r[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 Ke(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");Xe(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,r,s){s.container||(s.container="RIFF"),this.container=s.container,this.bitDepth=i,r=function(s){let a=[];if(0<s.length)if(s[0].constructor!==Number){a=new Float64Array(s[0].length*s.length);for(let i=0,e=s[0].length,r=0;i<e;i++)for(let e=0,t=s.length;e<t;e++,r++)a[r]=s[e][i]}else a=s;return a}(r),this.updateDataType_();var a=this.dataType.bits/8;this.data.samples=new Uint8Array(r.length*a),Ze(r,this.dataType,this.data.samples,0),this.makeWavHeader_(i,e,t,a,this.data.samples.length,s),this.data.chunkId="data",this.data.chunkSize=this.data.samples.length,this.validateWavHeader_()}makeWavHeader_(e,t,i,r,s,a){"4"==e?this.createADPCMHeader_(e,t,i,r,s,a):"8a"==e||"8m"==e?this.createALawMulawHeader_(e,t,i,r,s,a):-1==Object.keys(this.WAV_AUDIO_FORMATS).indexOf(e)||2<t?this.createExtensibleHeader_(e,t,i,r,s,a):this.createPCMHeader_(e,t,i,r,s,a)}createPCMHeader_(e,t,i,r,s,a){this.container=a.container,this.chunkSize=36+s,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*r*i,blockAlign:t*r,bitsPerSample:parseInt(e,10),cbSize:0,validBitsPerSample:0,dwChannelMask:0,subformat:[]}}createADPCMHeader_(e,t,i,r,s,a){this.createPCMHeader_(e,t,i,r,s,a),this.chunkSize=40+s,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*s}}createExtensibleHeader_(e,t,i,r,s,a){this.createPCMHeader_(e,t,i,r,s,a),this.chunkSize=60+s,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,r,s,a){this.createPCMHeader_(e,t,i,r,s,a),this.chunkSize=40+s,this.fmt.chunkSize=20,this.fmt.cbSize=2,this.fmt.validBitsPerSample=8,this.fact={chunkId:"fact",chunkSize:4,dwSampleLength:s}}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(!it(this.fmt.numChannels,this.fmt.bitsPerSample,this.fmt.sampleRate))throw new Error("Invalid sample rate.")}}class st 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 r={};if(null!==i)for(let e=0,t=this.LIST[i].subChunks.length;e<t;e++)r[this.LIST[i].subChunks[e].chunkId]=this.LIST[i].subChunks[e].value;return r}getLISTIndex(i){for(let e=0,t=this.LIST.length;e<t;e++)if(this.LIST[e].format==i)return e;return null}getTagIndex_(r){let s={LIST:null,TAG:null};for(let i=0,e=this.LIST.length;i<e;i++)if("INFO"==this.LIST[i].format){s.LIST=i;for(let e=0,t=this.LIST[i].subChunks.length;e<t;e++)if(this.LIST[i].subChunks[e].chunkId==r){s.TAG=e;break}break}return s}}class at extends st{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 r=this.cue.points.length;this.cue.points=[];for(let e=0;e<r;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,r){var s=this.getLISTIndex("adtl");if(null!==s)for(let e=0,t=this.LIST[s].subChunks.length;e<t;e++)this.LIST[s].subChunks[e].dwName==i&&(this.LIST[s].subChunks[e].value=r)}getCuePoints_(){let i=[];for(let t=0;t<this.cue.points.length;t++){var r=this.cue.points[t];let e=this.getDataForCuePoint_(r.dwName);e.label=e.value||"",e.dwPosition=r.dwPosition,e.fccChunk=r.fccChunk,e.dwChunkStart=r.dwChunkStart,e.dwBlockStart=r.dwBlockStart,e.dwSampleOffset=r.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,r,s){for(let e=0,t=this.LIST[r].subChunks.length;e<t;e++){var a;this.LIST[r].subChunks[e].dwName==s&&(a=this.LIST[r].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 r=!1;for(let e=0;e<t.length;e++)t[e].dwSampleOffset>i.dwSampleOffset&&!r?(this.setCuePoint_(i,e+1),this.setCuePoint_(t[e],e+2),r=!0):this.setCuePoint_(t[e],r?e+2:e+1);r||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 nt{constructor(e,t,i){var r;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_=(r=i.sincWindow||ot,function(e){return(0!==(t=e)?Math.sin(Math.PI*t)/(Math.PI*t):1)*r(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),r=[this.getTangent_(i,t),this.getTangent_(i+1,t)],s=[this.getClippedInput_(i,t),this.getClippedInput_(i+1,t)],t=(e-=i)*e,i=e*t;return(2*i-3*t+1)*s[0]+(i-2*t+e)*r[0]+(-2*i+3*t)*s[1]+(i-t)*r[1]}sinc(t,i){t=this.scaleFactor_*t;var e=Math.floor(t),r=e-this.sincFilterSize_+1,s=e+this.sincFilterSize_;let a=0;for(let e=r;e<=s;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 ot(e){return Math.exp(-e/2*e/2)}const ht={point:!1,linear:!1,cubic:!0,sinc:!0},lt={IIR:16,FIR:71},ct={IIR:class{constructor(t,i,r){let s=[];for(let e=0;e<t;e++)s.push(this.getCoeffs_({Fs:i,Fc:r,Q:.5/Math.sin(Math.PI/(2*t)*(e+.5))}));this.stages=[];for(let e=0;e<s.length;e++)this.stages[e]={b0:s[e].b[0],b1:s[e].b[1],b2:s[e].b[2],a1:s[e].a[0],a2:s[e].a[1],k:s[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 r=2*Math.PI*e.Fc/e.Fs;return i.alpha=Math.sin(r)/(2*e.Q),i.cw=Math.cos(r),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 r=2*Math.PI*i/e;let s=0;this.filters=[];for(let e=0;e<=t;e++)e-t/2==0?this.filters[e]=r:(this.filters[e]=Math.sin(r*(e-t/2))/(e-t/2),this.filters[e]*=.54-.46*Math.cos(2*Math.PI*e/t)),s+=this.filters[e];for(let e=0;e<=t;e++)this.filters[e]/=s;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 ut(e,t,i,r=null){r=r||{};var s=new Float64Array(e.length*((i-t)/t+1));r.method=r.method||"cubic";var a=new nt(e.length,s.length,{method:r.method,tension:r.tension||0,sincFilterSize:r.sincFilterSize||6,sincWindow:r.sincWindow||void 0,clip:r.clip||"mirror"});if(void 0===r.LPF&&(r.LPF=ht[r.method]),r.LPF){r.LPFType=r.LPFType||"IIR";const n=ct[r.LPFType];t<i?function(i,r,s,a){for(let e=0,t=r.length;e<t;e++)r[e]=a.filter(s.interpolate(e,i));a.reset();for(let e=r.length-1;0<=e;e--)r[e]=a.filter(r[e])}(e,s,a,new n(r.LPForder||lt[r.LPFType],i,t/2)):function(i,e,t,r){for(let e=0,t=i.length;e<t;e++)i[e]=r.filter(i[e]);r.reset();for(let e=i.length-1;0<=e;e--)i[e]=r.filter(i[e]);dt(i,e,t)}(e,s,a,new n(r.LPForder||lt[r.LPFType],t,i/2))}else dt(e,s,a);return s}function dt(i,r,s){for(let e=0,t=r.length;e<t;e++)r[e]=s.interpolate(e,i)}class pt extends at{toRIFF(){var e=new Float64Array(gt(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(gt(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(gt(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",Ie(e),{container:this.correctContainer_()})}fromIMAADPCM(e="16"){let s;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),r=0;for(let e=0;e<a;e++)e&&e%4==0&&(r+=4),t[e]=this.data.samples[r+e],i[e]=this.data.samples[r+e+4];s=[Ae(t,this.fmt.blockAlign/2),Ae(i,this.fmt.blockAlign/2)]}else s=Ae(this.data.samples,this.fmt.blockAlign);this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",s,{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toALaw(){this.assure16Bit_();var e=new Int16Array(gt(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",xe(e),{container:this.correctContainer_()})}fromALaw(e="16"){this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",Pe(this.data.samples),{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toMuLaw(){this.assure16Bit_();var e=new Int16Array(gt(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",Le(e),{container:this.correctContainer_()})}fromMuLaw(e="16"){this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,"16",Fe(this.data.samples),{container:this.correctContainer_()}),"16"!=e&&this.toBitDepth(e)}toBitDepth(e,t=!0){let i=e,r=this.bitDepth;t||("32f"!=e&&(i=this.dataType.bits.toString()),r=""+this.dataType.bits),this.assureUncompressed_();var s=this.getSamples(!0),t=new Float64Array(s.length);we(s,r,t,i),this.fromExisting_(this.fmt.numChannels,this.fmt.sampleRate,e,t,{container:this.correctContainer_()})}toSampleRate(t,i){this.validateResample_(t);var r=this.getSamples();let s=[];if(r.constructor===Float64Array)s=ut(r,this.fmt.sampleRate,t,i);else for(let e=0;e<r.length;e++)s.push(ut(r[e],this.fmt.sampleRate,t,i));this.fromExisting_(this.fmt.numChannels,t,this.bitDepth,s,{container:this.correctContainer_()})}validateResample_(e){if(!it(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,r,s){var a=new at;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,r,s)}}function gt(e,t){let i=e/t;return i%2&&i++,i}class mt extends pt{constructor(e){super(),e&&this.fromBuffer(e)}fromBase64(e){this.fromBuffer(function(i){let r=new Uint8Array(256);for(let e=0;e<ye.length;e++)r[ye.charCodeAt(e)]=e;let e=.75*i.length;"="===i[i.length-1]&&(e--,"="===i[i.length-2]&&e--);let s=new Uint8Array(e);for(let e=0,t=0;e<i.length;e+=4){var a=r[i.charCodeAt(e)],n=r[i.charCodeAt(e+1)],o=r[i.charCodeAt(e+2)],h=r[i.charCodeAt(e+3)];s[t++]=a<<2|n>>4,s[t++]=(15&n)<<4|o>>2,s[t++]=(3&o)<<6|63&h}return s}(e))}toBase64(){return function(t){let i="";for(let e=0;e<t.length;e+=3)i+=ye[t[e]>>2],i+=ye[(3&t[e])<<4|t[e+1]>>4],i+=ye[(15&t[e+1])<<2|t[e+2]>>6],i+=ye[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 ft{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 mt(e);return"4"===t.bitDepth&&t.fromIMAADPCM(),t.toBuffer()}isRawImaAdpcm(){return this.rawData&&"4"===new mt(this.rawData).bitDepth}}class yt{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 wt{constructor(e){this.file=e}asFile(){return new File([this.file],this.file.name,{type:"audio/mp3"})}}const Tt=(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"]);s=["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"];Tt.set("sidec01.mix",s).set("sidec02.mix",s);var bt,vt,s=["reportbug.shp"];Tt.set("sidec01cd.mix",s).set("sidec02cd.mix",s),(s=bt=bt||{})[s.Archive=0]="Archive",s[s.Cdn=1]="Cdn",s[s.Local=2]="Local";class St{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}}(s=vt=vt||{})[s.Battle=0]="Battle",s[s.ManBattle=1]="ManBattle",s[s.FreeForAll=2]="FreeForAll",s[s.Unholy=3]="Unholy",s[s.Cooperative=4]="Cooperative";class _t{constructor(e,t){this.modeIniLoader=t,this.entries=new Map,this.loadIni(e)}loadIni(e){e.getOrderedSections().forEach(r=>{let s=vt[r.name]??vt.Battle;[...r.entries.keys()].forEach(e=>{let t=r.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:s,label:t[0],description:t[1],rulesOverride:e,mapFilter:t[3],randomMapsAllowed:t[4],aiAllowed:i<3,mpDialogSettings:(new St).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 kt{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(/\(\d(-\d)?\)$/)||(e+=` (2${2<t?"-"+t:""})`),e}fromMapFile(e,t){var i=e.readAsString();let r=e.filename;const s=new c(this.extractIniSection("Basic",i)).getSection("Basic");if(!s)throw new Error(`Map "${r}" is missing the [Basic] section`);this.fileName=r,this.uiName="NOSTR:"+(s.getString("Name")||r.replace(/\.[^.]+$/,""));let a=s.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=s.getBool("Official");let n=s.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 Ot{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 kt).fromIni(t,this.gameModes.getAll())})),this.dedupeEntries(),this}add(e){this.manifests.push(e)}addFromMapFile(e){this.add((new kt).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 Ot(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 It{getMatrix(e){return this.matrices[e]}}var At,Ct,Bt=__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 r=i.readInt32(),s=i.readInt32();for(let e=0;e<s;++e){let e=new It;e.name=i.readCString(16),e.matrices=new Array(r),this.sections.push(e)}for(let t=0;t<r;++t)for(let e=0;e<s;++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 Bt.Matrix4).fromArray(i).transpose()}}(s=At=At||{})[s.AutoDetect=0]="AutoDetect",s[s.TiberianSun=1]="TiberianSun",s[s.Firestorm=2]="Firestorm",s[s.RedAlert2=3]="RedAlert2",s[s.YurisRevenge=4]="YurisRevenge";class xt{static getVersion(){return"0.45.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 me;return t.addRootDirectoryHandle(e),t}static async initVfs(e,t){return this.vfs=new de(e,t),xt.iniFiles.setVfs(this.vfs),xt.palettes.setVfs(this.vfs),xt.images.setVfs(this.vfs),xt.voxels.setVfs(this.vfs),xt.voxelAnims.setVfs(this.vfs),xt.tileData.setVfs(this.vfs),xt.sounds.setVfs(this.vfs),xt.themes.setDir(await this.rfs?.findDirectory(xt.rfsSettings.musicDir)),xt.taunts.setDir(await this.rfs?.findDirectory(xt.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(!xt.rules||!xt.art)throw new Error("Rules and art should be loaded first");if(void 0===xt.gameResSource)throw new Error("No gameResSource is set");var t=xt.getActiveEngine();let i;var r,s=xt.getTheaterSettings(t,e);if(xt.gameResSource!==bt.Cdn)for(var a of s.Mixes)await xt.vfs.addMixFile(a);return xt.theaters.has(e)?i=xt.theaters.get(e):(r=xt.getTheaterIni(t,e),t=xt.getTileData(),i=Y.factory(e,r,s,t,xt.palettes),xt.theaters.set(e,i)),xt.activeTheater=i,i}static unloadTheater(e){if(xt.vfs){var t,i=xt.getActiveEngine();for(t of xt.getTheaterSettings(i,e).Mixes)xt.vfs.removeArchive(t)}}static unloadSideMixData(){for(var e of["sidec01.mix","sidec01cd.mix"]){var t,i=Tt.get(e);if(!i)return void console.warn(`Mix "${e}" not found in mix database`);for(t of i)("pal"===t.split(".").pop()?xt.palettes:xt.images).clear(t)}}static getTheaterIni(e,t){t=xt.getTheaterSettings(e,t).TheaterIni;return xt.getIni(t)}static loadRules(){var e=this.getFileNameVariant("rules.ini"),t=this.getFileNameVariant("art.ini");let i=this.iniFiles.get(e),r=this.iniFiles.get(t);if(!i)throw new Error(`Rules "${e}" not found`);if(!r)throw new Error(`Art "${t}" not found`);e=this.iniFiles.get(xt.customRulesFileName),t=this.iniFiles.get(xt.customArtFileName);if(!e)throw new Error(`Rules "${xt.customRulesFileName}" not found`);if(!t)throw new Error(`Art "${xt.customArtFileName}" not found`);xt.art=r.clone().mergeWith(t),xt.rules=i.clone().mergeWith(e),xt.modHash=xt.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,r,s=this.theaterSettings.get(this.getActiveEngine());if(!s)throw new Error(`Unsupported engineType "${this.getActiveEngine()}`);for(t of s)e.push(this.getFileNameVariant(t.TheaterIni));let a=this.getMpModes();for(i of a.getAll())e.push(i.rulesOverride);let n=new oe;for(r of e){if(!this.vfs.fileExists(r))throw new Error(`File ${r} not found`);var o=this.vfs.openFile(r).stream;n.append(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}return n.append(D(this.getVersion())),n.get()}static getRules(){if(!xt.rules)throw new Error("Rules must be loaded first");return xt.rules}static getArt(){if(!xt.art)throw new Error("Art must be loaded first");return xt.art}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 _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,r,t=this.getMpModes();let s=new Ot(t);s.addFromIni(this.getIni(this.getFileNameVariant("missions.pkt")));for(e of this.vfs.listArchives()){var a=e.toLowerCase().replace(/\.[^.]+$/,"")+".pkt";this.vfs.fileExists(a)&&s.addFromIni(new c(this.vfs.openFile(a)))}let n=new Ot(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)),s.addFromIni(i)):this.supportedMapTypes.some(e=>t.endsWith("."+e))&&(r=await this.rfs.openFile(o,!0),n.addFromMapFile(r))}catch(e){console.warn(`Couldn't read file "${o}"`,e)}}return n.sortByName(),s.mergeWith(n),this.mapList=s,s}static getTileData(){return xt.tileData}static getImages(){return xt.images}static getVoxels(){return xt.voxels}static getVoxelAnims(){return xt.voxelAnims}static getPalettes(){return xt.palettes}static getSounds(){return xt.sounds}static getThemes(){return xt.themes}static getTaunts(){return xt.taunts}static getActiveEngine(){return At.RedAlert2}static getLastTheaterType(){return xt.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(xt.rfsSettings.replayDir)}return this.getOrCreateDir(this.rfsSettings.replayDir)}static getModDir(){return this.getOrCreateDir(xt.rfsSettings.modDir)}static getMapDir(){return this.getOrCreateDir(xt.rfsSettings.mapDir)}static async getOrCreateDir(e,t=!1){let i=this.rfs?.getRootDirectory();if(i)return 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.theaters.clear(),this.tileData.clear(),this.voxels.clear(),this.voxelAnims.clear()}}xt.UI_ANIM_SPEED=2,xt.rfsSettings={menuVideoFileName:"ra2ts_l.webm",splashImgFileName:"glsl.png",mapDir:"maps",modDir:"mods",musicDir:"music",tauntsDir:"Taunts",cacheDir:"cache",replayDir:"replays"},xt.supportedMapTypes=["mpr","map"],xt.images=new fe(e=>new r(e)),xt.voxels=new fe(e=>new S(e)),xt.voxelAnims=new fe(e=>new Et(e)),xt.sounds=new fe(e=>new ft(e)),xt.themes=new yt(e=>new wt(e),!1),xt.taunts=new yt(async e=>new ft(new Uint8Array(await e.arrayBuffer()))),xt.iniFiles=new fe(e=>new c(e)),xt.tileData=new fe(e=>new x(e)),xt.palettes=new fe(e=>new G(e)),xt.theaters=new Map,xt.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"}]),xt.customRulesFileName="rulescd.ini",xt.customArtFileName="artcd.ini",xt.customMpModesFileName="mpmodescd.ini",(s=Ct=Ct||{})[s.None=0]="None",s[s.Aircraft=1]="Aircraft",s[s.Building=2]="Building",s[s.Infantry=3]="Infantry",s[s.Overlay=4]="Overlay",s[s.Smudge=5]="Smudge",s[s.Terrain=6]="Terrain",s[s.Vehicle=7]="Vehicle",s[s.Animation=8]="Animation",s[s.Projectile=9]="Projectile",s[s.VoxelAnim=10]="VoxelAnim",s[s.Debris=11]="Debris";class Pt{constructor(e){this.type=e}isStructure(){return this.type===Ct.Building}isVehicle(){return this.type===Ct.Vehicle}isInfantry(){return this.type===Ct.Infantry}isAircraft(){return this.type===Ct.Aircraft}isTerrain(){return this.type===Ct.Terrain}isSmudge(){return this.type===Ct.Smudge}isOverlay(){return this.type===Ct.Overlay}isNamed(){return"name"in this}isTechno(){return"health"in this}}class Nt extends Pt{}class Rt extends Nt{}class Dt extends Rt{constructor(){super(Ct.Building)}}class Mt extends Rt{constructor(){super(Ct.Vehicle)}}class Lt extends Rt{constructor(){super(Ct.Infantry)}}class Ft extends Rt{constructor(){super(Ct.Aircraft)}}class jt extends Nt{constructor(){super(Ct.Terrain)}}class Wt extends Nt{constructor(){super(Ct.Smudge)}}class Ut extends Pt{constructor(){super(Ct.Overlay)}}class Vt{static decode(e,t){t=new Uint8Array(t);return this.decodeInto(e,t),t}static decodeInto(e,t){let i=new w(new DataView(e.buffer,e.byteOffset,e.byteLength)),r=0;for(;;){var s=i.readUint8();if(0==(128&s)){var a=i.readUint8(),n=3+((112&s)>>4);this.replicatePrevious(t,r,r-(((15&s)<<8)+a),n),r+=n}else if(0==(64&s)){n=63&s;if(0==n)return r;t.set(i.readUint8Array(n),r),r+=n}else{s=63&s;if(62==s)for(var o=i.readInt16(),h=i.readUint8(),l=r+o;r<l;r++)t[r]=h;else if(63==s){o=i.readInt16();let e=i.readInt16();if(e>=r)throw new Error(`srcIndex >= destIndex ${e} ${r}`);for(var c=r+o;r<c;r++)t[r]=t[e++]}else{s=3+s;let e=i.readInt16();if(e>=r)throw new Error(`srcIndex >= destIndex ${e} ${r}`);for(var u=r+s;r<u;r++)t[r]=t[e++]}}}}static replicatePrevious(t,i,r,s){if(i<r)throw new Error(`srcIndex > destIndex ${r} ${i}`);if(i-r==1)for(let e=0;e<s;e++)t[i+e]=t[i-1];else for(let e=0;e<s;e++)t[i+e]=t[r+e]}}var zt,Ht,Gt,$t,qt,Zt,Qt,Xt,Yt,Kt,Jt,ei,ti,ii,ri,si,ai,ni,oi=__webpack_require__(251).default;class hi{static decompress(e,t){e={inputBuffer:e,outputBuffer:null},t=oi.decompress(e,{outputSize:t});if(0!==t)throw new Error(`MiniLzo decode failed with code ${t}`);return e.outputBuffer}}class li{static decode(e,t,i=5){t=new Uint8Array(t);return this.decodeInto(e,t,i),t}static decodeInto(e,i,r=5){var t=i.length;let s=0,a=0;for(;a<t;){var n=e[s+1]<<8|e[s];s+=2;var o=e[s+1]<<8|e[s];if(s+=2,!n||!o)break;let t;t=80===r?Vt.decode(e.subarray(s,s+n),o):hi.decompress(e.subarray(s,s+n),o);for(let e=0;e<o;++e)i[a+e]=t[e];s+=n,a+=o}}}function ci(e){switch(e){case zt.Indexed:return 1;case zt.Rgb:return 3;case zt.Rgba:return 4;default:throw new Error(`Unsupported pixel format ${e}`)}}(s=zt=zt||{})[s.Rgb=1]="Rgb",s[s.Rgba=2]="Rgba",s[s.Indexed=3]="Indexed";class ui{constructor(e,t,i,r=zt.Rgba){var s=ci(r);this.data=i||new Uint8Array(s*e*t),this.pixelFormat=r,this.width=e,this.height=t}drawIndexedImage(t,e,i){var r=ci(this.pixelFormat);const s=this.data;var a=this.width,n=r*a,o=r*a*this.height;let h=0+n*i+r*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&&(s[h]=c,3<=r&&(s[h+1]=0,s[h+2]=0),4===r&&(s[h+3]=255)),h+=r,l++}h+=n-t.width*r}}}class di extends ui{constructor(e,t,i){super(e,t,i,zt.Rgb)}}(s=Ht=Ht||{})[s.OnceAny=0]="OnceAny",s[s.OnceAll=1]="OnceAll",s[s.Repeat=2]="Repeat";class pi{read(e){let t=[];for(var[i,r]of e.entries){var s=r.split(",");s.length<3?console.warn(`Invalid tag ${i}=${r}. Skipping.`):(r=Number(s[0]),void 0!==Ht[r]?(s={id:i,repeatType:r,name:s[1],triggerId:s[2]},t.push(s)):console.warn(`Invalid repeat value ${r} for tag id ${i}. Skipping.`))}return t}}(s=Gt=Gt||{})[s.NoEvent=0]="NoEvent",s[s.EnteredBy=1]="EnteredBy",s[s.SpiedBy=2]="SpiedBy",s[s.AttackedByAny=6]="AttackedByAny",s[s.DestroyedByAny=7]="DestroyedByAny",s[s.AnyEvent=8]="AnyEvent",s[s.DestroyedAllUnits=9]="DestroyedAllUnits",s[s.DestroyedAllBuildings=10]="DestroyedAllBuildings",s[s.DestroyedAll=11]="DestroyedAll",s[s.CreditsExceed=12]="CreditsExceed",s[s.ElapsedTime=13]="ElapsedTime",s[s.MissionTimerExpired=14]="MissionTimerExpired",s[s.DestroyedBuildings=15]="DestroyedBuildings",s[s.DestroyedUnits=16]="DestroyedUnits",s[s.NoFactoriesLeft=17]="NoFactoriesLeft",s[s.BuildBuilding=19]="BuildBuilding",s[s.BuildUnit=20]="BuildUnit",s[s.BuildInfantry=21]="BuildInfantry",s[s.BuildAircraft=22]="BuildAircraft",s[s.GlobalIsSet=27]="GlobalIsSet",s[s.GlobalIsCleared=28]="GlobalIsCleared",s[s.DestroyedOrCaptured=29]="DestroyedOrCaptured",s[s.LowPower=30]="LowPower",s[s.DestroyedBridge=31]="DestroyedBridge",s[s.BuildingExists=32]="BuildingExists",s[s.ComesNearWaypoint=34]="ComesNearWaypoint",s[s.LocalIsSet=36]="LocalIsSet",s[s.LocalIsCleared=37]="LocalIsCleared",s[s.FirstDamagedCombat=38]="FirstDamagedCombat",s[s.HalfHealthCombat=39]="HalfHealthCombat",s[s.QuarterHealthCombat=40]="QuarterHealthCombat",s[s.FirstDamagedAny=41]="FirstDamagedAny",s[s.HalfHealthAny=42]="HalfHealthAny",s[s.QuarterHealthAny=43]="QuarterHealthAny",s[s.AttackedByHouse=44]="AttackedByHouse",s[s.AmbientLightBelow=45]="AmbientLightBelow",s[s.AmbientLightAbove=46]="AmbientLightAbove",s[s.ElapsedScenarioTime=47]="ElapsedScenarioTime",s[s.DestroyedOrCapturedOrInfiltrated=48]="DestroyedOrCapturedOrInfiltrated",s[s.PickupCrate=49]="PickupCrate",s[s.PickupCrateAny=50]="PickupCrateAny",s[s.RandomDelay=51]="RandomDelay",s[s.CreditsBelow=52]="CreditsBelow",s[s.SpyEnteringAsHouse=53]="SpyEnteringAsHouse",s[s.SpyEnteringAsInfantry=54]="SpyEnteringAsInfantry",s[s.DestroyedAllUnitsNaval=55]="DestroyedAllUnitsNaval",s[s.DestroyedAllUnitsLand=56]="DestroyedAllUnitsLand",s[s.BuildingNotExists=57]="BuildingNotExists",(s=$t=$t||{})[s.NoAction=0]="NoAction",s[s.FireSale=9]="FireSale",s[s.TextTrigger=11]="TextTrigger",s[s.DestroyTrigger=12]="DestroyTrigger",s[s.ChangeHouse=14]="ChangeHouse",s[s.RevealMap=16]="RevealMap",s[s.RevealAroundWaypoint=17]="RevealAroundWaypoint",s[s.PlaySoundFx=19]="PlaySoundFx",s[s.PlaySpeech=21]="PlaySpeech",s[s.ForceTrigger=22]="ForceTrigger",s[s.TimerStart=23]="TimerStart",s[s.TimerStop=24]="TimerStop",s[s.TimerExtend=25]="TimerExtend",s[s.TimerShorten=26]="TimerShorten",s[s.TimerSet=27]="TimerSet",s[s.GlobalSet=28]="GlobalSet",s[s.GlobalClear=29]="GlobalClear",s[s.DestroyObject=32]="DestroyObject",s[s.AddOneTimeSuperWeapon=33]="AddOneTimeSuperWeapon",s[s.AddRepeatingSuperWeapon=34]="AddRepeatingSuperWeapon",s[s.AllChangeHouse=36]="AllChangeHouse",s[s.ResizePlayerView=40]="ResizePlayerView",s[s.PlayAnimAt=41]="PlayAnimAt",s[s.DetonateWarhead=42]="DetonateWarhead",s[s.ReshroudMap=51]="ReshroudMap",s[s.EnableTrigger=53]="EnableTrigger",s[s.DisableTrigger=54]="DisableTrigger",s[s.CreateRadarEvent=55]="CreateRadarEvent",s[s.LocalSet=56]="LocalSet",s[s.LocalClear=57]="LocalClear",s[s.SellBuilding=60]="SellBuilding",s[s.TurnOffBuilding=61]="TurnOffBuilding",s[s.TurnOnBuilding=62]="TurnOnBuilding",s[s.ApplyOneHundredDamage=63]="ApplyOneHundredDamage",s[s.DestroyTag=70]="DestroyTag",s[s.SetAmbientStep=71]="SetAmbientStep",s[s.SetAmbientRate=72]="SetAmbientRate",s[s.SetAmbientLight=73]="SetAmbientLight",s[s.NukeStrike=95]="NukeStrike",s[s.PlaySoundFxAt=99]="PlaySoundFxAt",s[s.UnrevealAroundWaypoint=101]="UnrevealAroundWaypoint",s[s.LightningStrike=102]="LightningStrike",s[s.TimerText=103]="TimerText",s[s.CreateCrate=108]="CreateCrate",s[s.IronCurtainAt=109]="IronCurtainAt",s[s.EvictOccupiers=111]="EvictOccupiers",s[s.Cheer=113]="Cheer",s[s.StopSoundsAt=116]="StopSoundsAt";class gi{read(e,t,i,r){let s=this.readTriggers(e),{events:a,unknownEventTypes:n}=this.readEvents(t),{actions:o,unknownActionTypes:h}=this.readActions(i),l=[...r.values()],c=new Set(s);for(let t of s.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=s.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=s.indexOf(e);-1!==p&&s.splice(p,1),e=e.attachedTrigger}}}return{triggers:s,unknownEventTypes:n,unknownActionTypes:h}}readTriggers(e){let t=[];for(var[i,r]of e.entries){var s=r.split(",");s.length<8?console.warn(`Invalid trigger ${i}=${r}. Skipping.`):(s={id:i,houseName:s[0],attachedTriggerId:"<none>"!==s[1]?s[1]:void 0,attachedTrigger:void 0,name:s[2],disabled:Boolean(Number(s[3])),difficulties:{easy:Boolean(Number(s[4])),medium:Boolean(Number(s[5])),hard:Boolean(Number(s[6]))},events:[],actions:[],tag:void 0},t.push(s))}return t}readEvents(e){let t=new Map,s=new Set;for(var[a,i]of e.entries){let r=i.split(",");if(r.length<4)console.warn(`Invalid event ${a}=${i}. Skipping.`);else{var n=Number(r.shift());let i=[];for(let t=0;t<n;t++){var o=Number(r.shift()),h=Number(r.shift());let e=r.splice(0,2===h?2:1);void 0!==Gt[o]?(h={triggerId:a,eventIndex:t,type:o,params:[h,...e.map(e=>e||"0")]},i.push(h)):(s.add(o),console.warn(`Unknown event type ${o} for trigger id ${a}. Skipping.`))}t.set(a,i)}}return{events:t,unknownEventTypes:s}}readActions(e){let r=new Map,s=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!==$t[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)):(s.add(o),console.warn(`Unknown action type ${o} for trigger id "${a}". Skipping.`))}r.set(a,t)}}}return{actions:r,unknownActionTypes:s}}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 mi{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 fi{read(e,t){let i=[];for(var[r,s]of e.entries){r={tagId:s,coords:this.readCoords(Number(r),t)};i.push(r)}return i}readCoords(e,t){t=t<4?128:1e3;return{x:e%t,y:Math.floor(e/t)}}}class yi{constructor(e,t){this.name=e,this.value=t}clone(){return new yi(this.name,this.value)}}class wi 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}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 mi).read(e),this.ionLighting=(new mi).read(e,"Ion"),this.ionLighting.forceTint=!0}readTagsAndTriggers(){this.tags=(new pi).read(this.getOrCreateSection("Tags"));var e=this.getOrCreateSection("Triggers"),t=this.getOrCreateSection("Events"),i=this.getOrCreateSection("Actions"),{triggers:e,unknownEventTypes:t,unknownActionTypes:i}=(new gi).read(e,t,i,this.tags);this.triggers=e,this.unknownEventTypes=t,this.unknownActionTypes=i}readCellTags(e){this.cellTags=(new fi).read(this.getOrCreateSection("CellTags"),e)}readVariableNames(){var e,t,i=this.getOrCreateSection("VariableNames");let r=new Map;for([e,t]of i.entries){var s,a,n=Number(e);Number.isNaN(n)?console.warn(`Map [VariableNames] contains non-numeric index "${e}". Skipping.`):([s,a]=t.split(","),a=new yi(s,Boolean(Number(a))),r.set(n,a))}this.variables=r}readTiles(){let e=this.getSection("IsoMapPack5");if(!e)throw new Error("[IsoMapPack5] section not found");var t=M(e.getConcatenatedValues()),i=(2*this.fullSize.width-1)*this.fullSize.height,r=new Uint8Array(11*i+4);li.decodeInto(t,r);let s=new w(r.buffer),a=2*this.fullSize.width-1;var n,o,h,l,r=this.fullSize.height,c=(e,t)=>t*a+e;this.tiles=new Array(a*r);for(let e=this.maxTileNum=0;e<i;e++){var u=s.readUint16(),d=s.readUint16(),p=Math.max(0,s.readInt16());this.maxTileNum=Math.max(this.maxTileNum,p),s.readInt16();var g=s.readUint8(),m=s.readUint8();s.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 r;let e;isNaN(r=parseInt(t,10))||isNaN(e=parseInt(i,10))||(t=Math.floor(e/1e3),i=e-1e3*t,this.waypoints.push({number:r,rx:i,ry:t}))}}readStructures(e){this.structures=[];for(var[,t]of e.entries){t=t.split(",");if(!(t.length<=15)){let e=new Dt;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 Mt;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 Lt;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 Ft;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 jt;e.name=i,e.rx=t%1e3,e.ry=Math.floor(t/1e3),this.terrains.push(e)}}}readOverlays(){this.overlays=[];let t=this.getSection("OverlayPack");if(t){var i=M(t.getConcatenatedValues()),r=new Uint8Array(1<<18);li.decodeInto(i,r,80);let e=this.getSection("OverlayDataPack");if(e){var i=M(e.getConcatenatedValues()),s=new Uint8Array(1<<18);li.decodeInto(i,s,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=r[a];if(255!==n){a=s[a];let e=new Ut;e.id=n,e.value=a,e.rx=o,e.ry=h,this.overlays.push(e)}}}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,r]=e.getArray("Size").map(e=>Number(e)),s=M(t.getConcatenatedValues()),r=new di(i,r);return li.decodeInto(s,r.data),r}}}(s=qt=qt||{})[s.GDI=0]="GDI",s[s.Nod=1]="Nod",s[s.Civilian=2]="Civilian",s[s.Mutant=3]="Mutant";const Ti=(new Map).set("GDI",qt.GDI).set("Nod",qt.Nod).set("Civilian",qt.Civilian).set("Mutant",qt.Mutant),bi=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 vi{constructor(e){this.id=e}readIni(e){this.name=e.name,this.uiName=e.getString("UIName"),this.uiTooltip=e.get("UITooltip")||bi.get(this.name);var t=e.getString("Side");if(!t)throw new Error(`Missing Side for country "${this.name}"`);t=Ti.get(t);if(void 0===t)throw new Error(`Unknown side "${t}" for country "${this.name}"`);this.side=t,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 Si{constructor(e,t,i=-1){this.type=e,this.ini=t,this.index=i,this.parse()}static iniSpeedToLeptonsPerTick(e){return 255*e/64}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===Ct.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}}Si.IMAGE_NONE="none";class _i{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=Si.iniSpeedToLeptonsPerTick(e),this.suicide=this.rules.getBool("Suicide"),this.useSparkParticles=this.rules.getBool("UseSparkParticles"),this.warhead=this.rules.getString("Warhead")}}class ki{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")}}(s=Zt=Zt||{})[s.GenericCombat=0]="GenericCombat",s[s.GenericNonCombat=1]="GenericNonCombat",s[s.DropZone=2]="DropZone",s[s.BaseUnderAttack=3]="BaseUnderAttack",s[s.HarvesterUnderAttack=4]="HarvesterUnderAttack",s[s.EnemyObjectSensed=5]="EnemyObjectSensed";class Oi{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 Ii{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 Ai{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 Ci{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 Bi{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 Ei{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 xi{readIni(e){return 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.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 r=[];for(let e=0;e<t.length;++e)0<i[e]&&r.push({inf:t[e],num:i[e]});return r}getParadropSquads(e){switch(e){case qt.GDI:return this.allyParaDrop;case qt.Nod:return this.sovParaDrop;default:throw new Error(`Unhandled side type "${e}"`)}}}class Pi{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 Ni{}class Ri extends Ni{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 Di extends Ni{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 Mi{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}}(s=Qt=Qt||{})[s.Power=0]="Power",s[s.Factory=1]="Factory",s[s.Barracks=2]="Barracks",s[s.Radar=3]="Radar",s[s.Tech=4]="Tech",s[s.Proc=5]="Proc";const Li=(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 Fi{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.getNumber("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 Ci).readIni(e),this.defaultMirageDisguises=e.getArray("DefaultMirageDisguises"),this.dMisl=(new Di).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 Mi).readIni(e),this.infantryBlinkDisguiseTime=e.getNumber("InfantryBlinkDisguiseTime"),this.lightningStorm=(new Pi).readIni(e),this.lowPowerPenaltyModifier=e.getNumber("LowPowerPenaltyModifier",1),this.minLowPowerProductionSpeed=e.getNumber("MinLowPowerProductionSpeed",.5),this.maxLowPowerProductionSpeed=e.getNumber("MaxLowPowerProductionSpeed",1),this.maximumCheerRate=e.getNumber("MaximumCheerRate"),this.maximumQueuedObjects=e.getNumber("MaximumQueuedObjects"),this.maxWaypointPathLength=e.getNumber("MaxWaypointPathLength"),this.multipleFactory=e.getNumber("MultipleFactory",1),this.normalTargetingDelay=e.getNumber("NormalTargetingDelay"),this.padAircraft=e.getArray("PadAircraft"),this.parachuteMaxFallRate=e.getNumber("ParachuteMaxFallRate"),this.paradrop=(new xi).readIni(e),this.prism=(new Bi).readIni(e),this.purifierBonus=e.getNumber("PurifierBonus"),this.radar=(new Oi).readIni(e),this.refundPercent=e.getNumber("RefundPercent"),this.repair=(new Ii).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 Ei).readIni(e),this.treeStrength=e.getNumber("TreeStrength"),this.v3Rocket=(new Ri).readIni(e),this.veteran=(new Ai).readIni(e),this.wallBuildSpeedCoefficient=e.getNumber("WallBuildSpeedCoefficient"),this.readPrereqCategories(e)}readPrereqCategories(e){for(var[t,i]of Li){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}"`)}}}(s=Xt=Xt||{})[s.Default=0]="Default",s[s.Tunnel=5]="Tunnel",s[s.Railroad=6]="Railroad",s[s.Rock1=7]="Rock1",s[s.Rock2=8]="Rock2",s[s.Water=9]="Water",s[s.Shore=10]="Shore",s[s.Pavement=11]="Pavement",s[s.Dirt=12]="Dirt",s[s.Clear=13]="Clear",s[s.Rough=14]="Rough",s[s.Cliff=15]="Cliff",(s=Yt=Yt||{})[s.Clear=0]="Clear",s[s.Road=1]="Road",s[s.Rock=2]="Rock",s[s.Beach=3]="Beach",s[s.Rough=4]="Rough",s[s.Railroad=5]="Railroad",s[s.Water=6]="Water",s[s.Wall=7]="Wall",s[s.Tiberium=8]="Tiberium",s[s.Cliff=9]="Cliff";const ji=new Map([[Xt.Default,Yt.Clear],[Xt.Clear,Yt.Clear],[Xt.Tunnel,Yt.Cliff],[Xt.Railroad,Yt.Railroad],[Xt.Rock1,Yt.Rock],[Xt.Rock2,Yt.Rock],[Xt.Water,Yt.Water],[Xt.Shore,Yt.Beach],[Xt.Pavement,Yt.Road],[Xt.Dirt,Yt.Road],[Xt.Rough,Yt.Rough],[Xt.Cliff,Yt.Cliff]]);function Wi(e){if(!ji.has(e))throw new Error(`Unknown terrain type ${e}`);return ji.get(e)}(s=Kt=Kt||{})[s.Foot=0]="Foot",s[s.Track=1]="Track",s[s.Wheel=2]="Wheel",s[s.Hover=3]="Hover",s[s.Float=4]="Float",s[s.FloatBeach=5]="FloatBeach",s[s.Amphibious=6]="Amphibious",s[s.Winged=7]="Winged";class Ui{constructor(){this.speedModifiers=new Map}readIni(t){return this.buildable=t.getBool("Buildable",!1),[...t.entries.keys()].forEach(e=>{void 0!==Kt[e]&&this.speedModifiers.set(Kt[e],t.getNumber(e))}),this}getSpeedModifier(e){if(e===Kt.Foot&&0===this.speedModifiers.get(Kt.Track))return 0;let t=this.speedModifiers.get(e);return void 0===t&&(t=1),t}}(s=Jt=Jt||{})[s.None=0]="None",s[s.Gunfire=1]="Gunfire",s[s.Explode=2]="Explode",s[s.ExplodeAlt=3]="ExplodeAlt",s[s.Fire=4]="Fire",s[s.Electro=5]="Electro",s[s.HeadExplode=6]="HeadExplode",s[s.Nuke=7]="Nuke";class Vi{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.cellSpread=this.rules.getNumber("CellSpread"),this.conventional=this.rules.getBool("Conventional"),this.culling=this.rules.getBool("Culling"),this.electricAssault=this.rules.getBool("ElectricAssault"),this.emEffect=this.rules.getBool("EMEffect"),this.infDeath=this.rules.getNumber("InfDeath",Jt.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 zi extends Si{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=Si.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")}}(s=ei=ei||{})[s.Green=0]="Green",s[s.Yellow=1]="Yellow",s[s.White=2]="White",s[s.Red=3]="Red",s[s.Blue=4]="Blue",(s=ti=ti||{})[s.Statue=0]="Statue",s[s.Aircraft=1]="Aircraft",s[s.Chrono=2]="Chrono",s[s.Hover=3]="Hover",s[s.Infantry=4]="Infantry",s[s.Jumpjet=5]="Jumpjet",s[s.Missile=6]="Missile",s[s.Ship=7]="Ship",s[s.Vehicle=8]="Vehicle";const Hi=new Map([["{4A582746-9839-11d1-B709-00A024DDAFD1}",ti.Aircraft],["{4A582747-9839-11d1-B709-00A024DDAFD1}",ti.Chrono],["{4A582742-9839-11d1-B709-00A024DDAFD1}",ti.Hover],["{4A582744-9839-11d1-B709-00A024DDAFD1}",ti.Infantry],["{92612C46-F71F-11d1-AC9F-006008055BB5}",ti.Jumpjet],["{B7B49766-E576-11d3-9BD9-00104B972FE8}",ti.Missile],["{2BEA74E1-7CCA-11d3-BE14-00104B62A16C}",ti.Ship],["{4A582741-9839-11d1-B709-00A024DDAFD1}",ti.Vehicle]]),Gi=new Map([[ti.Infantry,Kt.Foot],[ti.Ship,Kt.Float],[ti.Hover,Kt.Hover],[ti.Jumpjet,Kt.Winged],[ti.Aircraft,Kt.Winged],[ti.Missile,Kt.Winged]]);(s=ii=ii||{})[s.Amphibious=0]="Amphibious",s[s.AmphibiousCrusher=1]="AmphibiousCrusher",s[s.AmphibiousDestroyer=2]="AmphibiousDestroyer",s[s.Crusher=3]="Crusher",s[s.CrusherAll=4]="CrusherAll",s[s.Destroyer=5]="Destroyer",s[s.Fly=6]="Fly",s[s.Infantry=7]="Infantry",s[s.InfantryDestroyer=8]="InfantryDestroyer",s[s.Normal=9]="Normal",s[s.Subterranean=10]="Subterranean",s[s.Water=11]="Water",(s=ri=ri||{})[s.None=0]="None",s[s.Flak=1]="Flak",s[s.Plate=2]="Plate",s[s.Light=3]="Light",s[s.Medium=4]="Medium",s[s.Heavy=5]="Heavy",s[s.Wood=6]="Wood",s[s.Steel=7]="Steel",s[s.Concrete=8]="Concrete",s[s.Special_1=9]="Special_1",s[s.Special_2=10]="Special_2",(s=si=si||{})[s.Primary=0]="Primary",s[s.Secondary=1]="Secondary",s[s.DeathWeapon=2]="DeathWeapon",(s=ai=ai||{})[s.FASTER=0]="FASTER",s[s.STRONGER=1]="STRONGER",s[s.FIREPOWER=2]="FIREPOWER",s[s.SCATTER=3]="SCATTER",s[s.ROF=4]="ROF",s[s.SIGHT=5]="SIGHT",s[s.SELF_HEAL=6]="SELF_HEAL",s[s.CLOAK=7]="CLOAK",s[s.EXPLODES=8]="EXPLODES",s[s.RADAR_INVISIBLE=9]="RADAR_INVISIBLE",s[s.SENSORS=10]="SENSORS",s[s.FEARLESS=11]="FEARLESS",s[s.C4=12]="C4",s[s.GUARD_AREA=13]="GUARD_AREA",s[s.CRUSHER=14]="CRUSHER",(s=ni=ni||{})[s.None=0]="None",s[s.Normal=1]="Normal",s[s.Strong=2]="Strong";var $i,qi,Zi,Qi,Xi,Yi=__webpack_require__(949);(s=$i=$i||{})[s.Combat=0]="Combat",s[s.Tech=1]="Tech",s[s.Resource=2]="Resource",s[s.Power=3]="Power",(s=qi=qi||{})[s.None=0]="None",s[s.BuildingType=1]="BuildingType",s[s.InfantryType=2]="InfantryType",s[s.UnitType=3]="UnitType",s[s.NavalUnitType=4]="NavalUnitType",s[s.AircraftType=5]="AircraftType";class Ki extends Si{parse(){super.parse(),this.owner=this.ini.getArray("Owner");var e=this.ini.getNumber("AIBasePlanningSide");this.aiBasePlanningSide=-1!==e&&void 0!==qt[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",$i,$i.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");let t=this.ini.getString("SuperWeapon");this.superWeapon=t&&"none"!==t.toLowerCase()?t:void 0,this.chargedAnimTime=this.ini.getNumber("ChargedAnimTime");var i=this.ini.getBool("Naval");this.naval=i,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===Ct.Building),this.clickRepairable=this.ini.getBool("ClickRepairable",this.type===Ct.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",qi,qi.None),this.factory===qi.UnitType&&i&&(this.factory=qi.NavalUnitType),this.weaponsFactory=this.ini.getBool("WeaponsFactory"),this.helipad=this.ini.getBool("Helipad"),this.hospital=this.ini.getBool("Hospital"),this.landTargeting=this.ini.getNumber("LandTargeting"),this.navalTargeting=this.ini.getNumber("NavalTargeting"),this.tooBigToFitUnderBridge=this.ini.getBool("TooBigToFitUnderBridge",this.type===Ct.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.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");let r=this.ini.getString("Primary");r&&"none"!==r.toLowerCase()&&(this.primary=r);let s=this.ini.getString("Secondary");s&&"none"!==s.toLowerCase()&&(this.secondary=s);let a=this.ini.getString("ElitePrimary");a&&"none"!==a.toLowerCase()&&(this.elitePrimary=a);let n=this.ini.getString("EliteSecondary");n&&"none"!==n.toLowerCase()&&(this.eliteSecondary=n),this.weaponCount=this.ini.getNumber("WeaponCount"),this.deathWeapon=this.ini.getString("DeathWeapon"),this.deathWeaponDamageModifier=this.ini.getNumber("DeathWeaponDamageModifier",1),this.occupyWeapon=this.ini.getString("OccupyWeapon"),this.eliteOccupyWeapon=this.ini.getString("EliteOccupyWeapon"),this.veteranAbilities=new Set(this.ini.getEnumArray("VeteranAbilities",ai)),this.eliteAbilities=new Set([...this.veteranAbilities,...this.ini.getEnumArray("EliteAbilities",ai)]),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=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 o=this.ini.getBool("Landable");this.landable=o,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;e=this.ini.getString("Locomotor");if(e?(i=Hi.get(e))?this.locomotor=i:(console.warn(`Object rules "${this.name}" has invalid Locomotor "${e}"`),this.locomotor=ti.Statue):this.locomotor=ti.Statue,this.locomotor!==ti.Statue){let e=Gi.get(this.locomotor);void 0===e&&(this.type===Ct.Aircraft||this.consideredAircraft?e=Kt.Winged:this.type===Ct.Vehicle?e=this.crusher?Kt.Track:Kt.Wheel:this.type===Ct.Infantry&&(e=Kt.Foot)),this.speedType=this.ini.getEnum("SpeedType",Kt,e)}this.speed=Si.iniSpeedToLeptonsPerTick(this.ini.getNumber("Speed")),this.movementZone=this.ini.getEnum("MovementZone",ii,ii.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",si.Secondary),this.undeployDelay=this.ini.getNumber("UndeployDelay"),this.fraidycat=this.ini.getBool("Fraidycat",!1),this.isHuman=!this.ini.getBool("NotHuman"),this.organic=this.type===Ct.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!==Ct.Building),this.crewed=this.ini.getBool("Crewed"),this.parasiteable=this.ini.getBool("Parasiteable",this.type!==Ct.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",ni,ni.None,!0),this.pip=this.ini.getEnum("Pip",ei,ei.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===Ct.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(Ki.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===Ct.Aircraft&&!o)&&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!==Ct.Aircraft),this.leadershipRating=this.ini.getNumber("LeadershipRating",5),this.allowedToStartInMultiplayer=this.ini.getBool("AllowedToStartInMultiplayer",!0),this.rot=Si.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=Si.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");o=this.ini.getNumberArray("DamageSmokeOffset",void 0,[0,0,0]);this.damageSmokeOffset=new Yi.Vector3(o[0],o[2]/Math.SQRT2,o[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}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.ini.getString(`Weapon${e+1}`)||void 0}getEliteWeaponAtIndex(e){return this.ini.getString(`EliteWeapon${e+1}`)||void 0}}Ki.MAX_SIGHT=11,Ki.MAGIC_SPEED_MULT=.65;class Ji extends Si{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",Yt,Yt.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)}}(s=Zi=Zi||{})[s.All=7]="All",s[s.Right=1]="Right",s[s.Left=2]="Left",s[s.Bottom=4]="Bottom";class er extends Si{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",Zi.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",Zi.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===Zi.All)return e;let r=[];for(t of e)!function(e,t){switch(e){case 0:case 1:return 1;case 2:return 0!=(t&Zi.Right);case 3:return 0!=(t&Zi.Left);case 4:return 0!=(t&Zi.Bottom);default:throw new Error(`Invalid subCell "${e}`)}}(t,i)||r.push(t);return r}}class tr extends Si{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 ir extends Si{parse(){super.parse(),this.damage=this.ini.getNumber("Damage"),this.damageRadius=this.ini.getNumber("DamageRadius"),this.duration=this.ini.getNumber("Duration"),this.elasticity=U(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 rr{create(e,t,i){switch(e){case Ct.Aircraft:case Ct.Building:case Ct.Infantry:case Ct.Vehicle:return new Ki(e,t,i);case Ct.Overlay:return new Ji(e,t,i);case Ct.Terrain:return new er(e,t,i);case Ct.Smudge:return new tr(e,t,i);case Ct.VoxelAnim:return new ir(e,t,i);default:return new Si(e,t,i)}}}class sr{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 ar{readIni(e){return this.value=e.getNumber("Value"),this}}class nr{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 or{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 hr{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")}}(s=Qi=Qi||{})[s.MultiMissile=0]="MultiMissile",s[s.IronCurtain=1]="IronCurtain",s[s.LightningStorm=2]="LightningStorm",s[s.ChronoSphere=3]="ChronoSphere",s[s.ChronoWarp=4]="ChronoWarp",s[s.ParaDrop=5]="ParaDrop",s[s.AmerParaDrop=6]="AmerParaDrop";class lr{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",Qi,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",Qi,void 0),this.uiName=e.getString("UIName"),this.weaponType=e.getString("WeaponType")||void 0,this}}class cr{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}}(s=Xi=Xi||{})[s.Cheer=0]="Cheer",s[s.UnitDeployUndeploy=1]="UnitDeployUndeploy",s[s.WeaponFire=2]="WeaponFire",s[s.ObjectDestroy=3]="ObjectDestroy",s[s.ObjectSpawn=4]="ObjectSpawn",s[s.ObjectUnspawn=5]="ObjectUnspawn",s[s.ObjectMorph=6]="ObjectMorph",s[s.ObjectLiftOff=7]="ObjectLiftOff",s[s.ObjectLand=8]="ObjectLand",s[s.ObjectCrashing=9]="ObjectCrashing",s[s.ObjectDisguiseChange=10]="ObjectDisguiseChange",s[s.ObjectCloakChange=11]="ObjectCloakChange",s[s.ObjectAttacked=12]="ObjectAttacked",s[s.ShipSubmergeChange=13]="ShipSubmergeChange",s[s.BridgeRepair=14]="BridgeRepair",s[s.BuildStatusChange=15]="BuildStatusChange",s[s.BuildingPlace=16]="BuildingPlace",s[s.BuildingFailedPlace=17]="BuildingFailedPlace",s[s.BuildingSell=18]="BuildingSell",s[s.BuildingRepairFull=19]="BuildingRepairFull",s[s.BuildingCapture=20]="BuildingCapture",s[s.BuildingInfiltration=21]="BuildingInfiltration",s[s.BuildingGarrison=22]="BuildingGarrison",s[s.BuildingEvacuate=23]="BuildingEvacuate",s[s.BuildingRepairStart=24]="BuildingRepairStart",s[s.UnitRepairStart=25]="UnitRepairStart",s[s.UnitRepairFinish=26]="UnitRepairFinish",s[s.UnitRecycle=27]="UnitRecycle",s[s.InflictDamage=28]="InflictDamage",s[s.HealthChange=29]="HealthChange",s[s.WarheadDetonate=30]="WarheadDetonate",s[s.PlayerDefeated=31]="PlayerDefeated",s[s.PlayerResigned=32]="PlayerResigned",s[s.DeployNotAllowed=33]="DeployNotAllowed",s[s.PowerChange=34]="PowerChange",s[s.PowerLow=35]="PowerLow",s[s.PowerRestore=36]="PowerRestore",s[s.RadarOnOff=37]="RadarOnOff",s[s.ObjectOwnerChange=38]="ObjectOwnerChange",s[s.RadarEvent=39]="RadarEvent",s[s.InsufficientFunds=40]="InsufficientFunds",s[s.RallyPointChange=41]="RallyPointChange",s[s.PrimaryFactoryChange=42]="PrimaryFactoryChange",s[s.FactoryProduceUnit=43]="FactoryProduceUnit",s[s.ObjectTeleport=44]="ObjectTeleport",s[s.AllianceChange=45]="AllianceChange",s[s.UnitPromote=46]="UnitPromote",s[s.EnterTransport=47]="EnterTransport",s[s.LeaveTransport=48]="LeaveTransport",s[s.EnterObject=49]="EnterObject",s[s.EnterTile=50]="EnterTile",s[s.SuperWeaponReady=51]="SuperWeaponReady",s[s.SuperWeaponActivate=52]="SuperWeaponActivate",s[s.LightningStormManifest=53]="LightningStormManifest",s[s.LightningStormCloud=54]="LightningStormCloud",s[s.CratePickup=55]="CratePickup",s[s.PingLocation=56]="PingLocation",s[s.StalemateDetect=57]="StalemateDetect",s[s.TriggerSoundFx=58]="TriggerSoundFx",s[s.TriggerStopSoundFx=59]="TriggerStopSoundFx",s[s.TriggerEva=60]="TriggerEva",s[s.TriggerAnim=61]="TriggerAnim",s[s.TriggerText=62]="TriggerText",s[s.TimerExpire=63]="TimerExpire";class ur{constructor(e,t,i,r){this.target=e,this.player=t,this.source=i,this.tile=r,this.type=Xi.CratePickup}}var dr,pr=__webpack_require__(949);class gr{static init(e){gr.worldOrigin=e}static worldToScreen(e,t){if(!gr.worldOrigin)throw new Error("Coords not initialized with world origin");return{x:(e-=gr.worldOrigin.x)-(t-=gr.worldOrigin.y)-1,y:(e+t-1)/2}}static screenToWorld(e,t){if(!gr.worldOrigin)throw new Error("Coords not initialized with world origin");return{x:(e+2*t)/2+1+gr.worldOrigin.x,y:(2*t-e)/2+gr.worldOrigin.y}}static tileToWorld(e,t){return{x:e*gr.ISO_TILE_SIZE,y:t*gr.ISO_TILE_SIZE}}static worldToTile(e,t){return{x:Math.floor(e/gr.ISO_TILE_SIZE),y:Math.floor(t/gr.ISO_TILE_SIZE)}}static worldToLeptons(e){return e*gr.LEPTONS_PER_TILE/gr.ISO_TILE_SIZE}static leptonsToWorld(e){return e/gr.LEPTONS_PER_TILE*gr.ISO_TILE_SIZE}static vecWorldToLeptons(e){return e.clone().multiplyScalar(gr.LEPTONS_PER_TILE/gr.ISO_TILE_SIZE)}static vecLeptonsToWorld(e){return e.clone().multiplyScalar(gr.ISO_TILE_SIZE/gr.LEPTONS_PER_TILE)}static vecWorldToScreen(e){let t=gr.worldToScreen(e.x,e.z);return t.y-=e.y/gr.zScale,t}static vecWorldToGround(e){return new pr.Vector2(e.x,e.z)}static vecGroundToWorld(e){return new pr.Vector3(e.x,0,e.y)}static tileHeightToWorld(e){return e*(gr.ISO_TILE_SIZE/2)*gr.zScale+1}static tileHeightToScreen(e){return e*(gr.ISO_TILE_SIZE/2)+1/gr.zScale}static worldToTileHeight(e){return(e-1)/gr.zScale/(gr.ISO_TILE_SIZE/2)}static tileToScreen(e,t){t=gr.tileToWorld(e,t);return gr.worldToScreen(t.x,t.y)}static tile3dToWorld(e,t,i){t=gr.tileToWorld(e,t),i=gr.tileHeightToWorld(i);return new pr.Vector3(t.x,i,t.y)}static tile3dToScreen(e,t,i){t=gr.tileToWorld(e,t);let r=gr.worldToScreen(t.x,t.y);return r.y-=i*(gr.ISO_TILE_SIZE/2)+1/gr.zScale,r}static screenTileToScreen(e,t){return{x:e*gr.ISO_TILE_SIZE,y:t*gr.ISO_TILE_SIZE/2}}static screenToScreenTile(e,t){return{x:e/gr.ISO_TILE_SIZE,y:t/(gr.ISO_TILE_SIZE/2)}}static screenTileToWorld(e,t){t=gr.screenTileToScreen(e,t);return gr.screenToWorld(t.x,t.y)}static getScreenTileSize(){return{width:gr.tileToScreen(1,0).x-gr.tileToScreen(0,1).x,height:gr.tileToScreen(1,1).y-gr.tileToScreen(0,0).y}}static screenDistanceToWorld(e,t){var i=gr.screenToWorld(0,0),t=gr.screenToWorld(e,t);return{x:t.x-i.x,y:t.y-i.y}}static screenDistanceToLeptons(e,t){var{x:e,y:t}=gr.screenDistanceToWorld(e,t);return{x:e/gr.ISO_TILE_SIZE*gr.LEPTONS_PER_TILE,y:t/gr.ISO_TILE_SIZE*gr.LEPTONS_PER_TILE}}static getWorldTileSize(){return gr.ISO_TILE_SIZE}}function mr(e){return[Yt.Water,Yt.Beach].includes(e)?dr.Water:dr.Ground}gr.ISO_TILE_SIZE=30,gr.LEPTONS_PER_TILE=256,gr.ISO_CAMERA_ALPHA=Math.PI/6,gr.ISO_CAMERA_BETA=Math.PI/4,gr.COS_ISO_CAMERA_BETA=Math.cos(gr.ISO_CAMERA_BETA),gr.zScale=Math.cos(gr.ISO_CAMERA_BETA)/Math.cos(gr.ISO_CAMERA_ALPHA),(s=dr=dr||{})[s.Ground=0]="Ground",s[s.Air=1]="Air",s[s.Water=2]="Water";var fr,yr=__webpack_require__(949);const wr=e=>void 0!==e.position,Tr=e=>void 0!==e.addScalar;class br{constructor(e){this.tileOccupation=e}isInWeaponRange(e,t,i,r,s){var a=s??e;if(i.rules.limboLaunch&&2<Math.abs((wr(a)?a.position.tileElevation+a.tile.z:a.z)-(wr(t)?t.position.tileElevation+t.tile.z:t.z)))return!1;var{minRange:s,range:r}=this.computeWeaponRangeVsTarget(a,t,i,r);return i.rules.cellRangefinding?this.isInTileRange(a,t,s,r):e.isUnit()&&e.rules.movementZone===ii.Fly?this.isInRange2(a,t,s,r):this.isInRange3(a,t,s,r)}computeWeaponRangeVsTarget(e,t,i,r){let s=0;var a,n;return!wr(t)||!t.isBuilding()||i.projectileRules.arcing||i.projectileRules.vertical||i.warhead.rules.ivanBomb||1<(n=t.getFoundation()).width&&1<n.height&&(s+=Math.ceil(Math.min(n.width,n.height)/2)),!i.projectileRules.subjectToElevation||i.projectileRules.arcing&&!wr(t)||(a=wr(e)?e.tile.z+e.tileElevation:e.z,(n=wr(t)?t.tile.z+t.tileElevation:t.z)<a&&(s+=r.elevationModel.getBonus(a,n))),i.projectileRules.isAntiAir&&wr(e)&&e.isTechno()&&wr(t)&&t.isUnit()&&t.zone===dr.Air&&(s+=e.rules.airRangeBonus),{minRange:i.minRange,range:i.range+s}}isInRange(e,t,i,r,s=!1){return s?this.isInTileRange(e,t,i,r):e.isUnit()&&e.rules.movementZone===ii.Fly?this.isInRange2(e,t,i,r):this.isInRange3(e,t,i,r)}isInRange3(e,t,i,r){return V(this.distance3(e,t)/gr.ISO_TILE_SIZE,i,r)}isInRange2(e,t,i,r){return V(this.distance2(e,t)/gr.ISO_TILE_SIZE,i,r)}distance3(e,t){let i=wr(e)?e.position.worldPosition:Tr(e)?e:gr.tile3dToWorld(e.rx+.5,e.ry+.5,e.z);t=wr(t)?t.position.worldPosition:Tr(t)?t:gr.tile3dToWorld(t.rx+.5,t.ry+.5,t.z);return i.distanceTo(t)}distance2(e,t){let i=wr(e)?new yr.Vector2(e.position.worldPosition.x,e.position.worldPosition.z):Tr(e)?new yr.Vector2(e.x,e.z):new yr.Vector2(e.rx+.5,e.ry+.5).multiplyScalar(gr.ISO_TILE_SIZE);t=wr(t)?new yr.Vector2(t.position.worldPosition.x,t.position.worldPosition.z):Tr(t)?new yr.Vector2(t.x,t.z):new yr.Vector2(t.rx+.5,t.ry+.5).multiplyScalar(gr.ISO_TILE_SIZE);return i.distanceTo(t)}isInTileRange(e,t,i,r){return V(this.tileDistance(e,t),i,r)}tileDistance(e,t){var i,e=wr(e)?this.tileOccupation.calculateTilesForGameObject(e.tile,e):Array.isArray(e)?e:[e],r=wr(t)?this.tileOccupation.calculateTilesForGameObject(t.tile,t):Array.isArray(t)?t:[t];let s=new yr.Vector2,a=new yr.Vector2,n=Number.POSITIVE_INFINITY;for(i of e)for(var o of r){s.set(i.rx,i.ry),a.set(o.rx,o.ry);o=s.distanceTo(a);o<=n&&(n=o)}return n}}const vr=e=>"name"in e;(s=fr=fr||{})[s.Brutal=0]="Brutal",s[s.Medium=1]="Medium",s[s.Easy=2]="Easy";var Sr,_r,kr,Or,Ir,Ar,Cr,Br,Er;(new Map).set(fr.Easy,"GUI:AIDummy");class xr{static computeGameSpeed(e){let t;return t=6===e?60:5===e?45:60/(6-e),t/xr.BASE_TICKS_PER_SECOND}}xr.BASE_TICKS_PER_SECOND=15;class Pr{constructor(e,t,i,r,s,a,n,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.foundation=r,this.maxDistance=a,this.predicate=n,this.checkBounds=o,this.distance=s,this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){var r=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t))return t};do{var s=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>=s;e--)i=r(e,o),i&&(yield i);for(t=o-1;t>=a;t--)i=r(n,t),i&&(yield i);for(e=s;e<n;e++)i=r(e,a),i&&(yield i);for(t=1+a;t<o;t++)i=r(s,t),i&&(yield i)}else this.predicate(this.startTile)&&(yield this.startTile)}while(this.distance++,this.distance<=this.maxDistance)}}(s=Sr=Sr||{})[s.Armor=0]="Armor",s[s.Firepower=1]="Firepower",s[s.HealBase=2]="HealBase",s[s.Money=3]="Money",s[s.Reveal=4]="Reveal",s[s.Speed=5]="Speed",s[s.Veteran=6]="Veteran",s[s.Unit=7]="Unit",s[s.Invulnerability=8]="Invulnerability",s[s.IonStorm=9]="IonStorm",s[s.Gas=10]="Gas",s[s.Tiberium=11]="Tiberium",s[s.Pod=12]="Pod",s[s.Cloak=13]="Cloak",s[s.Darkness=14]="Darkness",s[s.Explosion=15]="Explosion",s[s.ICBM=16]="ICBM",s[s.Napalm=17]="Napalm",s[s.Squad=18]="Squad",(_r=_r||{}).onTick=Symbol(),(kr=kr||{}).onChange=Symbol();class Nr{constructor(e){this.target=e,this.type=Xi.SuperWeaponReady}}(s=Or=Or||{})[s.Charging=0]="Charging",s[s.Paused=1]="Paused",s[s.Ready=2]="Ready";class Rr{constructor(e,t,i,r=!1){this.name=e,this.rules=t,this.owner=i,this.oneTimeOnly=r,this.status=Or.Charging,this.isGift=!1,this.rechargeTicks=60*t.rechargeTime*xr.BASE_TICKS_PER_SECOND,this.chargeTicks=this.rechargeTicks,r&&(this.status=Or.Ready,this.chargeTicks=0)}update(e){0<this.chargeTicks&&this.status!==Or.Paused&&(this.chargeTicks--,0===this.chargeTicks&&(this.status=Or.Ready,e.events.dispatch(new Nr(this))))}pauseTimer(){this.status=Or.Paused}resumeTimer(){this.status=0<this.chargeTicks?Or.Charging:Or.Ready}resetTimer(){this.chargeTicks=this.rechargeTicks,this.status===Or.Ready&&(this.status=Or.Charging)}getTimerSeconds(){return this.chargeTicks/xr.BASE_TICKS_PER_SECOND}getChargeProgress(){return(this.rechargeTicks-this.chargeTicks)/this.rechargeTicks}}(s=Ir=Ir||{})[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Finished=2]="Finished";class Dr{constructor(e,t,i){this.type=e,this.owner=t,this.tile=i,this.status=Ir.NotStarted}onStart(e){}onTick(e){return!0}}(s=Ar=Ar||{}).onPowerLow=Symbol(),s.onPowerRestore=Symbol(),s.onPowerChange=Symbol(),(Cr=Cr||{}).onActivate=Symbol();class Mr{constructor(e,t,i,r,s){this.target=e,this.owner=t,this.atTile=i,this.atTile2=r,this.noSfxWarning=s,this.type=Xi.SuperWeaponActivate}}(s=Br=Br||{})[s.None=0]="None",s[s.Guard=1]="Guard",s[s.Prone=2]="Prone",s[s.Deployed=3]="Deployed",s[s.Paradrop=4]="Paradrop",s[s.Cheer=5]="Cheer",(s=Er=Er||{})[s.NotStarted=0]="NotStarted",s[s.Running=1]="Running",s[s.Finished=2]="Finished",s[s.Cancelling=3]="Cancelling",s[s.Cancelled=4]="Cancelled";class Lr{constructor(){this.status=Er.NotStarted,this.children=[],this.cancellable=!0,this.useChildTargetLines=!1,this.blocking=!0,this.waitingForChildrenToFinish=!1,this.preventOpportunityFire=!0,this.preventLanding=!0}isRunning(){return this.status===Er.Running}isCancelling(){return this.status===Er.Cancelling}setCancellable(e){return this.cancellable=e,this}onStart(e){}onEnd(e){}cancel(){if(this.cancellable)if(this.status===Er.Running)this.status=Er.Cancelling,this.children.length&&this.children.forEach(e=>e.cancel());else if(this.status===Er.NotStarted&&(this.status=Er.Cancelled,this.children.length))throw new Error("Should't have any children before starting a task")}getTargetLinesConfig(e){}}function Fr(t,i){for(let e=t.length-1;0<=e;e--)if(i(t[e],e,t))return e;return-1}class jr extends Lr{constructor(e){super(),this.ticks=e}onTick(){return!!this.isCancelling()||!(0<this.ticks--)}}class Wr{constructor(e){this.map=e}findPositions(e,r,s){let a=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 n=[],o=this.findCenterTile([...i.objects]);i.objects.forEach(t=>{var i=this.map.tiles.getByMapCoords(r.rx+t.tile.rx-o.rx,r.ry+t.tile.ry-o.ry),e=i?.onBridgeLandType?this.map.tileOccupation.getBridgeOnTile(i):void 0;if(!i||!this.map.mapBounds.isWithinBounds(i)||a.has(i)&&!this.tileHasRoom(t,a.get(i))||t.rules.movementZone===ii.Fly&&!t.rules.balloonHover&&!this.map.terrain.getPassableSpeed(i,Kt.Amphibious,!!e)||t.rules.movementZone!==ii.Fly&&!this.isEligibleTile(i,e,s,r))n.push(t);else{let e=a.get(i);void 0===e&&(e=[],a.set(i,e)),e.push(t)}}),t.forEach(e=>n.push(...e.objects));let h=new Pr(this.map.tiles,this.map.mapBounds,r,{width:1,height:1},1,5,()=>!0),l;for(;n.length&&(l=h.getNextTile());){var c=n[0],u=this.map.tileOccupation.getBridgeOnTile(l);if((!a.has(l)||this.tileHasRoom(c,a.get(l)))&&((c.rules.movementZone!==ii.Fly||c.rules.balloonHover||this.map.terrain.getPassableSpeed(l,Kt.Amphibious,!!u))&&(c.rules.movementZone===ii.Fly||this.isEligibleTile(l,u,s,r)))){let e=a.get(l);void 0===e&&(e=[],a.set(l,e)),e.push(n.shift())}}let d=new Map;if(a.forEach((e,t)=>{e.forEach(e=>d.set(e,t))}),n.forEach(e=>d.set(e,r)),d.size!==e.length)throw new Error("We should have computed a number of positions equal to the number of input objects");return d}tileHasRoom(e,t){if(e.isInfantry()){if(t.find(e=>!e.isInfantry()))return!1;e=e.rules.movementZone===ii.Fly?1:3;return t.filter(e=>e.isInfantry()).length>=e?!1:!0}return!t.length}isEligibleTile(e,t,i,r){return i?.isHighBridge()||t?.isHighBridge()?e.z+(t?.tileElevation??0)===r.z+(i?.tileElevation??0):!(!i&&!t)||Math.abs(e.z-r.z)<2}clusterObjects(e){let s=new Map;e.forEach(e=>{var t=e.tile.rx+"_"+e.tile.ry;s.set(t,[...s.get(t)||[],e])});let t=[],a=new Set(e);for(;a.size;){let e=new Set,r=[];var i=[...a][0].tile;for(s.get(i.rx+"_"+i.ry).forEach(e=>{r.push(e)});r.length;){var n=r.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=s.get(n.tile.rx+i+"_"+(n.tile.ry+t));e&&e.length&&e.forEach(e=>{a.has(e)&&(a.delete(e),r.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 r=this.map.tiles.getByMapCoords(t,i);if(!r&&(r=e.find(e=>Math.abs(e.tile.rx-t)<=1&&Math.abs(e.tile.ry-i)<=1)?.tile,!r))throw new Error("At least one adjacent object should have been found");return r}}var Ur=__webpack_require__(949);function Vr(e,t){var i=e.center;return Math.pow(i.x-t.x,2)+Math.pow(i.y-t.y,2)<=Math.pow(e.radius,2)}function zr(e,t){let i=new Ur.Box2(new Ur.Vector2(e.x,e.y),new Ur.Vector2(e.x+e.width,e.y+e.height));return i.containsPoint(new Ur.Vector2(t.x,t.y))}function Hr(e,t){var i=Ur.Math.degToRad(Math.floor(t)),t=z(Math.cos(i),10),i=z(Math.sin(i),10);return e.set(e.x*t-e.y*i,e.x*i+e.y*t)}function Gr(e){let t=Ur.Math.radToDeg(e.angle());return Math.abs(Math.abs(t)-Math.floor(Math.abs(t))-.5)<.01&&(t+=.01),Math.round(t)}function $r(e,t){t=2*Math.acos(Math.abs(Ur.Math.clamp(e.dot(t),-1,1)));let i=Ur.Math.radToDeg(t);return Math.abs(Math.abs(i)-Math.floor(Math.abs(i))-.5)<.01&&(i+=.01),Math.round(i)}function qr(e,t){e=Gr(e),t=Gr(t);return Math.min((e-t+360)%360,(t-e+360)%360)}function Zr(e,t){return $r(Qr(e),Qr(t))}function Qr(e){return(new Ur.Quaternion).setFromRotationMatrix((new Ur.Matrix4).lookAt(e,new Ur.Vector3(0,0,0),new Ur.Vector3(0,1,0)))}function Xr(e,t,i){var r,s=e.length(),a=Qr(t),n=Qr(e);r=i,0!==(a=$r(t=n,i=a))&&(a=Math.min(1,r/a),function(e,t,i){if(0===i)return;if(1===i)return e.copy(t);var r=e.x,s=e.y,a=e.z,n=e.w;let o=n*t.w+r*t.x+s*t.y+a*t.z;o<0?(e.w=-t.w,e.x=-t.x,e.y=-t.y,e.z=-t.z,o=-o):e.copy(t);if(1<=o)return e.w=n,e.x=r,e.y=s,e.z=a;var h=1-o*o;if(h<=Number.EPSILON){var l=1-i;return e.w=l*n+i*e.w,e.x=l*r+i*e.x,e.y=l*s+i*e.y,e.z=l*a+i*e.z,e.normalize(),e.onChangeCallback()}t=Math.sqrt(h),l=z(Math.atan2(t,o),10),h=z(Math.sin((1-i)*l),10)/t,t=z(Math.sin(i*l),10)/t;e.w=n*h+e.w*t,e.x=r*h+e.x*t,e.y=s*h+e.y*t,e.z=a*h+e.z*t,e.onChangeCallback()}(t,i,a)),e.set(0,0,1).applyQuaternion(n).setLength(s)}class Yr extends Lr{constructor(e,t){super(),this.game=e,this.fromDirection=t,this.resolved=!1,this.chainPushIssued=!1}onEnd(e){e.moveTrait.collisionState=Gs.Resolved}onTick(i){if(this.timeoutTicks=void 0===this.timeoutTicks?0:this.timeoutTicks+1,40<this.timeoutTicks||this.resolved||this.isCancelling())return!0;let r=this.game.map,t=new Wr(r),s=i.onBridge?r.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=Hr(this.fromDirection.clone(),e).round(),o=r.tiles.getByMapCoords(i.tile.rx+Math.sign(o.x),i.tile.ry+Math.sign(o.y));if(o&&r.mapBounds.isWithinBounds(o)&&(n=!s||s.isHighBridge()?r.tileOccupation.getBridgeOnTile(o):void 0,i.rules.movementZone===ii.Fly||!r.terrain.findObstacles({tile:o,onBridge:n},i).length&&t.isEligibleTile(o,n,s,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 Us(this.game,a,!!n,{closeEnoughTiles:0,strictCloseEnough:!0})),!1);{if(this.chainPushIssued)return this.children.push(new jr(5)),!1;let t=r.tiles.getByMapCoords(i.tile.rx+Math.sign(this.fromDirection.x),i.tile.ry+Math.sign(this.fromDirection.y));if(!t||!r.mapBounds.isWithinBounds(t))return!0;n=!s||s.isHighBridge()?r.tileOccupation.getBridgeOnTile(t):void 0;let e=r.tileOccupation.getGroundObjectsOnTile(t).filter(e=>e.isUnit()&&e.owner===i.owner&&e.tile===t&&e.onBridge===!!n&&!(e.isInfantry()&&e.stance===Br.Paradrop)&&!(e.isAircraft()&&e.missileSpawnTrait));return e.find(e=>e.moveTrait.collisionState===Gs.Waiting||e.unitOrderTrait.hasTasks())?(this.children.push(new jr(5)),i.moveTrait.collisionState=Gs.Waiting,i.moveTrait.moveState=zs.PlanMove,!1):(e.forEach(e=>{e.unitOrderTrait.addTask(new Yr(this.game,this.fromDirection))}),this.children.push(new jr(1)),i.moveTrait.collisionState=Gs.Waiting,i.moveTrait.moveState=zs.PlanMove,!(this.chainPushIssued=!0))}}}const Kr=__webpack_require__(163);var Jr=__webpack_require__(949);class es{constructor(e){this.game=e,this.ignoresTerrain=!0,this.distanceToWaypoint=new Jr.Vector2}onNewWaypoint(e,t){}tick(e,t,i,r){if(r)return{distance:new Jr.Vector3,done:!0};this.distanceToWaypoint.copy(t).sub(e.position.getMapPosition());r=this.game.rules.general;return r.chronoTrigger&&(r=(t=this.distanceToWaypoint.length())<r.chronoRangeMinimum?r.chronoMinimumDelay:t/r.chronoDistanceFactor,e.warpedOutTrait.setTimed(r,!1,this.game)),{distance:new Jr.Vector3(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!0,isTeleport:!0}}}var ts=__webpack_require__(949);class is{static tick(e,t,i){if(e===t)return{facing:e,delta:0};var r=(e-t+360)%360,s=(t-e+360)%360;if(Math.min(r,s)<i)return{facing:t,delta:0};i*=s<=r?1:-1;return{facing:(e+i+360)%360,delta:i}}static fromMapCoords(e){return(-Gr(e)-90+720)%360}static toMapCoords(e){return Hr(new ts.Vector2(10,0),is.toWorldDeg(e)).normalize()}static toWorldDeg(e){return-(e+90)}}class rs extends Lr{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}=is.tick(e.direction,this.direction,t);return e.direction=i,e.spinVelocity=t,!1}}var ss,as=__webpack_require__(949);(s=ss=ss||{})[s.None=0]="None",s[s.Start=1]="Start",s[s.Normal=2]="Normal",s[s.End=3]="End",s[s.Single=4]="Single";class ns{constructor(e){this.game=e,this.hasMomentum=!1,this.moveOnCurve=!1,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=ss.None}selectNextWaypoint(i,r){if(this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==ss.End?ss.Normal:ss.Start,this.initialPosition=i.position.getMapPosition(),this.currentWaypointType!==ss.Start?i.moveTrait.speedPenalty=0:this.currentSpeed=0,1<r.length){var s=r[r.length-1],a=r[r.length-2],e=new as.Vector2(s.tile.rx-i.tile.rx,s.tile.ry-i.tile.ry),n=Math.abs(Gr(e)-Gr(new as.Vector2(a.tile.rx-s.tile.rx,a.tile.ry-s.tile.ry)));if(!Math.abs(is.fromMapCoords(e)-i.direction)&&0<n&&n<90&&this.hasMomentum){this.moveOnCurve=!0,this.currentWaypointType=2===r.length?this.currentWaypointType===ss.Start?ss.Single:ss.End:ss.Normal;let e=this.initialPosition;i=new as.Vector2(s.tile.rx+.5,s.tile.ry+.5).multiplyScalar(gr.LEPTONS_PER_TILE);let t=new as.Vector2(a.tile.rx+.5,a.tile.ry+.5).multiplyScalar(gr.LEPTONS_PER_TILE);n=e.clone().lerp(i,.5),s=t.clone().lerp(i,.5);return this.steerCurve=new as.CurvePath,this.steerCurve.add(new as.LineCurve(e,n)),this.steerCurve.add(new as.QuadraticBezierCurve(n,i,s)),this.steerCurve.add(new as.LineCurve(s,t)),this.lastPosition=e,a}}else this.currentWaypointType=this.currentWaypointType===ss.Start?ss.Single:ss.End;return this.hasMomentum=!0,this.moveOnCurve=!1,r[r.length-1]}onNewWaypoint(e,t,i){let r=(new as.Vector2).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=this.moveOnCurve?this.steerCurve.getLength():r.length();t=is.fromMapCoords(r);if(t!==e.direction&&(this.pointTurretToTarget(e,i),!this.moveOnCurve))return e.moveTrait.velocity.set(0,0,0),[new rs(t)]}tick(i,r,s){this.pointTurretToTarget(i,s);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;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,this.carryOverDistance&&(a=this.carryOverDistance);var n=i.position.getMapPosition();let o;if(this.moveOnCurve){var s=this.steerCurve.getLength(),h=Math.min(this.distanceTravelled+a,s);this.carryOverDistance=Math.max(0,this.distanceTravelled+a-s),this.distanceTravelled=h;let e=this.steerCurve.getPointAt(this.distanceTravelled/s),t=this.steerCurve.getTangentAt(this.distanceTravelled/s);h=t.clone().setLength(a);i.moveTrait.velocity.set(h.x,0,h.y).multiplyScalar(gr.getWorldTileSize()/gr.LEPTONS_PER_TILE);var s=i.rules.rot,{facing:h,delta:s}=is.tick(i.direction,is.fromMapCoords(t),s);i.direction=h,i.spinVelocity=s;s=this.lastPosition;this.lastPosition=e.clone(),o=e.sub(s)}else{let e=(new as.Vector2).copy(r).sub(n);n=Math.min(e.length(),a);o=e.clone().setLength(n);let t=o.clone();this.carryOverDistance&&t.add(gr.vecWorldToGround(gr.vecWorldToLeptons(i.moveTrait.velocity))),i.moveTrait.velocity.set(t.x,0,t.y).multiplyScalar(gr.getWorldTileSize()/gr.LEPTONS_PER_TILE),this.distanceTravelled+=n,this.carryOverDistance=Math.max(0,a-e.length())}return{distance:new as.Vector3(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 r=t.position.getMapPosition();let e=(new as.Vector2).copy(i).sub(r);e.length()&&(r=is.fromMapCoords(e),t.turretTrait.desiredFacing=r)}}applyAcceleration(e,t,i,r){if(this.currentWaypointType===ss.Single)return.3*i;if(this.currentWaypointType!==ss.End)return Math.min(t+e.rules.accelerationFactor*i,i);return this.moveOnCurve&&this.currentWaypointType===ss.End&&(r=r<=.5?0:2*(r-.5)),as.Math.lerp(1,i,1-r)}}var os=__webpack_require__(949);class hs{constructor(e){this.game=e,this.currentMoveDirection=new os.Vector2,this.distanceToWaypoint=new os.Vector2,this.carryOverDistance=0}onNewWaypoint(e,t){this.currentMoveDirection.copy(t).sub(e.position.getMapPosition());t=is.fromMapCoords(this.currentMoveDirection);t!==e.direction&&(e.direction=t)}onWaypointUpdate(e,t){this.onNewWaypoint(e,t)}tick(e,t){let i=e.moveTrait.baseSpeed*Ki.MAGIC_SPEED_MULT;e.stance===Br.Prone&&(i/=2),e.isPanicked&&(i*=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,i*=r,this.carryOverDistance&&(i=this.carryOverDistance,this.carryOverDistance=0),this.distanceToWaypoint.copy(t).sub(e.position.getMapPosition());t=this.distanceToWaypoint.clone().setLength(i);e.moveTrait.velocity.set(t.x,0,t.y).multiplyScalar(gr.getWorldTileSize()/gr.LEPTONS_PER_TILE);t=Math.min(this.distanceToWaypoint.length(),i);return this.carryOverDistance=Math.max(0,i-this.distanceToWaypoint.length()),this.distanceToWaypoint.setLength(t),{distance:new os.Vector3(this.distanceToWaypoint.x,0,this.distanceToWaypoint.y),done:!this.distanceToWaypoint.length()||!!this.carryOverDistance}}}var ls,cs=__webpack_require__(949);(s=ls=ls||{})[s.None=0]="None",s[s.Start=1]="Start",s[s.Normal=2]="Normal",s[s.End=3]="End",s[s.Single=4]="Single";class us{constructor(e){this.hoverRules=e,this.currentSpeed=0,this.distanceTravelled=0,this.carryOverDistance=0,this.currentWaypointType=ls.None,this.nextWaypointDir=new cs.Vector2}selectNextWaypoint(e,t){var i;return this.currentWaypointType=this.currentWaypointType&&this.currentWaypointType!==ls.End?ls.Normal:ls.Start,this.initialPosition=e.position.getMapPosition(),this.currentWaypointType===ls.Start&&(this.currentSpeed=0),t.length<=1?(this.currentWaypointType=this.currentWaypointType===ls.Start?ls.Single:ls.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 r=(new cs.Vector2).copy(t).sub(this.initialPosition);this.distanceTravelled=0,this.totalDistanceToTravel=r.length();t=this.maxSpeed=e.moveTrait.baseSpeed*Ki.MAGIC_SPEED_MULT,e=60*this.hoverRules.acceleration*xr.BASE_TICKS_PER_SECOND;this.acceleration=t/e;e=60*this.hoverRules.brake*xr.BASE_TICKS_PER_SECOND;this.deceleration=t/e}tick(e,t){var i=e.position.getMapPosition();let r=t.clone().sub(i);t=r.length(),i=this.maxSpeed;this.currentWaypointType===ls.Single?this.currentSpeed=i/2:this.currentWaypointType===ls.End?(s=this.computeBrakeDistance(this.currentSpeed,this.deceleration),this.totalDistanceToTravel-this.distanceTravelled<=s&&(this.currentSpeed=Math.max(0,this.currentSpeed-this.deceleration))):this.currentSpeed=Math.min(this.currentSpeed+this.acceleration,i);var s=is.fromMapCoords(r),i=is.fromMapCoords(this.nextWaypointDir);let a=s,n=e.rules.rot;this.currentWaypointType===ls.Normal&&s!==i&&(s=(o=qr(this.nextWaypointDir,is.toMapCoords(e.direction)))/n,s=Math.max(this.currentSpeed*s,this.totalDistanceToTravel),this.totalDistanceToTravel-this.distanceTravelled<=s&&(a=i,n=o/((this.totalDistanceToTravel-this.distanceTravelled)/this.currentSpeed)));var o=is.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=r.clone().setLength(o),c=l.clone();return this.carryOverDistance&&c.add(gr.vecWorldToGround(gr.vecWorldToLeptons(e.moveTrait.velocity))),e.moveTrait.velocity.set(c.x,0,c.y).multiplyScalar(gr.ISO_TILE_SIZE/gr.LEPTONS_PER_TILE),this.distanceTravelled+=o,this.carryOverDistance=Math.max(0,h-t),{distance:new cs.Vector3(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)}}var ds=__webpack_require__(949);class ps{static computeInterceptPoint(e,t,i,r){let s=e.clone().sub(i);var a=r.length(),e=t*t-a*a,t=2*s.dot(r),a=-s.dot(s);if(t*t-4*e*a<0)return new ds.Vector3;e=(-t+Math.sqrt(t*t-4*e*a))/(2*e);return r.clone().multiplyScalar(e).add(i)}static computeTurnCircle(e,t,i,r){r/=ds.Math.degToRad(Math.abs(i));let s=Hr(t.clone(),90*-Math.sign(i));return{center:isFinite(r)?s.setLength(r).add(e):e.clone(),radius:r}}}class gs{constructor(e){this.gameObject=e,this.type=Xi.ObjectLiftOff}}class ms{constructor(e){this.gameObject=e,this.type=Xi.ObjectLand}}var fs=__webpack_require__(949);class ys{constructor(e){this.game=e,this.allowOutOfBounds=!0,this.currentMoveDir=new fs.Vector2,this.currentHorizSpeed=0}static tickStationary(t,i){if(t.zone===dr.Air){var r=t.tile.onBridgeLandType?i.map.tileOccupation.getBridgeOnTile(t.tile):void 0,s=!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)!==dr.Water&&0<i.map.terrain.getPassableSpeed(t.tile,Kt.Foot,!!t.tile.onBridgeLandType)&&0===i.map.terrain.findObstacles({tile:t.tile,onBridge:r},t).length);let e;e=s?(a=t.tile.z+(r?.tileElevation??0),gr.worldToLeptons(gr.tileHeightToWorld(a))):(n=t.tile.z+i.map.getGroundObjectsOnTile(t.tile).filter(e=>!(e.isInfantry()&&e.stance===Br.Paradrop)).reduce((e,t)=>Math.max(e,t.tileElevation+t.art.height),0),gr.worldToLeptons(gr.tileHeightToWorld(n))+t.rules.jumpjetHeight);var a,n,o=gr.worldToLeptons(t.position.worldPosition.y);e!==o?(a=t.rules.jumpjetClimb,n=Math.abs(e-o),n=Math.sign(e-o)*Math.min(a,n),t.position.moveByLeptons3(new fs.Vector3(0,n,0))):s&&(t.zone=dr.Ground,t.onBridge=!!r,i.events.dispatch(new ms(t)))}}static tickCrash(e,t,i){var r=2*e.rules.jumpjetCrash;return e.direction=(e.direction-6+360)%360,new fs.Vector3(0,-r,0)}onNewWaypoint(e,t,i){this.currentMoveDir=is.toMapCoords(e.direction),this.cancelDestLeptons=void 0}tick(t,e,i,r){if(t.zone!==dr.Air&&(t.onBridge=!1,t.zone=dr.Air,this.game.events.dispatch(new gs(t))),r){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 s=t.position.getMapPosition();let a=i.clone().sub(s),n=this.findTilesToCheckForBlockers(t.tile,s,this.currentMoveDir,a.length());var o=n.map(e=>e.z+this.game.map.getGroundObjectsOnTile(e).filter(e=>!(e.isDestroyed||e.isInfantry()&&e.stance===Br.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=gr.worldToLeptons(gr.tileHeightToWorld(o)),c=gr.worldToLeptons(gr.tileHeightToWorld(o+h)),u=gr.worldToLeptons(t.position.worldPosition.y),d=is.fromMapCoords(a),p=a.length()<t.rules.jumpjetSpeed;let g=0;l<=u&&!p&&({facing:T,delta:r}=is.tick(t.direction,d,t.rules.jumpjetTurnRate),g=r,t.direction=T,this.currentMoveDir.copy(is.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()):((s=T||g?ps.computeTurnCircle(s,this.currentMoveDir,Math.sign(g)*t.rules.jumpjetTurnRate,T):void 0)&&Vr(s,i)?(w=0,this.currentHorizSpeed=0):w=T,!1));let b;b=p?(f=!0,a):this.currentMoveDir.clone().setLength(w);let v=new fs.Vector3(b.x,y,b.y);p=v.clone();return t.moveTrait.velocity.copy(p).multiplyScalar(gr.ISO_TILE_SIZE/gr.LEPTONS_PER_TILE),{distance:v,done:f&&m}}findTilesToCheckForBlockers(e,t,i,r){r=i.clone().setLength(Math.min(r,gr.LEPTONS_PER_TILE)).add(t).multiplyScalar(1/gr.LEPTONS_PER_TILE).floor(),t=this.game.map.tiles.getByMapCoords(r.x,r.y);if(!t||t===e)return[e];r=Math.sign(t.rx-e.rx),t=Math.sign(t.ry-e.ry);let s=[e],a;return r&&(a=this.game.map.tiles.getByMapCoords(e.rx+r,e.ry),a&&s.push(a)),t&&(a=this.game.map.tiles.getByMapCoords(e.rx,e.ry+t),a&&s.push(a)),r&&t&&(a=this.game.map.tiles.getByMapCoords(e.rx+r,e.ry+t),a&&s.push(a)),s}computeCancelDest(e,t){var i=t.clone().multiplyScalar(1/gr.LEPTONS_PER_TILE).floor().multiplyScalar(gr.LEPTONS_PER_TILE),i=t.clone().sub(i);return new fs.Vector2(e.rx,e.ry).multiplyScalar(gr.LEPTONS_PER_TILE).add(i)}}var ws,Ts,bs=__webpack_require__(949);(s=ws=ws||{})[s.Boost=0]="Boost",s[s.Midcourse=1]="Midcourse",s[s.Terminal=2]="Terminal";class vs{constructor(e,t){this.game=e,this.missileRules=t,this.flightPhase=ws.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=gr.vecWorldToLeptons(gr.tile3dToWorld(i.tile.rx+.5,i.tile.ry+.5,t)),this.cruiseAltitude=gr.worldToLeptons(gr.tileHeightToWorld(t))+this.missileRules.altitude,i}onNewWaypoint(e,t,i){}tick(i,e,t){let r=gr.vecWorldToLeptons(i.position.worldPosition),s=this.targetPosition.clone().sub(r);i.zone!==dr.Air&&(i.onBridge=!1,i.zone=dr.Air,this.game.events.dispatch(new gs(i)));let a;var n;a=this.currentVelocity?(n=i.rules.speed*Ki.MAGIC_SPEED_MULT,Math.min(this.currentVelocity.length()+this.missileRules.acceleration,n)):(p=this.missileRules.acceleration,this.missileRules.lazyCurve?this.currentVelocity=new bs.Vector3(s.x,0,s.z):this.currentVelocity=gr.vecGroundToWorld(is.toMapCoords(i.direction)),Xr(this.currentVelocity,new bs.Vector3(this.currentVelocity.x,1e8,this.currentVelocity.z),i.pitch),p),this.currentVelocity.setLength(a);let o=!1;switch(this.flightPhase){case ws.Boost:if(!(gr.worldToLeptons(i.position.worldPosition.y)>=this.cruiseAltitude)){o=!1;break}this.flightPhase=ws.Midcourse;case ws.Midcourse:var h,l=new bs.Vector2(s.x,s.z).length();if(!this.missileRules.lazyCurve){Xr(this.currentVelocity,new bs.Vector3(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)),Xr(this.currentVelocity,new bs.Vector3(s.x,this.currentVelocity.y,s.z),i.rules.rot),i.direction=is.fromMapCoords(gr.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*Zr(this.currentVelocity,new bs.Vector3(this.currentVelocity.x,0,this.currentVelocity.z)),l/(r.y-this.targetPosition.y)<1&&(this.flightPhase=ws.Terminal);break}this.flightPhase=ws.Terminal;var c=r.clone().add(this.currentVelocity.clone().setLength(l/3/z(Math.cos(bs.Math.degToRad(i.pitch)),10))),u=this.targetPosition.clone().lerp(r,.15).setY(c.y);this.descentCurve=new bs.CubicBezierCurve3(r,c,u,this.targetPosition);case ws.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(r));u=t.clone().setY(0);i.pitch=Math.sign(t.y-u.y)*Zr(u,t),o=1<=(this.descentTravelled+c)/d}else{Xr(this.currentVelocity,s,i.rules.rot),i.direction=is.fromMapCoords(gr.vecWorldToGround(this.currentVelocity)),i.pitch=Math.sign(this.currentVelocity.y)*Zr(this.currentVelocity,new bs.Vector3(this.currentVelocity.x,0,this.currentVelocity.z));d=s.length()-c;(d<a||d<1)&&(this.currentVelocity.copy(s.clone().addScalar(-c)),o=!0)}break;default:throw new Error(`Unhandled flight phase "${this.flightPhase}"`)}var p=gr.vecLeptonsToWorld(r.clone().add(this.currentVelocity));return this.game.map.isWithinHardBounds(p)?(i.moveTrait.velocity.copy(this.currentVelocity).multiplyScalar(gr.ISO_TILE_SIZE/gr.LEPTONS_PER_TILE),{distance:this.currentVelocity,done:o}):(this.game.destroyObject(i),{done:!0,distance:new bs.Vector3})}}class Ss extends jr{constructor(e){super(Math.floor(xr.BASE_TICKS_PER_SECOND*e*60))}}class _s extends Lr{constructor(e){super(),this.cb=e}onTick(e){return this.cb(e),!0}}(Ts=Ts||{}).onTick=Symbol();var ks,Os=__webpack_require__(949);(s=ks=ks||{})[s.Idle=0]="Idle",s[s.MoveToQueueingTile=1]="MoveToQueueingTile",s[s.WaitForTurn=2]="WaitForTurn",s[s.MoveToDock=3]="MoveToDock",s[s.Docking=4]="Docking",s[s.Docked=5]="Docked";class Is extends Lr{constructor(e,t){super(),this.game=e,this.target=t,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.dockingStatus=ks.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=ks.MoveToDock:void 0!==(t=this.target.dockTrait.getFirstAvailableDockNumber())?(this.target.dockTrait.reserveDockAt(e,t),this.dockingStatus=ks.MoveToDock):this.target.helipadTrait?this.cancel():this.dockingStatus=ks.MoveToQueueingTile}onEnd(e){this.dockingStatus!==ks.Docked&&this.target.isSpawned&&(this.target.dockTrait.undockUnit(e),this.target.dockTrait.unreserveDockForUnit(e)),this.dockingStatus=ks.Idle}onTick(e){if(this.isCancelling())return!0;if(!this.isValidTarget(this.target,e))return!0;if(this.dockingStatus===ks.MoveToQueueingTile){var t=this.findReachableQueueingTile(e);if(!t)return!0;if(e.tile!==t)return this.children.push(new Us(this.game,t,!1,{closeEnoughTiles:5}),new _s(()=>{e.moveTrait.lastMoveResult===Hs.Fail?this.cancel():e.moveTrait.lastMoveResult===Hs.CloseEnough&&(this.game.map.tileOccupation.isTileOccupiedBy(e.tile,this.target)||(this.dockingStatus=ks.WaitForTurn))})),!1;this.dockingStatus=ks.WaitForTurn}if(this.dockingStatus===ks.WaitForTurn){var i=this.target.dockTrait.getFirstAvailableDockNumber();if(void 0===i)return this.children.push(new Ss(1/60)),!1;this.target.dockTrait.reserveDockAt(e,i),this.dockingStatus=ks.MoveToDock}if(this.dockingStatus===ks.MoveToDock){var r=this.target.dockTrait.getReservedDockForUnit(e),i=this.target.dockTrait.getDockTile(r),r=gr.vecWorldToGround(this.target.dockTrait.getDockOffset(r)).add(this.target.position.getMapPosition()).sub(new Os.Vector2(i.rx,i.ry).multiplyScalar(gr.LEPTONS_PER_TILE));if(e.tile!==i)return this.children.push(new Us(this.game,i,!1,{targetOffset:e.isAircraft()?r:void 0,closeEnoughTiles:0,strictCloseEnough:!0}),new _s(()=>{e.moveTrait.lastMoveResult===Hs.Fail&&this.cancel()})),this.game.afterTick(()=>e.unitOrderTrait[Ts.onTick](e,this.game)),!1;this.dockingStatus=ks.Docking}if(this.dockingStatus!==ks.Docking)return!1;r=this.target.dockTrait.getReservedDockForUnit(e);return this.target.dockTrait.unreserveDockForUnit(e),this.target.dockTrait.dockUnitAt(e,r),e.isAircraft()&&e.airportBoundTrait&&this.target.helipadTrait&&(e.airportBoundTrait.preferredAirport=this.target),this.dockingStatus=ks.Docked,!0}isValidTarget(e,t){return e.isSpawned&&this.game.areFriendly(e,t)}findReachableQueueingTile(t){var e=this.target.getFoundation(),e=new Os.Vector2(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 Pr(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===ii.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)}}var As,Cs,Bs=__webpack_require__(949);(s=As=As||{})[s.None=0]="None",s[s.CircleStrafe=1]="CircleStrafe",s[s.HoverStrafe=2]="HoverStrafe";class Es{constructor(e){this.game=e,this.allowOutOfBounds=!0,this.lastDestLeptons=new Bs.Vector2,this.currentMoveDir=new Bs.Vector2,this.currentHorizSpeed=0,this.maneuverType=As.None,this.deceleratingToTurn=!1}static tickStationary(s,a){if(s.zone===dr.Air){var n=s.tile.onBridgeLandType?a.map.tileOccupation.getBridgeOnTile(s.tile):void 0;let e=s.rules.landable&&!s.unitOrderTrait.getCurrentTask()?.preventLanding,i=s.spawnLinkTrait?.getParent();e&&i?e=!((!i.isUnit()||!i.onBridge)&&n||i.tile!==s.tile):e&&!s.airportBoundTrait&&(e=a.map.getTileZone(s.tile)!==dr.Water&&0<a.map.terrain.getPassableSpeed(s.tile,Kt.Foot,!!s.tile.onBridgeLandType)&&0===a.map.terrain.findObstacles({tile:s.tile,onBridge:n},s).length);let r;if(e){let e=s.airportBoundTrait?.preferredAirport?.dockTrait;var o=e?.isDocked(s)||e?.hasReservedDockForUnit(s);if(!s.airportBoundTrait||o){var h=o?0:270;if(s.direction!==h)return void(s.direction=is.tick(s.direction,h,s.rules.rot).facing)}if(s.airportBoundTrait){let e=s.airportBoundTrait.preferredAirport;if(!e?.dockTrait?.isDocked(s))return e?.dockTrait?.getAvailableDockCount()||(e=s.airportBoundTrait.findAvailableAirport(s),s.airportBoundTrait.preferredAirport=e,e&&(h=e.dockTrait.getFirstAvailableDockNumber(),e.dockTrait.reserveDockAt(s,h))),void(e?(s.unitOrderTrait.addTask(new Is(a,e)),s.unitOrderTrait[Ts.onTick](s,a)):s.crashableTrait.crash(void 0))}let t;t=i?i.tile.z+i.tileElevation:s.tile.z+(n?.tileElevation??0),r=gr.worldToLeptons(gr.tileHeightToWorld(t))}else{var t=s.tile.z+(n?.tileElevation??0),l=s.rules.flightLevel??a.rules.general.flightLevel;r=gr.worldToLeptons(gr.tileHeightToWorld(t))+l}t=gr.worldToLeptons(s.position.worldPosition.y);r!==t?(l=Math.abs(r-t),l=Math.sign(r-t)*Math.min(30,l),s.position.moveByLeptons3(new Bs.Vector3(0,l,0))):e&&(s.zone=dr.Ground,i?i.airSpawnTrait.storeAircraft(s,a):s.onBridge=!!n,a.events.dispatch(new ms(s)))}}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=gr.vecWorldToGround(gr.vecWorldToLeptons(e.moveTrait.velocity));return new Bs.Vector3(e.x,-30,e.y)}onNewWaypoint(e,t,i){this.currentHorizSpeed=gr.worldToLeptons(gr.vecWorldToGround(e.moveTrait.velocity).length()),this.cancelDestLeptons=void 0}tick(t,e,i,r){if(r){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 s=t.position.getMapPosition();let a=i.clone().sub(s);var n=a.length();this.lastDestLeptons.equals(i)||(this.lastDestLeptons.copy(i),r?this.maneuverType=As.HoverStrafe:t.zone===dr.Air&&this.currentHorizSpeed<5?this.maneuverType=n>gr.LEPTONS_PER_TILE?As.CircleStrafe:As.HoverStrafe:this.maneuverType=As.None,this.deceleratingToTurn=!1),t.zone!==dr.Air&&(t.onBridge=!1,t.zone=dr.Air,this.game.events.dispatch(new gs(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,r=gr.worldToLeptons(gr.tileHeightToWorld(h))+l,o=gr.worldToLeptons(t.position.worldPosition.y),c=is.fromMapCoords(a);t.direction===c&&this.maneuverType===As.None&&n<=gr.LEPTONS_PER_TILE?this.maneuverType=As.HoverStrafe:t.direction===c&&this.maneuverType===As.CircleStrafe&&(this.maneuverType=As.None);let u;switch(this.maneuverType){case As.HoverStrafe:if(t.attackTrait?.currentTarget){let e=gr.vecWorldToGround(gr.vecWorldToLeptons(t.attackTrait.currentTarget.getWorldCoords()));u=is.fromMapCoords(e.sub(s))}else u=t.airportBoundTrait?.preferredAirport?.dockTrait?.hasReservedDockForUnit(t)?0:270;break;case As.CircleStrafe:case As.None:u=c;break;default:throw new Error(`Unknown maneuver type "${this.maneuverType}`)}var{facing:d,delta:p}=is.tick(t.direction,u,t.rules.rot);t.direction=d,t.roll=Math.sign(p)*t.rules.pitchAngle;let g;switch(this.maneuverType){case As.HoverStrafe:g=c;break;case As.CircleStrafe:g=(d-90*Math.sign(p)+360)%360;break;case As.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}=is.tick(this.thrustFacing,g,h);this.thrustFacing=l,this.currentMoveDir.copy(is.toMapCoords(this.thrustFacing));let m=!1,f=0,y=0;let w=!0;r!==o&&(b=Math.abs(r-o),f=Math.sign(r-o)*Math.min(30,b),w=b<=30);let T=t.rules.speed*Ki.MAGIC_SPEED_MULT;n<=gr.LEPTONS_PER_TILE&&this.maneuverType!==As.CircleStrafe&&(T=Bs.Math.lerp(1,T/2,Math.sqrt(n/gr.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?ps.computeTurnCircle(s,this.currentMoveDir,Math.sign(h)*t.rules.rot,b):void 0,(0===b||Vr(h,i))&&(this.maneuverType===As.HoverStrafe||n>gr.LEPTONS_PER_TILE)&&(this.deceleratingToTurn=!0),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 Bs.Vector3(v.x,f,v.y);n=S.clone();return t.moveTrait.velocity.copy(n).multiplyScalar(gr.ISO_TILE_SIZE/gr.LEPTONS_PER_TILE),{distance:S,done:m&&w}}computeCancelDest(e,t){var i=t.clone().multiplyScalar(1/gr.LEPTONS_PER_TILE).floor().multiplyScalar(gr.LEPTONS_PER_TILE),i=t.clone().sub(i);return new Bs.Vector2(e.rx,e.ry).multiplyScalar(gr.LEPTONS_PER_TILE).add(i)}}class xs{constructor(e){this.game=e}create(e){var t=e.rules.locomotor;switch(t){case ti.Infantry:return new hs(this.game);case ti.Jumpjet:return new ys(this.game);case ti.Vehicle:case ti.Ship:return new ns(this.game);case ti.Chrono:return e.isVehicle()&&e.harvesterTrait&&e.rules.teleporter?new ns(this.game):new es(this.game);case ti.Aircraft:return new Es(this.game);case ti.Missile:return new vs(this.game,this.game.rules.general.getMissileRules(e.name));case ti.Hover:return new us(this.game.rules.general.hover);default:throw new Error(`Unhandled locomotor type ${t}`)}}}class Ps{constructor(e,t,i,r,s,a,n=!1,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=r,this.rng=s,this.predicate=a,this.includeStartTile=n,this.checkBounds=o,this.pool=[],this.pool=new Array(Math.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,r=this.pool.splice(i,1)[0],i=r%t,r=Math.floor(r/t),r=e(this.startTile.rx-this.maxDistance+i,this.startTile.ry-this.maxDistance+r);r&&(yield r)}}}class Ns{constructor(e,t,i){this.target=e,this.isChronoshift=t,this.prevTile=i,this.type=Xi.ObjectTeleport}}(Cs=Cs||{}).onBeforeTeleport=Symbol();class Rs{constructor(e){this.game=e,this.movePositionHelper=new Wr(e.map)}findPositions(e,t){let i=new Set,r=new Map;for(var s of e){var a=this.findFreeMovePosition(s,i,t);a&&(r.set(s,a),i.add(a.tile))}return r}findFreeMovePosition(i,e,{ignoredBlockers:t,excludedTiles:r,noSlopes:s}={}){let a=this.game.map,n=i.onBridge?a.tileOccupation.getBridgeOnTile(i.tile):void 0,o=new Ps(a.tiles,a.mapBounds,i.tile,1,this.game,e=>{if(r?.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))&&(!s||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 Ds extends Lr{constructor(e,t,i){super(),this.game=e,this.target=t,this.options=i}onStart(i){if(!i.moveTrait.isDisabled()&&i.rules.movementZone!==ii.Fly){let e,t;if(this.target)({tile:e,toBridge:t}=this.target);else{i=new Rs(this.game).findPositions([i],this.options).get(i);if(!i)return;e=i.tile,t=!!i.onBridge}this.children.push(new Us(this.game,e,t,{closeEnoughTiles:0,ignoredBlockers:this.options?.ignoredBlockers}))}}onTick(e){return!0}}var Ms,Ls,Fs,js,Ws=__webpack_require__(949);class Us extends Lr{constructor(e,t,i,r){super(),this.game=e,this.targetTile=t,this.toBridge=i,this.options=r,this.preventOpportunityFire=!1,this.logger=Kr.get("move"),this.destinationLeptons=new Ws.Vector2,this.currentWaypointLeptons=new Ws.Vector2,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:[]}}onStart(e){if(e.moveTrait.currentWaypoint)throw new Error("Nested move tasks are not supported");void 0===e.moveTrait.locomotor&&(e.moveTrait.locomotor=new xs(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=zs.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===ii.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===ii.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 r=this.targetTile,s=this.toBridge?i.tileOccupation.getBridgeOnTile(this.targetTile):void 0,a=this.options?.ignoredBlockers;var n=new Pr(i.tiles,i.mapBounds,r,{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!==r&&(r=n,s=i.tileOccupation.getBridgeOnTile(r)),[{tile:r,onBridge:s},{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===zs.Moving&&t.moveTrait.currentWaypoint&&(e=t.moveTrait.currentWaypoint.tile,i=t.moveTrait.currentWaypoint.onBridge);let r;var s=this.toBridge?this.game.map.tileOccupation.getBridgeOnTile(this.targetTile):void 0,a=this.nodeIsBlockedForPathfinding({tile:this.targetTile,onBridge:s},t);if(Math.abs(e.rx-this.targetTile.rx)<=1&&Math.abs(e.ry-this.targetTile.ry)<=1&&new Wr(this.game.map).isEligibleTile(e,i,s,this.targetTile)&&a)r=[];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:s},obj:n}),r=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 r}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*gr.LEPTONS_PER_TILE,e.ry*gr.LEPTONS_PER_TILE).add(t)}canStopAtTile(t,i,r){if(t.zone===dr.Air){if((!t.isAircraft()||!t.airportBoundTrait)&&!t.rules.spawned&&this.game.map.getObjectsOnTile(i).filter(e=>e.isBuilding()&&!e.dockTrait?.hasReservedDockForUnit(t)&&!t.rules.dock.includes(e.name)||e.isUnit()&&e.tile===i&&e.moveTrait.moveState!==zs.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===r&&e.moveTrait.moveState!==zs.Moving&&e!==t);if(2<e.length||e.find(e=>e.position.subCell===t.position.subCell))return!1}return!(t.zone!==dr.Air&&t.rules.tooBigToFitUnderBridge&&!r&&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 r=new br(this.game.map.tileOccupation);return!(r.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=Gs.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!==Er.Running&&this.status!==Er.Cancelling||(e.moveTrait.unreservePathNodes(),e.moveTrait.lastMoveResult=Hs.Cancel,this.onEnd(e),e.moveTrait.lastTargetOffset=this.targetOffset,e.moveTrait.lastVelocity=e.moveTrait.velocity.clone()),this.status=Er.Cancelled,!0))}onTick(s){if(s.moveTrait.isDisabled()&&s.moveTrait.moveState===zs.ReachedNextWaypoint)return!!this.isCancelling()&&(s.moveTrait.lastMoveResult=Hs.Cancel,!0);this.needsPathUpdate&&(s.moveTrait.moveState===zs.PlanMove&&(this.inPlanningForTicks=void 0,s.moveTrait.currentWaypoint=void 0,s.moveTrait.collisionState=Gs.Resolved,s.moveTrait.moveState=zs.ReachedNextWaypoint,s.moveTrait.velocity.set(0,0,0)),this.computePath(s,s.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(s.moveTrait.moveState===zs.ReachedNextWaypoint){s.moveTrait.unreservePathNodes();var t=this.path.findIndex(e=>e===s.moveTrait.currentWaypoint);if(-1!==t?this.path.splice(t):this.path.pop(),s.moveTrait.currentWaypoint=void 0,this.isCancelling()?!this.cancelProcessed:this.hasReachedDestination(s)){var a=!this.isCancelling()&&!this.isCloseEnoughToDest(s,s.tile,this.options?.closeEnoughTiles);if(!a&&this.canStopAtTile(s,s.tile,s.onBridge))return s.moveTrait.lastMoveResult=this.isCancelling()?Hs.Cancel:Hs.Success,!0;{if(5<this.unreachableTargets.length)return s.moveTrait.lastMoveResult=Hs.Fail,this.log(s,"bail_max_unreachable_dest"),!0;let e=s.tile,t=s.onBridge?i.tileOccupation.getBridgeOnTile(e):void 0;a&&(e=this.targetTile,t=this.toBridge?i.tileOccupation.getBridgeOnTile(e):void 0);var n=this.findRelocationTile(e,t,s);if(!n)return s.moveTrait.lastMoveResult=a?Hs.Fail:Hs.CloseEnough,this.log(s,"bail_no_free_dest"),!0;a=!t||t.isHighBridge()?i.tileOccupation.getBridgeOnTile(n):void 0;return this.updateTarget(n,!!a),this.isCancelling()&&(this.cancelProcessed=!0,this.cancelRepositionPending=!0),!1}}if(this.cancelProcessed&&!this.path.length)return s.moveTrait.lastMoveResult=Hs.Cancel,!0;this.cancelProcessed=!1,s.moveTrait.moveState=zs.PlanMove;let e=s.moveTrait.locomotor;s.moveTrait.currentWaypoint=e.selectNextWaypoint?e.selectNextWaypoint(s,this.path):this.path[this.path.length-1],this.currentWaypointLeptons.set(s.moveTrait.currentWaypoint.tile.rx,s.moveTrait.currentWaypoint.tile.ry).multiplyScalar(gr.LEPTONS_PER_TILE).add(this.targetOffset);n=e.onNewWaypoint(s,this.currentWaypointLeptons,this.destinationLeptons);if(n)return this.children.push(...n),!1}if(s.moveTrait.moveState===zs.PlanMove){if(this.isCancelling()&&!this.cancelRepositionPending)return s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=zs.ReachedNextWaypoint,this.onTick(s);if(this.inPlanningForTicks=void 0===this.inPlanningForTicks?0:this.inPlanningForTicks+1,200<this.inPlanningForTicks)return this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,s.moveTrait.velocity.set(0,0,0),this.log(s,"repath_plan_timeout"),!1;if(s.rules.movementZone!==ii.Fly&&!s.moveTrait.locomotor.ignoresTerrain){let t=this.path.slice(this.path.indexOf(s.moveTrait.currentWaypoint)).reverse();var r,e,o=s.moveTrait.velocity.length();for(r of t){if(!i.terrain.getPassableSpeed(r.tile,s.rules.speedType,!!r.onBridge,this.options?.ignoredBlockers))return this.needsPathUpdate=!0,s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=zs.ReachedNextWaypoint,this.onTick(s);if(!r.onBridge){var h=i.getGroundObjectsOnTile(r.tile).find(e=>e.isOverlay()&&e.rules.crate);if(h)if(this.game.crateGeneratorTrait.peekInsideCrate(h)===Sr.Unit){this.game.crateGeneratorTrait.pickupCrate(s,h,this.game);h=this.game.map.getGroundObjectsOnTile(r.tile).find(e=>e.isUnit()&&!e.onBridge);if(h)return this.needsPathUpdate=!0,this.blockedPathNodes.push({node:r,obj:h}),s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=zs.ReachedNextWaypoint,this.onTick(s)}}for(e of i.terrain.findObstacles(r,s).filter(e=>!this.options?.ignoredBlockers?.includes(e.obj))){if(e.static)return this.needsPathUpdate=!0,s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=zs.ReachedNextWaypoint,this.onTick(s);if(e.obj.rules.crushable){if(!(s.rules.speedType!==Kt.Track||!s.crusher||e.obj.isTechno()&&this.game.areFriendly(e.obj,s)))continue;if(!e.obj.isTechno())return this.needsPathUpdate=!0,s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=zs.ReachedNextWaypoint,this.onTick(s)}if(e.obj.isTerrain()){if(!s.isInfantry())throw new Error(`Obstacle ${e.obj.name} should be a blocker for non infantry`);var l=this.findFreeSubCell(s,r);return void 0!==l?this.relocateToSubCell(s,l):(this.needsPathUpdate=!0,this.blockedPathNodes.push({node:r,obj:e.obj}),s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=zs.ReachedNextWaypoint),this.onTick(s)}if(!e.obj.isTechno())throw new Error(`Unexpected obstacle of type ${e.obj.type}`);const m=e.obj;var c=m.isUnit()?m.moveTrait.velocity.length():0;if(!m.isAircraft()||m.zone!==dr.Ground||!this.options?.ignoredBlockers?.some(e=>e.isBuilding()&&e.dockTrait?.isDocked(m))){if(1===t.length&&m.isUnit()&&c&&o&&o<=c&&s.direction===m.direction&&m.tile===r.tile&&m.moveTrait.currentWaypoint?.tile!==r.tile)break;if(m.isBuilding()||m.moveTrait.moveState===zs.Idle||m.moveTrait.collisionState!==Gs.Resolved){if(!o&&s.moveTrait.collisionState!==Gs.Resolved&&m.isUnit()&&m.moveTrait.collisionState!==Gs.Resolved)return 200<this.inPlanningForTicks+1&&(this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,this.log(s,"repath_waited_too_long_blocker "+m.id),s.moveTrait.velocity.set(0,0,0)),!1;{if(m.isInfantry()&&s.isInfantry()&&m.moveTrait.collisionState===Gs.Resolved){var u=this.findFreeSubCell(s,r);if(void 0!==u)return this.relocateToSubCell(s,u),this.onTick(s)}l=Fr(this.path.slice(0,this.path.indexOf(r)),e=>!i.terrain.findObstacles(e,s).length);if(-1===l){if(this.canStopAtTile(s,s.tile,s.onBridge)&&this.isCloseEnoughToDest(s,s.tile,this.options?.closeEnoughTiles))return s.moveTrait.lastMoveResult=Hs.CloseEnough,this.log(s,"bail_waypoints_blocked_close_enough"),!0;if(!(0===this.options?.closeEnoughTiles||Math.abs(s.tile.rx-this.targetTile.rx)<=1&&Math.abs(s.tile.ry-this.targetTile.ry)<=1))return this.needsPathUpdate=!0,this.blockedPathNodes.push(...this.path.slice(0,this.path.indexOf(r)+1).map(e=>({node:e,obj:i.terrain.findObstacles(e,s)[0].obj}))),s.moveTrait.velocity.set(0,0,0),this.log(s,"repath_waypoints_blocked_too_far"),!1}let e;if(e=-1!==l?(u=this.path[l],i.terrain.computePath(s.rules.speedType,s.tile,s.onBridge,u.tile,!!u.onBridge,{maxExpandedNodes:15,bestEffort:!1,excludeTiles:e=>!!i.terrain.findObstacles(e,s).length})):[],e.length||m.owner!==s.owner||1!==t.length)return e.length?(this.path.splice(l,this.path.length,...e),s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=zs.ReachedNextWaypoint,this.onTick(s)):((d=this.selectWeaponVsObstacle(s,m))?(this.children.push(s.attackTrait.createAttackTask(this.game,m,m.tile,d,{passive:!0,holdGround:!0})),s.moveTrait.velocity.set(0,0,0)):this.options?.forceWaitOnPathBlocked&&1===t.length?(this.children.push(new jr(40)),this.inPlanningForTicks=0,s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=Gs.Waiting):(this.needsPathUpdate=!0,this.blockedPathNodes.push({node:r,obj:m}),m.isBuilding()&&(this.allObstaclesAreBlockers=!0),this.log(s,"repath_unavoidable_blocker "+m.id),s.moveTrait.velocity.set(0,0,0)),!1);d=m.unitOrderTrait.hasTasks();if(this.pushTried||m.isBuilding()||m.moveTrait.collisionState===Gs.Waiting||d||m.isAircraft()&&m.missileSpawnTrait)return!this.options?.forceWaitOnPathBlocked&&(m.isBuilding()||d&&m.moveTrait.moveState===zs.Idle||200<this.inPlanningForTicks+40)?(this.needsPathUpdate=!0,this.allObstaclesAreBlockers=!0,this.log(s,"repath_blocker_busy_wait_timeout "+m.id),s.moveTrait.velocity.set(0,0,0)):(this.children.push(new jr(40)),this.options?.forceWaitOnPathBlocked?this.inPlanningForTicks=0:this.inPlanningForTicks+=40,s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=Gs.Waiting),!1;var d,d=new Ws.Vector2(m.tile.rx-s.tile.rx,m.tile.ry-s.tile.ry);return this.pushTried=!0,m.unitOrderTrait.addTask(new Yr(this.game,d)),this.children.push(new jr(1)),s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=Gs.Waiting,this.log(s,"push "+m.id),!1}}if(!o)return 40<this.inPlanningForTicks&&(s.moveTrait.collisionState=Gs.Waiting),!1;if(180===Math.abs(s.direction-m.direction))return s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=Gs.Waiting,!1;if(Math.abs(s.direction-m.direction)<=45&&1.5*c<o){c=this.path.indexOf(r);if(5<=c){let e=Fr(this.path.slice(0,c-5),e=>!i.terrain.findObstacles(e,s).length);if(-1!==e){c=this.path[e],c=i.terrain.computePath(s.rules.speedType,s.tile,s.onBridge,c.tile,!!c.onBridge,{maxExpandedNodes:15,bestEffort:!1,excludeTiles:t=>!!i.terrain.findObstacles(t,s).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),s.moveTrait.currentWaypoint=void 0,s.moveTrait.moveState=zs.ReachedNextWaypoint,this.onTick(s)}}return s.moveTrait.collisionState=Gs.Waiting,s.moveTrait.velocity.set(0,0,0),!1}return s.moveTrait.velocity.set(0,0,0),s.moveTrait.collisionState=Gs.Waiting,!1}}}if(s.rules.speedType===Kt.Track&&o){var p,g=this.path.indexOf(s.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(ai.SCATTER)&&!this.game.areFriendly(e,s)))p.unitOrderTrait.hasTasks()||p.unitOrderTrait.addTask(new Ds(this.game))}}s.moveTrait.reservedPathNodes.length||(s.moveTrait.reservedPathNodes.push(...t),t.forEach(e=>{i.tileOccupation.occupySingleTile(e.tile,s)}))}s.moveTrait.moveState=zs.Moving,this.inPlanningForTicks=void 0,this.unreachableTargets.length=0,this.pushTried=!1,s.moveTrait.collisionState===Gs.Waiting&&(s.moveTrait.collisionState=Gs.Resolved)}if(s.moveTrait.moveState===zs.Moving){let e=s.moveTrait.locomotor,{distance:t,done:i,isTeleport:r}=e.tick(s,this.currentWaypointLeptons,this.destinationLeptons,(this.isCancelling()||!this.path.length)&&!this.cancelRepositionPending);if(r&&s.traits.filter(Cs).forEach(e=>{e[Cs.onBeforeTeleport](s,this.game,!0,!0)}),t.length()){a=s.tile,n=e.allowOutOfBounds;if(t.y?s.position.moveByLeptons3(t,n):s.position.moveByLeptons(t.x,t.z,n),s.tile!==a){g=s.onBridge?this.game.map.tileOccupation.getBridgeOnTile(a):void 0,n=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===s.tile),g=n?n.onBridge:g||s.moveTrait.currentWaypoint.onBridge?this.game.map.tileOccupation.getBridgeOnTile(s.tile):void 0;if(s.moveTrait.handleTileChange(a,g,!1,this.game,r),r&&(s.moveTrait.lastTeleportTick=this.game.currentTick,this.game.events.dispatch(new Ns(s,!0,a))),s.isDestroyed)return!0}}if(i)return s.moveTrait.moveState=zs.ReachedNextWaypoint,this.onTick(s)}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(r,s,a){let n=this.game.map,i;if(a.rules.movementZone===ii.Fly){let e=new Ps(n.tiles,n.mapBounds,r,1,this.game,e=>!0);i=e.getNextTile()}else{let e=new Wr(n),t=new Pr(n.tiles,n.mapBounds,r,{width:1,height:1},0,5,t=>{let i=!s||s.isHighBridge()?n.tileOccupation.getBridgeOnTile(t):void 0;return!this.unreachableTargets.find(e=>e.tile===t&&e.toBridge===!!i)&&(a.zone===dr.Air||!n.terrain.findObstacles({tile:t,onBridge:i},a).length&&e.isEligibleTile(t,i,s,r))&&this.canStopAtTile(a,t,!!i)});i=t.getNextTile()}return i}findFreeSubCell(t,i){let e=this.game.map.getGroundObjectsOnTile(i.tile);var r=e.filter(e=>e.isInfantry()&&e.onBridge===!!i.onBridge&&e!==t).map(e=>e.position.desiredSubCell),s=e.filter(e=>e.isTerrain()).map(e=>e.rules.getOccupiedSubCells(this.game.map.getTheaterType())).flat();let a=[...r,...s];return ca.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(gr.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 xs(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}`)}}(Ms=Ms||{}).onDestroy=Symbol(),(s=Ls=Ls||{})[s.None=0]="None",s[s.Normal=1]="Normal",s[s.Demolish=2]="Demolish",s[s.Crush=3]="Crush",s[s.Temporal=4]="Temporal",s[s.Sink=5]="Sink",(Fs=Fs||{}).onTileChange=Symbol(),(js=js||{}).onTileChange=Symbol();class Vs{constructor(e,t){this.target=e,this.source=t,this.type=Xi.EnterTile}}var zs,Hs,Gs,$s,qs,Zs,Qs,Xs,Ys,Ks=__webpack_require__(949);(s=zs=zs||{})[s.Idle=0]="Idle",s[s.ReachedNextWaypoint=1]="ReachedNextWaypoint",s[s.PlanMove=2]="PlanMove",s[s.Moving=3]="Moving",(s=Hs=Hs||{})[s.Success=0]="Success",s[s.Cancel=1]="Cancel",s[s.CloseEnough=2]="CloseEnough",s[s.Fail=3]="Fail",(s=Gs=Gs||{})[s.Waiting=0]="Waiting",s[s.Resolved=1]="Resolved";const Js=e=>e instanceof Us||e.children[0]&&Js(e.children[0]);class ea{constructor(e,t){this.gameObject=e,this.tileOccupation=t,this.disabled=!1,this.speedPenalty=0,this.velocity=new Ks.Vector3,this.reservedPathNodes=[],this.moveState=zs.Idle,this.collisionState=Gs.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!==ti.Hover?.75:1)*(1-this.speedPenalty)}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}isMoving(){return this.moveState===zs.Moving}isIdle(){return this.moveState===zs.Idle}isWaiting(){return this.collisionState===Gs.Waiting}[Ts.onTick](e,t){var i;this.moveState!==zs.Idle&&this.collisionState===Gs.Resolved&&((i=e.unitOrderTrait.getCurrentTask())&&Js(i)||(this.velocity.set(0,0,0),this.moveState=zs.Idle,this.locomotor=void 0,!i&&!e.attackTrait?.currentTarget&&e.isVehicle()&&e.turretTrait&&(e.turretTrait.desiredFacing=e.direction))),this.moveState===zs.Idle&&(e.rules.locomotor===ti.Jumpjet?ys.tickStationary(e,t):e.isAircraft()&&e.rules.locomotor===ti.Aircraft&&Es.tickStationary(e,t))}[Ms.onDestroy](e,t){this.unreservePathNodes()}teleportUnitToTile(e,t,i,r,s){let a=this.gameObject;var n=a.tile;a.traits.filter(Cs).forEach(e=>{e[Cs.onBeforeTeleport](a,s,i,r)}),a.position.tileElevation=a.tileElevation,a.position.tile=e,a.position.subCell=a.position.desiredSubCell,this.handleTileChange(n,t,!0,s,!0),r||(this.unreservePathNodes(),this.speedPenalty=0,this.velocity.set(0,0,0),this.moveState=zs.Idle,this.collisionState=Gs.Resolved,this.locomotor=void 0,this.currentWaypoint=void 0,this.lastTargetOffset=void 0,this.lastVelocity=void 0,this.lastMoveResult=Hs.Cancel,a.isVehicle()&&(a.spinVelocity=0,a.turretTrait&&(a.turretTrait.desiredFacing=a.direction))),this.lastTeleportTick=s.currentTick,s.events.dispatch(new Ns(a,i,n))}handleTileChange(t,e,i,r,s=!1){const a=this.gameObject;if(r.map.tileOccupation.unoccupyTileRange(t,a),r.map.tileOccupation.occupyTileRange(a.tile,a),r.map.technosByTile.updateObject(a),a.zone!==dr.Air){var n=a.onBridge?r.map.tileOccupation.getBridgeOnTile(t):void 0,o=a.onBridge?t.onBridgeLandType:t.landType,h=e?a.tile.onBridgeLandType:a.tile.landType;o!==h&&(0<r.rules.getLandRules(h).getSpeedModifier(a.rules.speedType)||a.rules.speedType===Kt.Amphibious||s)&&(a.zone=mr(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 r.map.getGroundObjectsOnTile(a.tile).filter(e=>(!e.isUnit()||e.onBridge===a.onBridge)&&e.rules.crushable&&!(e.isInfantry()&&e.stance===Br.Paradrop)&&(!(e.isTechno()&&!i)||!r.areFriendly(e,a))))l.isDestroyed||(l.isInfantry()&&(l.infDeathType=Jt.None),a.isVehicle()&&l.isOverlay()&&l.rules.wall&&a.applyRocking(0,.5),l.deathType=Ls.Crush,r.destroyObject(l,{player:a.owner,obj:a}));a.onBridge||(e=r.map.tileOccupation.getGroundObjectsOnTile(a.tile).find(e=>e.isOverlay()&&e.rules.crate))&&r.crateGeneratorTrait.pickupCrate(a,e,r)}r.traits.filter(Fs).forEach(e=>{e[Fs.onTileChange](a,r,t,s)}),a.traits.filter(js).forEach(e=>{e[js.onTileChange](a,r,t,s)}),r.events.dispatch(new Vs(a.tile,a))}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 ta{constructor(){this.suppressionTicks=0,this.enabled=!0}disable(){this.enabled=!1}isSuppressed(){return this.enabled&&0<this.suppressionTicks}supress(){this.enabled&&(this.suppressionTicks=30)}[Ts.onTick](){0<this.suppressionTicks&&this.suppressionTicks--}}class ia{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()}}($s=$s||{}).onChange=Symbol(),(qs=qs||{}).onSpawn=Symbol(),(Zs=Zs||{}).onUnspawn=Symbol(),(Qs=Qs||{}).onAttack=Symbol();class ra{constructor(e,t,i,r){this.traits=new ia,this.cachedTraits={tick:[]},this.isCrashing=!1,this.isDestroyed=!1,this.deathType=Ls.Normal,this.isDisposed=!1,this.isSpawned=!1,this.type=e,this.name=t,this.rules=i,this.art=r}get tile(){return this.position.tile}get tileElevation(){return this.position.tileElevation}getFoundation(){return{width:1,height:1}}isSmudge(){return this.type===Ct.Smudge}isOverlay(){return this.type===Ct.Overlay}isTerrain(){return this.type===Ct.Terrain}isProjectile(){return this.type===Ct.Projectile}isDebris(){return this.type===Ct.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[Ts.onTick](this,e)}onSpawn(t){this.isSpawned=!0,this.traits.filter(qs).forEach(e=>{e[qs.onSpawn](this,t)})}onUnspawn(t){this.isSpawned=!1,this.traits.filter(Zs).forEach(e=>{e[Zs.onUnspawn](this,t)})}onDestroy(t,i,r){this.traits.filter(Ms).forEach(e=>{e[Ms.onDestroy](this,t,i,r)})}onOwnerChange(t,i){this.traits.filter($s).forEach(e=>{e[$s.onChange](this,t,i)})}onAttack(t,i){this.traits.filter(Qs).forEach(e=>{e[Qs.onAttack](this,i,t)})}addTrait(e){this.traits.add(e),e[Ts.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}}(s=Xs=Xs||{})[s.None=0]="None",s[s.Veteran=1]="Veteran",s[s.Elite=2]="Elite";class sa extends ra{constructor(e,t,i,r){super(e,t,i,r),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(Ki.MAX_SIGHT,this.rules.sight*(this.veteranTrait?.getVeteranSightMultiplier()??1))}get veteranLevel(){return this.veteranTrait?.veteranLevel??Xs.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[Ts.onTick](this,e);else super.update(e)}isTechno(){return!0}}class aa{constructor(){this.cooldownTicks=Number.POSITIVE_INFINITY,this._actionDueThisTick=!1}[Ts.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 Ds(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*xr.BASE_TICKS_PER_SECOND)}}class na{constructor(e){this.gameObject=e,this.type=Xi.ObjectCrashing}}(Ys=Ys||{}).onCrash=Symbol();class oa{constructor(e){this.gameObject=e,this.crashingEvtSent=!1,this.crashState={}}[Ts.onTick](i,r){if(i.isCrashing){if(this.crashingEvtSent||(this.crashingEvtSent=!0,i.traits.filter(Ys).forEach(e=>e[Ys.onCrash](i,r)),r.events.dispatch(new na(i))),i.rules.locomotor!==ti.Jumpjet&&i.rules.locomotor!==ti.Aircraft)throw new Error(`Crashing logic not implemented for locomotor ${ti[i.rules.locomotor]}`);{let e;if(i.rules.locomotor===ti.Jumpjet)e=ys.tickCrash(i,r,this.crashState);else{if(i.rules.locomotor!==ti.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=Es.tickCrash(i,r,this.crashState)}let t=!1;var s,a=gr.vecLeptonsToWorld(e).add(i.position.worldPosition);r.map.isWithinHardBounds(a)?(s=i.tile,i.position.moveByLeptons3(e),i.tile!==s&&i.moveTrait.handleTileChange(s,void 0,!1,r),s=(a=i.tile.onBridgeLandType?r.map.tileOccupation.getBridgeOnTile(i.tile):void 0)?.tileElevation??0,i.position.tileElevation=Math.max(i.position.tileElevation,s),i.position.tileElevation===s&&(i.zone=r.map.getTileZone(i.tile),i.onBridge=!!a,t=!0)):t=!0,t&&r.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 ha{infiltrate(e,t,i){var r;t.rules.radar&&![...t.owner.buildings].some(e=>e.rules.spySat)&&i.mapShroudTrait.resetShroud(t.owner,i),0<t.rules.power&&(r=i.rules.general.spyPowerBlackout,t.owner.powerTrait?.setBlackoutFor(r,i)),t.superWeaponTrait&&t.superWeaponTrait.getSuperWeapon(t)?.resetTimer(),0<t.rules.storage&&(r=U(i.rules.general.spyMoneyStealPercent,0,1),r=Math.floor(t.owner.credits*r),t.owner.credits-=r,e.owner.credits+=r),!i.rules.ai.buildTech.includes(t.name)||void 0!==(i=t.rules.aiBasePlanningSide)&&e.owner.production.addStolenTech(i),[qi.InfantryType,qi.UnitType].includes(t.factoryTrait?.type)&&e.owner.production?.addVeteranType(t.factoryTrait.type)}}class la{constructor(){this.firepower=1,this.armor=1,this.speed=1}}class ca extends sa{constructor(e,t,i){super(Ct.Infantry,e,t,i),this.direction=0,this.onBridge=!1,this.zone=dr.Ground,this._stance=Br.None,this.isFiring=!1,this.isPanicked=!1,this.infDeathType=Jt.Gunfire,this.crateBonuses=new la}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,r){let s=new this(e,t,i);return s.moveTrait=new ea(s,r),s.traits.add(s.moveTrait),s.rules.crashable&&(s.crashableTrait=new oa(s),s.traits.add(s.crashableTrait)),s.rules.proneWhenAttacked&&(s.suppressionTrait=new ta,s.traits.add(s.suppressionTrait)),s.rules.agent&&(s.agentTrait=new ha,s.traits.add(s.agentTrait)),s.idleActionTrait=new aa,s.traits.add(s.idleActionTrait),s}get stance(){return this._stance===Br.None&&this.suppressionTrait?.isSuppressed()?Br.Prone:this._stance}set stance(e){this._stance=e,this.moveTrait.setDisabled([Br.Deployed,Br.Cheer].includes(e)),this.attackTrait?.setDisabled([Br.Paradrop,Br.Cheer].includes(e))}isUnit(){return!0}isInfantry(){return!0}}ca.SUB_CELLS=[2,4,3];var ua=__webpack_require__(949);class da extends Lr{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,r=gr.worldToLeptons(gr.tileHeightToWorld(i)),s=gr.worldToLeptons(gr.tileHeightToScreen(e.tileElevation));return r<Math.max(r,s-t)?(e.position.moveByLeptons3(new ua.Vector3(0,-t,0)),!1):(e.position.tileElevation=i,e.stance=Br.None,this.game.map.terrain.getPassableSpeed(e.tile,e.rules.speedType,e.onBridge)||(e.infDeathType=Jt.None,this.game.destroyObject(e,void 0,!0)),!0)}}function pa(i,r,s,a,n){let o=[];n=n||((e,t)=>{o.push({x:e,y:t})});var e=s-i,t=a-r,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=r;u<0?e>=s:e<=s;e+=u)n(e,t),c+=l,c<<1>=h&&(t+=d,c-=h);else for(let e=i,t=r;d<0?t>=a:t<=a;t+=d)n(e,t),c+=h,c<<1>=l&&(e+=u,c-=l);return o}function ga(e){return null!=e}class ma extends Lr{constructor(...e){super(),this.children.push(...e)}onTick(e){return!0}}var fa=__webpack_require__(949);class ya{constructor(){this.enabled=!0}setEnabled(e){this.enabled=e}[Ts.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 ma(new Us(t,i,!1,{allowOutOfBoundsTarget:!0}),new _s(e=>t.unspawnObject(e))).setCancellable(!1)))}chooseExitTile(e,t){var i=t.map.tiles.getMapSize(),i=.5<t.generateRandom()?new fa.Vector2(Math.floor(i.width/2),0):new fa.Vector2(0,Math.floor(i.height/2)),e=new fa.Vector2(e.rx,e.ry),i=pa(e.x,e.y,i.x,i.y).map(e=>t.map.tiles.getByMapCoords(e.x,e.y)).filter(ga);if(!i.length)throw new Error("No valid exit tile found");return i[i.length-1]}}var wa,Ta,ba,va,Sa,_a,ka,Oa=__webpack_require__(949);(s=wa=wa||{})[s.Spawning=0]="Spawning",s[s.EnRoute=1]="EnRoute",s[s.Dropping=2]="Dropping",s[s.TurningAround=3]="TurningAround";const Ia=5*xr.BASE_TICKS_PER_SECOND;class Aa extends Dr{constructor(e,t,i,r,s){super(e,t,i),this.paradropSquad=r,this.state=wa.Spawning,this.spawnDelay=s*Ia}onStart(e){this.passengerRules=e.rules.getObject(this.paradropSquad.inf,Ct.Infantry),this.passengerCount=this.paradropSquad.num}computeFlightPath(e,t,i){if(t.equals(e))throw new Error("Source and destination must be different");let r=e.clone().sub(t);e=i.rules.general.paradrop.paradropRadius/gr.LEPTONS_PER_TILE,e=t.clone().add(r.clone().setLength(r.length()+2*e)).floor();let s=pa(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(;s.length;){var a=s[0],a=gr.tileToWorld(a.rx+.5,a.ry+.5);if(i.map.isWithinHardBounds(new Oa.Vector2(a.x,a.y)))break;s.shift()}if(!s.length)throw new Error("No valid paradrop path found");return{fromTile:s[0],toTile:s[s.length-1]}}onTick(s){if(this.state===wa.Spawning){if(0<this.spawnDelay)return this.spawnDelay--,!1;var a=s.map.tiles.getMapSize(),n=[new Oa.Vector2(0,0),new Oa.Vector2(Math.floor(a.width/2),0),new Oa.Vector2(0,Math.floor(a.height/2))][s.generateRandomInt(0,2)];let t=this.passengerRules.speedType,e=new Pr(s.map.tiles,s.map.mapBounds,this.tile,{width:1,height:1},0,50,e=>0<s.map.terrain.getPassableSpeed(e,t,!!e.onBridgeLandType));var o=this.targetTile=e.getNextTile();if(!o)return!0;let i=new Oa.Vector2(o.rx,o.ry);var{fromTile:h,toTile:a}=this.computeFlightPath(i,n,s),o=s.rules.general.paradrop.paradropPlane,n=s.rules.getObject(o,Ct.Aircraft);let r=this.pdPlane=s.createUnitForPlayer(n,this.owner);s.spawnObject(r,h),r.direction=is.fromMapCoords(i.clone().sub(new Oa.Vector2(h.rx,h.ry))),r.position.tileElevation=gr.worldToTileHeight(gr.leptonsToWorld(r.rules.flightLevel??s.rules.general.flightLevel)),r.zone=dr.Air,r.onBridge=!1,r.unitOrderTrait.addTask(new Us(s,a,!1,{allowOutOfBoundsTarget:!0})),r.traits.get(ya).setEnabled(!1),this.state=wa.EnRoute}if(!this.pdPlane||this.pdPlane.isDestroyed||this.pdPlane.isCrashing)return!0;o=this.targetTile;if(!this.pdPlane.unitOrderTrait.hasTasks())return this.state=wa.TurningAround,this.pdPlane.unitOrderTrait.addTask(new Us(s,o,!1,{allowOutOfBoundsTarget:!0})),!1;n=s.rules.general.paradrop.paradropRadius/gr.LEPTONS_PER_TILE;let e=new br(s.map.tileOccupation);h=e.isInTileRange(this.pdPlane.tile,o,0,n);if(this.state===wa.EnRoute&&h&&(this.state=wa.Dropping),this.state===wa.Dropping)if(h&&0<this.passengerCount){a=this.pdPlane.tile;let t=!!a.onBridgeLandType;if(!s.map.terrain.getPassableSpeed(a,this.passengerRules.speedType,t))return!1;let e=s.map.getGroundObjectsOnTile(a);if(e.some(e=>e.isVehicle()&&e.onBridge===t||e.isBuilding()&&!e.isDestroyed||e.isInfantry()&&e.stance===Br.Paradrop))return!1;n=this.findFreeSubCell(s,a);if(!n)return!1;this.passengerCount--;let i=s.createUnitForPlayer(this.passengerRules,this.owner);i.stance=Br.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(Xs.Veteran),s.spawnObject(i,a),i.unitOrderTrait.addTask(new da(s).setCancellable(!1))}else{if(!(0<this.passengerCount))return this.pdPlane.unitOrderTrait.getCurrentTask().forceCancel(this.pdPlane),this.pdPlane.traits.get(ya).setEnabled(!0),!0;this.state=wa.TurningAround,this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!!o.onBridgeLandType)}return this.state===wa.TurningAround&&h&&(o=this.computeFlightPath(new Oa.Vector2(o.rx,o.ry),new Oa.Vector2(this.pdPlane.tile.rx,this.pdPlane.tile.ry),s)["toTile"],this.pdPlane.unitOrderTrait.getCurrentTask().updateTarget(o,!1),this.state=wa.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=ca.SUB_CELLS.filter(e=>-1===i.indexOf(e));if(e.length)return 1<e.length?e[t.generateRandomInt(0,e.length-1)]:e[0]}}(s=Ta=Ta||{})[s.NotBridge=0]="NotBridge",s[s.Concrete=1]="Concrete",s[s.Wood=2]="Wood";class Ca{static getOverlayBridgeType(e){return V(e,this.minHighBridgeConcreteId,this.maxHighBridgeConcreteId)||V(e,this.minLowBridgeConcreteId,this.maxLowBridgeConcreteId)?Ta.Concrete:V(e,this.minHighBridgeWoodId,this.maxHighBridgeWoodId)||V(e,this.minLowBridgeWoodId,this.maxLowBridgeWoodId)?Ta.Wood:Ta.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===Ta.Concrete)i=this.minLowBridgeConcreteId;else{if(e!==Ta.Wood)throw new Error("Not implemented");i=this.minLowBridgeWoodId}return i+(t?0:9)}static calculateHighBridgeOverlayId(e,t){let i;if(e===Ta.Concrete)i=this.minHighBridgeConcreteId;else{if(e!==Ta.Wood)throw new Error("Not implemented");i=this.minHighBridgeWoodId}return i+(t?0:1)}}Ca.minLowBridgeWoodId=74,Ca.maxLowBridgeWoodId=99,Ca.minLowBridgeConcreteId=205,Ca.maxLowBridgeConcreteId=230,Ca.minHighBridgeConcreteId=24,Ca.maxHighBridgeConcreteId=25,Ca.minHighBridgeWoodId=237,Ca.maxHighBridgeWoodId=238,Ca.bridgePlaceholderIds=[100,101,231,232],(ba=ba||{}).onAttack=Symbol(),(s=va=va||{})[s.None=0]="None",s[s.Ground=1]="Ground",s[s.Wall=2]="Wall",s[s.Cliff=3]="Cliff",s[s.OnBridge=4]="OnBridge",s[s.UnderBridge=5]="UnderBridge",s[s.Shore=6]="Shore";class Ba{constructor(e,t,i,r){this.target=e,this.position=t,this.explodeAnim=i,this.isLightningStrike=r,this.type=Xi.WarheadDetonate}}(s=Sa=Sa||{})[s.Top=0]="Top",s[s.TopLeft=1]="TopLeft",s[s.TopRight=2]="TopRight",s[s.Left=3]="Left",s[s.Right=4]="Right",s[s.BottomLeft=5]="BottomLeft",s[s.Bottom=6]="Bottom",s[s.BottomRight=7]="BottomRight";class Ea{constructor(i,r,e){this.tileSets=r,this.generalRules=e;let s=this.rSize={width:0,height:0},a=this.dSize={width:0,height:0};for(let e=0,t=i.length;e<t;++e)s.width=Math.max(s.width,i[e].rx),s.height=Math.max(s.height,i[e].ry),a.width=Math.max(a.width,i[e].dx),a.height=Math.max(a.height,i[e].dy);s.width++,s.height++,a.width++,a.height++;let n=this.tilesByRxy=new Array(s.width*s.height);n.fill(void 0);let o=this.tilesByDxy=new Array(a.width*a.height);o.fill(void 0);let h=this.tiles=new Array(i.length),l=[],c=this.bridgeSetTiles=[],u=new Set(Object.values(Xt));this.minTileHeight=Number.POSITIVE_INFINITY;for(let e=this.maxTileHeight=0,t=i.length;e<t;++e){var d=i[e],p=r.getTileImage(d.tileNum,d.subTile),g=p.terrainType;if(!u.has(g))throw new Error(`Tile (${d.rx}, ${d.ry}) has unknown terrain type "${g}"`);var m={...d,terrainType:g,landType:Wi(g),onBridgeLandType:void 0,rampType:p.rampType,id:d.rx+"_"+d.ry,occluded:!1},f=m.rx,y=m.ry,g=m.dx,p=m.dy;h[e]=m,n[f+y*s.width]=m,o[g+p*a.width]=m,this.minTileHeight=Math.min(this.minTileHeight,m.z),this.maxTileHeight=Math.max(this.maxTileHeight,m.z),m.terrainType!==Xt.Cliff&&!r.isCliffTile(m.tileNum)||l.push(m),r.isHighBridgeBoundaryTile(d.tileNum)&&c.push(m)}this.computeLandBehindCliffTiles(l),this.cutoffTileHeight=Math.max(9,this.computeCutoffTileHeight())}computeLandBehindCliffTiles(e){e.forEach(i=>{var r=this.generalRules.cliffBackImpassability;for(let t=0;t<=r;t++)for(let e=0;e<=r;e++)if(t||e){const s=this.getByMapCoords(i.rx-t,i.ry-e);s&&1<=t&&t===e&&s.z<i.z&&0===s.rampType&&([[1,0],[0,1]].some(([e,t])=>{t=this.getByMapCoords(s.rx-e,s.ry-t);return t?.terrainType===Xt.Cliff&&t.z===s.z})||(s.landType=Yt.Rock))}})}getTileRadarColor(e){let t=this.tileSets.getTileImage(e.tileNum,e.subTile);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,r=0,s=!0;for(;s&&0<i;){for(let e=1;e<t-3;e++){var a=this.getByDisplayCoords(e,i);a&&(s=!1,a.z>r&&(r=a.z))}s&&i--}return r}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(ga)}getNeighbourTile(e,t){var i=e.rx,r=e.ry;switch(t){case Sa.Bottom:return this.getByMapCoords(i+1,r+1);case Sa.Top:return this.getByMapCoords(i-1,r-1);case Sa.Left:return this.getByMapCoords(i-1,r+1);case Sa.Right:return this.getByMapCoords(i+1,r-1);case Sa.BottomLeft:return this.getByMapCoords(i,r+1);case Sa.BottomRight:return this.getByMapCoords(i+1,r);case Sa.TopLeft:return this.getByMapCoords(i-1,r);case Sa.TopRight:return this.getByMapCoords(i,r-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(i,r){let s=[];for(let t=0;t<r.width;t++)for(let e=0;e<r.height;e++){var a=i.rx+t,n=i.ry+e,n=this.getByMapCoords(a,n);n&&s.push(n)}return s}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:Yt.Rock,terrainType:Xt.Rock1,rampType:0,subTile:0,tileNum:0,occluded:!1,onBridgeLandType:void 0}}}(s=_a=_a||{})[s.NotSpecial=0]="NotSpecial",s[s.Riparius=1]="Riparius",s[s.Cruentus=2]="Cruentus",s[s.Vinifera=4]="Vinifera",s[s.Aboreus=8]="Aboreus",s[s.Ore=1]="Ore",s[s.Gems=2]="Gems",s[s.All=15]="All";class xa{static getOverlayTibType(e){return this.isRiparius(e)?_a.Riparius:this.isCruentus(e)?_a.Cruentus:this.isVinifera(e)?_a.Vinifera:this.isAboreus(e)?_a.Aboreus:_a.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}}xa.minIdRiparius=102,xa.maxIdRiparius=127,xa.minIdCruentus=27,xa.maxIdCruentus=38,xa.minIdVinifera=127,xa.maxIdVinifera=146,xa.minIdAboreus=147,xa.maxIdAboreus=166,(s=ka=ka||{})[s.Riparius=0]="Riparius",s[s.Cruentus=1]="Cruentus",s[s.Vinifera=2]="Vinifera",s[s.Aboreus=3]="Aboreus",s[s.Ore=0]="Ore",s[s.Gems=1]="Gems";class Pa{constructor(e){this.gameObject=e}static canBePlacedOn(e,t){return[Yt.Clear,Yt.Road,Yt.Rough].includes(e.landType)&&!t.getGroundObjectsOnTile(e).find(e=>!e.isSmudge()&&!e.isUnit())}getTiberiumType(){var e=xa.getOverlayTibType(this.gameObject.overlayId);switch(e){case _a.Ore:return ka.Ore;case _a.Gems:return ka.Gems;case _a.Vinifera:return ka.Ore;default:throw new Error(`Unsupported tiberium type ${e}`)}}collectBail(){if(this.getBailCount()<=0)throw new Error("Attempted to collect an ore bail, but there are none left");return this.gameObject.value--,this.getTiberiumType()}spawnBails(e){this.gameObject.value=Math.min(Pa.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}}Pa.maxBails=11;class Na{destroyOre(i,r,s){if(r.landType===Yt.Tiberium&&(s.art.hasObject(i,Ct.Animation)?s.art.getAnimation(i):void 0)?.crater){let t=s.map.getObjectsOnTile(r).find(e=>e.isOverlay()&&e.isTiberium());if(t){r=Math.ceil(Pa.maxBails/2),r=i.startsWith("S_CLSN")?r:s.generateRandomInt(1,r);let e=t.traits.get(Pa);e.removeBails(r),e.getBailCount()||s.unspawnObject(t)}}}spawnSmudges(e,s,a){if(s.landType===Yt.Clear&&0===s.rampType&&a.map.mapBounds.isWithinBounds(s)&&!a.map.getObjectsOnTile(s).find(e=>!e.isUnit())){e=a.art.hasObject(e,Ct.Animation)?a.art.getAnimation(e):void 0;if(e?.crater){let t=e?.forceBigCraters?2:1,i=e?.scorch,r=[Sa.Bottom,Sa.BottomLeft,Sa.BottomRight].every(e=>a.map.tiles.getNeighbourTile(s,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)&&!r));e.length&&(e=e[a.generateRandomInt(0,e.length-1)].name,e=a.createObject(Ct.Smudge,e),a.spawnObject(e,s))}}}}class Ra{constructor(e,t,i){this.target=e,this.attacker=t,this.incidental=i,this.type=Xi.ObjectAttacked}}var Da,Ma,La=__webpack_require__(949);class Fa{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!==dr.Air||i===dr.Air)&&(!(!e.isUnit()&&i===dr.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()||!Ca.isLowBridgeHead(e.overlayId))))))))))))}computeDamage(t,i,r=!1){let s=t;if(0<t&&i.isTechno()&&i.invulnerableTrait.isActive())return 0;if(i.isAircraft()&&i.missileSpawnTrait&&i.zone!==dr.Air)return 0;if(this.rules.radiation||this.rules.temporal||!i.isInfantry()||i.stance!==Br.Prone||(s*=this.rules.proneDamage),i.isTechno()||i.isOverlay()||i.isTerrain()){let e=i.isTerrain()?ri.Wood:i.rules.armor;i.isOverlay()&&i.isBridge()&&((t=Ca.getOverlayBridgeType(i.overlayId))===Ta.Wood?e=ri.Wood:t===Ta.Concrete&&(e=ri.Concrete)),r&&i.isOverlay()&&(i.isBridge()||i.rules.wall)||(s*=this.rules.verses.get(e)),0<s&&i.isTechno()&&i.veteranTrait&&(s/=i.veteranTrait.getVeteranArmorMultiplier()),0<s&&i.isUnit()&&(s/=i.crateBonuses.armor)}return(i.isOverlay()||i.isBuilding())&&i.rules.wall&&(this.rules.wallAbsoluteDestroyer?s=Number.POSITIVE_INFINITY:this.rules.wall||this.rules.wood&&i.rules.armor===ri.Wood||(s=0)),i.isOverlay()&&i.isBridge()&&(this.rules.wall||(s=0)),s=0<s?Math.floor(s):Math.ceil(s),s}inflictDamage(e,t,i,r,s=!1){let a=t.healthTrait;return e===Number.POSITIVE_INFINITY&&(e=a.getHitPoints()),a.inflictDamage(e,i,r),r.traits.filter(ba).forEach(e=>{e[ba.onAttack](t,i?.obj,r)}),t.onAttack(r,i),r.events.dispatch(new Ra(t,i,s)),t.isTechno()&&!this.rules.temporal&&this.supressOrScatterTarget(t,r),!a.health&&(t.isInfantry()&&(t.infDeathType=this.rules.infDeath),this.rules.temporal&&(t.deathType=Ls.Temporal),t.isUnit()&&t.crashableTrait&&t.zone===dr.Air&&!this.rules.temporal?t.crashableTrait.crash(i):r.destroyObject(t,i,void 0,s),!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 Ds(t)),e.isInfantry()&&e.unitOrderTrait.addTask(new _s(()=>e.isPanicked=!1).setCancellable(!1))):e.isInfantry()&&e.suppressionTrait?.supress()}createDummyWeaponInfo(){return{minRange:0,range:0,speed:Number.POSITIVE_INFINITY,type:si.Primary,rules:new _i(new h("Dummy")),projectileRules:new zi(Ct.Projectile,new h("Dummy")),warhead:this}}detonate(i,e,t,r,s,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/gr.LEPTONS_PER_TILE:this.rules.cellSpread,v=this.rules.percentAtMax;let S=new Set,_=new Map,k=new br(i.map.tileOccupation),O=new Pr(i.map.tiles,i.map.mapBounds,t,{width:1,height:1},0,Math.ceil(b),()=>!0);for(;g=O.getNextTile();)for(m of i.map.getObjectsOnTile(g))if((!S.has(m)||m.isBuilding())&&(n!==va.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-r)||n===va.OnBridge&&!m.isBridge()))){var I=z(I=m.isBuilding()?g===t?0:k.distance3(g,s)/gr.ISO_TILE_SIZE:m.isTerrain()||m.isOverlay()?k.distance3(g,t)/gr.ISO_TILE_SIZE:k.distance3(m,s)/gr.ISO_TILE_SIZE,3);if(!(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&&b<I||(S.add(m),_.set(m,m.isBuilding()?(_.get(m)||[]).concat(I):[I]))}}let A=!1,C;for(f of S)if(!f.isDestroyed&&!f.isCrashing){var B,E=this.computeDamage(e,f,c);if(E)for(var x of _.get(f)){let t=E;if(0<b&&Number.isFinite(t)&&(t=La.Math.lerp(t,v*t,x/b)),Math.abs(t)<1&&(!b||.25<=t/E)&&(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&&x<1&&(C=f),this.inflictDamage(t,f,h,i,!C))break;f.isVehicle()&&this.rules.rocker&&(0<(B=U(E/300,0,1))&&(x=is.fromMapCoords(f.position.getMapPosition().clone().sub(gr.vecWorldToGround(gr.vecWorldToLeptons(s))))-f.direction,f.applyRocking(x,B)))}}}else f.isTechno()&&f.invulnerableTrait.isActive()&&(A=!0)}y=y.rules.radLevel;y&&b&&i.mapRadiationTrait.createRadSite(t,y,b+1);p=p?void 0:A?i.rules.audioVisual.weaponNullifyAnim:this.pickExplodeAnim(e,C,a,i,c);if(!A&&a===dr.Ground){let e=new Na;p&&e.destroyOre(p,t,i),u&&e.spawnSmudges(u,t,i),p&&e.spawnSmudges(p,t,i)}i.events.dispatch(new Ba(this,s,p,c))}pickExplodeAnim(t,i,r,s,a){if(t){if(a)return s.rules.audioVisual.weatherConBoltExplosion;if(this.rules.conventional&&r===dr.Water&&(!i||i.isBuilding()||i.isVehicle()&&i.submergibleTrait)){var n=s.rules.combatDamage.splashList;return n[U(Math.floor(t/50),0,n.length-1)]}n=this.rules.animList.length;let e;return n?(e=s.rules.combatDamage.c4Warhead===this.rules.name?n-1:this.rules.emEffect?s.generateRandomInt(0,n-1):U(Math.floor(t/25),0,n-1),this.rules.animList[e]):void 0}}}Fa.SPECIAL_WARHEAD_NAME="Special",Fa.HE_WARHEAD_NAME="HE";class ja{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 ja([this.forward,this.lateral,this.vertical])}}class Wa{constructor(e,t){this.weapon=e,this.gameObject=t,this.type=Xi.WeaponFire}}(s=Da=Da||{})[s.LandOk=0]="LandOk",s[s.LandNotOk=1]="LandNotOk",s[s.LandSecondary=2]="LandSecondary",(s=Ma=Ma||{})[s.UnderwaterNever=0]="UnderwaterNever",s[s.UnderwaterSecondary=1]="UnderwaterSecondary",s[s.UnderwaterOnly=2]="UnderwaterOnly",s[s.OrganicSecondary=3]="OrganicSecondary",s[s.SealSpecial=4]="SealSpecial",s[s.NavalAll=5]="NavalAll",s[s.NavalNone=6]="NavalNone";class Ua{constructor(e,t,i,r,s,a){this.weaponType=e,this.projectileRules=t,this.weaponRules=i,this.warheadRules=r,this.gameObject=s,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===si.Secondary?this.targetChecks.push((e,t,i,r,s)=>!(!s||!e?.isBuilding()||e.name!==a||e.owner!==this.gameObject.owner)):this.warheadRules.electricAssault?this.targetChecks.push((e,t,i,r,s)=>!(!r&&!s||!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,r,s)=>!s&&!!(!this.warheadRules.bombDisarm||e?.isTechno()&&e.tntChargeTrait?.hasCharge())):this.targetChecks.push((e,t,i,r)=>!((!r||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,r,s)=>!(s&&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,r)=>!!(!e&&r||e?.isInfantry()||(e?.isVehicle()||e?.isAircraft())&&e.parasiteableTrait)),this.warheadRules.mindControl&&this.targetChecks.push(e=>!(!e?.isTechno()||!e.mindControllableTrait))),this.targetChecks.push((e,t)=>this.canTargetZone(e,t))}canTarget(t,i,r,s,a){return this.targetChecks.every(e=>e(t,i,r,s,a))}canTargetZone(e,t){let i;if(e?.isUnit()){if(e?.isInfantry()&&e.stance===Br.Paradrop)return this.projectileRules.isAntiAir&&(this.projectileRules.isAntiGround||this.weaponType===si.Secondary);if(e.zone===dr.Air)return this.projectileRules.isAntiAir;if(this.weaponType===si.Secondary&&this.projectileRules.isAntiAir)return!1;i=e.zone}else i=t.landType===Yt.Water?dr.Water:dr.Ground;return i===dr.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 Da.LandOk:return!0;case Da.LandNotOk:return!1;case Da.LandSecondary:return t===si.Secondary;default:throw new Error(`Unhandled LandTargeting value "${e}"`)}}canTargetNaval(e,t,i,r){switch(e){case Ma.UnderwaterNever:return!i||!(i.isVehicle()&&i.submergibleTrait?.isSubmerged());case Ma.UnderwaterSecondary:return i&&i.isVehicle()&&i.submergibleTrait&&!t.rules.spawned?r===si.Secondary:r===si.Primary;case Ma.UnderwaterOnly:return!!(i&&i.isVehicle()&&i.submergibleTrait);case Ma.OrganicSecondary:return i?.isTechno()&&i.rules.organic?r===si.Secondary:r===si.Primary;case Ma.SealSpecial:return i?.isTechno()&&i.rules.naval&&!i.rules.organic&&(i.isBuilding()||i.rules.speedType===Kt.Float)?r===si.Secondary:r===si.Primary;case Ma.NavalAll:return!0;case Ma.NavalNone:return!1;default:throw new Error(`Unhandled NavalTargeting value "${e}"`)}}}var Va=__webpack_require__(949);class za{constructor(e,t,i,r,s,a,n){this.type=e,this.gameObject=t,this.rules=i,this.warhead=r,this.projectileRules=s,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,r,s){var a=r.getWeapon(e);let n=a.warhead;n===Fa.SPECIAL_WARHEAD_NAME&&(n=za.findSpecialWarheadName(a,i,r));var o=new Fa(r.getWarhead(n)),e=r.getProjectile(a.projectile),r=new Ua(t,e,a,o.rules,i,r.general);return new this(t,i,a,o,e,s||new ja,r)}static findSpecialWarheadName(e,t,i){let r;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)r=i.combatDamage.v3Warhead;else if(t.rules.spawns===i.general.dMisl.type)r=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,Ct.Aircraft);if(!t.primary)throw new Error(`Spawned unit "${t.name}" doesn't have a primary weapon`);r=i.getWeapon(t.primary).warhead}return r}static computeSpeed(e,t){return t.arcing?.75*Si.iniSpeedToLeptonsPerTick(50):!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===si.Secondary&&this.gameObject.primaryWeapon?Math.min(this.gameObject.primaryWeapon.rules.range,this.rules.range):this.rules.range}get speed(){return za.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,s,a=1){let n=this.gameObject,e,o=0;if(!n.airSpawnTrait||!this.rules.spawner||(e=n.airSpawnTrait.prepareLaunch(n,r,s),o=n.airSpawnTrait.availableSpawns,e)){this.burstsLeft?(this.burstsLeft--,this.burstIndex++,this.lateralMuzzleMult*=-1):(this.useBurstDelay=!1,this.burstIndex=0,e?this.burstsLeft=o: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<o?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]:s.generateRandomInt(3,5)),this.burstsLeft||this.resetBursts(),this.rules.limboLaunch&&(s.limboObject(this.gameObject,{selected:s.getUnitSelection().isSelected(this.gameObject),controlGroup:s.getUnitSelection().getOrCreateSelectionModel(this.gameObject).getControlGroupNumber()}),this.warhead.rules.parasite&&(r.obj?.isVehicle()||r.obj?.isAircraft())&&r.obj.parasiteableTrait&&(r.obj.parasiteableTrait.beingBoarded=!0));let t=e??s.createProjectile(this.projectileRules.name,this.gameObject,this,r,!1);t.isAircraft()||(t.baseDamageMultiplier=a*(this.gameObject.isUnit()?this.gameObject.crateBonuses.firepower:1));let i=this.flh.clone();i.lateral*=this.lateralMuzzleMult;var h=n.position.getMapPosition();if(s.map.isWithinHardBounds(gr.vecLeptonsToWorld(h))){t.position.moveToLeptons(h),t.position.tileElevation=n.position.tileElevation;let e=new Va.Vector2(i.lateral,i.forward);a=this.getMuzzleFacing()+this.distributedFireAngle;e=Hr(e,a);var h=Hr(h=new Va.Vector2(0,n.art.turretOffset),n.direction);e.add(h),n.rules.radialFireSegments&&n.rules.distributedFire&&(h=Math.floor(180/n.rules.radialFireSegments),this.distributedFireAngle=(this.distributedFireAngle+h+90)%180-90),t.direction=a,n.isBuilding()&&n.rules.turretAnim&&n.rules.turretAnimX&&(c=gr.screenDistanceToLeptons(n.rules.turretAnimX,n.rules.turretAnimY),l=n.getFoundationCenterOffset(),t.position.moveByLeptons(-l.x+c.x,-l.y+c.y));var l=new Va.Vector3(e.x,i.vertical,-e.y),c=gr.vecLeptonsToWorld(l).add(t.position.worldPosition);if(s.map.isWithinHardBounds(c)&&t.position.moveByLeptons3(l),t.tileElevation<0&&(t.position.tileElevation=0),t.isAircraft()?s.unlimboObject(t,t.position.tile):s.spawnObject(t,t.position.tile),this.rules.revealOnFire&&r.obj?.isTechno()){let e=s.mapShroudTrait.getPlayerShroud(r.obj.owner);e?.isShrouded(n.tile)&&e.revealTemporarily(n)}this.rules.decloakToFire&&this.gameObject.cloakableTrait?.uncloak(s),s.events.dispatch(new Wa(this,this.gameObject))}}}getMuzzleFacing(){let e=this.gameObject,t;return t=!e.isInfantry()&&!e.isAircraft()&&(e.isBuilding()||e.isVehicle())&&e.turretTrait?e.turretTrait.facing:e.direction,t}}za.NUKE_PAYLOAD_NAME="NukePayload";var Ha,Ga,$a,qa=__webpack_require__(949);class Za extends Dr{constructor(e,t,i,r){super(e,t,i),this.weaponType=r}onStart(t){var i=t.rules.getWeapon(this.weaponType),r=t.createTarget(void 0,this.tile),s=this.owner.getOwnedObjectsByType(Ct.Building).find(e=>e.rules.nukeSilo);if(s){let e=za.factory(i.name,si.Primary,s,t.rules);e.fire(r,t)}else this.fireLooseNuke(i,r,t)}fireLooseNuke(t,i,r){var s=new qa.Vector2(this.tile.rx+.5,this.tile.ry+.5).multiplyScalar(gr.ISO_TILE_SIZE);if(r.map.isWithinHardBounds(s)){let e=r.createLooseProjectile(t.name,this.owner,i);e.position.moveToLeptons(gr.vecWorldToLeptons(s)),e.position.tileElevation=gr.worldToTileHeight(gr.leptonsToWorld(e.rules.detonationAltitude)),r.spawnObject(e,e.position.tile)}}onTick(e){return!0}}class Qa{constructor(e,t){this.art=e,this.init(t)}init(e){this.shadow=this.art.getBool("Shadow"),this.reverse=this.art.getBool("Reverse"),this.frameCount="number"==typeof e?e:this.shadow?e.numImages/2:e.numImages,this.end=this.art.getNumber("End",this.frameCount-1);e=this.art.getNumberArray("RandomRate").sort();2===e.length?this.rate=W(e[0],e[1])/60:this.rate=this.art.getNumber("Rate",60*Qa.defaultRate)/60,this.start=this.art.getNumber("Start",0),this.loopStart=this.art.getNumber("LoopStart",0),this.loopEnd=Math.max(this.loopStart,this.art.getNumber("LoopEnd",this.end+1)-1),this.loopCount=this.art.getNumber("LoopCount",1);e=this.art.getNumberArray("RandomLoopDelay").sort();this.randomLoopDelay=2===e.length?[e[0],e[1]]:void 0}getArt(){return this.art}setArt(e){this.art=e,this.init(this.frameCount)}}Qa.defaultRate=xr.BASE_TICKS_PER_SECOND;class Xa{constructor(e){this.position=e,this.type=Xi.LightningStormCloud}}class Ya{constructor(e){this.target=e,this.type=Xi.LightningStormManifest}}(s=Ha=Ha||{})[s.Approaching=0]="Approaching",s[s.Manifesting=1]="Manifesting";class Ka extends Dr{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 Ya(this.tile)))),this.state===Ha.Manifesting){var i,s=t.rules.general.lightningStorm;if(0<this.manifestEndTimer&&(this.manifestEndTimer--,0<this.nextDirectHitTimer&&this.nextDirectHitTimer--,this.nextDirectHitTimer<=0&&(this.nextDirectHitTimer=s.hitDelay,this.spawnCloudAt(this.tile,t)),0<this.nextRandomHitTimer&&this.nextRandomHitTimer--,this.nextRandomHitTimer<=0)){this.nextRandomHitTimer=s.scatterDelay;var a=Math.floor(s.cellSpread/2);let i=s.separation,r=new br(t.map.tileOccupation),e=new Ps(t.map.tiles,t.map.mapBounds,this.tile,a,t,t=>!this.clouds.some(e=>r.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 r=s.warhead;let e=new Fa(t.rules.getWarhead(r));var n=i.tile,o=t.map.tileOccupation.getBridgeOnTile(n),h=o?.tileElevation??0,r=t.map.getTileZone(n);e.detonate(t,s.damage,n,h,gr.tile3dToWorld(n.rx+.5,n.ry+.5,n.z+h),r,o?va.OnBridge:va.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),i=t.art.getAnimation(t.rules.audioVisual.weatherConClouds[i]),i=new Qa(i.art,60),i=Math.floor(xr.BASE_TICKS_PER_SECOND/i.rate*60);this.clouds.push({tile:e,durationTicks:i,ticksLeft:i});i=(t.map.tileOccupation.getBridgeOnTile(e)?.tileElevation??0)+gr.worldToTileHeight(gr.leptonsToWorld(t.rules.general.flightLevel)),i=gr.tile3dToWorld(e.rx+.5,e.ry+.5,e.z+i);t.events.dispatch(new Xa(i))}}class Ja extends Dr{onStart(e){var t,i,r=e.rules.combatDamage.ironCurtainDuration,s={player:this.owner};let a=new Pr(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,s):(i.invulnerableTrait.setActiveFor(r,e.currentTick),(i.isVehicle()||i.isAircraft())&&i.parasiteableTrait?.isInfested()&&i.parasiteableTrait.destroyParasite(s,e)))}onTick(e){return!0}}class en extends Dr{constructor(e,t,i,r){super(e,t,i),this.tile2=r,this.objectsToTeleport=[]}onStart(i){this.delayTicks=i.rules.general.chronoDelay;let r=i.map.tiles;for(let t=-1;t<=1;t++)for(let e=-1;e<=1;e++){var s=r.getByMapCoords(this.tile.rx+t,this.tile.ry+e);if(s){var a,n=!!s.onBridgeLandType,o=r.getByMapCoords(this.tile2.rx+t,this.tile2.ry+e);for(a of i.map.getGroundObjectsOnTile(s))!a.isUnit()||a.tile!==s||a.onBridge!==n||a.isInfantry()&&a.stance===Br.Paradrop||a.isDisposed||(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,r=h?l.map.tileOccupation.getBridgeOnTile(h):void 0,s=l.map.getGroundObjectsOnTile(h),a=s.find(e=>e.isBuilding());var c=s.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.owner===o.owner;let e=!1,n=o.rules.speedType;o.rules.movementZone===ii.Fly&&(n=Kt.Wheel);var u=l.map.mapBounds.isWithinBounds(h);if(!(t||l.map.terrain.getPassableSpeed(h,n,!!r)&&u)){let t=!1;if(!c&&(0<l.map.terrain.getPassableSpeed(h,n,!!r,void 0,!0)||!u)){a&&(i=!0);let e=new Pr(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,r=l.map.tileOccupation.getBridgeOnTile(h),s=l.map.getGroundObjectsOnTile(h),t=!0)}t||(o.moveTrait.teleportUnitToTile(h,r,!0,!1,l),o.warpedOutTrait.setActive(!1,!0,l),l.map.getTileZone(h)===dr.Water&&(o.deathType=Ls.Sink),l.destroyObject(o,{player:this.owner}),e=!0)}if(!e||c)for(let t of s)t.isDisposed||t.isUnit()&&(this.objectsToTeleport.some(({obj:e})=>e===t)||t.onBridge!==!!r&&t.tile===h||2<Math.abs(t.tileElevation-o.tileElevation)||(t.isInfantry()&&t.stance!==Br.Paradrop&&(t.deathType=Ls.Crush),l.destroyObject(t,{player:this.owner,obj:o})));e||(o.moveTrait.teleportUnitToTile(h,r,!0,!1,l),t&&a?.dockTrait&&(t=a.dockTrait.getAllDockTiles().indexOf(h),a.dockTrait.undockUnitAt(t),a.dockTrait.dockUnitAt(o,t)),i?o.warpedOutTrait.setTimed(l.rules.general.chronoDelay,!1,l):o.warpedOutTrait.setActive(!1,!0,l))}return!0}}(Ga=Ga||{}).onDeactivate=Symbol();class tn{constructor(){this.effects=[]}[_r.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===Ir.NotStarted&&(t.onStart(i),t.status=Ir.Running),t.onTick(i)&&(t.status=Ir.Finished,i.traits.filter(Ga).forEach(e=>{e[Ga.onDeactivate](t.type,t.owner,i)}));this.effects=this.effects.filter(e=>e.status!==Ir.Finished)}[Ar.onPowerLow](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!1)})}[Ar.onPowerRestore](e,t){e.superWeaponsTrait?.getAll()?.filter(e=>e.rules.isPowered).forEach(e=>{this.updateTimer(e,!0)})}[Ar.onPowerChange](e,t){}[kr.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,r,s){let a=e.superWeaponsTrait?.getAll().find(e=>e.rules.type===t);if(a&&a.status===Or.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,r,s)}}activateEffect(e,i,r,s,a,n=!1){const o=e.type;if(void 0!==o){let t=[];switch(o){case Qi.AmerParaDrop:for(var[h,l]of r.rules.general.paradrop.amerParaDrop.entries())t.push(new Aa(o,i,s,l,h));break;case Qi.ParaDrop:{let e=r.rules.general.paradrop.getParadropSquads(i.country.side);for(var[c,u]of e.entries())t.push(new Aa(o,i,s,u,c));break}case Qi.MultiMissile:if(!e.weaponType)throw new Error("Missing WeaponType in super weapon rules");t.push(new Za(o,i,s,e.weaponType));break;case Qi.LightningStorm:t.push(new Ka(o,i,s));break;case Qi.IronCurtain:t.push(new Ja(o,i,s));break;case Qi.ChronoSphere:if(!a)throw new Error("Missing tile2 action param");t.push(new en(o,i,s,a))}for(var d of t)this.addEffect(d);r.traits.filter(Cr).forEach(e=>{e[Cr.onActivate](o,i,r,s,a)}),r.events.dispatch(new Mr(o,i,s,a,n))}}}class rn{constructor(e){this.target=e,this.type=Xi.ObjectCloakChange}}($a=$a||{}).onDamage=Symbol();class sn{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 rn(this.gameObject)))}resetCloakCooldown(){this.cooldownTicks=Math.floor(60*this.cloakDelayMinutes*xr.BASE_TICKS_PER_SECOND)}[qs.onSpawn](e,t){this.resetCloakCooldown()}[Ts.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 rn(this.gameObject)))}[$a.onDamage](e,t){this.uncloak(t)}dispose(){this.gameObject=void 0}}class an{static calculateOverlayId(e,t,i){let r;if("number"!=typeof e?(r=xa.getOverlayTibType(e.id),t=e.rx,i=e.ry):r=e,r!==_a.NotSpecial){var t=gr.tileToScreen(t,i),{x:i,y:t}=gr.screenToScreenTile(t.x,t.y),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,r===_a.Ore?xa.minIdRiparius+i:r===_a.Gems?xa.minIdCruentus+i:r===_a.Vinifera?xa.minIdVinifera+i:r===_a.Aboreus?xa.minIdAboreus+i:void 0}}}var nn,on,hn=__webpack_require__(949);const ln=[Sr.IonStorm,Sr.Gas,Sr.Pod,Sr.Squad];class cn{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,r=!1,s=!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)===dr.Water;t?(u||(i=c),s=u):u?r=s=!0:t=i=c}else if(t&&!c)break}t&&(e.push(t),i&&i!==t&&e.push(i),r||s||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}[_r.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)===dr.Water,i=this.choosePowerup(i,t.rules.powerups.powerups,t);if(i)return this.spawnCrateAt(e,i,t)}}spawnCrateAt(t,i,r){if(this.canPlaceCrateOnTile(r,t)){var s=r.map.getTileZone(t,!0)===dr.Water,a=r.rules.crateRules,s=s?a.waterCrateImg:a.crateImg;let e=r.createObject(Ct.Overlay,s);e.overlayId=r.rules.getOverlayId(s),e.value=0,r.spawnObject(e,t);r=60*a.crateRegen*xr.BASE_TICKS_PER_SECOND*(.5+1.5*r.generateRandom());return this.crates.push({obj:e,powerup:i,ticksLeft:r}),e}}chooseSpawnTile(e,t){return t.generateRandom()<(this.mapEdgeIsWater?1/3:2/3)&&(e=this.availEdgeTiles),this.chooseRandomTile(e,t)}chooseRandomTile(e,t){let i;let r=0;for(;i=e[t.generateRandomInt(0,e.length-1)],r++,r<100&&!this.canPlaceCrateOnTile(t,i););if(100<=r){var s=t.map.tileOccupation.getEmptyTiles();if(!s.length)return;i=s[t.generateRandomInt(0,s.length-1)]}return i}canPlaceCrateOnTile(e,t){return e.map.mapBounds.isWithinBounds(t)&&!e.map.getGroundObjectsOnTile(t).length&&0<e.map.terrain.getPassableSpeed(t,Kt.Amphibious,!1)&&t.terrainType!==Xt.Shore&&0===t.rampType}choosePowerup(t,i,r){if((i=t?i.filter(e=>e.waterAllowed):i).length){var s,t=i.reduce((e,t)=>e+t.probShares,0),a=r.generateRandomInt(0,t);let e=0;for(s of i)if(e+=s.probShares,a<e)return s}}peekInsideCrate(t){return this.crates.find(e=>e.obj===t)?.powerup.type}pickupCrate(e,t,i){let r=this.crates.find(e=>e.obj===t);if(r){this.crates.splice(this.crates.indexOf(r),1),i.unspawnObject(r.obj),r.obj.dispose();let t=this.grantPowerup(e,r.powerup,r.obj.tile,i);var s;return void 0!==t&&(s=i.rules.powerups.powerups.find(e=>e.type===t),i.events.dispatch(new ur(s,e.owner,e,r.obj.tile))),this.randomCrateSpawn&&this.spawnCrateAtRandom(this.allTiles,i),t}}grantPowerup(t,i,r,s){let a=t.owner,n=!1;if(a.isCombatant()){if(i.type===Sr.Unit){let e;if(![...a.buildings].some(e=>e.rules.constructionYard)&&s.rules.crateRules.freeMCV){let t=s.rules.general.baseUnit;if(!a.getOwnedObjects(!0).some(e=>t.includes(e.name))&&a.credits>=[...s.rules.ai.buildPower,...s.rules.ai.buildRefinery].map(e=>s.rules.getBuilding(e)).filter(e=>e.aiBasePlanningSide===a.country.side).reduce((e,t)=>e+t.cost,0)){var o=t.find(e=>{let t=s.rules.getObject(e,Ct.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=s.rules.getObject(o,Ct.Vehicle)}}if(e||(h=s.rules.crateRules.unitCrateType?[s.rules.getObject(s.rules.crateRules.unitCrateType,Ct.Vehicle)]:[...s.rules.vehicleRules.values()].filter(e=>e.crateGoodie&&0<s.map.terrain.getPassableSpeed(r,e.speedType,!1))).length&&(e=h[s.generateRandomInt(0,h.length-1)]),e){let t=s.createUnitForPlayer(e,a);var h=new Pr(s.map.tiles,s.map.mapBounds,r,{width:1,height:1},0,3,e=>0<s.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&!s.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length).getNextTile();h?(s.spawnObject(t,h),n=!0):(a.removeOwnedObject(t),t.dispose())}}else if(i.type===Sr.Money){if(!i.data)throw new Error("Money powerup missing data field");a.credits+=Math.floor(Number(i.data)*(.55+2*s.generateRandom()*.45)),n=!0}else if(i.type===Sr.HealBase){var e;for(e of a.getOwnedObjects(!0))e.isDestroyed||e.healthTrait.healToFull(void 0,s);n=!0}else if(i.type===Sr.Reveal)s.mapShroudTrait.revealMap(a,s),n=!0;else if(i.type===Sr.Darkness)s.mapShroudTrait.resetShroud(a,s),n=!0;else if(i.type===Sr.Veteran){if(t.veteranTrait&&!t.veteranTrait.isMaxLevel()){n=!0;var l,c=Number(i.data);for(l of this.getUnitsInCrateRadius(s,r,a))l.veteranTrait?.promote(c,s)}}else if(i.type===Sr.Armor){if(1===t.crateBonuses.armor){n=!0;var u,d=Number(i.data);for(u of this.getUnitsInCrateRadius(s,r,a))1===u.crateBonuses.armor&&(u.crateBonuses.armor=d)}}else if(i.type===Sr.Firepower){if(1===t.crateBonuses.firepower){n=!0;var p,g=Number(i.data);for(p of this.getUnitsInCrateRadius(s,r,a))1===p.crateBonuses.firepower&&(p.crateBonuses.firepower=g)}}else if(i.type===Sr.Speed){if(1===t.crateBonuses.speed){n=!0;var m,f=Number(i.data);for(m of this.getUnitsInCrateRadius(s,r,a))1===m.crateBonuses.speed&&(m.crateBonuses.speed=f)}}else if(i.type===Sr.Cloak){if(!t.cloakableTrait){n=!0;for(var y of this.getUnitsInCrateRadius(s,r,a))y.cloakableTrait||(y.cloakableTrait=new sn(y,s.rules.general.cloakDelay),s.addObjectTrait(y,y.cloakableTrait))}}else if(i.type===Sr.ICBM){var w=[...s.rules.superWeaponRules.values()].find(e=>e.type===Qi.MultiMissile);if(w&&a.superWeaponsTrait&&!a.superWeaponsTrait.has(w.name)){let e=s.createSuperWeapon(w.name,a,!0);e.isGift=!0,a.superWeaponsTrait.add(e),n=!0}}else if(i.type===Sr.Invulnerability){var T=[...s.rules.superWeaponRules.values()].find(e=>e.type===Qi.IronCurtain);T&&(s.traits.get(tn).activateEffect(T,a,s,r,void 0,!0),n=!0)}else if(i.type===Sr.Explosion||i.type===Sr.Napalm){n=!0;w=Number(i.data),T=i.type===Sr.Napalm?s.rules.combatDamage.flameDamage:s.rules.combatDamage.c4Warhead;let e=new Fa(s.rules.getWarhead(T));e.detonate(s,w,t.tile,t.tileElevation,t.position.worldPosition,t.zone,va.None,s.createTarget(t,t.tile),{player:t.owner,weapon:void 0},!1,!1,void 0,0)}else{if(i.type!==Sr.Tiberium)return void console.warn(`Unhandled powerup type "${Sr[i.type]}"`);{let e=new Ps(s.map.tiles,s.map.mapBounds,r,2,s,e=>Pa.canBePlacedOn(e,s.map)),t,i=0;for(;i++<6&&(t=e.getNextTile());){var b=an.calculateOverlayId(_a.Ore,t.rx,t.ry);if(void 0===b)throw new Error("Expected an overlayId");let e=s.createObject(Ct.Overlay,s.rules.getOverlayName(b));e.overlayId=b,e.value=3,s.spawnObject(e,t),n=!0}}}if(n)return i.type;i=s.rules.powerups.powerups.find(e=>e.type===Sr.Money&&0<e.probShares);return i?this.grantPowerup(t,i,r,s):void 0}}getUnitsInCrateRadius(e,t,i){let r=e.rules.crateRules.crateRadius,s=new br(e.map.tileOccupation);return e.map.technosByTile.queryRange((new hn.Box2).setFromCenterAndSize(new hn.Vector2(t.rx,t.ry),new hn.Vector2(r,r))).filter(e=>e.owner===i&&e.isUnit()&&s.tileDistance(e,t)<=r)}}class un{constructor(){this.powerups=[]}readIni(e){for(var[s,a]of e.entries){let[e,t,i,r]=a.split(",");var n=Number(e),a=Sr[s];void 0!==a?ln.includes(a)||this.powerups.push({type:a,probShares:n,animName:"<none>"!==t.toLowerCase()?t:void 0,waterAllowed:"yes"===i,data:r}):console.warn(`Unknown powerup "${s}". Skipping.`)}return this}}const dn=["Gold","DarkRed","DarkBlue","DarkGreen","Orange","DarkSky","Purple","Magenta"];class pn{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 un,this.colors=new Map,this.general=new Fi,this.ai=new nr,this.crateRules=new cr,this.elevationModel=new or,this.mpDialogSettings=new St,this.audioVisual=new ki,this.combatDamage=new sr,this.radiation=new hr,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}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 _i(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);var i;if(t||(i=this.ini.getSection(e))&&(t=new Vi(i),this.warheadRules.set(e,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 zi(Ct.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}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 dn.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===Yt.Cliff?"Rock":Yt[e],t=(new Ui).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}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(Ct.Building,this.buildingRules).set(Ct.Infantry,this.infantryRules).set(Ct.Vehicle,this.vehicleRules).set(Ct.Aircraft,this.aircraftRules).set(Ct.Terrain,this.terrainRules).set(Ct.Overlay,this.overlayRules).set(Ct.Smudge,this.smudgeRules).set(Ct.VoxelAnim,this.voxelAnimRules),this.readObjects(Ct.Building,this.buildingTypes,this.buildingRules),this.readObjects(Ct.Infantry,this.infantryTypes,this.infantryRules),this.readObjects(Ct.Vehicle,this.vehicleTypes,this.vehicleRules),this.readObjects(Ct.Aircraft,this.aircraftTypes,this.aircraftRules),this.readObjects(Ct.Terrain,this.terrainTypes,this.terrainRules),this.readObjects(Ct.Overlay,this.overlayTypes,this.overlayRules),this.readObjects(Ct.Smudge,this.smudgeTypes,this.smudgeRules),this.readObjects(Ct.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,r){let e=this.ini.getSection(i);if(!e)throw new Error(`Missing [${i}] section`);let s=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.`):(r.set(s++,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,r,e]=e.split(","),e=j.fromHsv(parseInt(i,10),parseInt(r,10),parseInt(e,10));this.colors.set(t,e)})}readObjects(r,e,s){e.forEach((e,t)=>{var i=this.ini.getSection(e);i?(t=(new rr).create(r,i,t),s.set(e,t)):this.logger?.debug(`${Ct[r]} 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 r=new vi(t);r.readIni(i),this.countryRules.set(e,r)})}readWarheads(){this.warheadTypes.forEach(e=>{var t=this.ini.getSection(e);t?(t=new Vi(t),this.warheadRules.set(e,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 ar).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 lr(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 r,i;e.add(za.NUKE_PAYLOAD_NAME);for(let i of[...this.buildingRules.values(),...this.aircraftRules.values(),...this.vehicleRules.values(),...this.infantryRules.values()])for(r 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(ga).filter(e=>""!==e))e.add(r);let s=0;for(i of e)this.weaponTypes.set(s++,i)}}(s=nn=nn||{})[s.Ready=0]="Ready",s[s.Guard=1]="Guard",s[s.Prone=2]="Prone",s[s.Walk=3]="Walk",s[s.FireUp=4]="FireUp",s[s.Down=5]="Down",s[s.Crawl=6]="Crawl",s[s.Up=7]="Up",s[s.FireProne=8]="FireProne",s[s.Idle1=9]="Idle1",s[s.Idle2=10]="Idle2",s[s.Die1=11]="Die1",s[s.Die2=12]="Die2",s[s.Hover=13]="Hover",s[s.Fly=14]="Fly",s[s.FireFly=15]="FireFly",s[s.Tumble=16]="Tumble",s[s.AirDeathStart=17]="AirDeathStart",s[s.AirDeathFalling=18]="AirDeathFalling",s[s.AirDeathFinish=19]="AirDeathFinish",s[s.Tread=20]="Tread",s[s.Swim=21]="Swim",s[s.WetAttack=22]="WetAttack",s[s.WetIdle1=23]="WetIdle1",s[s.WetIdle2=24]="WetIdle2",s[s.WetDie1=25]="WetDie1",s[s.WetDie2=26]="WetDie2",s[s.Deploy=27]="Deploy",s[s.Deployed=28]="Deployed",s[s.DeployedFire=29]="DeployedFire",s[s.DeployedIdle=30]="DeployedIdle",s[s.Undeploy=31]="Undeploy",s[s.Paradrop=32]="Paradrop",s[s.Cheer=33]="Cheer",s[s.Panic=34]="Panic";const gn=new Map([["E",5],["S",3],["W",1],["N",7]]);class mn{readIni(e){let t=new Map;for(var[i,r]of e.entries){i=nn[i];void 0!==i&&(r=r.split(","),r={type:i,startFrame:Number(r[0]),frameCount:Number(r[1]),facingMult:Number(r[2]),onlyFacing:r[3]?gn.get(r[3]):void 0},t.set(i,r))}return t}}(s=on=on||{})[s.None=0]="None",s[s.Global=1]="Global",s[s.Level=2]="Level",s[s.Ambient=3]="Ambient",s[s.Full=4]="Full",s[s.Default=5]="Default";var fn,yn,wn,Tn=__webpack_require__(949);class bn{constructor(e,t,i){this.dockingOffsets=[],this.type=e,this.rules=t,this.art=i,this.init()}static getDefaultPalette(e){switch(e){case Ct.Building:case Ct.Aircraft:case Ct.Infantry:case Ct.Vehicle:case Ct.Projectile:case Ct.VoxelAnim:return O.Unit;case Ct.Overlay:return O.Overlay;case Ct.Smudge:case Ct.Terrain:return O.Iso;default:Ct.Animation;return O.Anim}}static getDefaultLighting(e){switch(e){case Ct.Animation:return on.None;case Ct.Aircraft:case Ct.Building:case Ct.Infantry:case Ct.Vehicle:return on.Ambient;case Ct.Projectile:case Ct.VoxelAnim:return on.Global;case Ct.Overlay:case Ct.Smudge:case Ct.Terrain:default:return on.Full}}static getDefaultRemapability(e){switch(e){case Ct.Aircraft:case Ct.Building:case Ct.Infantry:case Ct.Vehicle:return!0;case Ct.Overlay:case Ct.Smudge:case Ct.Terrain:case Ct.Animation:case Ct.Projectile:case Ct.VoxelAnim:return!1;default:throw new Error(`Unknown object type ${e}`)}}static getDefaultDrawOffset(e){switch(e){case Ct.Animation:case Ct.Building:case Ct.Vehicle:case Ct.Infantry:case Ct.Overlay:case Ct.Smudge:case Ct.Projectile:case Ct.VoxelAnim:return new Tn.Vector2(0,0);case Ct.Terrain:case Ct.Aircraft:return new Tn.Vector2(0,(gr.ISO_TILE_SIZE+1)/2);default:throw new Error(`Unknown object type ${e}`)}}static getDefaultShadow(e){switch(e){case Ct.Overlay:case Ct.Building:case Ct.Infantry:case Ct.Terrain:case Ct.Vehicle:case Ct.Aircraft:return!0;default:case Ct.Smudge:case Ct.Animation:case Ct.Projectile:case Ct.VoxelAnim:return!1}}static getDefaultHeight(e){switch(e){case Ct.Building:return 2;case Ct.Infantry:case Ct.Vehicle:case Ct.Aircraft:return 1;default:return 0}}static factory(e,t,i,r){var s=t.imageName;let a=i.getSection(s);a||(r?.debug(`Image ${s} (${Ct[e]}: ${t.name}) has no section in art.ini`),a=new h(s));let n=new this(e,t,a);return e===Ct.Infantry&&(!(e=a.getString("Sequence"))||(e=i.getSection(e))&&(n.sequences=(new mn).readIni(e))),n}init(){this.image=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 Tn.Vector2(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",bn.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",bn.getDefaultHeight(this.type)),this.isVoxel=this.art.getBool("Voxel"),this.occupyHeight=this.art.getNumber("OccupyHeight",this.height),this.type===Ct.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")||bn.MISSING_CAMEO;return e.toLowerCase()}get altCameo(){let e=this.art.getString("AltCameo")||bn.MISSING_CAMEO;return e.toLowerCase()}get useTheaterExtension(){return this.art.getBool("Theater")}readPaletteAndLightingTypes(){this.paletteType=O.Default,this.lightingType=on.Default,(this.rules instanceof Ji?this.rules.noUseTileLandType:void 0)&&(this.paletteType=O.Iso,this.lightingType=on.Full),this.art.getBool("TerrainPalette")||this.art.getBool("ShouldUseCellDrawer")?this.paletteType=O.Iso:this.art.getBool("AnimPalette")?(this.paletteType=O.Anim,this.lightingType=on.None):this.art.getString("Palette")&&(this.paletteType=O.Custom,this.customPaletteName=this.art.getString("Palette")),this.art.getBool("AltPalette")&&(this.paletteType=O.Unit),(this.rules instanceof Ji||this.rules instanceof Ki)&&this.rules.wall&&(this.paletteType=O.Unit,this.lightingType=on.Ambient),(this.rules instanceof er||this.rules instanceof Ki)&&this.rules.gate&&(this.paletteType=O.Unit),this.rules instanceof er&&this.rules.spawnsTiberium&&(this.paletteType=O.Unit,this.lightingType=on.None),this.rules instanceof Ji&&(this.rules.isVeins&&(this.paletteType=O.Unit,this.lightingType=on.None),this.rules.isVeinholeMonster&&(this.paletteType=O.Unit,this.lightingType=on.None),this.rules.tiberium&&(this.lightingType=on.None),this.rules.land===Yt.Railroad&&(this.paletteType=O.Iso,this.lightingType=on.Full),this.rules.crate&&(this.paletteType=O.Iso,this.lightingType=on.Full)),this.paletteType===O.Default&&(this.paletteType=bn.getDefaultPalette(this.type)),this.lightingType===on.Default&&(this.lightingType=bn.getDefaultLighting(this.type))}readRemapability(){this.remapable=bn.getDefaultRemapability(this.type),this.art.getBool("TerrainPalette")||this.art.getBool("AnimPalette")?this.remapable=!1:this.rules instanceof zi&&this.rules.firersPalette&&(this.remapable=!0)}readFlatness(){let e=!1;this.type===Ct.Building||this.type===Ct.Animation?e=this.art.getBool("Flat"):this.type===Ct.Smudge&&(e=!0),this.rules instanceof Ji&&(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 r=this.art.getNumberArray(`Rotor${e+1}Axis`,void 0,[0,1,0]),r=new Tn.Vector3(-r[2],-r[0],r[1]).normalize();t.push({name:i[e],axis:r,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[r,s]=this.art.getNumberArray(t);i.push({x:r,y:s}),e++,t=`MuzzleFlash${e}`}this.muzzleFlash=i.length?i:void 0}readDockingOffsets(){if(this.type===Ct.Building){var t=this.rules.numberOfDocks;for(let e=0;e<t;e++){var[i,r,s]=this.art.getNumberArray(`DockingOffset${e}`,/\,\s*/,[0,0,0]);this.dockingOffsets.push(new Tn.Vector3(i,s,r))}}}readAddRemoveOccupy(e){let t=0,i=[];for(;;){var r=this.art.getNumberArray(e+ ++t);if(!r.length)break;i.push(new Tn.Vector2(r[0],r[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{x:Math.floor(this.foundation.width/2-.5),y:Math.floor(this.foundation.height/2-.5)}}getDrawOffset(){if(this.rules instanceof er&&this.rules.spawnsTiberium)return new Tn.Vector2(0,0);let e=bn.getDefaultDrawOffset(this.type);return this.rules instanceof Ji&&this.rules.isARock&&(e.y+=(gr.ISO_TILE_SIZE+1)/2),e}get hasShadow(){return this.art.getBool("Shadow",bn.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 ja(this.art.getNumberArray("PrimaryFireFLH"))}get elitePrimaryFireFlh(){var e=this.art.getNumberArray("ElitePrimaryFireFLH");return e.length?new ja(e):this.primaryFireFlh}get primaryFirePixelOffset(){return this.art.getNumberArray("PrimaryFirePixelOffset")}get secondaryFirePixelOffset(){return this.art.getNumberArray("SecondaryFirePixelOffset")}get secondaryFireFlh(){return new ja(this.art.getNumberArray("SecondaryFireFLH"))}get eliteSecondaryFireFlh(){var e=this.art.getNumberArray("EliteSecondaryFireFLH");return e.length?new ja(e):this.secondaryFireFlh}getSpecialWeaponFlh(e){return new ja(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}}bn.DEFAULT_LINE_TRAIL_DEC=16,bn.MISSING_CAMEO="xxicon";class vn{constructor(e,t,i){this.rules=e,this.artIni=t,this.logger=i,this.objectArt=new Map,this.parse()}hasObject(e,t){return this.objectArt.get(t)?.has(e)}getObject(e,t){t=this.objectArt.get(t)?.get(e);if(!t)throw new Error(`Missing art for object "${e}"`);return t}getOrCreateObject(e,t){return this.hasObject(e,t)?this.getObject(e,t):new bn(t,this.rules.hasObject(e,t)?this.rules.getObject(e,t):new Si(t,new h(e)),new h(e))}getAnimation(e){return this.getObject(e,Ct.Animation)}getProjectile(e){e=this.rules.getProjectile(e);return bn.factory(e.type,e,this.artIni,this.logger)}getIni(){return this.artIni}parse(){this.rules.allObjectRules.forEach((e,t)=>{let i=new Map;this.objectArt.set(t,i),e.forEach(e=>{var t;this.artIni.getSection(e.imageName)?(t=bn.factory(e.type,e,this.artIni),i.set(e.name,t)):this.logger?.debug(`${Ct[e.type]} "${e.name}" has no art section`)})});let e=[[Ct.Animation,this.rules.animationNames]];e.forEach(([r,e])=>{let s=new Map;this.objectArt.set(r,s),e.forEach(e=>{var t,i=this.artIni.getSection(e);i?(t=new Si(r,new h(e)),i=new bn(r,t,i),s.set(e,i)):this.logger?.debug(`${Ct[r]} "${e}" has no art section`)})})}}class Sn{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 Ct.Aircraft:i=this.rules.veteranAircraft;break;case Ct.Infantry:i=this.rules.veteranInfantry;break;case Ct.Vehicle:i=this.rules.veteranUnits;break;default:throw new Error(`Unsupported object type "${Ct[e]}"`)}return i.includes(t)}}class _n{constructor(e,t){this.target=e,this.player=t,this.type=Xi.BuildingEvacuate}}class kn{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}[$a.onDamage](e,t){e.healthTrait.health<=100*this.evacThreshold&&this.evacuate(t)}[Ms.onDestroy](e,t,i,r){if(r){for(var s of this.units)t.destroyObject(s,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(r,s=!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 Pr(r.map.tiles,r.map.mapBounds,a.tile,a.art.foundation,1,1,e=>0<r.map.terrain.getPassableSpeed(e,t,!1)&&Math.abs(e.z-a.tile.z)<2&&!r.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),r.unlimboObject(o,h),o.unitOrderTrait.addTask(new Ds(r))):s||(r.destroyObject(o,{player:o.owner}),n.splice(l,1))}}var i=a.owner;n.length||a.isDestroyed||r.changeObjectOwner(a,r.getCivilianPlayer()),r.events.dispatch(new _n(a,i))}}}class On{constructor(){this.facing=0,this.desiredFacing=0}isRotating(){return this.facing!==this.desiredFacing}[Ts.onTick](e){this.desiredFacing!==this.facing&&(e=e.rules.rot,this.facing=is.tick(this.facing,this.desiredFacing,e||Number.POSITIVE_INFINITY).facing)}}class In{constructor(e,t){this.target=e,this.status=t,this.type=Xi.BuildStatusChange}}class An{constructor(e){this.target=e,this.type=Xi.PowerLow}}class Cn{constructor(e){this.target=e,this.type=Xi.PowerRestore}}class Bn{constructor(e,t,i){this.target=e,this.power=t,this.drain=i,this.type=Xi.PowerChange}}(s=fn=fn||{})[s.Low=0]="Low",s[s.Normal=1]="Normal";class En{constructor(e){this.player=e,this.power=0,this.drain=0,this.level=fn.Normal,this.blackoutFrames=0,this.powerByObject=new Map}isLowPower(){return this.level===fn.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,r){var s=t.rules.power;if(s){if(s<0)"add"!==i&&"remove"!==i||(this.drain+="add"===i?-s:s);else{let e=0;if("add"===i){var a=Math.ceil(s*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?(s=Math.ceil(s*t.healthTrait.health/100),this.powerByObject.set(t,s),s-a):(this.powerByObject.delete(t),-a)}this.power+=e}this.updateLevel(r),r.traits.filter(Ar).forEach(e=>{e[Ar.onPowerChange](this.player,r)}),r.events.dispatch(new Bn(this.player,this.power,this.drain))}}updateLevel(t){var e=this.level;this.level=this.power>=this.drain&&!this.blackoutFrames?fn.Normal:fn.Low,this.level!==e&&(e===fn.Normal&&this.level===fn.Low&&(t.traits.filter(Ar).forEach(e=>{e[Ar.onPowerLow](this.player,t)}),t.events.dispatch(new An(this.player))),e===fn.Low&&this.level===fn.Normal&&(t.traits.filter(Ar).forEach(e=>{e[Ar.onPowerRestore](this.player,t)}),t.events.dispatch(new Cn(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 xn{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.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!==fn.Low))}dispose(){this.obj=void 0}}class Pn{constructor(){this.listeners=new Set}subscribe(e){this.listeners.add(e)}subscribeOnce(i){let r=(e,t)=>{i(e,t),this.unsubscribe(r),r=void 0};this.subscribe(r)}unsubscribe(e){this.listeners.delete(e)}dispatch(t,i){this.listeners.forEach(e=>e(i,t))}asEvent(){return this}}(s=yn=yn||{})[s.Structures=0]="Structures",s[s.Armory=1]="Armory",s[s.Infantry=2]="Infantry",s[s.Vehicles=3]="Vehicles",s[s.Aircrafts=4]="Aircrafts",s[s.Ships=5]="Ships",(s=wn=wn||{})[s.Idle=0]="Idle",s[s.Active=1]="Active",s[s.OnHold=2]="OnHold",s[s.Ready=3]="Ready";class Nn{constructor(e,t,i){this.type=e,this._maxSize=t,this.maxItemQuantity=i,this.items=[],this.size=0,this._status=wn.Idle,this._onUpdate=new Pn}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,r=0;for(;i<=this.size&&r<this.items.length;){let e=this.items[r];i+=e.quantity,i>this.size&&(e.quantity-=i-this.size),0<e.quantity&&r++}this._maxSize=e,this.items[r]&&this.items.splice(r),t!==this.size&&(this.size||(this._status=wn.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 r=this.find(e).reduce((e,t)=>e+t.quantity,0);t=Math.min(this.maxItemQuantity-r,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===wn.Idle&&(this._status=wn.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 r=this.find(e);if(!r.length)throw new Error(`Can't remove non-existent item ${e.name} from queue ${yn[this.type]}`);var s;if(r.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?r.shift():r.pop();e.quantity<=a?(s=this.getFirst()===e,this.items.splice(this.items.indexOf(e),1),s&&(this._status=wn.Active),a-=e.quantity):(e.quantity-=a,a=0)}this.size-=t,t&&(this.size||(this._status=wn.Idle),this._onUpdate.dispatch(this))}notifyUpdated(){this._onUpdate.dispatch(this)}}class Rn extends Us{constructor(e,t,i,r){super(e,i,!1,{ignoredBlockers:[t],closeEnoughTiles:0,strictCloseEnough:!0,forceWaitOnPathBlocked:t.factoryTrait?.type!==qi.InfantryType}),this.factory=t,this.rallyPoint=r,this.preventOpportunityFire=!0,this.cancellable=!1}canStopAtTile(e,t,i){return!this.game.map.tileOccupation.isTileOccupiedBy(t,this.factory)&&super.canStopAtTile(e,t,i)}onTick(e){return e.moveTrait.moveState===zs.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)}}var Dn,Mn,Ln,Fn,jn=__webpack_require__(949);class Wn{constructor(e,t,i,r,s,a=()=>!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=s,this.predicate=a,this.dirVec=new jn.Vector2(10,0),this.finished=!1,this.diagonal=!0,this.distance=r}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 jn.Vector2,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}}}(Dn=Dn||{}).onSell=Symbol();class Un{[Zs.onUnspawn](e){this.undock(e),this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[$s.onChange](e){e.owner!==this.dock?.owner&&this.undock(e),e.owner!==this.reservedDock?.owner&&this.reservedDock?.dockTrait.unreserveDockForUnit(e)}[Cs.onBeforeTeleport](e,t,i,r){r||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 Vn{constructor(e,t,i,r){this.building=e,this.tiles=t,this.numberOfDocks=i,this.dockingOffsets=r,this.ticksWhenWarpedOut=!0,this.unitsByDockNumber=new Array(i).fill(void 0),this.reservedDocks=new Array(i).fill(void 0)}[qs.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}}[Zs.onUnspawn](){for(let e=0;e<this.numberOfDocks;e++)this.unreserveDockAt(e)}[Ts.onTick](){for(let e=0;e<this.numberOfDocks;e++){var t=this.unitsByDockNumber[e];t&&t.tile!==this.getDockTile(e)&&this.undockUnit(t)}}[Ms.onDestroy](e,t,i,r){var s=(e.rules.unitRepair||e.helipadTrait)&&!e.rules.naval&&!i?.weapon?.warhead.rules.temporal;if(s)for(var a of this.unitsByDockNumber)a&&!a.isDestroyed&&(s?t.destroyObject(a,i,r):this.undockUnit(a))}[Dn.onSell](r,s){if(r.helipadTrait&&this.hasDockedUnits()){var a,e,n;let t=[],i=0;for(a of[...r.owner.buildings].filter(e=>e.helipadTrait&&(e.dockTrait?.getAvailableDockCount()??!1)&&e!==r)){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 Is(s,n)):e.unitOrderTrait.addTask(new ma(new Us(s,e.tile,!1),new _s(e=>{e.crashableTrait?e.crashableTrait.crash({player:r.owner}):s.destroyObject(e,{player:r.owner})})).setCancellable(!1))),i++}else{var t,i=r.rules.unitRepair&&!r.rules.naval;for(t of this.unitsByDockNumber)t&&(i?s.sellTrait.sell(t):this.undockUnit(t))}}[$s.onChange](e,t,i){for(var r of this.unitsByDockNumber)r&&i.changeObjectOwner(r,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]}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)/gr.LEPTONS_PER_TILE),Math.floor((t.y+e.z)/gr.LEPTONS_PER_TILE))}isValidUnitForDock(e){return(this.building.unitRepairTrait&&e.isVehicle()&&(!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}`);(this.unitsByDockNumber[t]=e).traits.get(Un).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(Un).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(ga)}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(Un).reservedDock?.dockTrait.unreserveDockForUnit(e),e.traits.get(Un).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(Un).reservedDock=void 0)}unreserveDockForUnit(e){e=this.reservedDocks.indexOf(e);-1!==e&&this.unreserveDockAt(e)}hasReservedDockForUnit(e){return!!this.reservedDocks.includes(e)}getReservedDockForUnit(e){e=this.reservedDocks.indexOf(e);if(-1!==e)return e}dispose(){this.building=void 0}}class zn{constructor(e){this.target=e,this.type=Xi.FactoryProduceUnit}}(s=Mn=Mn||{})[s.All=0]="All",s[s.Ground=1]="Ground",s[s.Air=2]="Air";class Hn{constructor(e){this.tiles=e,this.tileOccupation=[],this.emptyTiles=new Set,this._onChange=new Pn;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===Yt.Rock)return Yt.Rock;var t,i=Wi(e.terrainType);for(t of this.tileOccupation[e.rx]?.[e.ry]??[]){if((t.isOverlay()||t.isBuilding())&&t.rules.wall)return Yt.Wall;if(t.isOverlay()&&t.isTiberium())return Yt.Tiberium;if(t.isOverlay()&&t.rules.land!==Yt.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()?Yt.Road:t.rules.land}getTileZone(e,t=!1){return mr(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===dr.Air||t.push(i);return t}getAirObjectsOnTile(e){let t=[];for(var i of this.tileOccupation[e.rx]?.[e.ry]??[])i.isUnit()&&i.zone===dr.Air&&t.push(i);return t}getObjectsOnTileByLayer(e,t){if(t===Mn.Ground)return this.getGroundObjectsOnTile(e);if(t===Mn.Air)return this.getAirObjectsOnTile(e);if(t===Mn.All)return this.getObjectsOnTile(e);throw new Error(`Unhandled layer type "${t}"`)}getEmptyTiles(){return[...this.emptyTiles]}}(Ln=Ln||{}).onChange=Symbol(),(Fn=Fn||{}).onProduce=Symbol();var Gn,$n=__webpack_require__(949);(s=Gn=Gn||{})[s.Idle=0]="Idle",s[s.Delivering=1]="Delivering";class qn{constructor(e,t=!1){this.type=e,this.isCloningVats=t,this.status=Gn.Idle}[qs.onSpawn](e,t){this.resetRallyPoint(e,t)}resetRallyPoint(e,t){var i;[qi.BuildingType,qi.AircraftType].includes(this.type)||(i=this.computeDefaultRallyPoint(e,this.type,t.map),e.rallyTrait?.changeRallyPoint(i,e,t))}[Ln.onChange](t,e,i){if(t.owner.production){let e=[];e=this.type===qi.BuildingType?[yn.Structures,yn.Armory]:[t.owner.production.getQueueTypeForFactory(this.type)];for(var r of e)t.owner.production.getQueue(r).notifyUpdated()}}[Ts.onTick](i,r){if(this.status===Gn.Delivering){if(!this.deliveringUnit||this.deliveringUnit.isDestroyed){if(this.buildingProductionTicks=this.buildingProductionTicks??1,0<this.buildingProductionTicks--)return;this.buildingProductionTicks=void 0}else if(r.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=Gn.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===qi.UnitType)&&this.type!==qi.BuildingType){let e=i.owner.production.getQueueForFactory(this.type);if(e&&e.status===wn.Ready){let t=e.getFirst();if(this.type===qi.AircraftType){let e=this.produceAircraftAt(i,t,r);var s;if(!e)for(s of[...i.owner.buildings].filter(e=>e.factoryTrait?.type===qi.AircraftType&&e.helipadTrait)){if(e)break;e=this.produceAircraftAt(s,t,r)}if(!e)return}else if(this.produceGroundUnitAt(i,t,r),!this.isCloningVats&&this.type===qi.InfantryType){let e=[...i.owner.buildings].find(e=>e.factoryTrait&&e.rules.cloning);e?.factoryTrait.status===Gn.Idle&&e?.factoryTrait.produceGroundUnitAt(e,t,r)}i.owner.unitsBuilt++,t.creditsSpent=0,t.progress=0,e.shift(t.rules,1),e.currentSize&&(e.status=wn.Active)}}}}produceGroundUnitAt(e,t,i){let r=i.createUnitForPlayer(t.rules,e.owner);t.rules.trainable&&e.owner.canProduceVeteran(r.rules)&&r.veteranTrait?.setVeteranLevel(Xs.Veteran),r.isInfantry()&&(r.position.subCell=ca.SUB_CELLS[0]);let s=e.rallyTrait.findRallyPointforUnit(r,this.computeInternalRallyPoint(e,this.type,e.rallyTrait.getRallyPoint(),i.map),i.map),a;var n;a=this.type===qi.NavalUnitType?s:(n=this.computeExitCoords(e,this.type),i.map.tiles.getByMapCoords(Math.floor(n.rx),Math.floor(n.ry))),r.rules.consideredAircraft&&(s=a);let o;if(e.rallyTrait.getRallyPoint()!==s&&(o=e.rallyTrait.findRallyNodeForUnit(r,i.map)),r.isInfantry()){let t=i.map.tileOccupation.getObjectsOnTileByLayer(o?.tile??s,r.rules.consideredAircraft?Mn.Air:Mn.Ground).filter(e=>e.isInfantry()&&e.moveTrait.moveState!==zs.Moving).map(e=>e.position.subCell);r.position.subCell=ca.SUB_CELLS.find(e=>!t.includes(e))??ca.SUB_CELLS[0]}r.direction=270,i.spawnObject(r,a),i.traits.filter(Fn).forEach(e=>{e[Fn.onProduce](r,i)}),i.events.dispatch(new zn(r)),r.rules.consideredAircraft?(n=o??{tile:s,onBridge:void 0},r.unitOrderTrait.addTask(new Us(i,n.tile,!!n.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))):r.unitOrderTrait.addTask(new Rn(i,e,s,o)),this.status=Gn.Delivering,this.deliveringUnit=r}produceAircraftAt(e,t,i){let r=e.traits.find(Vn);if(!r)return!1;var s=r.getFirstAvailableDockNumber();if(void 0===s)return!1;let a=i.createUnitForPlayer(t.rules,e.owner);t.rules.trainable&&e.owner.canProduceVeteran(a.rules)&&a.veteranTrait?.setVeteranLevel(Xs.Veteran);t=r.getDockOffset(s);return a.position.moveToLeptons(e.position.getMapPosition()),a.position.moveByLeptons3(t),i.spawnObject(a,a.position.tile),r.dockUnitAt(a,s),a.isAircraft()&&a.airportBoundTrait&&(a.airportBoundTrait.preferredAirport=e),i.traits.filter(Fn).forEach(e=>{e[Fn.onProduce](a,i)}),i.events.dispatch(new zn(a)),!0}computeExitCoords(e,t){if(t===qi.InfantryType)return this.computeBarracksDefaultExitCoords(e);if(t===qi.UnitType)return this.computeWarFactoryExitCoords(e);throw new Error(`Unsupported factory type ${qi[t]}`)}computeInternalRallyPoint(e,t,i,r){let s,a;if(t===qi.NavalUnitType)a=this.computeNavalInternalRallyPoint(e,i,r);else{if(t===qi.InfantryType)s=this.computeBarracksInternalRallyCoords(e);else{if(t!==qi.UnitType)throw new Error(`Unsupported factory type ${qi[t]}`);s=this.computeWarFactoryInternalRallyCoords(e)}a=r.tiles.getByMapCoords(s.rx,s.ry)}return a??this.findTileAdjacentToBuilding(e,r)}computeDefaultRallyPoint(e,t,i){let r,s;if(t===qi.NavalUnitType)s=this.computeNavalDefaultRallyPoint(e,i);else{if(t===qi.InfantryType)r=this.computeBarracksInternalRallyCoords(e);else{if(t!==qi.UnitType)throw new Error(`Unsupported factory type ${qi[t]}`);r=this.computeWarFactoryDefaultRallyCoords(e)}s=i.tiles.getByMapCoords(r.rx,r.ry)}return s??this.findTileAdjacentToBuilding(e,i)}findTileAdjacentToBuilding(e,t){return new Pr(t.tiles,t.mapBounds,e.tile,e.getFoundation(),1,1,()=>!0).getNextTile()}computeBarracksDefaultExitCoords(e){var t=e.getFoundation();let i,r;return t.width<=2||t.height<=2?(i=t.width-1,r=t.height-1,e.rules.gdiBarracks&&2<t.width&&(i=Math.floor(t.width/2))):(i=0,r=t.height-1),{rx:e.tile.rx+i,ry:e.tile.ry+r}}computeBarracksInternalRallyCoords(e){var t=e.getFoundation();let{rx:i,ry:r}=this.computeBarracksDefaultExitCoords(e);return!(t.width<=2||t.height<=2)||e.rules.gdiBarracks?r+=1:e.rules.nodBarracks&&(i+=t.width<=2?1:0,r+=t.height<=2?1:0),{rx:i,ry:r}}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 Wn(t.tiles,t.mapBounds,e.centerTile,5,5,e=>e.terrainType===Xt.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 $n.Vector2(t.rx,t.ry).sub(new $n.Vector2(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 Zn{constructor(e,t,i,r,s,a,n,o=!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.foundation=r,this.maxDistance=a,this.predicate=n,this.checkBounds=o,this.distance=s,this.generator=this.generate()}getNextTile(){return this.generator.next().value}*generate(){var r=(e,t)=>{t=this.tiles.getByMapCoords(e,t);if(t&&(!this.checkBounds||this.mapBounds.isWithinBounds(t))&&this.predicate(t))return t};do{var s=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=r(s,t),i&&(yield i);for(e=s;e<n;e++)i=r(e,a),i&&(yield i);for(t=o-1;t>=a;t--)i=r(n,t),i&&(yield i);for(e=n;e>=s;e--)i=r(e,o),i&&(yield i)}else this.predicate(this.startTile)&&(yield this.startTile)}while(this.distance++,this.distance<=this.maxDistance)}}class Qn{[qs.onSpawn](i,r){let e;if(r.rules.hasObject(i.rules.freeUnit,Ct.Vehicle))e=r.rules.getObject(i.rules.freeUnit,Ct.Vehicle);else{if(!r.rules.hasObject(i.rules.freeUnit,Ct.Infantry))return void console.warn(`Free unit "${i.rules.freeUnit}" is not a vehicle or infantry type.`);e=r.rules.getObject(i.rules.freeUnit,Ct.Infantry)}let s=r.createUnitForPlayer(e,i.owner),a;var t=new Zn(r.map.tiles,r.map.mapBounds,i.tile,i.getFoundation(),1,1,e=>{var t=0<r.map.terrain.getPassableSpeed(e,s.rules.speedType,!1)&&Math.abs(e.z-i.tile.z)<2&&!r.map.terrain.findObstacles({tile:e,onBridge:void 0},s).length;return!a&&t&&(a=e),t&&!r.map.getObjectsOnTile(e).find(e=>e.isOverlay())}).getNextTile()??a;if(!t)return i.owner.removeOwnedObject(s),void s.dispose();r.spawnObject(s,t)}}class Xn{[Dn.onSell](e,t){this.spawnSurvivors(e,t)}[Ms.onDestroy](e,t,i,r){r||i?.obj===e&&i.weapon?.rules.suicide||e.isVehicle()&&e.moveTrait.isMoving()||e.crashableTrait||this.spawnSurvivors(e,t)}spawnSurvivors(r,s){var t=s.rules.general.crew,e=r.owner.country.side;let i,a;if(e===qt.GDI)i=t.alliedSurvivorDivisor,a=t.alliedCrew;else{if(e!==qt.Nod)return;i=t.sovietSurvivorDivisor,a=t.sovietCrew}let n=Math.ceil(r.rules.cost*t.survivorRate/i);r.isVehicle()&&(n=Math.min(1,n));let o=[];for(let e=0;e<n;e++)(0===e||s.generateRandom()>=t.crewEscape)&&o.push(a);if(r.rules.constructionYard&&(o=[...o,s.rules.general.engineer]),0<o.length){var h,l=s.map.tiles.getInRectangle(r.tile,r.getFoundation()).filter(e=>s.map.isWithinBounds(e));let i=[...l];for(h of o){var c=s.rules.getObject(h,Ct.Infantry);if(s.map.terrain.getPassableSpeed(r.tile,c.speedType,!r.isBuilding()&&r.onBridge,void 0,!0)){let e=s.createUnitForPlayer(c,r.owner),t=i.length?i.splice(s.generateRandomInt(0,i.length-1),1)[0]:void 0;t=t||l[s.generateRandomInt(0,l.length-1)],e.isInfantry()&&(e.position.subCell=ca.SUB_CELLS[0]),e.veteranTrait&&r.owner.canProduceVeteran(e.rules)&&e.veteranTrait.setVeteranLevel(Xs.Veteran),s.spawnObject(e,t),r.isBuilding()&&e.unitOrderTrait.addTask(new Ds(s,void 0,{ignoredBlockers:r.isDestroyed?void 0:[r]}))}}}}}class Yn{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 r=this.findClosestBridgeBounds();if(!r)throw new Error("No bridge bounds found");var e=this.bridges.findDestroyedPieceTiles(r),s=r.start.rx!==r.end.rx;let a;a=r.isHigh?Ca.calculateHighBridgeOverlayId(r.type,s):Ca.calculateLowBridgeOverlayId(r.type,s);var n,o,h=t.rules.getOverlayName(a);for(n of e){let e=t.createObject(Ct.Overlay,h);e.overlayId=a,e.value=0,e.position.tileElevation=r.isHigh?4:0,t.spawnObject(e,n),this.updateUnitsUnderBridgePiece(n,r,t,i)}for(o of this.bridges.findBridgePieces(r))o.obj.bridgeTrait.bridgeSpec=r}updateUnitsUnderBridgePiece(e,i,r,s){var a;for(let t of this.bridges.getPieceTiles(this.bridges.getPieceAtTile(e)))if(i.isHigh){let e=r.map.getGroundObjectsOnTile(t).filter(e=>e.tile===t&&e.isUnit()&&!e.unitOrderTrait.hasTasks()&&e.rules.tooBigToFitUnderBridge);e.forEach(e=>e.unitOrderTrait.addTask(new Ds(r)))}else for(a of r.map.getGroundObjectsOnTile(t))a.isUnit()&&(r.map.terrain.getPassableSpeed(t,a.rules.speedType,!0)?(a.zone=dr.Ground,a.onBridge=!0):a.isDestroyed||r.destroyObject(a,{player:s}))}demolishBridge(e,t){var i=this.getBridgePieces();if(i)for(var r of i)r.obj.isLowBridge()&&e.map.getTileZone(r.obj.tile,!0)!==dr.Water||r.obj.isDestroyed||(r.obj.deathType=Ls.Demolish,e.destroyObject(r.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 Kn{constructor(){this.isActive=!1,this.produceCashCooldown=0}[qs.onSpawn](e){e.owner.isNeutral||(this.isActive=!0)}[$s.onChange](e,t){t.isNeutral&&!e.owner.isNeutral&&(e.owner.credits+=e.rules.produceCashStartup,this.isActive=!0,this.produceCashCooldown=e.rules.produceCashDelay)}[Ts.onTick](e){this.isActive&&(this.produceCashCooldown--,this.produceCashCooldown<=0&&(this.produceCashCooldown=e.rules.produceCashDelay,e.owner.credits+=e.rules.produceCashAmount))}}class Jn{constructor(){this.linkedDamageHandled=!1}[$a.onDamage](e,t,i,r){if(!this.linkedDamageHandled){var s=Math.floor(i/2);if(s)for(var a of t.map.tiles.getAllNeighbourTiles(e.tile))if(a.landType===Yt.Wall){let e=t.map.getObjectsOnTile(a).find(e=>(e.isBuilding()||e.isOverlay())&&e.wallTrait);e.wallTrait.linkedDamageHandled=!0,e.healthTrait.inflictDamage(s,r,t),e.wallTrait.linkedDamageHandled=!1,e.healthTrait.health||t.destroyObject(e,r)}}}}const eo=e=>void 0!==e.position;class to{constructor(e,t){this.tiles=e,this.tileOccupation=t}hasLineOfSight(e,t,i){var r=i.warhead.rules.wall||!i.projectileRules.subjectToWalls,s=i.projectileRules.subjectToCliffs,a=i.rules.spawner;let n=0,o=!1;if(!r||s||a){var h,l,c=eo(e)?e.tile:e,t=eo(t)?t.tile:t;for({x:h,y:l}of pa(c.rx,c.ry,t.rx,t.ry)){var u=this.tiles.getByMapCoords(h,l);if(!r&&u.landType===Yt.Wall)return!1;if(s)if(u.landType===Yt.Cliff){if(u.z>c.z)return!1;o=!0}else{if(u.z>c.z&&o)return!1;o=!1}if(a&&n<2&&this.tileOccupation.getBridgeOnTile(u)?.isHighBridge())return!1;n++}}return!0}}var io=__webpack_require__(949);class ro extends Us{constructor(e,t,i,r){super(e,t instanceof ra?t.isBuilding()?t.centerTile:t.tile:t,i,{pathFinderIgnoredBlockers:t instanceof ra?[t]:void 0}),this.target=t,this.weapon=r,this.recalcMinRange=!0,this.cancelRequested=!1,this.bomberInitialLock=!1,this.rangeHelper=new br(e.map.tileOccupation),this.losHelper=new to(e.map.tiles,e.map.tileOccupation)}onStart(i){let e=this.target,r=this.game.map;if(e instanceof ra&&e.isBuilding()&&i.rules.movementZone!==ii.Fly){let t=e.tile;var s=e instanceof ra?e.getFoundation():{width:1,height:1},s=new Pr(r.tiles,r.mapBounds,t,s,1,5,e=>0<r.terrain.getPassableSpeed(e,i.rules.speedType,!1)&&Math.abs(e.z-t.z)<2).getNextTile();s&&this.rangeHelper.tileDistance(e,s)>Math.SQRT2&&this.updateTarget(s,!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===ii.Fly&&e.rules.locomotor===ti.Aircraft&&e.rules.fighter&&1<this.weapon.projectileRules.iniRot}isBombingRun(e){return e.rules.movementZone===ii.Fly&&e.rules.locomotor===ti.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 Ps(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!==dr.Air&&this.target instanceof ra&&this.game.map.tileOccupation.isTileOccupiedBy(e,this.target)&&(!this.target.isUnit()||this.target.tile===e&&this.target.moveTrait.moveState!==zs.Moving))return!1;if(t.zone!==dr.Air){if(!super.canStopAtTile(t,e,i))return!1}else if(this.game.map.tileOccupation.getAirObjectsOnTile(e).filter(e=>e.isUnit()&&e.moveTrait.moveState!==zs.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===dr.Air?e.position.computeSubCellOffset(e.position.desiredSubCell):e.position.getTileOffset(),{minRange:r,range:s}=this.rangeHelper.computeWeaponRangeVsTarget(t,this.target,this.weapon,this.game.rules),i=gr.tile3dToWorld(t.rx+i.x/gr.LEPTONS_PER_TILE,t.ry+i.y/gr.LEPTONS_PER_TILE,t.z+e.position.tileElevation);return(e.isUnit()&&e.rules.movementZone===ii.Fly?this.rangeHelper.isInRange2(i,this.target,r,s):this.rangeHelper.isInRange3(i,this.target,r,s))&&this.losHelper.hasLineOfSight(t,this.target,this.weapon)}findRelocationTile(t,i,r){if(r.rules.movementZone!==ii.Fly)return super.findRelocationTile(t,i,r);{i=this.game.map;let e=new Ps(i.tiles,i.mapBounds,t,1,this.game,e=>this.isCancelling()||this.isCloseEnoughToDest(r,e));return e.getNextTile()}}retarget(e,t){var i=e instanceof ra?e.isBuilding()?e.centerTile:e.tile:e;this.updateTarget(i,t),this.target=e,this.options?.ignoredBlockers&&(this.options.ignoredBlockers=e instanceof ra?[e]:void 0),this.options??(this.options={}),this.options.pathFinderIgnoredBlockers=e instanceof ra?[e]:void 0,this.recalcMinRange=!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 ra?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target,!1),!this.isAirStrafeCloseEnough(r)||(s=this.findStrafeDestination(r,this.targetTile))&&this.updateTarget(s,!1)),this.isBombingRun(r)&&!this.isCancelling()&&(!r.ammo||this.weapon.getBurstsFired()||this.bomberInitialLock)&&!this.bomberManeuverTile){this.bomberInitialLock=!1;let t=r.position.getMapPosition();e=this.target instanceof ra?this.target.isBuilding()?this.target.centerTile:this.target.tile:this.target;let i=new io.Vector2(e.rx+.5,e.ry+.5).clone().multiplyScalar(gr.LEPTONS_PER_TILE).sub(t);var s=i.length();if(0<s){let e=t.clone().add(i.setLength(s+7*gr.LEPTONS_PER_TILE));s=e.multiplyScalar(1/gr.LEPTONS_PER_TILE).floor(),s=pa(s.x,s.y,r.tile.rx,r.tile.ry);s.length&&(s=s[0],this.bomberManeuverTile=this.game.map.tiles.getByMapCoords(s.x,s.y)??this.game.map.tiles.getPlaceholderTile(s.x,s.y))}this.bomberManeuverTile??(this.bomberManeuverTile=e),this.options.allowOutOfBoundsTarget=!0,this.updateTarget(this.bomberManeuverTile,!1)}return this.bomberManeuverTile&&this.bomberCanReturn(r.tile)&&(this.bomberManeuverTile=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:r}=this.rangeHelper.computeWeaponRangeVsTarget(e,this.target,this.weapon,this.game.rules);return e.rules.locomotor===ti.Chrono?this.rangeHelper.isInRange(e,this.target,r-1,r,this.weapon.rules.cellRangefinding)?t:this.findTileInRange(e,t,r-1,2*r)??t:this.rangeHelper.isInRange(e,this.target,i,Number.POSITIVE_INFINITY,this.weapon.rules.cellRangefinding)?t:this.findTileInRange(e,t,2*i,r-i)}findTileInRange(t,e,i,r){let s=this.game.map;var a,i=new io.Vector2(t.tile.rx-e.rx,t.tile.ry-e.ry).setLength(i).floor().add(new io.Vector2(e.rx,e.ry));let n;for(a of pa(i.x,i.y,e.rx,e.ry))if(n=s.tiles.getByMapCoords(a.x,a.y),n)break;if(n){let e=new Pr(s.tiles,s.mapBounds,n,{width:1,height:1},0,r,e=>this.rangeHelper.isInWeaponRange(t,this.target,this.weapon,this.game.rules,e)&&this.losHelper.hasLineOfSight(e,this.target,this.weapon)&&0<s.terrain.getPassableSpeed(e,t.rules.speedType,!!e.onBridgeLandType)&&!s.terrain.findObstacles({tile:e,onBridge:!!e.onBridgeLandType},t).length);return e.getNextTile()}}}class so{tick(e,t){this.tickChildren(e,t)}startTask(e,t){if(e.status!==Er.NotStarted)throw new Error(`Attempted to start a task with status ${e.status}`);e.status=Er.Running,e.onStart(t)}tickTask(e,t){let i=this.tickChildren(e.children,t);var r=e.children.find(e=>e.blocking);if(!i&&r)return!1;if(!t.isSpawned)return!1;if(e.status===Er.NotStarted)throw new Error("Attempted tick on a non-started task");if(e.isRunning()||e.isCancelling()){var s=e.isCancelling(),a=!!e.waitingForChildrenToFinish||e.onTick(t);e.children.length&&!r&&a&&(i=e.children.every(e=>e.status===Er.Cancelled||e.status===Er.Finished),e.waitingForChildrenToFinish=!i);a=a&&i;return a&&(e.onEnd(t),e.status=s?Er.Cancelled:Er.Finished),a}return!0}tickChildren(r,s){let a=!0;if(r.length){let t=new Set,i;for(;s.isSpawned&&(i=r.find(e=>!t.has(e)));){let e;if(i.status===Er.NotStarted&&this.startTask(i,s),i.status===Er.Running||i.status===Er.Cancelling)e=!0===this.tickTask(i,s);else{if(i.status!==Er.Cancelled)throw new Error(`Unhandled task status ${Er[i.status]}`);e=!0}if(e){var n=r.indexOf(i);-1!==n&&r.splice(n,1)}else{if(a=!1,i.blocking)break;t.add(i)}}}return a}}class ao{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===Yt.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:gr.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)}}var no,oo=__webpack_require__(949);(s=no=no||{})[s.Idle=0]="Idle",s[s.CheckRange=1]="CheckRange",s[s.PrepareToFire=2]="PrepareToFire",s[s.FireUp=3]="FireUp",s[s.Firing=4]="Firing",s[s.JustFired=5]="JustFired";class ho{constructor(e,t){this.disabled=!1,this.attackState=no.Idle,this.passiveScanCooldownTicks=0,this.taskRunner=new so,this.distributedFireHistory=new Map,this.rangeHelper=new br(t),this.losHelper=new to(e,t)}isIdle(){return this.attackState===no.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}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===qt.GDI?e.primaryWeapon:e.secondaryWeapon??e.primaryWeapon:void 0:e.isBuilding()&&e.overpoweredTrait?e.overpoweredTrait.getWeapon():e.primaryWeapon;return i}selectWeaponVersus(e,t,i,r=!1,s=!1){var a=t.tile;const n=t instanceof ao?t.obj:t;t=this.getAvailableWeapons(e,s,n?.isOverlay()||r&&!n);return this.selectWeaponFromList(e,n,a,t,i,r,s,!1)}selectWeaponFromList(e,t,i,r,s,a,n,o){if((!t?.isInfantry()&&!t?.isVehicle()||!t.disguiseTrait||this.canAttackThroughDisguise(e,t,t.disguiseTrait,s,a,n,o))&&(t?.isBuilding()&&t.overpoweredTrait&&t.owner===e.owner&&r.find(e=>e.warhead.rules.electricAssault)&&(r=r.filter(e=>e.warhead.rules.electricAssault)),!(n&&t?.isAircraft()&&t.missileSpawnTrait&&t.zone!==dr.Air))){var h=t?.isTechno()?t.rules.armor:void 0;for(const l of r)if(l.targeting.canTarget(t,i,s,a,n)&&(void 0===h||this.checkArmor(l.warhead.rules,h,n)))return l}}getAvailableWeapons(e,t,i){let r;var s;return r=(e.isInfantry()||e.isVehicle())&&e.rules.deployFire&&e.armedTrait?(s=e.armedTrait.getDeployFireWeapon(),[e.deployerTrait?.isDeployed()?s.rules.areaFire?void 0:s:s===e.secondaryWeapon?e.primaryWeapon:e.secondaryWeapon]):e.isBuilding()&&e.garrisonTrait?e.garrisonTrait.isOccupied()?[e.owner.country.side===qt.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],r.filter(e=>e&&!e.rules.neverUse)}canAttackThroughDisguise(e,t,i,r,s,a,n){if(!s&&i.hasTerrainDisguise()&&!r.areFriendly(e,t)&&!e.owner.sharedDetectDisguiseTrait?.has(t))return!1;if(a){if(n&&t.moveTrait.isIdle()&&!e.rules.detectDisguise&&!r.areFriendly(t,e))return!1;i=i.getDisguise();if(i?.owner&&!e.rules.detectDisguise&&!e.owner.sharedDetectDisguiseTrait?.has(t)&&(i.owner===e.owner||r.alliances.areAllied(e.owner,i.owner)))return!1}return!0}checkArmor(e,t,i){var r=e.ivanBomb||e.bombDisarm?1:e.verses.get(t);return void 0===r?(console.warn(`Unhandled ArmorType ${ri[t]} in warhead ${e.name}`),!1):!(100*r<=(i?1:0))}createAttackTask(e,t,i,r,s){return new co(e,e.createTarget(t,i),r,s)}[Ts.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 co?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===ii.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,r;!o&&a.guardMode&&e&&a.owner.isCombatant()&&(t=a.armedTrait?.computeGuardScanRange(e),i=a.guardArea?.tile,r=50);let s=!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===ii.Fly&&!a.guardMode||a.rules.movementZone!==ii.Fly&&e.isUnit()&&e.zone===dr.Air||(a.isInfantry()||a.isVehicle())&&!!a.disguiseTrait||!a.owner.isCombatant(),disallowTurning:o,leashTiles:r,passive:!0});o?this.opportunityFireTask=l:a.unitOrderTrait.addTask(l),s=!0,o||!a.guardMode||a.guardArea||(a.guardArea={tile:a.tile,onBridge:!!a.isUnit()&&a.onBridge})}}s||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),s=!0)),!s&&!o&&a.guardArea&&a.isUnit()&&a.moveTrait&&!a.moveTrait.isDisabled()&&a.guardArea.tile!==a.tile&&a.unitOrderTrait.addTasks(new Us(n,a.guardArea.tile,a.guardArea.onBridge),new _s(()=>{[Hs.Success,Hs.CloseEnough].includes(a.moveTrait.lastMoveResult)||a.resetGuardModeToIdle(),a.guardArea=void 0}))}}}[$a.onDamage](e,t,i,r){this.isDisabled()||!this.retaliateTarget&&!this.opportunityFireTask&&r&&r.obj&&r.weapon&&this.shouldRetaliate(e,t,i,r.obj,r.weapon.warhead)&&(this.retaliateTarget=r.obj)}[Cs.onBeforeTeleport](e,t,i,r){r||(this.attackState=no.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;if(e.isUnit()&&e.rules.opportunityFire){if(e.unitOrderTrait.hasTasks()&&e.unitOrderTrait.getTasks()[0].preventOpportunityFire)return!1}else if(e.unitOrderTrait.hasTasks())return!1;return!0}shouldRetaliate(e,t,i,r,s){return!(i<1||t.areFriendly(e,r)||!e.rules.canRetaliate||!e.primaryWeapon||s.rules.temporal||r.rules.missileSpawn||e.unitOrderTrait.hasTasks()||!t.isValidTarget(r)||(r.isInfantry()||r.isVehicle())&&r.disguiseTrait&&!e.rules.detectDisguise||e.mindControllerTrait?.isAtCapacity()||!this.selectWeaponVersus(e,r,t,!1)||(e.isBuilding()||r.isBuilding()?this.rangeHelper.tileDistance(e,r):this.rangeHelper.distance2(e,r)/gr.ISO_TILE_SIZE)>e.sight)}scanForTarget(e,t,i,r,s,a=!1){let n={},o=Number.NEGATIVE_INFINITY;var h=this.getAvailableWeapons(e,!0,!1),t=r??(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)&&(r?this.rangeHelper.isInRange(e,u,c.minRange,r,c.rules.cellRangefinding)&&(!s||this.rangeHelper.isInRange2(s,u,0,r)):this.rangeHelper.isInWeaponRange(e,u,c,i.rules))&&(a||this.losHelper.hasLineOfSight(e,u,c))&&(l=this.rangeHelper.distance3(e,u)/gr.ISO_TILE_SIZE,(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 r=e.getFoundation();const s=new oo.Vector2(e.tile.rx,e.tile.ry),a=new oo.Vector2(e.tile.rx+r.width-1,e.tile.ry+r.height-1);s.addScalar(-t),a.addScalar(t);t=new oo.Box2(s,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,r,s){let a=[e.primaryWeapon,e.secondaryWeapon].filter(ga).map(e=>e.warhead.rules.verses.get(t.rules.armor)??0).reduce((e,t)=>Math.max(e,t),0)*s.targetEffectivenessCoefficientDefault;return e.attackTrait?.currentTarget?.obj===t&&(a*=-1),a+=e.rules.specialThreatValue*s.targetSpecialThreatCoefficientDefault,a+=(i.warhead.rules.verses.get(e.rules.armor)??0)*s.myEffectivenessCoefficientDefault,a+=e.healthTrait.health/100*s.targetStrengthCoefficientDefault,a+=r*s.targetDistanceCoefficientDefault,t.rules.distributedFire&&(a-=1e6*(this.distributedFireHistory.get(e)??0)),t.rules.vhpScan===ni.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()}}var lo=__webpack_require__(949);class co extends Lr{constructor(e,t,i,r={}){super(),this.game=e,this.target=t,this.weapon=i,this.options=r,this.moveExecuted=!1,this.moveAttempts=0,this.rangeCheckCooldown=0,this.lastInRangeTargetPosition=new lo.Vector3,this.lastInRangeSelfPosition=new lo.Vector3,this.initialIndirectTarget=!1,this.forceDropTarget=!1,this.rangeHelper=new br(e.map.tileOccupation),this.losHelper=new to(e.map.tiles,e.map.tileOccupation),this.targetLinesConfig={pathNodes:[]},this.updateTargetLines(this.target,!0)}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,r;t.attackTrait.attackState=no.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:r}=this.findReachableMeleePosition(this.target.tile,!!this.target.getBridge(),{width:1,height:1},t),!i&&r&&(this.lastValidTargetPosition=r,this.updateTargetLines(this.game.createTarget(r.onBridge,r.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:r}=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,r&&(this.lastValidTargetPosition=r,this.updateTargetLines(this.game.createTarget(r.onBridge,r.tile),!1))))),this.rangeHelper.isInWeaponRange(t,this.target.obj??this.target.tile,this.weapon,this.game.rules)&&t.isUnit()&&t.rules.movementZone===ii.Fly&&t.zone!==dr.Air&&(t.rules.hoverAttack||t.isAircraft())&&this.children.push(new Us(this.game,t.tile,!1).setCancellable(!1))}else this.cancel()}findReachableMeleePosition(r,e,t,s){let i=this.game.map,a=i.tileOccupation,n=e?a.getBridgeOnTile(r):void 0,o=new Wr(i),h=s.rules.movementZone===ii.Fly,l=(e,t)=>h||0<i.terrain.getPassableSpeed(e,s.rules.speedType,!!t)&&o.isEligibleTile(e,t,n,r)&&!i.terrain.findObstacles({tile:e,onBridge:t},s).length,c,u=new Pr(i.tiles,i.mapBounds,r,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(s,r,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=no.Idle,e.attackTrait.currentTarget=void 0;var t=this.game.rules.general.prism.type;e.isBuilding()&&e.name===t&&this.weapon.type!==si.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!==ii.Fly)return!1;if(!this.cancellable||this.children.some(e=>!e.cancellable))return!1;if(this.status===Er.Running||this.status===Er.Cancelling){if(this.children.filter(e=>e instanceof Us).some(e=>!e.forceCancel(t)))return!1;this.onEnd(t),(t.isInfantry()||t.isVehicle())&&(t.isFiring=!1)}return this.status=Er.Cancelled,!0}onTick(t){let i=t.attackTrait;(t.isInfantry()||t.isVehicle())&&i.attackState!==no.Firing&&(t.isFiring=!1);let r=this.target.obj,s=this.children.find(e=>e instanceof ro);if(this.isCancelling()&&i.attackState!==no.FireUp)return!t.airSpawnTrait?.isLaunchingMissiles()&&(s?.cancel(),!0);let a=!1;if(i.attackState===no.FireUp){if(i.isDisabled())return!0;i.attackState=no.Firing,a=!0}if(i.attackState===no.Firing){if(this.initialIndirectTarget&&!this.game.map.getObjectsOnTile(this.target.tile).find(e=>e.isOverlay()&&!e.isBridgePlaceholder()||e.isTerrain()))return this.cancel(),this.onTick(t);if(a){var n=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(t,n,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(t,n,this.weapon))return i.attackState=no.CheckRange,this.onTick(t)}if(this.weapon.rules.limboLaunch){if((r?.isVehicle()||r?.isAircraft())&&r.parasiteableTrait?.isInfested())return!0;if(t.rules.movementZone!==ii.Fly&&r?.isUnit()&&r.zone===dr.Air)return!0}if(this.target.tile.onBridgeLandType&&t.tile.onBridgeLandType&&t.isUnit()&&(this.game.map.tileOccupation.getBridgeOnTile(this.target.tile)?.isHighBridge()||this.game.map.tileOccupation.getBridgeOnTile(t.tile)?.isHighBridge()))if((r?r.isUnit()&&(r.zone===dr.Air||r.onBridge):this.target.isBridge())!==(t.zone===dr.Air||t.onBridge)&&this.game.map.bridges.findHighBridgeBoundary(t.tile)?.tile===this.game.map.bridges.findHighBridgeBoundary(this.target.tile)?.tile)return!0;let e=1;n=this.game.rules.general.prism.type;if(t.isBuilding()&&t.name===n&&this.weapon.type!==si.Secondary&&(n=this.countSupportBeamsAndFireDownTowers(t,n),e=1+n*this.game.rules.general.prism.supportModifier),this.weapon.rules.spawner&&(t.isVehicle()||t.isAircraft())&&t.parasiteableTrait?.isParalyzed())return!0;if(0===t.ammo)return t.isAircraft()&&(t.rules.fighter||t.rules.spawned)&&s?.cancel(),!0;if(this.weapon.fire(this.target,this.game,e),this.weapon.rules.limboLaunch){if(s){if(!s.forceCancel(t))throw new Error("Force cancel was unsuccessful");t.moveTrait.lastTargetOffset=void 0,t.moveTrait.lastVelocity=void 0}return!0}return this.weapon.rules.fireOnce?!0:!(!this.options.passive||!t.rules.distributedFire)||(i.attackState=no.JustFired,!1)}if(i.attackState===no.JustFired)return i.attackState=no.PrepareToFire,this.onTick(t);this.needsTargetUpdate&&(this.target=this.needsTargetUpdate,r=this.target.obj,this.needsTargetUpdate=void 0,this.onTargetChange(t),r||s?.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(t));let o=this.game.isValidTarget(r)&&!this.shouldDropTarget(r);if(o){let e=this.weapon.targeting.canTarget(r,this.target.tile,this.game,!!this.options.force,!!this.options.passive);if(!e||!t.armedTrait.isEquippedWithWeapon(this.weapon)){var h=i.selectWeaponVersus(t,this.target,this.game,this.options.force,this.options.passive);if(h){if(this.setWeapon(h),i.attackState!==no.CheckRange)return i.attackState=no.CheckRange,this.onTick(t);e=!0}else e=!1}o=e}if(o&&(l=this.lastTargetTpCheck,r?.isUnit()&&l&&r.moveTrait.lastTeleportTick>=l?(o=!1,this.rangeCheckCooldown=0):this.lastTargetTpCheck=this.game.currentTick),o&&r&&(this.lastValidTargetPosition={tile:r.tile,onBridge:this.target.getBridge()}),o||(this.targetLinesConfig.isAttack=!1),i.attackState===no.CheckRange){if(0<this.rangeCheckCooldown)return this.rangeCheckCooldown--,!1;let e=this.target.obj?o?this.target.obj:this.lastValidTargetPosition.tile:this.target.tile;var l=this.target.obj?o?this.target.obj.isBuilding()?this.target.obj.centerTile:this.target.obj.tile:this.lastValidTargetPosition.tile:this.target.tile;if(!this.rangeHelper.isInWeaponRange(t,e,this.weapon,this.game.rules)||!this.losHelper.hasLineOfSight(t,e,this.weapon)||t.isUnit()&&t.rules.balloonHover&&!t.rules.hoverAttack&&!s&&t.tile!==l||t.isAircraft()&&this.weapon.projectileRules.iniRot<=1&&!s){if(t.isUnit()&&!this.options.holdGround&&this.game.map.isWithinBounds(l)){if(s){if(s.target!==this.target.obj||o)if(o&&this.target.obj&&this.rangeHelper.tileDistance(this.target.obj,this.lastSelfMoveTargetTile)>this.weapon.range)s.retarget(this.target.obj,!!this.target.getBridge()),this.lastSelfTileBeforeMove=t.tile,this.lastSelfMoveTargetTile=this.target.obj?.tile??this.target.tile;else{if(void 0!==this.options.leashTiles&&this.rangeHelper.tileDistance(this.initialSelfPosition.tile,t.tile)>this.options.leashTiles)return s.cancel(),!0;var c=e instanceof ra&&e.isUnit()?e.moveTrait.baseSpeed:0,u=Math.ceil((this.rangeHelper.tileDistance(t,e)-(this.weapon.range+1))/((t.moveTrait.baseSpeed+c)/gr.LEPTONS_PER_TILE));0<u&&(this.rangeCheckCooldown=Math.min(xr.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),i.currentTarget=e,s.retarget(e.tile,e.isBridge()),this.updateTargetLines(e,!1)}return!1}if(!t.moveTrait||t.moveTrait.isDisabled())return!0;if(this.isCancelling())return!0;if(t.tile===this.lastSelfTileBeforeMove||this.moveExecuted&&t.moveTrait.lastMoveResult===Hs.Fail?this.moveAttempts++:this.moveAttempts=0,this.weapon.rules.limboLaunch&&t.defaultToGuardArea&&r&&this.moveExecuted&&t.moveTrait.lastMoveResult===Hs.Fail&&this.rangeHelper.isInRange(t,r,0,t.armedTrait.computeGuardScanRange(this.weapon),!0))return!0;if(3<this.moveAttempts)return!0;0<this.moveAttempts&&this.children.push(new Ss(1/60));c=e,u=r&&!o?this.lastValidTargetPosition.onBridge:this.target.getBridge();return s=new ro(this.game,c,!!u,this.weapon),s.blocking=!1,this.children.push(s),this.moveExecuted=!0,this.lastSelfTileBeforeMove=t.tile,this.lastSelfMoveTargetTile=c instanceof ra?c.tile:c,this.onTick(t)}return!0}if(this.moveExecuted=!1,this.moveAttempts=0,s&&(t.rules.balloonHover&&!t.rules.hoverAttack||t.rules.fighter||t.rules.spawned||t.rules.movementZone===ii.Fly&&!this.rangeHelper.isInRange2(t,this.target.obj??this.target.tile,this.weapon.minRange,this.weapon.range-1)||s.cancel()),s&&(t.isInfantry()&&!t.rules.balloonHover||this.weapon.rules.spawner))return!1;if(s?.children.some(e=>!e.cancellable)&&this.weapon.rules.limboLaunch)return!1;if(s&&s.shouldAirStrafe(t)&&this.target.obj?.isUnit()&&this.target.obj.moveTrait.isMoving()&&1<this.weapon.range&&!this.rangeHelper.isInRange2(t,this.target.obj,this.weapon.minRange,this.weapon.range-1))return!1;i.attackState=no.PrepareToFire}if(i.attackState!==no.PrepareToFire)return!1;if(!o||i.isDisabled())return s?.cancel(),!0;u=this.target.getWorldCoords(),c=t.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),i.attackState=no.CheckRange,this.onTick(t);if(!(this.weapon.rules.omniFire||t.rules.omniFire&&t.rules.fighter)){var c=(new lo.Vector3).copy(u).sub(c),e=is.fromMapCoords(new lo.Vector2(c.x,c.z)),c=this.weapon.projectileRules.rot?45:11.25;if((t.isVehicle()||t.isBuilding())&&t.turretTrait){if(t.turretTrait.desiredFacing=e,Math.abs(e-t.turretTrait.facing)>=c)return!1}else if(Math.abs(e-t.direction)>=c){if(t.isAircraft())return t.direction=is.tick(t.direction,e,t.rules.rot).facing,!1;if(s)return!1;if(t.isVehicle())return!!this.options.disallowTurning||(this.children.push(new rs(e)),!1);t.direction=e}}if(!this.losHelper.hasLineOfSight(t,this.target.obj||this.target.tile,this.weapon))return i.attackState=no.CheckRange,this.onTick(t);if(i.isOnCooldown(t))return!1;if(this.weapon.warhead.rules.temporal&&t.temporalTrait.getTarget()===this.target.obj)return!1;if(this.weapon.rules.suicide&&this.weapon.type!==si.DeathWeapon)return this.game.destroyObject(t,{player:t.owner,obj:t,weapon:this.weapon}),!0;e=this.game.rules.general.prism.type;return t.isBuilding()&&t.name===e&&this.weapon.type!==si.Secondary&&this.fireUpPrismSupportTowers(t,e),(t.isInfantry()||t.isVehicle())&&(t.isFiring=!0),t.art.fireUp?(this.children.push(new jr(t.art.fireUp).setCancellable(!1)),i.attackState=no.FireUp,!1):(i.attackState=no.Firing,this.onTick(t))}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(Ct.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,r=t.owner.getOwnedObjectsByType(Ct.Building).filter(e=>e.name===i&&e.attackTrait?.currentTarget?.obj===t);for(e of r)e.unitOrderTrait.getCurrentTask()?.cancel();return Math.min(this.game.rules.general.prism.supportMax,r.length)}getTargetLinesConfig(){return this.targetLinesConfig}}class uo{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()}[Ts.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 co&&((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 po{constructor(e,t){this.target=e,this.from=t,this.type=Xi.UnitRepairFinish}}class go{constructor(e){this.target=e,this.type=Xi.UnitRepairStart}}var mo,fo,yo,wo=__webpack_require__(949);(s=mo=mo||{})[s.Idle=0]="Idle",s[s.Repairing=1]="Repairing";class To{constructor(){this.status=mo.Idle,this.cooldownTicks=0,this.lastRepairTickSuccessful=!1}[qs.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))}[Ts.onTick](t,i){if(t.dockTrait&&(!t.rules.needsEngineer||!t.owner.isNeutral))if(!t.dockTrait.hasDockedUnits()||t.dockTrait.getDockedUnits().some(e=>e.zone===dr.Air)||t.poweredTrait&&!t.poweredTrait.isPoweredOn())this.status=mo.Idle;else if(this.cooldownTicks<=0){var r,s,a=i.rules.general.repair,a=t.rules.unitReload?a.reloadRate:a.uRepairRate;this.cooldownTicks+=xr.BASE_TICKS_PER_SECOND*a*60;let e=!1;for(r of t.dockTrait.getDockedUnits())r.zone!==dr.Air&&(r.healthTrait.health<100&&i.areFriendly(r,t)?(this.tickRepair(r,i,t)&&(e=!0),!e||this.status!==mo.Idle&&this.lastRepairTickSuccessful||t.helipadTrait||i.events.dispatch(new go(r))):((s=t.rallyTrait.findRallyNodeForUnit(r,i.map))&&(t.dockTrait.undockUnit(r),r.unitOrderTrait.addTask(new Us(i,s.tile,!!s.onBridge,{closeEnoughTiles:i.rules.general.closeEnough}))),t.helipadTrait||i.events.dispatch(new po(r,t))));this.lastRepairTickSuccessful=e,this.status=e?mo.Repairing:mo.Idle}else this.cooldownTicks--}tickRepair(e,t,i){var r=t.rules.general.repair,s=Math.floor(r.repairStep),a=r.repairPercent;let n;if(a){r=a*e.purchaseValue/e.healthTrait.maxHitPoints,a=Math.min(i.owner.credits,Math.max(1,Math.floor(r*s)));if(n=r&&a?Math.floor(a/r):s,!a)return!1;i.owner.credits-=a}else n=s;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 wo.Vector2(e.tile.rx,e.tile.ry+i.height);return t.tiles.getByMapCoords(i.x,i.y)??e.tile}}class bo{getRallyPoint(){return this.rallyPoint}changeRallyPoint(e,t,i){i=this.findValidRallyPoint(t,e,i.map);i&&(this.rallyPoint=i)}findValidRallyPoint(i,e,r){let t=new Pr(r.tiles,r.mapBounds,e,{width:1,height:1},0,20,e=>i.rules.naval===(e.terrainType===Xt.Water)&&!r.tileOccupation.isTileOccupiedBy(e,i)),s=t.getNextTile();if(!s&&i.factoryTrait?.type===qi.NavalUnitType){var{width:a,height:n}=i.getFoundation();for(let t=0;t<a;t++)for(let e=0;e<n;e++){var o=r.tiles.getByMapCoords(i.tile.rx+t,i.tile.ry+e);if(0<r.terrain.getPassableSpeed(o,Kt.Float,!1)){s=o;break}}}return s}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,r,s){let a=i.rules.naval?void 0:r.tileOccupation.getBridgeOnTile(e),n=i.rules.movementZone===ii.Fly,t=new Pr(r.tiles,r.mapBounds,e,{width:1,height:1},0,5,e=>{var t=!a||a.isHighBridge()?r.tileOccupation.getBridgeOnTile(e):void 0;return!((n?[]:r.terrain.findObstacles({tile:e,onBridge:t},i)).length||s&&r.getObjectsOnTile(e).find(e=>e.isBuilding()&&!e.isDestroyed)||!(n||0<r.terrain.getPassableSpeed(e,i.rules.speedType,!!t)))});return t.getNextTile()??e}}class vo{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 So{constructor(){this.timer=new vo}hasCharge(){return this.timer.isActive()}setCharge(e,t){this.hasCharge()||(this.timer.setActiveFor(e),this.attackerInfo=t)}[Ts.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=Ls.Demolish,t.destroyObject(e,this.attackerInfo,!0))))}}class _o{[$s.onChange](e,t,i){this.checkAircraftsForPlayer(t,i)}[Zs.onUnspawn](e,t){this.checkAircraftsForPlayer(e.owner,t)}checkAircraftsForPlayer(e,t){let i=t.rules.general.padAircraft;var r;for(r of e.getOwnedObjectsByType(Ct.Aircraft).filter(e=>i.includes(e.name)))r.airportBoundTrait&&(r.airportBoundTrait.preferredAirport=void 0)}}class ko{[Ts.onTick](t,i){if(t.dockTrait&&t.dockTrait.hasDockedUnits()&&!t.dockTrait.getDockedUnits().every(e=>!this.canReloadUnit(e)))if(void 0===this.cooldownTicks&&(this.cooldownTicks=xr.BASE_TICKS_PER_SECOND*i.rules.general.repair.reloadRate*60),this.cooldownTicks<=0){this.cooldownTicks=xr.BASE_TICKS_PER_SECOND*i.rules.general.repair.reloadRate*60;let e=t.dockTrait.getDockedUnits();var r;for(r of 0===e[0].ammo?e.slice(0,1):e)this.canReloadUnit(r)&&r.ammoTrait.ammo++}else this.cooldownTicks--}canReloadUnit(e){return!(!e.ammoTrait||!e.rules.manualReload||e.ammoTrait.isFull()||e.zone===dr.Air)}}class Oo extends ma{constructor(e){super(new Ss(e),new _s(e=>e.buildStatus=No.Ready)),this.cancellable=!1}}class Io{constructor(e){this.name=e}getSuperWeapon(e){return e.owner.superWeaponsTrait?.get(this.name)}[qs.onSpawn](e,t){this.addSuperWeaponToPlayerIfNeeded(e.owner,t)}[Zs.onUnspawn](e,t){this.removeSuperWeaponFromPlayerIfNeeded(e.owner)}[$s.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(Ct.Building).some(e=>e.superWeaponTrait?.name===this.name)||(e=t.get(this.name))&&!e.isGift&&t.remove(this.name))}}(s=fo=fo||{})[s.Unexplored=0]="Unexplored",s[s.TemporaryReveal=1]="TemporaryReveal",s[s.Explored=2]="Explored",yo=yo||{},yo[yo.Darken=8]="Darken";class Ao{constructor(){this.invalidations=new Map,this.temporaryReveals=new Map,this.fullInvalidation=!1,this._onChange=new Pn}get onChange(){return this._onChange.asEvent()}fromTiles(e){var t,i=this.size=e.getMapSize();this.tiles=new Uint8Array(i.width*i.height),this.tiles.fill(fo.Unexplored),this.tileElevation=new Uint8Array(i.width*i.height);for(t of e.getAll())this.tileElevation[t.rx+t.ry*i.width]=t.terrainType===Xt.Cliff&&0<t.z?t.z-1:t.z;return this}clone(){let e=new Ao;return e.tiles=this.tiles.slice(),e.size=this.size,e.tileElevation=this.tileElevation,e}copy(e){this.tiles=e.tiles.slice(),this.size=e.size,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){return this.getShroudType(e)===fo.Unexplored}getShroudType(e){return 7&this.tiles[e.rx+e.ry*this.size.width]}isFlagged(e,t){return 0!=(this.tiles[e.rx+e.ry*this.size.width]&t)}getShroudTypeByCoords(e,t){return 7&this.tiles[e+t*this.size.width]}invalidateFull(){this.fullInvalidation=!0}invalidate(e,t,i){let r=this.invalidations.get(e);r||(r={centerTile:e,elevation:0,radius:0},this.invalidations.set(e,r)),r.elevation=Math.max(r.elevation,t),r.radius=Math.max(r.radius,i)}revealFrom(e){var t=e.sight;t&&this.invalidate(e.tile,e.tileElevation+e.tile.z,t)}revealAround(e,t){this.invalidate(e,Number.POSITIVE_INFINITY,t)}unrevealAround(e,t){var i=[];this.setValueAround(e,t,Number.POSITIVE_INFINITY,i,fo.Unexplored,fo.Explored),this._onChange.dispatch(this,{type:"incremental",tiles:i})}revealTemporarily(e){this.temporaryReveals.set(e.tile,5*xr.BASE_TICKS_PER_SECOND)}revealObject(e){this.invalidate(e.tile,Number.POSITIVE_INFINITY,4.25)}toggleFlagsAround(e,t,i,r){var s=[];this.setValueAround(e,t,Number.POSITIVE_INFINITY,s,void 0,void 0,r?{setFlags:i}:{clearFlags:i}),this._onChange.dispatch(this,{type:"incremental",tiles:s})}update(){let i=[];if(this.invalidations.size){for(var e of this.invalidations.values())this.setValueAround(e.centerTile,e.radius,e.elevation,i,fo.Explored,[fo.Unexplored,fo.TemporaryReveal]);this.invalidations.clear()}this.temporaryReveals.size&&this.temporaryReveals.forEach((e,t)=>{e<=0?(this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,fo.Unexplored,fo.TemporaryReveal),this.temporaryReveals.delete(t)):(e===5*xr.BASE_TICKS_PER_SECOND&&this.setValueAround(t,3,Number.POSITIVE_INFINITY,i,fo.TemporaryReveal,fo.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",tiles:i})}setValueAround(r,s,a,n,o,h=void 0,{setFlags:l,clearFlags:c}={}){var e=Math.ceil(s),t=r.rx-e,u=r.rx+e,d=r.ry-e,p=r.ry+e,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-r.rx)*(i-r.rx)+(t-r.ry)*(t-r.ry)>s*s+1||this.tileElevation[m]>=a+4||(this.tiles[m]=(o??f)|e,f===o&&y===e||n.push({x:i,y:t})))}}revealAll(){this.tiles.fill(fo.Explored),this._onChange.dispatch(this,{type:"clear"})}reset(){this.tiles.fill(fo.Unexplored),this._onChange.dispatch(this,{type:"cover"})}}var Co=__webpack_require__(949);class Bo{constructor(e){this.radiusTiles=e,this.refreshTicks=0}[Ts.onTick](e,t){0<this.refreshTicks&&this.refreshTicks--,this.refreshTicks<=0&&this.update(e,t)}[qs.onSpawn](e,t){this.markGapTilesForFriendlies(e,e.owner,t,!0)}[Zs.onUnspawn](e,t){this.markGapTilesForFriendlies(e,e.owner,t,!1),this.update(e,t)}[$s.onChange](e,t,i){this.markGapTilesForFriendlies(e,t,i,!1),this.markGapTilesForFriendlies(e,e.owner,i,!0),this.update(e,i)}[Ln.onChange](e,t,i){this.markGapTilesForFriendlies(e,e.owner,t,!i),i&&this.update(e,t)}markGapTilesForFriendlies(i,e,r,t){let s=[e,...r.alliances.getAllies(e)],a;for(var n of s){let e=r.mapShroudTrait.getPlayerShroud(n);if(e&&(e.toggleFlagsAround(i.tile,this.radiusTiles,yo.Darken,t),!t)){if(!a){let t=new br(r.map.tileOccupation);a=s.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,yo.Darken,!0)}}}update(t,i){this.refreshTicks=5*xr.BASE_TICKS_PER_SECOND;let r;var s,a,n,o,h=t.owner.buildings.has(t)&&t.poweredTrait?.isPoweredOn();for(s of i.getCombatants())if(s!==t.owner&&!i.alliances.areAllied(t.owner,s)){let e=i.mapShroudTrait.getPlayerShroud(s);if(e)if(h){e.unrevealAround(t.tile,this.radiusTiles),r||(n=this.radiusTiles+Ki.MAX_SIGHT,a=new Co.Vector2(t.tile.rx,t.tile.ry).addScalar(-n),n=new Co.Vector2(t.tile.rx,t.tile.ry).addScalar(n),r=i.map.technosByTile.queryRange(new Co.Box2(a,n)));for(o of r)o.owner===s||i.alliances.areAllied(o.owner,s)?e.revealFrom(o):o.rules.revealToAll&&e.revealObject(o)}else[...s.buildings].some(e=>e.rules.spySat)&&e.revealAround(t.tile,this.radiusTiles)}}}const Eo=xr.BASE_TICKS_PER_SECOND;class xo{constructor(e){this.radiusTiles=e,this.detectionLines=[],this.nextScan=Eo}[Ts.onTick](e,t){e.owner.powerTrait?.isLowPower()?this.disable():(0<this.nextScan&&this.nextScan--,this.nextScan<=0&&(this.nextScan=Eo,this.detectionLines=this.scan(e,t)))}[Ln.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 r=[],s=new br(i.map.tileOccupation);var a,n,o,h=e=>s.distance2(e,t)/gr.ISO_TILE_SIZE<=this.radiusTiles;for(a of e)for(var l of a.getOwnedObjects())l.attackTrait?.currentTarget?h((n=l.attackTrait.currentTarget).obj??n.tile)&&r.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),r.push({source:l,target:n})):(o=o.pathNodes[0])&&h(o.tile)&&(o=i.createTarget(o.onBridge,o.tile),r.push({source:l,target:o})));return r}}class Po{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 ${Ct[this.unit.type]}#${this.unit.id}}`);this.unit=e,this.healTicks=5*xr.BASE_TICKS_PER_SECOND}[Ts.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 po(i,e))))}[Ms.onDestroy](e,t,i){this.unit&&(t.destroyObject(this.unit,i,!0),this.unit=void 0)}evacuate(t,i,r){let e;var s={x:i.tile.rx,y:i.tile.ry+i.art.foundation.height},s=r.map.tiles.getByMapCoords(s.x,s.y);s&&r.map.isWithinBounds(s)&&this.canEvacuateTo(s,t,i,r)&&(e=s),e=e||new Pr(r.map.tiles,r.map.mapBounds,i.tile,i.art.foundation,1,1,e=>this.canEvacuateTo(e,t,i,r)).getNextTile(),e?(r.unlimboObject(t,e),t.unitOrderTrait.addTask(new Ds(r))):r.destroyObject(t,{player:t.owner})}canEvacuateTo(e,t,i,r){return 0<r.map.terrain.getPassableSpeed(e,t.rules.speedType,!1)&&Math.abs(e.z-i.tile.z)<2&&!r.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length}}var No,Ro=__webpack_require__(949);(s=No=No||{})[s.BuildUp=0]="BuildUp",s[s.Ready=1]="Ready",s[s.BuildDown=2]="BuildDown";class Do extends sa{constructor(e,t,i){super(Ct.Building,e,t,i),this.showWeaponRange=!1,this.wallType=[0,0,0,0],this.direction=0,this.buildStatus=No.BuildUp,this.lastBuildStatus=this.buildStatus}static factory(e,t,i,r,s,a){let n=new this(e,t,r);return t.canBeOccupied&&(n.garrisonTrait=new kn(n,i.audioVisual.conditionRed,t.maxNumberOccupants),n.traits.add(n.garrisonTrait)),t.canC4&&!t.wall&&(n.c4ChargeTrait=new So,n.traits.add(n.c4ChargeTrait)),t.bridgeRepairHut&&(n.cabHutTrait=new Yn(n,a),n.traits.add(n.cabHutTrait)),t.crewed&&(n.crewedTrait=new Xn,n.traits.add(n.crewedTrait)),t.turret&&(n.turretTrait=new On,n.traits.add(n.turretTrait)),t.overpowerable&&(n.overpoweredTrait=new uo(n),n.traits.add(n.overpoweredTrait)),(t.powered&&0!==t.power||t.needsEngineer)&&(n.poweredTrait=new xn(n),n.traits.add(n.poweredTrait)),(t.factory||t.cloning)&&(n.factoryTrait=new qn(t.cloning?qi.InfantryType:t.factory,t.cloning),n.traits.add(n.factoryTrait)),t.superWeapon&&(n.superWeaponTrait=new Io(t.superWeapon),n.traits.add(n.superWeaponTrait)),t.numberOfDocks&&(n.dockTrait=new Vn(n,s,t.numberOfDocks,r.dockingOffsets),n.traits.add(n.dockTrait),t.helipad&&(n.helipadTrait=new _o,n.traits.add(n.helipadTrait)),(t.unitRepair||t.unitReload)&&(n.unitRepairTrait=new To,n.traits.add(n.unitRepairTrait)),t.unitReload&&(n.unitReloadTrait=new ko,n.traits.add(n.unitReloadTrait))),t.hospital&&(n.hospitalTrait=new Po,n.traits.add(n.hospitalTrait)),(t.factory||t.cloning||t.numberOfDocks)&&(n.rallyTrait=new bo,n.traits.add(n.rallyTrait)),t.freeUnit&&n.traits.add(new Qn),t.produceCashStartup&&n.traits.add(new Kn),t.wall&&(n.wallTrait=new Jn,n.traits.add(n.wallTrait)),t.gapGenerator&&(n.gapGeneratorTrait=new Bo(t.gapRadiusInCells),n.traits.add(n.gapGeneratorTrait)),t.psychicDetectionRadius&&(n.psychicDetectorTrait=new xo(t.psychicDetectionRadius),n.traits.add(n.psychicDetectorTrait)),n}isBuilding(){return!0}getFoundation(){return this.art.foundation}getFoundationCenterOffset(){var e=this.getFoundation();return new Ro.Vector2(e.width/2*gr.LEPTONS_PER_TILE,e.height/2*gr.LEPTONS_PER_TILE)}update(e){this.buildStatus!==No.BuildUp||this.unitOrderTrait.hasTasks()||this.unitOrderTrait.addTask(new Oo(e.rules.general.buildupTime)),this.buildStatus!==this.lastBuildStatus&&(this.lastBuildStatus=this.buildStatus,e.events.dispatch(new In(this,this.buildStatus))),this.attackTrait?.setDisabled(this.buildStatus!==No.Ready||!!this.poweredTrait&&!this.poweredTrait.isPoweredOn()),super.update(e)}}class Mo extends ra{constructor(e,t,i){super(Ct.Terrain,e,t,i),this.radarInvisible=this.rules.radarInvisible}static factory(e,t,i){return new this(e,t,i)}}class Lo extends ra{constructor(e,t,i){super(Ct.Overlay,e,t,i),this.radarInvisible=this.rules.radarInvisible}static factory(e,t,i){let r=new this(e,t,i);return t.wall&&(r.wallTrait=new Jn,r.traits.add(r.wallTrait)),r}isTiberium(){return xa.getOverlayTibType(this.overlayId)!==_a.NotSpecial}isBridge(){return Ca.isBridge(this.overlayId)}isXBridge(){return Ca.isXBridge(this.overlayId)}isHighBridge(){return Ca.isHighBridge(this.overlayId)}isLowBridge(){return Ca.isLowBridge(this.overlayId)}isBridgePlaceholder(){return Ca.isBridgePlaceholder(this.overlayId)}getFoundation(){let e={width:1,height:1};return this.isBridge()&&(this.isXBridge()?e.height+=2:e.width+=2),e}}class Fo extends ra{constructor(e,t,i){super(Ct.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 jo extends Us{constructor(e,t,i,r){super(e,i??t,!1,{closeEnoughTiles:i?void 0:0,strictCloseEnough:!i}),this.teleportTile=t,this.teleportCondition=r}onStart(e){if(super.onStart(e),!e.harvesterTrait||e.rules.locomotor!==ti.Chrono)throw new Error(`Vehicle ${e.name} is not a chrono miner`)}onTick(e){return!e.moveTrait.isDisabled()&&(!(this.isCancelling()||e.moveTrait.moveState!==zs.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===dr.Air&&(e.zone=dr.Ground,e.position.tileElevation=0),!0))}}class Wo extends Lr{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 br(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=zo.MovingToOreSite,e.harvesterTrait.lastGatherExplicit=this.explicitOrder}onEnd(e){e.harvesterTrait.status!==zo.LookingForOreSite&&(e.harvesterTrait.status=zo.Idle)}onTick(i){if(this.isCancelling())return!0;let r=i.harvesterTrait;if(r.status===zo.MovingToOreSite){if(this.target=this.initialTarget?.landType===Yt.Tiberium?this.initialTarget:this.findClosestReachableOreSite(i,r.lastOreSite??i.tile,!0),r.lastOreSite=this.target,!this.target){r.status=zo.LookingForOreSite;let e=this.getRefineryOnTile(i.tile);if(e&&1===i.unitOrderTrait.getTasks().length){let t=i.rules.movementZone===ii.Fly;var s=new Pr(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();s&&i.unitOrderTrait.addTasks(new Us(this.game,s,!1),new _s(()=>{[Hs.Success,Hs.CloseEnough,Hs.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new Ss(1/60))}))}return!0}var a=this.game.rules.general.closeEnough,s=this.rangeHelper.tileDistance(i.tile,this.target)<=a;if(i.tile!==this.target&&(i.tile.landType!==Yt.Tiberium||!s||this.strictTarget)){if(i.tile!==this.target&&s&&i.tile.landType!==Yt.Tiberium){s=this.findClosestReachableOreSite(i,i.tile,!1,!0);if(s)this.target=s,r.lastOreSite=this.target;else{if(!this.forceMoveTried)return this.forceMoveTried=!0,this.children.push(new Us(this.game,this.target,!1,{closeEnoughTiles:0,strictCloseEnough:!0})),!1;if(this.forceMoveTried=!1,!r.isEmpty())return this.returnOreIfPossible(i),!0;s=this.findClosestReachableOreSite(i,i.tile,!0,!0);if(!s)return r.status=zo.LookingForOreSite,!0;this.target=s,r.lastOreSite=this.target}}return this.children.push(new Us(this.game,this.target,!1,{closeEnoughTiles:a}),new _s(()=>{[Hs.Success,Hs.CloseEnough,Hs.Cancel].includes(i.moveTrait.lastMoveResult)||this.children.push(new Ss(5/60))})),!1}this.target=i.tile,r.lastOreSite=this.target,r.status=zo.Harvesting,this.forceMoveTried=!1,this.strictTarget=!1}if(r.status!==zo.Harvesting)return!1;{if(r.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,r.lastOreSite??i.tile,!1)||r.isEmpty()?(r.status=zo.MovingToOreSite,this.onTick(i)):(this.returnOreIfPossible(i),!0);let t=e.traits.get(Pa);a=t.collectBail();if(t.getBailCount()||this.game.unspawnObject(e),a===ka.Ore)r.ore++;else{if(a!==ka.Gems)throw new Error(`Unsupported tiberium type ${a}`);r.gems++}return[...i.owner.buildings].some(e=>e.rules.refinery)||this.explicitOrder?(this.children.push(new Ss(1/60)),!1):!0}}findClosestReachableOreSite(t,i,e,r=!1){let s=t.rules.movementZone===ii.Fly;var a=e=>e.landType===Yt.Tiberium&&(!r||(s||!this.game.map.terrain.findObstacles({tile:e,onBridge:void 0},t).length));if(a(i))return i;let n=1;if(!e){let e=new Ps(this.game.map.tiles,this.game.map.mapBounds,i,1,this.game,a,!1);var o=e.getNextTile();if(o)return o;n=2}e=e?this.scanFarRadius:this.scanNearRadius;let h=new Pr(this.game.map.tiles,this.game.map.mapBounds,i,{width:1,height:1},n,e,a);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 $o(this.game))}getTargetLinesConfig(e){return{pathNodes:this.initialTarget?[{tile:this.initialTarget,onBridge:void 0}]:[]}}}var Uo,Vo,zo,Ho,Go=__webpack_require__(949);class $o extends Lr{constructor(e,t,i=!1,r=!1){super(),this.game=e,this.forceTarget=t,this.resetLastOreSite=i,this.explicitOrder=r,this.useChildTargetLines=!0,this.preventOpportunityFire=!1,this.rangeHelper=new br(e.map.tileOccupation)}onStart(e){if(!e.isVehicle()||!e.harvesterTrait)throw new Error(`Unit ${e.name} is not a harvester.`);e.harvesterTrait.status=zo.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!==zo.LookingForRefinery&&(e.harvesterTrait.status=zo.Idle)}onTick(r){if(this.isCancelling())return!0;let s=r.harvesterTrait;if(s.status===zo.LookingForRefinery)return!0;if(s.status===zo.MovingToRefinery){if(!this.target||!this.isValidTargetRefinery(this.target,r)||r.tile!==this.findRefineryDockingTile(this.target)){var a=this.forceTarget??this.findClosestReachableRefinery(r);if(!a)return s.status=zo.LookingForRefinery,!0;this.target&&this.target!==a&&this.target.dockTrait.hasReservedDockForUnit(r)&&this.target.dockTrait.unreserveDockForUnit(r),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(r)));let i=this.findRefineryDockingTile(this.target);var n=this.rangeHelper.tileDistance(r,i);if(void 0===e||t||n>this.game.rules.general.harvesterTooFarDistance&&!this.explicitOrder){var o=this.findReachableQueueingTile(r);return o?(r.tile!==o&&this.children.push(r.rules.teleporter?new jo(this.game,i,o,()=>this.chronoMinerCanTeleport(r,i,this.target)):new Us(this.game,o,!1),new _s(()=>{r.moveTrait.lastMoveResult===Hs.Fail?s.status=zo.LookingForRefinery:r.moveTrait.lastMoveResult===Hs.CloseEnough&&this.children.push(new Ss(5/60))})),!1):!0}if(this.target.dockTrait.hasReservedDockForUnit(r)||this.target.dockTrait.reserveDockAt(r,e),void 0===this.reservedDockNumber&&(this.reservedDockNumber=this.target.dockTrait.getReservedDockForUnit(r)),r.tile!==i)return this.children.push(r.rules.teleporter?new jo(this.game,i,void 0,()=>this.chronoMinerCanTeleport(r,i,this.target)):new Us(this.game,i,!1,{closeEnoughTiles:0,strictCloseEnough:!0}),new _s(()=>{r.moveTrait.lastMoveResult===Hs.Fail&&(s.status=zo.LookingForRefinery)})),!1;s.status=zo.Docking}if(!this.isValidTargetRefinery(this.target,r))return s.status=zo.MovingToRefinery,this.forceTarget=void 0,this.onTick(r);if(s.status===zo.Docking){if(270!==r.direction)return this.children.push(new rs(270)),!1;this.target.dockTrait.dockUnitAt(r,this.reservedDockNumber),this.reservedDockNumber=void 0,s.status=zo.PreparingToUnload}if(s.status===zo.PreparingToUnload)return this.preventOpportunityFire=!0,this.children.push(new Ss(2/60)),s.status=zo.Unloading,!1;if(s.status!==zo.Unloading)return!1;a=s.ore*this.game.rules.getTiberium(ka.Ore).value+s.gems*this.game.rules.getTiberium(ka.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),s.ore=0,s.gems=0,1===r.unitOrderTrait.getTasks().length&&r.unitOrderTrait.addTask(new Wo(this.game)),!0}isValidTargetRefinery(e,t){return e.isSpawned&&this.game.areFriendly(e,t)&&!e.warpedOutTrait.isActive()}findClosestReachableRefinery(i){let r=this.rangeHelper,e=[...i.owner.buildings].filter(e=>e.rules.refinery&&e.dockTrait&&!e.warpedOutTrait.isActive()).sort((e,t)=>r.distance2(i,e)-r.distance2(i,t));var t=e[0],s=e.find(e=>0<e.dockTrait.getAvailableDockCount());return!s||t&&r.tileDistance(i,s.centerTile)-r.tileDistance(i,t.centerTile)>this.game.rules.general.harvesterTooFarDistance?t:s}findReachableQueueingTile(t){if(this.target.art.queueingCell){var e=new Go.Vector2(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 Pr(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===dr.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 r=this.rangeHelper;t=r.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))))}}(Uo=Uo||{}).onPush=Symbol(),(s=Vo=Vo||{})[s.Move=0]="Move",s[s.ForceMove=1]="ForceMove",s[s.Attack=2]="Attack",s[s.ForceAttack=3]="ForceAttack",s[s.AttackMove=4]="AttackMove",s[s.Guard=5]="Guard",s[s.GuardArea=6]="GuardArea",s[s.Capture=7]="Capture",s[s.Occupy=8]="Occupy",s[s.Deploy=9]="Deploy",s[s.DeploySelected=10]="DeploySelected",s[s.Stop=11]="Stop",s[s.Cheer=12]="Cheer",s[s.Dock=13]="Dock",s[s.Gather=14]="Gather",s[s.Repair=15]="Repair",s[s.Scatter=16]="Scatter",s[s.EnterTransport=17]="EnterTransport",s[s.PlaceBomb=18]="PlaceBomb",(s=zo=zo||{})[s.Idle=0]="Idle",s[s.LookingForOreSite=1]="LookingForOreSite",s[s.MovingToOreSite=2]="MovingToOreSite",s[s.Harvesting=3]="Harvesting",s[s.LookingForRefinery=4]="LookingForRefinery",s[s.MovingToRefinery=5]="MovingToRefinery",s[s.Docking=6]="Docking",s[s.PreparingToUnload=7]="PreparingToUnload",s[s.Unloading=8]="Unloading";class qo{constructor(e){this.storage=e,this.ore=0,this.gems=0,this.status=zo.Idle,this.lastGatherExplicit=!1,this.autoGatherOnNextIdle=!1,this.ticksSinceLastRefineryCheck=0,this.ticksSinceLastOreCheck=0}[qs.onSpawn](e,t){e.owner.isCombatant()&&t.afterTick(()=>{e.unitOrderTrait.addTask(new Wo(t))})}[$s.onChange](e,t,i){!t.isCombatant()&&e.owner.isCombatant()&&i.afterTick(()=>{e.unitOrderTrait.addTask(new Wo(i))})}[Ts.onTick](e,t){this.status===zo.LookingForRefinery?this.ticksSinceLastRefineryCheck++>5*xr.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastRefineryCheck=0,e.unitOrderTrait.hasTasks()?this.ticksSinceLastRefineryCheck=-25*xr.BASE_TICKS_PER_SECOND:[...e.owner.buildings].some(e=>e.rules.refinery)||this.lastGatherExplicit?e.unitOrderTrait.addTask(new $o(t)):this.status=zo.Idle):this.status===zo.LookingForOreSite?this.ticksSinceLastOreCheck++>20*xr.BASE_TICKS_PER_SECOND&&(this.ticksSinceLastOreCheck=0,e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new Wo(t))):this.status===zo.Idle&&this.autoGatherOnNextIdle&&e.unitOrderTrait.isIdle()&&e.tile.landType===Yt.Tiberium&&(this.autoGatherOnNextIdle=!1,e.unitOrderTrait.addTask(new Wo(t,e.tile,!0)))}[Cs.onBeforeTeleport](e,t,i,r){!r&&e.owner.isCombatant()&&(this.status=zo.Idle,this.lastOreSite=void 0,i&&e.rules.teleporter&&t.afterTick(()=>{e.unitOrderTrait.addTask(new(this.isFull()?$o:Wo)(t))}))}[Uo.onPush](e,t){this.autoGatherOnNextIdle=[Vo.AttackMove,Vo.Move,Vo.ForceMove,Vo.Scatter].includes(t),[zo.LookingForRefinery,zo.LookingForOreSite].includes(this.status)&&(this.status=zo.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 Zo{constructor(e){this.target=e,this.type=Xi.LeaveTransport}}class Qo{constructor(e){this.obj=e,this.units=[],this.loadQueue=[]}unitFitsInside(e){return e.rules.size<=this.obj.rules.sizeLimit&&e.rules.size<=this.getAvailableCapacity()}getAvailableCapacity(){return this.obj.rules.passengers-this.units.reduce((e,t)=>e+t.rules.size,0)}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)}[Ts.onTick](e,t){this.loadQueue=this.loadQueue.filter(e=>!e.isDestroyed&&!e.isCrashing)}[Ms.onDestroy](e,t,i,r){var s=!!e.armedTrait?.deathWeapon,a=i?.weapon?.warhead.rules.parasite;if(r||s||e.zone===dr.Air||a)for(var n of this.units)s&&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 Ds(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 Zo(t))}}getHash(){return H(this.units.map(e=>e.getHash()))}debugGetState(){return this.units.map(e=>e.debugGetState())}dispose(){this.obj=void 0}}class Xo{[Ts.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===Xs.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}}}(Ho=Ho||{}).onHeal=Symbol();class Yo{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=ih+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}[Ts.onTick](r,s){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?ih+2:e.getCooldownTicks();let t=e.rules.damage;this.parasite.veteranTrait&&(t*=this.parasite.veteranTrait.getVeteranDamageMultiplier());let i=e.warhead.computeDamage(t,r);this.canBeCulled(r,this.parasite,e,s)&&(i=r.healthTrait.getHitPoints()),e.warhead.inflictDamage(i,r,{player:this.parasite.owner,obj:this.parasite,weapon:e},s),r.isCrashing?(this.parasiteWeapon.expireCooldown(),this.evictOrDestroyParasite(r,s)):!r.isDestroyed&&r.isVehicle()&&r.zone!==dr.Air&&e.warhead.rules.rocker&&r.applyRocking(90*(.5<=s.generateRandom()?1:-1),1)}}canBeCulled(e,t,i,r){if(!i.warhead.rules.culling)return!1;r=r.rules.audioVisual,r=t.veteranTrait?.isElite()?r.conditionYellow:r.conditionRed;return e.healthTrait.health<=100*r}[Ho.onHeal](e,t,i,r){var s;!this.parasite||this.parasite.isDestroyed||r===e||e.isAircraft()&&r?.rules.unitReload||(this.parasite.rules.organic?(s=this.parasite,this.evictOrDestroyParasite(e,t),this.stunParasite(s,t)):(this.parasite.deathType=Ls.None,t.destroyObject(this.parasite,r?{player:r.owner,obj:r}:void 0),this.uninfest()))}[$a.onDamage](e,t,i,r){r?.obj!==this.parasite&&(this.lastExternalDamageInflicted=i,this.lastExternalDamageTick=t.currentTick)}[Qs.onAttack](i,r,s){if(this.parasite&&!this.parasite.isDestroyed&&r?.weapon?.warhead.rules.sonic){var a=this.parasite;this.evictOrDestroyParasite(i,s),this.stunParasite(a,s);let e=r.weapon.warhead;e.canDamage(a,a.tile,a.zone)&&(i=e.computeDamage(r.weapon.rules.damage,a),e.inflictDamage(i,a,r,s));let t=r.obj?.unitOrderTrait.getCurrentTask();t instanceof co&&t.getWeapon().warhead.rules.sonic&&t.cancel()}}[Ms.onDestroy](e,t,i,r){this.parasite&&!this.parasite.isDestroyed&&(r||!this.parasite.invulnerableTrait.isActive()&&this.shouldSupressParasite(t,this.parasite,i)?(this.parasite.deathType=Ls.None,t.destroyObject(this.parasite,i,r),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}[Cs.onBeforeTeleport](e,t,i,r){i&&r&&this.parasite&&!this.parasite.isDestroyed&&(this.parasiteWeapon.expireCooldown(),r=this.parasite,this.evictOrDestroyParasite(e,t,!0),r.isDestroyed||this.stunParasite(r,t))}stunParasite(e,t){e.unitOrderTrait.addTaskToFront(new Ss(10/60).setCancellable(!1)),e.isVehicle()&&e.submergibleTrait&&(e.submergibleTrait.emerge(e,t),e.cloakableTrait?.uncloak(t),e.submergibleTrait.setCooldown(10*xr.BASE_TICKS_PER_SECOND))}evictOrDestroyParasite(r,s,a=!1){if(this.parasite&&!this.parasite.isDestroyed){var e=r.zone===dr.Air;if(e&&this.parasite.rules.movementZone!==ii.Fly||!e&&!s.map.terrain.getPassableSpeed(r.tile,this.parasite.rules.speedType,r.onBridge)&&!s.map.getObjectsOnTile(r.tile).find(e=>e.isBuilding()))this.parasite.deathType=Ls.None,s.destroyObject(this.parasite,{player:r.owner,obj:r});else{let t=r.tile,i=r.onBridge;if(!a&&!r.isDestroyed||this.parasite.rules.organic){let e=new Pr(s.map.tiles,s.map.mapBounds,t,{width:1,height:1},1,1,e=>0<s.map.terrain.getPassableSpeed(e,this.parasite.rules.speedType,i)&&!s.map.terrain.findObstacles({tile:e,onBridge:i},this.parasite).length);a=e.getNextTile();if(!a)return this.parasite.deathType=Ls.None,s.destroyObject(this.parasite,{player:r.owner,obj:r}),void this.uninfest();t=a}this.parasite.onBridge=i,this.parasite.position.subCell=this.parasite.isInfantry()?r.position.subCell:0,this.parasite.zone=s.map.getTileZone(t,!i),this.parasite.position.tileElevation=i?s.map.tileOccupation.getBridgeOnTile(t).tileElevation:0,this.parasite.resetGuardModeToIdle(),s.unlimboObject(this.parasite,t,!0)}this.uninfest()}}destroyParasite(e,t){this.parasite&&(this.parasite.deathType=Ls.None,t.destroyObject(this.parasite,e),this.uninfest())}dispose(){this.gameObject=void 0}}class Ko{constructor(e){this.target=e,this.type=Xi.ShipSubmergeChange}}class Jo{constructor(){this.isActive=!1}isSubmerged(){return this.isActive}setCooldown(e){this.cooldownTicks=e}[Ts.onTick](e,t){this.isActive||e.parasiteableTrait?.isInfested()||(e.attackTrait&&e.attackTrait.attackState!==no.Idle&&!e.moveTrait.isMoving()?this.cooldownTicks=Math.max(this.cooldownTicks??0,5*xr.BASE_TICKS_PER_SECOND):this.cooldownTicks??(this.cooldownTicks=Math.floor(60*t.rules.general.cloakDelay*xr.BASE_TICKS_PER_SECOND)),0<this.cooldownTicks&&this.cooldownTicks--,this.cooldownTicks<=0&&(this.isActive=!0,t.events.dispatch(new Ko(e))))}[$a.onDamage](e,t){this.emerge(e,t)}emerge(e,t){this.isActive&&(this.isActive=!1,this.cooldownTicks=void 0,t.events.dispatch(new Ko(e)))}}class eh{constructor(){this.prevHoverBobLeptons=0}[qs.onSpawn](e,t){this.setBaseElevation(e,t)}[js.onTileChange](e,t,i,r){r&&(this.prevHoverBobLeptons=0,this.setBaseElevation(e,t))}setBaseElevation(e,t){e.position.tileElevation=(e.onBridge?t.map.tileOccupation.getBridgeOnTile(e.tile)?.tileElevation??0:0)+gr.worldToTileHeight(gr.leptonsToWorld(t.rules.general.hover.height))}[Ts.onTick](e,t){var i=this.computeHoverBobLeptons(t.currentTick,t.rules.general.hover),t=i-this.prevHoverBobLeptons;this.prevHoverBobLeptons=i;i=gr.tileHeightToWorld(e.position.tileElevation);e.position.tileElevation=gr.worldToTileHeight(i+gr.leptonsToWorld(t))}computeHoverBobLeptons(e,t){e=e/xr.BASE_TICKS_PER_SECOND/(60*t.bob);return.1*t.height*z(Math.sin(2*e*Math.PI),10)}}class th{constructor(){this.tilt={pitch:0,yaw:0}}[qs.onSpawn](e){this.tilt=this.computeTilt(e.tile.rampType)}[js.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 ih=34;class rh extends sa{constructor(e,t,i){super(Ct.Vehicle,e,t,i),this.direction=0,this.spinVelocity=0,this.crateBonuses=new la,this.turretNo=0,this.onBridge=!1,this.isSinker=!1,this.isFiring=!1,this.zone=t.naval?dr.Water:dr.Ground}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,r,s){let a=new this(e,t,i);return a.isSinker=!t.underwater&&(t.weight>=r.general.shipSinkingWeight||!t.naval),a.moveTrait=new ea(a,s),a.traits.add(a.moveTrait),t.crashable&&(a.crashableTrait=new oa(a),a.traits.add(a.crashableTrait)),t.crewed&&(a.crewedTrait=new Xn,a.traits.add(a.crewedTrait)),t.harvester&&(a.harvesterTrait=new qo(t.storage),a.traits.add(a.harvesterTrait)),t.passengers&&(a.transportTrait=new Qo(a),a.traits.add(a.transportTrait),t.gunner&&(a.gunnerTrait=new Xo,a.traits.add(a.gunnerTrait))),t.turret&&(a.turretTrait=new On,a.traits.add(a.turretTrait)),t.consideredAircraft&&!t.landable||a.traits.add(new Un),t.parasiteable&&(a.parasiteableTrait=new Yo(a),a.traits.add(a.parasiteableTrait)),t.naval&&t.underwater&&(a.submergibleTrait=new Jo,a.traits.add(a.submergibleTrait)),t.locomotor===ti.Hover&&a.traits.add(new eh),t.isTilter&&!t.consideredAircraft&&(a.tilterTrait=new th,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??ih,facing:e,factor:t}}}class sh{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 ah{setParent(e){this.parent=e}getParent(){return this.parent}[Ts.onTick](r,s){if(this.parent&&r.attackTrait&&r.primaryWeapon){let e=this.parent.attackTrait?.currentTarget,t=r.unitOrderTrait.getCurrentTask(),i=new br(s.map.tileOccupation);var a=this.parent.armedTrait?.getWeapons().find(e=>e.rules.spawner);r.ammo&&!(e&&r.attackTrait.currentTarget?e.equals(r.attackTrait.currentTarget):e===r.attackTrait.currentTarget||!e&&this.parent.isUnit()&&(this.parent.unitOrderTrait.getCurrentTask()instanceof Us||this.parent.unitOrderTrait.getCurrentTask()instanceof co))&&(!e||a&&i.isInWeaponRange(this.parent,e.obj??e.tile,a,s.rules))?e&&r.primaryWeapon.targeting.canTarget(e.obj,e.tile,s,!0,!1)?!t||t instanceof Us?(r.unitOrderTrait.cancelAllTasks(),r.unitOrderTrait.addTask(r.attackTrait.createAttackTask(s,e.obj,e.tile,r.primaryWeapon,{force:!0}))):r.attackTrait.attackState!==no.Idle&&t.requestTargetUpdate(e):t?t instanceof Us||t.cancel():this.tryMoveToParent(r,this.parent,s):this.tryMoveToParent(r,this.parent,s)}}tryMoveToParent(t,i,r){if(t.tile!==i.tile){let e=t.unitOrderTrait.getCurrentTask();e?e instanceof Us&&e.updateTarget(i.tile,!!i.isUnit()&&i.onBridge):t.unitOrderTrait.addTask(new Us(r,i.tile,!!i.isUnit()&&i.onBridge,{closeEnoughTiles:0,strictCloseEnough:!0}))}}}class nh{setWarhead(e){return this.warhead=e,this}setDamage(e){return this.damage=e,this}setLauncher(e){return this.launcher=e,this}[Ms.onDestroy](e,t){this.warhead&&this.damage&&this.launcher&&this.warhead.detonate(t,this.damage,e.tile,e.tileElevation,e.position.worldPosition,e.zone,va.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 oh extends sa{constructor(e,t,i,r){super(Ct.Aircraft,e,t,i),this.pitch=0,this.yaw=0,this.roll=0,this.onBridge=!1,this.zone=dr.Ground,this.crateBonuses=new la,this.generalRules=r}get sight(){return this.rules.spawned?super.sight:super.sight+(this.zone===dr.Air&&0<super.sight?this.generalRules.aircraftFogReveal:0)}get direction(){return this.yaw}set direction(e){this.yaw=e}get isMoving(){return this.moveTrait.isMoving()}static factory(e,t,i,r,s){let a=new this(e,t,i,r.general);return a.rules.airportBound&&a.rules.dock.length&&(a.airportBoundTrait=new sh(a.rules.dock),a.traits.add(a.airportBoundTrait)),a.rules.missileSpawn||(a.crashableTrait=new oa(a),a.traits.add(a.crashableTrait)),a.rules.spawned&&(a.rules.missileSpawn?(a.missileSpawnTrait=new nh,a.traits.add(a.missileSpawnTrait)):(a.spawnLinkTrait=new ah,a.traits.add(a.spawnLinkTrait))),a.moveTrait=new ea(a,s),a.traits.add(a.moveTrait),t.dock.length&&a.traits.add(new Un),t.landable&&e!==r.general.paradrop.paradropPlane||a.traits.add(new ya),t.parasiteable&&(a.parasiteableTrait=new Yo(a),a.traits.add(a.parasiteableTrait)),a}isUnit(){return!0}isAircraft(){return!0}}class hh{constructor(e){this.gameObject=e,this.orders=[],this.queuedOrders=new Set,this.tasks=[],this.taskRunner=new so}[Ts.onTick](i,e){if(i.isSpawned){var r=this.hasTasks(),t=this.tasks.find(e=>!e.isCancelling());r&&this.taskRunner.tick(this.tasks,i);var s,a=this.orders.length;if(a&&(!r||!t)){let e,t=!1;for(;e=this.orders[0];)if(e.isValid()&&e.isAllowed()&&((s=e.process())&&(this.queuedOrders.has(e)&&(this.tasks.push(new jr(5)),this.tasks.push(new _s(()=>{i.resetGuardModeToIdle()}))),this.tasks.push(...s),r||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&&!r&&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))}}[$s.onChange](){this.clearOrders(),this.cancelAllTasks()}[Cs.onBeforeTeleport](e,t,i,r){i&&!r&&(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!==Er.NotStarted),this.tasks.forEach(e=>e.cancel())),this.orders.push(t),e&&this.queuedOrders.add(t),this.gameObject.traits.filter(Uo).forEach(e=>{e[Uo.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)}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 lh=[[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]];var ch=__webpack_require__(949);class uh{constructor(e){this.tiles=e,this._worldPosition=new ch.Vector3,this._tileOffset=new ch.Vector2,this._centerOffset=new ch.Vector2,this.desiredSubCell=0,this._tileElevation=0,this._onPositionChange=new Pn}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/gr.LEPTONS_PER_TILE-.5),t=Math.sign(this._tileOffset.y/gr.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 ch.Vector2(this._tile.rx*gr.LEPTONS_PER_TILE+this._tileOffset.x+this._centerOffset.x,this._tile.ry*gr.LEPTONS_PER_TILE+this._tileOffset.y+this._centerOffset.y)}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 r=Math.floor(e),s=Math.floor(t),a=!this._tile||this._tile.rx!==r||this._tile.ry!==s;if(a){let e=this.tiles.getByMapCoords(r,s);if(!e){if(!i)throw new RangeError(`Attempted move to a non-existent tile: [${r},${s}]`);e=this.tiles.getPlaceholderTile(r,s)}this._tile=e}this._tileOffset.set((e-r)*gr.LEPTONS_PER_TILE,(t-s)*gr.LEPTONS_PER_TILE),this.updateWorldPosition(this._tile,this._tileOffset),this._onPositionChange.dispatch(this,{tileChanged:a})}moveToLeptons(e,t=!1){this.moveToTileCoords(e.x/gr.LEPTONS_PER_TILE,e.y/gr.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)/gr.LEPTONS_PER_TILE,this._tile.ry+(this._tileOffset.y+t)/gr.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/gr.LEPTONS_PER_TILE*gr.ISO_TILE_SIZE)}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,r=2*Math.floor((e-1)/2)-1,t={width:i*gr.LEPTONS_PER_TILE/4,height:r*gr.LEPTONS_PER_TILE/4});var r=gr.LEPTONS_PER_TILE/2;return new ch.Vector2(r+t.width,r+t.height)}interpolateRampHeight(e,t,i){var r=lh[i],s=r[1],i=r[0];return s*(1-e)*(1-t)+r[2]*e*(1-t)+i*(1-e)*t+r[3]*e*t}updateWorldPosition(t,e){var i=(e.x+this._centerOffset.x)/gr.LEPTONS_PER_TILE,r=(e.y+this._centerOffset.y)/gr.LEPTONS_PER_TILE,e=gr.tileToWorld(t.rx+i,t.ry+r);let s;if(void 0!==this._tileElevation){let e=0;0!==t.rampType&&(e=this.interpolateRampHeight(i,r,t.rampType)),s=gr.tileHeightToWorld(t.z+e+this._tileElevation)}else s=this._absoluteElevation;this._worldPosition.set(e.x,s,e.y),void 0===this._tileElevation&&(this._computedTileElevation=this.computeTileElevationFromWorldPos())}computeTileElevationFromWorldPos(){if(!this._tile)return 0;var e=gr.worldToTileHeight(this._worldPosition.y),t=(this._tileOffset.x+this._centerOffset.x)/gr.LEPTONS_PER_TILE,i=(this._tileOffset.y+this._centerOffset.y)/gr.LEPTONS_PER_TILE;let r=0;return 0!==this._tile.rampType&&(r=this.interpolateRampHeight(t,i,this._tile.rampType)),e-this._tile.z-r}clone(){let e=new uh(this.tiles);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 dh{constructor(e){this.tileOccupation=e}checkCollisions(e,t,i){var r,s=e.tile;let a,n;for(r of this.tileOccupation.getObjectsOnTile(s))r.isOverlay()&&r.isBridge()&&(a=r),r.isBuilding()&&(n=r);if(i.walls){if(e.tileElevation<=2&&s.landType===Yt.Wall)return va.Wall;if(i.buildings&&n?.tile===s&&e.tileElevation<=1.1&&i.buildings(n.owner))return va.Wall}if(i.shore&&s.landType!==Yt.Water)return va.Shore;if(i.ground&&e.tileElevation<0)return va.Ground;var o=e.tileElevation+s.z,h=t.tileElevation+t.tile.z;if(a?.isHighBridge()){var l=a.tile.z+a.tileElevation;if(l<h&&o<=l||h<l&&l-1<=o)return h<l?va.UnderBridge:va.OnBridge}else if(a?.isLowBridge()&&i.shore)return va.UnderBridge;if(i.cliffs){t=s.z-t.tile.z;if(e.tileElevation<0&&4<=t)return va.Cliff}return va.None}computeDetonationZone(e,t,i){let r=this.tileOccupation.getBridgeOnTile(e);return i===va.None&&t>1.5+(r?.tileElevation??0)?dr.Air:r&&1.5<t||e.terrainType!==Xt.Water||r?.isLowBridge()?dr.Ground:dr.Water}}var ph,gh,mh,fh,yh,wh,Th,bh=__webpack_require__(949);(s=ph=ph||{})[s.Travel=0]="Travel",s[s.Impact=1]="Impact",s[s.Detonation=2]="Detonation";class vh extends ra{constructor(e,t,i,r){super(Ct.Projectile,e,t,i),this.tileOccupation=r,this.state=ph.Travel,this.detonationTimer=0,this.collisionType=va.None,this.direction=0,this.zone=dr.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 bh.Vector3,this.sonicVisitedObjects=new Map,this.collisionHelper=new dh(r)}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?Si.iniRotToDegsPerTick(this.iniRot):this.rules.rot}get iniRot(){return this.fromWeapon.rules.isSonic?10:this.rules.iniRot}static factory(e,t,i,r){return new this(e,t,i,r)}onSpawn(a){var e;if(super.onSpawn(a),this.initialSelfPosition=this.position.worldPosition.clone(),!this.target.obj||this.fromWeapon.type===si.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 br(this.tileOccupation);var t=e.distance2(this.target.getWorldCoords(),this)/gr.ISO_TILE_SIZE;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!==Xs.Elite||e.unitOrderTrait.hasTasks()||e.unitOrderTrait.addTask(new Ds(a))}}else if(this.rules.vertical){let e=this.position.clone();e.tileElevation=this.fromWeapon.warhead.rules.nukeMaker?gr.worldToTileHeight(gr.leptonsToWorld(this.fromWeapon.projectileRules.detonationAltitude)):0,this.aimPoint=gr.vecWorldToLeptons(e.worldPosition)}else{let s=this.target.getWorldCoords();a.afterTick(()=>{let e=gr.vecWorldToLeptons(this.target.getWorldCoords().clone().sub(s));var t=e.length()>gr.LEPTONS_PER_TILE;let i=t?gr.vecWorldToLeptons(s):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):gr.vecWorldToLeptons(this.target.getWorldCoords());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 r=i.clone().sub(gr.vecWorldToLeptons(this.position.worldPosition));r.length()<this.fromWeapon.speed&&this.update(a)})}}adjustAimForBallisticScatter(e,t){let i=e.rules.combatDamage.ballisticScatter,r;r=this.rules.flakScatter?(this.rules.inviso&&(i*=2),e.generateRandom()*i):i/2+e.generateRandom()*(i/2);let s=r*gr.LEPTONS_PER_TILE;this.rules.flakScatter&&(n=t.clone().sub(gr.vecWorldToLeptons(this.initialSelfPosition)).length(),s*=n/(this.fromWeapon.range*gr.LEPTONS_PER_TILE));var a=Hr(new bh.Vector2(s,0),e.generateRandomInt(0,360)),n=gr.vecWorldToGround(t).add(a).multiplyScalar(1/gr.LEPTONS_PER_TILE).floor();e.map.tiles.getByMapCoords(n.x,n.y)&&t.add(new bh.Vector3(a.x,0,a.y))}calculateBallisticOvershootVsMoving(e,t){let i=gr.vecWorldToLeptons(this.target.getWorldCoords()).sub(gr.vecWorldToLeptons(this.initialSelfPosition));var r=qr(gr.vecWorldToGround(i),gr.vecWorldToGround(t.moveTrait.velocity)),t=(90<r?180-r:r)/90,r=i.length()/gr.LEPTONS_PER_TILE,t=t*r/5;return e.generateRandom()<=t?2*Math.min(1,r/5):0}calculateInaccurateBallisticOvershoot(e){return e.generateRandom()<=.5?2:0}update(n){if(void 0!==this.maxSpeed)if(super.update(n),this.state!==ph.Impact){var r=this.velocity.clone(),o=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 n.destroyObject(this)}var h=this.updateSpeed(this.maxSpeed);this.speed=h;let a=this.target.getWorldCoords();if(this.lastTargetLockPosition&&(this.targetLockLost||a.clone().sub(this.lastTargetLockPosition).length()>=gr.ISO_TILE_SIZE)?(a=this.lastTargetLockPosition,this.targetLockLost=!0):this.lastTargetLockPosition=a.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*gr.LEPTONS_PER_TILE))return void this.detonate(n);if(this.homingMoveDir||(c=is.toMapCoords(this.direction),this.homingMoveDir=new bh.Vector3(c.x,0,c.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(n);this.limboTravelTicks++}}else if(!this.isInHomingRange(a,n))return void this.detonate(n);let e=new br(this.tileOccupation);var l=Math.floor(e.distance2(a,this)/gr.ISO_TILE_SIZE),c=2<l&&1<this.iniRot;let t=gr.vecWorldToLeptons(a.clone().sub(this.position.worldPosition)),i=0;this.homingTravelTicks<this.rules.courseLockDuration||(c?(Xr(this.homingMoveDir,new bh.Vector3(t.x,this.homingMoveDir.y,t.z),this.rot),this.rules.level||(u=U(Math.floor(this.initialTileDistToTarget)-1,0,2)+U(l-2,0,3)-this.position.tileElevation)&&(p=.25+6/this.iniRot*.1,i=gr.tileHeightToWorld(Math.sign(u)*Math.min(Math.abs(u),p))/gr.ISO_TILE_SIZE*gr.LEPTONS_PER_TILE)):Xr(this.homingMoveDir,t,this.rot)),this.direction=is.fromMapCoords(new bh.Vector2(this.homingMoveDir.x,this.homingMoveDir.z));var l=t.length(),u=Math.min(l,h);this.homingTravelDistance+=u,this.homingTravelTicks++;let r=!1,s=va.None;if(1<=u){let e=this.homingMoveDir.clone().setLength(u);i&&(e.y+=i),u===h&&this.velocity.copy(e).multiplyScalar(gr.ISO_TILE_SIZE/gr.LEPTONS_PER_TILE);var d=gr.vecLeptonsToWorld(e).add(this.position.worldPosition);n.map.mapBounds.isWithinHardBounds(d)?this.position.moveByLeptons3(e):r=!0,s=this.checkObstacles(o,n),(s||u<h)&&(r=!0)}else this.position.moveByLeptons3(t),r=!0;r&&(this.collisionType=s,this.detonate(n,s))}else{let t=this.aimPoint.clone().sub(gr.vecWorldToLeptons(this.position.worldPosition));this.rules.vertical||(this.direction=is.fromMapCoords(new bh.Vector2(t.x,t.z))),this.rules.arcing&&(t.y=0);var p=Math.min(t.length(),h);if(t.setLength(p),this.rules.arcing){let e=gr.vecWorldToGround(gr.vecWorldToLeptons(this.position.worldPosition.clone().sub(this.initialSelfPosition)).add(t));var l=this.aimPoint.clone().sub(gr.vecWorldToLeptons(this.initialSelfPosition)),s=e.length(),d=gr.vecWorldToGround(l).length(),u=l.y,l=n.rules.audioVisual.gravity,s=(u/d*h+l/2*d/h)*s/h-l*Math.pow(s/h,2)/2;t.y=s+gr.worldToLeptons(this.initialSelfPosition.y)-gr.worldToLeptons(this.position.worldPosition.y)}let e=!1;s=gr.vecLeptonsToWorld(t).add(this.position.worldPosition);n.map.isWithinHardBounds(s)?this.position.moveByLeptons3(t):e=!0;let i=va.None;if(1<=p?(p!==h&&!this.overshootTiles||this.velocity.copy(t).multiplyScalar(gr.ISO_TILE_SIZE/gr.LEPTONS_PER_TILE),i=this.checkObstacles(o,n),(i||p<h)&&(e=!0)):e=!0,e){if(!i)if(this.overshootTiles){var g=gr.vecWorldToGround(r).setLength(this.overshootTiles*gr.LEPTONS_PER_TILE);if(Hr(g,n.generateRandomInt(-45,45)),s=gr.vecLeptonsToWorld(gr.vecGroundToWorld(g)).add(this.position.worldPosition),!n.map.isWithinHardBounds(s))return void n.unspawnObject(this);this.position.moveByLeptons(g.x,g.y)}else if(this.snapToTarget&&!this.targetLockLost){if(!n.map.isWithinHardBounds(a))return void n.unspawnObject(this);this.position.moveByLeptons3(gr.vecWorldToLeptons(a.clone().sub(this.position.worldPosition)))}this.collisionType=i,this.isNuke?(this.state=ph.Impact,this.detonationTimer=2.5*xr.BASE_TICKS_PER_SECOND):this.detonate(n,i)}}let e=this.fromWeapon.warhead;if(e.rules.sonic){var t,i,g=this.position.worldPosition.clone().add(this.velocity.clone().setLength(11)),g=gr.vecWorldToGround(g).multiplyScalar(1/gr.ISO_TILE_SIZE).floor(),m=n.map.tiles.getByMapCoords(g.x,g.y);if(m&&m!==this.fromObject?.tile){var f,y=n.map.getTileZone(m);for(f of n.map.getGroundObjectsOnTile(m))if((!f.isUnit()||!f.onBridge)&&(!f.isTechno()||!f.rules.typeImmune||f.owner!==this.fromPlayer||f.name!==this.fromObject?.name)&&(!f.isAircraft()||!f.rules.spawned)&&e.canDamage(f,m,y)){let e=this.sonicVisitedObjects.get(f)??new Set;e.add(m),this.sonicVisitedObjects.set(f,e)}}for([t,i]of this.sonicVisitedObjects)for(var w of i)n.map.tileOccupation.isTileOccupiedBy(w,t)&&(w=this.fromWeapon.rules.ambientDamage*this.veteranDamageMult*this.baseDamageMultiplier,w=e.computeDamage(w,t),e.inflictDamage(w,t,{player:this.fromPlayer,weapon:this.fromWeapon,obj:this.fromObject},n,t!==this.target.obj))}}else 0<this.detonationTimer?this.detonationTimer--:this.detonate(n,this.collisionType)}isHoming(){return!!this.rot&&!this.rules.arcing}isInHomingRange(t,i){let r=!0,s=this.target.obj;if(s?.isUnit()&&this.fromObject){let e=new br(this.tileOccupation);i=e.computeWeaponRangeVsTarget(this.fromObject,s,this.fromWeapon,i.rules).range;this.fromWeapon.rules.limboLaunch?r=e.isInRange3(this.initialSelfPosition,t,0,i+.5):(t=gr.worldToLeptons(s.moveTrait.velocity.length()))&&(this.fromObject.rules.movementZone===ii.Fly?5<this.speed/t&&(r=e.isInRange2(this.initialSelfPosition,this.position.worldPosition,0,i)):isFinite(this.fromWeapon.speed)&&3.5<this.fromWeapon.speed/s.rules.speed&&(r=e.isInRange3(this.initialSelfPosition,this.position.worldPosition,0,i)))}return r}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 r=e*Ki.MAGIC_SPEED_MULT;return this.rules.arcing&&(r*=(1+i/6)/2,t=Math.floor(t),r*=t<=8?1:1+t/8*.5),this.fromWeapon.warhead.rules.sonic&&(r=Math.ceil(t*gr.LEPTONS_PER_TILE/21)),r}checkObstacles(e,t){return this.fromWeapon.rules.limboLaunch?va.None:this.collisionHelper.checkCollisions(this.position,e,{cliffs:this.rules.subjectToCliffs,ground:this.isHoming(),shore:this.rules.level,walls:this.rules.subjectToWalls,buildings:e=>this.fromPlayer!==e&&!t.alliances.areAllied(this.fromPlayer,e)})}computeBaseDamage(e){var t=this.fromWeapon,i=t.warhead;let r=t.rules.damage;t.type===si.DeathWeapon&&i.rules.ivanBomb&&(r=e.rules.combatDamage.ivanDamage);let s=r*this.baseDamageMultiplier;return t.type===si.DeathWeapon&&this.fromObject&&(s*=this.fromObject.rules.deathWeaponDamageModifier),s*=this.veteranDamageMult,s}detonate(n,e=va.None){var i=this.fromWeapon;let r=i.warhead;var t,s=this.zone=this.collisionHelper.computeDetonationZone(this.tile,this.tileElevation,e);let o=this.tile;i.type===si.DeathWeapon&&r.rules.ivanBomb&&(r=new Fa(n.rules.getWarhead(n.rules.combatDamage.ivanWarhead)));let a=this.computeBaseDamage(n);n.destroyObject(this),this.state=ph.Detonation;let h=this.target.obj,l=!1;if(r.rules.parasite&&h?.isUnit()&&o===h.tile&&r.canDamage(h,o,s))if(h.isInfantry())a=Number.POSITIVE_INFINITY;else if(h.parasiteableTrait&&this.fromObject?.isUnit()){if(!(this.fromWeapon instanceof za))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),r.rules.sonic&&(c=!1),r.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}))),r.rules.bombDisarm&&(c=!1,h?.isTechno()&&h.tntChargeTrait?.hasCharge()&&!h.isDestroyed&&h.tntChargeTrait.removeCharge()),r.rules.mindControl&&(c=!1,this.fromObject&&!this.fromObject.isDestroyed&&h?.isTechno()&&h.mindControllableTrait&&!h.mindControllableTrait?.isActive()&&!n.areFriendly(h,this.fromObject)&&r.canDamage(h,o,s)&&!h.invulnerableTrait.isActive()&&this.fromObject.mindControllerTrait.control(h,n)),r.rules.temporal&&(c=!1,this.fromObject&&!this.fromObject.isDestroyed&&h?.isTechno()&&r.canDamage(h,o,s)&&!h.invulnerableTrait.isActive()&&(r.inflictDamage(0,h,{player:this.fromPlayer,weapon:i,obj:this.fromObject},n),this.fromObject.temporalTrait.updateTarget(h,i,n))),r.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)),r.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&&r.detonate(n,a,o,this.tileElevation,this.position.worldPosition,s,e,this.target,{player:this.fromPlayer,weapon:i,obj:this.fromObject},this.isShrapnel,!1,this.impactAnim),r.rules.nukeMaker){let e;e=this.fromObject?(u=za.factory(za.NUKE_PAYLOAD_NAME,si.Primary,this.fromObject,n.rules),n.createProjectile(u.projectileRules.name,this.fromObject,u,this.target,!1)):n.createLooseProjectile(za.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,r=new br(n.map.tileOccupation),e=new Pr(n.map.tiles,n.map.mapBounds,o,{width:1,height:1},1,t.range,e=>r.isInTileRange(o,e,t.minimumRange,t.range)),s=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?Mn.Air:Mn.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===Br.Paradrop))))if(!s.has(g)&&(s.add(g),i=Math.max(0,i-1-(g.isTechno()?.5:0)),Math.floor(i)<=0))break}for(d of s){var f=n.createTarget(d.isTerrain()?void 0:d,d.tile);this.createShrapnel(n,f,t.name)}i=Math.floor(i);let a=new Ps(n.map.tiles,n.map.mapBounds,o,t.range,n,e=>r.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 s=this.fromObject;r.rules.parasite&&(this.target.obj.isVehicle()||this.target.obj?.isAircraft())&&this.target.obj.parasiteableTrait&&(this.target.obj.parasiteableTrait.beingBoarded=!1);let t,a;i=s.rules.movementZone===ii.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),r=new Wr(n.map),e=new Pr(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,s.rules.speedType,!!t)&&r.isEligibleTile(e,t,i,o)&&(e===o||!n.map.terrain.findObstacles({tile:e,onBridge:i},s).length)});t=e.getNextTile(),a=!!t?.onBridgeLandType}t?(!i&&this.target.obj.isUnit()&&(s.onBridge=a,s.position.tileElevation=a?n.map.tileOccupation.getBridgeOnTile(t)?.tileElevation??0:0),n.unlimboObject(s,t),s.isInfantry()&&(s.position.subCell=this.target.obj.position.subCell),s.direction=this.direction):s.owner.removeOwnedObject(s)}}createShrapnel(e,t,i){let r=e.createLooseProjectile(i,this.fromPlayer,t);r.isShrapnel=!0,r.veteranDamageMult=this.veteranDamageMult,r.position.moveToLeptons(this.position.getMapPosition()),r.position.tileElevation=this.position.tileElevation,e.spawnObject(r,r.position.tile)}computeAimPointVersusMovingTarget(t,i,r,s){let a=t.position.worldPosition,n=a.clone();i=gr.leptonsToWorld(i);if(i<3*t.moveTrait.velocity.length())return gr.vecWorldToLeptons(a);let o=ps.computeInterceptPoint(r,i,a,t.moveTrait.velocity);if(o.length()){let e=o.clone().sub(a);r=e.length(),i=t.moveTrait.velocity.length(),r=i?Math.ceil(r/i):0;if(o=a.clone().add(e.setLength(r*i)),s.isWithinHardBounds(o))if(t.zone!==dr.Air){o.multiplyScalar(1/gr.ISO_TILE_SIZE);let e=t.position.clone();e.moveToTileCoords(o.x,o.z),n=e.worldPosition}else n=o;else n=a}return gr.vecWorldToLeptons(n)}}(s=gh=gh||{})[s.None=0]="None",s[s.PreparingToFire=1]="PreparingToFire",s[s.FiringUp=2]="FiringUp",s[s.Firing=3]="Firing";class Sh{constructor(e){this.gameObject=e,this.deployed=!1,this.deployFireDelay=0,this.deployFireState=gh.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?Br.Deployed:Br.None),t?(this.deployFireState=gh.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===gh.FiringUp&&(e.isFiring=!1),this.deployFireState=gh.None,this.deployWeapon=void 0)}}toggleDeployed(){this.setDeployed(!this.isDeployed())}[Ts.onTick](e,t){if(void 0!==this.undeployDelay&&(0<this.undeployDelay&&this.undeployDelay--,this.undeployDelay<=0&&[gh.None,gh.PreparingToFire].includes(this.deployFireState)))return this.undeployDelay=void 0,void this.setDeployed(!1);if(this.deployWeapon&&this.deployFireState!==gh.None){if(this.deployFireState===gh.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=gh.FiringUp}if(this.deployFireState===gh.FiringUp){if(e.isFiring=!0,0<this.fireUpDelay--)return;this.deployFireState=gh.Firing}var i;this.deployFireState===gh.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=gh.None,this.deployWeapon=void 0):this.deployFireState=gh.PreparingToFire)}}computeDeployFireCooldown(t,i){if(t.rules.radLevel&&t.rules.areaFire){var r=this.gameObject.tile,r=i.mapRadiationTrait.getRadSiteLevel(r);if(!r)return 0;i=i.rules.radiation;let e=Math.max(0,r*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}}(mh=mh||{}).onChange=Symbol();class _h{constructor(e,t,i,r,s){this.target=e,this.attacker=t,this.damageHitPoints=i,this.currentHealth=r,this.prevHealth=s,this.type=Xi.InflictDamage}}(fh=fh||{}).onChange=Symbol(),(s=yh=yh||{})[s.Green=0]="Green",s[s.Yellow=1]="Yellow",s[s.Red=2]="Red";class kh{constructor(e,t,i){this.target=e,this.currentHealth=t,this.prevHealth=i,this.type=Xi.HealthChange}}class Oh{constructor(e,t,i,r){this.maxHitPoints=e,this.gameObject=t,this.conditionYellow=i,this.conditionRed=r,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?yh.Green:this.health>100*this.conditionRed?yh.Yellow:yh.Red}setHitPoints(e){if(e!==Math.floor(e))throw new Error(`Value ${e} is not an integer`);this.hitPoints=U(e,0,this.maxHitPoints),this._computedHealth=this.hitPoints/this.maxHitPoints*100}getHitPoints(){return this.hitPoints}getProjectedHitPoints(){return this.projectedHitPoints}inflictDamage(t,i,r){var e=this.hitPoints,s=this.health;this.applyHitPoints(e-t,r),e!==this.hitPoints&&0<t&&(this.gameObject.traits.filter($a).forEach(e=>{e[$a.onDamage](this.gameObject,r,t,i)}),r.events.dispatch(new _h(this.gameObject,i,t,this.health,s)))}healBy(e,i,r){if(e<0)throw new Error(`Can't heal by negative value ${e}`);if(this.hitPoints<this.maxHitPoints){var s=this.hitPoints;this.applyHitPoints(this.hitPoints+e,r),this.projectedHitPoints=this.hitPoints;let t=this.hitPoints-s;this.gameObject.traits.filter(Ho).forEach(e=>{e[Ho.onHeal]?.(this.gameObject,r,t,i)})}}healToFull(i,r){if(this.hitPoints<this.maxHitPoints){var e=this.hitPoints;this.applyHitPoints(this.maxHitPoints,r),this.projectedHitPoints=this.hitPoints;let t=this.hitPoints-e;this.gameObject.traits.filter(Ho).forEach(e=>{e[Ho.onHeal]?.(this.gameObject,r,t,i)})}}applyHitPoints(e,t){let i=this.health;this.setHitPoints(e),i!==this.health&&(t.traits.filter(mh).forEach(e=>{e[mh.onChange](this.gameObject,t,i)}),this.gameObject.traits.filter(fh).forEach(e=>{e[fh.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)}[Ts.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 Ih{constructor(e){this.bridges=e,this.needsImageUpdate=!1,this.dominoHandled=!1}[$a.onDamage](){this.needsImageUpdate=!0}[Ts.onTick](e){this.needsImageUpdate&&(this.needsImageUpdate=!1,this.bridges.handlePieceHealthChange(this.bridges.getPieceAtTile(e.tile)))}[Ms.onDestroy](r,s,a){var e=this.bridges.getPieceAtTile(r.tile);this.dominoHandled||this.bridges.findDominoPieces(e).forEach(e=>{e.obj.traits.get(Ih).dominoHandled=!0,s.destroyObject(e.obj,a)});let t=s.map.tileOccupation.calculateTilesForGameObject(r.tile,r);t.forEach(e=>{let t=Wi(e.terrainType),i=s.rules.getLandRules(t);s.map.getGroundObjectsOnTile(e).forEach(e=>{e.isUnit()&&e.onBridge&&(r.isLowBridge()&&0<i.getSpeedModifier(e.rules.speedType)||e.isInfantry()&&e.stance===Br.Paradrop?(e.onBridge=!1,e.zone=mr(t)):(e.isInfantry()&&(e.infDeathType=Jt.None),s.destroyObject(e,a,!0)))})})}}(s=wh=wh||{})[s.Idle=0]="Idle",s[s.Spawning=1]="Spawning";class Ah{constructor(e){this.rules=e,this.ticksSinceLastSpawn=0,this.cooldownTicks=Math.floor(1/this.rules.animationProbability),this.status=wh.Idle}[Ts.onTick](e,t){this.status=wh.Idle,this.ticksSinceLastSpawn++>this.cooldownTicks&&(this.ticksSinceLastSpawn=0,this.status=wh.Spawning,this.spawnTiberium(e.tile,t))}spawnTiberium(r,s){for(let i=1;i<=2;i++){let e=new Pr(s.map.tiles,s.map.mapBounds,r,{width:1,height:1},i,i,e=>Pa.canBePlacedOn(e,s.map));var a=e.getNextTile();if(a){var n=an.calculateOverlayId(_a.Ore,a.rx,a.ry);if(void 0===n)throw new Error("Expected an overlayId");let e=s.createObject(Ct.Overlay,s.rules.getOverlayName(n));return e.overlayId=n,e.value=3,void s.spawnObject(e,a)}e=new Pr(s.map.tiles,s.map.mapBounds,r,{width:1,height:1},i,i,e=>e.landType===Yt.Tiberium);let t;for(;!t;){var o=e.getNextTile();if(!o)break;t=s.map.getObjectsOnTile(o).find(e=>e.isOverlay()&&e.isTiberium()&&e.traits.get(Pa).getBailCount()+1<=Pa.maxBails)}if(t)return void t.traits.get(Pa).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}[Ts.onTick](t,i){if(!this.isDisabled())if(100===t.healthTrait.health&&this.setDisabled(!0),this.cooldownTicks<=0){var r=i.rules.general.repair,s=t.isInfantry()?r.iRepairRate:t.isBuilding()?r.repairRate:r.uRepairRate;this.cooldownTicks+=xr.BASE_TICKS_PER_SECOND*s*60;var a=t.isInfantry()?r.iRepairStep:r.repairStep,s=this.freeRepair?0:r.repairPercent;let e;s?(r=s*t.purchaseValue/t.healthTrait.maxHitPoints,s=Math.min(t.owner.credits,Math.max(1,Math.floor(r*a))),e=r&&s?s/r:a,s?t.owner.credits-=s: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--}[$s.onChange](){this.setDisabled(!0)}}(Th=Th||{}).onDestroy=Symbol();class Bh{constructor(e){this.target=e,this.type=Xi.UnitPromote}}class Eh{constructor(){this.cooldownTicks=0}[Ts.onTick](e,t){100!==e.healthTrait.health&&(this.cooldownTicks<=0?(this.cooldownTicks+=xr.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===Xs.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?(s=e?t.art.elitePrimaryFireFlh:t.art.primaryFireFlh,this.primaryWeapon=za.factory(i,si.Primary,t,this.rules,s)):this.primaryWeapon=void 0;var r,s=e&&t.rules.eliteSecondary||t.rules.secondary;s?(r=e?t.art.eliteSecondaryFireFlh:t.art.secondaryFireFlh,this.secondaryWeapon=za.factory(s,si.Secondary,t,this.rules,r)):this.secondaryWeapon=void 0,(t.explodes||t.crashableTrait)&&(r=t.rules.deathWeapon||!!t.crashableTrait&&this.secondaryWeapon?.rules.name||this.primaryWeapon?.rules.name||this.rules.combatDamage.deathWeapon,this.deathWeapon=za.factory(r,si.DeathWeapon,t,this.rules))}selectSpecialWeapon(e,t=!1){let i=this.gameObject;var r=i.rules.weaponCount;if(r<1)throw new Error(`Object "${i.name}" doesn't support special weapons`);if(r-1<e)throw new RangeError(`Weapon index ${e} out of bounds (max ${r}) for object ${i.name}`);r=t&&i.rules.getEliteWeaponAtIndex(e)||i.rules.getWeaponAtIndex(e);if(!r)throw new Error(`Missing weapon at index ${e} for object "${i.name}"`);t=i.art.getSpecialWeaponFlh(e);this.primaryWeapon=za.factory(r,si.Primary,i,this.rules,t),this.secondaryWeapon=void 0,this.specialWeaponIndex=e,this.deathWeapon=this.primaryWeapon.rules.suicide?za.factory(i.rules.deathWeapon||this.primaryWeapon.name,si.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===si.Primary?this.primaryWeapon:this.secondaryWeapon}isEquippedWithWeapon(e){return[this.primaryWeapon,this.secondaryWeapon].includes(e)}getWeapons(){return[this.primaryWeapon,this.secondaryWeapon].filter(ga)}[Ts.onTick](){this.primaryWeapon&&this.primaryWeapon.tick(),this.secondaryWeapon&&this.secondaryWeapon.tick()}[Ms.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 Ph{}class Nh{constructor(e,t){this.gameObject=e,this.veteranRules=t,this.veteranLevel=Xs.None,this.xp=0,this.promotionThresh=e.rules.cost*t.veteranRatio+1}[Th.onDestroy](e,t,i,r){e.isDestroyed&&!e.isCrashing||t.isTechno()&&(t.rules.dontScore||t.rules.insignificant||(i&&(i.warhead.rules.temporal||i.warhead.rules.parasite&&e.rules.organic)||!r.areFriendly(e,t))&&(this.veteranLevel>=this.veteranRules.veteranCap||this.gainXP(t.rules.cost*(t.veteranLevel+1))&&this.handlePromotion(e,r)))}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===Xs.Elite}setVeteranLevel(e){this.veteranLevel=e,this.veteranLevel===Xs.Elite&&this.gameObject.armedTrait?.toggleEliteWeapons(!0)}handlePromotion(e,t){this.hasVeteranAbility(ai.SELF_HEAL)&&(e.traits.find(Eh)||t.addObjectTrait(e,new Eh)),this.hasVeteranAbility(ai.CLOAK)&&(e.cloakableTrait||(e.cloakableTrait=new sn(e,t.rules.general.cloakDelay),t.addObjectTrait(e,e.cloakableTrait))),this.hasVeteranAbility(ai.EXPLODES)&&(e.explodes||(e.explodes=!0,e.armedTrait||(e.armedTrait=new xh(e,t.rules),t.addObjectTrait(e,e.armedTrait)))),this.hasVeteranAbility(ai.RADAR_INVISIBLE)&&(e.radarInvisible||(e.radarInvisible=!0)),this.hasVeteranAbility(ai.SENSORS)&&(e.sensorsTrait||(e.sensorsTrait=new Ph,t.addObjectTrait(e,e.sensorsTrait))),e.isInfantry()&&this.hasVeteranAbility(ai.FEARLESS)&&e.suppressionTrait?.disable(),this.hasVeteranAbility(ai.C4)&&(e.c4||(e.c4=!0)),this.hasVeteranAbility(ai.GUARD_AREA)&&(e.defaultToGuardArea||(e.defaultToGuardArea=!0,e.unitOrderTrait.isIdle()&&e.resetGuardModeToIdle())),this.hasVeteranAbility(ai.CRUSHER)&&(e.crusher||(e.crusher=!0)),t.events.dispatch(new Bh(e))}getVeteranSightMultiplier(){return this.getVeteranAbilityMultiplier(ai.SIGHT)}getVeteranSpeedMultiplier(){return this.getVeteranAbilityMultiplier(ai.FASTER)}getVeteranArmorMultiplier(){return this.getVeteranAbilityMultiplier(ai.STRONGER)}getVeteranDamageMultiplier(){return this.getVeteranAbilityMultiplier(ai.FIREPOWER)}getVeteranRofMultiplier(){return this.getVeteranAbilityMultiplier(ai.ROF)}hasVeteranAbility(e){return this.veteranLevel===Xs.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=Xs.Elite&&this.gameObject.rules.eliteAbilities.has(e)}getVeteranAbilityMultiplier(e){let t=1;return(this.veteranLevel===Xs.Veteran&&this.gameObject.rules.veteranAbilities.has(e)||this.veteranLevel>=Xs.Elite&&this.gameObject.rules.eliteAbilities.has(e))&&(t=this.getVeteranRulesMultiplier(e)),t}getVeteranRulesMultiplier(e){switch(e){case ai.FASTER:return this.veteranRules.veteranSpeed;case ai.STRONGER:return this.veteranRules.veteranArmor;case ai.FIREPOWER:return this.veteranRules.veteranCombat;case ai.ROF:return this.veteranRules.veteranROF;case ai.SIGHT:return this.veteranRules.veteranSight;default:throw new Error(`Unhandled VeteranAbility ${e}`)}}dispose(){this.gameObject=void 0}}class Rh{constructor(e,t=e){this.maxAmmo=e,this.ammo=t}get ammo(){return this._ammo}set ammo(e){this._ammo=U(e,0,this.maxAmmo)}isFull(){return this.ammo===this.maxAmmo}}class Dh{constructor(e){this.target=e,this.type=Xi.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===Ct.Terrain}disguiseAs(e,t,i){this.disguisedAs={rules:e.rules,owner:e.owner},this.isActive=!0,i.events.dispatch(new Dh(t))}revealDisguise(e,t){this.cooldownTicks=t.rules.general.infantryBlinkDisguiseTime,this.isActive=!1,t.events.dispatch(new Dh(e))}[qs.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,Ct.Infantry),this.disguisedAs={rules:i,owner:e.owner},this.isActive=!0))}getDefaultInfantryDisguise(e,t){switch(e){case qt.GDI:return t.alliedDisguise;case qt.Nod:return t.sovietDisguise;default:return}}[Ts.onTick](e,t){e.rules.permaDisguise||(e.attackTrait?.attackState===no.JustFired||e.moveTrait.moveState!==zs.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 Dh(e))))}[$a.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,Ct.Terrain)}}class Lh{constructor(){this.timer=new vo}isActive(){return this.timer.isActive()}setActiveFor(e,t){this.timer.setActiveFor(e,t)}[Ts.onTick](e,t){this.timer.tick(t.currentTick)}}class Fh{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(kr).forEach(e=>{e[kr.onChange](this.gameObject,i,t)}),this.gameObject.traits.filter(Ln).forEach(e=>{e[Ln.onChange](this.gameObject,i,t)})}expire(e){this.remainingTicks=0,this.notifyChange(!1,e)}isInvulnerable(){return this.isActive()&&this.invulnerable}[Ts.onTick](e,t){0<this.remainingTicks&&(this.remainingTicks--,this.remainingTicks<=0&&this.notifyChange(!1,t))}dispose(){this.gameObject=void 0}}class jh{constructor(){this.timer=new vo}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()}[Ts.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))}[Ms.onDestroy](e,t,i){this.timer.isActive()&&!i?.weapon?.warhead.rules.ivanBomb&&e.deathType!==Ls.None&&e.deathType!==Ls.Temporal&&(this.timer.reset(),this.detonateIvanWarhead(t,e))}detonateIvanWarhead(e,t){var i=e.rules.combatDamage.ivanDamage;let r=new Fa(e.rules.getWarhead(e.rules.combatDamage.ivanWarhead));var s=t.tile,a=t.tileElevation,n=t.isUnit()?t.zone:e.map.getTileZone(s),o=!!t.isUnit()&&t.onBridge;r.detonate(e,i,s,a,t.isBuilding()?gr.tile3dToWorld(s.rx+.5,s.ry+.5,s.z+a):t.position.worldPosition,n,o?va.OnBridge:va.None,e.createTarget(t,s),{...this.attackerInfo,weapon:void 0},!1,!1,void 0)}}class Wh{constructor(e){this.gameObject=e}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)}[Zs.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)}[Zs.onUnspawn](e,t){for(var i of this.targets)i.mindControllableTrait.restore(t);this.targets.length=0}dispose(){this.gameObject=void 0}}class Vh{constructor(e){this.gameObject=e,this.ticksWhenWarpedOut=!0,this.attackers=new Set}[Ts.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 r=i.temporalTrait.currentWeapon;if(!r)throw new Error(`Attacker "${i.name}" is no longer targeting "${e.name}"`);var s=r.rules.damage;if(this.eraseTicks-=s,this.eraseTicks<=0){e.deathType=Ls.Temporal,t.destroyObject(e,{player:i.owner,obj:i,weapon:r},!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 co||e instanceof Us)&&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}}[Ms.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}[qs.onSpawn](t,i){var r=i.rules.getObject(t.rules.spawns,Ct.Aircraft);for(let e=0;e<t.rules.spawnsNumber;e++)this.pushNewSpawn(r,i,t)}[Zs.onUnspawn](e,t){this.destroySpawns(e,t)}[Ms.onDestroy](e,t,i,r){this.destroySpawns(e,t,i,r)}pushNewSpawn(e,t,i){let r=t.createUnitForPlayer(e,i.owner);r.limboData={selected:!1,controlGroup:void 0},e.missileSpawn&&(r.pitch=90*t.rules.general.getMissileRules(e.name).pitchInitial),this.spawns.push(r),this.storage.push(r)}destroySpawns(e,t,i,r){for(var s of this.spawns)s.isDestroyed||(s.isSpawned&&!s.rules.missileSpawn&&s.crashableTrait?s.crashableTrait.crash(i):(s.isSpawned||(s.armedTrait&&(s.armedTrait.deathWeapon=void 0),s.position.tileElevation=e.position.tileElevation,s.zone=e.isUnit()?e.zone:dr.Ground,s.onBridge=!!e.isUnit()&&e.onBridge,s.position.tile=e.tile),t.destroyObject(s,i,r)));this.spawns.length=0,this.storage.length=0,this.missileLaunches.length=0}[Ts.onTick](s,a){var t;if(this.spawns=this.spawns.filter(e=>!e.isDestroyed),this.missileLaunches=this.missileLaunches.filter(e=>!e.missile.isDestroyed),this.spawns.length<s.rules.spawnsNumber){var i=s.rules.spawnsNumber-this.spawns.length,r=a.rules.getObject(s.rules.spawns,Ct.Aircraft);for(let e=0;e<i;e++)r.missileSpawn&&e&&void 0===this.nextRegenTicks[e]?this.nextRegenTicks[e]=this.nextRegenTicks[0]:((t=this.nextRegenTicks)[e]??(t[e]=s.rules.spawnRegenRate),0<this.nextRegenTicks[e]&&this.nextRegenTicks[e]--),this.nextRegenTicks[e]<=0&&this.pushNewSpawn(r,a,s);this.nextRegenTicks=this.nextRegenTicks.filter(e=>0<e)}if(this.storage.length){if(this.nextReloadTicks??(this.nextReloadTicks=s.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=s.rules.spawnReloadRate}}else this.nextReloadTicks=void 0;for(let r of this.missileLaunches.slice()){var n=a.rules.general.getMissileRules(r.missile.name);if(r.pauseFrames??(r.pauseFrames=n.pauseFrames),0<r.pauseFrames&&r.pauseFrames--,r.pauseFrames<=0){var o=90*n.pitchFinal,n=90*(n.pitchFinal-n.pitchInitial)/n.tiltFrames;let i=r.missile;if(i.pitch<o)i.pitch=Math.min(o,i.pitch+n);else{i.unitOrderTrait.addTask(new ma(new Us(a,r.targetTile,!!r.targetBridge),new _s(()=>{var e,t;i.isDestroyed||(a.unspawnObject(i),i.dispose(),t=gr.vecGroundToWorld(is.toMapCoords(i.direction).multiplyScalar(gr.leptonsToWorld(1))),e=r.targetWorldPos.clone().add(t),t=a.map.getTileZone(r.targetTile),r.warhead.detonate(a,r.damage,r.targetTile,r.targetBridge?.tileElevation??0,e,t,r.targetBridge?va.OnBridge:va.None,r.target,{player:i.owner,obj:s,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(r),1)}}}}[$s.onChange](e,t,i){for(var r of this.spawns)r.isDestroyed||i.changeObjectOwner(r,e.owner)}[Ln.onChange](e,t,i){i&&this.removeMissileLaunches(t)}[Cs.onBeforeTeleport](e,t,i,r){r||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(r,s,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=r.veteranTrait?.isElite(),o=a.rules;if(r.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(r.rules.spawns!==o.general.dMisl.type)throw new Error(`Unhandled missile type "${r.rules.spawns}"`);e=n?o.combatDamage.dMislEliteWarhead:o.combatDamage.dMislWarhead,t=n?o.general.dMisl.eliteDamage:o.general.dMisl.damage}a=new Fa(a.rules.getWarhead(e));i.missileSpawnTrait.setDamage(t).setWarhead(a).setLauncher(r),this.missileLaunches.push({missile:i,targetTile:(s.obj?.isUnit()?s.obj:s).tile,targetBridge:s.getBridge(),targetWorldPos:s.getWorldCoords().clone(),target:s,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(r)}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 Hh{[Ys.onCrash](e,t){this.handleDestroy(e,t)}[Ms.onDestroy](e,t,i){i?.weapon?.warhead.rules.temporal||e.isCrashing||e.deathType!==Ls.Sink&&e.isSpawned&&this.handleDestroy(e,t)}handleDestroy(e,t){var i,r;(e.isVehicle()||e.isBuilding()||e.isOverlay())&&(i=e.isOverlay()?0:e.rules.minDebris,r=e.isOverlay()?t.rules.general.bridgeVoxelMax:e.rules.maxDebris,0<(r=t.generateRandomInt(i,r))&&this.spawnDebris(e,t,r))}spawnDebris(t,i,r){let s=t.position.getMapPosition();if(i.map.isWithinHardBounds(gr.vecLeptonsToWorld(s))){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,Ct.VoxelAnim)||i.art.hasObject(e,Ct.Animation)),new Array(r).fill(0).map(()=>e[i.generateRandomInt(0,e.length-1)]).map(e=>i.createObject(Ct.Debris,e)).forEach(e=>{e.position.moveToLeptons(s),e.position.tileElevation=t.position.tileElevation,i.spawnObject(e,e.position.tile)})}}}var Gh=__webpack_require__(949);class $h extends ra{constructor(e,t,i,r){super(Ct.Debris,e,t,i),this.age=0,this.direction=0,this.rotationAxis=new Gh.Vector3,this.angularVelocity=0,this.zone=dr.Air,this.velocity=new Gh.Vector3,this.collisionHelper=new dh(r)}static factory(e,t,i,r){return new this(e,t,i,r)}onSpawn(e){super.onSpawn(e),this.direction=e.generateRandomInt(0,359),this.xySpeed=Gh.Math.lerp(0,this.rules.maxXYVel,e.generateRandom()),this.zSpeed=Gh.Math.lerp(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=Gh.Math.lerp(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 e=is.toMapCoords(this.direction).setLength(this.xySpeed),i=new Gh.Vector3(e.x,this.zSpeed,e.y),r=this.position.clone(),e=gr.vecLeptonsToWorld(i).add(this.position.worldPosition);if(t.map.isWithinHardBounds(e)){this.position.moveByLeptons3(i);let e=!1;r=this.collisionHelper.checkCollisions(this.position,r,{cliffs:!0,ground:!0,shore:!1,walls:!0,buildings:!1});r&&(!([va.Ground,va.OnBridge].includes(r)&&0<this.rules.elasticity&&t.map.getTileZone(this.tile)!==dr.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?(this.velocity.set(0,0,0),this.detonate(t,r)):this.velocity.copy(i).multiplyScalar(gr.ISO_TILE_SIZE/gr.LEPTONS_PER_TILE)}else t.unspawnObject(this)}detonate(t,i=va.None){var e,r=this.rules.warhead?t.rules.getWarhead(this.rules.warhead):void 0,s=this.zone=this.collisionHelper.computeDetonationZone(this.tile,this.tileElevation,i);let a;s===dr.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 Na;if(a&&n.spawnSmudges(a,this.tile,t),t.destroyObject(this),r){let e=new Fa(r);e.detonate(t,this.rules.damage,this.tile,this.tileElevation,this.position.worldPosition,s,i,t.createTarget(void 0,this.tile),void 0,!1,!1,void 0,this.rules.damageRadius||void 0,!0)}}}class qh{constructor(e,t,i,r){this.tiles=e,this.tileOccupation=t,this.bridges=i,this.nextObjectId=r}create(e,t,i,r){let s,a;e===Ct.Smudge?(a=r.getOrCreateObject(t,Ct.Smudge),s=i.getObject(t,Ct.Smudge)):e===Ct.Debris?s=i.hasObject(t,Ct.VoxelAnim)?(a=r.getOrCreateObject(t,Ct.VoxelAnim),i.getObject(t,Ct.VoxelAnim)):(a=r.getAnimation(t),new ir(Ct.Debris,r.getIni().getOrCreateSection(t))):a=e===Ct.Projectile?(s=i.getProjectile(t),s.inviso?new bn(Ct.Projectile,s,new h(t)):r.getProjectile(t)):(s=i.getObject(t,e),r.getObject(t,e));let n;switch(e){case Ct.Building:n=Do.factory(t,s,i,a,this.tiles,this.bridges);break;case Ct.Infantry:n=ca.factory(t,s,a,this.tileOccupation);break;case Ct.Vehicle:n=rh.factory(t,s,a,i,this.tileOccupation);break;case Ct.Aircraft:n=oh.factory(t,s,a,i,this.tileOccupation);break;case Ct.Terrain:n=Mo.factory(t,s,a);break;case Ct.Overlay:n=Lo.factory(t,s,a);break;case Ct.Smudge:n=Fo.factory(t,s,a);break;case Ct.Projectile:n=vh.factory(t,s,a,this.tileOccupation);break;case Ct.Debris:n=$h.factory(t,s,a,this.tileOccupation);break;default:throw new Error("Not implemented")}if(n.id=this.nextObjectId.value++,n.position=new uh(this.tiles),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 Rh(n.rules.ammo,-1!==o?o:void 0),n.traits.add(n.ammoTrait)),n.unitOrderTrait=new hh(n),n.traits.addToFront(n.unitOrderTrait),(n.primaryWeapon||n.secondaryWeapon)&&(n.attackTrait=new ho(this.tiles,this.tileOccupation),n.traits.add(n.attackTrait)),(n.isInfantry()||n.isVehicle())&&n.rules.deployer&&(n.deployerTrait=new Sh(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 sn(n,i.general.cloakDelay),n.traits.add(n.cloakableTrait)),n.rules.sensors&&(n.sensorsTrait=new Ph,n.traits.add(n.sensorsTrait)),n.autoRepairTrait=new Ch(!n.isBuilding()),n.traits.add(n.autoRepairTrait),n.rules.trainable&&(n.veteranTrait=new Nh(n,i.general.veteran),n.traits.add(n.veteranTrait)),n.rules.selfHealing&&n.traits.add(new Eh),n.invulnerableTrait=new Lh,n.traits.add(n.invulnerableTrait),n.warpedOutTrait=new Fh(n),n.traits.add(n.warpedOutTrait),n.temporalTrait=new Vh(n),n.traits.add(n.temporalTrait),n.rules.bombable&&(n.tntChargeTrait=new jh,n.traits.add(n.tntChargeTrait)),n.rules.immuneToPsionics||n.isBuilding()||(n.mindControllableTrait=new Wh(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 Hh)),n.isTechno()||n.isOverlay()||n.isTerrain()){var o=n.isOverlay()&&Ca.isBridge(i.getOverlayId(n.name));let e=n.rules.strength;!e&&n.isTerrain()&&(e=i.general.treeStrength),o&&(e=i.combatDamage.bridgeStrength),e&&(n.healthTrait=new Oh(e,n,i.audioVisual.conditionYellow,i.audioVisual.conditionRed),n.traits.add(n.healthTrait)),n.isOverlay()&&o&&(n.bridgeTrait=new Ih(this.bridges),n.traits.add(n.bridgeTrait),Ca.getOverlayBridgeType(i.getOverlayId(n.name))===Ta.Concrete&&n.traits.add(new Hh))}return n.isOverlay()&&n.isOverlay()&&xa.getOverlayTibType(i.getOverlayId(n.name))!==_a.NotSpecial&&n.traits.add(new Pa(n)),n.isTerrain()&&n.rules.spawnsTiberium&&n.traits.add(new Ah(n.rules)),n.cachedTraits.tick.push(...n.traits.filter(Ts)),n}}class Zh{constructor(){this.allObjects=new Map,this._onObjectSpawned=new Pn,this._onObjectRemoved=new Pn}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 s=__webpack_require__(495),Qh=__webpack_require__.n(s),Xh=__webpack_require__(45);class Yh{constructor(e,t,i,r,s){this.tiles=e,this.theaterType=t,this.mapBounds=i,this.tileOccupation=r,this.rules=s,this.passabilityGraphs=new Map,this.invalidatedTiles=new Map,this.handleTileOccupationUpdate=({tiles:e,object:i})=>{e=e.filter(e=>{let t=Kt.Foot;return i.isTerrain()&&i.rules.getOccupationBits(this.theaterType)!==Zi.All&&(t=Kt.Wheel),i.isOverlay()&&i.isBridge()||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()},r.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,r,s,{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(r,s),d=!!l.hasNode(u);d||((h=new Pr(this.tiles,this.mapBounds,r,{width:1,height:1},1,5,e=>0<this.getPassableSpeed(e,t,!1)&&Math.abs(e.z-r.z)<2&&!o?.({tile:e,onBridge:void 0,speed:100})).getNextTile())?(r=h,s=!1):(l.addNode(u,{tile:r,onBridge:void 0,speed:100}),a=Math.min(a,500)));let p=(0,Xh.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 r=Math.abs(e.data.tile.rx-t.data.tile.rx),t=Math.abs(e.data.tile.ry-t.data.tile.ry);let s=r+t+(Math.SQRT2-2)*Math.min(r,t);return i?.parent&&(t=(r=i.parent.node).data.tile.rx-e.data.tile.rx,e=r.data.tile.ry-e.data.tile.ry,i.dirX=t,i.dirY=e,t===i.parent.dirX&&e===i.parent.dirY||(s+=.2)),s}}),g=p.find(this.getNodeId(e,i),this.getNodeId(r,s)).map(e=>({tile:e.data.tile,onBridge:e.data.onBridge}));return(g.length<2||o&&g.length&&(!n&&g[0].tile!==r||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(Kt).forEach(e=>{e=Number(e);isNaN(e)||e===Kt.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=Qh()({multigraph:!0}),this.passabilityGraphs.set(t,i),this.tiles.forEach(e=>{this.computePassability(e,t,i)});return i}updatePassability(e,t,i,r=[]){let s=new Set;e.forEach(e=>{[e,this.tiles.getNeighbourTile(e,Sa.Right),this.tiles.getNeighbourTile(e,Sa.BottomRight),this.tiles.getNeighbourTile(e,Sa.Bottom),this.tiles.getNeighbourTile(e,Sa.BottomLeft)].filter(ga).forEach(e=>s.add(e))}),e.forEach(e=>{i.removeNode(this.getNodeId(e,!1)),i.removeNode(this.getNodeId(e,!0))}),s.forEach(e=>{this.computePassability(e,t,i,r)})}computePassability(e,t,i,r=[]){var s=[Sa.Left,Sa.TopLeft,Sa.Top,Sa.TopRight];let a=this.getPassableSpeed(e,t,!1,r);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 s)this.connectTiles(e,void 0,n,t,i,r)}var h=this.tileOccupation.getBridgeOnTile(e);if(h&&(a=this.getPassableSpeed(e,t,!0,r),a)){var l,o=this.getNodeId(e,!0);i.hasNode(o)||i.addNode(o,{speed:a,tile:e,onBridge:h});for(l of s)this.connectTiles(e,h,l,t,i,r)}}connectTiles(t,i,r,s,a,n=[]){var o=this.tiles.getNeighbourTile(t,r);if(o){let e=this.tileOccupation.getBridgeOnTile(o);r=i||e?0:1;if(Math.abs(t.z+(i?.tileElevation??0)-(o.z+(e?.tileElevation??0)))>r){if(!e?.isHighBridge()&&!i?.isHighBridge()||0!==Math.abs(t.z-o.z)||!a.hasNode(this.getNodeId(t,!1)))return;i=e=void 0}s=this.getPassableSpeed(o,s,!!e,n);s&&(n=this.getNodeId(o,!!e),a.hasNode(n)||a.addNode(n,{speed:s,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,r=[],s=!1){if(!this.mapBounds.isWithinBounds(e))return 0;let a=i?e.onBridgeLandType:e.landType;if(void 0===a)return 0;a===Yt.Wall&&t===Kt.Track&&(a=Wi(e.terrainType));let n=this.rules.getLandRules(a);var o,h=n.getSpeedModifier(t);if(!h)return 0;if(!s)for(o of this.tileOccupation.getObjectsOnTile(e))if(this.isBlockerObject(o,e,i,t)&&!r.includes(o))return 0;return h}isBlockerObject(t,i,e,r){if(t.isTerrain()&&r===Kt.Foot&&t.rules.getOccupationBits(this.theaterType)!==Zi.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 s=t.art.foundation;let e=t.rules.numberImpassableRows;return r===Kt.Foot?e=s.width:t.rules.weaponsFactory&&!e&&(e=s.width-1),zr({x:t.tile.rx,y:t.tile.ry,width:(e||s.width)-1,height:s.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())||r===Kt.Track&&t.rules.crushable)}findObstacles(t,e){var i,r,s=e.rules.speedType;let a=[];for(i of this.tileOccupation.getGroundObjectsOnTile(t.tile))i!==e&&(((r=this.isBlockerObject(i,t.tile,!!t.onBridge,s))||i.isUnit()&&(i.tile===t.tile&&i.onBridge===!!t.onBridge||i.moveTrait.reservedPathNodes.find(e=>e.tile===t.tile&&!!e.onBridge==!!t.onBridge))||s===Kt.Track&&i.rules.crushable||s===Kt.Foot&&i.isTerrain()||i.isBuilding()&&i.rules.gate)&&(r={obj:i,static:r},i.isInfantry()&&e.isInfantry()?i.position.desiredSubCell===e.position.desiredSubCell&&a.push(r):i.isTerrain()&&e.isInfantry()&&!i.rules.getOccupiedSubCells(this.theaterType).includes(e.position.desiredSubCell)||a.push(r)));return a}dispose(){this.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate),this.mapBounds.onLocalResize.unsubscribe(this.handleMapBoundsResize)}}class Kh{constructor(){this.mapCutoffHeight=0,this.mapBuildableSize={x:0,y:0,width:0,height:0},this.screenBounds={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 Pn}get onLocalResize(){return this._onLocalResize.asEvent()}fromMapFile(e,t){return 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/gr.ISO_TILE_SIZE,height:2*(e.fullSize.height-1)-1/gr.ISO_TILE_SIZE},this.mapCutoffHeight=t.getCutoffTileHeight(),this.updateRawLocalSize(e.localSize),this}updateRawLocalSize(e){var t,i;this.rawLocalSize.width&&this.rawLocalSize.height&&!function(e,t){let i=new Ur.Box2(new Ur.Vector2(e.x,e.y),new Ur.Vector2(e.x+e.width,e.y+e.height));return t=new Ur.Box2(new Ur.Vector2(t.x,t.y),new Ur.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.screenBounds=this.computeScreenBounds(this.localSize),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}}computeScreenBounds(e){var t=gr.screenTileToScreen(e.x,e.y),e=gr.screenTileToScreen(e.x+e.width,e.y+e.height-1);return{x:t.x,y:t.y,width:e.x-t.x,height:e.y-t.y}}getLocalSize(){return this.localSize}getRawLocalSize(){return this.rawLocalSize}getFullSize(){return this.fullSize}getClampedFullSize(){return this.clampedFullSize}getScreenBounds(){return this.screenBounds}isWithinBounds(e){return zr(this.mapBuildableSize,{x:e.dx,y:e.dy-e.z})}clampWithinBounds(e){let{x:t,y:i}=function(e,t){let i=new Ur.Box2(new Ur.Vector2(e.x,e.y),new Ur.Vector2(e.x+e.width,e.y+e.height));return i.clampPoint(new Ur.Vector2(t.x,t.y),new Ur.Vector2)}(this.mapBuildableSize,{x:e.dx,y:e.dy-e.z});return i+=e.z,i+=t%2-i%2,i>this.mapBuildableSize.y+this.mapBuildableSize.height&&(i-=2),{dx:t,dy:i}}isWithinHardBounds(e){var t=e.x/gr.ISO_TILE_SIZE,i=(e.z??e.y)/gr.ISO_TILE_SIZE,e=t-i+this.fullSize.width/2-1,i=t+i-this.fullSize.width/2-1;return zr(this.clampedFullSize,{x:++e,y:++i})}}class Jh{constructor(e,t,i,r,s,a,n,o=()=>!0){this.tiles=e,this.mapBounds=t,this.startTile=i,this.maxDistance=s,this.dirX=a,this.dirY=n,this.predicate=o,this.finished=!1,this.distance=r}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}}}var el,tl=__webpack_require__(949);(s=el=el||{})[s.None=0]="None",s[s.Start=1]="Start",s[s.End=2]="End";class il{constructor(e,t,i,r,s){this.tileSets=e,this.tiles=t,this.tileOccupation=i,this.mapBounds=r,this.rules=s,this.pieces=new Set,this.piecesByTile=new Map,this.handleTileOccupationUpdate=({object:t,type:i})=>{if(t.isOverlay()&&t.isBridge()){var r=t.tile;let e=this.piecesByTile.get(r);if("added"===i){if(e)throw new Error(`A bridge piece already exists at tile (${r.rx},${r.ry})`);var s=this.findBridgeAdjacentTiles(t);e={obj:t,prev:void 0,next:void 0,headType:this.computeHead(t,s.prev,s.next)},this.piecesByTile.set(r,e),this.pieces.add(e),this.connectPiece(e,s.prev,s.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 (${r.rx},${r.ry})`);t=e.prev,s=e.next;this.disconnectPiece(e),this.piecesByTile.delete(r),this.pieces.delete(e),t&&this.updateOverlayData(t),s&&this.updateOverlayData(s)}}},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=[],r=!1,e=t.next;if(t.headType===el.None||e)for(;e;){if(i.push(e),e.headType!==el.None){r=!0;break}e=e.next}else r=!0;if(r){r=!1,i.length=0;let e=t.prev;if(t.headType===el.None||e)for(;e;){if(i.push(e),e.headType!==el.None){r=!0;break}e=e.prev}else r=!0;if(r)return[]}return i}findBridgeAdjacentTiles(e){var t=e.isXBridge(),t=new tl.Vector2(Number(t),Number(!t));let i=new tl.Vector2(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 r=e.tile;if(e.isHighBridge()){r=r.z+e.tileElevation;return t?.z===r?el.Start:i?.z===r?el.End:el.None}return Ca.isLowBridgeHead(e.overlayId)?Ca.isLowBridgeHeadStart(e.overlayId)?el.Start:el.End:el.None}updateOverlayData(t){let i=t.obj,r=t.prev,s=t.next,a=!1;var n=i.isXBridge(),o=Ca.getOverlayBridgeType(i.overlayId);if(Ca.isLowBridgeHead(i.overlayId)){let e=0;Ca.isLowBridgeHeadStart(i.overlayId)?(e=n?20:22,s||e++):(e=n?18:24,r||e++),i.overlayId=(o===Ta.Wood?Ca.minLowBridgeWoodId:Ca.minLowBridgeConcreteId)+e,i.value=e,a=!0}else{let e;var h,l=(i.healthTrait?.health??100)<=50;e=t.headType!==el.None?t.headType===el.Start?s?l?6:(s.obj.healthTrait?.health??100)<=50?5:0:n?8:7:r?l?6:(r.obj.healthTrait?.health??100)<=50?4:0:n?7:8:(n||(h=r,r=s,s=h),r||s?r?s?(t=(r.obj.healthTrait?.health??100)<=50,h=(s.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===Ta.Wood?Ca.minLowBridgeWoodId:Ca.minLowBridgeConcreteId)+e,i.value=e,a=!0)}a&&(i.name=this.rules.getOverlayName(i.overlayId))}findClosestBridgeSpec(i){let e=new Pr(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===el.None)||!!this.tileSets.isHighBridgeBoundaryTile(e.tileNum)});var o=e.getNextTile();if(o){let r,t,s,a;var h=!this.tileOccupation.getBridgeOnTile(o);let e;if(h){var l=this.findHighBridgeBoundary(o);if(!l)return;r=l.tile,t=Ta.Concrete,this.tileSets.getSetNum(o.tileNum)===this.tileSets.getGeneralValue("WoodBridgeSet")&&(t=Ta.Wood),s=l.headType===k.TopLeft||l.headType===k.BottomRight,a=l.headType===k.TopLeft||l.headType===k.TopRight,e=l.headType}else{r=this.tileOccupation.getBridgeOnTile(o).tile;let e=this.getPieceAtTile(r);if(!e)throw new Error("Bridge head is not defined");var c=Ca.getOverlayBridgeType(e.obj.overlayId);if(c===Ta.NotBridge)throw new Error("Expected a bridge type");t=c,s=e.obj.isXBridge(),a=e.headType===el.Start}var u=Number(s)*(a?1:-1),d=Number(!s)*(a?1:-1);let n;if(h){o=new Jh(this.tiles,this.mapBounds,r,1,100,u,d,e=>e.z===r.z&&this.tileSets.isHighBridgeBoundaryTile(e.tileNum)).getNextTile(),c=this.tileSets.getSetNum(r.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=r.rx,g=r.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()!==s)return;e?.headType===(a?el.End:el.Start)&&(t=e),i++}n=t.obj.tile}return{start:a?r:n,end:a?n:r,type:t,isHigh:h}}}findHighBridgeBoundary(s){var a,e=this.tileSets.getTile(s.tileNum),n=this.tileSets.getHighBridgeHeadType(e.index);if(void 0!==n){let i=0,r=0;switch(n){case k.TopLeft:i=1,r=0;break;case k.BottomRight:i=-1,r=0;break;case k.TopRight:i=0,r=1;break;case k.BottomLeft:i=0,r=-1;break;case k.MiddleTlBr:i=1,r=0;break;case k.MiddleTrBl:i=0,r=1;break;default:throw new Error(`Unhandled head type "${n}"`)}let e=new Pr(this.tiles,this.mapBounds,s,{width:1,height:1},0,5,e=>e.terrainType===Xt.Pavement&&e.z>=s.z&&e.tileNum===s.tileNum),t=[];for(;a=e.getNextTile();)t.push(a);if(t.sort((e,t)=>100*(i?i*(t.rx-e.rx):r*(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}" @ ${s.rx},${s.ry}`)}canBeRepaired(i){let e=this.createBridgePieceTileFinder(i,e=>!(this.getPieceAtTile(e)||this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===i.start.z)),r=!1,s;for(var a=i.start.rx!==i.end.rx?Sa.BottomLeft:Sa.BottomRight;s=e.getNextTile();){r=!0;let e=this.tiles.getNeighbourTile(s,a),t=this.tiles.getNeighbourTile(e,a);if(i.isHigh){if([s,e,t].find(e=>this.tileOccupation.getGroundObjectsOnTile(e).some(e=>e.isBuilding()&&!e.rules.invisibleInGame)))return!1}else if([s,e,t].find(e=>this.tileOccupation.getGroundObjectsOnTile(e).some(e=>!(e.isUnit()||e.isSmudge()||e.isOverlay()&&e.isBridgePlaceholder()))))return!1}return r}getPieceTiles(e){var t=e.obj.tile,i=e.obj.isXBridge()?Sa.BottomLeft:Sa.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 r=this.findHighBridgeBoundary(e);r&&i.add(r.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,r=e.start.rx!==e.end.rx?Sa.BottomLeft:Sa.BottomRight;for(i of this.findNonBuildablePieceTiles(e)){var s=this.tiles.getNeighbourTile(i,r),a=this.tiles.getNeighbourTile(s,r);t.push(i,s,a)}return t}findBridgePieces(e){let t=this.createBridgePieceTileFinder(e,e=>!!this.getPieceAtTile(e)),i=[];for(var r;r=t.getNextTile();)i.push(this.getPieceAtTile(r));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 r;r=e.getNextTile();)i.push(r);return i}findNonBuildablePieceTiles(t){let e=this.createBridgePieceTileFinder(t,e=>!(this.tileSets.isHighBridgeMiddleTile(e.tileNum)&&e.z===t.start.z)),i=[];for(var r;r=e.getNextTile();)i.push(r);return i}createBridgePieceTileFinder(e,t){var i=e.start.rx!==e.end.rx;return new Jh(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 rl=new(__webpack_require__(949).Vector2);class sl{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 r of this.regions)if(r.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 r of this.objects)e.containsPoint(r.key)&&t.push(r.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},r=this.generateRegions(),s=this.objects;this.objects=[],this.regions=[];for(t of r){let e=new sl(t,i);e.parentMap=this.parentMap,this.regions.push(e),e.parent=this}for(e of s)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 r=this.box.getCenter(rl);let s=i[0],a=s.clone();s.max.x=r.x,a.min.x=r.x,i.push(a);for(let e=0,t=i.length;e<t;e++)s=i[e],a=s.clone(),s.max.y=r.y,a.min.y=r.y,i.push(a);return i}}var al=__webpack_require__(949);class nl{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 r=[];var s=e.getFoundation();for(let t=1;t<=i;t++)for(let e=0;e<s.width;e++)r.push(new al.Vector2(e-t,-t));for(let t=1;t<=i;t++)for(let e=1;e<s.height;e++)r.push(new al.Vector2(-t,e-t));r.push(...e.art.addOccupy);for(let{x:t,y:i}of e.art.removeOccupy){var a=r.findIndex(e=>e.x===t&&e.y===i);-1!==a&&r.splice(a,1)}var n,o,h=e.tile;let l=[];for({x:n,y:o}of r){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 ol{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 r=u.getNeighbourTile(t,Sa.TopRight),s=u.getNeighbourTile(t,Sa.BottomRight),a=u.getNeighbourTile(t,Sa.BottomLeft),n=u.getNeighbourTile(t,Sa.TopLeft);r&&d.canConnectTiles(i,p.get(r))&&(e+=1),s&&d.canConnectTiles(i,p.get(s))&&(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,Sa.TopRight),h=u.getNeighbourTile(t,Sa.BottomRight),l=u.getNeighbourTile(t,Sa.BottomLeft),c=u.getNeighbourTile(t,Sa.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))}})}}var hl,ll,cl,ul,dl,pl,gl,ml,fl,yl=__webpack_require__(949);class wl{constructor(e,t,i){this.mapFile=e,this.tiles=new Ea(this.mapFile.tiles,t,i.general),this.mapBounds=(new Kh).fromMapFile(this.mapFile,this.tiles),this.tileOccupation=new Hn(this.tiles),this.tileOcclusion=new nl(this.tiles),this.terrain=new Yh(this.tiles,this.mapFile.theaterType,this.mapBounds,this.tileOccupation,i),this.bridges=new il(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))}i=this.tiles.getMapSize();this.technosByTile=new sl(new yl.Box2(new yl.Vector2(0,0),new yl.Vector2(i.width,i.height)),{getKey:e=>{e=e.isBuilding()?e.centerTile:e.tile;return new yl.Vector2(e.rx,e.ry)},maxDepth:Math.ceil(Math.log2(Math.max(i.width,i.height)/5)),splitThreshold:10,joinThreshold:5}),this.mapFile.theaterType!==I.Snow&&ol.calculate(this.tiles,t)}get startingLocations(){return this.mapFile.startingLocations}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){e=this.mapBounds.clampWithinBounds(e);let t=this.tiles.getByDisplayCoords(e.dx,e.dy);if(!t)throw new Error("Clamped tile not found by display coords");for(;!this.mapBounds.isWithinBounds(t);)if(t=this.tiles.getNeighbourTile(t,Sa.Bottom),!t)throw new Error("Unexpected missing neighbour for clamped tile");return t}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 Tl{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}}(s=hl=hl||{})[s.Requested=0]="Requested",s[s.Formed=1]="Formed";class bl{constructor(e){this.playerList=e,this.alliances=[]}findByPlayers(e,t){let i=new Tl(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,hl.Requested)}}cancelRequest(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==hl.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!==hl.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=hl.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 r;if(r=this.findByPlayers(e,t))throw new Error(`An alliance already exists between players ${e.name} and ${t.name}`);return r={players:new Tl(e,t),status:i},this.alliances.push(r),r}breakAlliance(e,t){var i=this.findByPlayers(e,t);if(!i||i.status!==hl.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===hl.Formed}getAllies(t){return this.filterByPlayer(t).filter(e=>e.status===hl.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 r=new Tl(t,i);return!!e.filter(e=>!e.equals(r)).length}getHostilePlayers(){var i,r=this.playerList.getCombatants();let s=[];for(let t=0;t<r.length;t++)for(let e=t+1;e<r.length;e++)this.getAllies(r[t]).includes(r[e])||(i=new Tl(r[t],r[e]),s.push(i));return s}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 vl{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===qt.Civilian)}getAll(){return this.players}}(s=ll=ll||{})[s.None=0]="None",s[s.Hover=1]="Hover",s[s.Selected=2]="Selected",s[s.SelectedHover=3]="SelectedHover";class Sl{constructor(e){this.selectionLevel=ll.None,e.isBuilding()&&e.rules.wall?this.maxSelectionLevel=ll.None:this.maxSelectionLevel=e.rules.selectable?ll.Selected|ll.Hover:ll.Hover}getSelectionLevel(){return this.selectionLevel}setSelectionLevel(e){this.selectionLevel=Math.min(this.maxSelectionLevel,e)}setHover(e){this.setSelectionLevel(e?this.selectionLevel|ll.Hover:this.selectionLevel&~ll.Hover)}setSelected(e){this.setSelectionLevel(e?this.selectionLevel|ll.Selected:this.selectionLevel&~ll.Selected)}isHovered(){return this.selectionLevel>>ll.Hover&1}isSelected(){return this.selectionLevel>=ll.Selected}getControlGroupNumber(){return this.controlGroupNumber}setControlGroupNumber(e){this.controlGroupNumber=e}}class _l{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 Sl(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 r=this.groups.get(e);r||(r=new Set,this.groups.set(e,r)),i&&([...r.values()].forEach(e=>this.selectionModelsByUnit.get(e)?.setControlGroupNumber(void 0)),r.clear());for(var s of t)r.add(s),this.getOrCreateSelectionModel(s).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 kl{constructor(e){this._onChange=new Pn,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 Ol{constructor(e,t=void 0,i=0,r=new j(255,0,0)){this.name=e,this.country=t,this.startLocation=i,this.color=r,this.isAi=!1,this.defeated=!1,this.resigned=!1,this.objectsByType=new Map,this.objectsById=new Map,this.traits=new ia,this.credits=0,this.kills=0,this.score=0,this.unitsLost=0,this.unitsBuilt=0,this.cheerCooldownTicks=0,this.isObserver=!t,this.isNeutral=!!t&&!t.isPlayable()}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(Ct.Building)}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 Il{constructor(){this.disabled=!0,this.activeEvents=[]}isDisabled(){return this.disabled}setDisabled(e){this.disabled=e}}const Al=(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 Cl{constructor(e,t,i,r,s){this.player=e,this.maxTechLevel=t,this.gameOpts=i,this.rules=r,this.allAvailableObjects=s,this.buildSpeedModifier=1,this.queues=new Map,this._onQueueUpdate=new Pn,this.primaryFactories=new Map,this.factoryCounts=new Map,this.veteranTypes=new Set,this.stolenTech=new Set}static factory(e,t,i,r){let s=new Cl(e,t.mpDialogSettings.techLevel,i,t,r);t=t.general.maximumQueuedObjects+1;return s.addQueue(yn.Structures,new Nn(yn.Structures,1,1)),s.addQueue(yn.Armory,new Nn(yn.Armory,1,1)),s.addQueue(yn.Infantry,new Nn(yn.Infantry,t,t)),s.addQueue(yn.Vehicles,new Nn(yn.Vehicles,t,t)),s.addQueue(yn.Ships,new Nn(yn.Ships,t,t)),s.addQueue(yn.Aircrafts,new Nn(yn.Aircrafts,0,t)),s}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 ${yn[e]}`);return t}getAllQueues(){return[...this.queues.values()]}getQueueTypeForObject(e){if(e.type===Ct.Building)return e.buildCat===$i.Combat?yn.Armory:yn.Structures;if(e.type===Ct.Infantry)return yn.Infantry;if(e.type===Ct.Vehicle)return e.naval?yn.Ships:yn.Vehicles;if(e.type===Ct.Aircraft)return yn.Aircrafts;throw new Error(`Unsupported object type ${Ct[e.type]}`)}getQueueForObject(e){return this.getQueue(this.getQueueTypeForObject(e))}getQueueTypeForFactory(e){if(e===qi.InfantryType)return yn.Infantry;if(e===qi.UnitType)return yn.Vehicles;if(e===qi.AircraftType)return yn.Aircrafts;if(e===qi.NavalUnitType)return yn.Ships;throw new Error(`Unsupported factory type ${qi[e]}`)}getFactoryTypeForQueueType(e){if(e===yn.Structures||e===yn.Armory)return qi.BuildingType;if(e===yn.Infantry)return qi.InfantryType;if(e===yn.Vehicles)return qi.UnitType;if(e===yn.Aircrafts)return qi.AircraftType;if(e===yn.Ships)return qi.NavalUnitType;throw new Error(`Unsupported queue type ${yn[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!==qi.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(qt.GDI):!e.requiresStolenSovietTech||this.stolenTech.has(qt.Nod)}getFactoryTypeFor(e){return e.type===Ct.Building?qi.BuildingType:e.type===Ct.Infantry?qi.InfantryType:e.type===Ct.Aircraft?qi.AircraftType:e.naval?qi.NavalUnitType:qi.UnitType}meetsPrerequisites(e){let t=[...this.player.buildings].map(e=>e.name);var i;for(i of e.prerequisite)if(i=i.toUpperCase(),Al.has(i)){var r=Al.get(i);if(void 0===r)throw new Error(`Unknown prereqName ${i}`);var s,a=this.rules.general.prereqCategories.get(r);if(void 0===a)throw new Error(`Missing prerequisite category ${r} in rules`);let e=!1;for(s of a)if(-1!==t.indexOf(s)){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 ${qi[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 Bl{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 El{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 xl{constructor(e,t,i){this.rules=e,this.gameOpts=t,this.allAvailableObjects=i}createCombatant(e,t,i,r,s,a){let n=new Ol(e,t,i,r);return n.isAi=s,n.aiDifficulty=a,n.powerTrait=new En(n),n.traits.add(n.powerTrait),n.radarTrait=new Il,n.traits.add(n.radarTrait),n.superWeaponsTrait=new Bl,n.traits.add(n.superWeaponsTrait),n.production=Cl.factory(n,this.rules,this.gameOpts,this.allAvailableObjects),n.sharedDetectDisguiseTrait=new El,n}createObserver(e,t){let i=new Ol(e,void 0,void 0,t.colors.get("LightGrey"));return i.radarTrait=new Il,i.traits.add(i.radarTrait),i.radarTrait.setDisabled(!1),i}createNeutral(e,t){var i=[...e.countryRules.values()].find(e=>e.side===qt.Civilian);if(!i)throw new Error("Missing neutral country. No country found in rules with Civilian side");i=new Sn(i);let r=new Ol(t,i,void 0,e.colors.get("LightGrey"));return r.powerTrait=new En(r),r.traits.add(r.powerTrait),r}}(cl=cl||{}).onSpawn=Symbol(),(ul=ul||{}).onUnspawn=Symbol(),(dl=dl||{}).onChange=Symbol();class Pl{[cl.onSpawn](e,t){e.isTechno()&&e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"add",t)}[ul.onUnspawn](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"remove",t)}[mh.onChange](e,t){e.isTechno()&&e.rules.power&&!e.warpedOutTrait.isActive()&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,"update",t)}[dl.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))}[kr.onChange](e,t,i){e.rules.power&&!this.isCapturablePower(e,e.owner)&&e.owner.powerTrait?.updateFrom(e,i?"remove":"add",t)}[_r.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 Nl{constructor(e){this.target=e,this.type=Xi.BuildingSell}}class Rl{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(Dn).forEach(e=>{e[Dn.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 Nl(e)),e.dispose()}computeRefundValue(e){let t=0;return 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 Dl{constructor(e,t){this.target=e,this.radarEnabled=t,this.type=Xi.RadarOnOff}}class Ml{constructor(e,t,i){this.target=e,this.radarEventType=t,this.tile=i,this.type=Xi.RadarEvent}}class Ll{constructor(){this.activeLightningStrikes=new Map}[cl.onSpawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[ul.onUnspawn](e,t){e.isBuilding()&&e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Ar.onPowerLow](e,t){this.updateRadarForPlayer(e,t)}[Ar.onPowerRestore](e,t){this.updateRadarForPlayer(e,t)}[Ar.onPowerChange](){}[dl.onChange](e,t,i){e.rules.radar&&(this.updateRadarForPlayer(t,i),this.updateRadarForPlayer(e.owner,i))}[kr.onChange](e,t){e.rules.radar&&this.updateRadarForPlayer(e.owner,t)}[Cr.onActivate](e,t,i){if(e===Qi.LightningStorm){this.activeLightningStrikes.set(t,(this.activeLightningStrikes.get(t)??0)+1);for(var r of i.getCombatants())r===t||i.alliances.areAllied(r,t)||this.updateRadarForPlayer(r,i)}}[Ga.onDeactivate](e,t,i){if(e===Qi.LightningStorm){e=(this.activeLightningStrikes.get(t)??0)-1;if(0<e?this.activeLightningStrikes.set(t,e):this.activeLightningStrikes.delete(t),e<=0)for(var r of i.getCombatants())this.updateRadarForPlayer(r,i)}}updateRadarForPlayer(i,r){var e,t;i.radarTrait&&(e=i.radarTrait?.isDisabled(),t=![...i.buildings].find(e=>e.rules.radar&&!e.warpedOutTrait.isActive())||i.powerTrait.level===fn.Low||[...this.activeLightningStrikes.entries()].some(([e,t])=>t&&e!==i&&!r.alliances.areAllied(e,i)),i.radarTrait.setDisabled(t),e!==t&&r.events.dispatch(new Dl(i,!t)))}[ba.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(r,e,s,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 br(a.map.tileOccupation);!!n.activeEvents.find(e=>e.type===r&&i.isInTileRange(s,e.tile,0,t.getEventSuppresionDistance(e.type)))||(n.activeEvents.push({startTick:a.currentTick,tile:s,type:r}),a.events.dispatch(new Ml(e,r,s)))}}}class Fl{constructor(e){this.target=e,this.type=Xi.InsufficientFunds}}class jl{constructor(e,t){this.rules=e,this.speedCheat=t,this.availableObjectRules=new Set;t=60*e.general.buildSpeed*xr.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)})}[_r.onTick](e){for(var t of e.getCombatants())for(var i of t.production.getAllQueues())this.tickQueue(i,t,e)}[cl.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===qi.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t)):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[ul.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===qi.AircraftType&&this.updateAircraftQueueMaxSize(e.owner,t))):e.isAircraft()&&e.owner.production&&this.rules.general.padAircraft.includes(e.name)&&this.updateAircraftQueueMaxSize(e.owner,t)}[dl.onChange](e,t,i){var r;e.isBuilding()?(this.ensurePrerequisites(t),(r=e.rules.factory)&&(t.production?.getPrimaryFactory(r)===e&&t.production.crownPrimaryFactoryHeir(r),e.owner.production&&!e.owner.production.getPrimaryFactory(r)&&e.owner.production.setPrimaryFactory(e),t.production?.decrementFactoryCount(r),e.owner.production?.incrementFactoryCount(r),r===qi.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))}[Ar.onPowerLow](e){e.production&&(e.production.buildSpeedModifier=this.computeLowPowerBuildSpeedModifier(e.powerTrait.power,e.powerTrait.drain))}[Ar.onPowerRestore](e){e.production&&(e.production.buildSpeedModifier=1)}[Ar.onPowerChange](e){e.powerTrait?.level===fn.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 U(1-.3*t.lowPowerPenaltyModifier*e/.15,t.minLowPowerProductionSpeed,t.maxLowPowerProductionSpeed)}updateAircraftQueueMaxSize(i,r){i.production&&r.afterTick(()=>{var e=[...i.buildings].filter(e=>e.helipadTrait).reduce((e,t)=>e+t.dockTrait.numberOfDocks,0),t=i.getOwnedObjectsByType(Ct.Aircraft,!0).filter(e=>r.rules.general.padAircraft.includes(e.name)).length;i.production.getQueueForFactory(qi.AircraftType).maxSize=Math.max(0,e-t)})}tickQueue(r,s,a){if(r.status===wn.Active){let e=!1,t=r.getFirst();var n=s.production.getFactoryTypeForQueueType(r.type),o=s.production.getFactoryCount(n),h=s.production.buildSpeedModifier,n=1/this.rules.general.multipleFactory**(o-1),o=t.rules.wall?1/this.rules.general.wallBuildSpeedCoefficient:1;let i=this.speedCheat.value?150:this.baseBuildSpeed*h*n*o;h=.06*60*xr.BASE_TICKS_PER_SECOND,n=t.creditsEach?t.creditsEach/i:h;n/(60*xr.BASE_TICKS_PER_SECOND)<.06&&(i=t.creditsEach/h);var l,o=s.credits,h=t.creditsEach-t.creditsSpent,h=Math.min(s.credits,i+t.creditsSpentLeftover,h);0<h?(l=Math.floor(h),t.creditsSpentLeftover=h-l,l&&(t.creditsSpent+=l,t.progress=t.creditsSpent/t.creditsEach,s.credits-=l,e=!0)):t.creditsEach||(l=t.progress*n,t.progress=Math.min(1,(1+l)/n),e=!0),e&&1===t.progress&&(r.status=wn.Ready),0<o&&!s.credits&&a.events.dispatch(new Fl(s)),e&&r.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]}}(pl=pl||{}).onChange=Symbol();class Wl{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 Ao).fromTiles(this.map.tiles);for(var r of t.getCombatants()){let e=i.clone();this.shroudByPlayer.set(r,e),this.revealObjects(e,r,t),e.update()}}[_r.onTick](e){for(var[t,i]of this.shroudByPlayer)t.defeated&&!t.isObserver?this.shroudByPlayer.delete(t):i.update()}[dl.onChange](e,t,i){if(e.isBuilding()&&e.rules.spySat&&(this.revealMap(e.owner,i),t.getOwnedObjectsByType(Ct.Building).find(e=>e.rules.spySat)||this.resetShroud(t,i)),e.isSpawned)for(var r of[e.owner,...i.alliances.getAllies(e.owner)])this.shroudByPlayer.get(r)?.revealFrom(e)}[pl.onChange](t,e,i){if(e){let e=this.getPlayerShroud(t.players.first);var r,s,t=i.alliances.getAllies(t.players.first).map(e=>this.getPlayerShroud(e)).filter(ga);for(r of t)e.merge(r);e.invalidateFull();for(s of t)s.copy(e),s.invalidateFull()}}[cl.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(Ll).addEventForPlayer(Zt.EnemyObjectSensed,i,e.centerTile,t))}e.gapGeneratorTrait&&this.gapGenerators.add(e)}}[ul.onUnspawn](e,t){e.isBuilding()&&(e.rules.spySat&&(e.owner.getOwnedObjectsByType(Ct.Building).find(e=>e.rules.spySat)||this.resetShroud(e.owner,t)),e.rules.revealToAll&&this.revealedToAll.delete(e),e.gapGeneratorTrait&&this.gapGenerators.delete(e))}[Ar.onPowerLow](e,t){this.updateGaps(t,e)}[Ar.onPowerRestore](e,t){this.updateGaps(t,e)}[Ar.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 r;for(r of[...e.getOwnedObjects(),...i.alliances.getAllies(e).map(e=>e.getOwnedObjects()).flat()])t.revealFrom(r);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,yo.Darken,!0)}dispose(){this.map.tileOccupation.onChange.unsubscribe(this.handleTileOccupationUpdate)}}class Ul extends Lr{onTick(e){return!(e.buildStatus!==No.BuildDown&&(e.buildStatus=No.BuildDown,!e.rules.wall))||(this.children.push(new Ss(.035)),!1)}}class Vl{constructor(e,t,i,r,s,a){this.player=e,this.production=t,this.rules=i,this.art=r,this.map=s,this.game=a}getAdjacentRect(e,t,i){return{x:e.x-i,y:e.y-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():[]]){var r={x:t.tile.rx,y:t.tile.ry},s=this.rules.getBuilding(t.name),a=this.art.getObject(t.name,Ct.Building).foundation;s.baseNormal&&i.push(this.getAdjacentRect(r,a,e))}return i}meetsAdjacency(e,t){var i,r,s;for(i of this.getAdjacencyMap(t))if(r=e,s=i,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;return!1}canBuild(e){return this.production.isAvailableForProduction(this.rules.getBuilding(e))}canBuildAt(e,t,i,r=!1){var s=this.rules.getBuilding(e),a=this.art.getObject(e,Ct.Building);let n=[];var o=a.foundation,h=r?t:this.normalizePlacementTileCoords(e,t);let l=!0;t={x:h.rx,y:h.ry,width:o.width,height:o.height};s.constructionYard||this.meetsAdjacency(t,s.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:!(!this.map.isWithinBounds(u)||!l)&&(this.isTileBuildable(u,s,i)&&!this.game.mapShroudTrait.getPlayerShroud(this.player)?.isShrouded(u))})}if(s.wall&&n[0].buildable){let e=this.getWallConnectingTiles(h,s);e.forEach(e=>{n.push({rx:e.rx,ry:e.ry,buildable:!0})})}return n}placeAt(e,t,i=!1){let r=[],s=this.rules.getBuilding(e),a=i?t:this.normalizePlacementTile(e,t);if(s.wall){let t=[[a,s]],e=this.getWallConnectingTiles(a,s);e.forEach(e=>{e!==a&&t.push([e,s])});for(var n of t)r.push(this.executePlacement(n[0],n[1]));e.forEach(e=>{e=this.map.getObjectsOnTile(e).find(e=>e.isBuilding()&&e.name===s.name&&e.owner===this.player);this.connectWall(e)})}else{var o,t=this.executePlacement(a,s);r.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 r}normalizePlacementTileCoords(e,t){e=this.art.getObject(e,Ct.Building).foundationCenter;return{rx:t.rx-e.x,ry:t.ry-e.y}}normalizePlacementTile(e,t){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 ma(new Ul,new _s(()=>{this.game.unspawnObject(e),e.rules.wall&&this.updateAdjacentWalls(e),t()})).setCancellable(!1))}executePlacement(e,t){let i=this.game.createObject(Ct.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,r){var s,a=r.guardRange+1;let n=[];for(s of[[0,1],[0,-1],[1,0],[-1,0]]){let t=[];for(let e=0;e<a;++e){var o={x:i.rx+s[0]*e,y:i.ry+s[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===r.name&&e.owner===this.player)){n=n.concat(t);break}if(!this.isTileBuildable(o,r))break;t.push(o)}}return n}getAdjacentBuildingData(e,t){var i;let r=[];for(i of[[0,1],[0,-1],[1,0],[-1,0]]){var s={x:e.rx+i[0],y:e.ry+i[1]},a=this.map.tiles.getByMapCoords(s.x,s.y);a&&((s=this.map.getObjectsOnTile(a).find(e=>e.isBuilding()&&e.name===t&&e.owner===this.player))&&r.push({direction:i,tile:a,building:s}))}return r}updateAdjacentWalls(t){let e=new Wn(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.getGroundObjectsOnTile(e).some(e=>!(i?.includes(e)||e.isBuilding()&&e.rules.invisibleInGame||e.isSmudge()))&&(t.waterBound?0<this.rules.getLandRules(e.landType).getSpeedModifier(Kt.Float):0===e.rampType&&this.rules.getLandRules(e.landType).buildable)}}class zl{static generate(e,t,i,r){var s,a=i.reduce((e,t)=>e+t.cost,0)/i.length*e;let n=[],o=a,h=(i=i.filter(e=>e.isAvailableTo(r)&&e.hasOwner(r))).filter(e=>t.includes(e.name));for(s of h){if(o<=0)break;var l=2/3/h.length,l=Math.ceil(l*a/s.cost);o-=l*s.cost,n.push({name:s.name,type:Ct.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:Ct.Infantry,count:d})}return n}}class Hl{constructor(){this.dispatcher=new Pn,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,r;return r="function"==typeof e?e:(i=e,t),void 0===i?(this.dispatcher.subscribe(r),()=>this.unsubscribe(r)):this.subscribeType(i,r)}unsubscribe(e,t){let i=void 0,r;r="function"==typeof e?e:(i=e,t),void 0===i?this.dispatcher.unsubscribe(r):this.unsubscribeType(i,r)}subscribeType(e,t){let i=this.dispatchersByType.get(e);return i||(i=new Pn,this.dispatchersByType.set(e,i)),i.subscribe(t),()=>this.unsubscribeType(e,t)}unsubscribeType(e,t){this.dispatchersByType.get(e)?.unsubscribe(t)}}class Gl{constructor(e,t,i){this.target=e,this.attackerInfo=t,this.incidental=i,this.type=Xi.ObjectDestroy}}class $l{constructor(e){this.target=e,this.type=Xi.PlayerDefeated}}(gl=gl||{}).onDestroy=Symbol();class ql{constructor(e,t){this.target=e,this.prevOwner=t,this.type=Xi.ObjectOwnerChange}}class Zl{constructor(e){this.gameObject=e,this.type=Xi.ObjectUnspawn}}class Ql{constructor(e){this.gameObject=e,this.type=Xi.ObjectSpawn}}class Xl{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}}(s=ml=ml||{})[s.NoAction=0]="NoAction",s[s.QuitGame=1]="QuitGame",s[s.ObserveGame=2]="ObserveGame",s[s.PlaceBuilding=3]="PlaceBuilding",s[s.SellBuilding=4]="SellBuilding",s[s.ToggleRepair=5]="ToggleRepair",s[s.SelectUnits=6]="SelectUnits",s[s.OrderUnits=7]="OrderUnits",s[s.UpdateQueue=8]="UpdateQueue",s[s.ToggleAlliance=9]="ToggleAlliance",s[s.ActivateSuperWeapon=10]="ActivateSuperWeapon",s[s.PingLocation=11]="PingLocation";class Yl{constructor(e){this.actionType=e}unserialize(e){}serialize(){return[]}print(){return""}}(s=fl=fl||{})[s.Add=0]="Add",s[s.Cancel=1]="Cancel",s[s.Pause=2]="Pause",s[s.Resume=3]="Resume";class Kl extends Yl{constructor(e){super(ml.UpdateQueue),this.game=e}unserialize(e){this.queueType=Number(e[0]),this.updateType=Number(e[1]),this.updateType!==fl.Add&&this.updateType!==fl.Cancel||(this.item=this.game.rules.getObject(e[2],Number(e[3])),this.quantity=Number(e[4]))}serialize(){let e=[""+this.queueType,""+this.updateType];return this.updateType!==fl.Add&&this.updateType!==fl.Cancel||e.push(""+this.item.name,""+this.item.type,""+this.quantity),e}print(){return this.updateType===fl.Resume?`Resume queue ${yn[this.queueType]}`:this.updateType===fl.Add?`Add to queue ${this.item.name} x ${this.quantity}`:this.updateType===fl.Pause?`Put queue ${yn[this.queueType]} on hold.`:this.updateType===fl.Cancel?`Cancel ${this.item.name} x ${this.quantity}`:`Unhandled queue update type ${this.updateType}`}process(){let t=this.game.getPlayerByName(this.playerName),i=this.item,r=t.production.getQueue(this.queueType);if(this.updateType===fl.Resume)r.status===wn.OnHold&&(r.status=wn.Active);else if(this.updateType===fl.Add){let e=r.find(i);var s;(r.status===wn.Active||r.status===wn.Idle||r.status===wn.OnHold&&e[0]!==r.getFirst()||r.status===wn.Ready&&i.type!==Ct.Building)&&(s=e.reduce((e,t)=>e+t.quantity,0),Number.isFinite(i.buildLimit)&&t.getOwnedObjectsByType(i.type,!0).filter(e=>e.name===i.name).length+s>=i.buildLimit||t.production.isAvailableForProduction(i)&&(a=Math.min(r.maxSize-r.currentSize,r.maxItemQuantity-s),0<(n=Math.min(this.quantity,a))&&r.push(i,n,i.cost)))}else if(this.updateType===fl.Cancel){if([wn.Ready,wn.OnHold,wn.Active].includes(r.status)){let e=r.find(i);var a,n;e.length&&(a=e.reduce((e,t)=>e+t.quantity,0),0<(n=Math.min(a,this.quantity))&&(r.pop(i,n),n===a&&(t.credits+=e[0].creditsSpent)))}}else this.updateType===fl.Pause&&r.status===wn.Active&&(r.status=wn.OnHold)}}var Jl=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},ec=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class tc{constructor(e,t,i,r){oc.add(this),rc.set(this,void 0),sc.set(this,void 0),ac.set(this,void 0),nc.set(this,void 0),Jl(this,rc,t,"f"),Jl(this,sc,i,"f"),Jl(this,ac,e,"f"),Jl(this,nc,r,"f")}placeBuilding(t,i,r){ec(this,oc,"m",hc).call(this,ml.PlaceBuilding,e=>{e.name=t,e.tile={x:i,y:r}})}sellBuilding(t){ec(this,oc,"m",hc).call(this,ml.SellBuilding,e=>{e.buildingId=t})}toggleRepairWrench(t){ec(this,oc,"m",hc).call(this,ml.ToggleRepair,e=>{e.buildingId=t})}toggleAlliance(t,i){ec(this,oc,"m",hc).call(this,ml.ToggleAlliance,e=>{e.toPlayerName=t,e.toggle=i})}pauseProduction(t){ec(this,oc,"m",hc).call(this,ml.UpdateQueue,e=>{e.queueType=t,e.updateType=fl.Pause})}resumeProduction(t){ec(this,oc,"m",hc).call(this,ml.UpdateQueue,e=>{e.queueType=t,e.updateType=fl.Resume})}queueForProduction(t,e,i,r){let s=ec(this,ac,"f").rules.getObject(e,i);ec(this,oc,"m",hc).call(this,ml.UpdateQueue,e=>{e.queueType=t,e.updateType=fl.Add,e.item=s,e.quantity=r})}unqueueFromProduction(t,e,i,r){let s=ec(this,ac,"f").rules.getObject(e,i);ec(this,oc,"m",hc).call(this,ml.UpdateQueue,e=>{e.queueType=t,e.updateType=fl.Cancel,e.item=s,e.quantity=r})}activateSuperWeapon(t,i,r){ec(this,oc,"m",hc).call(this,ml.ActivateSuperWeapon,e=>{e.superWeaponType=t,e.tile={x:i.rx,y:i.ry},e.tile2=r?{x:r.rx,y:r.ry}:void 0})}orderUnits(t,i,r,s,a){ec(this,oc,"m",hc).call(this,ml.SelectUnits,e=>{e.unitIds=t});let n;if(r){let e,t;if(s){e=void 0;var o=ec(this,ac,"f").map.tiles.getByMapCoords(r,s);if(!o)throw new Error(`No tile found at rx,ry=${r},${s}`);t=o,a&&(e=ec(this,ac,"f").map.tileOccupation.getBridgeOnTile(o))}else e=ec(this,ac,"f").getObjectById(r),t=e.tile;n=ec(this,ac,"f").createTarget(e,t)}ec(this,oc,"m",hc).call(this,ml.OrderUnits,e=>{e.orderType=i,e.target=n})}quitGame(){ec(this,oc,"m",hc).call(this,ml.QuitGame)}}var ic,rc=new WeakMap,sc=new WeakMap,ac=new WeakMap,nc=new WeakMap,oc=new WeakSet,hc=function(e,t){if(!ec(this,nc,"f"))throw new Error("Player name must be set before issuing any actions");let i=ec(this,rc,"f").create(e);i.playerName=ec(this,nc,"f"),t?.(i),ec(this,sc,"f").push(i)},lc=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},cc=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};(s=ic=ic||{})[s.ObjectOwnerChange=0]="ObjectOwnerChange",s[s.ObjectSpawn=1]="ObjectSpawn",s[s.ObjectUnspawn=2]="ObjectUnspawn",s[s.ObjectDestroy=3]="ObjectDestroy";class uc{constructor(e){gc.add(this),dc.set(this,void 0),pc.set(this,[]),lc(this,dc,e,"f")}subscribe(e,t){let i=void 0,r;r="function"==typeof e?e:(i=e,t);t=cc(this,dc,"f").subscribe(e=>{e=cc(this,gc,"m",mc).call(this,e);!e||void 0!==i&&i!==e.type||r(e)});return cc(this,pc,"f").push(t),t}dispose(){for(var e of cc(this,pc,"f"))e();cc(this,pc,"f").length=0}}var dc=new WeakMap,pc=new WeakMap,gc=new WeakSet,mc=function(t){switch(t.type){case Xi.ObjectOwnerChange:return{type:ic.ObjectOwnerChange,prevOwnerName:t.prevOwner.name,newOwnerName:t.target.owner.name,target:t.target.id};case Xi.ObjectSpawn:return{type:ic.ObjectSpawn,target:t.gameObject.id};case Xi.ObjectUnspawn:return{type:ic.ObjectUnspawn,target:t.gameObject.id};case Xi.ObjectDestroy:{let e=t;return e.target.isProjectile()?void 0:{type:ic.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}},fc=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},yc=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class wc{constructor(e){vc.add(this),Tc.set(this,void 0),bc.set(this,void 0),fc(this,Tc,e,"f"),fc(this,bc,e.map,"f")}getStartingLocations(){return yc(this,bc,"f").startingLocations}getTheaterType(){return yc(this,bc,"f").getTheaterType()}getTile(e,t){t=yc(this,bc,"f").tiles.getByMapCoords(e,t);if(t&&yc(this,bc,"f").mapBounds.isWithinBounds(t))return t}getTilesInRect(e,t){return yc(this,bc,"f").tiles.getInRectangle(e,t).filter(e=>yc(this,bc,"f").mapBounds.isWithinBounds(e))}getObjectsOnTile(e){return yc(this,bc,"f").getObjectsOnTile(e).map(e=>e.id)}hasBridgeOnTile(e){return!!e.onBridgeLandType}hasHighBridgeOnTile(e){return!!yc(this,bc,"f").tileOccupation.getBridgeOnTile(e)?.isHighBridge()}isPassableTile(e,t,i){return 0<yc(this,bc,"f").terrain.getPassableSpeed(e,t,i)}isVisibleTile(e,t){var i=yc(this,Tc,"f").getPlayerByName(t);if(!i)throw new Error(`Player "${t}" doesn't exist`);return!yc(this,Tc,"f").mapShroudTrait.getPlayerShroud(i)?.isShrouded(e)}getTileResourceData(e){e=yc(this,bc,"f").getObjectsOnTile(e).find(e=>e.isOverlay()&&e.isTiberium()||e.isTerrain()&&e.rules.spawnsTiberium);return e?yc(this,vc,"m",Sc).call(this,e):void 0}getAllTilesResourceData(){var e;let t=[];for(e of yc(this,Tc,"f").getWorld().getAllObjects()){var i=yc(this,vc,"m",Sc).call(this,e);i&&t.push(i)}return t}}var Tc=new WeakMap,bc=new WeakMap,vc=new WeakSet,Sc=function(t){let i;if(t.isOverlay()&&t.isTiberium()){let e=t.traits.get(Pa);var r=e.getTiberiumType(),s=e.getBailCount();i={tile:t.tile,ore:r===ka.Ore?s:0,gems:r===ka.Gems?s:0,spawnsOre:!1}}else t.isTerrain()&&t.rules.spawnsTiberium&&(i={tile:t.tile,ore:0,gems:0,spawnsOre:!0});return i},_c=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},kc=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class Oc{constructor(e){Ic.set(this,void 0),_c(this,Ic,e,"f")}get allObjectRules(){return kc(this,Ic,"f").allObjectRules}get buildingRules(){return kc(this,Ic,"f").buildingRules}get infantryRules(){return kc(this,Ic,"f").infantryRules}get vehicleRules(){return kc(this,Ic,"f").vehicleRules}get aircraftRules(){return kc(this,Ic,"f").aircraftRules}get terrainRules(){return kc(this,Ic,"f").terrainRules}get overlayRules(){return kc(this,Ic,"f").overlayRules}get countryRules(){return kc(this,Ic,"f").countryRules}get general(){return kc(this,Ic,"f").general}get ai(){return kc(this,Ic,"f").ai}get crateRules(){return kc(this,Ic,"f").crateRules}get combatDamage(){return kc(this,Ic,"f").combatDamage}get radiation(){return kc(this,Ic,"f").radiation}hasObject(e,t){return kc(this,Ic,"f").hasObject(e,t)}getObject(e,t){return kc(this,Ic,"f").getObject(e,t)}getBuilding(e){return kc(this,Ic,"f").getBuilding(e)}getWeapon(e){return kc(this,Ic,"f").getWeapon(e)}getWarhead(e){return kc(this,Ic,"f").getWarhead(e)}getProjectile(e){return kc(this,Ic,"f").getProjectile(e)}getOverlayName(e){return kc(this,Ic,"f").getOverlayName(e)}getOverlayId(e){return kc(this,Ic,"f").getOverlayId(e)}getOverlay(e){return kc(this,Ic,"f").getOverlay(e)}getCountry(e){return kc(this,Ic,"f").getCountry(e)}getMultiplayerCountries(){return kc(this,Ic,"f").getMultiplayerCountries()}getIni(){return kc(this,Ic,"f").getIni()}}var Ic=new WeakMap,Ac=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},Cc=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class Bc{constructor(e,t){Dc.add(this),Nc.set(this,void 0),Rc.set(this,void 0),Ac(this,Nc,e,"f"),Ac(this,Rc,t,"f"),this.mapApi=new wc(e),this.rulesApi=new Oc(e.rules)}isPlayerDefeated(e){return Cc(this,Nc,"f").getPlayerByName(e).defeated}areAlliedPlayers(e,t){var i=Cc(this,Nc,"f").getPlayerByName(e);if(!i)throw new Error(`Player "${e}" doesn't exist`);e=Cc(this,Nc,"f").getPlayerByName(t);if(!e)throw new Error(`Player "${t}" doesn't exist`);return Cc(this,Nc,"f").alliances.areAllied(i,e)}canPlaceBuilding(e,t,i){var r=Cc(this,Nc,"f").getPlayerByName(e);if(!r)throw new Error(`Player "${e}" doesn't exist`);let s=Cc(this,Nc,"f").getConstructionWorker(r).canBuildAt(t,i,void 0,!0);return!s.some(e=>!e.buildable)}getBuildingPlacementData(e){e=Cc(this,Nc,"f").art.getObject(e,Ct.Building);return{foundation:e.foundation,foundationCenter:e.foundationCenter}}getPlayers(){return Cc(this,Nc,"f").getNonNeutralPlayers().map(e=>e.name)}getPlayerData(e){let t=Cc(this,Nc,"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===fn.Low},radarDisabled:!!t.radarTrait?.isDisabled()}}getAllTerrainObjects(){return Cc(this,Nc,"f").getWorld().getAllObjects().filter(e=>e.isTerrain()).map(e=>e.id)}getAllUnits(){return Cc(this,Nc,"f").getWorld().getAllObjects().filter(e=>e.isTechno()).map(e=>e.id)}getVisibleUnits(e,t,i=()=>!0){const r=Cc(this,Nc,"f").getPlayerByName(e);if(!r)throw new Error(`Player "${e}" doesn't exist`);if("self"===t)return r.getOwnedObjects().filter(e=>i(e.rules)).map(e=>e.id);let s;if("allied"===t)s=e=>e.owner===r||Cc(this,Nc,"f").alliances.areAllied(e.owner,r);else{if("hostile"!==t)throw new Error(`Unexpected type ${t}`);{let t=Cc(this,Nc,"f").mapShroudTrait.getPlayerShroud(r);s=e=>!t?.isShrouded(e.tile)&&e.owner!==r&&!Cc(this,Nc,"f").alliances.areAllied(e.owner,r)}}return Cc(this,Nc,"f").getWorld().getAllObjects().filter(e=>e.isTechno()&&s(e)&&i(e.rules)).map(e=>e.id)}getGameObjectData(t){if(Cc(this,Nc,"f").getWorld().hasObjectId(t)){let e=Cc(this,Nc,"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}}}getUnitData(t){var i=this.getGameObjectData(t);if(i){let e=Cc(this,Nc,"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?Cc(this,Dc,"m",Mc).call(this,e.primaryWeapon):void 0,secondaryWeapon:e.secondaryWeapon?Cc(this,Dc,"m",Mc).call(this,e.secondaryWeapon):void 0,deathWeapon:e.armedTrait?.deathWeapon?Cc(this,Dc,"m",Mc).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(),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,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 Cc(this,Nc,"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 Cc(this,Nc,"f").rules.general}getRulesIni(){return Cc(this,Nc,"f").rules.getIni()}getArtIni(){return Cc(this,Nc,"f").art.getIni()}generateRandomInt(e,t){if(Cc(this,Rc,"f"))return Cc(this,Nc,"f").generateRandomInt(e,t);var i=this.generateRandom();return Math.round(i*(t-e))+e}generateRandom(){return Cc(this,Rc,"f")?Cc(this,Nc,"f").generateRandom():Math.random()}getTickRate(){return Cc(this,Nc,"f").speed.value*xr.BASE_TICKS_PER_SECOND}getCurrentTick(){return Cc(this,Nc,"f").currentTick}}var Ec,xc,Pc,Nc=new WeakMap,Rc=new WeakMap,Dc=new WeakSet,Mc=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()}},Lc=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},Fc=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class jc{constructor(e){Ec.set(this,void 0),Lc(this,Ec,e,"f")}isAvailableForProduction(e){return Fc(this,Ec,"f").isAvailableForProduction(e)}getAvailableObjects(t){let e=Fc(this,Ec,"f").getAvailableObjects();return void 0!==t&&(e=e.filter(e=>this.getQueueTypeForObject(e)===t)),e}getQueueTypeForObject(e){return Fc(this,Ec,"f").getQueueTypeForObject(e)}getQueueData(e){let t=Fc(this,Ec,"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}))}}}Ec=new WeakMap;class Wc{constructor(e,t){this.name=e,this.country=t}setGameApi(e){this.gameApi=e}setActionsApi(e){this.actionsApi=e}setProductionApi(e){this.productionApi=e}onGameStart(e){}onGameTick(e){}onGameEvent(e,t){}}(s=xc=xc||{})[s.Initial=0]="Initial",s[s.Deployed=1]="Deployed",s[s.Attacking=2]="Attacking",s[s.Defeated=3]="Defeated";class Uc extends Wc{constructor(){super(...arguments),this.botState=xc.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 xc.Initial:{const i=e.getGeneralRules().baseUnit;if(e.getVisibleUnits(this.name,"self",e=>e.constructionYard).length){this.botState=xc.Deployed;break}var t=e.getVisibleUnits(this.name,"self",e=>i.includes(e.name));t.length&&this.actionsApi.orderUnits([t[0]],Vo.DeploySelected);break}case xc.Deployed:break;case xc.Attacking:e.getVisibleUnits(this.name,"self",e=>e.isSelectableCombatant).length||(this.botState=xc.Defeated,this.actionsApi.quitGame())}}}(s=Pc=Pc||{})[s.Requested=0]="Requested",s[s.Formed=1]="Formed",s[s.Broken=2]="Broken";class Vc{constructor(e,t,i){this.alliance=e,this.changeType=t,this.from=i,this.type=Xi.AllianceChange}}var zc,Hc,s=__webpack_require__(948),Gc=__webpack_require__.n(s);class $c{constructor(e){this.prng=new(Gc())(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 qc{constructor(e,t){this.action=e,this.trigger=t}getDebugName(){return`${this.action.triggerId}[${this.action.index}] (${this.trigger.name}).`}}class Zc extends qc{constructor(e,t,i){super(e,t),this.oneTimeOnly=i,this.superWeaponIdx=Number(e.params[1])}execute(i){var r=[...i.rules.superWeaponRules.values()].find(e=>e.index===this.superWeaponIdx);if(r){let t=i.getAllPlayers().find(e=>e.country?.name===this.trigger.houseName);if(t&&t.superWeaponsTrait&&!t.superWeaponsTrait.has(r.name)){let e=i.createSuperWeapon(r.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 Qc extends qc{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 r=t.rules.getWarhead(Fa.HE_WARHEAD_NAME);let e=new Fa(r);var s=t.map.tileOccupation.getBridgeOnTile(i),a=s?.tileElevation??0,r=t.map.getTileZone(i);e.detonate(t,this.damage,i,a,gr.tile3dToWorld(i.rx+.5,i.ry+.5,i.z+a),r,s?va.OnBridge:va.None,t.createTarget(s,i),void 0,!1,!1,void 0)}else console.warn(`No valid location found for waypoint ${e}. `+`Skipping action ${this.getDebugName()}.`)}}class Xc extends qc{execute(e){let i=e.getAllPlayers().find(e=>e.country?.name===this.trigger.houseName);if(i){let t=Number(this.action.params[1]);var r=e.getAllPlayers().find(e=>e.country?.id===t);if(r)for(var s of i.getOwnedObjects(!0))e.changeObjectOwner(s,r)}}}class Yc extends qc{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 r of t)r instanceof ra&&r.isSpawned&&e.changeObjectOwner(r,i)}}class Kc extends Lr{constructor(){super(),this.executed=!1,this.cancellable=!1}onTick(e){return this.executed?(e.stance=Br.None,!0):!e.isInfantry()||!e.art.sequences?.has(nn.Cheer)||(e.stance!==Br.None&&e.stance!==Br.Guard||(e.stance=Br.Cheer,this.children.push(new Ss(1/60).setCancellable(!1)),!(this.executed=!0)))}}class Jc extends qc{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(Ct.Infantry))i.unitOrderTrait.isIdle()&&i.unitOrderTrait.addTask(new Kc)}}const eu=new Map([[0,e=>{e=e.rules.powerups.powerups.find(e=>e.type===Sr.Money);return e?{...e,data:"5000"}:void 0}],[1,Sr.Unit],[2,Sr.HealBase],[3,Sr.Cloak],[4,Sr.Explosion],[5,Sr.Napalm],[6,Sr.Money],[7,Sr.Darkness],[8,Sr.Reveal],[9,Sr.Armor],[10,Sr.Speed],[11,Sr.Firepower],[12,Sr.ICBM],[13,void 0],[14,Sr.Veteran],[15,void 0],[16,Sr.Gas],[17,Sr.Tiberium],[18,void 0]]);class tu extends qc{execute(e){var t=Number(this.action.params[1]),i=this.action.params[6],r=e.map.getTileAtWaypoint(i);if(r)if(eu.has(t)){const s=eu.get(t);t="function"==typeof s?s(e):e.rules.powerups.powerups.find(e=>e.type===s);t&&e.crateGeneratorTrait.spawnCrateAt(r,t,e)}else e.crateGeneratorTrait.spawnRandomCrateAt(r,e);else console.warn(`No valid location found for waypoint ${i}. `+`Skipping action ${this.getDebugName()}.`)}}class iu extends qc{execute(e){var t=Number(this.action.params[1])-1;if(Object.values(Zt).includes(t)){var i=this.action.params[6],r=e.map.getTileAtWaypoint(i);if(r)for(var s of e.getCombatants())e.traits.get(Ll).addEventForPlayer(t,s,r,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 ru extends qc{execute(e,t){for(var i of t)i instanceof ra&&i.isSpawned&&e.destroyObject(i)}}class su extends qc{execute(e){var t=this.action.params[1];e.triggers.destroyTag(t)}}class au extends qc{execute(e){var t=this.action.params[1];e.triggers.destroyTrigger(t)}}class nu extends qc{execute(r){var s=Number(this.action.params[1]),e=this.action.params[6],a=r.map.getTileAtWaypoint(e);if(a){let t;try{t=r.rules.getWeaponByInternalId(s)}catch(e){if(e instanceof RangeError)return void console.warn(`Weapon with internal ID "${s}" not found. `+`Skipping action ${this.getDebugName()}.`);throw e}let e;try{e=r.rules.getWarhead(t.warhead)}catch(e){return void console.warn(`Warhead "${t.warhead}" not found. `+`Skipping action ${this.getDebugName()}.`)}let i=new Fa(e);var n=r.map.tileOccupation.getBridgeOnTile(a),o=n?.tileElevation??0,s=r.map.getTileZone(a);i.detonate(r,t.damage,a,o,gr.tile3dToWorld(a.rx+.5,a.ry+.5,a.z+o),s,n?va.OnBridge:va.None,r.createTarget(n,a),void 0,!1,!1,void 0)}else console.warn(`No valid location found for waypoint ${e}. `+`Skipping action ${this.getDebugName()}.`)}}class ou extends qc{execute(e,t){for(var i of t)i instanceof ra&&i.isBuilding()&&i.garrisonTrait&&!i.isDestroyed&&i.garrisonTrait.evacuate(e)}}class hu extends qc{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 lu extends qc{execute(e){var t=this.action.params[1];e.triggers.forceTrigger(t,e)}}class cu extends qc{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 uu extends qc{execute(e){var t,i,r=this.action.params[6],s=e.map.getTileAtWaypoint(r);s?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===Qi.IronCurtain))&&e.traits.get(tn).activateEffect(i,t,e,s,void 0,!0):console.warn(`No valid location found for waypoint ${r}. `+`Skipping action ${this.getDebugName()}.`)}}class du extends qc{execute(e){var t,i,r=this.action.params[6],s=e.map.getTileAtWaypoint(r);s?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===Qi.LightningStorm))&&e.traits.get(tn).activateEffect(i,t,e,s,void 0,!0):console.warn(`No valid location found for waypoint ${r}. `+`Skipping action ${this.getDebugName()}.`)}}class pu extends qc{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 gu extends qc{execute(){}}class mu extends qc{execute(e){var t,i,r=this.action.params[6],s=e.map.getTileAtWaypoint(r);s?!(t=e.getAllPlayers().find(e=>!e.defeated&&e.country?.name===this.trigger.houseName))||(i=[...e.rules.superWeaponRules.values()].find(e=>e.type===Qi.MultiMissile))&&e.traits.get(tn).activateEffect(i,t,e,s,void 0,!0):console.warn(`No valid location found for waypoint ${r}. `+`Skipping action ${this.getDebugName()}.`)}}class fu{constructor(e,t){this.name=e,this.tile=t,this.type=Xi.TriggerAnim}}class yu extends qc{execute(e){var t,i=this.action,r=Number(i.params[1]),s=e.rules.getAnimationName(r);void 0!==s?(t=i.params[6],(i=e.map.getTileAtWaypoint(t))?e.events.dispatch(new fu(s,i)):console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)):console.warn(`No animation found for index "${r}". Skipping action ${this.getDebugName()}`)}}class wu{constructor(e,t){this.soundId=e,this.tile=t,this.type=Xi.TriggerSoundFx}}class Tu extends qc{execute(e){var t=this.action,i=t.params[1],r=t.params[6],t=e.map.getTileAtWaypoint(r);t?e.events.dispatch(new wu(i,t)):console.warn(`No valid location found for waypoint ${r}. `+`Skipping action ${this.getDebugName()}.`)}}class bu extends qc{execute(e){e.events.dispatch(new wu(this.action.params[1]))}}class vu{constructor(e){this.soundId=e,this.type=Xi.TriggerEva}}class Su extends qc{execute(e){e.events.dispatch(new vu(this.action.params[1]))}}class _u extends qc{execute(e){for(var t of e.getCombatants())e.mapShroudTrait.resetShroud(t,e)}}class ku extends qc{execute(e){var[t,i,r,s]=this.action.params.slice(2,6).map(Number);e.map.mapBounds.updateRawLocalSize({x:t,y:i,width:r,height:s})}}class Ou extends qc{execute(e){var t=Number(this.action.params[1]),i=e.map.getTileAtWaypoint(t);if(i)for(var r of e.getCombatants())e.mapShroudTrait.getPlayerShroud(r)?.revealAround(i,e.rules.general.revealTriggerRadius);else console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class Iu extends qc{execute(e){for(var t of e.getCombatants())e.mapShroudTrait.revealMap(t,e)}}class Au extends qc{execute(e,t){for(var i of t)i instanceof ra&&i.isBuilding()&&!i.isDestroyed&&e.sellTrait.sell(i)}}class Cu extends qc{execute(e){var t=Number(this.action.params[1])/100;e.mapLightingTrait.setTargetAmbientIntensity(t)}}function Bu(e){let t=new DataView(new ArrayBuffer(4));return t.setInt32(0,e),t.getFloat32(0)}class Eu extends qc{execute(e){var t=Bu(Number(this.action.params[1]));e.mapLightingTrait.setAmbientChangeRate(t)}}class xu extends qc{execute(e){var t=Bu(Number(this.action.params[1]));e.mapLightingTrait.setAmbientChangeStep(t)}}class Pu{constructor(e){this.tile=e,this.type=Xi.TriggerStopSoundFx}}class Nu extends qc{execute(e){var t=this.action.params[6],i=e.map.getTileAtWaypoint(t);i?e.events.dispatch(new Pu(i)):console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class Ru{constructor(e){this.label=e,this.type=Xi.TriggerText}}class Du extends qc{execute(e){e.events.dispatch(new Ru(this.action.params[1]))}}class Mu extends qc{execute(e){e.countdownTimer.addSeconds(Number(this.action.params[1]))}}class Lu extends qc{execute(e){e.countdownTimer.setSeconds(Number(this.action.params[1]))}}class Fu extends qc{execute(e){e.countdownTimer.addSeconds(-Number(this.action.params[1]))}}class ju extends qc{execute(e){e.countdownTimer.start()}}class Wu extends qc{execute(e){e.countdownTimer.stop()}}class Uu extends qc{execute(e){e.countdownTimer.text=this.action.params[1]}}class Vu extends qc{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 zu extends qc{constructor(e,t,i){super(e,t),this.turnOn=i}execute(e,t){for(var i of t)i instanceof ra&&i.isBuilding()&&i.poweredTrait?.setTurnedOn(this.turnOn)}}class Hu extends qc{execute(e){var t=Number(this.action.params[1]),i=e.map.getTileAtWaypoint(t);if(i)for(var r of e.getCombatants())e.mapShroudTrait.getPlayerShroud(r)?.unrevealAround(i,e.rules.general.revealTriggerRadius);else console.warn(`No valid location found for waypoint ${t}. `+`Skipping action ${this.getDebugName()}.`)}}class Gu{create(e,t){switch(e.type){case $t.NoAction:return new gu(e,t);case $t.FireSale:return new hu(e,t);case $t.TextTrigger:return new Du(e,t);case $t.DestroyTrigger:return new au(e,t);case $t.ChangeHouse:return new Yc(e,t);case $t.RevealMap:return new Iu(e,t);case $t.RevealAroundWaypoint:return new Ou(e,t);case $t.PlaySoundFx:return new bu(e,t);case $t.PlaySpeech:return new Su(e,t);case $t.ForceTrigger:return new lu(e,t);case $t.TimerStart:return new ju(e,t);case $t.TimerStop:return new Wu(e,t);case $t.TimerExtend:return new Mu(e,t);case $t.TimerShorten:return new Fu(e,t);case $t.TimerSet:return new Lu(e,t);case $t.GlobalSet:return new cu(e,t,!0);case $t.GlobalClear:return new cu(e,t,!1);case $t.DestroyObject:return new ru(e,t);case $t.AddOneTimeSuperWeapon:return new Zc(e,t,!0);case $t.AddRepeatingSuperWeapon:return new Zc(e,t,!1);case $t.AllChangeHouse:return new Xc(e,t);case $t.ResizePlayerView:return new ku(e,t);case $t.PlayAnimAt:return new yu(e,t);case $t.DetonateWarhead:return new nu(e,t);case $t.ReshroudMap:return new _u(e,t);case $t.EnableTrigger:return new Vu(e,t,!0);case $t.DisableTrigger:return new Vu(e,t,!1);case $t.CreateRadarEvent:return new iu(e,t);case $t.LocalSet:return new pu(e,t,!0);case $t.LocalClear:return new pu(e,t,!1);case $t.SellBuilding:return new Au(e,t);case $t.TurnOffBuilding:return new zu(e,t,!1);case $t.TurnOnBuilding:return new zu(e,t,!0);case $t.ApplyOneHundredDamage:return new Qc(e,t,100);case $t.DestroyTag:return new su(e,t);case $t.SetAmbientStep:return new xu(e,t);case $t.SetAmbientRate:return new Eu(e,t);case $t.SetAmbientLight:return new Cu(e,t);case $t.NukeStrike:return new mu(e,t);case $t.PlaySoundFxAt:return new Tu(e,t);case $t.UnrevealAroundWaypoint:return new Hu(e,t);case $t.LightningStrike:return new du(e,t);case $t.TimerText:return new Uu(e,t);case $t.CreateCrate:return new tu(e,t);case $t.IronCurtainAt:return new uu(e,t);case $t.EvictOccupiers:return new ou(e,t);case $t.Cheer:return new Jc(e,t);case $t.StopSoundsAt:return new Nu(e,t);default:throw new Error(`Unhandled action type "${$t[e.type]}"`)}}}class $u{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 qu extends $u{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 Zu extends $u{check(e){return!0}}class Qu extends $u{check(r,e){return e.filter(e=>{if(e.type!==Xi.ObjectAttacked)return!1;let t=e.target;if(!t.isTechno()||!this.targets.includes(t))return!1;var i=e.attacker?.player;return(!i||!r.alliances.areAllied(i,t.owner)&&i!==t.owner)&&!e.incidental}).map(e=>e.target)}}class Xu extends $u{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==Xi.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 Yu extends $u{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 Ku extends $u{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===Xi.ObjectSpawn&&e.gameObject.type===this.objectType&&e.gameObject.rules.index===this.objectIndex)}}class Ju extends $u{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===Xi.EnterTile&&i.source.owner===this.player){let e=new br(t.map.tileOccupation);if(e.tileDistance(i.target,this.waypointTile)<2)return!0}return!1}}class ed extends $u{constructor(e,t){super(e,t),this.threshold=Number(e.params[1])}check(e,t){return!!this.player&&this.player.credits<this.threshold}}class td extends $u{constructor(e,t){super(e,t),this.threshold=Number(e.params[1])}check(e,t){return!!this.player&&this.player.credits>this.threshold}}class id extends $u{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!==Xi.ObjectDestroy)return!1;let t=e.target;return!(!t.isBuilding()||t.owner.country?.id!==this.houseId)&&!t.owner.buildings.size})&&(this.allDestroyed=!0)}}class rd extends $u{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!==Xi.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 sd extends $u{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!==Xi.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[Ct.Aircraft,Ct.Vehicle,Ct.Infantry])if(e.getOwnedObjectsByType(t,!0).length)return!0;return!1}}class ad extends $u{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!==Xi.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[Ct.Vehicle,Ct.Infantry])if(e.getOwnedObjectsByType(t,!0).filter(e=>!e.rules.naval).length)return!0;return!1}}class nd extends $u{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!==Xi.ObjectDestroy)return!1;let t=e.target;return!(!t.isVehicle()||t.owner.country?.id!==this.houseId)&&!t.owner.getOwnedObjectsByType(Ct.Vehicle,!0).filter(e=>e.rules.naval).length})&&(this.allDestroyed=!0)}}class od extends $u{check(r,e){return e.filter(e=>{if(e.type!==Xi.ObjectDestroy)return!1;let t=e.target;if(!t.isOverlay()||!t.isBridge())return!1;e=t.bridgeTrait?.bridgeSpec;if(!e)return!1;let i=r.map.bridges.findAllBridgeTiles(e);return i.find(e=>this.targets.includes(e))}).map(e=>e.target.tile)}}class hd extends $u{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===Xi.ObjectDestroy){let e=i.target;e.isBuilding()&&e.owner.country?.id===this.houseId&&this.count++}return this.count>=this.threshold}}class ld extends $u{check(r,e){return e.filter(e=>{if(e.type!==Xi.ObjectDestroy)return!1;let t=e.target;if(!t.isTechno()||!this.targets.includes(t))return!1;var i=e.attackerInfo?.player;return(!i||!r.alliances.areAllied(i,t.owner)&&i!==t.owner)&&!e.incidental}).map(e=>e.target)}}class cd extends $u{check(e,t){return t.filter(e=>{if(e.type!==Xi.ObjectDestroy&&e.type!==Xi.ObjectOwnerChange)return!1;let t=e.target;return!(!t.isTechno()||!this.targets.includes(t))}).map(e=>e.target)}}class ud extends $u{constructor(){super(...arguments),this.eventsFilter=[Xi.ObjectDestroy,Xi.ObjectOwnerChange,Xi.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 dd extends $u{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===Xi.ObjectDestroy){let e=i.target;e.isUnit()&&e.owner.country?.id===this.houseId&&this.count++}return this.count>=this.threshold}}class pd extends $u{constructor(e,t){super(e,t),this.timerTicks=Number(this.event.params[1])*xr.BASE_TICKS_PER_SECOND}check(e){return e.currentTick>this.timerTicks}}class gd extends $u{constructor(e,t){super(e,t),this.elapsedTicks=0,this.timerTicks=Number(this.event.params[1])*xr.BASE_TICKS_PER_SECOND}check(e){return this.elapsedTicks++>this.timerTicks}reset(){this.elapsedTicks=0}}class md extends $u{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(e=>(e.type===Xi.EnterObject||e.type===Xi.EnterTile)&&this.targets.includes(e.target)&&(-1===this.houseId||e.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class fd extends $u{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 yd extends $u{constructor(e,t,i){super(e,t),this.threshold=i}check(e,t){return t.filter(e=>{if(e.type!==Xi.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 wd extends $u{constructor(e,t,i){super(e,t),this.threshold=i}check(e,t){return t.filter(e=>{if(e.type!==Xi.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 Td extends $u{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 bd extends $u{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 vd extends $u{check(e){return!1}}class Sd extends $u{check(){if(!this.player)return!1;for(var e of this.player.buildings)if(e.factoryTrait)return!1;return!0}}class _d extends $u{check(e,t){return t.some(e=>e.type===Xi.CratePickup)}}class kd extends $u{check(e,t){return t.filter(e=>e.type===Xi.CratePickup&&this.targets.includes(e.source)).map(e=>e.source)}}class Od extends $u{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]))*xr.BASE_TICKS_PER_SECOND),this.elapsedTicks++>this.timerTicks}reset(){this.timerTicks=void 0,this.elapsedTicks=0}}class Id extends $u{constructor(e,t){super(e,t),this.houseId=Number(this.event.params[1])}check(e,t){return t.filter(e=>e.type===Xi.BuildingInfiltration&&this.targets.includes(e.target)&&(-1===this.houseId||e.source.owner.country?.id===this.houseId)).map(e=>e.target)}}class Ad extends $u{constructor(e,t){super(e,t),this.houseId=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==Xi.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 Cd extends $u{constructor(e,t){super(e,t),this.infantryIdx=Number(e.params[1])}check(e,t){return t.filter(e=>{if(e.type!==Xi.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 Bd extends $u{check(e,t){return t.some(e=>e.type===Xi.TimerExpire)}}class Ed{create(e,t){switch(e.type){case Gt.NoEvent:return new vd(e,t);case Gt.EnteredBy:return new md(e,t);case Gt.SpiedBy:return new Id(e,t);case Gt.AttackedByAny:return new Qu(e,t);case Gt.DestroyedByAny:return new ld(e,t);case Gt.AnyEvent:return new Zu(e,t);case Gt.DestroyedAllUnits:return new sd(e,t);case Gt.DestroyedAllBuildings:return new id(e,t);case Gt.DestroyedAll:return new rd(e,t);case Gt.CreditsExceed:return new td(e,t);case Gt.ElapsedTime:return new gd(e,t);case Gt.MissionTimerExpired:return new Bd(e,t);case Gt.DestroyedBuildings:return new hd(e,t);case Gt.DestroyedUnits:return new dd(e,t);case Gt.NoFactoriesLeft:return new Sd(e,t);case Gt.BuildBuilding:return new Ku(e,t,Ct.Building);case Gt.BuildUnit:return new Ku(e,t,Ct.Vehicle);case Gt.BuildInfantry:return new Ku(e,t,Ct.Infantry);case Gt.BuildAircraft:return new Ku(e,t,Ct.Aircraft);case Gt.GlobalIsSet:return new fd(e,t,!0);case Gt.GlobalIsCleared:return new fd(e,t,!1);case Gt.DestroyedOrCaptured:return new cd(e,t);case Gt.LowPower:return new bd(e,t);case Gt.DestroyedBridge:return new od(e,t);case Gt.BuildingExists:return new Yu(e,t);case Gt.ComesNearWaypoint:return new Ju(e,t);case Gt.LocalIsSet:return new Td(e,t,!0);case Gt.LocalIsCleared:return new Td(e,t,!1);case Gt.FirstDamagedCombat:return new wd(e,t,100);case Gt.HalfHealthCombat:return new wd(e,t,50);case Gt.QuarterHealthCombat:return new wd(e,t,25);case Gt.FirstDamagedAny:return new yd(e,t,100);case Gt.HalfHealthAny:return new yd(e,t,50);case Gt.QuarterHealthAny:return new yd(e,t,25);case Gt.AttackedByHouse:return new Xu(e,t);case Gt.AmbientLightBelow:return new qu(e,t,"below");case Gt.AmbientLightAbove:return new qu(e,t,"above");case Gt.ElapsedScenarioTime:return new pd(e,t);case Gt.DestroyedOrCapturedOrInfiltrated:return new ud(e,t);case Gt.PickupCrate:return new kd(e,t);case Gt.PickupCrateAny:return new _d(e,t);case Gt.RandomDelay:return new Od(e,t);case Gt.CreditsBelow:return new ed(e,t);case Gt.SpyEnteringAsHouse:return new Ad(e,t);case Gt.SpyEnteringAsInfantry:return new Cd(e,t);case Gt.DestroyedAllUnitsNaval:return new nd(e,t);case Gt.DestroyedAllUnitsLand:return new ad(e,t);case Gt.BuildingNotExists:return new Yu(e,t,!0);default:throw new Error(`Unhandled trigger event type "${Gt[e.type]}"`)}}}class xd{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 Pd{constructor(){this.disposables=new xd,this.triggerInstances=new Map,this.targetsByTag=new Map,this.conditionFactory=new Ed,this.executorFactory=new Gu,this.pendingGameEvents=[],this.globalVariables=new Map,this.localVariables=new Map}init(i){var t,e,r,s,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,r]of i.map.getVariables())this.localVariables.set(e,r.clone());for(s of i.map.getTriggers())this.triggerInstances.set(s.id,this.createTriggerInstance(s,i));this.disposables.add(i.events.subscribe(e=>this.pendingGameEvents.push(e)))}createTriggerInstance(i,r){let s=this.targetsByTag.get(i.tag.id)??[];return{trigger:i,conditions:i.events.map(e=>{let t=this.conditionFactory.create(e,i);return t.setTargets(s),t.init(r),t}).sort((e,t)=>Number(t.blocking)-Number(e.blocking)),targets:s,remainingTargets:new Set(i.tag.repeatType===Ht.OnceAll?s:[]),disabled:i.disabled,finished:!1}}update(i){var r,s=this.pendingGameEvents.splice(0,this.pendingGameEvents.length);for(r of this.triggerInstances.values())if(!r.finished&&!r.disabled){let e=!0,t=[];for(var a of r.conditions){var n=a.check(i,s);if("boolean"==typeof n?n||(e=!1):n.length?t.push(...n):e=!1,a.blocking&&!e)break}if(e){var o=r.trigger;r.conditions.forEach(e=>e.reset?.());let e=[];if(o.tag.repeatType===Ht.OnceAll){for(var h of t)r.remainingTargets.delete(h);if(r.remainingTargets.size)continue;e=t.length?[t[t.length-1]]:[]}else e=r.targets;this.executeActions(o,e,i),o.tag.repeatType!==Ht.Repeat&&(r.finished=!0)}}}executeActions(t,i,r){for(var s of t.actions){let e=this.executorFactory.create(s,t);e.execute(r,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,r]of this.triggerInstances)r.trigger.tag.id===e&&t.push(i);for(var s of t)this.destroyTrigger(s)}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 yi("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 yi("No name",t)):i.value=t}dispose(){this.disposables.dispose()}}class Nd{constructor(e){this.target=e,this.type=Xi.TimerExpire}}class Rd{constructor(){this.ticks=0,this.running=!1}getSeconds(){return Math.floor(this.ticks/xr.BASE_TICKS_PER_SECOND)}setSeconds(e){this.ticks=Math.max(0,Math.floor(xr.BASE_TICKS_PER_SECOND*e))}addSeconds(e){this.ticks=Math.max(0,this.ticks+Math.floor(xr.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 Nd(this))))}}(zc=zc||{}).onAdd=Symbol(),(s=Hc=Hc||{})[s.NotStarted=0]="NotStarted",s[s.Started=1]="Started",s[s.Ended=2]="Ended";class Dd{constructor(e,t,i,r,s,a,n,o,h,l,c,u,d,p){this.updatableObjects=new Set,this.constructionWorkers=new Map,this.currentTick=0,this.currentTime=0,this.countdownTimer=new Rd,this._onEnd=new Pn,this.afterTickCallbacks=[],this.events=new Hl,this.traits=new ia,this.world=e,this.map=t,this.rules=i,this.art=r,this.id=s,this.startTimestamp=a,this.prng=new $c(Number(s+""+a)),this.gameOpts=n,this.gameModeType=o,this.playerList=h,this.unitSelection=l,this.alliances=c,this.desiredSpeed=new kl(xr.computeGameSpeed(n.gameSpeed)),this.speed=new kl(this.desiredSpeed.value),this.nextObjectId=u,this.objectFactory=d,this.botManager=class{constructor(e,t,i,r,s){this.game=e,this.actionFactory=t,this.actionQueue=i,this.gameApi=r,this.eventsApi=s,this.bots=new Map}static factory(e,t){return new this(e,t,new Xl,new Bc(e,!0),new uc(e.events))}init(){var e,t;for(e of this.game.getCombatants().filter(e=>e.isAi))this.bots.set(e,new Uc(e.name,e.country.name));this.eventsApi.subscribe(t=>this.bots.forEach(e=>e.onGameEvent(t,this.gameApi)));for(t of this.bots.values())t.setGameApi(this.gameApi),t.setActionsApi(new tc(this.game,this.actionFactory,this.actionQueue,t.name)),t.setProductionApi(new jc(this.game.getPlayerByName(t.name).production)),t.onGameStart(this.gameApi)}update(){var e,t;for(e of this.actionQueue.dequeueAll())e.process();for(t of this.game.getCombatants().filter(e=>e.isAi))this.bots.get(t).onGameTick(this.gameApi)}dispose(){this.eventsApi.dispose()}}.factory(this,p),this.triggers=new Pd}get onEnd(){return this._onEnd.asEvent()}addPlayer(e){this.playerList.addPlayer(e),e.isCombatant()&&this.constructionWorkers.set(e,this.createConstructionWorker(e,e.production))}getPlayer(e){return this.playerList.getPlayerAt(e)}getPlayerByName(e){return this.playerList.getPlayerByName(e)}getAiPlayerName(e){return`@@AI${this.gameOpts.aiPlayers.indexOf(e)+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,t){return new Vl(e,t,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=Hc.Started,this.currentTick=0,this.currentTime=0,this.botManager.init(),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=>vr(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 r=this.getPlayerByName(i[t]),s=this.getPlayerByName(i[e]),s=this.alliances.setAlliance(r,s,hl.Formed);this.onAllianceChange(s,r,!0)}}}createMapObjects(){var e=this.rules.general.harvesterUnit.every(e=>!V(this.rules.getObject(e,Ct.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 r,s,a=i.name;this.validateMapObjectRulesAndArt(a,Ct.Terrain)&&((r=this.map.tiles.getByMapCoords(i.rx,i.ry))?(s=this.rules.getObject(a,Ct.Terrain),t&&s.spawnsTiberium||(a=this.createObject(Ct.Terrain,a),this.spawnObject(a,r))):console.warn(`Invalid map object location (${i.rx},${i.ry})`,i))}}createInitialMapOverlays(e,s){let a=new Map,n=new Map;for(var o of e){var h=this.rules.getOverlayName(o.id);if(this.validateMapObjectRulesAndArt(h,Ct.Overlay)){let e=this.createObject(Ct.Overlay,h),t=o.id;!e.rules.tiberium||void 0!==(l=an.calculateOverlayId(o))&&l!==o.id&&(e=this.createObject(Ct.Overlay,this.rules.getOverlayName(l)),t=l),e.overlayId=t,e.value=o.value;let i=o.rx,r=o.ry;e.isBridge()&&e.isHighBridge()&&(e.position.tileElevation=4,i+=e.isXBridge()?0:-1,r+=e.isXBridge()?-1:0);var l=this.map.tiles.getByMapCoords(i,r);if(l)if(Ca.isLowBridge(o.id))Ca.isBridgePlaceholder(o.id)||(a.set(l,o.value),1===o.value?n.set(l,e):e.dispose());else{if(e.isTiberium()){if(![_a.Ore,_a.Gems,_a.Vinifera].includes(xa.getOverlayTibType(e.overlayId))){console.warn(`Found unsupported TS tiberium overlay ${e.overlayId} @${l.rx},${l.ry}. Skipping.`);continue}if(this.map.getObjectsOnTile(l).find(e=>e.isTerrain())){e.dispose();continue}}s&&e.isTiberium()?e.dispose():this.spawnObject(e,l)}else console.warn(`Invalid map object location (${i},${r})`,o),e.dispose()}}for(var[t,i]of n){var r=i.isXBridge(),c=this.map.tiles.getByMapCoords(t.rx+(r?0:-1),t.ry+(r?-1:0)),r=this.map.tiles.getByMapCoords(t.rx+(r?0:1),t.ry+(r?1:0));c&&r&&(0===a.get(c)||2===a.get(r))?(i.value=0,this.spawnObject(i,c)):(i.dispose(),console.warn(`Invalid bridge segment @${t.rx},${t.ry}. Skipping.`))}var u,d=[...n.keys()].filter(e=>this.map.bridges.getPieceAtTile(e)?.headType!==el.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=Ca.bridgePlaceholderIds[0],y=this.rules.getOverlayName(f);for(m of e){let e=this.createObject(Ct.Overlay,y);e.overlayId=f,this.spawnObject(e,m)}}createInitialMapSmudges(e){for(var t of e){var i=t.name,r=this.map.tiles.getByMapCoords(t.rx,t.ry);r?(i=this.createObject(Ct.Smudge,i),this.spawnObject(i,r)):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])),r=this.map.getTags();for(let i of e){var s=i.name;if(this.validateMapObjectRulesAndArt(s,i.type)){var a=this.map.tiles.getByMapCoords(i.rx,i.ry);if(a){var n=t.get(i.owner);if(n){let t=this.createObject(i.type,s);i.tag&&(t.tag=r.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=mr(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,Ct.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,Ct.Vehicle),l=this.createUnitForPlayer(l,h);this.spawnObject(l,c);let e=zl.generate(this.gameOpts.unitCount,[...this.rules.vehicleRules.keys()],i,h.country);this.gameModeType===vt.Unholy&&e.push(...this.rules.general.baseUnit.filter(e=>e!==t).map(e=>({name:e,type:Ct.Vehicle,count:1})));var u,d,p;let r=[],s=!1,a=new Wn(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,Kt.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(s||(t=a.getNextTile(),t?r.push(t):s=!0),s){var g=r[o];let e=n.get(g);e||(e=new Wn(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,Kt.Foot,!1)),n.set(g,e)),o=(o+1)%r.length,t=e.getNextTile()}if(t){var m,f=this.rules.getObject(u,d);if(d===Ct.Vehicle){g=this.createUnitForPlayer(f,h);this.applyInitialVeteran(g,h),this.spawnObject(g,t),i--}else{if(d!==Ct.Infantry)throw new Error("Should not reach this line");for(m of ca.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(Xs.Elite):t.country.hasVeteranUnit(e.type,e.name)&&e.veteranTrait.setVeteranLevel(Xs.Veteran))}createObject(e,t){return this.objectFactory.create(e,t,this.rules,this.art)}createUnitForPlayer(e,t){if(![Ct.Aircraft,Ct.Vehicle,Ct.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,r,s){let a=this.createObject(Ct.Projectile,e);return a.fromWeapon=i,a.fromObject=t,a.fromPlayer=t.owner,a.target=r,a.isShrapnel=s,a}createLooseProjectile(e,t,i){var r=this.rules.getWeapon(e),s=r.projectile,a=this.rules.getProjectile(s),e=this.rules.getWarhead(r.warhead),e={minRange:0,projectileRules:a,range:Number.POSITIVE_INFINITY,rules:r,speed:za.computeSpeed(r,a),type:si.Primary,warhead:new Fa(e)};let n=this.createObject(Ct.Projectile,s);return n.fromWeapon=e,n.fromObject=void 0,n.fromPlayer=t,n.target=i,n}createSuperWeapon(e,t,i=!1){var r=this.rules.getSuperWeapon(e);return new Rr(e,r,t,i)}createTarget(e,t){return new ao(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 r=e.limboData;if(!r)throw new Error(`Object ${e.name}#${e.id} has no limboData attached`);e.limboData=void 0,this.doSpawnObject(e,t);let s=this.getUnitSelection();r.selected&&!i&&s.addToSelection(e),void 0!==r.controlGroup&&s.addUnitsToGroup(r.controlGroup,[e],!1)}doSpawnObject(t,e){var i,r;t.position.tile=e,t.isBuilding()&&(r=t.art.foundationCenter,i=e.rx+r.x,r=e.ry+r.y,t.centerTile=this.map.tiles.getByMapCoords(i,r)??this.map.tiles.getPlaceholderTile(i,r)),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(cl).forEach(e=>{e[cl.onSpawn](t,this)}),this.events.dispatch(new Ql(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(ul).forEach(e=>{e[ul.onUnspawn](t,this)}),this.events.dispatch(new Zl(t))}destroyObject(t,i,e=!1,r=!1){if(t.isDestroyed)throw new Error(`Object with ID "${t.id}" is already destroyed`);if(i&&t.isTechno()&&(!t.isBuilding()||t.owner.isCombatant())&&(i.player.kills++,i.player===t.owner||this.alliances.areAllied(i.player,t.owner)||(i.player.score+=t.rules.points)),t.isTechno()&&!t.owner.isNeutral&&t.owner.unitsLost++,t.isDestroyed=!0,t.healthTrait&&(t.healthTrait.health=0),t.onDestroy(this,i,e),this.traits.filter(gl).forEach(e=>{e[gl.onDestroy](t,this,i)}),i?.obj?.traits.filter(Th).forEach(e=>{e[Th.onDestroy](i.obj,t,i.weapon,this)}),this.events.dispatch(new Gl(t,i,r)),t.isBuilding()&&t.rules.leaveRubble&&t.deathType!==Ls.Temporal){t.owner.removeOwnedObject(t),this.unitSelection.cleanupUnit(t);r=this.map.tileOccupation.calculateTilesForGameObject(t.tile,t);this.map.terrain.invalidateTiles(r),t.art.canHideThings&&this.map.tileOcclusion.removeOccluder(t),this.updatableObjects.delete(t),t.onUnspawn(this),this.traits.filter(ul).forEach(e=>{e[ul.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(dl).forEach(e=>{e[dl.onChange](t,i,this)}),t.onOwnerChange(i,this),this.events.dispatch(new ql(t,i)))}addObjectTrait(t,i){t.addTrait(i),this.traits.filter(zc).forEach(e=>{e[zc.onAdd](t,i,this)})}onAllianceChange(t,e,i){this.events.dispatch(new Vc(t,i?Pc.Formed:Pc.Broken,e)),this.traits.filter(pl).forEach(e=>{e[pl.onChange](t,i,this)})}update(){if(this.status!==Hc.NotStarted){this.botManager.update(),this.status!==Hc.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(_r).forEach(e=>{e[_r.onTick](this)}),this.localPlayer&&!this.localPlayer.isObserver&&!this.localPlayer.defeated){var t=this.unitSelection.getSelectedUnits();if(1===t.length){let e=t[0];if(e.isTechno()&&e.owner!==this.localPlayer){let t=this.mapShroudTrait.getPlayerShroud(this.localPlayer);this.map.tileOccupation.calculateTilesForGameObject(e.tile,e).find(e=>!t.isShrouded(e))||(this.unitSelection.deselectAll(),this.unitSelection.cleanupUnit(e))}}}for(var i of this.afterTickCallbacks)i();this.afterTickCallbacks.length=0,this.triggers.update(this),this.countdownTimer.update(this),this.currentTick++,this.currentTime+=1e3/xr.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||(this.status=Hc.Ended,this._onEnd.dispatch(this,void 0))}updateDefeatedPlayers(e){let r=this.stalemateDetectTrait?.isStale()&&0===this.stalemateDetectTrait.getCountdownTicks(),s=this.gameOpts.shortGame;e.forEach(t=>{let i;if(r)i=!0;else{let e;e=s?(e=[...t.getOwnedObjectsByType(Ct.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}i&&(t.defeated=!0,this.removeAllPlayerAssets(t),this.events.dispatch(new $l(t)))})}removeAllPlayerAssets(e){e.getOwnedObjects().forEach(e=>{e.isDestroyed||this.destroyObject(e,void 0,!0)}),e.getOwnedObjects(!0).forEach(e=>{e.isDestroyed||(e.limboData?.inTransport?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.botManager.dispose(),this.botManager=void 0,this.triggers.dispose(),this.map.dispose(),this.traits.dispose()}}var Md,Ld,Fd,jd,Wd,Ud,Vd=__webpack_require__(949);class zd{constructor(e){this.map=e,this.radSites=new Map,this.radLevelByTile=new Map,this._onChange=new Pn}get onChange(){return this._onChange.asEvent()}getRadLevel(e){return this.radLevelByTile.get(e)}[_r.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 Fa(a.rules.getWarhead(n.radSiteWarhead));this.radLevelByTile.forEach((e,t)=>{var i,r,s=Math.min(n.radLevelMax,e)*n.radLevelFactor;for(i of a.map.getGroundObjectsOnTile(t).filter(e=>e.isUnit()&&!(e.isInfantry()&&e.stance===Br.Paradrop&&1<e.tileElevation)))o.canDamage(i,t,i.zone)&&(0<(r=o.computeDamage(s,i))&&o.inflictDamage(r,i,void 0,a,!0))})}applyDecay(r){var e=new Set(this.radLevelByTile.keys());this.radLevelByTile.clear(),this.radSites.forEach(({radLevel:e,radius:t},i)=>{e-=r;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 r=new br(this.map.tileOccupation),s=new Pr(this.map.tiles,this.map.mapBounds,e,{width:1,height:1},0,t,e=>!!e,!1);var a;let n=new Set;for(;a=s.getNextTile();){var o=r.tileDistance(e,a);o<=t&&(o=Math.ceil(Vd.Math.lerp(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 Hd{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 Gd{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 $d{constructor(){this.unitSelectionByPlayer=new Map}getOrCreateSelection(e){let t=this.unitSelectionByPlayer.get(e);return t||(t=new Gd(e),this.unitSelectionByPlayer.set(e,t)),t}}class qd extends Yl{constructor(){super(ml.NoAction)}process(){}}class Zd{create(){return new qd}}class Qd{constructor(e){this.target=e,this.type=Xi.BuildingPlace}}class Xd{constructor(e,t,i){this.name=e,this.player=t,this.tile=i,this.type=Xi.BuildingFailedPlace}}(Md=Md||{}).onPlace=Symbol();class Yd extends Yl{constructor(e){super(ml.PlaceBuilding),this.game=e}unserialize(e){this.name=e[0],this.tile={x:Number(e[1]),y:Number(e[2])}}serialize(){return[this.name,""+this.tile.x,""+this.tile.y]}print(){return`Place building ${this.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.game.getPlayerByName(this.playerName);const i=this.tryPlaceBuilding(t,e);i?(this.game.traits.filter(Md).forEach(e=>{e[Md.onPlace](i,this.game)}),this.game.events.dispatch(new Qd(i))):this.game.events.dispatch(new Xd(this.name,t,e))}else console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}tryPlaceBuilding(r,s){var a=this.game.rules.getBuilding(this.name);if(r.production){let i=r.production.getQueueForObject(a);if(i.status===wn.Ready&&i.getFirst().rules===a){let t=this.game.getConstructionWorker(r);if(t.canBuild(this.name)){let e=t.canBuildAt(this.name,s,void 0,!0);if(!e.filter(e=>!e.buildable).length){s=t.placeAt(this.name,s,!0);r.unitsBuilt++,i.shift(a,1);let e=r.production.getPrimaryFactory(qi.BuildingType);return e&&(e.factoryTrait.status=Gn.Delivering),s[0]}}}}}}class Kd{constructor(e){this.game=e}create(){return new Yd(this.game)}}class Jd extends Yl{constructor(e){super(ml.SellBuilding),this.game=e}unserialize(e){this.buildingId=Number(e[0])}serialize(){return[""+this.buildingId]}print(){return`Sell building ${this.buildingId}`}process(){var t=this.game.getPlayerByName(this.playerName);if(this.game.getWorld().hasObjectId(this.buildingId)){let e=this.game.getObjectById(this.buildingId);e.isBuilding()&&(t!==e.owner||e.isDestroyed||e.buildStatus!==No.Ready||e.warpedOutTrait.isActive()||this.game.sellTrait.sell(e))}}}class ep{constructor(e){this.game=e}create(){return new Jd(this.game)}}class tp extends Yl{constructor(e,t){super(ml.SelectUnits),this.game=e,this.orderActionContext=t}unserialize(e){this.unitIds=e.map(Number)}serialize(){return this.unitIds.map(String)}print(){return`Select unit(s) [${this.unitIds.join(",")}]`}process(){let e=this.game.getPlayerByName(this.playerName),t=[];for(var i of this.unitIds){i=e.getOwnedObjectById(i);i&&t.push(i)}this.orderActionContext.getOrCreateSelection(e).update(t)}}class ip{constructor(e,t){this.game=e,this.orderActionContext=t}create(){return new tp(this.game,this.orderActionContext)}}const rp=[Vo.Occupy,Vo.Dock,Vo.Attack,Vo.Capture,Vo.Repair,Vo.EnterTransport,Vo.PlaceBomb,Vo.Deploy,Vo.Gather];(s=Ld=Ld||{})[s.Default=0]="Default",s[s.Mini=1]="Mini",s[s.Scroll=2]="Scroll",s[s.NoScroll=10]="NoScroll",s[s.Select=18]="Select",s[s.Move=31]="Move",s[s.NoMove=41]="NoMove",s[s.MoveMini=42]="MoveMini",s[s.NoActionMini=52]="NoActionMini",s[s.AttackRange=53]="AttackRange",s[s.AttackNoRange=58]="AttackNoRange",s[s.AttackMini=63]="AttackMini",s[s.Guard=68]="Guard",s[s.GuardMini=73]="GuardMini",s[s.Unknown1=78]="Unknown1",s[s.Unknown2=88]="Unknown2",s[s.Occupy=89]="Occupy",s[s.NoOccupy=99]="NoOccupy",s[s.OccupyMini=100]="OccupyMini",s[s.Deploy=110]="Deploy",s[s.NoDeploy=119]="NoDeploy",s[s.Unknown3=120]="Unknown3",s[s.Sell=129]="Sell",s[s.SellMini=139]="SellMini",s[s.NoSell=149]="NoSell",s[s.RepairMove=150]="RepairMove",s[s.SideRepair=170]="SideRepair",s[s.NoRepair=190]="NoRepair",s[s.Unknown4=191]="Unknown4",s[s.Unknown5=199]="Unknown5",s[s.Dynamite=204]="Dynamite",s[s.Unknown6=209]="Unknown6",s[s.Unknown7=214]="Unknown7",s[s.Unknown8=219]="Unknown8",s[s.Unknown9=224]="Unknown9",s[s.Unknown10=229]="Unknown10",s[s.Unknown11=234]="Unknown11",s[s.Unknwon12=239]="Unknwon12",s[s.Unknown13=249]="Unknown13",s[s.Para=259]="Para",s[s.Unknown14=269]="Unknown14",s[s.Storm=279]="Storm",s[s.Unknown15=299]="Unknown15",s[s.C4=309]="C4",s[s.Nuke=319]="Nuke",s[s.Unknown16=329]="Unknown16",s[s.Power=339]="Power",s[s.Unknown17=345]="Unknown17",s[s.Iron=346]="Iron",s[s.Unknown18=351]="Unknown18",s[s.Unknown19=356]="Unknown19",s[s.Chrono=357]="Chrono",s[s.DefuseBomb=369]="DefuseBomb",s[s.NoAction=384]="NoAction",s[s.Pan=385]="Pan",s[s.Unknown21=394]="Unknown21",s[s.AttackMove=404]="AttackMove",s[s.Unknown23=413]="Unknown23",s[s.Unknown24=422]="Unknown24",s[s.Unknown25=431]="Unknown25",s[s.Unknown26=432]="Unknown26",s[s.Unknown27=433]="Unknown27",s[s.Unknown28=434]="Unknown28",s[s.Beacon=435]="Beacon",(s=Fd=Fd||{})[s.None=0]="None",s[s.Move=1]="Move",s[s.Attack=2]="Attack",s[s.Enter=3]="Enter",s[s.Capture=4]="Capture",s[s.SpecialAttack=5]="SpecialAttack";class sp{constructor(e){this.orderType=e,this.targetOptional=!0,this.minimapAllowed=!0,this.singleSelectionRequired=!1,this.terminal=!1,this.feedbackType=Fd.None}getPointerType(e,t){return e?Ld.Mini:Ld.Default}set(e,t){return this.sourceObject=e,this.target=t,this}isValid(){return!0}isAllowed(){return!0}onAdd(e,t){return!0}}class ap{constructor(e,t){this.from=e,this.to=t,this.type=Xi.ObjectMorph}}class np extends Lr{constructor(e){super(),this.game=e}onStart(e){if(!this.morphInto)throw new Error("morphInto not set");e.isBuilding()&&e.buildStatus!==No.BuildDown&&this.morphInto.type!==Ct.Building&&this.children.push(new Ul),e.isVehicle()&&this.morphInto.type===Ct.Building&&this.children.push(new rs(180))}onTick(r){if(!this.morphInto)throw new Error("morphInto not set");let e=this.game.getUnitSelection();var t=e.isSelected(r),i=e.getOrCreateSelectionModel(r).getControlGroupNumber(),s=this.morphInto;let a;if(s.type===Ct.Building){if(r.isVehicle()&&r.parasiteableTrait?.isInfested())return!0;let t=r.tile,e=this.game.getConstructionWorker(r.owner),i=e.canBuildAt(this.morphInto.name,t);if(i.find(e=>!(e.buildable||e.rx===t.rx&&e.ry===t.ry)))return!0;this.game.unspawnObject(r),r.dispose(),[a]=e.placeAt(this.morphInto.name,t),a.healthTrait.health=r.healthTrait.health}else{let e=r.unitOrderTrait.getTasks().filter(e=>e instanceof Us);this.game.unspawnObject(r),r.dispose(),a=this.game.createUnitForPlayer(this.morphInto,r.owner),a.direction=180,a.healthTrait.health=r.healthTrait.health;s=r.art.foundationCenter;this.game.spawnObject(a,this.game.map.tiles.getByMapCoords(r.tile.rx+s.x,r.tile.ry+s.y)),e.forEach(e=>a.unitOrderTrait.addTask(e))}return a.purchaseValue=r.purchaseValue,r.replacedBy=a,t&&e.addToSelection(a),void 0!==i&&e.addUnitsToGroup(i,[a],!1),this.game.events.dispatch(new ap(r,a)),!0}}class op extends np{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,Ct.Vehicle),super.onStart(e)}}class hp{constructor(e){this.target=e,this.type=Xi.RallyPointChange}}class lp extends sp{constructor(e,t,i,r=!1){super(r?Vo.ForceMove:Vo.Move),this.game=e,this.map=t,this.unitSelection=i,this.forceMove=r,this.targetOptional=!1,this.feedbackType=Fd.Move}getPointerType(e){let t=this.isAllowed();var i,r,s,a;return!t||this.sourceObject.isBuilding()||this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile)||(i=!!this.target.getBridge(),r=this.sourceObject.rules.speedType,s=this.sourceObject.rules.movementZone===ii.Fly,a=this.map.getObjectsOnTile(this.target.tile).some(e=>(e.isInfantry()||e.isVehicle())&&e.disguiseTrait?.hasTerrainDisguise()),t=s?this.sourceObject.rules.balloonHover||0<this.map.terrain.getPassableSpeed(this.target.tile,Kt.Amphibious,i)&&!a:0<this.map.terrain.getPassableSpeed(this.target.tile,r,i)&&!a&&!(this.target.obj?.isTechno()&&!this.game.areFriendly(this.target.obj,this.sourceObject))),e?t?Ld.MoveMini:Ld.NoActionMini:t?Ld.Move:Ld.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.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 op(this.game),new Us(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:t})]:e.isUnit()?[new Us(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:t})]:void 0}}onAdd(t,e){if(this.sourceObject.isBuilding()&&this.sourceObject.rules.undeploysInto&&this.sourceObject.buildStatus===No.BuildUp)return this.sourceObject.unitOrderTrait.getTasks().find(e=>e instanceof Oo)?.setCancellable(!0),!0;if(this.sourceObject.isBuilding()&&this.sourceObject.rallyTrait?.getRallyPoint())return this.sourceObject.rallyTrait.changeRallyPoint(this.target.tile,this.sourceObject,this.game),this.game.events.dispatch(new hp(this.sourceObject)),!1;if(!e&&this.isValid()&&this.isAllowed()){this.sourceObject.attackTrait?.cancelOpportunityFire();let e=t.find(e=>e.constructor===Us&&!e.isCancelling());if(e)return e.updateTarget(this.target.tile,!!this.target.getBridge()),e.children.length&&e.children[0]instanceof co&&e.children[0].cancel(),t.splice(t.indexOf(e)+1),this.sourceObject.unitOrderTrait.clearOrders(),!1;if(this.sourceObject.isUnit()&&this.sourceObject.rules.movementZone===ii.Fly){let e=t.find(e=>e.constructor===co&&!e.isCancelling());e&&e.forceCancel(this.sourceObject)&&t.splice(t.indexOf(e))}}return!0}}class cp extends np{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,Ct.Building),super.onStart(e)}onTick(e){return!!this.isCancelling()||super.onTick(e)}}class up{constructor(e,t){this.unit=e,this.deployType=t,this.type=Xi.UnitDeployUndeploy}}class dp{constructor(e){this.target=e,this.type=Xi.PrimaryFactoryChange}}(s=jd=jd||{})[s.None=0]="None",s[s.OnlyPassengers=1]="OnlyPassengers",s[s.All=2]="All";class pp extends Lr{constructor(e,t){super(),this.game=e,this.soft=t,this.evacState=jd.None,this.evacTries=0,this.turnPerformed=!1,this.preventLanding=!1}forceEvac(){this.evacState=jd.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!==jd.OnlyPassengers&&1!==t.units.length||!e.rules.gunner?jd.OnlyPassengers:jd.All)}onTick(e){if(this.isCancelling()||this.evacState===jd.None)return!0;if(e.zone===dr.Air)return this.children.push(new _s(()=>e.zone!==dr.Air)),!1;let t=e.transportTrait.units;if(!t.length||e.rules.gunner&&1===t.length&&this.evacState!==jd.All)return!0;var i=t[t.length-1],r=this.findValidEvacTarget(e,i);if(r&&!this.turnPerformed){this.turnPerformed=!0;var s=(r.dir+180)%360;if(e.direction!==s)return this.children.push(new rs(s)),!1}return this.evacuateUnit(i,e,r)?(t.pop(),this.children.push(new Ss(1/60)),!1):!(++this.evacTries<=3)||(this.children.push(new Ss(.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:r,moveNode:i}=i;return e.position.tileElevation=r.onBridge?.tileElevation??0,e.onBridge=!!r.onBridge,e.zone=this.game.map.getTileZone(r.tile,!r.onBridge),this.game.unlimboObject(e,r.tile),e.unitOrderTrait.unmarkNextQueuedOrder(),i?e.unitOrderTrait.addTask(new Us(this.game,i.tile,!!i.onBridge)):e.unitOrderTrait.addTask(new Ds(this.game)),this.game.events.dispatch(new Zo(t)),!0}findValidEvacTarget(a,n){let o=this.game.map,h=new Wr(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=is.toMapCoords(l);let i=a.tile,r=t,s;for(let t=1;t<=2;t++){if(2===t){if(!s)break;i=s.tile,r=s.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=r,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:s,moveNode:{tile:T,onBridge:f},dir:l};s={tile:T,onBridge:f},g={spawnNode:s,moveNode:void 0,dir:l}}}}if(g)return g}}class gp extends sp{constructor(e,t){super(t?Vo.Deploy:Vo.DeploySelected),this.game=e,this.targeted=t,this.minimapAllowed=!1,this.getPointerType=()=>this.isAllowed()?Ld.Deploy:Ld.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&&![Br.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 i=this.sourceObject;if(i.isVehicle()&&i.transportTrait)return!!(i.transportTrait.units.length&&0<this.game.map.terrain.getPassableSpeed(i.tile,Kt.Foot,i.onBridge));if((i.isInfantry()||i.isVehicle())&&i.deployerTrait)return!0;if(i.isVehicle()&&i.rules.deploysInto){if(i.parasiteableTrait?.isInfested())return!1;let e=this.game.getConstructionWorker(i.owner);if(i.moveTrait.currentWaypoint?.onBridge)return!1;var r=i.moveTrait.currentWaypoint?.tile??i.tile;let t=e.canBuildAt(i.rules.deploysInto,r,[i]);return!t.find(e=>!e.buildable)}if(i.isBuilding()&&i.rules.factory)return!0;if(i.isBuilding()&&i.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 pp(this.game,!0)]:e.isBuilding()&&e.rules.factory?void 0:e.isVehicle()&&e.rules.deploysInto?[new cp(this.game)]:(e.isInfantry()||e.isVehicle())&&e.deployerTrait?[new _s(()=>{e.deployerTrait.toggleDeployed(),this.game.events.dispatch(new up(e,e.deployerTrait.isDeployed()?"undeploy":"deploy"))})]:e.isBuilding()&&e.garrisonTrait?.units.length?[new _s(()=>{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 dp(i)),!1;if(i.isVehicle()&&i.transportTrait&&!e&&this.isValid()&&this.isAllowed()){let e=t.find(e=>e.constructor===pp&&!e.isCancelling());if(e)return e.forceEvac(),!1}return!0}}class mp{constructor(e){this.player=e,this.type=Xi.Cheer}}class fp{constructor(e){this.target=e,this.type=Xi.DeployNotAllowed}}class yp extends Yl{constructor(e,t,i,r){super(ml.OrderUnits),this.game=e,this.map=t,this.orderActionContext=i,this.orderFactory=r,this.queue=!1,this.isInvalid=!1}unserialize(t){if(this.orderType=Number(t[0]),1!==t.length){let e;if(""!==t[1]){var i=Number(t[1]);if(!this.game.getWorld().hasObjectId(i))return void(this.isInvalid=!0);e=this.game.getObjectById(i)}else e=void 0;var[r,i]=t[2].split(","),i=this.map.tiles.getByMapCoords(Number(r),Number(i));this.target=this.game.createTarget(e,i),this.queue=Boolean(Number(t[3]||"0"))}}serialize(){let e=[""+this.orderType];var t;return this.target&&(t=(this.target.obj||this.target.getBridge())?.id,e.push(""+(void 0!==t?t:""),this.target.tile.rx+","+this.target.tile.ry,this.queue?"1":"0")),e}print(){return this.isInvalid?"":`${Vo[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.game.getPlayerByName(this.playerName);const h=this.game.mapShroudTrait.getPlayerShroud(n);if(h){if(this.target?.obj){let e=this.game.map.tileOccupation.calculateTilesForGameObject(this.target.obj.tile,this.target.obj);if(!e.find(e=>!h.isShrouded(e)))return}let e=this.validateOrders(n).slice(0,128),a=[],t=[],r=[],i=[],s=[];if(e.forEach(e=>{(e instanceof lp?t:e.orderType===Vo.Scatter?r:e.orderType===Vo.DeploySelected?i:e.orderType===Vo.Cheer?s:a).push(e)}),t.length&&this.target){let r=this.target.getBridge();var o=t.map(e=>e.sourceObject);let s=new Wr(this.map).findPositions(o,this.target.tile,r);t.forEach(e=>{var t=s.get(e.sourceObject),i=!r||r.isHighBridge()?this.map.tileOccupation.getBridgeOnTile(t):r,t=this.game.createTarget(i,t);e.target=t,a.push(e)})}if(r.length){o=r.map(e=>e.sourceObject).filter(e=>e.isInfantry()||e.isVehicle());let i=new Rs(this.game).findPositions(o);r.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))}s.length&&(n.cheerCooldownTicks||(n.cheerCooldownTicks=this.game.rules.general.maximumCheerRate,a.push(...s),this.game.events.dispatch(new mp(n)))),a.forEach(e=>e.sourceObject.unitOrderTrait.addOrder(e,this.queue)),this.updateWaypointPaths(a)}}}validateOrders(e){let i=this.orderActionContext.getOrCreateSelection(e);var r,s=i.getSelectedUnits();let t=this.orderFactory.create(this.orderType,i);t.target=this.target;let a=[];for(r of s)if(!(r.owner!==e||r.rules.spawned||r.isDestroyed||r.isCrashing||r.isDisposed||r.warpedOutTrait.isActive()||(t.sourceObject=r,t instanceof gp&&t.isValid()&&!t.isAllowed()&&this.game.events.dispatch(new fp(r)),t.singleSelectionRequired&&1<s.length)))if(t.isValid()&&t.isAllowed()){let e=this.orderFactory.create(this.orderType,i);e.set(r,this.target),a.push(e)}else{let t=!1;for(var n of rp){let e=this.orderFactory.create(n,i);if(e.set(r,this.target),!(e.singleSelectionRequired&&1<s.length)&&(e.targetOptional===!this.target&&e.isValid()&&e.isAllowed())){a.push(e),t=!0;break}}if(!t&&this.target&&this.orderType!==Vo.Deploy){let e=this.orderFactory.create(Vo.Move,i);e.set(r,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(ga))];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 wp extends Us{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 Tp extends Us{constructor(e,t){super(e,Tp.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 bp{constructor(e){this.target=e,this.type=Xi.BuildingGarrison}}class vp{constructor(e,t){this.target=e,this.source=t,this.type=Xi.EnterObject}}class Sp extends Lr{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1,this.preventOpportunityFire=!1}isAllowed(e){return 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 wp(this.game,this.target)),!(this.aborted=!0)):(this.game.limboObject(e,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(e).getControlGroupNumber()}),t.units.length||(this.game.changeObjectOwner(this.target,e.owner),this.game.events.dispatch(new bp(this.target))),this.game.events.dispatch(new vp(this.target,e)),t.units.push(e),!0):!!this.movePerformed||(this.children.push(new Tp(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class _p{constructor(e){this.target=e,this.type=Xi.UnitRecycle}}class kp extends Lr{constructor(e,t){super(),this.game=e,this.target=t,this.aborted=!1,this.movePerformed=!1}isAllowed(e){return e.rules.movementZone!==ii.Fly&&e.rules.locomotor!==ti.Chrono&&0<this.game.sellTrait.computeRefundValue(e)&&this.target.rules.cloning&&!this.target.isDestroyed&&this.target.buildStatus===No.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 wp(this.game,this.target)),!(this.aborted=!0)):(this.game.sellTrait.sell(e),this.game.events.dispatch(new _p(e)),this.game.events.dispatch(new vp(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Tp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Op{constructor(e,t){this.target=e,this.source=t,this.type=Xi.BuildingInfiltration}}class Ip extends Lr{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!==No.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 wp(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),e.agentTrait?.infiltrate(e,this.target,this.game),this.game.events.dispatch(new Op(this.target,e)),this.game.events.dispatch(new vp(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Tp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}(s=Wd=Wd||{})[s.MoveToQueueingTile=0]="MoveToQueueingTile",s[s.WaitForTurn=1]="WaitForTurn",s[s.MoveToTarget=2]="MoveToTarget",s[s.EnterTarget=3]="EnterTarget",s[s.ClearTarget=4]="ClearTarget";class Ap extends Lr{constructor(e,t){super(),this.game=e,this.target=t,this.movePerformed=!1}isAllowed(e){return e.rules.movementZone!==ii.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=Wd.MoveToQueueingTile:this.state=Wd.MoveToTarget}onEnd(e){!this.target.isDestroyed&&e.isSpawned&&this.target.hospitalTrait.removeFromHealQueue(e)}onTick(i){if(this.isCancelling()&&this.state!==Wd.EnterTarget||this.state===Wd.ClearTarget||i.moveTrait.isDisabled())return!0;if(this.state===Wd.MoveToQueueingTile){let t=new Wr(this.game.map);var e=new Pr(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 Us(this.game,e,!1,{closeEnoughTiles:5})),this.children.push(new _s(()=>{[Hs.Success,Hs.CloseEnough].includes(i.moveTrait.lastMoveResult)||this.cancel()})),this.state=Wd.WaitForTurn,this.queueingTile=e,!1)}if(this.state===Wd.WaitForTurn){if(!this.target.hospitalTrait.unitIsFirstInHealQueue(i))return!1;this.queueingTile=void 0,this.state=Wd.MoveToTarget}if(this.state===Wd.MoveToTarget){if(!this.isAllowed(i))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(i.tile,this.target))return!!this.movePerformed||(this.children.push(new Tp(this.game,this.target)),!(this.movePerformed=!0));this.state=Wd.EnterTarget}return this.state===Wd.EnterTarget&&(!this.isAllowed(i)||this.isCancelling()?(this.children.push(new wp(this.game,this.target)),this.state=Wd.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 vp(this.target,i)),!0))}getTargetLinesConfig(e){return{target:this.queueingTile?void 0:this.target,pathNodes:this.queueingTile?[{tile:this.queueingTile,onBridge:void 0}]:[]}}}class Cp extends sp{constructor(e){super(Vo.Occupy),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Fd.Capture}getPointerType(e){return e?this.isAllowed()?Ld.OccupyMini:Ld.NoActionMini:this.isAllowed()?Ld.Occupy:Ld.NoOccupy}isValid(){return!(this.target.obj?.isDestroyed||!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!==ii.Fly&&t.rules.locomotor!==ti.Chrono&&0<this.game.sellTrait.computeRefundValue(t):e.hospitalTrait?t.healthTrait.health<100&&t.rules.movementZone!==ii.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 kp(this.game,e)]:e.hospitalTrait?[new Ap(this.game,e)]:e.garrisonTrait?[new Sp(this.game,e)]:[new Ip(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof Sp||e instanceof Ip);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new br(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Bp extends Lr{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 Tp(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));if(!this.isAllowed(e)||this.isCancelling())return this.children.push(new wp(this.game,this.target)),!(this.aborted=!0);var t=Math.floor(60*this.game.rules.combatDamage.c4Delay*xr.BASE_TICKS_PER_SECOND);return this.target.c4ChargeTrait.setCharge(t,{player:e.owner,obj:e}),this.game.events.dispatch(new vp(this.target,e)),this.children.push(new wp(this.game,this.target)),!(this.aborted=!0)}getTargetLinesConfig(e){return{target:this.target,pathNodes:[],isAttack:!0}}}class Ep extends sp{constructor(e,{forceAttack:t,noIvanBomb:i}={}){super(t?Vo.ForceAttack:Vo.Attack),this.game=e,this.isC4=!1,this.forceAttack=!!t,this.ivanBombAllowed=!i||!!t,this.targetOptional=!1,this.feedbackType=Fd.None,this.rangeHelper=new br(this.game.map.tileOccupation),this.losHelper=new to(this.game.map.tiles,e.map.tileOccupation)}getPointerType(e,t){if(!this.isAllowed())return e?Ld.NoActionMini:Ld.NoAction;if(this.isC4)return Ld.C4;var i=this.sourceObject.attackTrait?.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);if(i?.rules.sabotageCursor)return Ld.C4;if(this.ivanBombAllowed&&this.sourceObject.rules.ivan&&i?.warhead.rules.ivanBomb)return Ld.Dynamite;if(i?.warhead.rules.bombDisarm)return Ld.DefuseBomb;if(i&&i.rules.damage<0)return Ld.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?Ld.AttackMini:t?Ld.AttackRange:Ld.AttackNoRange}isValid(){if(!this.sourceObject.attackTrait)return!1;if(this.forceAttack&&this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile)&&!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=Fd.SpecialAttack,!0;if(this.isC4=!1,this.feedbackType=Fd.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===dr.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.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 Bp(this.game,this.target.obj)];var e=this.sourceObject.attackTrait.selectWeaponVersus(this.sourceObject,this.target,this.game,this.forceAttack);return[new co(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===ii.Fly){let e=t.find(e=>(e.constructor===Us||e.constructor===co)&&!e.isCancelling());e&&(i.moveTrait.currentWaypoint?.tile===this.target.tile||i.isAircraft()||e.constructor===co)&&e.forceCancel(i)&&t.splice(t.indexOf(e))}else{t.length&&i.isUnit()&&(i.rules.locomotor===ti.Vehicle||i.rules.locomotor===ti.Ship)&&(i.moveTrait.speedPenalty=.5);let e=t.find(e=>e.constructor===co&&!e.isCancelling());if(e?.getWeapon().warhead.rules.temporal)return e.setForceAttack(this.forceAttack),e.requestTargetUpdate(this.target),!1}return!0}}class xp extends sp{constructor(e){super(Vo.Stop),this.game=e,this.getPointerType=()=>Ld.NoAction}isValid(){return this.sourceObject.isTechno()}isAllowed(){return!0}process(){return[new _s(e=>{!e.isUnit()||e.rules.locomotor!==ti.Vehicle&&e.rules.locomotor!==ti.Ship||(e.moveTrait.speedPenalty=0)})]}onAdd(e,t){let i=this.sourceObject;return t||!e.length||!i.isUnit()||i.rules.locomotor!==ti.Vehicle&&i.rules.locomotor!==ti.Ship||(i.moveTrait.speedPenalty=.5),i.isBuilding()&&i.rallyTrait?.getRallyPoint()&&(i.unitRepairTrait?.resetRallyPoint(i,this.game),i.factoryTrait?.resetRallyPoint(i,this.game)),!0}}class Pp extends sp{constructor(){super(Vo.Cheer),this.getPointerType=()=>Ld.NoAction}isValid(){return this.sourceObject.isInfantry()&&[Br.None,Br.Guard].includes(this.sourceObject.stance)}isAllowed(){return!0}process(){return[new Kc]}}class Np extends sp{constructor(e){super(Vo.Dock),this.game=e,this.targetOptional=!1,this.feedbackType=Fd.Move}getPointerType(e){return e?this.isAllowed()?Ld.OccupyMini:Ld.NoActionMini:this.isAllowed()?Ld.Occupy:Ld.NoOccupy}isValid(){if(!this.target.obj?.isBuilding()||this.target.obj.isDestroyed||!this.target.obj.dockTrait||this.target.obj.buildStatus!==No.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 $o(this.game,e,!0,!0)]:e.unitRepairTrait||this.sourceObject.rules.dock.includes(e.name)?[new Is(this.game,e)]:[]}}class Rp extends sp{constructor(e){super(Vo.Gather),this.game=e,this.targetOptional=!1,this.feedbackType=Fd.Move}getPointerType(e){return e?Ld.AttackMini:Ld.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.isOre}isAllowed(){return!0}process(){return[new Wo(this.game,this.target.tile,!0)]}}class Dp extends Us{constructor(){super(...arguments),this.attackPerformed=!1,this.passedFirstWaypoint=!1}onTick(i){if(i.moveTrait.moveState===zs.Moving&&(this.passedFirstWaypoint=!0),i.moveTrait.moveState===zs.ReachedNextWaypoint&&i.attackTrait&&!i.attackTrait.isDisabled()&&!this.isCancelling()){let e=i.attackTrait.selectDefaultWeapon(i);if(e&&(this.passedFirstWaypoint||e&&!e.getCooldownTicks())){var r=i.attackTrait.scanForTarget(i,e,this.game);if(r.target){let{target:e,weapon:t}=r;if(!t.getCooldownTicks()){r=i.attackTrait.createAttackTask(this.game,e,e.tile,t,{holdGround:!0,passive:!0});return this.children.push(r),this.useChildTargetLines=!0,this.attackPerformed=!0,i.moveTrait.velocity.set(0,0,0),i.moveTrait.currentWaypoint=void 0,i.moveTrait.collisionState=Gs.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=Gs.Resolved,this.updateTarget(this.targetTile,this.toBridge)}}return super.onTick(i)}}class Mp extends sp{constructor(e,t){super(Vo.AttackMove),this.game=e,this.map=t,this.targetOptional=!1,this.feedbackType=Fd.Attack}getPointerType(e){let t=this.isAllowed();var i,r,s;return t&&(i=!!this.target.getBridge(),r=this.sourceObject.rules.speedType,s=this.sourceObject.rules.movementZone===ii.Fly,t=s||0<this.map.terrain.getPassableSpeed(this.target.tile,r,i)||!!this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile)),e?t?Ld.AttackMini:Ld.NoActionMini:t?Ld.AttackMove:Ld.NoMove}isValid(){return this.sourceObject.isUnit()&&!!this.sourceObject.attackTrait&&!this.sourceObject.rules.preventAttackMove&&!(this.game.mapShroudTrait.getPlayerShroud(this.sourceObject.owner)?.isShrouded(this.target.tile)&&!this.sourceObject.rules.moveToShroud)}isAllowed(){return!this.sourceObject.moveTrait.isDisabled()&&!this.sourceObject.attackTrait.isDisabled()}process(){return[new Dp(this.game,this.target.tile,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})]}}class Lp{constructor(e,t){this.target=e,this.source=t,this.type=Xi.BuildingRepairFull}}class Fp{constructor(e,t){this.source=e,this.tile=t,this.type=Xi.BridgeRepair}}class jp extends Lr{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 wp(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 Fp(e.owner,this.target.centerTile))):(this.target.healthTrait.healToFull(e,this.game),this.game.events.dispatch(new Lp(this.target,e.owner))),this.game.events.dispatch(new vp(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Tp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Wp extends sp{constructor(e){super(Vo.Repair),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Fd.Capture}getPointerType(e){return e?this.isAllowed()?Ld.OccupyMini:Ld.NoActionMini:this.isAllowed()?Ld.RepairMove:Ld.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 jp(this.game,e)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof jp);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new br(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Up extends sp{constructor(e,t){super(t?Vo.GuardArea:Vo.Guard),this.game=e,this.targeted=t,this.getPointerType=e=>e?this.isAllowed()?Ld.GuardMini:Ld.NoActionMini:this.isAllowed()?Ld.Guard:Ld.NoMove,this.terminal=!0,this.targetOptional=!t,this.minimapAllowed=t,this.feedbackType=t?Fd.Move:Fd.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.sourceObject.rules.moveToShroud)}isAllowed(){return!0}process(){let t=this.targeted?this.target.tile:void 0;const e=this.sourceObject;if(!t&&e.isVehicle()&&e.harvesterTrait)return[new _s(()=>e.harvesterTrait.lastOreSite=void 0),new Wo(this.game,void 0,!0)];let i=[];return t&&i.push(new Us(this.game,t,!!this.target.getBridge(),{closeEnoughTiles:this.game.rules.general.closeEnough})),i.push(new _s(e=>{t&&![Hs.Success,Hs.CloseEnough].includes(this.sourceObject.moveTrait?.lastMoveResult)||(this.sourceObject.guardMode=!0)})),i}}class Vp extends sp{constructor(e){super(Vo.Scatter),this.game=e,this.getPointerType=()=>Ld.NoAction}isValid(){return(this.sourceObject.isInfantry()||this.sourceObject.isVehicle())&&this.sourceObject.rules.movementZone!==ii.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 Ds(this.game,{tile:this.target.tile,toBridge:!!this.target.getBridge()})]}}class zp{constructor(e){this.target=e,this.type=Xi.EnterTransport}}(s=Ud=Ud||{})[s.MoveToQueueingTile=0]="MoveToQueueingTile",s[s.WaitForTurn=1]="WaitForTurn",s[s.MoveToTransport=2]="MoveToTransport",s[s.EnterTransport=3]="EnterTransport",s[s.ClearTransport=4]="ClearTransport";class Hp extends Lr{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!==dr.Air&&this.target.zone!==dr.Air&&this.target.transportTrait.unitFitsInside(e)&&this.target.moveTrait.moveState===zs.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=Ud.MoveToQueueingTile:this.state=Ud.MoveToTransport}onEnd(e){this.target.isDestroyed||this.target.transportTrait?.removeFromLoadQueue(e)}onTick(n){if(this.isCancelling()&&this.state!==Ud.EnterTransport||this.state===Ud.ClearTransport||n.moveTrait.isDisabled())return!0;if(this.target.tile!==this.initialTargetTile||this.target.moveTrait.moveState!==zs.Idle)return!0;if(this.state===Ud.MoveToQueueingTile){let r=new Wr(this.game.map),s=this.target.onBridge?this.game.map.tileOccupation.getBridgeOnTile(this.target.tile):void 0,a;var e=new Pr(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)&&r.isEligibleTile(e,i,s,this.target.tile))return a=i,!0;return!1}).getNextTile();return!e||(this.children.push(new Us(this.game,e,!!a,{closeEnoughTiles:5})),this.children.push(new _s(()=>{[Hs.Success,Hs.CloseEnough].includes(n.moveTrait.lastMoveResult)||this.cancel()})),this.queueingNode={tile:e,onBridge:a},this.state=Ud.WaitForTurn,!1)}if(this.state===Ud.WaitForTurn){if(!this.target.transportTrait.unitIsFirstInLoadQueue(n))return!1;this.queueingNode=void 0,this.state=Ud.MoveToTransport}if(this.state===Ud.MoveToTransport){if(!this.isAllowed(n))return!0;if(!this.game.map.tileOccupation.isTileOccupiedBy(n.tile,this.target))return!!this.movePerformed||(this.children.push(new Tp(this.game,this.target)),this.movePerformed=!0,!(this.preventOpportunityFire=!0));this.state=Ud.EnterTransport}return this.state===Ud.EnterTransport&&(!this.isAllowed(n)||this.isCancelling()?(this.children.push(new wp(this.game,this.target)),this.state=Ud.ClearTransport,!1):(this.game.limboObject(n,{selected:!1,controlGroup:this.game.getUnitSelection().getOrCreateSelectionModel(n).getControlGroupNumber(),inTransport:!0}),this.game.events.dispatch(new zp(this.target)),this.game.events.dispatch(new vp(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 Gp extends sp{constructor(e){super(Vo.EnterTransport),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Fd.Enter}getPointerType(e){return e?this.isAllowed()?Ld.OccupyMini:Ld.NoActionMini:this.isAllowed()?Ld.Occupy:Ld.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!==dr.Air&&e.zone!==dr.Air&&e.transportTrait.unitFitsInside(t)&&e.moveTrait.moveState===zs.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 Hp(this.game,t)]:[new _s(()=>{t.unitOrderTrait.addTask(new Us(this.game,e.tile,e.onBridge)),t.unitOrderTrait.addTask(new _s(()=>{this.game.map.terrain.getPassableSpeed(t.tile,e.rules.speedType,e.onBridge)&&e.unitOrderTrait.addTask(new Hp(this.game,t))}))})]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof Hp);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new br(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class $p{constructor(e){this.target=e,this.type=Xi.BuildingCapture}}class qp extends Lr{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!==No.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 wp(this.game,this.target)),!(this.aborted=!0)):(this.game.unspawnObject(e),this.game.changeObjectOwner(this.target,e.owner),this.game.events.dispatch(new $p(this.target)),this.game.events.dispatch(new vp(this.target,e)),!0):!!this.movePerformed||(this.children.push(new Tp(this.game,this.target)),!(this.movePerformed=!0)))}getTargetLinesConfig(e){return{target:this.target,pathNodes:[]}}}class Zp extends sp{constructor(e){super(Vo.Capture),this.game=e,this.targetOptional=!1,this.terminal=!0,this.feedbackType=Fd.Capture}getPointerType(e){return e?this.isAllowed()?Ld.OccupyMini:Ld.NoActionMini:this.isAllowed()?Ld.Occupy:Ld.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 qp(this.game,this.target.obj)]}onAdd(t,e){if(!e){let e=t.find(e=>e instanceof qp);if(this.isValid()&&this.isAllowed()&&e&&!e.isCancelling()&&e.target===this.target.obj)if(new br(this.game.map.tileOccupation).isInTileRange(this.sourceObject,this.target.obj,0,Math.SQRT2))return!1}return!0}}class Qp{constructor(e,t){this.game=e,this.map=t}create(e,t){switch(e){case Vo.Deploy:return new gp(this.game,!0);case Vo.DeploySelected:return new gp(this.game,!1);case Vo.ForceMove:return new lp(this.game,this.map,t,!0);case Vo.Move:return new lp(this.game,this.map,t);case Vo.ForceAttack:return new Ep(this.game,{forceAttack:!0});case Vo.Attack:return new Ep(this.game,{noIvanBomb:!0});case Vo.PlaceBomb:return new Ep(this.game);case Vo.AttackMove:return new Mp(this.game,this.map);case Vo.Capture:return new Zp(this.game);case Vo.Occupy:return new Cp(this.game);case Vo.Stop:return new xp(this.game);case Vo.Cheer:return new Pp;case Vo.Dock:return new Np(this.game);case Vo.Gather:return new Rp(this.game);case Vo.Repair:return new Wp(this.game);case Vo.Guard:return new Up(this.game,!1);case Vo.GuardArea:return new Up(this.game,!0);case Vo.Scatter:return new Vp(this.game);case Vo.EnterTransport:return new Gp(this.game);default:throw new Error(`Unhandled order type ${Vo[e]}`)}}}class Xp{constructor(e,t,i){this.game=e,this.map=t,this.orderActionContext=i}create(){return new yp(this.game,this.map,this.orderActionContext,new Qp(this.game,this.map))}}class Yp{constructor(e){this.game=e}create(){return new Kl(this.game)}}class Kp{constructor(e){this.target=e,this.type=Xi.PlayerResigned}}class Jp extends Yl{constructor(e,t){super(ml.QuitGame),this.game=e,this.localPlayerName=t}process(){if(this.localPlayerName!==this.playerName){let e=this.game.getPlayerByName(this.playerName);this.game.removeAllPlayerAssets(e),e.isCombatant()&&(e.resigned=!0,this.game.events.dispatch(new Kp(e)))}}}class eg{constructor(e,t){this.game=e,this.localPlayerName=t}create(){return new Jp(this.game,this.localPlayerName)}}class tg{constructor(e){this.target=e,this.type=Xi.BuildingRepairStart}}class ig extends Yl{constructor(e){super(ml.ToggleRepair),this.game=e}unserialize(e){this.buildingId=Number(e[0])}serialize(){return[""+this.buildingId]}print(){return`Toggle repair ${this.buildingId}`}process(){var e=this.game.getPlayerByName(this.playerName);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 tg(t))}}}}class rg{constructor(e){this.game=e}create(){return new ig(this.game)}}class sg extends Yl{constructor(e){super(ml.ToggleAlliance),this.game=e}unserialize(e){this.toPlayerName=e[0],this.toggle=Boolean(Number(e[1]))}serialize(){return[this.toPlayerName,""+(this.toggle?1:0)]}print(){return`Toggle alliance ${this.toggle?"on":"off"} with ${this.toPlayerName}`}process(){var e=this.game.rules.mpDialogSettings;if(e.alliesAllowed&&e.allyChangeAllowed){var a,n=this.game.getPlayerByName(this.playerName),t=this.game.getPlayerByName(this.toPlayerName),e=this.toggle;let i=n,r=t,s=this.game.alliances;if(!n.defeated&&s.canRequestAlliance(r)){let t=s.findByPlayers(i,r);t?t.status===hl.Formed?e||(s.breakAlliance(i,r),this.game.onAllianceChange(t,i,!1)):t.status===hl.Requested&&(t.players.first===r?e&&s.canFormAlliance(i,r)&&(s.acceptRequest(r,i),this.game.onAllianceChange(t,i,!0),1!==(n=this.game.getCombatants().filter(e=>e!==i&&!s.areAllied(i,e))).length||(a=s.findByPlayers(n[0],i))&&s.cancelRequest(a.players.first,a.players.second),1!==(a=this.game.getCombatants().filter(e=>e!==r&&!s.areAllied(r,e))).length||(a=s.findByPlayers(a[0],r))&&s.cancelRequest(a.players.first,a.players.second)):e||(s.cancelRequest(i,r),this.game.events.dispatch(new Vc(t,Pc.Broken,i)),this.game.traits.filter(pl).forEach(e=>{e[pl.onChange](t,!1,this.game)}))):e&&s.canFormAlliance(i,r)&&((e=s.request(i,r))&&this.game.events.dispatch(new Vc(e,Pc.Requested,i)))}}}}class ag{constructor(e){this.game=e}create(){return new sg(this.game)}}class ng extends Yl{constructor(e){super(ml.ActivateSuperWeapon),this.game=e}unserialize(e){this.superWeaponType=Number(e[0]),this.tile={x:Number(e[1]),y:Number(e[2])},this.tile2=3<e.length?{x:Number(e[3]),y:Number(e[4])}:void 0}serialize(){return[this.superWeaponType,this.tile.x,this.tile.y,...this.tile2?[this.tile2.x,this.tile2.y]:[]].map(String)}print(){return`Activate SuperW ${Qi[this.superWeaponType]} at tile (${this.tile.x}, ${this.tile.y})`+(this.tile2?`, (${this.tile2.x}, ${this.tile2.y})`:"")}process(){var e,t=this.game.getPlayerByName(this.playerName),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(tn).activateSuperWeapon(this.superWeaponType,t,this.game,i,e)):console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}}class og{constructor(e){this.game=e}create(){return new ng(this.game)}}class hg{constructor(e,t){this.tile=e,this.player=t,this.type=Xi.PingLocation}}class lg extends Yl{constructor(e){super(ml.PingLocation),this.game=e}unserialize(e){this.tile={x:Number(e[0]),y:Number(e[1])}}serialize(){return[""+this.tile.x,""+this.tile.y]}print(){return`Ping location at tile (${this.tile.x}, ${this.tile.y})`}process(){var e=this.game.getPlayerByName(this.playerName),t=this.game.map.tiles.getByMapCoords(this.tile.x,this.tile.y);if(t){this.game.events.dispatch(new hg(t,e));for(var i of[e,...this.game.alliances.getAllies(e)])this.game.events.dispatch(new Ml(i,Zt.GenericNonCombat,t))}else console.warn(`Tile ${this.tile.x},${this.tile.y} doesn't exist`)}}class cg{constructor(e){this.game=e}create(){return new lg(this.game)}}class ug extends Yl{constructor(e){super(ml.ObserveGame),this.game=e}process(){let e=this.game.getPlayerByName(this.playerName);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 Kp(e)),this.game.events.dispatch(new $l(e)),this.game.mapShroudTrait.getPlayerShroud(e)?.revealAll(),t=e.radarTrait.isDisabled(),e.radarTrait.setDisabled(!1),t&&this.game.events.dispatch(new Dl(e,!0)))}}class dg{constructor(e){this.game=e}create(){return new ug(this.game)}}class pg{register(e,t,i){var r=new $d;e.registerFactory(ml.NoAction,new Zd),e.registerFactory(ml.PlaceBuilding,new Kd(t)),e.registerFactory(ml.SellBuilding,new ep(t)),e.registerFactory(ml.ToggleRepair,new rg(t)),e.registerFactory(ml.SelectUnits,new ip(t,r)),e.registerFactory(ml.OrderUnits,new Xp(t,t.map,r)),e.registerFactory(ml.UpdateQueue,new Yp(t)),e.registerFactory(ml.ToggleAlliance,new ag(t)),e.registerFactory(ml.ActivateSuperWeapon,new og(t)),e.registerFactory(ml.PingLocation,new cg(t)),e.registerFactory(ml.QuitGame,new eg(t,i)),e.registerFactory(ml.ObserveGame,new dg(t))}}var gg=__webpack_require__(949);class mg{constructor(){this.detectors=new Set}[cl.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.detect(e,t)}[ul.onUnspawn](e,t){e.isTechno()&&(this.isGlobalDetector(e)&&(this.detectors.delete(e),this.updateAroundDetector(e,t)),this.isDisguisable(e)&&this.undetect(e,t))}[dl.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isDisguisable(e)&&(this.undetect(e,i),this.detect(e,i))}[Fs.onTileChange](e,t,i){if(this.isGlobalDetector(e))throw new Error("Detector units not implemented");this.isDisguisable(e)&&(this.undetect(e,t),this.detect(e,t))}[Ar.onPowerLow](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait&&!e.poweredTrait.isPoweredOn());this.updateAroundDetectors(i,e)}[Ar.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[Ar.onPowerChange](e,t){}updateAroundDetectors(e,t){let i=new Set;for(var r of e)for(var s of this.findTechnosAroundDetector(r,t))i.add(s);for(var a of i)this.isDisguisable(a)&&(this.undetect(a,t),this.detect(a,t))}updateAroundDetector(e,t){var i;for(i of this.findTechnosAroundDetector(e,t))this.isDisguisable(i)&&(this.undetect(i,t),this.detect(i,t))}findTechnosAroundDetector(e,t){var i=e.getFoundation(),r=Math.max(i.width,i.height),i=e.rules.detectDisguiseRange+r,r=new gg.Vector2(e.tile.rx,e.tile.ry).addScalar(-i),i=new gg.Vector2(e.tile.rx,e.tile.ry).addScalar(i);return t.map.technosByTile.queryRange(new gg.Box2(r,i))}detect(e,t){let i=new Set,r=new br(t.map.tileOccupation);for(var s of this.detectors)if(!t.areFriendly(s,e)){var a=s.owner,n=s.rules.detectDisguiseRange;if(!i.has(a))if(!(s.isBuilding()&&s.poweredTrait&&!s.poweredTrait.isPoweredOn())&&r.tileDistance(e,s.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)}}var fg=__webpack_require__(949);class yg{constructor(){this.detectors=new Set}[cl.onSpawn](e,t){this.isGlobalDetector(e)&&(this.detectors.add(e),this.updateAroundDetector(e,t)),this.isCloakable(e)&&this.detect(e,t)}[ul.onUnspawn](e,t){e.isTechno()&&this.isGlobalDetector(e)&&this.detectors.delete(e)}[dl.onChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,i),this.isCloakable(e)&&this.detect(e,i)}[Fs.onTileChange](e,t,i){this.isGlobalDetector(e)&&this.updateAroundDetector(e,t),this.isCloakable(e)&&this.detect(e,t)}[zc.onAdd](e,t,i){e.isTechno()&&(t instanceof sn?this.isCloakable(e)&&this.detect(e,i):t instanceof Ph&&this.isGlobalDetector(e)&&this.updateAroundDetector(e,i))}[Ar.onPowerLow](e,t){}[Ar.onPowerRestore](t,e){var i=[...this.detectors].filter(e=>e.owner===t&&e.isBuilding()&&e.poweredTrait);this.updateAroundDetectors(i,e)}[Ar.onPowerChange](e,t){}[_r.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 r of e)for(var s of this.findTechnosAroundDetector(r,t))i.add(s);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(),r=Math.max(i.width,i.height),i=e.rules.sensorsSight+r,r=new fg.Vector2(e.tile.rx,e.tile.ry).addScalar(-i),i=new fg.Vector2(e.tile.rx,e.tile.ry).addScalar(i);return t.map.technosByTile.queryRange(new fg.Box2(r,i))}detect(e,t){let i=new br(t.map.tileOccupation);for(var r of this.detectors)if(!t.areFriendly(r,e)){var s=r.rules.sensorsSight;if(!(r.isBuilding()&&r.poweredTrait&&!r.poweredTrait.isPoweredOn())&&i.tileDistance(e,r.tile)<=s){s=e.cloakableTrait?.isCloaked();if(e.cloakableTrait.uncloak(t),s)for(var a of[r.owner,...t.alliances.getAllies(r.owner)])t.traits.get(Ll).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 wg{constructor(){this.type=Xi.StalemateDetect}}class Tg{constructor(){this.stale=!1,this.allPlayersCredits=new Map,this.resetCountdown()}isStale(){return this.stale}getCountdownTicks(){return this.countdownTicks}resetCountdown(){this.countdownTicks=Math.floor(60*Tg.graceMinutes*xr.BASE_TICKS_PER_SECOND)}clearStale(){this.stale=!1,this.resetCountdown()}[_r.onTick](e){0<this.countdownTicks?this.countdownTicks--:this.stale||(this.stale=!0,this.resetCountdown(),e.events.dispatch(new wg));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())}}[Fn.onProduce](){this.clearStale()}[Md.onPlace](e){e.wallTrait||this.clearStale()}[gl.onDestroy](e,t,i){!e.isBuilding()||e.owner.isNeutral||e.wallTrait||e.rules.insignificant||i?.obj&&t.areFriendly(e,i.obj)||this.clearStale()}[dl.onChange](e,t,i){e.isBuilding()&&!t.isNeutral&&(i.alliances.areAllied(e.owner,t)||this.clearStale())}}Tg.graceMinutes=5;var bg,vg,Sg=__webpack_require__(949);class _g{constructor(e){this.prng=e}static factory(e,t){return new this(new $c(Number(e+""+t)))}generateColors(e){let t=[...e.humanPlayers,...e.aiPlayers].filter(ga),i=t.map(e=>e.colorId).filter(e=>-2!==e);e=dn.length;let r=new Array(e).fill(0).map((e,t)=>t).filter(e=>!i.includes(e)),s=new Map;return t.forEach(e=>{if(-3!==e.countryId&&-2===e.colorId){if(r.length<1)throw new Error("Out of available colors to choose from");var t=this.prng.generateRandomInt(0,r.length-1);s.set(e,r[t]),r.splice(t,1)}}),s}generateCountries(e,t){let i=t.getMultiplayerCountries().length,r=[...e.humanPlayers,...e.aiPlayers].filter(ga),s=new Map;return r.forEach(e=>{-2===e.countryId&&s.set(e,this.prng.generateRandomInt(0,i-1))}),s}generateStartLocations(i,r){let e=[...i.humanPlayers,...i.aiPlayers].filter(ga),t=e.filter(e=>-2!==e.startPos).map(e=>e.startPos),s=[...r.keys()].filter(e=>!t.includes(e)),a=[];for(;s.length;){var n=s.length?this.prng.generateRandomInt(0,s.length-1):0;a.push(...s.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=>r[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=>r[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 r=e.map(e=>new Sg.Vector2(e.x,e.y)),s,a=0;if(!t.length)throw new Error("Search array must have at least one element");for(var n of t){let i=new Sg.Vector2(n.x,n.y);var o=r.reduce((e,t)=>e+i.distanceTo(t),0);o>=a&&(s=n,a=o)}return s}}class kg{constructor(e,t){this.mapLighting=new mi,this._onChange=new Pn,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}[_r.onTick](){var e;void 0!==this.targetAmbient&&(this.ambientUpdateTicks??(this.ambientUpdateTicks=Math.floor(60*xr.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 Og{constructor(e,t,i,r,s,a){this.game=e,this.inputActions=t,this.replayRecorder=i,this.actionSerializer=r,this.actionFactory=s,this.actionLogger=a,this.errorState=!1}init(){this.gameTurnMillis=1e3/(this.game.speed.value*xr.BASE_TICKS_PER_SECOND)}setErrorState(){this.errorState=!0}getErrorState(){return this.errorState}getTurnMillis(){return this.gameTurnMillis}doGameTurn(){if(!this.errorState){if(this.game.status!==Hc.Ended){var t,e=this.inputActions.dequeueAll();const r=new Map;for(t of e){var i=this.actionSerializer.getActionPayload(t);let e=r.get(t.playerName);e||(e=[],r.set(t.playerName,e)),e.push(i)}this.replayRecorder.recordActions(this.game.currentTick,r),r.forEach((t,i)=>{if(!t.length){let e=new qd;e.playerName=i,t.push(this.actionSerializer.getActionPayload(e))}}),this.processActions(r)}this.game.update()}}processActions(e){[...e].forEach(([i,e])=>e.forEach(e=>{let t=this.actionFactory.create(e.id);t.playerName=i,t.unserialize(e.params),t.process();e=t.print();e&&this.actionLogger?.debug(`(${i}): ${e}`)}))}dispose(){}}(s=bg=bg||{})[s.Closed=0]="Closed",s[s.Open=1]="Open",s[s.OpenObserver=2]="OpenObserver",s[s.Player=3]="Player",s[s.Ai=4]="Ai";class Ig{encode(e){let r=[],s=0;return e.split("").forEach((e,t)=>{var i=e.charCodeAt(0)<<2*t-7*s,e=127&i,t=i>>7&127,i=i>>14&127;i&&s++,r.push(e,t),i&&r.push(i)}),r.push(0,0),2<=e.length&&r.push(0),r=r.map(e=>128^e),r.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 r=[],s=0,a=0;for(;i.length;){var n=r.length,o=i.shift(),h=i.shift();let e=0,t=!1;(-1!==[1,2,3].indexOf(i[0])||n>s+3)&&(e=i.shift(),s=n,t=!0);n=(e<<14|h<<7|o)>>2*n-7*a;r.push(127&n),t&&a++}return r.map(e=>String.fromCharCode(e)).join("")}}class Ag{encode(e){return e.match(/^[a-z0-9-_]+\.[a-z]{3}$/i)?e:P.encode(L(e))}decode(e){return e.match(/\.[a-z]{3}$/i)?e:F(P.decode(e))}}class Cg{serializeOptions(e){let t=e.gameMode,i=(new Ig).encode(e.mapTitle),r=(new Ag).encode(e.mapName);var s=["0","0",6-e.gameSpeed,e.credits,e.unitCount,Number(e.shortGame),Number(e.superWeapons),Number(e.buildOffAlly),Number(e.mcvRepacks),Number(e.cratesAppear),t,"0",i,e.maxSlots,Number(e.mapOfficial),e.mapSizeBytes,r,e.mapDigest].join(",");return`${s}:${e.humanPlayers.map(e=>`${e.name},${e.countryId},${e.colorId},${e.startPos},${e.teamId},0,0,0`).join(",")}:@:${e.aiPlayers.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===fr.Easy)return"@EasyAI@";if(e.difficulty===fr.Medium)return"@MediumAI@";if(e.difficulty===fr.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].join(",")).join(",")}serializePlayerActions(e){return e.map(e=>e.id+"."+e.params.join(".")).join(";")}serializeAllPlayerActions(e,t){return e+"="+[...t].map(([e,t])=>{return`${e}:${this.serializePlayerActions(t)}`}).join("$")}serializeMapData(e){return e.replace(/\n/g,"")}}class Bg{parseOptions(e){let i={},[t,r,,s]=e.split(":"),a=t.split(",");a.shift(),a.shift(),i.gameSpeed=6-Number(a.shift()),i.credits=Number(a.shift()),i.unitCount=Number(a.shift()),i.shortGame=Boolean(Number(a.shift())),i.superWeapons=Boolean(Number(a.shift())),i.buildOffAlly=Boolean(Number(a.shift())),i.mcvRepacks=Boolean(Number(a.shift())),i.cratesAppear=Boolean(Number(a.shift())),i.gameMode=Number(a.shift()),a.shift(),i.mapTitle=(new Ig).decode(a.shift()),i.maxSlots=Number(a.shift()),i.mapOfficial=Boolean(Number(a.shift())),i.mapSizeBytes=Number(a.shift()),i.mapName=(new Ag).decode(a.shift()),i.mapDigest=a.shift();var n=r.split(",");if(n.length%8!=0)throw new Error(`Couldn't parse gameopt: unexpected players data length ${n.length}`);i.humanPlayers=[];for(let e=0,t=Math.floor(n.length/8);e<t;++e){var o={name:n[8*e],countryId:Number(n[8*e+1]),colorId:Number(n[8*e+2]),startPos:Number(n[8*e+3]),teamId:Number(n[8*e+4])};i.humanPlayers.push(o)}var h=s.slice(0,-1).split(",");if(h.length%5!=0)throw new Error(`Couldn't parse gameopt: unexpected ai data length ${h.length}`);i.aiPlayers=[];for(let e=0,t=Math.floor(h.length/5);e<t;++e){var l={difficulty:Number(h[5*e]),countryId:Number(h[5*e+1]),colorId:Number(h[5*e+2]),startPos:Number(h[5*e+3]),teamId:Number(h[5*e+4])};i.aiPlayers.push(-1!==l.countryId?l:void 0)}return 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 r=[];for(let e=0,t=Math.floor(i.length/2);e<t;++e)r.push({playerName:i[2*e],ping:Number(i[2*e+1])});return r}parseSlotData(e){var i;let r=[];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=fr.Easy;else if("@MediumAI@"===i)e=fr.Medium;else{if("@HardAI@"!==i)throw new Error(`Couldn't parse gameopt: unknown slot type ${i}`);e=fr.Brutal}t.difficulty=e}else t.type=bg.Player,t.name=i;r.push(t)}return r}parsePlayerActions(e){return e.split(";").map(e=>{var[t,...e]=e.split(".");return{id:Number(t),params:""!==e[0]?e:[]}})}parseAllPlayerActions(e){let i=new Map,[t,r]=e.split("=");return r.split("$").map(e=>{var[t,e]=e.split(":");i.set(t,this.parsePlayerActions(e))}),{turn:Number(t),actions:i}}parseMapData(e){return e.replace(/[\x1F]/g,"\n")}}class Eg{constructor(e,t){this.type=e,this.tickNo=t}}(s=vg=vg||{})[s.TurnActions=0]="TurnActions",s[s.ChatMessage=1]="ChatMessage",s[s.Taunt=2]="Taunt";class xg extends Eg{constructor(e){super(vg.ChatMessage,e)}serialize(){return this.payload.playerId+":"+P.encode(L(this.payload.message))}unserialize(e){var[t,e]=e.split(":"),t=Number(t),e=F(P.decode(e));this.payload={playerId:t,message:e}}}class Pg extends Eg{constructor(e){super(vg.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 Ng extends Eg{constructor(e,t,i){super(vg.TurnActions,i),this.gameOptsParser=e,this.gameOptsSerializer=t}serialize(){return this.payload.map(([e,t])=>{return`${e}:${this.gameOptsSerializer.serializePlayerActions(t)}`}).join("$")}unserialize(e){let t=[];for(var i of e.split("$")){var[r,i]=i.split(":"),i=this.gameOptsParser.parsePlayerActions(i);t.push([Number(r),i])}this.payload=t}}class Rg{constructor(e,t){this.gameOptsParser=e,this.gameOptsSerializer=t}create(e,t){switch(e){case vg.TurnActions:return new Ng(this.gameOptsParser,this.gameOptsSerializer,t);case vg.ChatMessage:return new xg(t);case vg.Taunt:return new Pg(t);default:throw new Error(`Unsupported replay event type "${e}" at game tick "${t}"`)}}}const Dg=[3,4];class Mg{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,r,s){this.gameId=e,this.gameTimestamp=t,this.gameOpts=i,this.engineVersion=r,this.modHash=s,this.name=Mg.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}serialize(){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");if(void 0===this.endTick)throw new Error("Replay is not finished");let e=new Cg,t=this.getHeaderTag()+"\n";t+=`ENGINE ${this.engineVersion} ${this.modHash}\n`,t+=[this.gameId,this.gameTimestamp,P.encode(e.serializeOptions(this.gameOpts))].join(" ")+"\n";for(var i of this.events)t+=i.tickNo+"="+i.type+"|"+i.serialize()+"\n";return t+=this.getEndTag()+" "+this.endTick+"\n",this.debugInfo&&(t+=P.encode(L(this.debugInfo))+"\n"),t}async parseHeader(e){let t=0,i,r,s,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:r,done:s}=await i.read();r=r?t.decode(r,{stream:!0}):"";let a=/\r\n|\n|\r/gm,n=0;for(;;){var o=a.exec(r);if(o)yield r.substring(n,o.index),n=a.lastIndex;else{if(s)break;o=r.substr(n);({value:r,done:s}=await i.read()),r=o+(r?t.decode(r,{stream:!0}):""),n=a.lastIndex=0}}n<r.length&&(yield r.substr(n))}(e)){if(0===t)i=this.readReplayVersion(h);else if(1===t){if(!h.match(Mg.engineLineRegex))throw new Error("Missing or invalid game engine version line");var l=h.split(" ");r=l[1],s=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=P.decode(l)}t++}if(t<3)throw new Error("Bad replay header");return{replayVersion:i,engineVersion:r,modHash:s,gameId:a,gameTimestamp:n,gameOptsSerialized:o}}unserialize(e,t){let i=e.split("\n");var r=this.readReplayVersion(i.shift()||"");if(!Dg.includes(r))throw new Error("Unsupported replay version");let s=new Bg,a=i.shift();if(!a||!a.match(Mg.engineLineRegex))throw new Error("Missing or invalid game engine version line");let[,n,o]=a.split(" ");r<4&&(o="0");let h=i.shift();if(!h||!h.match(/^\d+ \d+ .*$/))throw new Error("Missing or invalid game id/time/opts line");var[l,e,r]=h.split(" "),r=s.parseOptions(P.decode(r));this.init(Number(l),Number(e),r,n,Number(o)),this.name=t.name,this.timestamp=t.timestamp;let c,u=!1;for(;c=i.shift();){if(c.startsWith(this.getEndTag())){u=!0;break}var d=c.match(/^(\d+)=(\d+)\|(.+)$/);if(!d)throw new Error(`Invalid event line "${c}"`);var[,p,g,d]=d,p=Number(p),g=Number(g);let e=new Rg(s,new Cg).create(g,p);e.unserialize(d),this.writeEvent(e)}if(!u)throw new Error("Incomplete replay data");t=c.match(new RegExp(`^${this.getEndTag()} (\\d+)$`));if(!t)throw new Error("Invalid end tag");this.endTick=Number(t[1]),1<=i.length&&(this.debugInfo=F(P.decode(i[0])))}getHeaderTag(){return"RA2TSREPL_v4"}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"}}Mg.extension=".rpl",Mg.maxNameLength=128,Mg.engineLineRegex=/^ENGINE \d+\.\d+( \d+)?$/;class Lg{constructor(e,t,i,r){this.replay=e,this.playerId=t,this.humanPlayers=i,this.actionSerializer=r}recordActions(t,i){if(Array.isArray(i)){let e=new Ng(new Bg,new Cg,t);e.payload=[[this.playerId,i.map(e=>this.actionSerializer.getActionPayload(e))]],this.replay.writeEvent(e)}else if(this.hasActualActions(i)){let e=new Ng(new Bg,new Cg,t);e.payload=[...i].map(([t,e])=>[this.humanPlayers.findIndex(e=>e.name===t),e]),this.replay.writeEvent(e)}}recordChatMessage(e,t,i){let r=new xg(e);r.payload={playerId:this.humanPlayers.findIndex(e=>e.name===t),message:i},this.replay.writeEvent(r)}recordTaunt(e,t,i){let r=new Pg(e);r.payload={playerId:this.humanPlayers.findIndex(e=>e.name===t),tauntNo:i},this.replay.writeEvent(r)}hasActualActions(e){return!![...e.values()].find(e=>e.find(e=>e.id!==ml.NoAction))}}class Fg{getActionPayload(e){return{id:e.actionType,params:e.serialize()}}}class jg{constructor(e,t){this.options=e,this.logger=t,this.timeout=5,this._onMessage=new Pn,this._onError=new Pn,this._onClose=new Pn}get onMessage(){return this._onMessage.asEvent()}get onError(){return this._onError.asEvent()}get onClose(){return this._onClose.asEvent()}async connect(r){return new Promise((e,t)=>{this.socket=new WebSocket(r),"binary"===this.options.mode&&(this.socket.binaryType="blob");let i=e=>{this.socket.removeEventListener("error",i),t(new jg.ConnectError(`Connection to "${r}" 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){this.logger.debug("Got message:",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(r){return new Promise((e,t)=>{let i=new FileReader;i.onload=()=>e(i.result),i.onerror=()=>t(),i.readAsBinaryString(r)})}sendCommand(u,d){if(d.replyStartCode&&!d.replyEndCode)throw new Error("Invalid argument. Expected a reply end code, but got only a start code.");return new Promise((t,i)=>{let r=[],s,a=e=>{clearTimeout(s),t(e)},n=e=>{this.socket.removeEventListener("message",c),this.socket.removeEventListener("close",o),clearTimeout(s),s=void 0,i(e)};let o=()=>{n(new jg.SocketError("Connection was closed prematurely"))},h=e=>e.split(/\r?\n/).filter(e=>!!e).some(e=>(e=>{if(!d.replyEndCode&&!d.replyCodes)return a([{raw:e}]),!0;var[,t,...i]=e.split(" "),t=parseInt(t,10),i={raw:e,code:t,params:i};if(d.replyEndCode)return d.replyCodes&&-1!==d.replyCodes.indexOf(t)?(a([i]),!0):((t===d.replyStartCode||d.replyBodyCodes&&-1!==d.replyBodyCodes.indexOf(t)||t===d.replyEndCode)&&r.push(i),t===d.replyEndCode&&(a(r),!0));if(void 0===d.replyCodes)throw new Error("List of replyCodes must be specified when not using start/end codes");return-1!==d.replyCodes.indexOf(t)&&(a([i]),!0)})(e)),l=!1,c=e=>{l||(globalThis.Blob&&e.data instanceof Blob?this.parseData(e.data).then(e=>{l||h(e)&&(l=!0,this.socket.removeEventListener("message",c),this.socket.removeEventListener("close",o))}).catch(e=>{console.error("Failed to decode socket message.",e)}):h(e.data)&&(l=!0,this.socket.removeEventListener("message",c),this.socket.removeEventListener("close",o)))};if(this.socket&&this.socket.readyState===WebSocket.OPEN){var e=(void 0!==d.timeout?d:this).timeout;s=setTimeout(()=>{n(new jg.NoReplyError(`Timeout reached for command ${u}`))},1e3*e),this.socket.addEventListener("message",c),this.socket.addEventListener("close",o);try{this.sendMessage(u)}catch(e){n(e)}}else n(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.debug("Sent message:",e),e+="\r\n";let t;t="binary"===this.options.mode?D(e):e,this.socket.send(t)}close(){this.socket&&this.socket.close()}isOpen(){return this.socket&&this.socket.readyState===WebSocket.OPEN}}jg.MAX_CHANNELNAME_LEN=30,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 r extends Error{constructor(e){super(e)}}e.ConnectError=r}(jg=jg||{});class Wg extends Error{constructor(e,t){super(e),this.code=t}}(s=(s=Wg=Wg||{}).Code||(s.Code={}))[s.InstanceNonExistent=0]="InstanceNonExistent",s[s.InstanceAlreadyExists=1]="InstanceAlreadyExists";var Ug;(s=Ug=Ug||{})[s.Public=0]="Public",s[s.Private=1]="Private",s[s.Page=2]="Page";class Vg{constructor(e,t,i,r,s,a,n,o,h,l,c,u){this.game=e,this.gservCon=t,this.gameoptParser=i,this.gameoptSerializer=r,this.actionSerializer=s,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.lagState=!1,this._onLagStateChange=new Pn,this._onActionsSent=new Pn,this._onActionsProcessed=new Pn,this._onActionsReceived=new Pn,this.receiveActions=e=>{var t=this.gameoptParser.parseAllPlayerActions(e);this.receivedActions.set(t.turn,t.actions),this.debug(`Recv actions: ${e}`),this._onActionsReceived.dispatch(void 0,t.turn)},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*xr.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(Vg.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!==Hc.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.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();if(e.length||e.push(new qd),e.some(e=>e.actionType===ml.QuitGame))return this.setErrorState(),void this.debug("Send actions: quit");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.playerName=i,t.unserialize(e.params),t.process();e=t.print();e&&this.actionLogger?.debug(`(${i}): ${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)}}Vg.PREFERRED_HASH_CHECK_MILLIS=1e3;const zg=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks");class Hg{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=zg.performance.now(),r=this.updateDeltaGameFrames(i);if(0<r)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 r=0;return this.startTime?(i=e-this.startTime,t=Math.round(i/t),r=t-this.lastGameFrame,this.lastGameFrame=t):this.startTime=e,r}stop(){this.isStarted&&(this.isStarted=!1)}destroy(){this.stop()}}const Gg=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");var $g,qg,Zg,Qg,Xg,Yg,Kg,Jg,em=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i},tm=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)};class im{constructor(e,t,i,r,s,a,n,o){$g.set(this,void 0),qg.set(this,void 0),Zg.set(this,void 0),Qg.set(this,void 0),Xg.set(this,void 0),Yg.set(this,void 0),Kg.set(this,void 0),Jg.set(this,void 0),em(this,$g,e,"f"),em(this,qg,t,"f"),em(this,Zg,new Bc(t,!1),"f"),em(this,Qg,new uc(t.events),"f"),em(this,Xg,i,"f"),em(this,Yg,a,"f"),em(this,Kg,n,"f"),em(this,Jg,o,"f"),tm(this,Qg,"f").subscribe(t=>e.forEach(e=>e.onGameEvent(t,tm(this,Zg,"f")))),e.forEach(e=>{e.setGameApi(tm(this,Zg,"f")),e.setActionsApi(new tc(t,r,s,e.name)),e.setProductionApi(new jc(t.getPlayerByName(e.name).production)),e.onGameStart(tm(this,Zg,"f"))})}isFinished(){return tm(this,qg,"f").status===Hc.Ended||tm(this,Yg,"f").getErrorState()}async update(){if(tm(this,Kg,"f"))await tm(this,Kg,"f").waitForTick();else{if(!(tm(this,Yg,"f")instanceof Og))throw new Error("Missing animation loop or turn manager");tm(this,Yg,"f").doGameTurn()}tm(this,$g,"f").forEach(e=>e.onGameTick(tm(this,Zg,"f")))}getCurrentTick(){return tm(this,Zg,"f").getCurrentTick()}getTickRate(){return tm(this,Zg,"f").getTickRate()}getPlayerStats(){return tm(this,qg,"f").getNonNeutralPlayers().filter(e=>!e.isObserver).map(t=>({name:t.name,country:t.country,ai:t.isAi||tm(this,$g,"f").some(e=>e.name===t.name),defeated:t.defeated,credits:t.credits,startLocation:t.startLocation}))}saveReplay(e){let t=tm(this,Xg,"f");t.finish(tm(this,qg,"f").currentTick);var i=`${tm(this,qg,"f").gameOpts.mapName}_${Date.now()}${Mg.extension}`,r=t.serialize(),i=a.resolve(e??process.cwd(),i);Gg.writeFileSync(i,r,"utf-8"),process.stdout.write(`Replay saved to "${i}"\n`)}dispose(){tm(this,Qg,"f").dispose(),tm(this,$g,"f").length=0,tm(this,Jg,"f")?.call(this)}}$g=new WeakMap,qg=new WeakMap,Zg=new WeakMap,Qg=new WeakMap,Xg=new WeakMap,Yg=new WeakMap,Kg=new WeakMap,Jg=new WeakMap;var rm,sm,am,nm,om,hm,lm,cm,um,dm,pm,gm,mm=function(e,t,i,r){if("a"===i&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===i?r:"a"===i?r.call(e):r?r.value:t.get(e)},fm=function(e,t,i,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(e,i):s?s.value=i:t.set(e,i),i};const ym=a.resolve((0,e.default)(),"./res");class wm{constructor(){rm.add(this),sm.set(this,void 0),am.set(this,void 0),nm.set(this,void 0),om.set(this,void 0),hm.set(this,!1),lm.set(this,void 0)}async init(e){mm(this,rm,"m",cm).call(this);var t=await(0,n.getOriginPrivateDirectory)(o.default,a.resolve(e)),i=await(0,n.getOriginPrivateDirectory)(o.default,ym),e=await(0,n.getOriginPrivateDirectory)(o.default,process.cwd());xt.initGameResSource(bt.Local);let r=await xt.initRfs(t);r.addDirectoryHandle(i),r.addDirectoryHandle(e);let s=await xt.initVfs(r,Kr.get("vfs"));await s.loadStandaloneFiles(),await s.loadExtraMixFiles(xt.getActiveEngine()),await s.addMixFile("ra2cd.mix"),await s.loadImplicitMixFiles(xt.getActiveEngine()),xt.loadRules(),fm(this,lm,await xt.loadMapList(),"f"),fm(this,sm,xt.getMpModes(),"f"),fm(this,hm,!0,"f")}getAvailableMaps(){if(!mm(this,hm,"f"))throw new Error("API is not initialized. Call init() first.");return mm(this,lm,"f").getAll().map(e=>e.fileName.toLowerCase())}getAvailableGameModes(e){if(!mm(this,hm,"f"))throw new Error("API is not initialized. Call init() first.");let t=mm(this,lm,"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?mm(this,rm,"m",dm):mm(this,rm,"m",um)).call(this,e)}}sm=new WeakMap,am=new WeakMap,nm=new WeakMap,om=new WeakMap,hm=new WeakMap,lm=new WeakMap,rm=new WeakSet,cm=function(){Kr.useDefaults(),Kr.setLevel(Kr.ERROR);const e=process.env.DEBUG_LOGGING;var t;if(e)if(isNaN(e))for(t of e.split(","))Kr.get(t).setLevel(Kr.DEBUG);else Kr.setLevel(Boolean(Number(e))?Kr.DEBUG:Kr.ERROR);fm(this,am,Kr.get("ini"),"f"),fm(this,nm,Kr.get("action"),"f"),fm(this,om,Kr.get("net"),"f")},um=async function(e){if(!mm(this,hm,"f"))throw new Error("API is not initialized. Call init() first.");var t=mm(this,rm,"m",gm).call(this,e),i=e.agents.filter(e=>e instanceof Wc),r=new wi(xt.vfs.openFile(t.mapName)),s=await mm(this,rm,"m",pm).call(this,0,0,t,r,void 0),a=new Xl,e=new Hd;(new pg).register(e,s,void 0);let n=new Mg;n.init(s.id,s.startTimestamp,t,xt.getVersion(),xt.getModHash());r=new Fg,t=new Lg(n,0,s.gameOpts.humanPlayers,r);let o=new Og(s,a,t,r,e,mm(this,nm,"f"));return o.init(),new im(i,s,n,e,a,o)},dm=async function(e){if(!mm(this,hm,"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 Wc&&t.push(i)}if(!(e.agents[0]instanceof Wc))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 Wc))throw new Error("Only the first player in the agents array can be a bot in online mode");var r=mm(this,rm,"m",gm).call(this,e);let s=class{constructor(e){this._onLoadInfo=new Pn,this._onGameStart=new Pn,this._onGameActions=new Pn,this._onGameDesync=new Pn,this._onRateChange=new Pn,this._onChatMessage=new Pn,this._onTaunt=new Pn,this.handleMessage=e=>{let t=e.split(" ");var i;"ping"===t[0]?this.isOpen()&&this.con.sendMessage("pong"):"privmsg"===t[1].toLowerCase()?this.handlePrivMsg(e):"page"===t[1].toLowerCase()?this.handlePage(e):"600"===t[1]?this.handleLoadInfo(t[3]):"700"===t[1]?this.handleGameStart():"800"===t[1]?this.handlePlayerActions(t[3]):"801"===t[1]?this._onGameDesync.dispatch(this):"802"===t[1]?([i,e]=t[3].slice(1).split(","),this._onRateChange.dispatch(this,{rate:Number(i),turnNo:Number(e)})):"803"===t[1]&&this._onTaunt.dispatch(this,{from:t[0].replace(/^:/,""),tauntNo:Number(t[3].replace(/^:/,""))})},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()}static factory(e){return new this(new jg({mode:"text"},e))}getCurrentUser(){return this.currentUser}async connect(e){return this.con.onMessage.subscribe(this.handleMessage),this.con.connect(e)}close(){this.con.onMessage.unsubscribe(this.handleMessage),this.con.close(),this.currentUser=void 0}isOpen(){return this.con.isOpen()}async login(e){await this.con.sendCommand(`user ${e}`,{replyCodes:[100]}),this.currentUser=e}async createGame(e,t,i,r,s){let a=await this.con.sendCommand(`create ${e} ${t} ${P.encode(i)} ${r} ${s}`,{replyCodes:[200,201]});if(201===a[0].code){s=a[0].params?a[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new Wg(`Create error: ${s}`,Wg.Code.InstanceAlreadyExists)}}async joinGame(e,t,i){let r=await this.con.sendCommand(`join ${e} ${t} ${i}`,{replyCodes:[400,401]});if(401===r[0].code){i=r[0].params?r[0].params.splice(1).join(" ").replace(/^:/,""):"unknown";throw new Wg(`Join error: ${i}`,Wg.Code.InstanceNonExistent)}}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 P.decode(e[0].params.splice(1).join(" ").replace(/^:/,""))}sendLoadedPercent(e){this.con.sendMessage(`loaded ${e}`)}requestLoadInfo(){this.con.sendMessage("loadinfo")}sendGameStateHash(e,t){this.con.sendMessage(`h ${e} ${t}`)}sendPlayerActive(e){this.con.sendMessage(`active ${e?1:0}`)}sendTaunt(e){this.con.sendMessage(`taunt ${e}`)}async ping(e){return this.con.sendCommand("ping",{replyCodes:[900],timeout:e})}sendPlayerActions(e,t){this.con.sendMessage(`a ${e} ${t}`)}sendMap(e){this.con.sendMessage(`putmap :${(new Cg).serializeMapData(e)}`)}async getMap(){let e=await this.con.sendCommand("getmap",{replyCodes:[601],timeout:15});if(!e[0].params)throw new Error("Unexpected server reply for getmap command. Missing params.");return(new Bg).parseMapData(e[0].params.splice(1).join(" ").replace(/^:/,""))}handleLoadInfo(e){this._onLoadInfo.dispatch(this,e.replace(/^:/,""))}handleGameStart(){this._onGameStart.dispatch(this,void 0)}handlePlayerActions(e){this._onGameActions.dispatch(this,e.slice(1))}sayChannel(e){this.privmsg(["#all"],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,e,t]=t;let r;"#all"===e?r={type:Ug.Public,from:i,text:t}:e===this.currentUser&&(r={type:Ug.Private,from:i,text:t}),r&&this._onChatMessage.dispatch(this,r)}handlePage(e){var t=e.match(/^:([A-Za-z0-9-_]+) PAGE [A-Za-z0-9-_#']+ :(.*)/i);if(!t)throw new Error(`Unexpected PAGE message format "${e}"`);var[,e,t]=t,e={text:t,from:e,type:Ug.Page};this._onChatMessage.dispatch(this,e)}}.factory(mm(this,om,"f"));await s.connect(e.serverUrl),await s.login(e.agents[0].name);let a=new Cg;var n=a.serializeOptions(r),o=Date.now(),h=Number(o+"0");await s.createGame(h,0,n,xt.getVersion(),xt.getModHash()),await s.joinGame(h,xt.getVersion(),xt.getModHash());let l=new Bg;var c=l.parseOptions(await s.gameOpts());let u=xt.vfs.openFile(r.mapName);var d=new wi(u);r.mapOfficial||s.sendMap(u.readAsString());n=e.agents[0].name;let p=await mm(this,rm,"m",pm).call(this,h,0,c,d,n);r=new Fg,h=new Xl,d=new Hd;(new pg).register(d,p,n);let g=new Mg;g.init(p.id,p.startTimestamp,c,xt.getVersion(),xt.getModHash());var m,c=new Lg(g,0,p.gameOpts.humanPlayers,r);let f=new Vg(p,s,l,a,r,d,h,()=>{console.error("Desync detected."),process.exit(1)},mm(this,nm,"f"),void 0,c,!1);f.init();let y=new Hg(f);s.onRateChange.subscribe(e=>f.setRate(e)),p.onEnd.subscribe(()=>{process.stdout.write("Game ended.\n"),y.destroy()}),process.stdout.write("\nGame created. Use the following links to join:\n\n");for(m of e.agents.slice(1))process.stdout.write(`${e.clientUrl.replace(/\/$/,"")}/#/game/${o}/${encodeURIComponent(m.name)}\n`);process.stdout.write("\nWaiting for players to join...\n"),await new Promise((e,t)=>{s.onGameStart.subscribeOnce(()=>{s.onClose.unsubscribe(t),y.start(),e()}),s.onClose.subscribeOnce(t),s.sendLoadedPercent(100)}),process.stdout.write("Game started.\n");return s.onClose.subscribeOnce(()=>f.dispose()),new im(t,p,g,d,h,f,y,()=>{y.destroy(),mm(this,om,"f").setLevel(Kr.OFF),s.close()})},pm=async function(e,t,i,r,s){if(!mm(this,hm,"f"))throw new Error("API is not initialized. Call init() first.");var a=xt.getIni(mm(this,sm,"f").getById(i.gameMode).rulesOverride);await xt.loadTheater(r.theaterType);var n=xt.getActiveEngine(),o=xt.getTheaterSettings(n,r.theaterType),n=xt.getTheaterIni(n,r.theaterType);let h=new X(n);h.loadTileData(xt.getTileData(),o.Extension);let l=class{static create(e,t,i,r,s,a,n,o,h,l,c,u){var d=i.clone().mergeWith(s).mergeWith(e);let p=new pn(d,c);var g=new vn(p,r,c);(class{static sanitize(e,t){t=t.mpDialogSettings;e.credits=Math.floor(U(e.credits,t.minMoney,t.maxMoney)),e.gameSpeed=Math.floor(U(e.gameSpeed,0,6)),e.unitCount=Math.floor(U(e.unitCount,t.minUnitCount,t.maxUnitCount))}}).sanitize(o,p);let m=new pn(i),f=m.getMultiplayerCountries(),y=[...m.getMultiplayerColors().values()],w=new wl(e,t,p);s=new Zh,d=h.getById(o.gameMode).type,r=new vl,c=new bl(r),i=new _l,e=new kl(1),t=new qh(w.tiles,w.tileOccupation,w.bridges,e),h=new Hd;let T=new Dd(s,w,p,g,a,n,o,d,r,i,c,e,t,h);(new pg).register(h,T,void 0),T.traits.add(new Pl),T.sellTrait=new Rl(T,p.general),T.traits.add(T.sellTrait),T.traits.add(new Ll);let b=new jl(p,u);T.traits.add(b),T.mapShroudTrait=new Wl(w,c),T.traits.add(T.mapShroudTrait),T.mapRadiationTrait=new zd(w),T.traits.add(T.mapRadiationTrait),T.mapLightingTrait=new kg(p.audioVisual,w.getLighting()),T.traits.add(T.mapLightingTrait),T.traits.add(new tn),T.traits.add(new mg),T.traits.add(new yg),T.crateGeneratorTrait=new cn(o.cratesAppear),T.traits.add(T.crateGeneratorTrait),l||(T.stalemateDetectTrait=new Tg,T.traits.add(T.stalemateDetectTrait));let v=new xl(p,o,b.getAvailableObjects()),S=_g.factory(a,n),_=S.generateColors(o),k=S.generateCountries(o,m),O=S.generateStartLocations(o,w.startingLocations),I=[...o.humanPlayers,...o.aiPlayers].filter(ga);return I.forEach(e=>{let t,i,r;if(vr(e)?(t=e.name,i=!1):(t=T.getAiPlayerName(e),i=!0,r=e.difficulty),-3!==e.countryId){var s=k.get(e)??e.countryId,a=_.get(e)??e.colorId,e=O.get(e)??e.startPos;if(-2===s)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");s=f[s].name,s=Sn.factory(s,p),a=y[a];T.addPlayer(v.createCombatant(t,s,e,a,i,r))}else T.addPlayer(v.createObserver(t,p))}),T.addPlayer(v.createNeutral(p,"@@NEUTRAL@@")),T}}.create(r,h,xt.getRules(),xt.getArt(),a,e,t,i,mm(this,sm,"f"),!1,mm(this,am,"f"),new kl(!1));return gr.init({x:0,y:l.map.mapBounds.getFullSize().width*gr.getWorldTileSize()/2}),l.init(s?l.getPlayerByName(s):void 0),l.start(),l},gm=function(t){let e=mm(this,lm,"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=xt.vfs.openFile(t.mapName),r=new pn(xt.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:r.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}};class Tm{}const bm=new wm})();var __webpack_exports__ActionsApi=__webpack_exports__.ActionsApi,__webpack_exports__AiRules=__webpack_exports__.AiRules,__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__BuildCat=__webpack_exports__.BuildCat,__webpack_exports__BuildStatus=__webpack_exports__.BuildStatus,__webpack_exports__CombatDamageRules=__webpack_exports__.CombatDamageRules,__webpack_exports__Country=__webpack_exports__.Country,__webpack_exports__CountryRules=__webpack_exports__.CountryRules,__webpack_exports__CrateRules=__webpack_exports__.CrateRules,__webpack_exports__CrewRules=__webpack_exports__.CrewRules,__webpack_exports__DMislRules=__webpack_exports__.DMislRules,__webpack_exports__FactoryStatus=__webpack_exports__.FactoryStatus,__webpack_exports__FactoryType=__webpack_exports__.FactoryType,__webpack_exports__GameApi=__webpack_exports__.GameApi,__webpack_exports__GameInstanceApi=__webpack_exports__.GameInstanceApi,__webpack_exports__GeneralRules=__webpack_exports__.GeneralRules,__webpack_exports__HoverRules=__webpack_exports__.HoverRules,__webpack_exports__InfDeathType=__webpack_exports__.InfDeathType,__webpack_exports__IniFile=__webpack_exports__.IniFile,__webpack_exports__IniSection=__webpack_exports__.IniSection,__webpack_exports__LandTargeting=__webpack_exports__.LandTargeting,__webpack_exports__LandType=__webpack_exports__.LandType,__webpack_exports__LightningStormRules=__webpack_exports__.LightningStormRules,__webpack_exports__LocomotorType=__webpack_exports__.LocomotorType,__webpack_exports__MapApi=__webpack_exports__.MapApi,__webpack_exports__MissileRules=__webpack_exports__.MissileRules,__webpack_exports__MovementZone=__webpack_exports__.MovementZone,__webpack_exports__NavalTargeting=__webpack_exports__.NavalTargeting,__webpack_exports__ObjectRules=__webpack_exports__.ObjectRules,__webpack_exports__ObjectType=__webpack_exports__.ObjectType,__webpack_exports__OrderType=__webpack_exports__.OrderType,__webpack_exports__OverlayRules=__webpack_exports__.OverlayRules,__webpack_exports__ParadropRules=__webpack_exports__.ParadropRules,__webpack_exports__PipColor=__webpack_exports__.PipColor,__webpack_exports__PrereqCategory=__webpack_exports__.PrereqCategory,__webpack_exports__PrismRules=__webpack_exports__.PrismRules,__webpack_exports__ProductionApi=__webpack_exports__.ProductionApi,__webpack_exports__ProjectileRules=__webpack_exports__.ProjectileRules,__webpack_exports__PublicApi=__webpack_exports__.PublicApi,__webpack_exports__QueueStatus=__webpack_exports__.QueueStatus,__webpack_exports__QueueType=__webpack_exports__.QueueType,__webpack_exports__RadarEventType=__webpack_exports__.RadarEventType,__webpack_exports__RadarRules=__webpack_exports__.RadarRules,__webpack_exports__RadiationRules=__webpack_exports__.RadiationRules,__webpack_exports__RepairRules=__webpack_exports__.RepairRules,__webpack_exports__RulesApi=__webpack_exports__.RulesApi,__webpack_exports__SideType=__webpack_exports__.SideType,__webpack_exports__SpeedType=__webpack_exports__.SpeedType,__webpack_exports__StanceType=__webpack_exports__.StanceType,__webpack_exports__SuperWeaponStatus=__webpack_exports__.SuperWeaponStatus,__webpack_exports__SuperWeaponType=__webpack_exports__.SuperWeaponType,__webpack_exports__Tag=__webpack_exports__.Tag,__webpack_exports__TagRepeatType=__webpack_exports__.TagRepeatType,__webpack_exports__TechnoRules=__webpack_exports__.TechnoRules,__webpack_exports__TerrainRules=__webpack_exports__.TerrainRules,__webpack_exports__TerrainType=__webpack_exports__.TerrainType,__webpack_exports__TheaterType=__webpack_exports__.TheaterType,__webpack_exports__ThreatRules=__webpack_exports__.ThreatRules,__webpack_exports__V3RocketRules=__webpack_exports__.V3RocketRules,__webpack_exports__VeteranAbility=__webpack_exports__.VeteranAbility,__webpack_exports__VeteranLevel=__webpack_exports__.VeteranLevel,__webpack_exports__VeteranRules=__webpack_exports__.VeteranRules,__webpack_exports__VhpScan=__webpack_exports__.VhpScan,__webpack_exports__WarheadRules=__webpack_exports__.WarheadRules,__webpack_exports__WeaponRules=__webpack_exports__.WeaponRules,__webpack_exports__WeaponType=__webpack_exports__.WeaponType,__webpack_exports__ZoneType=__webpack_exports__.ZoneType,__webpack_exports__cdapi=__webpack_exports__.cdapi;export{__webpack_exports__ActionsApi as ActionsApi,__webpack_exports__AiRules as AiRules,__webpack_exports__ApiEventType as ApiEventType,__webpack_exports__ArmorType as ArmorType,__webpack_exports__AttackState as AttackState,__webpack_exports__Bot as Bot,__webpack_exports__BuildCat as BuildCat,__webpack_exports__BuildStatus as BuildStatus,__webpack_exports__CombatDamageRules as CombatDamageRules,__webpack_exports__Country as Country,__webpack_exports__CountryRules as CountryRules,__webpack_exports__CrateRules as CrateRules,__webpack_exports__CrewRules as CrewRules,__webpack_exports__DMislRules as DMislRules,__webpack_exports__FactoryStatus as FactoryStatus,__webpack_exports__FactoryType as FactoryType,__webpack_exports__GameApi as GameApi,__webpack_exports__GameInstanceApi as GameInstanceApi,__webpack_exports__GeneralRules as GeneralRules,__webpack_exports__HoverRules as HoverRules,__webpack_exports__InfDeathType as InfDeathType,__webpack_exports__IniFile as IniFile,__webpack_exports__IniSection as IniSection,__webpack_exports__LandTargeting as LandTargeting,__webpack_exports__LandType as LandType,__webpack_exports__LightningStormRules as LightningStormRules,__webpack_exports__LocomotorType as LocomotorType,__webpack_exports__MapApi as MapApi,__webpack_exports__MissileRules as MissileRules,__webpack_exports__MovementZone as MovementZone,__webpack_exports__NavalTargeting as NavalTargeting,__webpack_exports__ObjectRules as ObjectRules,__webpack_exports__ObjectType as ObjectType,__webpack_exports__OrderType as OrderType,__webpack_exports__OverlayRules as OverlayRules,__webpack_exports__ParadropRules as ParadropRules,__webpack_exports__PipColor as PipColor,__webpack_exports__PrereqCategory as PrereqCategory,__webpack_exports__PrismRules as PrismRules,__webpack_exports__ProductionApi as ProductionApi,__webpack_exports__ProjectileRules as ProjectileRules,__webpack_exports__PublicApi as PublicApi,__webpack_exports__QueueStatus as QueueStatus,__webpack_exports__QueueType as QueueType,__webpack_exports__RadarEventType as RadarEventType,__webpack_exports__RadarRules as RadarRules,__webpack_exports__RadiationRules as RadiationRules,__webpack_exports__RepairRules as RepairRules,__webpack_exports__RulesApi as RulesApi,__webpack_exports__SideType as SideType,__webpack_exports__SpeedType as SpeedType,__webpack_exports__StanceType as StanceType,__webpack_exports__SuperWeaponStatus as SuperWeaponStatus,__webpack_exports__SuperWeaponType as SuperWeaponType,__webpack_exports__Tag as Tag,__webpack_exports__TagRepeatType as TagRepeatType,__webpack_exports__TechnoRules as TechnoRules,__webpack_exports__TerrainRules as TerrainRules,__webpack_exports__TerrainType as TerrainType,__webpack_exports__TheaterType as TheaterType,__webpack_exports__ThreatRules as ThreatRules,__webpack_exports__V3RocketRules as V3RocketRules,__webpack_exports__VeteranAbility as VeteranAbility,__webpack_exports__VeteranLevel as VeteranLevel,__webpack_exports__VeteranRules as VeteranRules,__webpack_exports__VhpScan as VhpScan,__webpack_exports__WarheadRules as WarheadRules,__webpack_exports__WeaponRules as WeaponRules,__webpack_exports__WeaponType as WeaponType,__webpack_exports__ZoneType as ZoneType,__webpack_exports__cdapi as cdapi};